repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
edx/edx-app-ios
|
Test/CourseSectionTableViewCellTests.swift
|
1
|
6458
|
//
// CourseSectionTableViewCellTests.swift
// edX
//
// Created by Salman on 06/07/2017.
// Copyright © 2017 edX. All rights reserved.
//
import XCTest
@testable import edX
class CourseSectionTableViewCellTests: SnapshotTestCase {
let course = OEXCourse.freshCourse()
var outline : CourseOutline!
var router : OEXRouter!
var environment : TestRouterEnvironment!
let resumeCourseItem = CourseOutlineTestDataFactory.resumeCourseItem
let networkManager = MockNetworkManager(baseURL: URL(string: "www.example.com")!)
override func setUp() {
super.setUp()
outline = CourseOutlineTestDataFactory.freshCourseOutline(course.course_id!)
let config = OEXConfig(dictionary: ["COURSE_VIDEOS_ENABLED": true])
let interface = OEXInterface.shared()
environment = TestRouterEnvironment(config: config, interface: interface)
environment.mockCourseDataManager.querier = CourseOutlineQuerier(courseID: outline.root, interface: interface, outline: outline)
environment.interface?.t_setCourseEnrollments([UserCourseEnrollment(course: course)])
environment.interface?.t_setCourseVideos([course.course_id!: OEXVideoSummaryTestDataFactory.localCourseVideos(CourseOutlineTestDataFactory.knownLocalVideoID)])
router = OEXRouter(environment: environment)
}
func loadAndVerifyControllerWithBlockID(_ blockID : CourseBlockID, courseOutlineMode: CourseOutlineMode? = .full, verifier : @escaping (CourseOutlineViewController) -> ((XCTestExpectation) -> Void)?) {
let blockIdOrNilIfRoot : CourseBlockID? = blockID == outline.root ? nil : blockID
let controller = CourseOutlineViewController(environment: environment, courseID: outline.root, rootID: blockIdOrNilIfRoot, forMode: courseOutlineMode)
let expectations = expectation(description: "course loaded")
let updateStream = BackedStream<Void>()
inScreenNavigationContext(controller) {
DispatchQueue.main.async {
let blockLoadedStream = controller.t_setup()
updateStream.backWithStream(blockLoadedStream)
updateStream.listen(controller) {[weak controller] _ in
updateStream.removeAllBackings()
if let next = controller.flatMap({ verifier($0) }) {
next(expectations)
}
else {
expectations.fulfill()
}
}
}
waitForExpectations()
}
}
func testForSwipeToDeleteOptionDisable() {
loadAndVerifyControllerWithBlockID(outline.root) { (courseoutlineview) in
let indexPath = IndexPath(row: 1, section: 0)
let tableView = courseoutlineview.t_tableView()
let cell = tableView.cellForRow(at: indexPath) as? CourseSectionTableViewCell
let swipeActions = cell?.tableView(tableView, editActionsForRowAt: indexPath, for: SwipeActionsOrientation.right)
var downloadVideos:[OEXHelperVideoDownload] = []
let videosStream = BackedStream<[OEXHelperVideoDownload]>()
let blockLoadedStream = cell!.t_setup()
videosStream.backWithStream(blockLoadedStream)
videosStream.listen(self) { downloads in
if let videos = downloads.value {
downloadVideos = videos
}
}
return {expectation -> Void in
XCTAssertNil(swipeActions)
XCTAssertFalse(cell!.t_areAllVideosDownloaded(videos: downloadVideos))
expectation.fulfill()
}
}
}
func testForSwipeToDeleteOptionEnable() {
loadAndVerifyControllerWithBlockID(outline.root) { (courseoutlineview) in
let indexPath = IndexPath(row: 1, section: 0)
let tableView = courseoutlineview.t_tableView()
let cell = tableView.cellForRow(at: indexPath) as? CourseSectionTableViewCell
let videosStream = BackedStream<[OEXHelperVideoDownload]>()
let blockLoadedStream = cell!.t_setup()
var downloadVideos:[OEXHelperVideoDownload] = []
videosStream.backWithStream(blockLoadedStream)
videosStream.listen(self) { downloads in
if let downloads = downloads.value {
downloadVideos = downloads
for video in downloads {
video.downloadState = OEXDownloadState.complete
}
}
}
let swipeActions = cell?.tableView(tableView, editActionsForRowAt: indexPath, for: SwipeActionsOrientation.right)
return {expectation -> Void in
XCTAssertNotNil(swipeActions)
XCTAssertTrue(cell!.t_areAllVideosDownloaded(videos: downloadVideos))
expectation.fulfill()
}
}
}
func testForSwipeToDeleteAction() {
loadAndVerifyControllerWithBlockID(outline.root) { (courseoutlineview) in
let indexPath = IndexPath(row: 1, section: 0)
let tableView = courseoutlineview.t_tableView()
let cell = tableView.cellForRow(at: indexPath) as? CourseSectionTableViewCell
let videosStream = BackedStream<[OEXHelperVideoDownload]>()
let blockLoadedStream = cell!.t_setup()
var downloadVideos :[OEXHelperVideoDownload] = []
videosStream.backWithStream(blockLoadedStream)
videosStream.listen(self) { downloads in
if let downloads = downloads.value {
downloadVideos = downloads
for video in downloads {
video.downloadState = OEXDownloadState.complete
}
}
}
var swipeActions = cell?.tableView(tableView, editActionsForRowAt: indexPath, for: SwipeActionsOrientation.right)
return {expectation -> Void in
XCTAssertNotNil(swipeActions)
cell?.deleteVideos(videos: downloadVideos)
swipeActions = cell?.tableView(tableView, editActionsForRowAt: indexPath, for: SwipeActionsOrientation.right)
XCTAssertNil(swipeActions)
expectation.fulfill()
}
}
}
}
|
apache-2.0
|
dd80e1c521a4b3bc2f23dede8b7a7f05
| 45.789855 | 205 | 0.629085 | 5.556799 | false | true | false | false |
cdmx/MiniMancera
|
miniMancera/View/HomeFroob/VHomeFroobContent.swift
|
1
|
3163
|
import UIKit
class VHomeFroobContent:UIView
{
private weak var controller:CHomeFroob!
private weak var labelTitle:UILabel!
private let kCornerRadius:CGFloat = 15
private let kActionsHeight:CGFloat = 150
private let kInfoHeight:CGFloat = 160
private let kBorderWidth:CGFloat = 2
init(controller:CHomeFroob)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.black
translatesAutoresizingMaskIntoConstraints = false
layer.cornerRadius = kCornerRadius
layer.borderWidth = kBorderWidth
layer.borderColor = UIColor.black.cgColor
self.controller = controller
let viewHeader:VHomeFroobContentHeader = VHomeFroobContentHeader(controller:controller)
let viewInfo:VHomeFroobContentInfo = VHomeFroobContentInfo(controller:controller)
let viewActions:VHomeFroobContentActions = VHomeFroobContentActions(controller:controller)
addSubview(viewHeader)
addSubview(viewInfo)
addSubview(viewActions)
NSLayoutConstraint.bottomToBottom(
view:viewActions,
toView:self)
NSLayoutConstraint.height(
view:viewActions,
constant:kActionsHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewActions,
toView:self)
NSLayoutConstraint.bottomToTop(
view:viewInfo,
toView:viewActions)
NSLayoutConstraint.height(
view:viewInfo,
constant:kInfoHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewInfo,
toView:self)
NSLayoutConstraint.bottomToTop(
view:viewHeader,
toView:viewInfo)
NSLayoutConstraint.topToTop(
view:viewHeader,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:viewHeader,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func printInfo()
{
guard
let title:String = controller.option.title
else
{
return
}
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:22),
NSForegroundColorAttributeName:UIColor.white]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:15),
NSForegroundColorAttributeName:UIColor.white]
let stringTitle:NSAttributedString = NSAttributedString(
string:title,
attributes:attributesTitle)
let stringSubtitle:NSAttributedString = NSAttributedString(
string:String.localized(key:"VHomeFroobContent_labelSubtitle"),
attributes:attributesSubtitle)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(stringTitle)
mutableString.append(stringSubtitle)
labelTitle.attributedText = mutableString
}
}
|
mit
|
3148bc3dd17288dea7cd88b9bca91fb6
| 31.27551 | 98 | 0.637686 | 5.740472 | false | false | false | false |
jingchc/Mr-Ride-iOS
|
Mr-Ride-iOS/DataManager.swift
|
1
|
2918
|
//
// DataManager.swift
// Mr-Ride-iOS
//
// Created by 莊晶涵 on 2016/6/24.
// Copyright © 2016年 AppWorks School Jing. All rights reserved.
//
import Alamofire
import SwiftyJSON
class DataManager {
static let shared = DataManager()
}
// MARK: - RestroomDataManager
extension DataManager {
typealias GetRestroomSuccess = (restrooms: [RestroomModel]) -> Void
typealias GetRestroomFailure = (error: ErrorType) -> Void
func getRestrooms(success success: GetRestroomSuccess, failure: GetRestroomFailure) -> Request {
let URLRequest = Router.GetRestRoomData
let request = Alamofire.request(URLRequest).validate().responseData { result in
switch result.result {
case .Success(let data):
let json = JSON(data: data)
var restrooms: [RestroomModel] = []
for (_, subJSON) in json["result"]["results"] {
do {
let restroom = try RestroomModelHelper().parse(json: subJSON)
restrooms.append(restroom)
}
catch {
print("Can't get restroom data")
}
}
success(restrooms: restrooms)
case .Failure(let error):
failure(error: error)
// todo: error handling
print(error)
}
}
return request
}
}
// MARK: YouBikeDataManager
extension DataManager {
typealias GetYoubikeSuccess = (youbikes: [YouBikeModel]) -> Void
typealias GetYoubikeFailure = (error: ErrorType) -> Void
func getYoubikes(success success: GetYoubikeSuccess, failure: GetYoubikeFailure) -> Request {
let URLRequest = Router.GetYouBikeStationData
let request = Alamofire.request(URLRequest).validate().responseData { result in
switch result.result {
case .Success(let data):
let json = JSON(data: data)
var youbikes: [YouBikeModel] = []
for (_, subJSON) in json["retVal"] {
do {
let youbike = try YoubikeModelHelper().parse(json: subJSON)
youbikes.append(youbike)
}
catch {
print("Can't get youbike data")
}
}
success(youbikes: youbikes)
case .Failure(let error):
failure(error: error)
// todo: error handling
print(error)
}
}
return request
}
}
|
apache-2.0
|
121c2180505482c439b22ec9c00cdb3d
| 28.383838 | 100 | 0.486078 | 5.232014 | false | false | false | false |
tomvlk/MPFormatter_swift
|
Tests/MPFormatterTests/MPFormatterTests.swift
|
1
|
1179
|
import XCTest
@testable import MPFormatter
final class MPFormatterTests: XCTestCase {
func testSimple() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(MPFormatter().parse("Hello, World!").getString(), "Hello, World!")
}
func testStripping() {
let input = "$06fMyColor$[link]Link$l$oTest$wBold$sShadow$zNormal"
let formatter = MPFormatter()
let formattedString = formatter.parse(input)
let attributedString: NSAttributedString = formattedString.getAttributedString()
let attributes = attributedString.attributes(at: 0, effectiveRange: nil)
XCTAssertEqual(attributes.count, 2)
let strippedAttributedString: NSAttributedString = formattedString.stripAll().getAttributedString()
let strippedAttributes = strippedAttributedString.attributes(at: 0, effectiveRange: nil)
XCTAssertEqual(strippedAttributes.count, 1)
}
static var allTests = [
("testSimple", testSimple),
("testStripping", testStripping)
]
}
|
mit
|
f77c8a4f5f29b0bad9fc414d91a6667a
| 38.3 | 107 | 0.682782 | 5.060086 | false | true | false | false |
Journey321/xiaorizi
|
xiaorizi/Classes/Constant/JSSystemUtil.swift
|
1
|
1985
|
//
// JSSystemUtil.swift
// E_EducationBySwift
//
// Created by JohnSon on 15/12/25.
// Copyright © 2015年 JohnSon. All rights reserved.
//
import Foundation
import UIKit
/// 用户昵称
public let UserNickname : NSString = "UserNickname"
/// 用户签名
public let UserSignature : NSString = "UserSignature"
/// 邮箱
public let UserEmail : NSString = "UserEmail"
/// 电话
public let UserPhone : NSString = "UserPhone"
public let BGCOLOR = UIColor.init(rgbByFFFFFF: 0xf3f3f3)
/// 获取系统版本
let SystemVersion:Float = Float(UIDevice.currentDevice().systemVersion)!
/// 获取系统名称
let SystemName:String=UIDevice.currentDevice().systemName
/// 获取App版本号
let APP_VERSION = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
/// 获取App名称
let APP_NAME = NSBundle.mainBundle().infoDictionary!["CFBundleDisplayName"]
/// 判断是否是IOS7
let IOS7:Bool = SystemVersion >= 7.0 ? true : false
/// 判断是否是IOS8
let IOS8:Bool = SystemVersion >= 8.0 ? true : false
/// 判断是否是IOS9
let IOS9:Bool = SystemVersion >= 9.0 ? true : false
/// 获取屏幕的宽高
public let kScreenBounds = UIScreen.mainScreen().bounds
public let kScreenHeight = UIScreen.mainScreen().bounds.size.height
public let kScreenWidth = UIScreen.mainScreen().bounds.size.width
/// 获取系统window
public let kWindow = UIApplication.sharedApplication().keyWindow
/// 判断当前设备
let IS_IPHONE_4 = fabs(Double(kScreenHeight) - Double(480))<DBL_EPSILON
let IS_IPHONE_5 = fabs(Double(kScreenHeight) - Double(568))<DBL_EPSILON
let IS_IPHONE_6 = fabs(Double(kScreenHeight) - Double(667))<DBL_EPSILON
let IS_IPHONE_6P = fabs(Double(kScreenHeight) - Double(736))<DBL_EPSILON
struct theme {
/// APP导航条barButtonItem文字大小
static let navItemFont: UIFont = UIFont.systemFontOfSize(16)
/// APP导航条titleFont文字大小
static let navTitleFont: UIFont = UIFont.systemFontOfSize(18)
}
|
mit
|
0a684c2ba2b5fa5e39c39a23799c5983
| 32.163636 | 86 | 0.735197 | 3.576471 | false | false | false | false |
ImperialDevelopment/IDPopup
|
IDPopup/Classes/IDPopup.swift
|
1
|
6786
|
//
// IDPopup.swift
//
// Created by Michael Schoder on 11.08.17.
//
//
import UIKit
/// IDPopup with a style similar to the default iOS look&feel
open class IDPopup: UIView {
/// Identifier which is used to determine if this Popup is already shown
var identifier: String?
/// The leading Constraint to the PopupWindow
var leftConstraint: NSLayoutConstraint!
/// The trailing Constraint to the PopupWindow
var rightContraint: NSLayoutConstraint!
/// The bottom Constraint to the PopupWindow or a newer IDPopup
var bottomConstraint: NSLayoutConstraint!
/// The Dismiss Timer which controls when a Popup should be dismissed automaticlly.
var dismissTimer: Timer?
/// The TimeInterval after the Popup is dismissed.
var dismissInterval: TimeInterval?
/// The text to be displayed in the Popup. Setting the Text updates the Popup UI. Default is an empty String
public var text: String = "" {
didSet {
styleView()
}
}
/// Flag if the Popup should be Dismissable by the User. Setting the flag updates the Popup UI. Shows a 'OK'-Button if true. Default is false
public var isDismissable: Bool = false {
didSet {
styleView()
}
}
/// UIImageView to the left of the Text to add a thumbimage.
@IBOutlet public weak var imageViewThumb: UIImageView!
/// UILabel in the center to display text.
@IBOutlet public weak var labelText: UILabel!
/// UIButton to the right of the Text to dismiss the IDPopup. Only shown when the isDismissable flag is true
@IBOutlet public weak var buttonDismiss: UIButton!
/// Initializer for a IDPopup. Loads the IDPopup from a xib and styles the Popup
///
/// - Parameters:
/// - text: Text to be displayed in the Popup
/// - isDismissable: Flag, which indicates if the Popup should be dismissable by the User. Default is false
/// - timerSec: TimeInterval in sec. If set, the Popup dismisses after the given time. Default is nil
public init(identifier: String? = nil, text: String, isDismissable: Bool = false, dismissAfter timerSec: TimeInterval? = nil) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
self.identifier = identifier
self.text = text
self.isDismissable = isDismissable
xibSetup()
styleView()
if let timerSec = timerSec {
dismiss(afer: timerSec)
}
}
/// Initializer for a IDPopup. Loads the IDPopup from a xib and styles the Popup
///
/// - Parameter frame: Frame to be applied. This is ignored because of the use of Auto-Layout
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
styleView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
styleView()
}
/// IBAction which is connected to the UIButton in the IDPopup
///
/// - Parameter sender: sender of this event
@IBAction func buttonDismissTouched(_ sender: Any) {
if isDismissable {
dismiss()
}
}
/// This method gets called by the timer, when the set time is over
@objc func timerDismiss(_ timer: Timer) {
dismiss()
}
/// Styles the IDPopup. If you want to apply a custom style to a Popup override this Method.
open func styleView() {
backgroundColor = UIColor.white
layer.shadowOpacity = 0.5
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.cornerRadius = 3.0
imageViewThumb.image = nil
let dismissImage = UIImage(named: "popup-button-dismiss", in: Bundle(for: IDPopup.self), compatibleWith: nil)
buttonDismiss.setImage(dismissImage?.withRenderingMode(.alwaysTemplate), for: .normal)
buttonDismiss.tintColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0)
buttonDismiss.isHidden = !isDismissable
labelText.font = UIFont.systemFont(ofSize: 14.0)
labelText.textColor = UIColor.black
labelText.text = text
}
}
fileprivate extension IDPopup {
/// Loads the UI of the IDPopup from the Nib-File and adds it as Child-View
func xibSetup() {
let view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.backgroundColor = UIColor.clear
addSubview(view)
}
/// Loads the Nib-File from the current Bundle
///
/// - Returns: Loaded View
func loadViewFromNib() -> UIView {
let view = Bundle(for: IDPopup.self).loadNibNamed("IDPopup", owner: self, options: nil)?[0] as! UIView
return view
}
}
public extension IDPopup {
/// Shows the IDPopup on the Screen. The Popup is presented from the bottom. The Constraints of all other IDPopups are adjusted if needed.
func show() {
IDPopupController.shared.show(self)
}
/// Dismisses the IDPopup from the Screen. The Popup slides out of the Screen. Th Constraints of all other IDPopups are ajusted if needed.
func dismiss() {
IDPopupController.shared.dismiss(self)
}
/// Dismisses the IDPopup from the Screen after a given Time. The Popup slides out of the Screen. Th Constraints of all other IDPopups are ajusted if needed.
///
/// - Parameter timerSec: Seconds until the IDPopup is dismissed.
func dismiss(afer timerSec: TimeInterval) {
dismissInterval = timerSec
if dismissTimer != nil {
dismissTimer?.invalidate()
dismissTimer = nil
}
dismissTimer = Timer.scheduledTimer(timeInterval: timerSec, target: self, selector: #selector(timerDismiss(_:)), userInfo: nil, repeats: false)
}
/// Shakes the Popup and restarts the dismiss timer, if one is set.
func shake() {
if dismissTimer != nil {
guard let dismissInterval = dismissInterval else {
return
}
dismiss(afer: dismissInterval)
}
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.06
animation.repeatCount = 2
animation.autoreverses = true
animation.fromValue = CGPoint(x: center.x - 10, y: center.y)
animation.toValue = CGPoint(x: center.x + 10, y: center.y)
layer.add(animation, forKey: "position")
}
/// Dismisses all currently shown IDPopups.
static func dismissAll() {
IDPopupController.shared.dismissAll()
}
/// Dismissed the Popup with the given identifier
static func dismiss(identifier: String) {
IDPopupController.shared.dissmiss(identifier: identifier)
}
}
|
mit
|
5428ff32c32e76cc4662cadaf06602ef
| 34.34375 | 161 | 0.652962 | 4.505976 | false | false | false | false |
OscarSwanros/swift
|
test/Generics/requirement_inference.swift
|
2
|
12622
|
// RUN: %target-typecheck-verify-swift -typecheck %s -verify
// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
protocol P1 {
func p1()
}
protocol P2 : P1 { }
struct X1<T : P1> {
func getT() -> T { }
}
class X2<T : P1> {
func getT() -> T { }
}
class X3 { }
struct X4<T : X3> {
func getT() -> T { }
}
struct X5<T : P2> { }
// Infer protocol requirements from the parameter type of a generic function.
func inferFromParameterType<T>(_ x: X1<T>) {
x.getT().p1()
}
// Infer protocol requirements from the return type of a generic function.
func inferFromReturnType<T>(_ x: T) -> X1<T> {
x.p1()
}
// Infer protocol requirements from the superclass of a generic parameter.
func inferFromSuperclass<T, U : X2<T>>(_ t: T, u: U) -> T {
t.p1()
}
// Infer protocol requirements from the parameter type of a constructor.
struct InferFromConstructor {
init<T> (x : X1<T>) {
x.getT().p1()
}
}
// Don't infer requirements for outer generic parameters.
class Fox : P1 {
func p1() {}
}
class Box<T : Fox, U> {
func unpack(_ x: X1<T>) {}
func unpackFail(_ X: X1<U>) { } // expected-error{{type 'U' does not conform to protocol 'P1'}}
}
// ----------------------------------------------------------------------------
// Superclass requirements
// ----------------------------------------------------------------------------
// Compute meet of two superclass requirements correctly.
class Carnivora {}
class Canidae : Carnivora {}
struct U<T : Carnivora> {}
struct V<T : Canidae> {}
// CHECK-LABEL: .inferSuperclassRequirement1@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae>
func inferSuperclassRequirement1<T : Carnivora>(
_ v: V<T>) {}
// CHECK-LABEL: .inferSuperclassRequirement2@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae>
func inferSuperclassRequirement2<T : Canidae>(_ v: U<T>) {}
// ----------------------------------------------------------------------------
// Same-type requirements
// ----------------------------------------------------------------------------
protocol P3 {
associatedtype P3Assoc : P2 // expected-note{{declared here}}
}
protocol P4 {
associatedtype P4Assoc : P1
}
protocol PCommonAssoc1 {
associatedtype CommonAssoc
}
protocol PCommonAssoc2 {
associatedtype CommonAssoc
}
protocol PAssoc {
associatedtype Assoc
}
struct Model_P3_P4_Eq<T : P3, U : P4> where T.P3Assoc == U.P4Assoc {}
func inferSameType1<T, U>(_ x: Model_P3_P4_Eq<T, U>) {
let u: U.P4Assoc? = nil
let _: T.P3Assoc? = u!
}
func inferSameType2<T : P3, U : P4>(_: T, _: U) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {}
// expected-warning@-1{{redundant conformance constraint 'T.P3Assoc': 'P2'}}
// expected-note@-2{{conformance constraint 'T.P3Assoc': 'P2' implied here}}
func inferSameType3<T : PCommonAssoc1>(_: T) where T.CommonAssoc : P1, T : PCommonAssoc2 {
}
protocol P5 {
associatedtype Element
}
protocol P6 {
associatedtype AssocP6 : P5
}
protocol P7 : P6 {
associatedtype AssocP7: P6
}
// CHECK-LABEL: P7@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P7, τ_0_0.AssocP6.Element : P6, τ_0_0.AssocP6.Element == τ_0_0.AssocP7.AssocP6.Element>
extension P7 where AssocP6.Element : P6, // expected-note{{conformance constraint 'Self.AssocP6.Element': 'P6' written here}}
AssocP7.AssocP6.Element : P6, // expected-warning{{redundant conformance constraint 'Self.AssocP6.Element': 'P6'}}
AssocP6.Element == AssocP7.AssocP6.Element {
func nestedSameType1() { }
}
protocol P8 {
associatedtype A // expected-note{{'A' declared here}}
associatedtype B // expected-note{{'B' declared here}}
}
protocol P9 : P8 {
associatedtype A // expected-warning{{redeclaration of associated type 'A' from protocol 'P8' is better expressed as a 'where' clause on the protocol}}
associatedtype B // expected-warning{{redeclaration of associated type 'B' from protocol 'P8' is better expressed as a 'where' clause on the protocol}}
}
protocol P10 {
associatedtype A
associatedtype C
}
// CHECK-LABEL: sameTypeConcrete1@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.A == X3, τ_0_0.A == X3, τ_0_0.B == Int, τ_0_0.C == Int>
func sameTypeConcrete1<T : P9 & P10>(_: T) where T.A == X3, T.C == T.B, T.C == Int { }
// CHECK-LABEL: sameTypeConcrete2@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.B == X3, τ_0_0.C == X3>
// FIXME: Should have τ_0_0.A == τ_0_0.A
func sameTypeConcrete2<T : P9 & P10>(_: T) where T.B : X3, T.C == T.B, T.C == X3 { }
// expected-warning@-1{{redundant superclass constraint 'T.B' : 'X3'}}
// expected-note@-2{{same-type constraint 'T.C' == 'X3' written here}}
// Note: a standard-library-based stress test to make sure we don't inject
// any additional requirements.
// CHECK-LABEL: RangeReplaceableCollection
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : MutableCollection, τ_0_0 : RangeReplaceableCollection, τ_0_0.SubSequence == MutableRangeReplaceableSlice<τ_0_0>>
extension RangeReplaceableCollection where
Self.SubSequence == MutableRangeReplaceableSlice<Self>
{
func f() { }
}
// CHECK-LABEL: X14.recursiveConcreteSameType
// CHECK: Generic signature: <T, V where T == CountableRange<Int>>
// CHECK-NEXT: Canonical generic signature: <τ_0_0, τ_1_0 where τ_0_0 == CountableRange<Int>>
struct X14<T> where T.Iterator == IndexingIterator<T> {
func recursiveConcreteSameType<V>(_: V) where T == CountableRange<Int> { }
}
// rdar://problem/30478915
protocol P11 {
associatedtype A
}
protocol P12 {
associatedtype B: P11
}
struct X6 { }
struct X7 : P11 {
typealias A = X6
}
struct X8 : P12 {
typealias B = X7
}
struct X9<T: P12, U: P12> where T.B == U.B {
// CHECK-LABEL: X9.upperSameTypeConstraint
// CHECK: Generic signature: <T, U, V where T == X8, U : P12, U.B == X8.B>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 == X8, τ_0_1 : P12, τ_0_1.B == X7>
func upperSameTypeConstraint<V>(_: V) where T == X8 { }
}
protocol P13 {
associatedtype C: P11
}
struct X10: P11, P12 {
typealias A = X10
typealias B = X10
}
struct X11<T: P12, U: P12> where T.B == U.B.A {
// CHECK-LABEL: X11.upperSameTypeConstraint
// CHECK: Generic signature: <T, U, V where T : P12, U == X10, T.B == X10.A>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P12, τ_0_1 == X10, τ_0_0.B == X10>
func upperSameTypeConstraint<V>(_: V) where U == X10 { }
}
#if _runtime(_ObjC)
// rdar://problem/30610428
@objc protocol P14 { }
class X12<S: AnyObject> {
func bar<V>(v: V) where S == P14 {
}
}
@objc protocol P15: P14 { }
class X13<S: P14> {
func bar<V>(v: V) where S == P15 {
}
}
#endif
protocol P16 {
associatedtype A
}
struct X15 { }
struct X16<X, Y> : P16 {
typealias A = (X, Y)
}
// CHECK-LABEL: .X17.bar@
// CHECK: Generic signature: <S, T, U, V where S == X16<X3, X15>, T == X3, U == X15>
struct X17<S: P16, T, U> where S.A == (T, U) {
func bar<V>(_: V) where S == X16<X3, X15> { }
}
// Same-type constraints that are self-derived via a parent need to be
// suppressed in the resulting signature.
protocol P17 { }
protocol P18 {
associatedtype A: P17
}
struct X18: P18, P17 {
typealias A = X18
}
// CHECK-LABEL: .X19.foo@
// CHECK: Generic signature: <T, U where T == X18>
struct X19<T: P18> where T == T.A {
func foo<U>(_: U) where T == X18 { }
}
// rdar://problem/31520386
protocol P20 { }
struct X20<T: P20> { }
// CHECK-LABEL: .X21.f@
// CHECK: Generic signature: <T, U, V where T : P20, U == X20<T>>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P20, τ_0_1 == X20<τ_0_0>>
struct X21<T, U> {
func f<V>(_: V) where U == X20<T> { }
}
struct X22<T, U> {
func g<V>(_: V) where T: P20,
U == X20<T> { }
}
// CHECK: Generic signature: <Self where Self : P22>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P22>
// CHECK: Protocol requirement signature:
// CHECK: .P22@
// CHECK-NEXT: Requirement signature: <Self where Self.B : P20, Self.A == X20<Self.B>>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.B : P20, τ_0_0.A == X20<τ_0_0.B>>
protocol P22 {
associatedtype A
associatedtype B where A == X20<B>
}
// CHECK: Generic signature: <Self where Self : P23>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P23>
// CHECK: Protocol requirement signature:
// CHECK: .P23@
// CHECK-NEXT: Requirement signature: <Self where Self.B : P20, Self.A == X20<Self.B>>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.B : P20, τ_0_0.A == X20<τ_0_0.B>>
protocol P23 {
associatedtype A
associatedtype B: P20
where A == X20<B>
}
protocol P24 {
associatedtype C: P20
}
struct X24<T: P20> : P24 {
typealias C = T
}
// CHECK-LABEL: .P25a@
// CHECK-NEXT: Requirement signature: <Self where Self.B : P20, Self.A == X24<Self.B>>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.B : P20, τ_0_0.A == X24<τ_0_0.B>>
protocol P25a {
associatedtype A: P24 // expected-warning{{redundant conformance constraint 'Self.A': 'P24'}}
associatedtype B where A == X24<B> // expected-note{{conformance constraint 'Self.A': 'P24' implied here}}
}
// CHECK-LABEL: .P25b@
// CHECK-NEXT: Requirement signature: <Self where Self.B : P20, Self.A == X24<Self.B>>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.B : P20, τ_0_0.A == X24<τ_0_0.B>>
protocol P25b {
associatedtype A
associatedtype B where A == X24<B>
}
protocol P25c {
associatedtype A: P24
associatedtype B where A == X<B> // expected-error{{use of undeclared type 'X'}}
}
// Similar to the above, but with superclass constraints.
protocol P26 {
associatedtype C: X3
}
struct X26<T: X3> : P26 {
typealias C = T
}
// CHECK-LABEL: .P27a@
// CHECK-NEXT: Requirement signature: <Self where Self.B : X3, Self.A == X26<Self.B>>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.B : X3, τ_0_0.A == X26<τ_0_0.B>>
protocol P27a {
associatedtype A: P26 // expected-warning{{redundant conformance constraint 'Self.A': 'P26'}}
associatedtype B where A == X26<B> // expected-note{{conformance constraint 'Self.A': 'P26' implied here}}
}
// CHECK-LABEL: .P27b@
// CHECK-NEXT: Requirement signature: <Self where Self.B : X3, Self.A == X26<Self.B>>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.B : X3, τ_0_0.A == X26<τ_0_0.B>>
protocol P27b {
associatedtype A
associatedtype B where A == X26<B>
}
// ----------------------------------------------------------------------------
// Inference of associated type relationships within a protocol hierarchy
// ----------------------------------------------------------------------------
struct X28 : P2 {
func p1() { }
}
// CHECK-LABEL: .P28@
// CHECK-NEXT: Requirement signature: <Self where Self : P3, Self.P3Assoc == X28>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : P3, τ_0_0.P3Assoc == X28>
protocol P28: P3 {
typealias P3Assoc = X28 // expected-warning{{typealias overriding associated type}}
}
// ----------------------------------------------------------------------------
// Inference of associated types by name match
// ----------------------------------------------------------------------------
protocol P29 {
associatedtype X
}
protocol P30 {
associatedtype X
}
protocol P31 { }
// CHECK-LABEL: .sameTypeNameMatch1@
// CHECK: Generic signature: <T where T : P29, T : P30, T.X : P31, T.X == T.X>
func sameTypeNameMatch1<T: P29 & P30>(_: T) where T.X: P31 { }
// ----------------------------------------------------------------------------
// Infer requirements from conditional conformances
// ----------------------------------------------------------------------------
protocol P32 {}
protocol P33 {
associatedtype A: P32
}
protocol P34 {}
struct Foo<T> {}
extension Foo: P32 where T: P34 {}
// Inference chain: U.A: P32 => Foo<V>: P32 => V: P34
// CHECK-LABEL: conditionalConformance1@
// CHECK: Generic signature: <U, V where U : P33, V : P34, U.A == Foo<V>>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1 where τ_0_0 : P33, τ_0_1 : P34, τ_0_0.A == Foo<τ_0_1>>
func conditionalConformance1<U: P33, V>(_: U) where U.A == Foo<V> {}
struct Bar<U: P32> {}
// CHECK-LABEL: conditionalConformance2@
// CHECK: Generic signature: <V where V : P34>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P34>
func conditionalConformance2<V>(_: Bar<Foo<V>>) {}
|
apache-2.0
|
2aa8bf12c2a7185bde98631bcbdd2531
| 28.422535 | 172 | 0.617201 | 2.984286 | false | false | false | false |
bertomartin/Tomate
|
Remaining/TodayViewController.swift
|
3
|
4019
|
//
// TodayViewController.swift
// Remaining
//
// Created by dasdom on 11.03.15.
// Copyright (c) 2015 Dominik Hauser. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
var endDate: NSDate?
var timer: NSTimer?
var maxValue: Int?
var timerView: TimerView!
override func viewDidLoad() {
super.viewDidLoad()
// preferredContentSize = CGSize(width: view.frame.size.width, height: 120)
timerView = TimerView(frame: CGRect.zeroRect)
timerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(timerView)
var constraints = [NSLayoutConstraint]()
constraints.append(timerView.widthAnchor.constraintEqualToConstant(100))
constraints.append(timerView.heightAnchor.constraintEqualToConstant(100))
constraints.append(timerView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor))
constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[timer]-10@999-|", options: [], metrics: nil, views: ["timer": timerView])
NSLayoutConstraint.activateConstraints(constraints)
timerView.timeLabel.font = timerView.timeLabel.font.fontWithSize(CGFloat(100.0*0.9/3.0-10.0))
// self.view.backgroundColor = UIColor.brownColor()
}
func widgetMarginInsetsForProposedMarginInsets
(defaultMarginInsets: UIEdgeInsets) -> (UIEdgeInsets) {
return UIEdgeInsetsZero
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// if let defaults = NSUserDefaults(suiteName: "group.de.dasdom.Tomate") {
// let startDateAsTimeStamp = defaults.doubleForKey("date")
// println("startDate: \(startDateAsTimeStamp)")
// endDate = NSDate(timeIntervalSince1970: startDateAsTimeStamp)
// }
// println("endDate \(endDate)")
//
// timer?.invalidate()
// timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "updateLabel", userInfo: nil, repeats: true)
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
if let defaults = NSUserDefaults(suiteName: "group.de.dasdom.Tomate") {
let startDateAsTimeStamp = defaults.doubleForKey("date")
print("startDate: \(startDateAsTimeStamp)", appendNewline: false)
endDate = NSDate(timeIntervalSince1970: startDateAsTimeStamp)
maxValue = defaults.integerForKey("maxValue")
}
// println("endDate \(endDate)")
timerView.durationInSeconds = 0.0
timerView.maxValue = 1.0
timer?.invalidate()
if endDate != nil {
timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "updateLabel", userInfo: nil, repeats: true)
}
completionHandler(NCUpdateResult.NewData)
}
func updateLabel() {
let durationInSeconds = endDate!.timeIntervalSinceNow
if durationInSeconds > 0 {
// let seconds = Int(durationInSeconds % 60)
// let minutes = Int(durationInSeconds / 60.0)
// let format = "02"
// let labelText = "\(minutes.format(format))" + ":" + "\(seconds.format(format)) min"
// label.text = labelText
timerView.durationInSeconds = CGFloat(durationInSeconds)
timerView.maxValue = CGFloat(maxValue!)
timerView.setNeedsDisplay()
// print(timerView)
} else {
timer?.invalidate()
// label.text = "-"
}
}
}
extension Int {
func format(f: String) -> String {
return NSString(format: "%\(f)d", self) as String
}
}
|
mit
|
ef1dc7fecd4c9be892fd120e8b8ba8de
| 33.947826 | 148 | 0.685494 | 4.689615 | false | false | false | false |
whiteshadow-gr/HatForIOS
|
HAT/Services/HATAccountService.swift
|
1
|
23721
|
/**
* 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 SwiftyJSON
// MARK: Struct
/// A Struct about the methods concerning the user's HAT account
public struct HATAccountService {
// MARK: - Get hat values from a table
/**
Gets values from a particular table in use with v2 API
- parameter token: The user's token
- parameter userDomain: The user's domain
- parameter namespace: The namespace to read from
- parameter scope: The scope to read from
- parameter parameters: The parameters to pass to the request, e.g. startime, endtime, limit
- parameter successCallback: A callback called when successful of type @escaping ([JSON], String?) -> Void
- parameter errorCallback: A callback called when failed of type @escaping (HATTableError) -> Void)
*/
public static func getHatTableValues(token: String, userDomain: String, namespace: String, scope: String, parameters: Dictionary<String, Any>, successCallback: @escaping ([JSON], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
// form the url
let url: String = "https://\(userDomain)/api/v2.6/data/\(namespace)/\(scope)"
// create parameters and headers
let headers: [String: String] = [RequestHeaders.xAuthToken: token]
// make the request
HATNetworkHelper.asynchronousRequest(
url,
method: .get,
encoding: Alamofire.URLEncoding.default,
contentType: ContentType.json,
parameters: parameters,
headers: headers) { (response: HATNetworkHelper.ResultType) -> Void in
switch response {
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
errorCallback(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
errorCallback(.generalError(message, statusCode, error))
}
case .isSuccess(let isSuccess, let statusCode, let result, let token):
if statusCode != nil && (statusCode! == 401 || statusCode! == 403) {
let message: String = NSLocalizedString("Token expired", comment: "")
errorCallback(.generalError(message, statusCode, nil))
}
if isSuccess {
if let array: [JSON] = result.array {
successCallback(array, token)
} else {
errorCallback(.noValuesFound)
}
}
}
}
}
// MARK: - Create value
/**
Gets values from a particular table in use with v2 API
- parameter userToken: The user's token
- parameter userDomain: The user's domain
- parameter namespace: The namespace to read from
- parameter scope: The scope to read from
- parameter parameters: The parameters to pass to the request, e.g. startime, endtime, limit
- parameter successCallback: A callback called when successful of type @escaping (JSON, String?) -> Void
- parameter errorCallback: A callback called when failed of type @escaping (HATTableError) -> Void)
*/
public static func createTableValue(userToken: String, userDomain: String, namespace: String, scope: String, parameters: Dictionary<String, Any>, successCallback: @escaping (JSON, String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
// form the url
let url: String = "https://\(userDomain)/api/v2.6/data/\(namespace)/\(scope)"
// create parameters and headers
let headers: [String: String] = [RequestHeaders.xAuthToken: userToken]
// make the request
HATNetworkHelper.asynchronousRequest(
url,
method: .post,
encoding: Alamofire.JSONEncoding.default,
contentType: ContentType.json,
parameters: parameters,
headers: headers) { (response: HATNetworkHelper.ResultType) -> Void in
switch response {
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
errorCallback(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
errorCallback(.generalError(message, statusCode, error))
}
case .isSuccess(let isSuccess, let statusCode, let result, let token):
if isSuccess {
successCallback(result, token)
}
if statusCode == 404 {
errorCallback(.tableDoesNotExist)
} else if statusCode! == 401 || statusCode! == 403 {
let message: String = NSLocalizedString("Token expired", comment: "")
errorCallback(.generalError(message, statusCode, nil))
}
}
}
}
// MARK: - Delete from hat
/**
Deletes a record from hat using V2 API
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter recordIds: The record id to delete
- parameter success: A callback called when the request was successful of type @escaping (String) -> Void
- parameter failed: A callback called when the request failed of type @escaping (HATTableError) -> Void
*/
public static func deleteHatRecord(userDomain: String, userToken: String, recordIds: [String], success: @escaping (String) -> Void, failed: @ escaping (HATTableError) -> Void) {
// form the url
var url: String = "https://\(userDomain)/api/v2.6/data"
let firstRecord: String? = recordIds.first
url.append("?records=\(firstRecord!)")
for record: String in recordIds where record != firstRecord! {
url.append("&records=\(record)")
}
let headers: [String: String] = [RequestHeaders.xAuthToken: userToken]
// make the request
HATNetworkHelper.asynchronousRequest(
url,
method: .delete,
encoding: Alamofire.JSONEncoding.default,
contentType: ContentType.text,
parameters: [:],
headers: headers) { (response: HATNetworkHelper.ResultType) -> Void in
// handle result
switch response {
case .isSuccess(let isSuccess, let statusCode, _, _):
if isSuccess {
success(userToken)
HATAccountService.triggerHatUpdate(userDomain: userDomain, completion: { () -> Void in })
} else {
let message: String = NSLocalizedString("The request was unsuccesful", comment: "")
failed(.generalError(message, statusCode, nil))
}
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
failed(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
failed(.generalError(message, statusCode, error))
}
}
}
}
// MARK: - Edit record
/**
Edits a record from hat using v2 API's
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The object to upload formatted as a Dictionary<String, Any>
- parameter successCallback: A callback called when successful of type @escaping ([JSON], String?) -> Void
- parameter errorCallback: A callback called when failed of type @escaping (HATTableError) -> Void
*/
public static func updateHatRecord(userDomain: String, userToken: String, notes: [HATNotes], successCallback: @escaping ([JSON], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
let encoded: Data? = HATNotes.encode(from: notes)
var urlRequest: URLRequest = URLRequest.init(url: URL(string: "https://\(userDomain)/api/v2.6/data")!)
urlRequest.httpMethod = HTTPMethod.put.rawValue
urlRequest.addValue(userToken, forHTTPHeaderField: "x-auth-token")
urlRequest.networkServiceType = .background
urlRequest.httpBody = encoded
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
let configuration: URLSessionConfiguration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
let manager: SessionManager = Alamofire.SessionManager(configuration: configuration)
manager.request(urlRequest)
.responseJSON { response in
let header: [AnyHashable: Any]? = response.response?.allHeaderFields
let token: String? = header?["x-auth-token"] as? String
if response.response?.statusCode != 201 {
errorCallback(.generalError("An error occured", 400, nil))
} else {
let array: Any = response.result.value as Any
let json: JSON = JSON(array)
successCallback([json], token)
}
}
.session.finishTasksAndInvalidate()
}
// MARK: - Trigger an update
/**
Triggers an update to hat servers
*/
public static func triggerHatUpdate(userDomain: String, completion: @escaping () -> Void) {
// define the url to connect to
let url: String = "https://notables.hubofallthings.com/api/bulletin/tickle"
let configuration: URLSessionConfiguration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
let manager: SessionManager = Alamofire.SessionManager(configuration: configuration)
// make the request
manager.request(
url,
method: .get,
parameters: ["phata": userDomain],
encoding: Alamofire.URLEncoding.default,
headers: nil)
.responseString { _ in
completion()
}
.session.finishTasksAndInvalidate()
}
// MARK: - Get public key
/**
Constructs URL to get the public key
- parameter userHATDomain: The user's HAT domain
- returns: An optional String, nil if public key not found
*/
public static func theUserHATDomainPublicKeyURL(_ userHATDomain: String) -> String? {
if let escapedUserHATDomain: String = userHATDomain.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
return "https://\(escapedUserHATDomain)/publickey"
}
return nil
}
// MARK: - Change Password
/**
Changes the user's password
- parameter userDomain: The user's domain
- parameter userToken: The user's authentication token
- parameter oldPassword: The old password the user entered
- parameter newPassword: The new password to change to
- parameter successCallback: A function of type (String, String?) to call on success
- parameter failCallback: A fuction of type (HATError) to call on fail
*/
public static func changePassword(userDomain: String, userToken: String, oldPassword: String, newPassword: String, successCallback: @escaping (String, String?) -> Void, failCallback: @escaping (HATError) -> Void) {
let url: String = "https://\(userDomain)/control/v2/auth/password"
let parameters: Dictionary<String, Any> = ["password": oldPassword, "newPassword": newPassword]
let headers: [String: String] = [RequestHeaders.xAuthToken: userToken]
HATNetworkHelper.asynchronousRequest(
url,
method: .post,
encoding: Alamofire.JSONEncoding.default,
contentType: ContentType.json,
parameters: parameters,
headers: headers) { (response: HATNetworkHelper.ResultType) -> Void in
switch response {
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
failCallback(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
failCallback(.generalError(message, statusCode, error))
}
case .isSuccess(let isSuccess, _, let result, let token):
if isSuccess, let message: String = result.dictionaryValue["message"]?.stringValue {
successCallback(message, token)
}
}
}
}
// MARK: - Reset Password
/**
Resets the user's password
- parameter userDomain: The user's domain
- parameter userToken: The user's authentication token
- parameter email: The old password the user entered
- parameter successCallback: A function of type (String, String?) to call on success
- parameter failCallback: A fuction of type (HATError) to call on fail
*/
public static func resetPassword(userDomain: String, userToken: String, email: String, successCallback: @escaping (String, String?) -> Void, failCallback: @escaping (HATError) -> Void) {
let url: String = "https://\(userDomain)/control/v2/auth/passwordReset"
let parameters: Dictionary<String, Any> = ["email": email]
let headers: [String: String] = [RequestHeaders.xAuthToken: userToken]
HATNetworkHelper.asynchronousRequest(
url,
method: .post,
encoding: Alamofire.JSONEncoding.default,
contentType: ContentType.json,
parameters: parameters,
headers: headers) {(response: HATNetworkHelper.ResultType) -> Void in
switch response {
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
failCallback(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
failCallback(.generalError(message, statusCode, error))
}
case .isSuccess(let isSuccess, _, let result, let token):
if isSuccess, let message: String = result.dictionaryValue["message"]?.stringValue {
successCallback(message, token)
}
}
}
}
// MARK: - Create Combinator
/**
Creates combinator
- parameter userDomain: The user's domain
- parameter userToken: The user's authentication token
- parameter combinatorName: The desired combinator name
- parameter fieldToFilter: The field to filter with
- parameter lowerValue: The lower value of the filter
- parameter upperValue: The upper value of the filter
- parameter successCallback: A function of type (Bool, String?) to call on success
- parameter failCallback: A fuction of type (HATError) to call on fail
*/
public static func createCombinator(userDomain: String, userToken: String, endPoint: String, combinatorName: String, fieldToFilter: String, lowerValue: Int, upperValue: Int, transformationType: String? = nil, transformationPart: String? = nil, successCallback: @escaping (Bool, String?) -> Void, failCallback: @escaping (HATError) -> Void) {
let url: String = "https://\(userDomain)/api/v2.6/combinator/\(combinatorName)"
let bodyRequest: [BodyRequest] = [BodyRequest()]
bodyRequest[0].endpoint = endPoint
bodyRequest[0].filters[0].field = fieldToFilter
bodyRequest[0].filters[0].`operator`.lower = lowerValue
bodyRequest[0].filters[0].`operator`.upper = upperValue
if transformationPart != nil && transformationType != nil {
bodyRequest[0].filters[0].transformation = Transformation()
bodyRequest[0].filters[0].transformation?.part = transformationPart!
bodyRequest[0].filters[0].transformation?.transformation = transformationType!
}
var urlRequest: URLRequest = URLRequest.init(url: URL(string: url)!)
urlRequest.httpBody = BodyRequest.encode(from: bodyRequest)
urlRequest.httpMethod = HTTPMethod.post.rawValue
urlRequest.addValue(userToken, forHTTPHeaderField: RequestHeaders.xAuthToken)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
let configuration: URLSessionConfiguration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
let manager: SessionManager = Alamofire.SessionManager(configuration: configuration)
manager.request(urlRequest)
.responseJSON { response in
switch response.result {
case .success:
if response.response?.statusCode == 401 || response.response?.statusCode == 403 {
let message: String = NSLocalizedString("Token expired", comment: "")
failCallback(.generalError(message, response.response?.statusCode, nil))
} else {
successCallback(true, nil)
}
// in case of failure return the error but check for internet connection or unauthorised status and let the user know
case .failure(let error):
failCallback(HATError.generalError("", nil, error))
}
}
.session.finishTasksAndInvalidate()
}
/**
Gets the combinator data from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's authentication token
- parameter combinatorName: The combinator name to search for
- parameter successCallback: A function of type ([HATLocationsV2Object], String?) to call on success
- parameter failCallback: A fuction of type (HATError) to call on fail
*/
public static func getCombinator(userDomain: String, userToken: String, combinatorName: String, successCallback: @escaping ([JSON], String?) -> Void, failCallback: @escaping (HATError) -> Void) {
let url: String = "https://\(userDomain)/api/v2.6/combinator/\(combinatorName)"
let headers: [String: String] = [RequestHeaders.xAuthToken: userToken]
HATNetworkHelper.asynchronousRequest(
url,
method: .get,
encoding: Alamofire.JSONEncoding.default,
contentType: ContentType.json,
parameters: [:],
headers: headers) { (response: HATNetworkHelper.ResultType) -> Void in
switch response {
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
failCallback(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
failCallback(.generalError(message, statusCode, error))
}
case .isSuccess(let isSuccess, let statusCode, let result, let token):
if isSuccess, let array: [JSON] = result.array {
successCallback(array, token)
} else {
let message: String = NSLocalizedString("General Error", comment: "")
failCallback(.generalError(message, statusCode, nil))
}
}
}
}
}
/// The operator JSON format
private class Operator: HATObject {
var `operator`: String = "between"
var lower: Int = 0
var upper: Int = 0
}
/// The filter JSON format
private class Filter: HATObject {
var field: String = ""
var `operator`: Operator = Operator()
var transformation: Transformation?
}
/// The filter JSON format
private class Transformation: HATObject {
var transformation: String = ""
var part: String = ""
}
/// The combinator JSON format
private class BodyRequest: HATObject {
var endpoint: String = "rumpel/locations/ios"
var filters: [Filter] = [Filter()]
}
|
mpl-2.0
|
393055051f4f1422429d17173e056b4d
| 42.765683 | 345 | 0.566587 | 5.657286 | false | false | false | false |
evermeer/AlamofireXmlToObjects
|
AlamofireXmlToObjects/AlamofireXmlToObjects.swift
|
1
|
3450
|
//
// AlamofireXmlToObjects.swift
// AlamofireXmlToObjects
//
// Created by Edwin Vermeer on 6/21/15.
// Copyright (c) 2015 evict. All rights reserved.
//
import Foundation
import EVReflection
import XMLDictionary
import Alamofire
extension DataRequest {
static var outputXMLresult: Bool = false
enum ErrorCode: Int {
case noData = 1
}
internal static func newError(_ code: ErrorCode, failureReason: String) -> NSError {
let errorDomain = "com.alamofirejsontoobjects.error"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo)
return returnError
}
internal static func EVReflectionSerializer<T: EVObject>(_ keyPath: String?, mapToObject object: T? = nil) -> DataResponseSerializer<T> {
return DataResponseSerializer { request, response, data, error in
guard error == nil else {
return .failure(error!)
}
guard let _ = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = newError(.noData, failureReason: failureReason)
return .failure(error)
}
let object = T()
let xml: String = NSString(data: data ?? Data(), encoding: String.Encoding.utf8.rawValue) as? String ?? ""
if let result = NSDictionary(xmlString: xml ) {
if DataRequest.outputXMLresult {
print("Dictionary from XML = \(result)")
}
var XMLToMap: NSDictionary!
if let keyPath = keyPath, keyPath.isEmpty == false {
XMLToMap = result.value(forKeyPath: keyPath) as? NSDictionary ?? NSDictionary()
} else {
XMLToMap = result
}
let _ = EVReflection.setPropertiesfromDictionary(XMLToMap, anyObject: object)
return .success(object)
} else {
if DataRequest.outputXMLresult {
print("XML string = \(xml)")
}
let failureReason = "Data could not be serialized. Could not get a dictionary from the XML."
let error = newError(.noData, failureReason: failureReason)
return .failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter keyPath: The key path where EVReflection mapping should be performed
- parameter object: An object to perform the mapping on to
- parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by EVReflection.
- returns: The request.
*/
@discardableResult
open func responseObject<T: EVObject>(queue: DispatchQueue? = nil, keyPath: String? = nil, mapToObject object: T? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self {
let serializer = DataRequest.EVReflectionSerializer(keyPath, mapToObject: object)
return response(queue: queue, responseSerializer: serializer, completionHandler: completionHandler)
}
}
|
bsd-3-clause
|
9a954b06b81f97bd41c2a2f45241b6e8
| 38.655172 | 190 | 0.604058 | 5.315871 | false | false | false | false |
moongift/NCMBiOSUser
|
NCMBiOS_User/LoginViewController.swift
|
1
|
4122
|
//
// LoginViewController.swift
// NCMBiOS_User
//
// Created by naokits on 6/23/15.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var userNameTextField: UITextField!
@IBOutlet weak var mailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
// ------------------------------------------------------------------------
// MARK: - Lifecycle
// ------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// ------------------------------------------------------------------------
// MARK: - Navigation
// ------------------------------------------------------------------------
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
/// ログイン or 新規登録が成功した場合の処理
///
/// :param: user NCMBUserインスタンス
/// :returns: None
func successLoginOrSignupForUser(user: NCMBUser) {
println("会員登録後の処理")
// ACLを本人のみに設定
let acl = NCMBACL(user: NCMBUser.currentUser())
user.ACL = acl
user.saveInBackgroundWithBlock({ (error: NSError!) -> Void in
if error == nil {
// TODO一覧画面に遷移
self.performSegueWithIdentifier("unwindFromLogin", sender: self)
} else {
println("ACL設定の保存失敗: \(error)")
}
})
}
// ------------------------------------------------------------------------
// MARK: - Login or Signup
// ------------------------------------------------------------------------
/// 未登録なのか、登録済みなのかを判断する方法がなさそう?なので、ログインを実行してみて、エラーなら新規登録を行います。
///
/// :param: username ログイン時に指定するユーザ名
/// :param: email ログイン時に指定するメールアドレス
/// :param: password ログイン時に指定するパスワード
/// :returns: None
///
func loginWithUserName(username: String, password: String, mailaddress: String) {
NCMBUser.logInWithUsernameInBackground(username, password: password) { (user: NCMBUser!, error: NSError!) -> Void in
if error == nil {
self.successLoginOrSignupForUser(user)
} else {
println("ログインが失敗しました: \(error)")
let user = NCMBUser()
user.userName = username
user.password = password
user.mailAddress = mailaddress
user.signUpInBackgroundWithBlock { (error: NSError!) -> Void in
if error == nil {
self.successLoginOrSignupForUser(user)
return
}
println("新規会員登録が失敗しました: \(error)")
}
}
}
}
// ------------------------------------------------------------------------
// MARK: - Action
// ------------------------------------------------------------------------
/// ログインボタンをタップした時に実行されます。
@IBAction func tappedLoginButton(sender: AnyObject) {
let userName = self.userNameTextField.text
let mail = self.mailTextField.text
let password = self.passwordTextField.text
self.loginWithUserName(userName, password: password, mailaddress: mail)
}
}
|
mit
|
60817ead93e2dc76184af5191324074a
| 35.058252 | 124 | 0.495423 | 5.260623 | false | false | false | false |
larrynatalicio/15DaysofAnimationsinSwift
|
Animation 10 - SecretTextAnimation/SecretTextAnimation/FadingLabel.swift
|
1
|
2220
|
//
// FadingLabel.swift
// SecretTextAnimation
//
// Created by Larry Natalicio on 4/27/16.
// Copyright © 2016 Larry Natalicio. All rights reserved.
//
import UIKit
class FadingLabel: CharacterLabel {
// MARK: - Properties
override var attributedText: NSAttributedString! {
get {
return super.attributedText
}
set {
super.attributedText = newValue
self.animateIn { (finished) in
self.animateIn(nil)
}
}
}
override func initialTextLayerAttributes(_ textLayer: CATextLayer) {
textLayer.opacity = 0
}
// MARK: - Convenience
func animateIn(_ completion: ((_ finished: Bool) -> Void)?) {
for textLayer in characterTextLayers {
let duration = (TimeInterval(arc4random() % 100) / 200.0) + 0.25
let delay = TimeInterval(arc4random() % 100) / 500.0
CLMLayerAnimation.animation(textLayer, duration: duration, delay: delay, animations: {
textLayer.opacity = 1
}, completion: nil)
}
}
func animateOut(_ completion: ((_ finished: Bool) -> Void)?) {
var longestAnimation = 0.0
var longestAnimationIndex = -1
var index = 0
for textLayer in oldCharacterTextLayers {
let duration = (TimeInterval(arc4random() % 100) / 200.0) + 0.25
let delay = TimeInterval(arc4random() % 100) / 500.0
if duration+delay > longestAnimation {
longestAnimation = duration + delay
longestAnimationIndex = index
}
CLMLayerAnimation.animation(textLayer, duration: duration, delay: delay, animations: {
textLayer.opacity = 0
}, completion: { finished in
textLayer.removeFromSuperlayer()
if textLayer == self.oldCharacterTextLayers[longestAnimationIndex] {
if let completionFunction = completion {
completionFunction(finished)
}
}
})
index += 1
}
}
}
|
mit
|
ee218f90c048b959bf827a1e901f765d
| 29.819444 | 98 | 0.542587 | 5.172494 | false | false | false | false |
makingspace/NetworkingServiceKit
|
Example/NetworkingServiceKit/TwitterSearchService.swift
|
1
|
4062
|
//
// TwitterSearchService.swift
// Makespace Inc.
//
// Created by Phillipe Casorla Sagot (@darkzlave) on 4/24/17.
//
//
import Foundation
import NetworkingServiceKit
import ReactiveSwift
public struct TwitterUser {
public let handle: String
public let imagePath: String
public let location: String
public init?(dictionary:[String:Any]) {
guard let userHandle = dictionary["screen_name"] as? String,
let userImagePath = dictionary["profile_image_url_https"] as? String,
let location = dictionary["location"] as? String else { return nil }
self.handle = userHandle
self.imagePath = userImagePath
self.location = location
}
}
public struct TwitterSearchResult {
public let tweet: String
public let user: TwitterUser
public init?(dictionary:[String:Any]) {
guard let tweet = dictionary["text"] as? String,
let userDictionary = dictionary["user"] as? [String:Any],
let user = TwitterUser(dictionary:userDictionary) else { return nil }
self.tweet = tweet
self.user = user
}
}
open class TwitterSearchService: AbstractBaseService {
private var nextResultsPage: String?
open override var serviceVersion: String {
return "1.1"
}
/// Search Recent Tweets by hashtag
///
/// - Parameters:
/// - hashtag: the hashtag to use when searching
/// - completion: a list of TwitterSearchResult based on the term/hashtag sent
public func searchRecents(by hashtag: String,
completion:@escaping (_ results: [TwitterSearchResult]) -> Void) {
guard !hashtag.isEmpty else {
completion([TwitterSearchResult]())
return
}
let parameters = ["q": hashtag]
request(path: "search/tweets.json",
method: .get,
with: parameters,
success: { response in
var searchResults = [TwitterSearchResult]()
if let results = response["statuses"] as? [[String:Any]] {
for result in results {
if let twitterResult = TwitterSearchResult(dictionary: result) {
searchResults.append(twitterResult)
}
}
}
//save next page
if let metadata = response["search_metadata"] as? [String:Any],
let nextPage = metadata["next_results"] as? String {
self.nextResultsPage = nextPage
}
completion(searchResults)
}, failure: { _ in
completion([TwitterSearchResult]())
})
}
/// Continue the search for the last valid hashtag that was searched for (Reactive)
///
/// - Parameter completion: a list of TwitterSearchResult based on the term/hashtag sent
public func searchNextRecentsPageProducer() -> SignalProducer<[TwitterSearchResult],MSError> {
guard let nextPage = self.nextResultsPage else {
return SignalProducer.empty
}
return request(path: "search/tweets.json\(nextPage)").map { response -> [TwitterSearchResult] in
var searchResults = [TwitterSearchResult]()
guard let response = response else { return searchResults }
if let results = response["statuses"] as? [[String:Any]] {
for result in results {
if let twitterResult = TwitterSearchResult(dictionary: result) {
searchResults.append(twitterResult)
}
}
}
//save next page
if let metadata = response["search_metadata"] as? [String:Any],
let nextPage = metadata["next_results"] as? String {
self.nextResultsPage = nextPage
}
return searchResults
}
}
}
|
mit
|
48013e9b04a037b6a99c4cf6aebe7508
| 36.611111 | 104 | 0.567701 | 5.268482 | false | false | false | false |
cezarywojcik/Operations
|
Sources/Core/Shared/GroupOperation.swift
|
1
|
22890
|
//
// GroupOperation.swift
// Operations
//
// Created by Daniel Thorpe on 18/07/2015.
// Copyright © 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
// swiftlint:disable file_length
/**
An `Operation` subclass which enables the grouping
of other operations. Use `GroupOperation`s to associate
related operations together, thereby creating higher
levels of abstractions.
Additionally, `GroupOperation`s are useful as a way
of creating Operations which may repeat themselves before
subsequent operations can run. For example, authentication
operations.
*/
open class GroupOperation: AdvancedOperation, OperationQueueDelegate {
typealias ErrorsByOperation = [Operation: [Error]]
internal struct Errors {
var fatal = Array<Error>()
var attemptedRecovery: ErrorsByOperation = [:]
var previousAttempts: [Error] {
return attemptedRecovery.values.flatMap({ $0 })
}
var all: [Error] {
get {
var tmp: [Error] = fatal
tmp.append(contentsOf: previousAttempts)
return tmp
}
}
}
fileprivate let finishingOperation = Foundation.BlockOperation { }
fileprivate var protectedErrors = Protector(Errors())
fileprivate var canFinishOperation: GroupOperation.CanFinishOperation!
fileprivate var isGroupFinishing = false
fileprivate let groupFinishLock = NSRecursiveLock()
fileprivate var isAddingOperationsGroup = DispatchGroup()
/// - returns: the AdvancedOperationQueue the group runs operations on.
public let queue = AdvancedOperationQueue()
/// - returns: the operations which have been added to the queue
open fileprivate(set) var operations: [Operation] {
get {
return _operations.read { $0 }
}
set {
_operations.write { (ward: inout [Operation]) in
ward = newValue
}
}
}
fileprivate var _operations: Protector<[Operation]>
open override var userIntent: AdvancedOperation.UserIntent {
didSet {
let (nsops, ops) = operations.splitNSOperationsAndOperations
nsops.forEach { $0.setQualityOfServiceFromUserIntent(userIntent) }
ops.forEach { $0.userIntent = userIntent }
}
}
/**
Designated initializer.
- parameter operations: an array of `NSOperation`s.
*/
public init(operations ops: [Operation]) {
_operations = Protector<[Operation]>(ops)
// GroupOperation handles calling finish() on cancellation once all of its children have cancelled and finished
// and its finishingOperation has finished.
super.init(disableAutomaticFinishing: true) // Override default Operation finishing behavior
canFinishOperation = GroupOperation.CanFinishOperation(parentGroupOperation: self)
name = "Group Operation"
queue.isSuspended = true
queue.delegate = self
userIntent = operations.userIntent
addObserver(DidCancelObserver { [unowned self] operation in
if operation === self {
let errors = operation.errors
if errors.isEmpty {
self.operations.forEach { $0.cancel() }
}
else {
let (nsops, ops) = self.operations.splitNSOperationsAndOperations
nsops.forEach { $0.cancel() }
ops.forEach { $0.cancelWithError(OperationError.parentOperationCancelledWithErrors(errors)) }
}
}
})
}
/// Convenience initializer for direct usage without subclassing.
public convenience init(operations: Operation...) {
self.init(operations: operations)
}
/**
Executes the group by adding the operations to the queue. Then
starting the queue, and adding the finishing operation.
*/
open override func execute() {
_addOperations(operations.filter { !self.queue.operations.contains($0) }, addToOperationsArray: false)
_addCanFinishOperation(canFinishOperation)
queue.addOperation(finishingOperation)
queue.isSuspended = false
}
/**
Add an `NSOperation` to the group's queue.
- parameter operation: an `NSOperation` instance.
*/
open func addOperation(_ operation: Operation) {
addOperations(operation)
}
/**
Add multiple operations at once.
- parameter operations: an array of `NSOperation` instances.
*/
open func addOperations(_ operations: Operation...) {
addOperations(operations)
}
/**
Add multiple operations at once.
- parameter operations: an array of `NSOperation` instances.
*/
open func addOperations(_ additional: [Operation]) {
_addOperations(additional, addToOperationsArray: true)
}
fileprivate func _addOperations(_ additional: [Operation], addToOperationsArray: Bool = true) {
if additional.count > 0 {
let shouldAddOperations = groupFinishLock.withCriticalScope { () -> Bool in
guard !isGroupFinishing else { return false }
isAddingOperationsGroup.enter()
return true
}
guard shouldAddOperations else {
if !finishingOperation.isFinished {
assertionFailure("Cannot add new operations to a group after the group has started to finish.")
}
else {
assertionFailure("Cannot add new operations to a group after the group has completed.")
}
return
}
var handledCancelled = false
if isCancelled {
additional.forEachOperation { $0.cancel() }
handledCancelled = true
}
let logSeverity = log.severity
additional.forEachOperation { $0.log.severity = logSeverity }
queue.addOperations(additional)
if addToOperationsArray {
_operations.appendContentsOf(additional)
}
if !handledCancelled && isCancelled {
// It is possible that the cancellation happened before adding the
// additional operations to the operations array.
// Thus, ensure that all additional operations are cancelled.
additional.forEachOperation { if !$0.isCancelled { $0.cancel() } }
}
groupFinishLock.withCriticalScope {
isAddingOperationsGroup.leave()
}
}
}
/**
This method is called when a child operation in the group will finish with errors.
Often an operation will finish with errors become some of its pre-requisites were not
met. Errors of this nature should be recoverable. This can be done by re-trying the
original operation, but with another operation which fulfil the pre-requisites as a
dependency.
If the errors were recovered from, return true from this method, else return false.
Errors which are not handled will result in the Group finishing with errors.
- parameter errors: an [ErrorType], the errors of the child operation
- parameter operation: the child operation which is finishing
- returns: a Boolean, return true if the errors were handled, else return false.
*/
open func willAttemptRecoveryFromErrors(_ errors: [Error], inOperation operation: Operation) -> Bool {
return false
}
/**
This method is only called when a child operation finishes without any errors.
- parameter operation: the child operation which will finish without errors
*/
open func willFinishOperation(_ operation: Operation) {
// no-op
}
@available(*, unavailable, message: "Refactor your GroupOperation subclass as this method is no longer used.\n Override willFinishOperation(_: NSOperation) to manage scheduling of child operations. Override willAttemptRecoveryFromErrors(_: [ErrorType], inOperation: NSOperation) to do error handling. See code documentation for more details.")
open func willFinishOperation(_ operation: Operation, withErrors errors: [Error]) { }
@available(*, unavailable, renamed: "willFinishOperation")
open func operationDidFinish(_ operation: Operation, withErrors errors: [Error]) { }
internal func child(_ child: Operation, didEncounterFatalErrors errors: [Error]) {
addFatalErrors(errors)
}
internal func child(_ child: Operation, didAttemptRecoveryFromErrors errors: [Error]) {
protectedErrors.write { (tmp: inout Errors) in
tmp.attemptedRecovery[child] = errors
}
}
// MARK: - OperationQueueDelegate
/**
The group operation acts as its own queue's delegate. When an operation is added to the queue,
assuming that the group operation is not yet finishing or finished, then we add the operation
as a dependency to an internal "barrier" operation that separates executing from finishing state.
The purpose of this is to keep the internal operation as a final child operation that executes
when there are no more operations in the group operation, safely handling the transition of
group operation state.
*/
open func operationQueue(_ queue: AdvancedOperationQueue, willAddOperation operation: Operation) {
guard queue === self.queue else { return }
assert(!finishingOperation.isExecuting, "Cannot add new operations to a group after the group has started to finish.")
assert(!finishingOperation.isFinished, "Cannot add new operations to a group after the group has completed.")
if operation !== finishingOperation {
let shouldContinue = groupFinishLock.withCriticalScope { () -> Bool in
guard !isGroupFinishing else {
assertionFailure("Cannot add new operations to a group after the group has started to finish.")
return false
}
isAddingOperationsGroup.enter()
return true
}
guard shouldContinue else { return }
willAddChildOperationObservers.forEach { $0.groupOperation(self, willAddChildOperation: operation) }
canFinishOperation.addDependency(operation)
groupFinishLock.withCriticalScope {
isAddingOperationsGroup.leave()
}
}
}
/**
The group operation acts as it's own queue's delegate. When an operation finishes, if the
operation is the finishing operation, we finish the group operation here. Else, the group is
notified (using `operationDidFinish` that a child operation has finished.
*/
open func operationQueue(_ queue: AdvancedOperationQueue, willFinishOperation operation: Operation, withErrors errors: [Error]) {
guard queue === self.queue else { return }
if !errors.isEmpty {
if willAttemptRecoveryFromErrors(errors, inOperation: operation) {
child(operation, didAttemptRecoveryFromErrors: errors)
}
else {
child(operation, didEncounterFatalErrors: errors)
}
}
else if operation !== finishingOperation {
willFinishOperation(operation)
}
}
open func operationQueue(_ queue: AdvancedOperationQueue, didFinishOperation operation: Operation, withErrors errors: [Error]) {
guard queue === self.queue else { return }
if operation === finishingOperation {
finish(fatalErrors)
queue.isSuspended = true
}
}
open func operationQueue(_ queue: AdvancedOperationQueue, willProduceOperation operation: Operation) {
guard queue === self.queue else { return }
// Ensure that produced operations are added to GroupOperation's
// internal operations array (and cancelled if appropriate)
let shouldContinue = groupFinishLock.withCriticalScope { () -> Bool in
assert(!finishingOperation.isFinished, "Cannot produce new operations within a group after the group has completed.")
guard !isGroupFinishing else {
assertionFailure("Cannot produce new operations within a group after the group has started to finish.")
return false
}
isAddingOperationsGroup.enter()
return true
}
guard shouldContinue else { return }
_operations.append(operation)
if isCancelled && !operation.isCancelled {
operation.cancel()
}
groupFinishLock.withCriticalScope {
isAddingOperationsGroup.leave()
}
}
/**
This method is used for debugging the current state of a `GroupOperation`.
- returns: An `OperationDebugData` object containing debug data for the current `GroupOperation`.
*/
override open func debugData() -> OperationDebugData {
let operationData = super.debugData()
let queueData = queue.debugData()
return OperationDebugData(
description: "GroupOperation: \(self)",
properties: operationData.properties,
conditions: operationData.conditions,
dependencies: operationData.dependencies,
subOperations: queueData.subOperations)
}
}
public extension GroupOperation {
internal var internalErrors: Errors {
return protectedErrors.read { $0 }
}
/// - returns: the errors which could not be recovered from
var fatalErrors: [Error] {
return internalErrors.fatal
}
/**
Appends a fatal error.
- parameter error: an ErrorType
*/
final func addFatalError(_ error: Error) {
addFatalErrors([error])
}
/**
Appends an array of fatal errors.
- parameter errors: an [ErrorType]
*/
final func addFatalErrors(_ errors: [Error]) {
protectedErrors.write { (tmp: inout Errors) in
tmp.fatal.append(contentsOf: errors)
}
}
internal func didRecoverFromOperationErrors(_ operation: Operation) {
if let _ = internalErrors.attemptedRecovery[operation] {
log.verbose("successfully recovered from errors in \(operation)")
protectedErrors.write { (tmp: inout Errors) in
tmp.attemptedRecovery.removeValue(forKey: operation)
}
}
}
internal func didNotRecoverFromOperationErrors(_ operation: Operation) {
log.verbose("failed to recover from errors in \(operation)")
protectedErrors.write { (tmp: inout Errors) in
if let errors = tmp.attemptedRecovery.removeValue(forKey: operation) {
tmp.fatal.append(contentsOf: errors)
}
}
}
}
public extension GroupOperation {
@available(*, unavailable, renamed: "fatalErrors")
var aggregateErrors: [Error] {
return fatalErrors
}
@available(*, unavailable, renamed: "addFatalError")
final func aggregateError(_ error: Error) {
addFatalError(error)
}
}
public protocol GroupOperationWillAddChildObserver: OperationObserverType {
func groupOperation(_ group: GroupOperation, willAddChildOperation child: Operation)
}
extension GroupOperation {
internal var willAddChildOperationObservers: [GroupOperationWillAddChildObserver] {
return observers.compactMap { $0 as? GroupOperationWillAddChildObserver }
}
}
/**
WillAddChildObserver is an observer which will execute a
closure when the group operation it is attaches to adds a
child operation to its queue.
*/
public struct WillAddChildObserver: GroupOperationWillAddChildObserver {
public typealias BlockType = (_ group: GroupOperation, _ child: Operation) -> Void
fileprivate let block: BlockType
/// - returns: a block which is called when the observer is attached to an operation
public var didAttachToOperation: DidAttachToOperationBlock? = .none
/**
Initialize the observer with a block.
- parameter willAddChild: the `WillAddChildObserver.BlockType`
- returns: an observer.
*/
public init(willAddChild: @escaping BlockType) {
self.block = willAddChild
}
/// Conforms to GroupOperationWillAddChildObserver
public func groupOperation(_ group: GroupOperation, willAddChildOperation child: Operation) {
block(group, child)
}
/// Base OperationObserverType method
public func didAttachToOperation(_ operation: AdvancedOperation) {
didAttachToOperation?(operation)
}
}
private extension GroupOperation {
/**
The group operation handles thread-safe addition of operations by utilizing two final operations:
- a CanFinishOperation which manages handling GroupOperation internal state and has every child
operation as a dependency
- a finishingOperation, which has the CanFinishOperation as a dependency
The purpose of this is to handle the possibility that GroupOperation.addOperation() or
GroupOperation.queue.addOperation() are called right after all current child operations have
completed (i.e. after the CanFinishOperation has been set to ready), but *prior* to being able
to process that the GroupOperation is finishing (i.e. prior to the CanFinishOperation executing and
acquiring the GroupOperation.groupFinishLock to set state).
*/
class CanFinishOperation: Operation {
fileprivate weak var parent: GroupOperation?
fileprivate var _finished = false
fileprivate var _executing = false
init(parentGroupOperation: GroupOperation) {
self.parent = parentGroupOperation
super.init()
}
override func start() {
// Override NSOperation.start() because this operation may have to
// finish asynchronously (if it has to register to be notified when
// operations are no longer being added concurrently).
//
// Since we override start(), it is important to send NSOperation
// isExecuting / isFinished KVO notifications.
//
// (Otherwise, the operation may not be released, there may be
// problems with dependencies, with the queue's handling of
// maxConcurrentOperationCount, etc.)
isExecuting = true
main()
}
override func main() {
execute()
}
func execute() {
if let parent = parent {
// All operations that were added as a side-effect of anything up to
// WillFinishObservers of prior operations should have been executed.
//
// Handle an edge case caused by concurrent calls to GroupOperation.addOperations()
let isWaiting = parent.groupFinishLock.withCriticalScope { () -> Bool in
// Is anything currently adding operations?
guard parent.isAddingOperationsGroup.wait(timeout: DispatchTime.now()) == .success else {
// Operations are actively being added to the group
// Wait for this to complete before proceeding.
//
// Register to dispatch a new call to execute() in the future, after the
// wait completes (i.e. after concurrent calls to GroupOperation.addOperations()
// have completed), and return from this call to execute() without finishing
// the operation.
parent.isAddingOperationsGroup.notify(queue: Queue(qos: qualityOfService).queue, execute: execute)
return true
}
// Check whether new operations were added prior to the lock
// by checking for child operations that are not finished.
let activeOperations = parent.operations.filter({ !$0.isFinished })
if !activeOperations.isEmpty {
// Child operations were added after this CanFinishOperation became
// ready, but before it executed or before the lock could be acquired.
//
// The GroupOperation should wait for these child operations to finish
// before finishing. Add the oustanding child operations as
// dependencies to a new CanFinishOperation, and add that as the
// GroupOperation's new CanFinishOperation.
let newCanFinishOp = GroupOperation.CanFinishOperation(parentGroupOperation: parent)
activeOperations.forEach { op in
newCanFinishOp.addDependency(op)
}
parent.canFinishOperation = newCanFinishOp
parent._addCanFinishOperation(newCanFinishOp)
}
else {
// There are no additional operations to handle.
// Ensure that no new operations can be added.
parent.isGroupFinishing = true
}
return false
}
guard !isWaiting else { return }
}
isExecuting = false
isFinished = true
}
override fileprivate(set) var isExecuting: Bool {
get {
return _executing
}
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
override fileprivate(set) var isFinished: Bool {
get {
return _finished
}
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
}
func _addCanFinishOperation(_ canFinishOperation: GroupOperation.CanFinishOperation) {
finishingOperation.addDependency(canFinishOperation)
queue._addCanFinishOperation(canFinishOperation)
}
}
private extension AdvancedOperationQueue {
func _addCanFinishOperation(_ canFinishOperation: GroupOperation.CanFinishOperation) {
// Do not add observers (not needed - CanFinishOperation is an implementation detail of GroupOperation)
// Do not add conditions (CanFinishOperation has none)
// Call NSOperationQueue.addOperation() directly
super.addOperation(canFinishOperation)
}
}
|
mit
|
a7acd7d5efb9244bdd9c8190d2c7a831
| 37.21202 | 347 | 0.635502 | 5.449762 | false | false | false | false |
theadam/SwiftClient
|
Sources/Request.swift
|
1
|
9643
|
//
// SwiftClient.swift
// SwiftClient
//
// Created by Adam Nalisnick on 10/25/14.
// Copyright (c) 2014 Adam Nalisnick. All rights reserved.
//
import Foundation
private let errorHandler = {(error:Error) -> Void in };
/// Class for handling request building and sending
open class Request {
var data:Any?;
var headers: [String : String];
open var url:String;
let method: String;
var delegate: URLSessionDelegate?;
var timeout:Double;
var transformer:(Response) -> Response = {$0};
var query:[String] = Array();
var errorHandler:((Error) -> Void);
var formData:FormData?;
internal init(method: String, url: String, errorHandler:@escaping (Error) -> Void){
self.method = method;
self.url = url;
self.headers = Dictionary();
self.timeout = 60;
self.errorHandler = errorHandler;
}
/// Sets headers on the request from a dictionary
open func set(headers: [String:String]) -> Request{
for(key, value) in headers {
_ = self.set(key: key, value: value);
}
return self;
}
/// Sets headers on the request from a key and value
open func set(key: String, value: String) -> Request{
self.headers[key] = value;
return self;
}
/// Executs a middleware function on the request
open func use(middleware: (Request) -> Request) -> Request{
return middleware(self);
}
/// Stores a response transformer to be used on the received HTTP response
open func transform(transformer: @escaping (Response) -> Response) -> Request{
let oldTransformer = self.transformer;
self.transformer = {(response:Response) -> Response in
return transformer(oldTransformer(response));
}
return self;
}
/// Sets the content-type. Can be set using shorthand.
/// ex: json, html, form, urlencoded, form, form-data, xml, text
///
/// When not using shorthand, the value is used directory.
open func type(type:String) -> Request {
_ = self.set(key: "content-type", value: (types[type] ?? type));
return self;
}
/// Gets the header value for the case insensitive key passed
open func getHeader(header:String) -> String? {
return self.headers[header.lowercased()];
}
/// Gets the content-type of the request
private func getContentType() -> String?{
return getHeader(header: "content-type");
}
/// Sets the type if not set
private func defaultToType(type:String){
if self.getContentType() == nil {
_ = self.type(type: type);
}
}
/// Adds query params on the URL from a dictionary
open func query(query:[String : String]) -> Request{
for (key,value) in query {
self.query.append(queryPair(key: key, value: value))
}
return self;
}
/// Adds query params on the URL from a key and value
open func query(query:String) -> Request{
self.query.append(uriEncode(string: query));
return self;
}
/// Handles adding a single key and value to the request body
private func _send(key: String, value: Any) -> Request{
if var dict = self.data as? [String : Any] {
dict[key] = value;
self.data = dict;
}
else{
let arrayData: [String: Any] = [key : value];
self.data = arrayData;
}
return self;
}
/// Adds a string to the request body. If the body already contains
/// a string and the content type is form, & is also appended. If the body
/// is a string and the content-type is not a form, the string is merely appended.
/// Otherwise, the body is set to the string.
open func send(data:String) -> Request{
defaultToType(type: "form");
if self.getContentType() == types["form"] {
var oldData = "";
if let stringData = self.data as? String {
oldData = stringData + "&";
}
let dataString: String = oldData + uriEncode(string: data);
self.data = dataString;
}
else{
let oldData = self.data as? String ?? "";
let dataString: String = oldData + data;
self.data = dataString;
}
return self;
}
/// Sets the body of the request. If the body is a Dictionary,
/// and a dictionary is passed in, the two are merged. Otherwise,
/// the body is set directly to the passed data.
open func send(data:Any) -> Request{
if let entries = data as? [String : Any] {
defaultToType(type: "json");
for (key, value) in entries {
_ = self._send(key: key, value: value);
}
}
else{
self.data = data;
}
return self;
}
/// Sets the request's timeout interval
open func timeout(timeout:Double) -> Request {
self.timeout = timeout;
return self;
}
/// Sets the delegate on the request
open func delegate(delegate:URLSessionDelegate) -> Request {
self.delegate = delegate;
return self;
}
/// Sets the error handler on the request
open func onError(errorHandler:@escaping (Error) -> Void) -> Request {
self.errorHandler = errorHandler;
return self;
}
/// Adds Basic HTTP Auth to the request
open func auth(username:String, password:String) -> Request {
let authString = base64Encode(string: username + ":" + password);
_ = self.set(key: "authorization", value: "Basic \(authString)")
return self;
}
private func getFormData() -> FormData {
if(self.formData == nil) {
self.formData = FormData();
}
return self.formData!;
}
/// Adds a field to a multipart request
open func field(name:String, value:String) -> Request {
self.getFormData().append(name: name, value: value);
return self;
}
/// Attached a file to a multipart request. If the mimeType isnt given, it will be inferred.
open func attach(name:String, data:Data, filename:String, withMimeType mimeType:String? = nil) -> Request {
self.getFormData().append(name: name, data: data, filename: filename, mimeType: mimeType)
return self
}
/// Attached a file to a multipart request. If the mimeType isnt given, it will be inferred.
/// If the filename isnt given it will be pulled from the path
open func attach(name:String, path:String, filename:String? = nil, withMimeType mimeType:String? = nil) -> Request {
var basename:String! = filename;
if(filename == nil){
basename = URL(string: path)!.lastPathComponent;
}
let data = try? Data(contentsOf: URL(fileURLWithPath: path))
self.getFormData().append(name: name, data: data ?? Data(), filename: basename, mimeType: mimeType)
return self
}
/// Sends the request using the passed in completion handler and the optional error handler
open func end(done: @escaping (Response) -> Void, onError errorHandler: ((Error) -> Void)? = nil) {
if(self.query.count > 0){
if let queryString = queryString(query: self.query){
self.url += self.url.range(of: "?") != nil ? "&" : "?";
self.url += queryString;
}
}
let queue = OperationQueue();
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self.delegate, delegateQueue: queue);
var request = URLRequest(url: URL(string: self.url)!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: TimeInterval(self.timeout));
request.httpMethod = self.method;
if(self.method != "GET" && self.method != "HEAD") {
if(self.formData != nil) {
request.httpBody = self.formData!.getBody() as Data?;
_ = self.type(type: self.formData!.getContentType());
_ = self.set(key: "Content-Length", value: String(describing: request.httpBody?.count));
}
else if(self.data != nil){
if let data = self.data as? Data {
request.httpBody = data;
}
else if let type = self.getContentType(){
if let serializer = serializers[type]{
request.httpBody = serializer(self.data!) as Data?
}
else {
request.httpBody = stringToData(string: String(describing: self.data!))
}
}
}
}
for (key, value) in self.headers {
request.setValue(value, forHTTPHeaderField: key);
}
let task = session.dataTask(with: request, completionHandler:
{(data: Data?, response: URLResponse?, error: Error?) -> Void in
if let response = response as? HTTPURLResponse {
done(self.transformer(Response(response: response, request: self, rawData: data)));
}
else if errorHandler != nil {
errorHandler!(error!);
}
else {
self.errorHandler(error!);
}
}
);
task.resume();
}
}
|
mit
|
f908513ec69e954b2f50abe46a3a27e7
| 34.452206 | 167 | 0.566006 | 4.574478 | false | false | false | false |
GitHubStuff/SwiftExtensions
|
SwiftExtensionsTests/DateExtensions.swift
|
1
|
1383
|
//
// DateExtensions.swift
// SwiftExtensions
//
// Created by Steven Smith on 7/3/17.
// Copyright © 2017 LTMM. All rights reserved.
//
import XCTest
class DateExtensions: 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 testUtc() {
let date = Date(timeIntervalSince1970: 400_000_000)
let str = date.utc
XCTAssertEqual(str, "1982-09-04T15:06:40Z")
let v = date.utcName
XCTAssertEqual(v, "19820904T150640")
}
func testRefined() {
let date = Date(timeIntervalSince1970: 400_000_000)
let str = date.utc
XCTAssertEqual(str, "1982-09-04T15:06:40Z")
let dateOnly = date.refinedFor(mode: .date)
let newUtc = dateOnly.utc
XCTAssertEqual(newUtc, "1982-09-04T00:00:00Z")
let timeOnly = date.refinedFor(mode: .time)
let timeUtc = timeOnly.utc
XCTAssertEqual(timeUtc, "1982-09-04T15:06:00Z")
let dateTime = date.refinedFor(mode: .dateAndTime)
XCTAssertEqual(dateTime, date)
}
}
|
mit
|
8ca6cbe230cbc905c4667faa3a7bd7bb
| 27.791667 | 111 | 0.612156 | 3.860335 | false | true | false | false |
ZwxWhite/V2EX
|
V2EX/Pods/RealmSwift/RealmSwift/Object.swift
|
8
|
13210
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
In Realm you define your model classes by subclassing `Object` and adding properties to be persisted.
You then instantiate and use your custom subclasses instead of using the Object class directly.
```swift
class Dog: Object {
dynamic var name: String = ""
dynamic var adopted: Bool = false
let siblings = List<Dog>()
}
```
### Supported property types
- `String`, `NSString`
- `Int`
- `Int8`, `Int16`, `Int32`, `Int64`
- `Float`
- `Double`
- `Bool`
- `NSDate`
- `NSData`
- `RealmOptional<T>` for optional numeric properties
- `Object` subclasses for to-one relationships
- `List<T: Object>` for to-many relationships
`String`, `NSString`, `NSDate`, `NSData` and `Object` subclass properties can be
optional. `Int`, `Int8`, Int16`, Int32`, `Int64`, `Float`, `Double`, `Bool`
and `List` properties cannot. To store an optional number, instead use
`RealmOptional<Int>`, `RealmOptional<Float>`, `RealmOptional<Double>`, or
`RealmOptional<Bool>` instead, which wraps an optional value of the generic type.
All property types except for `List` and `RealmOptional` *must* be declared as
`dynamic var`. `List` and `RealmOptional` properties must be declared as
non-dynamic `let` properties.
### Querying
You can gets `Results` of an Object subclass via the `objects(_:)` instance
method on `Realm`.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
public class Object: RLMObjectBase {
// MARK: Initializers
/**
Initialize a standalone (unpersisted) `Object`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
- see: Realm().add(_:)
*/
public required override init() {
super.init()
}
/**
Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON object such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
*/
public init(value: AnyObject) {
self.dynamicType.sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema
super.init(value: value, schema: RLMSchema.partialSharedSchema())
}
// MARK: Properties
/// The `Realm` this object belongs to, or `nil` if the object
/// does not belong to a realm (the object is standalone).
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The `ObjectSchema` which lists the persisted properties for this object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self))
}
/// Indicates if an object can no longer be accessed.
///
/// An object can no longer be accessed if the object has been deleted from the containing
/// `realm` or if `invalidate` is called on the containing `realm`.
public override var invalidated: Bool { return super.invalidated }
/// Returns a human-readable description of this object.
public override var description: String { return super.description }
#if os(OSX)
/// Helper to return the class name for an Object subclass.
public final override var className: String { return "" }
#else
/// Helper to return the class name for an Object subclass.
public final var className: String { return "" }
#endif
// MARK: Object Customization
/**
Override to designate a property as the primary key for an `Object` subclass. Only properties of
type String and Int can be designated as the primary key. Primary key
properties enforce uniqueness for each value whenever the property is set which incurs some overhead.
Indexes are created automatically for primary key properties.
- returns: Name of the property designated as the primary key, or `nil` if the model has no primary key.
*/
public class func primaryKey() -> String? { return nil }
/**
Override to return an array of property names to ignore. These properties will not be persisted
and are treated as transient.
- returns: `Array` of property names to ignore.
*/
public class func ignoredProperties() -> [String] { return [] }
/**
Return an array of property names for properties which should be indexed. Only supported
for string and int properties.
- returns: `Array` of property names to index.
*/
public class func indexedProperties() -> [String] { return [] }
// MARK: Inverse Relationships
/**
Get an `Array` of objects of type `T` which have this object as the given property value. This can
be used to get the inverse relationship value for `Object` and `List` properties.
- parameter type: The type of object on which the relationship to query is defined.
- parameter propertyName: The name of the property which defines the relationship.
- returns: An `Array` of objects of type `T` which have this object as their value for the `propertyName` property.
*/
public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] {
// FIXME: use T.className()
return RLMObjectBaseLinkingObjectsOfClass(self, (T.self as Object.Type).className(), propertyName) as! [T]
}
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
public subscript(key: String) -> AnyObject? {
get {
if realm == nil {
return self.valueForKey(key)
}
let property = RLMValidatedGetProperty(self, key)
if property.type == .Array {
return self.listForProperty(property)
}
return RLMDynamicGet(self, property)
}
set(value) {
if realm == nil {
self.setValue(value, forKey: key)
}
else {
RLMDynamicValidatedSet(self, key, value)
}
}
}
// MARK: Dynamic list
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the KVC returns.
Returns a List of DynamicObjects for a property name
- warning: This method is useful only in specialized circumstances
- parameter propertyName: The name of the property to get a List<DynamicObject>
- returns: A List of DynamicObjects
:nodoc:
*/
public func dynamicList(propertyName: String) -> List<DynamicObject> {
return unsafeBitCast(listForProperty(RLMValidatedGetProperty(self, propertyName)), List<DynamicObject>.self)
}
// MARK: Equatable
/// Returns whether both objects are equal.
/// Objects are considered equal when they are both from the same Realm
/// and point to the same underlying object in the database.
public override func isEqual(object: AnyObject?) -> Bool {
return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase);
}
// MARK: Private functions
// FIXME: None of these functions should be exposed in the public interface.
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(value: AnyObject, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
// Helper for getting the list object for a property
internal func listForProperty(prop: RLMProperty) -> RLMListBase {
return object_getIvar(self, prop.swiftIvar) as! RLMListBase
}
}
/// Object interface which allows untyped getters and setters for Objects.
/// :nodoc:
public final class DynamicObject: Object {
private var listProperties = [String: List<DynamicObject>]()
// Override to create List<DynamicObject> on access
internal override func listForProperty(prop: RLMProperty) -> RLMListBase {
if let list = listProperties[prop.name] {
return list
}
let list = List<DynamicObject>()
listProperties[prop.name] = list
return list
}
/// :nodoc:
public override func valueForUndefinedKey(key: String) -> AnyObject? {
return self[key]
}
/// :nodoc:
public override func setValue(value: AnyObject?, forUndefinedKey key: String) {
self[key] = value
}
/// :nodoc:
public override class func shouldIncludeInDefaultSchema() -> Bool {
return false;
}
}
/// :nodoc:
/// Internal class. Do not use directly.
public class ObjectUtil: NSObject {
@objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.ignoredProperties() as NSArray?
}
return nil
}
@objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.indexedProperties() as NSArray?
}
return nil
}
// Get the names of all properties in the object which are of type List<>.
@objc private class func getGenericListPropertyNames(object: AnyObject) -> NSArray {
return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in
return prop.value.dynamicType is RLMListBase.Type
}.flatMap { (prop: Mirror.Child) in
return prop.label
}
}
@objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) {
(object as! Object).listForProperty(property)._rlmArray = array
}
@objc private class func getOptionalProperties(object: AnyObject) -> NSDictionary {
return Mirror(reflecting: object).children.reduce([String:AnyObject]()) { (var properties: [String:AnyObject], prop: Mirror.Child) in
guard let name = prop.label else { return properties }
let mirror = Mirror(reflecting: prop.value)
let type = mirror.subjectType
if type is Optional<String>.Type || type is Optional<NSString>.Type {
properties[name] = Int(PropertyType.String.rawValue)
} else if type is Optional<NSDate>.Type {
properties[name] = Int(PropertyType.Date.rawValue)
} else if type is Optional<NSData>.Type {
properties[name] = Int(PropertyType.Data.rawValue)
} else if type is Optional<Object>.Type {
properties[name] = Int(PropertyType.Object.rawValue)
} else if type is RealmOptional<Int>.Type ||
type is RealmOptional<Int8>.Type ||
type is RealmOptional<Int16>.Type ||
type is RealmOptional<Int32>.Type ||
type is RealmOptional<Int64>.Type {
properties[name] = Int(PropertyType.Int.rawValue)
} else if type is RealmOptional<Float>.Type {
properties[name] = Int(PropertyType.Float.rawValue)
} else if type is RealmOptional<Double>.Type {
properties[name] = Int(PropertyType.Double.rawValue)
} else if type is RealmOptional<Bool>.Type {
properties[name] = Int(PropertyType.Bool.rawValue)
} else if prop.value as? RLMOptionalBase != nil {
throwRealmException("'\(type)' is not a a valid RealmOptional type.")
} else if mirror.displayStyle == .Optional {
properties[name] = NSNull()
}
return properties
}
}
@objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? {
return nil
}
}
|
mit
|
2246d46770e58d133991ad97695ef3e9
| 36.211268 | 141 | 0.650189 | 4.71449 | false | false | false | false |
bag-umbala/music-umbala
|
Music-Umbala/Pods/M13Checkbox/Sources/Paths/M13CheckboxPathGenerator.swift
|
2
|
8834
|
//
// M13CheckboxPathGenerator.swift
// M13Checkbox
//
// Created by McQuilkin, Brandon on 10/6/16.
// Copyright © 2016 Brandon McQuilkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
/// The base class that generates the paths for the different mark types.
internal class M13CheckboxPathGenerator {
//----------------------------
// MARK: - Properties
//----------------------------
/// The maximum width or height the path will be generated with.
var size: CGFloat = 0.0
/// The line width of the created checkmark.
var checkmarkLineWidth: CGFloat = 1.0
/// The line width of the created box.
var boxLineWidth: CGFloat = 1.0
/// The corner radius of the box.
var cornerRadius: CGFloat = 3.0
/// The box type to create.
var boxType: M13Checkbox.BoxType = .circle
//----------------------------
// MARK: - Box Paths
//----------------------------
/**
Creates a path object for the box.
- returns: A `UIBezierPath` representing the box.
*/
final func pathForBox() -> UIBezierPath? {
switch boxType {
case .circle:
return pathForCircle()
case .square:
return pathForRoundedRect()
}
}
/**
Creates a circular path for the box. The path starts at the top center point of the box.
- returns: A `UIBezierPath` representing the box.
*/
func pathForCircle() -> UIBezierPath? {
let radius = (size - boxLineWidth) / 2.0
// Create a circle that starts in the top right hand corner.
return UIBezierPath(arcCenter: CGPoint(x: size / 2.0, y: size / 2.0),
radius: radius,
startAngle: CGFloat(-M_PI_2),
endAngle: CGFloat((2 * M_PI) - M_PI_2),
clockwise: true)
}
/**
Creates a rounded rect path for the box. The path starts at the top center point of the box.
- returns: A `UIBezierPath` representing the box.
*/
func pathForRoundedRect() -> UIBezierPath? {
let path = UIBezierPath()
let lineOffset: CGFloat = boxLineWidth / 2.0
let trX: CGFloat = size - lineOffset - cornerRadius
let trY: CGFloat = 0.0 + lineOffset + cornerRadius
let tr = CGPoint(x: trX, y: trY)
let brX: CGFloat = size - lineOffset - cornerRadius
let brY: CGFloat = size - lineOffset - cornerRadius
let br = CGPoint(x: brX, y: brY)
let blX: CGFloat = 0.0 + lineOffset + cornerRadius
let blY: CGFloat = size - lineOffset - cornerRadius
let bl = CGPoint(x: blX, y: blY)
let tlX: CGFloat = 0.0 + lineOffset + cornerRadius
let tlY: CGFloat = 0.0 + lineOffset + cornerRadius
let tl = CGPoint(x: tlX, y: tlY)
path.move(to: CGPoint(x: (tl.x + tr.x) / 2.0, y: ((tl.y + tr.y) / 2.0) - cornerRadius))
// Top side.
let trYCr: CGFloat = tr.y - cornerRadius
path.addLine(to: CGPoint(x: tr.x, y: trYCr))
// Right arc
if cornerRadius != 0 {
path.addArc(withCenter: tr,
radius: cornerRadius,
startAngle: CGFloat(-M_PI_2),
endAngle: 0.0,
clockwise: true)
}
// Right side.
let brXCr: CGFloat = br.x + cornerRadius
path.addLine(to: CGPoint(x: brXCr, y: br.y))
// Bottom right arc.
if cornerRadius != 0 {
path.addArc(withCenter: br,
radius: cornerRadius,
startAngle: 0.0,
endAngle: CGFloat(M_PI_2),
clockwise: true)
}
// Bottom side.
let blYCr: CGFloat = bl.y + cornerRadius
path.addLine(to: CGPoint(x: bl.x , y: blYCr))
// Bottom left arc.
if cornerRadius != 0 {
path.addArc(withCenter: bl,
radius: cornerRadius,
startAngle: CGFloat(M_PI_2),
endAngle: CGFloat(M_PI),
clockwise: true)
}
// Left side.
let tlXCr: CGFloat = tl.x - cornerRadius
path.addLine(to: CGPoint(x: tlXCr, y: tl.y))
// Top left arc.
if cornerRadius != 0 {
path.addArc(withCenter: tl,
radius: cornerRadius,
startAngle: CGFloat(M_PI),
endAngle: CGFloat(M_PI + M_PI_2),
clockwise: true)
}
path.close()
return path
}
/**
Creates a small dot for the box.
- returns: A `UIBezierPath` representing the dot.
*/
func pathForDot() -> UIBezierPath? {
let boxPath = pathForBox()
let scale: CGFloat = 1.0 / 20.0
boxPath?.apply(CGAffineTransform(scaleX: scale, y: scale))
boxPath?.apply(CGAffineTransform(translationX: (size - (size * scale)) / 2.0, y: (size - (size * scale)) / 2.0))
return boxPath
}
//----------------------------
// MARK: - Check Generation
//----------------------------
/**
Generates the path for the mark for the given state.
- parameter state: The state to generate the mark path for.
- returns: A `UIBezierPath` representing the mark.
*/
final func pathForMark(_ state: M13Checkbox.CheckState?) -> UIBezierPath? {
guard let state = state else {
return nil
}
switch state {
case .unchecked:
return pathForUnselectedMark()
case .checked:
return pathForMark()
case .mixed:
return pathForMixedMark()
}
}
/**
Generates the path for the long mark for the given state used in the spiral animation.
- parameter state: The state to generate the long mark path for.
- returns: A `UIBezierPath` representing the long mark.
*/
final func pathForLongMark(_ state: M13Checkbox.CheckState?) -> UIBezierPath? {
guard let state = state else {
return nil
}
switch state {
case .unchecked:
return pathForLongUnselectedMark()
case .checked:
return pathForLongMark()
case .mixed:
return pathForLongMixedMark()
}
}
/**
Creates a path object for the mark.
- returns: A `UIBezierPath` representing the mark.
*/
func pathForMark() -> UIBezierPath? {
return nil
}
/**
Creates a path object for the long mark.
- returns: A `UIBezierPath` representing the long mark.
*/
func pathForLongMark() -> UIBezierPath? {
return nil
}
/**
Creates a path object for the mixed mark.
- returns: A `UIBezierPath` representing the mixed mark.
*/
func pathForMixedMark() -> UIBezierPath? {
return nil
}
/**
Creates a path object for the long mixed mark.
- returns: A `UIBezierPath` representing the long mixed mark.
*/
func pathForLongMixedMark() -> UIBezierPath? {
return nil
}
/**
Creates a path object for the unselected mark.
- returns: A `UIBezierPath` representing the unselected mark.
*/
func pathForUnselectedMark() -> UIBezierPath? {
return nil
}
/**
Creates a path object for the long unselected mark.
- returns: A `UIBezierPath` representing the long unselected mark.
*/
func pathForLongUnselectedMark() -> UIBezierPath? {
return nil
}
}
|
mit
|
ee6d9ce9146d0a6bfc60673bcfd098c8
| 34.051587 | 464 | 0.561417 | 4.614943 | false | false | false | false |
pdx-cocoaheads/pdxcocoaheads.com
|
Tests/App/Meetup/MeetupEvent+MustacheTests.swift
|
1
|
1617
|
import XCTest
@testable import App
import Mustache
/** Ensure `mustacheBox(forKey:)` returns expected values. */
class EventMustacheBoxTests: XCTestCase {
let event = MeetupEvent(name: "Discussion",
time: 1234,
utcOffset: 5678,
rsvpCount: 9,
link: "http://example.com")
func testMustacheBoxName() {
let key = "name"
let expected = "Discussion"
let boxValue = event.mustacheBox(forKey: key).value
XCTAssertTrue((boxValue as? String) == expected)
}
func testMustacheBoxTime() {
let key = "time"
let expected = 1234
let boxValue = event.mustacheBox(forKey: key).value
XCTAssertTrue((boxValue as? Int) == expected)
}
func testMustacheBoxUtcOffset() {
let key = "utcOffset"
let expected = 5678
let boxValue = event.mustacheBox(forKey: key).value
XCTAssertTrue((boxValue as? Int) == expected)
}
func testMustacheBoxRsvpCount() {
let key = "rsvpCount"
let expected = 9
let boxValue = event.mustacheBox(forKey: key).value
XCTAssertTrue((boxValue as? Int) == expected)
}
func testMustacheBoxLink() {
let key = "link"
let expected = "http://example.com"
let boxValue = event.mustacheBox(forKey: key).value
XCTAssertTrue((boxValue as? String) == expected)
}
}
|
mit
|
985d89b1a4bb55cef619c6331eb35d89
| 24.666667 | 61 | 0.531231 | 4.960123 | false | true | false | false |
auth0/Auth0.swift
|
Auth0/Auth0Authentication.swift
|
1
|
15426
|
import Foundation
struct Auth0Authentication: Authentication {
let clientId: String
let url: URL
var telemetry: Telemetry
var logger: Logger?
let session: URLSession
init(clientId: String, url: URL, session: URLSession = URLSession.shared, telemetry: Telemetry = Telemetry()) {
self.clientId = clientId
self.url = url
self.session = session
self.telemetry = telemetry
}
func login(email: String, code: String, audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
return login(username: email, otp: code, realm: "email", audience: audience, scope: scope)
}
func login(phoneNumber: String, code: String, audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
return login(username: phoneNumber, otp: code, realm: "sms", audience: audience, scope: scope)
}
func login(usernameOrEmail username: String, password: String, realmOrConnection realm: String, audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
let url = URL(string: "oauth/token", relativeTo: self.url)!
var payload: [String: Any] = [
"username": username,
"password": password,
"grant_type": "http://auth0.com/oauth/grant-type/password-realm",
"client_id": self.clientId,
"realm": realm
]
payload["audience"] = audience
payload["scope"] = includeRequiredScope(in: scope)
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func loginDefaultDirectory(withUsername username: String, password: String, audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
let url = URL(string: "oauth/token", relativeTo: self.url)!
var payload: [String: Any] = [
"username": username,
"password": password,
"grant_type": "password",
"client_id": self.clientId
]
payload["audience"] = audience
payload["scope"] = includeRequiredScope(in: scope)
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func login(withOTP otp: String, mfaToken: String) -> Request<Credentials, AuthenticationError> {
let url = URL(string: "oauth/token", relativeTo: self.url)!
let payload: [String: Any] = [
"otp": otp,
"mfa_token": mfaToken,
"grant_type": "http://auth0.com/oauth/grant-type/mfa-otp",
"client_id": self.clientId
]
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func login(withOOBCode oobCode: String, mfaToken: String, bindingCode: String?) -> Request<Credentials, AuthenticationError> {
let url = URL(string: "oauth/token", relativeTo: self.url)!
var payload: [String: Any] = [
"oob_code": oobCode,
"mfa_token": mfaToken,
"grant_type": "http://auth0.com/oauth/grant-type/mfa-oob",
"client_id": self.clientId
]
if let bindingCode = bindingCode {
payload["binding_code"] = bindingCode
}
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func login(withRecoveryCode recoveryCode: String, mfaToken: String) -> Request<Credentials, AuthenticationError> {
let url = URL(string: "oauth/token", relativeTo: self.url)!
let payload: [String: Any] = [
"recovery_code": recoveryCode,
"mfa_token": mfaToken,
"grant_type": "http://auth0.com/oauth/grant-type/mfa-recovery-code",
"client_id": self.clientId
]
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func multifactorChallenge(mfaToken: String, types: [String]?, authenticatorId: String?) -> Request<Challenge, AuthenticationError> {
let url = URL(string: "mfa/challenge", relativeTo: self.url)!
var payload: [String: String] = [
"mfa_token": mfaToken,
"client_id": self.clientId
]
if let types = types {
payload["challenge_type"] = types.joined(separator: " ")
}
if let authenticatorId = authenticatorId {
payload["authenticator_id"] = authenticatorId
}
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func login(appleAuthorizationCode authorizationCode: String, fullName: PersonNameComponents?, profile: [String: Any]?, audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
var parameters: [String: Any] = [:]
var profile: [String: Any] = profile ?? [:]
if let fullName = fullName {
let name = ["firstName": fullName.givenName, "lastName": fullName.familyName].compactMapValues { $0 }
if !name.isEmpty {
profile["name"] = name
}
}
if !profile.isEmpty, let jsonData = try? JSONSerialization.data(withJSONObject: profile, options: []),
let json = String(data: jsonData, encoding: .utf8) {
parameters["user_profile"] = json
}
return self.tokenExchange(subjectToken: authorizationCode,
subjectTokenType: "http://auth0.com/oauth/token-type/apple-authz-code",
scope: scope,
audience: audience,
parameters: parameters)
}
func login(facebookSessionAccessToken sessionAccessToken: String, profile: [String: Any], audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
var parameters: [String: String] = [:]
if let jsonData = try? JSONSerialization.data(withJSONObject: profile, options: []),
let json = String(data: jsonData, encoding: .utf8) {
parameters["user_profile"] = json
}
return self.tokenExchange(subjectToken: sessionAccessToken,
subjectTokenType: "http://auth0.com/oauth/token-type/facebook-info-session-access-token",
scope: scope,
audience: audience,
parameters: parameters)
}
func signup(email: String, username: String? = nil, password: String, connection: String, userMetadata: [String: Any]? = nil, rootAttributes: [String: Any]? = nil) -> Request<DatabaseUser, AuthenticationError> {
var payload: [String: Any] = [
"email": email,
"password": password,
"connection": connection,
"client_id": self.clientId
]
payload["username"] = username
payload["user_metadata"] = userMetadata
if let rootAttributes = rootAttributes {
rootAttributes.forEach { (key, value) in
if payload[key] == nil { payload[key] = value }
}
}
let signup = URL(string: "dbconnections/signup", relativeTo: self.url)!
return Request(session: session,
url: signup,
method: "POST",
handle: databaseUser,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func resetPassword(email: String, connection: String) -> Request<Void, AuthenticationError> {
let payload = [
"email": email,
"connection": connection,
"client_id": self.clientId
]
let resetPassword = URL(string: "dbconnections/change_password", relativeTo: self.url)!
return Request(session: session,
url: resetPassword,
method: "POST",
handle: noBody,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func startPasswordless(email: String, type: PasswordlessType, connection: String) -> Request<Void, AuthenticationError> {
let payload: [String: Any] = [
"email": email,
"connection": connection,
"send": type.rawValue,
"client_id": self.clientId
]
let start = URL(string: "passwordless/start", relativeTo: self.url)!
return Request(session: session,
url: start,
method: "POST",
handle: noBody,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func startPasswordless(phoneNumber: String, type: PasswordlessType, connection: String) -> Request<Void, AuthenticationError> {
let payload: [String: Any] = [
"phone_number": phoneNumber,
"connection": connection,
"send": type.rawValue,
"client_id": self.clientId
]
let start = URL(string: "passwordless/start", relativeTo: self.url)!
return Request(session: session,
url: start,
method: "POST",
handle: noBody,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func userInfo(withAccessToken accessToken: String) -> Request<UserInfo, AuthenticationError> {
let userInfo = URL(string: "userinfo", relativeTo: self.url)!
return Request(session: session,
url: userInfo,
method: "GET",
handle: authenticationObject,
headers: ["Authorization": "Bearer \(accessToken)"],
logger: self.logger,
telemetry: self.telemetry)
}
func codeExchange(withCode code: String, codeVerifier: String, redirectURI: String) -> Request<Credentials, AuthenticationError> {
return self.token().parameters([
"code": code,
"code_verifier": codeVerifier,
"redirect_uri": redirectURI,
"grant_type": "authorization_code"
])
}
func renew(withRefreshToken refreshToken: String, scope: String? = nil) -> Request<Credentials, AuthenticationError> {
var payload: [String: Any] = [
"refresh_token": refreshToken,
"grant_type": "refresh_token",
"client_id": self.clientId
]
payload["scope"] = scope
let oauthToken = URL(string: "oauth/token", relativeTo: self.url)!
return Request(session: session,
url: oauthToken,
method: "POST",
handle: codable,
parameters: payload, // Initializer does not enforce 'openid' scope
logger: self.logger,
telemetry: self.telemetry)
}
func revoke(refreshToken: String) -> Request<Void, AuthenticationError> {
let payload: [String: Any] = [
"token": refreshToken,
"client_id": self.clientId
]
let oauthToken = URL(string: "oauth/revoke", relativeTo: self.url)!
return Request(session: session,
url: oauthToken,
method: "POST",
handle: noBody,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func jwks() -> Request<JWKS, AuthenticationError> {
let jwks = URL(string: ".well-known/jwks.json", relativeTo: self.url)!
return Request(session: session,
url: jwks,
method: "GET",
handle: codable,
logger: self.logger,
telemetry: self.telemetry)
}
}
// MARK: - Private Methods
private extension Auth0Authentication {
func login(username: String, otp: String, realm: String, audience: String?, scope: String) -> Request<Credentials, AuthenticationError> {
let url = URL(string: "oauth/token", relativeTo: self.url)!
var payload: [String: Any] = [
"username": username,
"otp": otp,
"realm": realm,
"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp",
"client_id": self.clientId
]
payload["audience"] = audience
payload["scope"] = includeRequiredScope(in: scope)
return Request(session: session,
url: url,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func token() -> Request<Credentials, AuthenticationError> {
let payload: [String: Any] = [
"client_id": self.clientId
]
let token = URL(string: "oauth/token", relativeTo: self.url)!
return Request(session: session,
url: token,
method: "POST",
handle: codable,
parameters: payload,
logger: self.logger,
telemetry: self.telemetry)
}
func tokenExchange(subjectToken: String, subjectTokenType: String, scope: String, audience: String?, parameters: [String: Any] = [:]) -> Request<Credentials, AuthenticationError> {
var parameters: [String: Any] = parameters
parameters["grant_type"] = "urn:ietf:params:oauth:grant-type:token-exchange"
parameters["subject_token"] = subjectToken
parameters["subject_token_type"] = subjectTokenType
parameters["audience"] = audience
parameters["scope"] = scope
return self.token().parameters(parameters) // parameters() enforces 'openid' scope
}
}
|
mit
|
ffe019d99081e7702b7bd49542ad8dbd
| 40.579515 | 215 | 0.537015 | 4.961724 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift
|
11-GoldenInterview/11-GoldenInterview/Stack/MyQueue.swift
|
1
|
763
|
//
// MyQueue.swift
// 11-GoldenInterview
//
// Created by keso on 2017/5/7.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class MyQueue {
var stackNew:[Int] = []
var stackOld:[Int] = []
func push(value:Int) {
stackNew.append(value)
}
func peek() -> Int? {
shiftStacks()
let value:Int? = stackOld.last
if value != nil {
stackOld.removeLast()
}
return value
}
private func shiftStacks() {
if stackOld.count == 0 {
while stackNew.count > 0 {
let value:Int = stackNew.last!
stackNew.removeLast()
stackOld.append(value)
}
}
}
}
|
mit
|
ee9b786a8ad0ba974f14a84a747f6fa3
| 19 | 55 | 0.505263 | 3.917526 | false | false | false | false |
DholStudio/DSGradientProgressView
|
DSGradientProgressView/DSGradientProgressView.swift
|
1
|
5839
|
//
// DSGradientProgressView.swift
// DSGradientProgressView
//
// Created by Abhinav on 2/16/17.
// Copyright © 2017 Dhol Studio. All rights reserved.
//
import UIKit
@IBDesignable
public class DSGradientProgressView: UIView, CAAnimationDelegate {
@IBInspectable public var barColor: UIColor = UIColor(hue: (29.0/360.0), saturation: 1.0, brightness: 1.0, alpha: 1.0) {
didSet {
initialize()
}
}
private let serialIncrementQueue = DispatchQueue(label: "com.dholstudio.DSGradientProgressView.serialIncrementQueue")
private var numberOfOperations: Int = 0
override public class var layerClass: AnyClass {
get {
return CAGradientLayer.self
}
}
// https://theswiftdev.com/2015/08/05/swift-init-patterns/
override public init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.initialize()
}
override public func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
private func initialize() {
let layer = self.layer as! CAGradientLayer
// Use a horizontal gradient
layer.startPoint = CGPoint(x: 0.0, y: 0.5)
layer.endPoint = CGPoint(x: 1.0, y: 0.5)
var colors: [CGColor] = []
// http://stackoverflow.com/a/39126332/2607823
// http://bjmiller.me/post/137624096422/on-c-style-for-loops-removed-from-swift-3
// stride syntax changed from the blog's syntax
/*
// ==== Blue gradient with changing hues ====
for hue in stride(from: 190, through: 230, by: 2) {
let color = UIColor(hue: CGFloat(1.0 * Double(hue) / 360.0),
saturation: 1.0,
brightness: 1.0,
alpha: 1.0)
colors.append(color.cgColor)
}
// can be done with stride with -2 too. but just to explore another way..
for hue in (190...230).reversed() where hue % 2 == 0 {
let color = UIColor(hue: CGFloat(1.0 * Double(hue) / 360.0),
saturation: 1.0,
brightness: 1.0,
alpha: 1.0)
colors.append(color.cgColor)
}
*/
// ==== Constant hue with changing alpha ====
/*
for alpha in stride(from: 0, through: 40, by: 2) {
let color = UIColor(hue: CGFloat(1.0 * Double(hue) / 360.0),
saturation: 1.0,
brightness: 1.0,
alpha: CGFloat(1.0 * Double(alpha)/100.0))
barColor.withAlphaComponent(CGFloat(alpha))
colors.append(color.cgColor)
}
*/
// === constant color from storyboard or default with changing alpha ===
for alpha in stride(from: 0, through: 40, by: 2) {
let color = barColor.withAlphaComponent(CGFloat(Double(alpha)/100.0))
colors.append(color.cgColor)
}
for alpha in stride(from: 40, through: 90, by: 10) {
let color = barColor.withAlphaComponent(CGFloat(Double(alpha)/100.0))
colors.append(color.cgColor)
}
for alpha in stride(from: 90, through: 100, by: 10) {
let color = barColor.withAlphaComponent(CGFloat(Double(alpha)/100.0))
colors.append(color.cgColor)
colors.append(color.cgColor) // adding twice
}
for alpha in stride(from: 100, through: 0, by: -20) {
let color = barColor.withAlphaComponent(CGFloat(Double(alpha)/100.0))
colors.append(color.cgColor)
}
layer.colors = colors
}
private func performAnimation() {
// Move the last color in the array to the front
// shifting all the other colors.
let layer = self.layer as! CAGradientLayer
guard let color = layer.colors?.popLast() else {
print("FATAL ERR: GradientProgressView : Layer should contain colors!")
return
}
layer.colors?.insert(color, at: 0)
let shiftedColors = layer.colors!
let animation = CABasicAnimation(keyPath: "colors")
animation.toValue = shiftedColors
animation.duration = 0.03
animation.isRemovedOnCompletion = true
animation.fillMode = CAMediaTimingFillMode.forwards
animation.delegate = self
layer.add(animation, forKey: "animateGradient")
}
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
// TODO: Make reads on serial queue too?
if flag && numberOfOperations > 0 {
performAnimation()
}
else {
self.isHidden = true
}
}
public func wait() {
serialIncrementQueue.sync {
numberOfOperations += 1
}
self.isHidden = false
if numberOfOperations == 1 { // rest will be called from animationDidStop
performAnimation()
}
}
public func signal() {
if numberOfOperations == 0 {
return
}
serialIncrementQueue.sync {
numberOfOperations -= 1
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
apache-2.0
|
f71d7fdd2de31298ba40fea2ffd760d4
| 27.617647 | 124 | 0.541281 | 4.700483 | false | false | false | false |
eduresende/ios-nd-swift-syntax-swift-3
|
Lesson3/L3_Exercises.playground/Contents.swift
|
1
|
3163
|
//: # Lesson 3 Exercises - Collections
import UIKit
//: ## Array initialization
//: ### Exercise 1
//: 1a) Initialize the array, cuteAnimals. It should be of type CuddlyCreature. Type your answer below.
//: 1b) Initialize an array of 5 bools using array literal syntax.
//: ## Array operations: count, insert, append, remove, retrieveWithSubscript
//: ### Exercise 2
//: Print out the number of spaniels in the array below.
var spaniels = ["American Cocker", "Cavalier King Charles", "English Springer", "French", "Irish Water","Papillon", "Picardy","Russian", "French", "Welsh Springer"]
//: ### Exercise 3
//: Insert "indigo" into the array below so that its index is after "blue" and before "violet".
var colors = ["red", "orange", "yellow", "green", "blue", "violet"]
//: ### Exercise 4
//: Insert "English Cocker" into the spaniels array so that its index is before "English Springer".
//: ### Exercise 5
//: Append "Barcelona" to the end of the olympicHosts array.
var olympicHosts = ["London", "Beijing","Athens", "Sydney", "Atlanta"]
//: ### Exercise 6
//: Remove "Lyla" and "Daniel" from the waitingList array and add them to the end of the admitted array.
var admitted = ["Jennifer", "Vijay", "James"]
var waitingList = ["Lyla", "Daniel", "Isabel", "Eric"]
//: ### Exercise 7
//: Using subscript syntax, print out the 2nd and 3rd names from the admitted array.
//: ## Dictionary initialization
//: ### Exercise 8
//: a) Initialize an empty dictionary which holds Strings as keys and Bools as values.
//: b) Initialize a dictionary using array literal syntax. The keys should be the Strings: "Anchovies", "Coconut", "Cilantro", "Liver" and each value should be a Bool representing whether you like the food or not.
//: ## Dictionary operations: count, insert, remove, update, retrieve with subscript
//: ### Exercise 9
//: Insert an entry for George H.W. Bush to the dictionary below.
var presidentialPetsDict = ["Barack Obama":"Bo", "Bill Clinton": "Socks", "George Bush": "Miss Beazley", "Ronald Reagan": "Lucky"]
//desired output
// ["Barack Obama":"Bo", "George Bush": "Miss Beazley","Bill Clinton": "Socks", "George H. W. Bush": "Millie", "Ronald Reagan": "Lucky"]
//: ### Exercise 10
//: Remove the entry for "George Bush" and replace it with an entry for "George W. Bush".
//: ### Exercise 11
//: We've initialized a new dictionary of presidentialDogs with the entries from presidentialPets. Update the entry for Bill Clinton by replacing "Socks" the cat with "Buddy" the dog.
var presidentialDogs = presidentialPetsDict
//: ### Exercise 12
//: Use subscript syntax to fill in the println statement below and produce the following string: "Michele Obama walks Bo every morning." You'll need to retrieve a value from the presidentialDogs dictionary and unwrap it using if let.
//print("Michele Obama walks \() every morning.")
//: ### Exercise 13
// How many studio albums did Led Zeppelin release?
var studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]
|
mit
|
a77bb466342b68b5b5715bab29aef1df
| 52.610169 | 234 | 0.706608 | 3.545964 | false | false | false | false |
panjinqiang11/Swift-WeiBo
|
WeiBo/WeiBo/Class/View/Compose/PJComposeToolBar.swift
|
1
|
2894
|
//
// PJComposeToolBar.swift
// WeiBo
//
// Created by 潘金强 on 16/7/19.
// Copyright © 2016年 潘金强. All rights reserved.
//
import UIKit
enum composeToolBarButtonType :Int{
case Picture = 0
case Mention = 1
case Trend = 2
case Emotion = 3
case Add = 4
}
class PJComposeToolBar: UIStackView {
var emotoinButton :UIButton?
var selectClosure :((type: composeToolBarButtonType) -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
//设置布局
axis = .Horizontal
distribution = .FillEqually
backgroundColor = UIColor.redColor()
addButton("compose_toolbar_picture", type: .Picture)
addButton("compose_mentionbutton_background", type: .Mention)
addButton("compose_trendbutton_background", type: .Trend)
emotoinButton = addButton("compose_emoticonbutton_background", type: .Emotion)
addButton("compose_add_background", type: .Add)
}
private func addButton(imageName: String,type: composeToolBarButtonType) -> UIButton{
let button = UIButton()
button.tag = type.rawValue
button.addTarget(self, action: "clickButton:", forControlEvents: .TouchUpInside)
// 设置图片
button.setImage(UIImage(named: imageName), forState: .Normal)
button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: .Highlighted)
// 设置背景图片
button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: .Normal)
button.adjustsImageWhenHighlighted = false
// addSubview(button)
addArrangedSubview(button)
return button
}
@objc private func clickButton(button: UIButton){
let type = composeToolBarButtonType(rawValue: button.tag)!
selectClosure?(type: type)
}
func showEnmotion(isEmotion: Bool){
if isEmotion {
emotoinButton?.setImage(UIImage(named: "compose_keyboardbutton_background"), forState: .Normal)
emotoinButton?.setImage(UIImage(named: "compose_keyboardbutton_background_highlighted"), forState: .Highlighted)
} else {
emotoinButton?.setImage(UIImage(named: "compose_emoticonbutton_background"), forState: .Normal)
emotoinButton?.setImage(UIImage(named: "compose_emoticonbutton_background_highlighted"), forState: .Highlighted)
}
}
}
|
mit
|
cb42a6088d2d6226274d6ccd9dde337f
| 23.791304 | 124 | 0.589618 | 4.856899 | false | false | false | false |
kousun12/RxSwift
|
RxCocoa/Common/RxCocoa.swift
|
5
|
3118
|
//
// RxCocoa.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if os(iOS)
import UIKit
#endif
public enum RxCocoaError : Int {
case Unknown = 0
case NetworkError = 1
case InvalidOperation = 2
case KeyPathInvalid = 3
}
/**
Error domain for internal RxCocoa errors.
*/
public let RxCocoaErrorDomain = "RxCocoaError"
/**
`userInfo` key for `NSURLResponse` object when `RxCocoaError.NetworkError` happens.
*/
public let RxCocoaErrorHTTPResponseKey = "RxCocoaErrorHTTPResponseKey"
/**
`userInfo` key for `NSData` object when `RxCocoaError.NetworkError` happens.
*/
public let RxCocoaErrorHTTPResponseDataKey = "RxCocoaErrorHTTPResponseDataKey"
func rxError(errorCode: RxCocoaError, _ message: String) -> NSError {
return NSError(domain: RxCocoaErrorDomain, code: errorCode.rawValue, userInfo: [NSLocalizedDescriptionKey: message])
}
#if !RELEASE
public func _rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError {
return rxError(errorCode, message: message, userInfo: userInfo)
}
#endif
func rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError {
var resultInfo: [NSObject: AnyObject] = [:]
resultInfo[NSLocalizedDescriptionKey] = message
for k in userInfo.allKeys {
resultInfo[k as! NSObject] = userInfo[k as! NSCopying]
}
return NSError(domain: RxCocoaErrorDomain, code: Int(errorCode.rawValue), userInfo: resultInfo)
}
func bindingErrorToInterface(error: ErrorType) {
let error = "Binding error to UI: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
}
func rxAbstractMethodWithMessage<T>(message: String) -> T {
rxFatalError(message)
}
func rxAbstractMethod<T>() -> T {
rxFatalError("Abstract method")
}
// workaround for Swift compiler bug, cheers compiler team :)
func castOptionalOrFatalError<T>(value: AnyObject?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrFatalError<T>(value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError(message)
}
return result
}
func castOrFatalError<T>(value: AnyObject!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from \(value) to \(T.self)")
}
return result
}
// Error messages {
let dataSourceNotSet = "DataSource not set"
let delegateNotSet = "Delegate not set"
// }
#if !RX_NO_MODULE
@noreturn func rxFatalError(lastMessage: String) {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
extension NSObject {
func rx_synchronized<T>(@noescape action: () -> T) -> T {
objc_sync_enter(self)
let result = action()
objc_sync_exit(self)
return result
}
}
#endif
|
mit
|
e3173a44e89be99d0478f10bb8624626
| 23.746032 | 120 | 0.6966 | 4.007712 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
Pod/Classes/Sources.Api/NetworkInfoBridge.swift
|
1
|
3521
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Managing the Network information operations
Auto-generated implementation of INetworkInfo specification.
*/
public class NetworkInfoBridge : BaseCommunicationBridge, INetworkInfo, APIBridge {
/**
API Delegate.
*/
private var delegate : INetworkInfo? = nil
/**
Constructor with delegate.
@param delegate The delegate implementing platform specific functions.
*/
public init(delegate : INetworkInfo?) {
self.delegate = delegate
}
/**
Get the delegate implementation.
@return INetworkInfo delegate that manages platform specific functions..
*/
public final func getDelegate() -> INetworkInfo? {
return self.delegate
}
/**
Set the delegate implementation.
@param delegate The delegate implementing platform specific functions.
*/
public final func setDelegate(delegate : INetworkInfo) {
self.delegate = delegate;
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public override func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
default:
// 404 - response null.
responseCode = 404
responseMessage = "NetworkInfoBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
apache-2.0
|
00abd77ed0cc0f61f360fa07d8997a64
| 35.278351 | 190 | 0.628588 | 5.159824 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox
|
nRF Toolbox/Profiles/UART/CollectionViewCells/ImageCollectionViewCell.swift
|
1
|
2232
|
/*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
let bgView = UIView()
let selectedBGView = UIView()
if #available(iOS 13.0, *) {
bgView.backgroundColor = .systemGray5
selectedBGView.backgroundColor = .systemGray2
} else {
bgView.backgroundColor = .nordicGrey5
selectedBGView.backgroundColor = .nordicGrey4
}
selectedBackgroundView = selectedBGView
backgroundView = bgView
imageView.tintColor = .nordicBlue
}
}
|
bsd-3-clause
|
1b7b813cca8ffdaa708281bb5f93def4
| 38.857143 | 84 | 0.733871 | 4.971047 | false | false | false | false |
dshamany/CIToolbox
|
CIToolbox/FormStatus.swift
|
1
|
10267
|
//
// FormStatus.swift
// CIToolbox
//
// Created by Daniel Shamany on 6/21/17.
// Copyright © 2017 Daniel Shamany. All rights reserved.
//
import UIKit
import CoreLocation
class FormStatus: UIViewController, CLLocationManagerDelegate {
//MARK: Outlets
//-------------------------------------------------------------------------------
@IBOutlet weak var addressInfo: UILabel!
@IBOutlet weak var fullAddress: UITextField!
@IBOutlet weak var updateButton: UIButton!
@IBOutlet weak var leadButton: UIButton!
@IBOutlet weak var noAnswerButton: UIButton!
@IBOutlet weak var noInteresetButton: UIButton!
@IBOutlet weak var dqButton: UIButton!
@IBOutlet weak var notOwnerButton: UIButton!
@IBOutlet weak var renterButton: UIButton!
@IBOutlet weak var solarButton: UIButton!
@IBOutlet weak var comebackButton: UIButton!
@IBOutlet weak var addressSubView: UIVisualEffectView!
@IBOutlet weak var statusSubView: UIVisualEffectView!
var status = ""
func setInterface(){
addressSubView.layer.cornerRadius = 10
addressSubView.layer.masksToBounds = true
statusSubView.layer.cornerRadius = 10
statusSubView.layer.masksToBounds = true
leadButton.layer.cornerRadius = 10
leadButton.layer.masksToBounds = true
noAnswerButton.layer.cornerRadius = 10
noAnswerButton.layer.masksToBounds = true
noInteresetButton.layer.cornerRadius = 10
noInteresetButton.layer.masksToBounds = true
dqButton.layer.cornerRadius = 10
dqButton.layer.masksToBounds = true
notOwnerButton.layer.cornerRadius = 10
notOwnerButton.layer.masksToBounds = true
renterButton.layer.cornerRadius = 10
renterButton.layer.masksToBounds = true
solarButton.layer.cornerRadius = 10
solarButton.layer.masksToBounds = true
comebackButton.layer.cornerRadius = 10
comebackButton.layer.masksToBounds = true
}
override func viewDidLoad() {
super.viewDidLoad()
setInterface()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
//-------------------------------------------------------------------------------
//MARK: Support Functions
// Set locationManager here to make it accessable to all functions in this class
let locationManager = CLLocationManager()
func clearView(){
leadButton.alpha = 1
noAnswerButton.alpha = 1
noInteresetButton.alpha = 1
dqButton.alpha = 1
notOwnerButton.alpha = 1
renterButton.alpha = 1
solarButton.alpha = 1
comebackButton.alpha = 1
status = ""
fullAddress.text?.removeAll()
}
//-------------------------------------------------------------------------------
//MARK: Retrieve Address Information
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
CLGeocoder().reverseGeocodeLocation(location) { (placemark, error) in
if (error != nil){
print("Error: \(String(describing: error?.localizedDescription))")
self.addressInfo.textColor = UIColor.red
self.addressInfo.text = "No Address available at this point"
} else {
if let place = placemark?[0] {
if (place.subThoroughfare == nil || place.thoroughfare == nil || place.locality == nil || place.administrativeArea == nil || place.postalCode == nil){
self.addressInfo.textColor = UIColor.red
self.addressInfo.text = "Error retrieving address"
} else {
self.fullAddress.text = "\(place.subThoroughfare!) \(place.thoroughfare!), \(place.locality!), \(place.administrativeArea!) \(place.postalCode!)"
}
}
}
}
self.locationManager.stopUpdatingLocation()
self.addressInfo.text = "Updated"
}
@IBAction func updateAddress(_ sender: Any) {
if Reachability.isConnectedToNetwork() == true {
self.addressInfo.textColor = UIColor.white
self.addressInfo.text = "Updating Address"
locationManager.startUpdatingLocation()
} else {
self.addressInfo.textColor = UIColor.red
self.addressInfo.text = "No Internet Connection"
locationManager.stopUpdatingLocation()
}
}
@IBAction func tapAnywhere(_ sender: Any) { //dismiss keyboard from anywhere
self.view.endEditing(true)
leadButton.alpha = 1
noAnswerButton.alpha = 1
noInteresetButton.alpha = 1
dqButton.alpha = 1
notOwnerButton.alpha = 1
renterButton.alpha = 1
solarButton.alpha = 1
comebackButton.alpha = 1
status = " "
}
func addressComplete() -> Bool{
if (fullAddress.text != ""){
return true
}
return false
}
@IBAction func statusLead(_ sender: Any) {
status = "Lead"
self.view.endEditing(true)
leadButton.alpha = 1
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 0.5
dqButton.alpha = 0.5
notOwnerButton.alpha = 0.5
renterButton.alpha = 0.5
solarButton.alpha = 0.5
comebackButton.alpha = 0.5
}
@IBAction func statusNoAnswer(_ sender: Any) {
status = "No Answer"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 1
noInteresetButton.alpha = 0.5
dqButton.alpha = 0.5
notOwnerButton.alpha = 0.5
renterButton.alpha = 0.5
solarButton.alpha = 0.5
comebackButton.alpha = 0.5
}
@IBAction func statusNoIntereset(_ sender: Any) {
status = "No Interest"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 1
dqButton.alpha = 0.5
notOwnerButton.alpha = 0.5
renterButton.alpha = 0.5
solarButton.alpha = 0.5
comebackButton.alpha = 0.5
}
@IBAction func statusDQ(_ sender: Any) {
status = "Disqualified"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 0.5
dqButton.alpha = 1
notOwnerButton.alpha = 0.5
renterButton.alpha = 0.5
solarButton.alpha = 0.5
comebackButton.alpha = 0.5
}
@IBAction func statusnotOwner(_ sender: Any) {
status = "Not Owner"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 0.5
dqButton.alpha = 0.5
notOwnerButton.alpha = 1
renterButton.alpha = 0.5
solarButton.alpha = 0.5
comebackButton.alpha = 0.5
}
@IBAction func statusRenter(_ sender: Any) {
status = "Renter"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 0.5
dqButton.alpha = 0.5
notOwnerButton.alpha = 0.5
renterButton.alpha = 1
solarButton.alpha = 0.5
comebackButton.alpha = 0.5
}
@IBAction func statusSolar(_ sender: Any) {
status = "Solar"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 0.5
dqButton.alpha = 0.5
notOwnerButton.alpha = 0.5
renterButton.alpha = 0.5
solarButton.alpha = 1
comebackButton.alpha = 0.5
}
@IBAction func statusComeback(_ sender: Any) {
status = "Comeback"
self.view.endEditing(true)
leadButton.alpha = 0.5
noAnswerButton.alpha = 0.5
noInteresetButton.alpha = 0.5
dqButton.alpha = 0.5
notOwnerButton.alpha = 0.5
renterButton.alpha = 0.5
solarButton.alpha = 0.5
comebackButton.alpha = 1
}
@IBAction func goToNext(_ sender: Any) {
//Put the data together
let HO = Lead()
//test for empty values before forwarding data
if (status == "" || !addressComplete()){
alertFunction(title: "Oops!", msg: "Update address and select status.")
} else {
//add data
HO.Representative = Global.currentUser.UserName
HO.Status = status
HO.Full_Address = "\(fullAddress.text!)"
}
//Check the path based on status
if (addressComplete() && status == "Lead"){
performSegue(withIdentifier: "toContactForm", sender: HO)
} else if (addressComplete() && status != "") {
performSegue(withIdentifier: "directlyToNotesForm", sender: HO)
}
clearView()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if (segue.identifier == "toContactForm" && status == "Lead") {
if let destination = segue.destination as? FormContact {
destination.fromPrevious = sender as! Lead
}
} else if (segue.identifier == "directlyToNotesForm" && (status != "Lead")) {
if let destination = segue.destination as? FormNotes {
destination.fromPrevious = sender as! Lead
}
}
}
@IBAction func exitView(_ sender: Any){
self.dismiss(animated: true, completion: nil)
}
// --------------------------------------------------------------------------------
//MARK: TEXTFIELD RETURN-KEY
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch (textField){
default:
self.view.endEditing(true)
}
return true
}
}
|
gpl-3.0
|
9c3e2da3db503f51f1d767e01ec78fc3
| 32.331169 | 170 | 0.572862 | 4.613933 | false | false | false | false |
apple/swift
|
test/SILGen/casts.swift
|
2
|
3581
|
// RUN: %target-swift-emit-silgen -module-name casts %s | %FileCheck %s
class B { }
class D : B { }
// CHECK-LABEL: sil hidden [ossa] @$s5casts6upcast{{[_0-9a-zA-Z]*}}F
func upcast(d: D) -> B {
// CHECK: {{%.*}} = upcast
return d
}
// CHECK-LABEL: sil hidden [ossa] @$s5casts8downcast{{[_0-9a-zA-Z]*}}F
func downcast(b: B) -> D {
// CHECK: {{%.*}} = unconditional_checked_cast
return b as! D
}
// CHECK-LABEL: sil hidden [ossa] @$s5casts3isa{{[_0-9a-zA-Z]*}}F
func isa(b: B) -> Bool {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $B):
// CHECK: [[COPIED_BORROWED_ARG:%.*]] = copy_value [[ARG]]
// CHECK: checked_cast_br [[COPIED_BORROWED_ARG]] : $B to D, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
//
// CHECK: [[YES]]([[CASTED_VALUE:%.*]] : @owned $D):
// CHECK: integer_literal {{.*}} -1
// CHECK: destroy_value [[CASTED_VALUE]]
//
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $B):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: integer_literal {{.*}} 0
return b is D
}
// CHECK-LABEL: sil hidden [ossa] @$s5casts16upcast_archetype{{[_0-9a-zA-Z]*}}F
func upcast_archetype<T : B>(t: T) -> B {
// CHECK: {{%.*}} = upcast
return t
}
// CHECK-LABEL: sil hidden [ossa] @$s5casts25upcast_archetype_metatype{{[_0-9a-zA-Z]*}}F
func upcast_archetype_metatype<T : B>(t: T.Type) -> B.Type {
// CHECK: {{%.*}} = upcast
return t
}
// CHECK-LABEL: sil hidden [ossa] @$s5casts18downcast_archetype{{[_0-9a-zA-Z]*}}F
func downcast_archetype<T : B>(b: B) -> T {
// CHECK: {{%.*}} = unconditional_checked_cast
return b as! T
}
// This is making sure that we do not have the default propagating behavior in
// the address case.
//
// CHECK-LABEL: sil hidden [ossa] @$s5casts12is_archetype{{[_0-9a-zA-Z]*}}F
func is_archetype<T : B>(b: B, _: T) -> Bool {
// CHECK: bb0([[ARG1:%.*]] : @guaranteed $B, [[ARG2:%.*]] : @guaranteed $T):
// CHECK: checked_cast_br {{%.*}}, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
// CHECK: [[YES]]([[CASTED_ARG:%.*]] : @owned $T):
// CHECK: integer_literal {{.*}} -1
// CHECK: destroy_value [[CASTED_ARG]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $B):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: integer_literal {{.*}} 0
return b is T
}
// CHECK: } // end sil function '$s5casts12is_archetype{{[_0-9a-zA-Z]*}}F'
// CHECK: sil hidden [ossa] @$s5casts20downcast_conditional{{[_0-9a-zA-Z]*}}F
// CHECK: checked_cast_br {{%.*}} : $B to D
// CHECK: bb{{[0-9]+}}({{.*}} : $Optional<D>)
func downcast_conditional(b: B) -> D? {
return b as? D
}
protocol P {}
struct S : P {}
// CHECK: sil hidden [ossa] @$s5casts32downcast_existential_conditional{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[IN:%.*]] : $*any P):
// CHECK: [[COPY:%.*]] = alloc_stack $any P
// CHECK: copy_addr [[IN]] to [init] [[COPY]]
// CHECK: [[TMP:%.*]] = alloc_stack $S
// CHECK: checked_cast_addr_br take_always any P in [[COPY]] : $*any P to S in [[TMP]] : $*S, bb1, bb2
// Success block.
// CHECK: bb1:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*S
// CHECK: [[T1:%.*]] = enum $Optional<S>, #Optional.some!enumelt, [[T0]] : $S
// CHECK: dealloc_stack [[TMP]]
// CHECK: br bb3([[T1]] : $Optional<S>)
// Failure block.
// CHECK: bb2:
// CHECK: [[T0:%.*]] = enum $Optional<S>, #Optional.none!enumelt
// CHECK: dealloc_stack [[TMP]]
// CHECK: br bb3([[T0]] : $Optional<S>)
// Continuation block.
// CHECK: bb3([[RESULT:%.*]] : $Optional<S>):
// CHECK: dealloc_stack [[COPY]]
// CHECK: return [[RESULT]]
func downcast_existential_conditional(p: P) -> S? {
return p as? S
}
|
apache-2.0
|
bdf276f3ba1c16b17099e89aa7e97b33
| 33.76699 | 104 | 0.56353 | 2.873997 | false | false | false | false |
abunur/quran-ios
|
Quran/SearchViewController.swift
|
1
|
6109
|
//
// SearchViewController.swift
// Quran
//
// Created by Mohamed Afifi on 4/19/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
class SearchViewController: BaseViewController, UISearchResultsUpdating, UISearchBarDelegate, SearchView {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .portrait
} else {
return super.supportedInterfaceOrientations
}
}
var router: SearchRouter? // DESIGN: Shouldn't be saved here
weak var delegate: SearchViewDelegate?
var searchController: UISearchController?
lazy var searchResults: SearchResultsViewController = {
let controller = SearchResultsViewController()
controller.dataSource.onAutocompletionSelected = { [weak self] index in
self?.searchController?.searchBar.resignFirstResponder()
self?.delegate?.onSelected(autocompletionAt: index)
}
controller.dataSource.onResultSelected = { [weak self] index in
self?.searchController?.searchBar.resignFirstResponder() // defensive
self?.delegate?.onSelected(searchResultAt: index)
}
return controller
}()
override var screen: Analytics.Screen { return .search }
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBOutlet weak var recents: UIStackView!
@IBOutlet weak var recentsTitle: UILabel!
@IBOutlet weak var popular: UIStackView!
@IBOutlet weak var popularTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.secondaryColor()
recentsTitle.text = NSLocalizedString("searchRecentsTitle", comment: "")
popularTitle.text = NSLocalizedString("searchPopularTitle", comment: "")
searchController = SearchControllerWithNoCancelButton(searchResultsController: searchResults)
searchController?.searchResultsUpdater = self
searchController?.searchBar.delegate = self
let searchBackgroundImage = #colorLiteral(red: 0.0716814159, green: 0.2847787611, blue: 0.3, alpha: 1).image(size: CGSize(width: 28, height: 28))?.rounded(by: 4)
searchController?.searchBar.setSearchFieldBackgroundImage(searchBackgroundImage, for: .normal)
searchController?.searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 8, vertical: 0)
searchController?.searchBar.showsCancelButton = false
searchController?.dimsBackgroundDuringPresentation = true
searchController?.hidesNavigationBarDuringPresentation = false
definesPresentationContext = true
navigationItem.titleView = searchController?.searchBar
delegate?.onViewLoaded()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = searchResults.tableView?.indexPathForSelectedRow {
searchResults.tableView?.deselectRow(at: indexPath, animated: animated)
}
}
func updateSearchResults(for searchController: UISearchController) {
delegate?.onSearchTextUpdated(to: searchController.searchBar.text ?? "", isActive: searchController.isActive)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
delegate?.onSearchButtonTapped()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchResults.switchToAutocompletes()
}
// MARK: - SearchView
func show(autocompletions: [NSAttributedString]) {
searchResults.setAutocompletes(autocompletions)
if searchController?.searchBar.isFirstResponder ?? false {
searchResults.switchToAutocompletes()
}
}
func show(results: [SearchResultUI], title: String?) {
searchResults.show(results: results, title: title)
}
func show(recents: [String], popular: [String]) {
updateList(stack: self.recents, title: recentsTitle, values: recents, tapSelector: #selector(onRecentOrPopularTapped(button:)))
updateList(stack: self.popular, title: popularTitle, values: popular, tapSelector: #selector(onRecentOrPopularTapped(button:)))
}
func showLoading() {
searchResults.showLoading()
}
func showError(_ error: Error) {
showErrorAlert(error: error)
}
func showNoResult(_ message: String) {
searchResults.showNoResult(message)
}
func updateSearchBarText(to text: String) {
searchController?.searchBar.text = text
}
func setSearchBarActive(_ isActive: Bool) {
searchController?.isActive = isActive
}
func onRecentOrPopularTapped(button: UIButton) {
delegate?.onSearchTermSelected(button.title(for: .normal) ?? "")
}
private func updateList(stack: UIStackView, title: UIView, values: [String], tapSelector: Selector) {
title.isHidden = values.isEmpty
for view in stack.arrangedSubviews {
stack.removeArrangedSubview(view)
view.removeFromSuperview()
}
stack.addArrangedSubview(title)
for value in values {
let button = UIButton(type: .system)
button.addHeightConstraint(44)
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
button.setTitle(value, for: .normal)
button.addTarget(self, action: tapSelector, for: .touchUpInside)
stack.addArrangedSubview(button)
}
}
}
|
gpl-3.0
|
07d5f65a6dd2f6a51c7db7b6a4e392b6
| 35.580838 | 169 | 0.696022 | 5.203578 | false | false | false | false |
nathawes/swift
|
benchmark/single-source/ReduceInto.swift
|
12
|
3279
|
//===--- ReduceInto.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let ReduceInto = [
BenchmarkInfo(name: "FilterEvenUsingReduce", runFunction: run_FilterEvenUsingReduce, tags: [.validation, .api], legacyFactor: 10),
BenchmarkInfo(name: "FilterEvenUsingReduceInto", runFunction: run_FilterEvenUsingReduceInto, tags: [.validation, .api]),
BenchmarkInfo(name: "FrequenciesUsingReduce", runFunction: run_FrequenciesUsingReduce, tags: [.validation, .api], legacyFactor: 10),
BenchmarkInfo(name: "FrequenciesUsingReduceInto", runFunction: run_FrequenciesUsingReduceInto, tags: [.validation, .api], legacyFactor: 10),
BenchmarkInfo(name: "SumUsingReduce", runFunction: run_SumUsingReduce, tags: [.validation, .api]),
BenchmarkInfo(name: "SumUsingReduceInto", runFunction: run_SumUsingReduceInto, tags: [.validation, .api]),
]
// Sum
@inline(never)
public func run_SumUsingReduce(_ N: Int) {
let numbers = [Int](0..<1000)
var c = 0
for _ in 1...N*1000 {
c = c &+ numbers.reduce(0) { (acc: Int, num: Int) -> Int in
acc &+ num
}
}
CheckResults(c != 0)
}
@inline(never)
public func run_SumUsingReduceInto(_ N: Int) {
let numbers = [Int](0..<1000)
var c = 0
for _ in 1...N*1000 {
c = c &+ numbers.reduce(into: 0) { (acc: inout Int, num: Int) in
acc = acc &+ num
}
}
CheckResults(c != 0)
}
// Filter
@inline(never)
public func run_FilterEvenUsingReduce(_ N: Int) {
let numbers = [Int](0..<100)
var c = 0
for _ in 1...N*10 {
let a = numbers.reduce([]) { (acc: [Int], num: Int) -> [Int] in
var a = acc
if num % 2 == 0 {
a.append(num)
}
return a
}
c = c &+ a.count
}
CheckResults(c != 0)
}
@inline(never)
public func run_FilterEvenUsingReduceInto(_ N: Int) {
let numbers = [Int](0..<100)
var c = 0
for _ in 1...N*100 {
let a = numbers.reduce(into: []) { (acc: inout [Int], num: Int) in
if num % 2 == 0 {
acc.append(num)
}
}
c = c &+ a.count
}
CheckResults(c != 0)
}
// Frequencies
@inline(never)
public func run_FrequenciesUsingReduce(_ N: Int) {
let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789"
var c = 0
for _ in 1...N*10 {
let a = s.reduce([:]) {
(acc: [Character: Int], c: Character) -> [Character: Int] in
var d = acc
d[c, default: 0] += 1
return d
}
c = c &+ a.count
}
CheckResults(c != 0)
}
@inline(never)
public func run_FrequenciesUsingReduceInto(_ N: Int) {
let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789"
var c = 0
for _ in 1...N*10 {
let a = s.reduce(into: [:]) {
(acc: inout [Character: Int], c: Character) in
acc[c, default: 0] += 1
}
c = c &+ a.count
}
CheckResults(c != 0)
}
|
apache-2.0
|
96db6adb8663f5fa16fb19af41609f1f
| 26.325 | 142 | 0.606587 | 3.552546 | false | false | false | false |
bradvandyk/OpenSim
|
OpenSim/Device.swift
|
1
|
2262
|
//
// Device.swift
// SimPholders
//
// Created by Luo Sheng on 11/9/15.
// Copyright © 2015 Luo Sheng. All rights reserved.
//
import Foundation
struct Device {
enum State: String {
case Shutdown = "Shutdown"
case Unknown = "Unknown"
case Booted = "Booted"
}
let UDID: String
let type: String
let name: String
let runtime: Runtime
let state: State
let applications: [Application]
init(UDID: String, type: String, name: String, runtime: String, state: State) {
self.UDID = UDID
self.type = type
self.name = name
self.runtime = Runtime(name: runtime)
self.state = state
let applicationPath = URLHelper.deviceURLForUDID(self.UDID).URLByAppendingPathComponent("data/Containers/Bundle/Application")
do {
let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(applicationPath, includingPropertiesForKeys: nil, options: [.SkipsSubdirectoryDescendants, .SkipsHiddenFiles])
self.applications = contents.map { Application(URL: $0) }.filter { $0 != nil }.map { $0! }
} catch {
self.applications = []
}
}
var fullName:String {
get {
return "\(self.name) (\(self.runtime))"
}
}
func containerURLForApplication(application: Application) -> NSURL? {
let URL = URLHelper.containersURLForUDID(UDID)
do {
let directories = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(URL, includingPropertiesForKeys: nil, options: .SkipsSubdirectoryDescendants)
if let matchingURL = directories.filter({ dir -> Bool in
if let contents = NSDictionary(contentsOfURL: dir.URLByAppendingPathComponent(".com.apple.mobile_container_manager.metadata.plist")),
identifier = contents["MCMMetadataIdentifier"] as? String
where identifier == application.bundleID {
return true
}
return false
}).first {
return matchingURL
} else {
return nil
}
} catch {
return nil
}
}
}
|
mit
|
c8b591d50e5c5412cfb9bab580ec315d
| 31.782609 | 197 | 0.593543 | 4.904555 | false | false | false | false |
dmitryrybakov/hubchatsample
|
hubchatTestapp/ViewModel/PostsViewModel.swift
|
1
|
2762
|
//
// PostsViewModel.swift
// hubchatTestapp
//
// Created by Dmitry on 24.03.17.
// Copyright © 2017 hubchat. All rights reserved.
//
import Foundation
import ReactiveSwift
import ReactiveCocoa
import Result
import Alamofire
public class PostsViewModel: PostsViewModelling {
fileprivate var postData: PostModel?
public var postText: String? {
return postData?.postText ?? ""
}
public var userName: String? {
return postData?.createdByUser?.userName ?? ""
}
public var upvotes: Float {
return postData?.upvotes ?? 0.0
}
public var avatarURL: String {
return postData?.createdByUser?.avatarURLString ?? ""
}
public var postImageURLs: [String]? {
return postData?.postImages?.map { $0.imageURL ?? "" } ?? []
}
fileprivate var forumNetworking: ForumNetworking
fileprivate var avatarImage: UIImage?
// Should be implemented in in View
// View might update its UI based on the data from the ModelView in this handler
public var dataDidChange: ((ForumViewModelling) -> ())?
required public init(forumNetworking: ForumNetworking) {
self.forumNetworking = forumNetworking
}
public init(postData: PostModel, forumNetworking: ForumNetworking) {
self.postData = postData
self.forumNetworking = forumNetworking
}
public func getAvatarImage(size:CGSize) -> SignalProducer<UIImage?, NetworkError> {
if let avatarImage = self.avatarImage {
return SignalProducer(value: avatarImage).observe(on: UIScheduler())
}
return forumNetworking.requestImage(imageURL: self.avatarURL, size:size)
}
public func getPostsInfo() -> SignalProducer<[PostsViewModelling]?, NetworkError> {
func toPostModel(_ post: PostModel) -> PostsViewModelling {
return PostsViewModel(postData: post, forumNetworking: self.forumNetworking) as PostsViewModelling
}
return SignalProducer { observer, disposable in
self.forumNetworking.updatePostsInfo(completionHandler: { (response: DataResponse<[PostModel]>) in
switch(response.result) {
case .success(let data):
let postsModel = data.map { toPostModel($0) }
observer.send(value: postsModel)
observer.sendCompleted()
break
case .failure(let error):
print("Updating failed with the error: \(error.localizedDescription)")
observer.send(error: NetworkError(error: error as NSError))
break
}
})
}
}
}
|
mit
|
216f3766a0708066f5da83bf2be600c8
| 32.26506 | 110 | 0.619703 | 5.038321 | false | false | false | false |
Chantalisima/Spirometry-app
|
EspiroGame/SpaceGameSceneClass.swift
|
1
|
4246
|
//
// SpaceGameSceneClass.swift
// EspiroGame
//
// Created by Chantal de Leste on 23/5/17.
// Copyright © 2017 Universidad de Sevilla. All rights reserved.
//
import SpriteKit
import AVFoundation
class SpaceGameSceneClass: SKScene, SKPhysicsContactDelegate{
private var space1: SpaceClass?
private var space2: SpaceClass?
private var space3: SpaceClass?
private var spikefloor1: SpikeClass?
private var spikefloor2: SpikeClass?
private var spikefloor3: SpikeClass?
private var spikeceilling1: SpikeClass?
private var spikeceilling2: SpikeClass?
private var spikeceilling3: SpikeClass?
private var gameplayer: GamePlayerClass?
var bombSoundEffect: AVAudioPlayer!
private var mainCamera: SKCameraNode?
override func didMove(to view: SKView) {
initializeGame()
}
override func update(_ currentTime: TimeInterval) {
manageCamera()
manageSpacesAndSpikes()
gameplayer?.move()
}
func exhalingAir(rpm: Int){
}
private func initializeGame(){
self.physicsWorld.contactDelegate = self
do{
let audioPath = Bundle.main.path(forResource: "boom", ofType: "wav")
try bombSoundEffect = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}catch{
//ERROR
}
mainCamera = childNode(withName: "MainCamera") as? SKCameraNode!
space1 = childNode(withName: "Space1") as? SpaceClass!
space2 = childNode(withName: "Space2") as? SpaceClass!
space3 = childNode(withName: "Space3") as? SpaceClass!
spikefloor1 = childNode(withName: "SpikeFloor1") as? SpikeClass!
spikefloor2 = childNode(withName: "SpikeFloor2") as? SpikeClass!
spikefloor3 = childNode(withName: "SpikeFloor3") as? SpikeClass!
spikefloor1?.initializeSpike()
spikefloor2?.initializeSpike()
spikefloor3?.initializeSpike()
spikeceilling1 = childNode(withName: "SpikeCeilling1") as? SpikeClass!
spikeceilling2 = childNode(withName: "SpikeCeilling2") as? SpikeClass!
spikeceilling3 = childNode(withName: "SpikeCeilling3") as? SpikeClass!
spikeceilling1?.initializeSpike()
spikeceilling2?.initializeSpike()
spikeceilling3?.initializeSpike()
gameplayer = childNode(withName: "GamePlayer") as? GamePlayerClass!
gameplayer?.initializeGamePlayer()
}
private func manageCamera(){
//move the camera every frame plus ten, moving by ten pixels every frame
self.mainCamera?.position.x += 10
}
private func manageSpacesAndSpikes(){
space1?.moveSpace(camera: mainCamera!)
space2?.moveSpace(camera: mainCamera!)
space3?.moveSpace(camera: mainCamera!)
spikefloor1?.moveSpike(camera: mainCamera!)
spikefloor2?.moveSpike(camera: mainCamera!)
spikefloor3?.moveSpike(camera: mainCamera!)
spikeceilling1?.moveSpike(camera: mainCamera!)
spikeceilling2?.moveSpike(camera: mainCamera!)
spikeceilling3?.moveSpike(camera: mainCamera!)
}
func didBegin(_ contact: SKPhysicsContact) {
var playerBody = SKPhysicsBody()
var spikeBody = SKPhysicsBody()
if contact.bodyA.node?.name == "GamePlayer" {
playerBody = contact.bodyA
spikeBody = contact.bodyB
}else{
playerBody = contact.bodyB
spikeBody = contact.bodyA
}
if playerBody.node?.name == "GamePlayer" && (spikeBody.node?.name == "SpikeCeilling1" || spikeBody.node?.name == "SpikeCeilling2" || spikeBody.node?.name == "SpikeCeilling3" || spikeBody.node?.name == "SpikeFloor1" || spikeBody.node?.name == "SpikeFloor2" || spikeBody.node?.name == "SpikeFloor3" ){
bombSoundEffect.play()
}
}
private func reverseGravity(){
physicsWorld.gravity.dy *= -1
}
func managePlayer(rpm: Int){
gameplayer?.moveUpAndDown(up: rpm)
}
}
|
apache-2.0
|
807f52ed531f0787e4734bb5c9365e75
| 29.985401 | 308 | 0.625913 | 4.207136 | false | false | false | false |
andrea-prearo/swift-algorithm-data-structures-dojo
|
SwiftAlgorithmsAndDataStructuresDojo/BinaryTree/BinaryTree.swift
|
1
|
4338
|
//
// BinaryTree.swift
// SwiftAlgorithmsAndDataStructuresDojo
//
// Created by Andrea Prearo on 3/20/17.
// Copyright © 2017 Andrea Prearo. All rights reserved.
//
import Foundation
// MARK: - BinaryTreeNode
public class BinaryTreeNode<T: Comparable> {
var data: T
var left: BinaryTreeNode<T>? = nil
var right: BinaryTreeNode<T>? = nil
public init(data: T) {
self.data = data
}
}
// MARK: - BinaryTreeNode + CustomStringConvertible
extension BinaryTreeNode: CustomStringConvertible {
public var description: String {
return String(describing: data)
}
}
// MARK: - BinaryTreeNode + Equatable
extension BinaryTreeNode: Equatable {}
public func ==<T: Equatable>(lhs: BinaryTreeNode<T>, rhs: BinaryTreeNode<T>) -> Bool {
return lhs.data == rhs.data
}
// MARK: - BinaryTree
/*
`BinaryTree` has no concept of order. Operations such as `insert`, `remove` and `search`
have no meaning here. These operations are implemented in `BinarySearchTree`, which will
introduce and leverage the concept of order.
*/
public class BinaryTree<T: Comparable> {
var root: BinaryTreeNode<T>?
public var isEmpty: Bool {
return root == nil
}
public init(root: BinaryTreeNode<T>?) {
self.root = root
}
public convenience init() {
self.init(root: nil)
}
public func traverseInOrder(_ node: BinaryTreeNode<T>?,
visit: ((BinaryTreeNode<T>?) -> Void)? = nil) {
guard let node = node else {
return
}
traverseInOrder(node.left, visit: visit)
visit?(node)
traverseInOrder(node.right, visit: visit)
}
public func traverseLevelOrder(_ node: BinaryTreeNode<T>?,
visit: ((BinaryTreeNode<T>?) -> Void)? = nil) {
guard let node = node else {
return
}
let queue = Queue<BinaryTreeNode<T>>()
try? queue.push(node)
while !queue.isEmpty {
let node = queue.pop()
visit?(node)
if let leftNode = node?.left {
try? queue.push(leftNode)
}
if let rightNode = node?.right {
try? queue.push(rightNode)
}
}
}
public func traversePreOrder(_ node: BinaryTreeNode<T>?,
visit: ((BinaryTreeNode<T>?) -> Void)? = nil) {
guard let node = node else {
return
}
visit?(node)
traversePreOrder(node.left, visit: visit)
traversePreOrder(node.right, visit: visit)
}
public func traversePostOrder(_ node: BinaryTreeNode<T>?,
visit: ((BinaryTreeNode<T>?) -> Void)? = nil) {
guard let node = node else {
return
}
traversePostOrder(node.left, visit: visit)
traversePostOrder(node.right, visit: visit)
visit?(node)
}
public func traverseBreadthFirst(visit: ((BinaryTreeNode<T>?) -> Void)? = nil) {
traverseLevelOrder(root, visit: visit)
}
public func traverseDepthFirst(visit: ((BinaryTreeNode<T>?) -> Void)? = nil) {
traverseInOrder(root, visit: visit)
}
}
// MARK: - Private Methods
fileprivate extension BinaryTree {
func dump() -> String {
var nodeDumps: [String] = []
traverseInOrder(root) { node in
let nodeDump: String = {
guard let node = node else {
return "-"
}
return node.description
}()
nodeDumps.append(nodeDump)
}
return nodeDumps.joined(separator: ", ")
}
}
// MARK: - BinaryTree + CustomStringConvertible
extension BinaryTree: CustomStringConvertible {
public var description: String {
return dump()
}
}
// MARK: - BinaryTree to Array
extension BinaryTree {
var array: [BinaryTreeNode<T>] {
var nodes: [BinaryTreeNode<T>] = []
traverseInOrder(root) { node in
if let node = node {
nodes.append(node)
}
}
return nodes
}
}
// MARK: - BinaryTree + Equatable
extension BinaryTree: Equatable {}
public func ==<T: Equatable>(lhs: BinaryTree<T>, rhs: BinaryTree<T>) -> Bool {
return lhs.array == rhs.array
}
|
mit
|
45288bd8366194485098acdca567bb65
| 26.624204 | 89 | 0.574591 | 4.452772 | false | false | false | false |
johnno1962d/swift
|
test/expr/closure/single_expr.swift
|
1
|
1211
|
// RUN: %target-parse-verify-swift
func takeIntToInt(_ f: (Int) -> Int) { }
func takeIntIntToInt(_ f: (Int, Int) -> Int) { }
// Simple closures with anonymous arguments
func simple() {
takeIntToInt({$0 + 1})
takeIntIntToInt({$0 + $1 + 1})
}
// Anonymous arguments with inference
func myMap<T, U>(_ array: [T], _ f: (T) -> U) -> [U] {}
func testMap(_ array: [Int]) {
var farray = myMap(array, { Float($0) })
var _ : Float = farray[0]
let farray2 = myMap(array, { (x : Int) in Float(x) })
farray = farray2
_ = farray
}
// Nested single-expression closures -- <rdar://problem/20931915>
class NestedSingleExpr {
private var b: Bool = false
private func callClosure(_ callback: Void -> Void) {}
func call() {
callClosure { [weak self] in
self?.callClosure {
self?.b = true
}
}
}
}
// Autoclosure nested inside single-expr closure should get discriminator
// <rdar://problem/22441425> Swift compiler "INTERNAL ERROR: this diagnostic should not be produced"
struct Expectation<T> {}
func expect<T>(_ expression: @autoclosure () -> T) -> Expectation<T> {
return Expectation<T>()
}
func describe(_ closure: () -> ()) {}
func f() { describe { expect("what") } }
|
apache-2.0
|
0c4ab061b02536d4553fb136f46d5e97
| 26.522727 | 100 | 0.628406 | 3.430595 | false | false | false | false |
cuappdev/eatery
|
Eatery/KeychainItemWrapper.swift
|
1
|
6948
|
// KeychainItemWrapper.swift
//
// Copyright (c) 2015 Mihai Costea (http://mcostea.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
import Security
class KeychainItemWrapper {
var genericPasswordQuery = [AnyHashable: Any]()
var keychainItemData = [AnyHashable: Any]()
var values = [String: AnyObject]()
init(identifier: String, accessGroup: String?) {
self.genericPasswordQuery[kSecClass as AnyHashable] = kSecClassGenericPassword
self.genericPasswordQuery[kSecAttrAccount as AnyHashable] = identifier
#if !(arch(i386) || arch(x86_64))
if (accessGroup != nil) {
self.genericPasswordQuery[kSecAttrAccessGroup as AnyHashable] = accessGroup
}
#endif
self.genericPasswordQuery[kSecMatchLimit as AnyHashable] = kSecMatchLimitOne
self.genericPasswordQuery[kSecReturnAttributes as AnyHashable] = kCFBooleanTrue
var outDict: AnyObject?
let copyMatchingResult = SecItemCopyMatching(genericPasswordQuery as CFDictionary, &outDict)
if copyMatchingResult != noErr {
self.resetKeychain()
self.keychainItemData[kSecAttrAccount as AnyHashable] = identifier
#if !(arch(i386) || arch(x86_64))
if (accessGroup != nil) {
self.keychainItemData[kSecAttrAccessGroup as AnyHashable] = accessGroup
}
#endif
} else {
self.keychainItemData = self.secItemDataToDict(outDict as! [AnyHashable: Any])
}
}
subscript(key: String) -> AnyObject? {
get {
return self.values[key]
}
set(newValue) {
self.values[key] = newValue
self.writeKeychainData()
}
}
func resetKeychain() {
if !self.keychainItemData.isEmpty {
let tempDict = self.dictToSecItemData(self.keychainItemData)
var junk = noErr
junk = SecItemDelete(tempDict as CFDictionary)
assert(junk == noErr || junk == errSecItemNotFound, "Failed to delete current dict")
}
self.keychainItemData[kSecAttrAccount as AnyHashable] = ""
self.keychainItemData[kSecAttrLabel as AnyHashable] = ""
self.keychainItemData[kSecAttrDescription as AnyHashable] = ""
self.keychainItemData[kSecValueData as AnyHashable] = ""
}
fileprivate func secItemDataToDict(_ data: [AnyHashable: Any]) -> [AnyHashable: Any] {
var returnDict = [AnyHashable: Any]()
for (key, value) in data {
returnDict[key] = value
}
returnDict[kSecReturnData as AnyHashable] = kCFBooleanTrue
returnDict[kSecClass as AnyHashable] = kSecClassGenericPassword
var passwordData: AnyObject?
// We could use returnDict like the Apple example but this crashes the app with swift_unknownRelease
// when we try to access returnDict again
let queryDict = returnDict
let copyMatchingResult = SecItemCopyMatching(queryDict as CFDictionary, &passwordData)
if copyMatchingResult != noErr {
assert(false, "No matching item found in keychain")
} else {
let retainedValuesData = passwordData as! Data
do {
let val = try JSONSerialization.jsonObject(with: retainedValuesData, options: []) as! [String: AnyObject]
returnDict.removeValue(forKey: kSecReturnData as AnyHashable)
returnDict[kSecValueData as AnyHashable] = val
self.values = val
} catch let error as NSError {
assert(false, "Error parsing json value. \(error.localizedDescription)")
}
}
return returnDict
}
fileprivate func dictToSecItemData(_ dict: [AnyHashable: Any]) -> [AnyHashable: Any] {
var returnDict = [AnyHashable: Any]()
for (key, value) in self.keychainItemData {
returnDict[key] = value
}
returnDict[kSecClass as AnyHashable] = kSecClassGenericPassword
do {
returnDict[kSecValueData as AnyHashable] = try JSONSerialization.data(withJSONObject: self.values, options: [])
} catch let error as NSError {
assert(false, "Error paring json value. \(error.localizedDescription)")
}
return returnDict
}
fileprivate func writeKeychainData() {
var attributes: AnyObject?
var updateItem: [AnyHashable: Any]?
var result: OSStatus?
let copyMatchingResult = SecItemCopyMatching(self.genericPasswordQuery as CFDictionary, &attributes)
if copyMatchingResult != noErr {
result = SecItemAdd(self.dictToSecItemData(self.keychainItemData) as CFDictionary, nil)
assert(result == noErr, "Failed to add keychain item")
} else {
updateItem = [String: AnyObject]()
for (key, value) in attributes as! [String: AnyObject] {
updateItem![key] = value
}
updateItem![kSecClass as AnyHashable] = self.genericPasswordQuery[kSecClass as AnyHashable]
var tempCheck = self.dictToSecItemData(self.keychainItemData)
tempCheck.removeValue(forKey: kSecClass as AnyHashable)
if TARGET_OS_SIMULATOR == 1 {
tempCheck.removeValue(forKey: kSecAttrAccessGroup as AnyHashable)
}
result = SecItemUpdate(updateItem! as CFDictionary, tempCheck as CFDictionary)
assert(result == noErr, "Failed to update keychain item")
}
}
}
|
mit
|
97a4f011bbdc93eb898700da416e0c77
| 38.477273 | 123 | 0.626367 | 5.377709 | false | false | false | false |
6ag/BaoKanIOS
|
BaoKanIOS/Classes/Module/Profile/Controller/JFProfileViewController.swift
|
1
|
13968
|
//
// JFProfileViewController.swift
// BaoKanIOS
//
// Created by jianfeng on 15/12/20.
// Copyright © 2015年 六阿哥. All rights reserved.
//
import UIKit
import YYWebImage
class JFProfileViewController: JFBaseTableViewController {
let imagePickerC = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
tableView.showsVerticalScrollIndicator = false
tableView.addSubview(headerView)
// 这个是用来占位的
let tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 275))
tableView.tableHeaderView = tableHeaderView
prepareData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
updateHeaderData()
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
/**
配置imagePicker
- parameter sourceType: 资源类型
*/
func setupImagePicker(_ sourceType: UIImagePickerControllerSourceType) {
imagePickerC.view.backgroundColor = BACKGROUND_COLOR
imagePickerC.delegate = self
imagePickerC.sourceType = sourceType
imagePickerC.allowsEditing = true
imagePickerC.modalTransitionStyle = UIModalTransitionStyle.coverVertical
}
/**
准备数据
*/
fileprivate func prepareData() {
// let group1CellModel1 = JFProfileCellArrowModel(title: "离线阅读", icon: "setting_star_icon")
// group1CellModel1.operation = { () -> Void in
// print("离线阅读")
// }
// let group1 = JFProfileCellGroupModel(cells: [group1CellModel1])
let group2CellModel1 = JFProfileCellLabelModel(title: "清除缓存", icon: "setting_clear_icon", text: "0.0M")
group2CellModel1.operation = { () -> Void in
JFProgressHUD.showWithStatus("正在清理")
YYImageCache.shared().diskCache.removeAllObjects({
JFProgressHUD.showSuccessWithStatus("清理成功")
group2CellModel1.text = "0.00M"
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
})
}
let group2CellModel2 = JFProfileCellArrowModel(title: "正文字体", icon: "setting_star_icon")
group2CellModel2.operation = { () -> Void in
let setFontSizeView = Bundle.main.loadNibNamed("JFSetFontView", owner: nil, options: nil)?.last as! JFSetFontView
setFontSizeView.delegate = self
setFontSizeView.show()
}
// let group2CellModel3 = JFProfileCellSwitchModel(title: "夜间模式", icon: "setting_duty_icon")
let group2 = JFProfileCellGroupModel(cells: [group2CellModel1, group2CellModel2])
let group3CellModel1 = JFProfileCellArrowModel(title: "意见反馈", icon: "setting_feedback_icon", destinationVc: JFProfileFeedbackViewController.classForCoder())
let group3CellModel2 = JFProfileCellArrowModel(title: "关于我们", icon: "setting_help_icon", destinationVc: JFAboutMeViewController.classForCoder())
let group3CellModel3 = JFProfileCellArrowModel(title: "推荐给好友", icon: "setting_share_icon")
group3CellModel3.operation = { () -> Void in
if JFShareItemModel.loadShareItems().count == 0 {
JFProgressHUD.showInfoWithStatus("没有可分享内容")
return
}
// 弹出分享视图
self.shareView.showShareView()
}
let group3CellModel4 = JFProfileCellLabelModel(title: "当前版本", icon: "setting_upload_icon", text: (Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String))
let group3 = JFProfileCellGroupModel(cells: [group3CellModel1, group3CellModel2, group3CellModel3, group3CellModel4])
groupModels = [group2, group3]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath) as! JFProfileCell
// 更新缓存数据
if indexPath.section == 0 && indexPath.row == 0 {
cell.settingRightLabel.text = "\(String(format: "%.2f", CGFloat(YYImageCache.shared().diskCache.totalCost()) / 1024 / 1024))M"
}
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
/**
更新头部数据
*/
fileprivate func updateHeaderData() {
if JFAccountModel.isLogin() {
headerView.avatarButton.yy_setBackgroundImage(with: URL(string: JFAccountModel.shareAccount()!.avatarUrl!), for: UIControlState(), options: YYWebImageOptions.allowBackgroundTask)
headerView.nameLabel.text = JFAccountModel.shareAccount()!.nickname
} else {
headerView.avatarButton.setBackgroundImage(UIImage(named: "default-portrait"), for: .normal)
headerView.nameLabel.text = "登录账号"
}
}
lazy var headerView: JFProfileHeaderView = {
let headerView = Bundle.main.loadNibNamed("JFProfileHeaderView", owner: nil, options: nil)?.last as! JFProfileHeaderView
headerView.delegate = self
headerView.frame = CGRect(x: 0, y: -(SCREEN_HEIGHT * 2 - 265), width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 2)
return headerView
}()
/// 分享视图
fileprivate lazy var shareView: JFShareView = {
let shareView = JFShareView()
shareView.delegate = self
return shareView
}()
}
// MARK: - JFProfileHeaderViewDelegate
extension JFProfileViewController: JFProfileHeaderViewDelegate {
/**
头像按钮点击
*/
func didTappedAvatarButton() {
if JFAccountModel.isLogin() {
let alertC = UIAlertController()
let takeAction = UIAlertAction(title: "拍照上传", style: UIAlertActionStyle.default, handler: { (action) in
self.setupImagePicker(.camera)
self.present(self.imagePickerC, animated: true, completion: {})
})
let photoLibraryAction = UIAlertAction(title: "图库选择", style: UIAlertActionStyle.default, handler: { (action) in
self.setupImagePicker(.photoLibrary)
self.present(self.imagePickerC, animated: true, completion: {})
})
let albumAction = UIAlertAction(title: "相册选择", style: UIAlertActionStyle.default, handler: { (action) in
self.setupImagePicker(.savedPhotosAlbum)
self.present(self.imagePickerC, animated: true, completion: {})
})
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
})
alertC.addAction(takeAction)
alertC.addAction(photoLibraryAction)
alertC.addAction(albumAction)
alertC.addAction(cancelAction)
self.present(alertC, animated: true, completion: {})
} else {
present(JFNavigationController(rootViewController: JFLoginViewController(nibName: "JFLoginViewController", bundle: nil)), animated: true, completion: {
})
}
}
/**
收藏列表
*/
func didTappedCollectionButton() {
if JFAccountModel.isLogin() {
navigationController?.pushViewController(JFCollectionTableViewController(style: UITableViewStyle.plain), animated: true)
} else {
present(JFNavigationController(rootViewController: JFLoginViewController(nibName: "JFLoginViewController", bundle: nil)), animated: true, completion: {
})
}
}
/**
评论列表
*/
func didTappedCommentButton() {
if JFAccountModel.isLogin() {
navigationController?.pushViewController(JFCommentListTableViewController(style: UITableViewStyle.plain), animated: true)
} else {
present(JFNavigationController(rootViewController: JFLoginViewController(nibName: "JFLoginViewController", bundle: nil)), animated: true, completion: {
})
}
}
/**
修改个人信息
*/
func didTappedInfoButton() {
if JFAccountModel.isLogin() {
navigationController?.pushViewController(JFEditProfileViewController(style: UITableViewStyle.grouped), animated: true)
} else {
present(JFNavigationController(rootViewController: JFLoginViewController(nibName: "JFLoginViewController", bundle: nil)), animated: true, completion: {
})
}
}
}
// MARK: - JFSetFontViewDelegate
extension JFProfileViewController: JFSetFontViewDelegate {
func didChangeFontSize(_ fontSize: Int) {
}
func didChangedFontName(_ fontName: String) {
}
func didChangedNightMode(_ on: Bool) {
}
}
// MARK: - UINavigationControllerDelegate, UIImagePickerControllerDelegate
extension JFProfileViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
let image = info[UIImagePickerControllerEditedImage] as! UIImage
let newImage = image.resizeImageWithNewSize(CGSize(width: 108, height: 108))
uploadUserAvatar(newImage)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
/**
上传用户头像
- parameter image: 头像图片
*/
func uploadUserAvatar(_ image: UIImage) {
let imagePath = saveImageAndGetURL(image, imageName: "avatar.png")
let parameters: [String : AnyObject] = [
"username" : JFAccountModel.shareAccount()!.username! as AnyObject,
"userid" : "\(JFAccountModel.shareAccount()!.id)" as AnyObject,
"token" : JFAccountModel.shareAccount()!.token! as AnyObject,
"action" : "UploadAvatar" as AnyObject,
]
JFProgressHUD.showWithStatus("正在上传")
JFNetworkTool.shareNetworkTool.uploadUserAvatar("\(MODIFY_ACCOUNT_INFO)", imagePath: imagePath, parameters: parameters) { (status, result, tipString) in
print(result ?? "")
if status == .success {
JFProgressHUD.showInfoWithStatus("上传成功")
// 更新用户信息并刷新tableView
JFAccountModel.checkUserInfo({
self.updateHeaderData()
})
} else {
JFProgressHUD.showInfoWithStatus("上传失败")
}
}
}
/**
保存图片并获取保存的图片路径
*/
func saveImageAndGetURL(_ image: UIImage, imageName: NSString) -> URL {
let home = NSHomeDirectory() as NSString
let docPath = home.appendingPathComponent("Documents") as NSString;
let fullPath = docPath.appendingPathComponent(imageName as NSString as String);
let imageData: Data = UIImageJPEGRepresentation(image, 0.5)!
try? imageData.write(to: URL(fileURLWithPath: fullPath as String), options: [])
return URL(fileURLWithPath: fullPath)
}
}
// MARK: - JFShareViewDelegate
extension JFProfileViewController: JFShareViewDelegate {
func share(type: JFShareType) {
let platformType: SSDKPlatformType!
switch type {
case .qqFriend:
platformType = SSDKPlatformType.subTypeQZone // 尼玛,这竟然是反的。。ShareSDK bug
case .qqQzone:
platformType = SSDKPlatformType.subTypeQQFriend // 尼玛,这竟然是反的。。
case .weixinFriend:
platformType = SSDKPlatformType.subTypeWechatSession
case .friendCircle:
platformType = SSDKPlatformType.subTypeWechatTimeline
}
var image = UIImage(named: "launchScreen")!
if image.size.width > 300 || image.size.height > 300 {
image = image.resizeImageWithNewSize(CGSize(width: 300, height: 300 * image.size.height / image.size.width))
}
let shareParames = NSMutableDictionary()
shareParames.ssdkSetupShareParams(byText: "爆侃网文精心打造网络文学互动平台,专注最新文学市场动态,聚焦第一手网文圈资讯!",
images : image,
url : URL(string:"http://www.baokan.tv/wapapp/index.html"),
title : "爆侃网文让您的网文之路不再孤单!",
type : SSDKContentType.auto)
ShareSDK.share(platformType, parameters: shareParames) { (state, _, entity, error) in
switch state {
case SSDKResponseState.success:
print("分享成功")
case SSDKResponseState.fail:
print("授权失败,错误描述:\(error)")
case SSDKResponseState.cancel:
print("操作取消")
default:
break
}
}
}
}
|
apache-2.0
|
f73858a845d5a6d3cfbc173bed788e1f
| 38.12828 | 190 | 0.623277 | 4.946922 | false | false | false | false |
jweinst1/CornFlake
|
CornFlake/machine.swift
|
1
|
2536
|
//
// machine.swift
// CornFlake
//
// Created by Joshua Weinstein on 2/20/16.
// Copyright © 2016 Joshua Weinstein. All rights reserved.
//
import Foundation
struct cornmachine {
var row:[Int]
var pointer:Int
init() {
self.row = [0, 0, 0]
self.pointer = 0
}
//resets the table
mutating func reset() {
self.row = [0, 0, 0]
}
//increments a slot
mutating func increment(slot:Int) {
self.row[slot] += 1
}
mutating func incrementcurrent() {
self.row[self.pointer] += 1
}
mutating func decrement(slot:Int) {
self.row[slot] -= 1
}
mutating func decrementcurrent() {
self.row[self.pointer] -= 1
}
mutating func resetpointer() {
self.pointer = 0
}
mutating func insert(slot:Int, value:Int) {
self.row[slot] = value
}
//passes in a custom value to the slot
mutating func insertcurrent(value:Int) {
self.row[self.pointer] = value
}
//increases the pointer
mutating func incpointer() {
self.pointer = increasepointer(self.pointer)
}
//decreases the pointer
mutating func decpointer() {
self.pointer = decreasepointer(self.pointer)
}
//prints the current slot
mutating func printcurrent() {
print(self.row[self.pointer])
}
//prints the entire operating row
mutating func printrow() {
print(self.row[0], terminator:" ")
print(self.row[1], terminator:" ")
print(self.row[2])
}
//sums to a number and sets the current cell to that
mutating func setsum() {
var total = 0
for elem in 1...self.row[self.pointer] {
total += elem
}
self.row[self.pointer] = total
}
//adds outer two slots to the middle
mutating func addtomiddle() {
self.row[1] += self.row[0] + self.row[2]
}
//subtracts middle cell from both sides
mutating func splittosides() {
self.row[0] -= self.row[1]
self.row[2] -= self.row[1]
}
//adds the value of the current cell to the left cell
mutating func addtoleft() {
self.row[decreasepointer(self.pointer)] += self.row[self.pointer]
}
//adds the value of the current cell to the right cell
mutating func addtoright() {
self.row[increasepointer(self.pointer)] += self.row[self.pointer]
}
//reverses the row
mutating func reverserow() {
self.row = self.row.reverse()
}
}
|
mit
|
49a35d106c74fae50dabde446bd2b3a5
| 24.867347 | 73 | 0.584615 | 3.766716 | false | false | false | false |
Rhapsody/Observable-Swift
|
Observable-Swift/ObservableTransformProxy.swift
|
1
|
1379
|
//
// ObservableTranformProxy.swift
// Skyway
//
// Created by Adam Ritenauer on 22.08.15.
// Copyright (c) 2015 Rhapsody International. All rights reserved.
//
import Foundation
open class ObservableTransformProxy<TransformType, ObservableType:AnyObservable> : OwnableObservable {
open /*internal(set)*/ var beforeChange = EventReference<ValueChange<TransformType>>()
open /*internal(set)*/ var afterChange = EventReference<ValueChange<TransformType>>()
// private storage in case subclasses override value with a setter
fileprivate var _value : TransformType
open var value : TransformType {
return _value
}
public init(_ o: ObservableType, transform:@escaping (ObservableType.ValueType)->TransformType) {
self._value = transform(o.value)
o.beforeChange.add(owner: self) { [weak self] change in
let transformChange = ValueChange(transform(change.oldValue), transform(change.newValue))
self!.beforeChange.notify(transformChange)
}
o.afterChange.add(owner: self) { [weak self] change in
let nV = change.newValue
self!._value = transform(nV)
let transformChange = ValueChange(transform(change.oldValue), transform(change.newValue))
self!.afterChange.notify(transformChange)
}
}
}
|
mit
|
34da24d559e3a64f63aa1725705fc5e0
| 35.289474 | 102 | 0.670051 | 4.706485 | false | false | false | false |
google/android-auto-companion-ios
|
Tests/AndroidAutoMessageStreamTests/VarintTest.swift
|
1
|
4152
|
// Copyright 2022 Google LLC
//
// 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 SwiftProtobuf
import XCTest
import AndroidAutoCompanionProtos
@testable import AndroidAutoMessageStream
private typealias Packet = Com_Google_Companionprotos_Packet
/// Unit tests for `Varint`.
class VarintTest: XCTestCase {
func testSmallVarintSize() throws {
let data = Data([17])
let (numRead, size) = try Varint.decodeFirstVarint(from: data)
XCTAssertEqual(numRead, 1)
XCTAssertEqual(size, 17)
}
func testIncompleteVarintThrowsIncompleteData() throws {
// If the high bit is set, then subsequent data will be needed to parse the Varint.
let varintByte: UInt8 = 17 | 0x80
let data = Data([varintByte])
XCTAssertThrowsError(try Varint.decodeFirstVarint(from: data)) { error in
XCTAssertTrue(error is Varint.DecodingError)
guard let error = error as? Varint.DecodingError else { return }
XCTAssertEqual(error, .incompleteData)
}
}
func testDecodeFirstVarintSingleByteDataSize() throws {
try assertFirstVarintDecodingBinaryDelimited(sizeByteCount: 1)
}
func testDecodeFirstVarintTwoByteDataSize() throws {
try assertFirstVarintDecodingBinaryDelimited(sizeByteCount: 2)
}
func testDecodeFirstVarintThreeByteDataSize() throws {
try assertFirstVarintDecodingBinaryDelimited(sizeByteCount: 3)
}
func testDecodeFirstVarintFourByteDataSize() throws {
try assertFirstVarintDecodingBinaryDelimited(sizeByteCount: 4)
}
}
// MARK: - Utilities
extension VarintTest {
/// Assert the first Varint decoded correctly measures the data size of the binary delimited data.
///
/// Tests whether `Varint.decodeFirstVarint(from:)` correctly decodes the data size by using it
/// to measure the data to deserialize and then attempting to deserialize it. Since the `Varint`
/// itself may be represented in a variable number of bytes, we can call this method to test with
/// different `Varint` sizes (bytes for Varint itself) and thus spanning different data sizes.
///
/// - Parameter sizeByteCount: Number of bytes encoding the size integer itself.
/// - Throws: An error if the decoding fails.
private func assertFirstVarintDecodingBinaryDelimited(sizeByteCount: Int) throws {
// Create a small packet.
var controlPacket = Packet()
controlPacket.packetNumber = 1
// 1 byte Varint -> Small Packet (no payload).
// 2 byte Varint -> A Packet with a payload of 0x80.
// >2 byte Varint -> A Packet with payload of 0x80 shifted by increments of 7.
if sizeByteCount > 1 {
let shift = 7 * (sizeByteCount - 2)
let dataSize = 0x80 << shift
controlPacket.payload = Data(
[UInt8](repeating: UInt8.random(in: 0 ..< .max), count: dataSize))
}
// Serialize the packet delimited (leading Varint).
let outputStream = OutputStream(toMemory: ())
outputStream.open()
try BinaryDelimited.serialize(message: controlPacket, to: outputStream)
outputStream.close()
guard
let data = outputStream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey)
as? Data
else {
XCTFail("No data in output stream.")
throw NSError(domain: "InputStreamMessageAdaptorTest", code: 1, userInfo: nil)
}
// Decode the Varint.
let (numRead, dataSize) = try Varint.decodeFirstVarint(from: data)
XCTAssertEqual(numRead, sizeByteCount)
let messageData = data[numRead...]
XCTAssertEqual(dataSize, messageData.count)
let testPacket = try Packet(serializedData: messageData)
XCTAssertEqual(controlPacket, testPacket)
}
}
|
apache-2.0
|
2442af4fdac69e08aada1b112bb03601
| 36.071429 | 100 | 0.730491 | 4.435897 | false | true | false | false |
Josscii/iOS-Demos
|
DynamicLabelsDemo/DynamicLabelsDemo/DynamicLabelsView.swift
|
1
|
2107
|
//
// DynamicLabelsView.swift
// DynamicLabelsDemo
//
// Created by Josscii on 2017/8/7.
// Copyright © 2017年 Josscii. All rights reserved.
//
import UIKit
class DynamicLabelsView: UIView {
var labels: [UILabel] = []
var dynamicConstraints: [NSLayoutConstraint] = []
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .green
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
let heightConstraint = heightAnchor.constraint(equalToConstant: 0)
dynamicConstraints.append(heightConstraint)
for i in 0..<4 {
let label = UILabel()
label.backgroundColor = .red
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
labels.append(label)
label.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
label.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
let bottomConstraint = label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10)
dynamicConstraints.append(bottomConstraint)
if i == 0 {
label.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
continue
}
label.topAnchor.constraint(equalTo: labels[i-1].bottomAnchor, constant: 10).isActive = true
}
}
func setup(with strings: [String]) {
dynamicConstraints.forEach { $0.isActive = false }
let count = strings.count
for i in 0..<count {
if i == 3 {
labels[i].text = "查看\(count)条评论"
break
}
labels[i].text = strings[i]
}
let index = min(count, 4)
dynamicConstraints[index].isActive = true
}
}
|
mit
|
547ba258a67b4eb2ad77f2b67b5b12c0
| 29.347826 | 103 | 0.567335 | 5.021583 | false | false | false | false |
Legoless/TapticPlayground
|
ViewControllerPreviewsUsingtheUIViewControllerpreviewingAPIs/ViewControllerPreview/MasterViewController.swift
|
1
|
4310
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The master view controller.
*/
import UIKit
class MasterViewController: UITableViewController {
// MARK: Types
/// A simple data structure to populate the table view.
struct PreviewDetail {
let title: String
let preferredHeight: Double
}
var timer : NSTimer?
// MARK: Properties
let sampleData = [
PreviewDetail(title: "Small", preferredHeight: 160.0),
PreviewDetail(title: "Medium", preferredHeight: 320.0),
PreviewDetail(title: "Large", preferredHeight: 0.0) // 0.0 to get the default height.
]
/// An alert controller used to notify the user if 3D touch is not available.
var alertController: UIAlertController?
// MARK: View Life Cycle
@IBAction func vibrateButtonTap(sender: UIBarButtonItem)
{
if sender.title != "Stop" {
sender.title = "Stop"
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "vibrate", userInfo: nil, repeats: true)
}
else {
sender.title = "Vibrate"
self.timer!.invalidate()
self.timer = nil
}
}
func vibrate () {
UIDevice.currentDevice().tapticEngine().actuateFeedback(UITapticEngineFeedbackPeek)
}
override func viewDidLoad() {
super.viewDidLoad()
// Check for force touch feature, and add force touch/previewing capability.
if traitCollection.forceTouchCapability == .Available {
/*
Register for `UIViewControllerPreviewingDelegate` to enable
"Peek" and "Pop".
(see: MasterViewController+UIViewControllerPreviewing.swift)
The view controller will be automatically unregistered when it is
deallocated.
*/
registerForPreviewingWithDelegate(self, sourceView: view)
}
else {
// Create an alert to display to the user.
alertController = UIAlertController(title: "3D Touch Not Available", message: "Unsupported device.", preferredStyle: .Alert)
}
}
override func viewWillAppear(animated: Bool) {
// Clear the selection if the split view is only showing one view controller.
clearsSelectionOnViewWillAppear = splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Present the alert if necessary.
if let alertController = alertController {
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
// Clear the `alertController` to ensure it's not presented multiple times.
self.alertController = nil
}
}
// MARK: UIStoryboardSegue Handling
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail", let indexPath = tableView.indexPathForSelectedRow {
let previewDetail = sampleData[indexPath.row]
let detailViewController = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
// Pass the `title` to the `detailViewController`.
detailViewController.detailItemTitle = previewDetail.title
}
}
// MARK: Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of items in the sample data structure.
return sampleData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let previewDetail = sampleData[indexPath.row]
cell.textLabel!.text = previewDetail.title
return cell
}
}
|
mit
|
7cd359b33402bf29100668fe8654c93c
| 34.02439 | 142 | 0.637419 | 5.609375 | false | false | false | false |
MiniDOM/MiniDOM
|
Tests/MiniDOMTests/TestData/RSSTestsSource.swift
|
1
|
10520
|
//
// RSSTestsSource.swift
// MiniDOM
//
// Copyright 2017-2020 Anodized Software, Inc.
//
// 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
let yahooTestsSource = [
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?> ",
"<rss version=\"2.0\">",
" <channel>",
" <title><![CDATA[Yahoo! News Search Results for market]]></title>",
" <link>http://news.search.yahoo.com/search/news?p=market&ei=UTF-8</link>",
" <description><![CDATA[Yahoo! News Search Results for market]]></description>",
" <language>en-us</language>",
" <copyright>Copyright (c) 2004 Yahoo! Inc. All rights reserved.</copyright>",
" <lastBuildDate>Sun, 03 Sep 2006 16:34:54 GMT</lastBuildDate>",
" <ttl>5</ttl>",
" <image>",
" <title>Yahoo! News</title>",
" <width>142</width>",
" <height>18</height>",
" <link>http://news.search.yahoo.com/news</link>",
" <url>http://us.i1.yimg.com/us.yimg.com/i/us/nws/th/main_142.gif</url>",
" </image>",
" <incremental xmlns=\"http://purl.org/syndication/history/1.0\">false</incremental>",
" <item>",
" <title><![CDATA[Toyota increases share in US auto market (Manila Bulletin)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=13ck33lrk/*http%3A//www.mb.com.ph/archive_pages.php?url=http://www.mb.com.ph/issues/2006/09/04/BSNS2006090473427.html</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=13ck33lrk/*http%3A//www.mb.com.ph/archive_pages.php?url=http://www.mb.com.ph/issues/2006/09/04/BSNS2006090473427.html</guid>",
" <pubDate>Sun, 03 Sep 2006 16:21:30 GMT</pubDate>",
" <description><![CDATA[DETROIT (AP) — With a model lineup that consumers love, Toyota Motor Corp. continued to take market share from other automakers last month, posting an industry-best 17 percent increase in sales.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[ANALYSIS - North Korea finds market for missiles shrinking (Reuters via Yahoo! Asia News)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=11ibfq78e/*http%3A//asia.news.yahoo.com/060903/3/2pd1j.html</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=11ibfq78e/*http%3A//asia.news.yahoo.com/060903/3/2pd1j.html</guid>",
" <pubDate>Sun, 03 Sep 2006 08:37:33 GMT</pubDate>",
" <description><![CDATA[ SEOUL (Reuters) - The missile market is not what it used to be for North Korea, with fewer buyers for a key export product and a loss in prestige when its top-end rocket fizzled after a short test flight, U.S. officials and experts said.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[Broward labor market's a solid performer (Miami Herald)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=13671c2t8/*http%3A//www.miami.com/mld/miamiherald/business/15427113.htm?source=rss&channel=miamiherald_business</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=13671c2t8/*http%3A//www.miami.com/mld/miamiherald/business/15427113.htm?source=rss&channel=miamiherald_business</guid>",
" <pubDate>Sun, 03 Sep 2006 07:39:53 GMT</pubDate>",
" <description><![CDATA[In looking at South Florida's labor market, it's a tale of two cities, with Fort Lauderdale coming out on top, by far, according to an annual Labor Day report by Florida International University's Bruce Nissen.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[NID to help Jharkhand e-market crafts (Yahoo! India News)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=11hg1j19f/*http%3A//in.news.yahoo.com/060903/43/6780a.html</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=11hg1j19f/*http%3A//in.news.yahoo.com/060903/43/6780a.html</guid>",
" <pubDate>Sun, 03 Sep 2006 10:02:54 GMT</pubDate>",
" <description><![CDATA[Ranchi, Sep 3 (IANS) Jharkhand will e-market its indigenous products with the help of National Institute of Design (NID), Ahmedabad.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[Reinsurance market goes high-tech to predict disasters (The Herald-Tribune)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12j43rdgp/*http%3A//www.heraldtribune.com/apps/pbcs.dll/article?AID=/20060903/NEWS/609030458</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12j43rdgp/*http%3A//www.heraldtribune.com/apps/pbcs.dll/article?AID=/20060903/NEWS/609030458</guid>",
" <pubDate>Sun, 03 Sep 2006 10:34:36 GMT</pubDate>",
" <description><![CDATA[Hurricane outlooks are closely watched at such places as the Lloyd's of London insurance market building.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[Government warned against going into property market (Sunday Business Post)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12pru5k6v/*http%3A//www.sbpost.ie/breakingnews/breaking_story.asp?j=4126020&p=4yz6x35&n=4126112&x=</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12pru5k6v/*http%3A//www.sbpost.ie/breakingnews/breaking_story.asp?j=4126020&p=4yz6x35&n=4126112&x=</guid>",
" <pubDate>Sun, 03 Sep 2006 09:31:34 GMT</pubDate>",
" <description><![CDATA[A new report is expected to warn the Government not to intervene in the property market. The report by IIB Bank, which is due to be published tomorrow, will argue that it doesn't make sense for the Government to try and stop speculators buying new homes for profit.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[Farmers Market gets shoulder-to-shoulder crowds on Saturdays (Great Falls Tribune)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12pfls0n1/*http%3A//www.greatfallstribune.com/apps/pbcs.dll/article?AID=/20060903/NEWS01/609030306</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12pfls0n1/*http%3A//www.greatfallstribune.com/apps/pbcs.dll/article?AID=/20060903/NEWS01/609030306</guid>",
" <pubDate>Sun, 03 Sep 2006 11:12:36 GMT</pubDate>",
" <description><![CDATA[The produce is bountiful at the Great Falls Farmers Market and so are the customers, vendors say. \"Business is booming,\" said Heather Sands of Little Creek Nursery in Fort Shaw.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[City Hall takes Plan B for SF market rehab (Sun Star)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=138rfnhvi/*http%3A//www.sunstar.com.ph/static/pam/2006/09/03/news/city.hall.takes.plan.b.for.sf.market.rehab.html</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=138rfnhvi/*http%3A//www.sunstar.com.ph/static/pam/2006/09/03/news/city.hall.takes.plan.b.for.sf.market.rehab.html</guid>",
" <pubDate>Sun, 03 Sep 2006 08:18:46 GMT</pubDate>",
" <description><![CDATA[CITY OF SAN FERNANDO -- The City Government here shelved an earlier proposal of constructing the old public market through a bond flotation scheme and instead took Plan B, which is the rehabilitation of the market's wet section.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[Market watch (AG Weekly)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12ahobgi6/*http%3A//www.agweekly.com/articles/2006/09/02/news/markets/markets01.txt</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=12ahobgi6/*http%3A//www.agweekly.com/articles/2006/09/02/news/markets/markets01.txt</guid>",
" <pubDate>Sun, 03 Sep 2006 04:20:37 GMT</pubDate>",
" <description><![CDATA[The Market Sentiment Index can be an invaluable tool in forecasting important price tops and bottoms in the market. The index was developed by Market Vane, a California-based research company, in the 1960s and is still published by a variety of reliable sources.]]></description>",
" </item>",
" <item>",
" <title><![CDATA[Catholic War Vets Ladies Club sets flea market (Times Leader)]]></title>",
" <link>http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=1383flil1/*http%3A//www.timesleader.com/mld/timesleader/living/15431391.htm?source=rss&channel=timesleader_living</link>",
" <guid isPermaLink=\"false\">http://us.rd.yahoo.com/dailynews/rss/search/market/SIG=1383flil1/*http%3A//www.timesleader.com/mld/timesleader/living/15431391.htm?source=rss&channel=timesleader_living</guid>",
" <pubDate>Sun, 03 Sep 2006 07:07:50 GMT</pubDate>",
" <description><![CDATA[Catholic War Veterans, Post 274, Ashley, Ladies Club will hold a flea market from 7 a.m. until 2 p.m. Sept. 10, Sept. 24 and Oct. 1 on the grounds of the Catholic War Veterans. The event will take place rain or shine. For more information, vendor information or to reserve a table, call Marsha Panetta at 823-6232 or Dorothy Liberaski at 474-9969. From left, members of the planning committee are ]]></description>",
" </item>",
" </channel>",
"</rss>",
"<!-- s8.news.dcn.yahoo.com uncompressed/chunked Sun Sep 3 09:34:54 PDT 2006 -->",
].joined(separator: "\n")
|
mit
|
2e82250c84dd04176e51499c4a222401
| 86.65 | 445 | 0.705457 | 3.001712 | false | false | false | false |
avario/LayoutKit
|
LayoutKit/LayoutKit/UIEdgeInsets+LayoutKit.swift
|
1
|
1353
|
//
// EdgeInsets.swift
// LayoutKit
//
// Created by Avario.
//
import Foundation
import UIKit
public extension UIEdgeInsets {
fileprivate init(_ topValue: CGFloat, _ leftValue: CGFloat, _ bottomValue: CGFloat, _ rightValue: CGFloat) {
self.init(top: topValue, left: leftValue, bottom: bottomValue, right: rightValue)
}
/// Create `UIEdgeInsets` by specifying only insets unique edges.
/// Unspecified edges will be set to `others` (default `0`).
public init(top: CGFloat? = nil, left: CGFloat? = nil, bottom: CGFloat? = nil, right: CGFloat? = nil, others: CGFloat = 0) {
self.init(top ?? others, left ?? others, bottom ?? others, right ?? others)
}
/// Create `UIEdgeInsets` by specifying horizontal and/or vertical insets.
/// Unspecified insets default to `0`.
///
/// - parameters:
/// - horizontal: `left` and `right` insets.
/// - vertical: `top` and `bottom` insets.
public init(horizontal: CGFloat = 0, vertical: CGFloat = 0) {
self.init(vertical, horizontal, vertical, horizontal)
}
/// Create `UIEdgeInsets` with all insets the same.
///
/// - parameters:
/// - inset: Value to be used for `top`, `left`, `bottom`, and `right` insets.
public init(_ inset: CGFloat) {
self.init(inset, inset, inset, inset)
}
}
|
mit
|
c3d326cde6826f4622bb14b028c6013c
| 27.787234 | 128 | 0.625277 | 3.944606 | false | false | false | false |
esummers-msft/azure-storage-ios
|
BlobSample/BlobSample/AddBlobViewController.swift
|
2
|
3225
|
// -----------------------------------------------------------------------------------------
// <copyright file="AddBlobViewController.swift" company="Microsoft">
// Copyright 2015 Microsoft Corporation
//
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://spdx.org/licenses/MIT
//
// 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.
// </copyright>
// -----------------------------------------------------------------------------------------
import UIKit
class AddBlobViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var textTextField: UITextField!
var container: AZSCloudBlobContainer?
var viewToReloadOnBlobAdd : BlobListTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field's user input through delegate callbacks.
nameTextField.delegate = self
textTextField.delegate = self
checkValidBlobName()
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
saveButton.enabled = false
}
func checkValidBlobName() {
// Disable save if text field is empty.
let text = nameTextField.text ?? ""
saveButton.enabled = !text.isEmpty
}
func textFieldDidEndEditing(textField: UITextField) {
checkValidBlobName()
if (textField === nameTextField) {
navigationItem.title = textField.text
}
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Navigation
@IBAction func cancel(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
if (!name.isEmpty)
{
let blob = container!.blockBlobReferenceFromName(name)
blob.uploadFromText(textTextField.text ?? "", completionHandler: { (error: NSError?) -> Void in
if (self.viewToReloadOnBlobAdd != nil) {
self.viewToReloadOnBlobAdd!.reloadBlobList()
}
})
}
}
}
}
|
mit
|
9abaaf789286d4a6ebbe7447690a4988
| 33.677419 | 133 | 0.605891 | 5.728242 | false | false | false | false |
mkrd/Swift-Big-Integer
|
Tests/MG Matrix Tests.swift
|
1
|
1419
|
/*
* ————————————————————————————————————————————————————————————————————————————
* MG Matrix Tests.swift
* ————————————————————————————————————————————————————————————————————————————
* Created by Marcel Kröker on 26.10.17.
* Copyright © 2017 Marcel Kröker. All rights reserved.
*/
import Foundation
#if !SWIFT_PACKAGE
public class MG_Matrix_Tests
{
static func testSparseMatrix()
{
// Make a random sparse matrix
var M = Matrix<Int>(
repeating: 0,
rows: math.random(1...500),
cols: math.random(1...500)
)
for (i, j) in M
{
if math.random(0.0...1.0) <= 0.01 { M[i, j] = math.random(1...99) }
}
// Now, convert it to a SparseMatrix
let S = SparseMatrix(M)
// print("Dimension: \(M.rows)x\(M.cols)")
// print("Sparse kbit: \(S.bitWidth / 1000)")
// print("Normal kbit: \(M.bitWidth / 1000)")
// let ratio = String(format: "%.1f", Double(M.bitWidth) / Double(S.bitWidth))
// print("Matrix needs \(ratio)x more Memory than SparseMatrix")
for (i, j) in M
{
precondition(M[i, j] == S[i, j], "Error: A[\(i), \(j)] != S[\(i), \(j)])")
}
}
}
#endif
|
mit
|
3772d471433c35d3664747c716f99e22
| 24.860465 | 81 | 0.504496 | 2.934037 | false | true | false | false |
nlap/NLSpinner
|
NLSpinner/NLSpinner.swift
|
1
|
4972
|
//
// NLSpinner.swift
// NLSpinner
//
// Created by Nathan Lapierre on 2017-03-13.
//
//
import Foundation
open class NLSpinner : NSView {
private var finColors = [NSColor]()
private var position: Int = 0
private var isFadingOut: Bool = false
private var animationTimer: Timer!
private var startTime : NSDate = NSDate()
//open library properties
open private(set) var isAnimating: Bool = false
open var numberOfFins: Int = 12
open var isDisplayedWhenStopped: Bool = true {
didSet {
self.needsDisplay = true
}
}
open var foregroundColor: NSColor! = NSColor.black
open var backgroundColor: NSColor! = NSColor.clear
open var tickDelay: Double = 0.05
open var frameTime: Double = 0.032 //30FPS Default (0.032 seconds/frame)
required public init?(coder: NSCoder) {
super.init(coder: coder)
for _ in 0..<numberOfFins {
finColors.append(foregroundColor)
}
}
override open func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
//check if we need to show at all
if (!isAnimating && !isDisplayedWhenStopped) {
NSColor.clear.set()
NSBezierPath.fill(self.bounds)
} else {
var maxSize: CGFloat = bounds.size.height
if bounds.size.width <= maxSize {
maxSize = bounds.size.width
}
backgroundColor.set()
NSBezierPath.fill(self.bounds)
let currentContext: CGContext = NSGraphicsContext.current!.cgContext
NSGraphicsContext.saveGraphicsState()
//draw fins
currentContext.translateBy(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
let path = NSBezierPath()
path.lineWidth = CGFloat(0.07 * maxSize)
path.lineCapStyle = NSBezierPath.LineCapStyle.round
path.move(to: NSMakePoint(0, CGFloat(0.25 * maxSize)))
path.line(to: NSMakePoint(0, CGFloat(0.45 * maxSize)))
for i in 0..<finColors.count {
if self.isAnimating {
finColors[i].set()
}
else {
foregroundColor.withAlphaComponent(CGFloat(0.2)).set()
}
path.stroke()
currentContext.rotate(by: CGFloat(Double.pi * 2 / Double(finColors.count)))
}
NSGraphicsContext.restoreGraphicsState()
}
}
open func startAnimation() {
if self.isAnimating && !isFadingOut {
return
}
startTime = NSDate()
self.startAnimationTimer()
}
open func stopAnimation() {
isFadingOut = true
}
//update animation
@objc func updateFrame(_ timer: Timer) {
//move position every tickDelay seconds
if (startTime.timeIntervalSinceNow <= 0 - abs(tickDelay)) {
if position > 0 {
position -= 1
}
else {
position = finColors.count - 1
}
startTime = NSDate()
}
//fade trailing fins
let minAlpha: CGFloat = CGFloat(0.2)
for i in 0..<finColors.count {
var newAlpha: CGFloat = finColors[i].alphaComponent
newAlpha *= CGFloat(0.9) // fade by this amount
if newAlpha < minAlpha {
newAlpha = minAlpha
}
finColors[i] = foregroundColor.withAlphaComponent(newAlpha)
}
//is whole spinner fading out?
if isFadingOut {
var done: Bool = true
for i in 0..<finColors.count {
if abs(finColors[i].alphaComponent - minAlpha) > 0.01 && isDisplayedWhenStopped {
done = false
break
}
}
if done {
self.stopAnimationTimer()
}
} else {
finColors[position] = foregroundColor
}
self.needsDisplay = true
}
private func startAnimationTimer() {
stopAnimationTimer()
isAnimating = true
isFadingOut = false
position = 1
animationTimer = Timer(timeInterval: frameTime, target: self, selector: #selector(self.updateFrame), userInfo: nil, repeats: true)
RunLoop.current.add(animationTimer, forMode: RunLoop.Mode.common)
RunLoop.current.add(animationTimer, forMode: RunLoop.Mode.default)
RunLoop.current.add(animationTimer, forMode: RunLoop.Mode.eventTracking)
}
private func stopAnimationTimer() {
self.isAnimating = false
isFadingOut = false
if animationTimer != nil {
// we were using timer-based animation
animationTimer.invalidate()
animationTimer = nil
}
}
}
|
mit
|
7ab38cac824c713bca9e9c604fa5d13d
| 31.077419 | 138 | 0.553298 | 4.908193 | false | false | false | false |
mozilla/focus
|
Blockzilla/SettingsViewController.swift
|
3
|
36153
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SnapKit
import UIKit
import Telemetry
import LocalAuthentication
import Intents
import IntentsUI
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIConstants.colors.cellSelected
selectedBackgroundView = backgroundColorView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func setupDynamicFont(forLabels labels: [UILabel], addObserver: Bool = false) {
for label in labels {
label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
label.adjustsFontForContentSizeCategory = true
}
NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { _ in
self.setupDynamicFont(forLabels: labels)
}
}
}
class SettingsTableViewAccessoryCell: SettingsTableViewCell {
private let newLabel = SmartLabel()
let accessoryLabel = SmartLabel()
private let spacerView = UIView()
var accessoryLabelText: String? {
get { return accessoryLabel.text }
set {
accessoryLabel.text = newValue
accessoryLabel.sizeToFit()
}
}
var labelText: String? {
get { return newLabel.text }
set {
newLabel.text = newValue
newLabel.sizeToFit()
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupDynamicFont(forLabels: [newLabel, accessoryLabel], addObserver: true)
newLabel.numberOfLines = 0
newLabel.lineBreakMode = .byWordWrapping
contentView.addSubview(accessoryLabel)
contentView.addSubview(newLabel)
contentView.addSubview(spacerView)
newLabel.textColor = UIConstants.colors.settingsTextLabel
accessoryLabel.textColor = UIConstants.colors.settingsDetailLabel
accessoryType = .disclosureIndicator
accessoryLabel.setContentHuggingPriority(.required, for: .horizontal)
accessoryLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
accessoryLabel.snp.makeConstraints { make in
make.trailing.centerY.equalToSuperview()
}
newLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
newLabel.setContentCompressionResistancePriority(.required, for: .vertical)
spacerView.snp.makeConstraints { make in
make.top.bottom.leading.equalToSuperview()
make.width.equalTo(UIConstants.layout.settingsFirstTitleOffset)
}
newLabel.snp.makeConstraints { make in
make.leading.equalTo(spacerView.snp.trailing)
make.top.equalToSuperview().offset(11)
make.bottom.equalToSuperview().offset(-11)
make.trailing.equalTo(accessoryLabel.snp.leading).offset(-10)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SettingsTableViewToggleCell: SettingsTableViewCell {
private let newLabel = SmartLabel()
private let newDetailLabel = SmartLabel()
private let spacerView = UIView()
var navigationController: UINavigationController?
init(style: UITableViewCell.CellStyle, reuseIdentifier: String?, toggle: BlockerToggle) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupDynamicFont(forLabels: [newLabel, newDetailLabel], addObserver: true)
newLabel.numberOfLines = 0
newLabel.text = toggle.label
textLabel?.numberOfLines = 0
textLabel?.text = toggle.label
newDetailLabel.numberOfLines = 0
detailTextLabel?.numberOfLines = 0
detailTextLabel?.text = toggle.subtitle
backgroundColor = UIConstants.colors.cellBackground
newLabel.textColor = UIConstants.colors.settingsTextLabel
textLabel?.textColor = UIConstants.colors.settingsTextLabel
layoutMargins = UIEdgeInsets.zero
newDetailLabel.textColor = UIConstants.colors.settingsDetailLabel
detailTextLabel?.textColor = UIConstants.colors.settingsDetailLabel
accessoryView = PaddedSwitch(switchView: toggle.toggle)
selectionStyle = .none
// Add "Learn More" button recognition
if toggle.label == UIConstants.strings.labelSendAnonymousUsageData || toggle.label == UIConstants.strings.settingsSearchSuggestions {
addSubview(newLabel)
addSubview(newDetailLabel)
addSubview(spacerView)
textLabel?.isHidden = true
let selector = toggle.label == UIConstants.strings.labelSendAnonymousUsageData ? #selector(tappedLearnMoreFooter) : #selector(tappedLearnMoreSearchSuggestionsFooter)
let learnMoreButton = UIButton()
learnMoreButton.setTitle(UIConstants.strings.learnMore, for: .normal)
learnMoreButton.setTitleColor(UIConstants.colors.settingsLink, for: .normal)
if let cellFont = detailTextLabel?.font {
learnMoreButton.titleLabel?.font = UIFont(name: cellFont.fontName, size: cellFont.pointSize)
}
let tapGesture = UITapGestureRecognizer(target: self, action: selector)
learnMoreButton.addGestureRecognizer(tapGesture)
addSubview(learnMoreButton)
// Adjust the offsets to allow the buton to fit
spacerView.snp.makeConstraints { make in
make.top.bottom.leading.equalToSuperview()
make.trailing.equalTo(textLabel!.snp.leading)
}
newLabel.snp.makeConstraints { make in
make.leading.equalTo(spacerView.snp.trailing)
make.top.equalToSuperview().offset(8)
}
learnMoreButton.snp.makeConstraints { make in
make.leading.equalTo(spacerView.snp.trailing)
make.bottom.equalToSuperview().offset(4)
}
newDetailLabel.snp.makeConstraints { make in
let lineHeight = newLabel.font.lineHeight
make.top.equalToSuperview().offset(10 + lineHeight)
make.leading.equalTo(spacerView.snp.trailing)
make.trailing.equalTo(contentView)
if let learnMoreHeight = learnMoreButton.titleLabel?.font.lineHeight {
make.bottom.equalToSuperview().offset(-8 - learnMoreHeight)
}
}
newLabel.setupShrinkage()
newDetailLabel.setupShrinkage()
}
}
private func tappedFooter(topic: String) {
guard let url = SupportUtils.URLForTopic(topic: topic) else { return }
let contentViewController = SettingsContentViewController(url: url)
navigationController?.pushViewController(contentViewController, animated: true)
}
@objc func tappedLearnMoreFooter(gestureRecognizer: UIGestureRecognizer) {
tappedFooter(topic: UIConstants.strings.sumoTopicUsageData)
}
@objc func tappedLearnMoreSearchSuggestionsFooter(gestureRecognizer: UIGestureRecognizer) {
tappedFooter(topic: UIConstants.strings.sumoTopicSearchSuggestion)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
enum Section: String {
case privacy, search, siri, integration, mozilla
var numberOfRows: Int {
switch self {
case .privacy:
if BiometryType(context: LAContext()).hasBiometry { return 4 }
return 3
case .search: return 3
case .siri: return 3
case .integration: return 1
case .mozilla:
// Show tips option should not be displayed for users that do not see tips
return TipManager.shared.shouldShowTips() ? 3 : 2
}
}
var headerText: String? {
switch self {
case .privacy: return UIConstants.strings.toggleSectionPrivacy
case .search: return UIConstants.strings.settingsSearchTitle
case .siri: return UIConstants.strings.siriShortcutsTitle
case .integration: return UIConstants.strings.toggleSectionSafari
case .mozilla: return UIConstants.strings.toggleSectionMozilla
}
}
static func getSections() -> [Section] {
if #available(iOS 12.0, *) {
return [.privacy, .search, .siri, integration, .mozilla]
} else {
return [.privacy, .search, integration, .mozilla]
}
}
}
enum BiometryType {
enum Status {
case hasIdentities
case hasNoIdentities
init(_ hasIdentities: Bool) {
self = hasIdentities ? .hasIdentities : .hasNoIdentities
}
}
case faceID(Status), touchID(Status), none
private static let NO_IDENTITY_ERROR = -7
var hasBiometry: Bool {
switch self {
case .touchID, .faceID: return true
case .none: return false
}
}
var hasIdentities: Bool {
switch self {
case .touchID(Status.hasIdentities), .faceID(Status.hasIdentities): return true
default: return false
}
}
init(context: LAContext) {
var biometricError: NSError?
guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &biometricError) else { self = .none; return }
let status = Status(biometricError.map({ $0.code != BiometryType.NO_IDENTITY_ERROR }) ?? true)
switch context.biometryType {
case .faceID: self = .faceID(status)
case .touchID: self = .touchID(status)
case .none: self = .none
}
}
}
private let tableView = UITableView(frame: .zero, style: .grouped)
// Hold a strong reference to the block detector so it isn't deallocated
// in the middle of its detection.
private let detector = BlockerEnabledDetector.makeInstance()
private let biometryType = BiometryType(context: LAContext())
private var isSafariEnabled = false
private let searchEngineManager: SearchEngineManager
private var highlightsButton: UIBarButtonItem?
private let whatsNew: WhatsNewDelegate
private lazy var sections = {
Section.getSections()
}()
private var toggles = [Int: [Int: BlockerToggle]]()
private func getSectionIndex(_ section: Section) -> Int? {
return Section.getSections().index(where: { $0 == section })
}
private func initializeToggles() {
let blockFontsToggle = BlockerToggle(label: UIConstants.strings.labelBlockFonts, setting: SettingsToggle.blockFonts)
let usageDataSubtitle = String(format: UIConstants.strings.detailTextSendUsageData, AppInfo.productName)
let usageDataToggle = BlockerToggle(label: UIConstants.strings.labelSendAnonymousUsageData, setting: SettingsToggle.sendAnonymousUsageData, subtitle: usageDataSubtitle)
let searchSuggestionSubtitle = String(format: UIConstants.strings.detailTextSearchSuggestion, AppInfo.productName)
let searchSuggestionToggle = BlockerToggle(label: UIConstants.strings.settingsSearchSuggestions, setting: SettingsToggle.enableSearchSuggestions, subtitle: searchSuggestionSubtitle)
let safariToggle = BlockerToggle(label: UIConstants.strings.toggleSafari, setting: SettingsToggle.safari)
let homeScreenTipsToggle = BlockerToggle(label: UIConstants.strings.toggleHomeScreenTips, setting: SettingsToggle.showHomeScreenTips)
if let privacyIndex = getSectionIndex(Section.privacy) {
if let biometricToggle = createBiometricLoginToggleIfAvailable() {
toggles[privacyIndex] = [1: blockFontsToggle, 2: biometricToggle, 3: usageDataToggle]
} else {
toggles[privacyIndex] = [1: blockFontsToggle, 2: usageDataToggle]
}
}
if let searchIndex = getSectionIndex(Section.search) {
toggles[searchIndex] = [2: searchSuggestionToggle]
}
if let integrationIndex = getSectionIndex(Section.integration) {
toggles[integrationIndex] = [0: safariToggle]
}
if let mozillaIndex = getSectionIndex(Section.mozilla) {
toggles[mozillaIndex] = [0: homeScreenTipsToggle]
}
}
/// Used to calculate cell heights.
private lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = PaddedSwitch(switchView: UISwitch())
return cell
}()
private var shouldScrollToSiri: Bool
init(searchEngineManager: SearchEngineManager, whatsNew: WhatsNewDelegate, shouldScrollToSiri: Bool = false) {
self.searchEngineManager = searchEngineManager
self.whatsNew = whatsNew
self.shouldScrollToSiri = shouldScrollToSiri
super.init(nibName: nil, bundle: nil)
tableView.register(SettingsTableViewAccessoryCell.self, forCellReuseIdentifier: "accessoryCell")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
view.backgroundColor = UIConstants.colors.background
title = UIConstants.strings.settingsTitle
let navigationBar = navigationController!.navigationBar
navigationBar.isTranslucent = false
navigationBar.barTintColor = UIConstants.colors.settingsNavBar
navigationBar.tintColor = UIConstants.colors.navigationButton
navigationBar.titleTextAttributes = [.foregroundColor: UIConstants.colors.navigationTitle]
let navBarBorderRect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 0.25)
let imageRenderer = UIGraphicsImageRenderer(bounds: navBarBorderRect)
let borderImage = imageRenderer.image(actions: { (context) in
UIConstants.colors.settingsNavBorder.setFill()
context.cgContext.fill(navBarBorderRect)
})
navigationController?.navigationBar.shadowImage = borderImage
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSettings))
doneButton.tintColor = UIConstants.Photon.Magenta40
doneButton.accessibilityIdentifier = "SettingsViewController.doneButton"
navigationItem.leftBarButtonItem = doneButton
highlightsButton = UIBarButtonItem(title: UIConstants.strings.whatsNewTitle, style: .plain, target: self, action: #selector(whatsNewClicked))
highlightsButton?.image = UIImage(named: "highlight")
highlightsButton?.accessibilityIdentifier = "SettingsViewController.whatsNewButton"
navigationItem.rightBarButtonItem = highlightsButton
if whatsNew.shouldShowWhatsNew() {
highlightsButton?.tintColor = UIConstants.colors.whatsNew
}
view.addSubview(tableView)
tableView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIConstants.colors.background
tableView.layoutMargins = UIEdgeInsets.zero
tableView.separatorColor = UIConstants.colors.settingsSeparator
tableView.allowsSelection = true
tableView.estimatedRowHeight = 44
initializeToggles()
for (sectionIndex, toggleArray) in toggles {
for (cellIndex, blockerToggle) in toggleArray {
let toggle = blockerToggle.toggle
toggle.onTintColor = UIConstants.colors.toggleOn
toggle.addTarget(self, action: #selector(toggleSwitched(_:)), for: .valueChanged)
toggle.isOn = Settings.getToggle(blockerToggle.setting)
toggles[sectionIndex]?[cellIndex] = blockerToggle
}
}
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateSafariEnabledState()
tableView.reloadData()
if shouldScrollToSiri {
guard let siriSection = getSectionIndex(Section.siri) else {
shouldScrollToSiri = false
return
}
let siriIndexPath = IndexPath(row: 0, section: siriSection)
tableView.scrollToRow(at: siriIndexPath, at: .none, animated: false)
shouldScrollToSiri = false
}
}
@objc private func applicationDidBecomeActive() {
// On iOS 9, we detect the blocker status by loading an invisible SafariViewController
// in the current view. We can only run the detector if the view is visible; otherwise,
// the detection callback won't fire and the detector won't be cleaned up.
if isViewLoaded && view.window != nil {
updateSafariEnabledState()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
private func createBiometricLoginToggleIfAvailable() -> BlockerToggle? {
guard biometryType.hasBiometry else { return nil }
let label: String
let subtitle: String
switch biometryType {
case .faceID:
label = UIConstants.strings.labelFaceIDLogin
subtitle = String(format: UIConstants.strings.labelFaceIDLoginDescription, AppInfo.productName)
case .touchID:
label = UIConstants.strings.labelTouchIDLogin
subtitle = String(format: UIConstants.strings.labelTouchIDLoginDescription, AppInfo.productName)
default:
// Unknown biometric type
return nil
}
let toggle = BlockerToggle(label: label, setting: SettingsToggle.biometricLogin, subtitle: subtitle)
toggle.toggle.isEnabled = biometryType.hasIdentities
return toggle
}
private func toggleForIndexPath(_ indexPath: IndexPath) -> BlockerToggle {
guard let toggle = toggles[indexPath.section]?[indexPath.row]
else { return BlockerToggle(label: "Error", setting: SettingsToggle.blockAds)}
return toggle
}
private func setupToggleCell(indexPath: IndexPath, navigationController: UINavigationController?) -> SettingsTableViewToggleCell {
let toggle = toggleForIndexPath(indexPath)
let cell = SettingsTableViewToggleCell(style: .subtitle, reuseIdentifier: "toggleCell", toggle: toggle)
cell.navigationController = navigationController
return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell
switch sections[indexPath.section] {
case .privacy:
if indexPath.row == 0 {
cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "trackingCell")
cell.textLabel?.text = String(format: UIConstants.strings.trackingProtectionLabel)
cell.accessibilityIdentifier = "settingsViewController.trackingCell"
cell.accessoryType = .disclosureIndicator
} else {
cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController)
}
case .search:
if indexPath.row < 2 {
guard let searchCell = tableView.dequeueReusableCell(withIdentifier: "accessoryCell") as? SettingsTableViewAccessoryCell else { fatalError("Accessory cells do not exist") }
let autocompleteLabel = Settings.getToggle(.enableDomainAutocomplete) || Settings.getToggle(.enableCustomDomainAutocomplete) ? UIConstants.strings.autocompleteCustomEnabled : UIConstants.strings.autocompleteCustomDisabled
let labels : (label: String, accessoryLabel: String, identifier: String) = indexPath.row == 0 ?
(UIConstants.strings.settingsSearchLabel, searchEngineManager.activeEngine.name, "SettingsViewController.searchCell")
:(UIConstants.strings.settingsAutocompleteSection, autocompleteLabel, "SettingsViewController.autocompleteCell")
searchCell.accessoryLabelText = labels.accessoryLabel
searchCell.labelText = labels.label
searchCell.accessibilityIdentifier = labels.identifier
cell = searchCell
} else {
cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController)
}
case .siri:
guard #available(iOS 12.0, *), let siriCell = tableView.dequeueReusableCell(withIdentifier: "accessoryCell") as? SettingsTableViewAccessoryCell else { fatalError("No accessory cells") }
if indexPath.row == 0 {
siriCell.labelText = UIConstants.strings.eraseSiri
siriCell.accessibilityIdentifier = "settingsViewController.siriEraseCell"
SiriShortcuts().hasAddedActivity(type: .erase) { (result: Bool) in
siriCell.accessoryLabel.text = result ? UIConstants.strings.Edit : UIConstants.strings.addToSiri
}
} else if indexPath.row == 1 {
siriCell.labelText = UIConstants.strings.eraseAndOpenSiri
siriCell.accessibilityIdentifier = "settingsViewController.siriEraseAndOpenCell"
SiriShortcuts().hasAddedActivity(type: .eraseAndOpen) { (result: Bool) in
siriCell.accessoryLabel.text = result ? UIConstants.strings.Edit : UIConstants.strings.addToSiri
}
} else {
siriCell.labelText = UIConstants.strings.openUrlSiri
siriCell.accessibilityIdentifier = "settingsViewController.siriOpenURLCell"
SiriShortcuts().hasAddedActivity(type: .openURL) { (result: Bool) in
siriCell.accessoryLabel.text = result ? UIConstants.strings.Edit : UIConstants.strings.add
}
}
cell = siriCell
case .mozilla where TipManager.shared.shouldShowTips():
if indexPath.row == 0 {
cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController)
} else if indexPath.row == 1 {
cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "aboutCell")
cell.textLabel?.text = String(format: UIConstants.strings.aboutTitle, AppInfo.productName)
cell.accessibilityIdentifier = "settingsViewController.about"
} else {
cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "ratingCell")
cell.textLabel?.text = String(format: UIConstants.strings.ratingSetting, AppInfo.productName)
cell.accessibilityIdentifier = "settingsViewController.rateFocus"
}
case .mozilla where !TipManager.shared.shouldShowTips():
if indexPath.row == 0 {
cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "aboutCell")
cell.textLabel?.text = String(format: UIConstants.strings.aboutTitle, AppInfo.productName)
cell.accessibilityIdentifier = "settingsViewController.about"
} else {
cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "ratingCell")
cell.textLabel?.text = String(format: UIConstants.strings.ratingSetting, AppInfo.productName)
cell.accessibilityIdentifier = "settingsViewController.rateFocus"
}
default:
cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController)
}
cell.backgroundColor = UIConstants.colors.cellBackground
cell.textLabel?.textColor = UIConstants.colors.settingsTextLabel
cell.layoutMargins = UIEdgeInsets.zero
cell.detailTextLabel?.textColor = UIConstants.colors.settingsDetailLabel
cell.textLabel?.setupShrinkage()
cell.detailTextLabel?.setupShrinkage()
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].numberOfRows
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Height for the Search Engine and Learn More row.
if indexPath.section == 5 ||
(indexPath.section == 4 && indexPath.row >= 1) {
return 44
}
// We have to manually calculate the cell height since UITableViewCell doesn't correctly
// layout multiline detailTextLabels.
let toggle = toggleForIndexPath(indexPath)
let tableWidth = tableView.frame.width
let accessoryWidth = dummyToggleCell.accessoryView!.frame.width
let insetsWidth = 2 * tableView.separatorInset.left
let width = tableWidth - accessoryWidth - insetsWidth
var height = heightForLabel(dummyToggleCell.textLabel!, width: width, text: toggle.label)
if let subtitle = toggle.subtitle {
height += heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: subtitle)
if toggle.label == UIConstants.strings.labelSendAnonymousUsageData ||
toggle.label == UIConstants.strings.settingsSearchSuggestions {
height += 10
}
}
return height + 22
}
private func heightForLabel(_ label: UILabel, width: CGFloat, text: String) -> CGFloat {
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs: [NSAttributedString.Key: Any] = [.font: label.font]
let boundingRect = NSString(string: text).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var groupingOffset = UIConstants.layout.settingsDefaultTitleOffset
if sections[section] == .privacy {
groupingOffset = UIConstants.layout.settingsFirstTitleOffset
}
// Hack: We want the header view's margin to match the cells, so we create an empty
// cell with a blank space as text to layout the text label. From there, we can define
// constraints for our custom label based on the cell's label.
let cell = UITableViewCell()
cell.textLabel?.text = " "
cell.backgroundColor = UIConstants.colors.background
let label = SmartLabel()
label.text = sections[section].headerText
label.textColor = UIConstants.colors.tableSectionHeader
label.font = UIConstants.fonts.tableSectionHeader
cell.contentView.addSubview(label)
label.snp.makeConstraints { make in
make.leading.trailing.equalTo(cell.textLabel!)
make.centerY.equalTo(cell.textLabel!).offset(groupingOffset)
}
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sections[section] == .privacy ? 50 : 30
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch sections[indexPath.section] {
case .privacy:
if indexPath.row == 0 {
let trackingProtectionVC = TrackingProtectionViewController()
navigationController?.pushViewController(trackingProtectionVC, animated: true)
}
case .search:
if indexPath.row == 0 {
let searchSettingsViewController = SearchSettingsViewController(searchEngineManager: searchEngineManager)
searchSettingsViewController.delegate = self
navigationController?.pushViewController(searchSettingsViewController, animated: true)
} else if indexPath.row == 1 {
let autcompleteSettingViewController = AutocompleteSettingViewController()
navigationController?.pushViewController(autcompleteSettingViewController, animated: true)
}
case .siri:
guard #available(iOS 12.0, *) else { return }
if indexPath.row == 0 {
SiriShortcuts().manageSiri(for: SiriShortcuts.activityType.erase, in: self)
UserDefaults.standard.set(false, forKey: TipManager.TipKey.siriEraseTip)
} else if indexPath.row == 1 {
SiriShortcuts().manageSiri(for: SiriShortcuts.activityType.eraseAndOpen, in: self)
UserDefaults.standard.set(false, forKey: TipManager.TipKey.siriEraseTip)
} else {
let siriFavoriteVC = SiriFavoriteViewController()
navigationController?.pushViewController(siriFavoriteVC, animated: true)
}
case .mozilla where TipManager.shared.shouldShowTips():
if indexPath.row == 1 {
aboutClicked()
} else if indexPath.row == 2 {
let appId = AppInfo.config.appId
if let reviewURL = URL(string: "https://itunes.apple.com/app/id\(appId)?action=write-review"), UIApplication.shared.canOpenURL(reviewURL) {
UIApplication.shared.open(reviewURL, options: [:], completionHandler: nil)
}
}
case .mozilla where !TipManager.shared.shouldShowTips():
if indexPath.row == 0 {
aboutClicked()
} else if indexPath.row == 1 {
let appId = AppInfo.config.appId
if let reviewURL = URL(string: "https://itunes.apple.com/app/id\(appId)?action=write-review"), UIApplication.shared.canOpenURL(reviewURL) {
UIApplication.shared.open(reviewURL, options: [:], completionHandler: nil)
}
}
default: break
}
}
private func updateSafariEnabledState() {
guard let index = getSectionIndex(Section.integration),
let safariToggle = toggles[index]?[0]?.toggle else { return }
safariToggle.isEnabled = false
detector.detectEnabled(view) { [weak self] enabled in
safariToggle.isOn = enabled && Settings.getToggle(.safari)
safariToggle.isEnabled = true
self?.isSafariEnabled = enabled
}
}
@objc private func dismissSettings() {
self.dismiss(animated: true, completion: nil)
}
@objc private func aboutClicked() {
navigationController!.pushViewController(AboutViewController(), animated: true)
}
@objc private func whatsNewClicked() {
highlightsButton?.tintColor = UIColor.white
guard let focusURL = SupportUtils.URLForTopic(topic: UIConstants.strings.sumoTopicWhatsNew) else { return }
guard let klarURL = SupportUtils.URLForTopic(topic: UIConstants.strings.klarSumoTopicWhatsNew) else { return }
if AppInfo.isKlar {
navigationController?.pushViewController(SettingsContentViewController(url: klarURL), animated: true)
} else {
navigationController?.pushViewController(SettingsContentViewController(url: focusURL), animated: true)
}
whatsNew.didShowWhatsNew()
}
@objc private func toggleSwitched(_ sender: UISwitch) {
let toggle = toggles.values.filter { $0.values.filter { $0.toggle == sender } != []}[0].values.filter { $0.toggle == sender }[0]
func updateSetting() {
let telemetryEvent = TelemetryEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.change, object: "setting", value: toggle.setting.rawValue)
telemetryEvent.addExtra(key: "to", value: sender.isOn)
Telemetry.default.recordEvent(telemetryEvent)
Settings.set(sender.isOn, forToggle: toggle.setting)
ContentBlockerHelper.shared.reload()
Utils.reloadSafariContentBlocker()
}
// First check if the user changed the anonymous usage data setting and follow that choice right
// here. Otherwise it will be delayed until the application restarts.
if toggle.setting == .sendAnonymousUsageData {
Telemetry.default.configuration.isCollectionEnabled = sender.isOn
Telemetry.default.configuration.isUploadEnabled = sender.isOn
} else if toggle.setting == .biometricLogin {
UserDefaults.standard.set(false, forKey: TipManager.TipKey.biometricTip)
}
switch toggle.setting {
case .safari where sender.isOn && !isSafariEnabled:
let instructionsViewController = SafariInstructionsViewController()
navigationController!.pushViewController(instructionsViewController, animated: true)
updateSetting()
case .enableSearchSuggestions:
UserDefaults.standard.set(true, forKey: SearchSuggestionsPromptView.respondedToSearchSuggestionsPrompt)
updateSetting()
case .showHomeScreenTips:
updateSetting()
// This update must occur after the setting has been updated to properly take effect.
if let browserViewController = presentingViewController as? BrowserViewController {
browserViewController.refreshTipsDisplay()
}
default:
updateSetting()
}
}
}
extension SettingsViewController: SearchSettingsViewControllerDelegate {
func searchSettingsViewController(_ searchSettingsViewController: SearchSettingsViewController, didSelectEngine engine: SearchEngine) {
(tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? SettingsTableViewAccessoryCell)?.accessoryLabelText = engine.name
}
}
extension SettingsViewController: INUIAddVoiceShortcutViewControllerDelegate {
@available(iOS 12.0, *)
func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
@available(iOS 12.0, *)
func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
@available(iOS 12.0, *)
extension SettingsViewController: INUIEditVoiceShortcutViewControllerDelegate {
func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID) {
controller.dismiss(animated: true, completion: nil)
}
func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
|
mpl-2.0
|
ae27006c772ad8f5dc1aea489984be84
| 44.821293 | 237 | 0.671148 | 5.404844 | false | false | false | false |
ryuichis/swift-ast
|
Sources/Parser/Parser+Lexing.swift
|
2
|
2337
|
/*
Copyright 2017-2018 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Source
import AST
import Lexer
extension Parser {
func assert(_ cond: Bool, orFatal fatalError: ParserErrorKind) throws {
guard cond else { throw _raiseFatal(fatalError) }
}
func assert(_ cond: Bool, orError error: ParserErrorKind) throws {
if !cond { try _raiseError(error) }
}
func match(_ kinds: [Token.Kind], exactMatch: Bool = false, orFatal fatalError: ParserErrorKind) throws {
try assert(_lexer.match(kinds, exactMatch: exactMatch), orFatal: fatalError)
}
func match(_ kind: Token.Kind, exactMatch: Bool = false, orFatal fatalError: ParserErrorKind) throws {
try match([kind], exactMatch: exactMatch, orFatal: fatalError)
}
func readIdentifier(_ id: String, orFatal fatalError: ParserErrorKind) throws {
try assert(_lexer.read(.dummyIdentifier) == .identifier(id, false), orFatal: fatalError)
}
func readNamedIdentifier() -> Identifier? {
guard let s = _lexer.look().kind.namedIdentifier else {
return nil
}
_lexer.advance()
return s.id
}
func readNamedIdentifierOrWildcard() -> Identifier? {
guard let s = _lexer.look().kind.namedIdentifierOrWildcard else {
return nil
}
_lexer.advance()
return s.id
}
@discardableResult func readUntilEOL() -> String {
var str = ""
while let scalar = _lexer.lookUnicodeScalar() {
guard scalar != "\n" else { return str }
_lexer.advanceChar()
str += String(scalar)
}
return str
}
}
extension NamedIdentifier {
var id: Identifier {
switch self {
case .name(let n): return .name(n)
case .backtickedName(let n): return .backtickedName(n)
case .wildcard: return .wildcard
}
}
}
|
apache-2.0
|
5d787aee9950de77ecbb355c49114d0f
| 28.961538 | 107 | 0.694908 | 4.107206 | false | false | false | false |
Egibide-DAM/swift
|
02_ejemplos/06_tipos_personalizados/03_propiedades/04_propiedades_calculadas.playground/Contents.swift
|
1
|
777
|
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")
|
apache-2.0
|
958ce1ddbc753a778f5833042104afd5
| 23.28125 | 73 | 0.531532 | 3.133065 | false | false | false | false |
ktatroe/MPA-Horatio
|
Horatio/Horatio/Classes/Operations/TimeoutObserver.swift
|
2
|
1758
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows how to implement the OperationObserver protocol.
*/
import Foundation
/**
`TimeoutObserver` is a way to make an `Operation` automatically time out and
cancel after a specified time interval.
*/
public struct TimeoutObserver: OperationObserver {
// MARK: Properties
static let timeoutKey = "Timeout"
fileprivate let timeout: TimeInterval
// MARK: Initialization
public init(timeout: TimeInterval) {
self.timeout = timeout
}
// MARK: OperationObserver
public func operationDidStart(_ operation: Operation) {
// When the operation starts, queue up a block to cause it to time out.
let when = DispatchTime.now() + Double(Int64(timeout * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
weak var operation = operation
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).asyncAfter(deadline: when) {
guard let operation = operation else { return }
/*
Cancel the operation if it hasn't finished and hasn't already
been cancelled.
*/
if !operation.isFinished && !operation.isCancelled {
let error = NSError(code: .executionFailed, userInfo: [
type(of: self).timeoutKey: self.timeout
])
operation.cancelWithError(error)
}
}
}
public func operation(_ operation: Operation, didProduceOperation newOperation: Foundation.Operation) {
// No op.
}
public func operationDidFinish(_ operation: Operation, errors: [Error]) {
// No op.
}
}
|
mit
|
570299f143df5c233ee4d9d7acb44f63
| 28.762712 | 108 | 0.638383 | 4.918768 | false | false | false | false |
hfutrell/BezierKit
|
BezierKit/BezierKitTests/BezierCurveTests.swift
|
1
|
17833
|
//
// BezierCurveTests.swift
// BezierKit
//
// Created by Holmes Futrell on 12/31/17.
// Copyright © 2017 Holmes Futrell. All rights reserved.
//
import XCTest
@testable import BezierKit
class BezierCurveTests: 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 testEquality() {
// two lines that are equal
let l1: BezierCurve = LineSegment(p0: CGPoint(x: 0, y: 1), p1: CGPoint(x: 2, y: 1))
let l2: BezierCurve = LineSegment(p0: CGPoint(x: 0, y: 1), p1: CGPoint(x: 2, y: 1))
XCTAssert(l1 == l2)
// a line that isn't equal
let l3: BezierCurve = LineSegment(p0: CGPoint(x: 0, y: 1), p1: CGPoint(x: 2, y: 2))
XCTAssertFalse(l1 == l3)
// a quadratic made from l1, different order, not equal!
let q1: BezierCurve = QuadraticCurve(lineSegment: l1 as! LineSegment)
XCTAssertFalse(l1 == q1)
}
func testScaleDistance() {
// line segment
let epsilon: CGFloat = 1.0e-5
let l = LineSegment(p0: CGPoint(x: 1.0, y: 2.0), p1: CGPoint(x: 5.0, y: 6.0))
let ls = l.scale(distance: sqrt(2))! // (moves line up and left by 1,1)
let expectedLine = LineSegment(p0: CGPoint(x: 0.0, y: 3.0), p1: CGPoint(x: 4.0, y: 7.0))
XCTAssert(BezierKitTestHelpers.curveControlPointsEqual(curve1: ls, curve2: expectedLine, tolerance: epsilon))
// quadratic
let q = QuadraticCurve(p0: CGPoint(x: 1.0, y: 1.0),
p1: CGPoint(x: 2.0, y: 2.0),
p2: CGPoint(x: 3.0, y: 1.0))
let qs = q.scale(distance: sqrt(2))!
let expectedQuadratic = QuadraticCurve(p0: CGPoint(x: 0.0, y: 2.0),
p1: CGPoint(x: 2.0, y: 4.0),
p2: CGPoint(x: 4.0, y: 2.0))
XCTAssert(BezierKitTestHelpers.curveControlPointsEqual(curve1: qs, curve2: expectedQuadratic, tolerance: epsilon))
// cubic
let c = CubicCurve(p0: CGPoint(x: -4.0, y: +0.0),
p1: CGPoint(x: -2.0, y: +2.0),
p2: CGPoint(x: +2.0, y: +2.0),
p3: CGPoint(x: +4.0, y: +0.0))
let cs = c.scale(distance: 2.0 * sqrt(2))!
let expectedCubic = CubicCurve(p0: CGPoint(x: -6.0, y: +2.0),
p1: CGPoint(x: -3.0, y: +5.0),
p2: CGPoint(x: +3.0, y: +5.0),
p3: CGPoint(x: +6.0, y: +2.0))
XCTAssert(BezierKitTestHelpers.curveControlPointsEqual(curve1: cs, curve2: expectedCubic, tolerance: epsilon))
// ensure that scaling a cubic initialized from a line yields the same thing as the line
let cFromLine = CubicCurve(lineSegment: l)
XCTAssert(BezierKitTestHelpers.curveControlPointsEqual(curve1: cFromLine.scale(distance: sqrt(2))!, curve2: CubicCurve(lineSegment: expectedLine), tolerance: epsilon))
// ensure scaling a quadratic from a line yields the same thing as the line
let qFromLine = QuadraticCurve(lineSegment: l)
XCTAssert(BezierKitTestHelpers.curveControlPointsEqual(curve1: qFromLine.scale(distance: sqrt(2))!,
curve2: QuadraticCurve(lineSegment: expectedLine),
tolerance: epsilon))
}
func testScaleDistanceDegenerate() {
let p = CGPoint(x: 3.14159, y: 2.71828)
let curve = CubicCurve(p0: p, p1: p, p2: p, p3: p)
XCTAssertNil(curve.scale(distance: 2))
}
func testScaleDistanceEdgeCase() {
let a = CGPoint(x: 0, y: 0)
let b = CGPoint(x: 1, y: 0)
let cubic = CubicCurve(p0: a, p1: a, p2: b, p3: b)
let result = cubic.scale(distance: 1)
let offset = CGPoint(x: 0, y: 1)
let aOffset = a + offset
let bOffset = b + offset
let expectedResult = CubicCurve(p0: aOffset, p1: aOffset, p2: bOffset, p3: bOffset)
XCTAssertEqual(result, expectedResult)
}
func testOffsetDistance() {
// line segments (or isLinear) have a separate codepath, so be sure to test those
let epsilon: CGFloat = 1.0e-6
let c1 = CubicCurve(lineSegment: LineSegment(p0: CGPoint(x: 0.0, y: 0.0), p1: CGPoint(x: 1.0, y: 1.0)))
let c1Offset = c1.offset(distance: sqrt(2))
let expectedOffset1 = CubicCurve(lineSegment: LineSegment(p0: CGPoint(x: -1.0, y: 1.0), p1: CGPoint(x: 0.0, y: 2.0)))
XCTAssertEqual(c1Offset.count, 1)
XCTAssert(BezierKitTestHelpers.curveControlPointsEqual(curve1: c1Offset[0] as! CubicCurve, curve2: expectedOffset1, tolerance: epsilon))
// next test a non-simple curve
let c2 = CubicCurve(p0: CGPoint(x: 1.0, y: 1.0), p1: CGPoint(x: 2.0, y: 2.0), p2: CGPoint(x: 3.0, y: 2.0), p3: CGPoint(x: 4.0, y: 1.0))
let c2Offset = c2.offset(distance: sqrt(2))
for i in 0..<c2Offset.count {
let c = c2Offset[i]
XCTAssert(c.simple)
if i == 0 {
// segment starts where un-reduced segment started (after ofsetting)
XCTAssert(distance(c.startingPoint, CGPoint(x: 0.0, y: 2.0)) < epsilon)
} else {
// segment starts where last ended
XCTAssertEqual(c.startingPoint, c2Offset[i-1].endingPoint)
}
if i == c2Offset.count - 1 {
// segment ends where un-reduced segment ended (after ofsetting)
XCTAssert(distance(c.endingPoint, CGPoint(x: 5.0, y: 2.0)) < epsilon)
}
}
}
func testOffsetTimeDistance() {
let epsilon: CGFloat = 1.0e-6
let q = QuadraticCurve(p0: CGPoint(x: 1.0, y: 1.0),
p1: CGPoint(x: 2.0, y: 2.0),
p2: CGPoint(x: 3.0, y: 1.0))
let p0 = q.offset(t: 0.0, distance: sqrt(2))
let p1 = q.offset(t: 0.5, distance: 1.5)
let p2 = q.offset(t: 1.0, distance: sqrt(2))
XCTAssert(distance(p0, CGPoint(x: 0.0, y: 2.0)) < epsilon)
XCTAssert(distance(p1, CGPoint(x: 2.0, y: 3.0)) < epsilon)
XCTAssert(distance(p2, CGPoint(x: 4.0, y: 2.0)) < epsilon)
}
static let lineSegmentForOutlining = LineSegment(p0: CGPoint(x: -10, y: -5), p1: CGPoint(x: 20, y: 10))
// swiftlint:disable large_tuple
private func lineOffsets(_ lineSegment: LineSegment, _ d1: CGFloat, _ d2: CGFloat, _ d3: CGFloat, _ d4: CGFloat) -> (CGPoint, CGPoint, CGPoint, CGPoint) {
let o0 = lineSegment.startingPoint + d1 * lineSegment.normal(at: 0)
let o1 = lineSegment.endingPoint + d3 * lineSegment.normal(at: 1)
let o2 = lineSegment.endingPoint - d4 * lineSegment.normal(at: 1)
let o3 = lineSegment.startingPoint - d2 * lineSegment.normal(at: 0)
return (o0, o1, o2, o3)
}
// swiftlint:enable large_tuple
func testOutlineDistance() {
// When only one distance value is given, the outline is generated at distance d on both the normal and anti-normal
let lineSegment = BezierCurveTests.lineSegmentForOutlining
let outline: PathComponent = lineSegment.outline(distance: 1)
XCTAssertEqual(outline.numberOfElements, 4)
let (o0, o1, o2, o3) = lineOffsets(lineSegment, 1, 1, 1, 1)
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 0), matchesCurve: LineSegment(p0: o3, p1: o0)))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 1), matchesCurve: LineSegment(p0: o0, p1: o1)))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 2), matchesCurve: LineSegment(p0: o1, p1: o2)))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 3), matchesCurve: LineSegment(p0: o2, p1: o3)))
}
func testOutlineDistanceAlongNormalDistanceOppositeNormal() {
// If two distance values are given, the outline is generated at distance d1 on along the normal, and d2 along the anti-normal.
let lineSegment = BezierCurveTests.lineSegmentForOutlining
let distanceAlongNormal: CGFloat = 1
let distanceOppositeNormal: CGFloat = 2
let outline: PathComponent = lineSegment.outline(distanceAlongNormal: distanceAlongNormal, distanceOppositeNormal: distanceOppositeNormal)
XCTAssertEqual(outline.numberOfElements, 4)
let o0 = lineSegment.startingPoint + distanceAlongNormal * lineSegment.normal(at: 0)
let o1 = lineSegment.endingPoint + distanceAlongNormal * lineSegment.normal(at: 1)
let o2 = lineSegment.endingPoint - distanceOppositeNormal * lineSegment.normal(at: 1)
let o3 = lineSegment.startingPoint - distanceOppositeNormal * lineSegment.normal(at: 0)
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 0), matchesCurve: LineSegment(p0: o3, p1: o0)))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 1), matchesCurve: LineSegment(p0: o0, p1: o1)))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 2), matchesCurve: LineSegment(p0: o1, p1: o2)))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 3), matchesCurve: LineSegment(p0: o2, p1: o3)))
}
func testOutlineQuadraticNormalsParallel() {
// this tests a special corner case of outlines where endpoint normals are parallel
let q = QuadraticCurve(p0: CGPoint(x: 0.0, y: 0.0), p1: CGPoint(x: 5.0, y: 0.0), p2: CGPoint(x: 10.0, y: 0.0))
let outline: PathComponent = q.outline(distance: 1)
let expectedSegment1 = LineSegment(p0: CGPoint(x: 0, y: -1), p1: CGPoint(x: 0, y: 1))
let expectedSegment2 = LineSegment(p0: CGPoint(x: 0, y: 1), p1: CGPoint(x: 10, y: 1))
let expectedSegment3 = LineSegment(p0: CGPoint(x: 10, y: 1), p1: CGPoint(x: 10, y: -1))
let expectedSegment4 = LineSegment(p0: CGPoint(x: 10, y: -1), p1: CGPoint(x: 0, y: -1))
XCTAssertEqual(outline.numberOfElements, 4)
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 0), matchesCurve: expectedSegment1 ))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 1), matchesCurve: expectedSegment2 ))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 2), matchesCurve: expectedSegment3 ))
XCTAssert( BezierKitTestHelpers.curve(outline.element(at: 3), matchesCurve: expectedSegment4 ))
}
func testOutlineShapesDistance() {
let lineSegment = BezierCurveTests.lineSegmentForOutlining
let distanceAlongNormal: CGFloat = 1
let shapes: [Shape] = lineSegment.outlineShapes(distance: distanceAlongNormal)
XCTAssertEqual(shapes.count, 1)
let (o0, o1, o2, o3) = lineOffsets(lineSegment, distanceAlongNormal, distanceAlongNormal, distanceAlongNormal, distanceAlongNormal)
let expectedShape = Shape(LineSegment(p0: o0, p1: o1), LineSegment(p0: o2, p1: o3), false, false) // shape made from lines with real (non-virtual) caps
XCTAssertTrue( BezierKitTestHelpers.shape(shapes[0], matchesShape: expectedShape) )
}
func testOutlineShapesDistanceAlongNormalDistanceOppositeNormal() {
let lineSegment = BezierCurveTests.lineSegmentForOutlining
let distanceAlongNormal: CGFloat = 1
let distanceOppositeNormal: CGFloat = 2
let shapes: [Shape] = lineSegment.outlineShapes(distanceAlongNormal: distanceAlongNormal, distanceOppositeNormal: distanceOppositeNormal)
XCTAssertEqual(shapes.count, 1)
let (o0, o1, o2, o3) = lineOffsets(lineSegment, distanceAlongNormal, distanceOppositeNormal, distanceAlongNormal, distanceOppositeNormal)
let expectedShape = Shape(LineSegment(p0: o0, p1: o1), LineSegment(p0: o2, p1: o3), false, false) // shape made from lines with real (non-virtual) caps
XCTAssertTrue( BezierKitTestHelpers.shape(shapes[0], matchesShape: expectedShape) )
}
func testCubicCubicIntersectionEndpoints() {
// these two cubics intersect only at the endpoints
let epsilon: CGFloat = 1.0e-3
let cubic1 = CubicCurve(p0: CGPoint(x: 0.0, y: 0.0),
p1: CGPoint(x: 1.0, y: 1.0),
p2: CGPoint(x: 2.0, y: 1.0),
p3: CGPoint(x: 3.0, y: 0.0))
let cubic2 = CubicCurve(p0: CGPoint(x: 3.0, y: 0.0),
p1: CGPoint(x: 2.0, y: -1.0),
p2: CGPoint(x: 1.0, y: -1.0),
p3: CGPoint(x: 0.0, y: 0.0))
let i = cubic1.intersections(with: cubic2, accuracy: epsilon)
XCTAssertEqual(i.count, 2, "start and end points should intersect!")
XCTAssertEqual(i[0].t1, 0.0)
XCTAssertEqual(i[0].t2, 1.0)
XCTAssertEqual(i[1].t1, 1.0)
XCTAssertEqual(i[1].t2, 0.0)
}
private func curveSelfIntersects(_ curve: CubicCurve) -> Bool {
let epsilon: CGFloat = 1.0e-5
let result = curve.selfIntersects
if result == true {
// check consistency
let intersections = curve.selfIntersections
XCTAssertEqual(intersections.count, 1)
XCTAssertTrue(distance(curve.point(at: intersections[0].t1),
curve.point(at: intersections[0].t2)) < epsilon)
}
return result
}
func testCubicSelfIntersection() {
let curve = CubicCurve(p0: CGPoint(x: 0, y: 0),
p1: CGPoint(x: 0, y: 1),
p2: CGPoint(x: 1, y: 1),
p3: CGPoint(x: 1, y: 1))
func selfIntersectsWithEndpointMoved(to point: CGPoint) -> Bool {
var copy = curve
copy.p3 = point
return curveSelfIntersects(copy)
}
// check basic cases with no self-intersections
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.5, y: 2)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.5, y: 0.5)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.5, y: -1)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: -0.5, y: -1)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: -1, y: 0.5)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: -1, y: 2)))
// check basic cases with self-intersections
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.25, y: 0.75)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: -1, y: -0.5)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: -0.5, y: 0.25)))
// check edge cases around (0, 0.75)
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0, y: 0.76)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0, y: 0.75)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0, y: 0.74)))
// check for edge cases around (-1, 0)
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: -1.01, y: 0)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: -1, y: 0)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: -0.99, y: 0)))
// check for edge cases around (-0.5, 0.58)
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: -0.5, y: -0.59)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: -0.5, y: -0.58)))
// check for edge cases around (0,0)
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0, y: 0)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.01, y: 0)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0, y: 0.01)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: -0.01, y: 0)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0, y: -0.01)))
// check for edge cases around (1,1)
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 1, y: 1)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.95, y: 0.9991)))
XCTAssertTrue(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.95, y: 0.9993)))
XCTAssertFalse(selfIntersectsWithEndpointMoved(to: CGPoint(x: 0.95, y: 0.9995)))
// check degenerate case where all points equal
let point = CGPoint(x: 3, y: 4)
let degenerateCurve = CubicCurve(p0: point, p1: point, p2: point, p3: point)
XCTAssertFalse(curveSelfIntersects(degenerateCurve))
// check line segment case
let lineSegment = CubicCurve(lineSegment: LineSegment(p0: CGPoint(x: 1, y: 2), p1: CGPoint(x: 3, y: 4)))
XCTAssertFalse(curveSelfIntersects(lineSegment))
}
func testCubicSelfIntersectionEdgeCase() {
// this curve nearly has a "cusp" which causes `reduce()` to fail
// this failure could prevent detection of the self-intersection in practice
let curve = CubicCurve(p0: CGPoint(x: 0.6699848912467168, y: 0.6276580745456783),
p1: CGPoint(x: 0.3985029248079961, y: 0.6770972104768092),
p2: CGPoint(x: 0.6414685401578772, y: 0.8591306876578386),
p3: CGPoint(x: 0.4385385980761747, y: 0.3866255870526274))
XCTAssertTrue(curveSelfIntersects(curve))
}
}
|
mit
|
008ac452e815f9455cced6d802120825
| 53.867692 | 175 | 0.62057 | 3.678977 | false | true | false | false |
WeHUD/app
|
weHub-ios/Gzone_App/Gzone_App/CommentViewController.swift
|
1
|
8993
|
//
// CommentViewController.swift
// Gzone_App
//
// Created by Lyes Atek on 10/07/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import UIKit
class CommentViewController : UIViewController, UITableViewDataSource,UITableViewDelegate,UITextViewDelegate{
@IBOutlet weak var avatarUser: UIImageView!
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var viewComment: UIView!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var date: UILabel!
@IBOutlet weak var reply: UILabel!
@IBOutlet weak var rate1: UIImageView!
@IBOutlet weak var rate2: UIImageView!
@IBOutlet weak var rate3: UIImageView!
@IBOutlet weak var rate4: UIImageView!
@IBOutlet weak var rate5: UIImageView!
@IBOutlet weak var textPost: UITextView!
@IBOutlet weak var mediaImage: UIImageView!
@IBOutlet weak var userComment: UITextView!
@IBOutlet var tableView: UITableView!
var rates :[UIImageView] = []
var comments : [Comment] = []
var users : [User] = []
var avatars : [UIImage] = []
var user : User?
var post : Post?
var flagOpinion : Bool?
var note : Int?
var placeHolderUserComment : String = "Add comment"
override func viewDidLoad() {
super.viewDidLoad()
self.createPlaceHolder()
self.getUserById(id: (post?._id)!)
self.getCommentByPostId()
self.initializeRates()
initializeRatting(note: self.note!)
self.userComment.delegate = self
self.navigationItem.setHidesBackButton(true, animated:true);
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.closeTextField()
}
//Function for placeHolder
func createPlaceHolder(){
self.userComment.text = "Add comment"
self.userComment.textColor = UIColor.lightGray
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
self.createPlaceHolder()
}
}
func textViewDidBeginEditing(_ textView: UITextView) {
if self.userComment.textColor == UIColor.lightGray {
self.userComment.text = nil
self.userComment.textColor = UIColor.black
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! CommentTableViewCell
let comment = self.comments[indexPath.row]
cell.textComment.text = comment.text
cell.date.text = comment.datetimeCreated.description
if(self.avatars.count > indexPath.row && self.users.count > indexPath.row){
cell.avatar.image = self.avatars[indexPath.row]
cell.username.text = self.users[indexPath.row].username
cell.reply.text = self.users[indexPath.row].reply
}
return cell
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func refreshTableView(){
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
func hiddenRates(){
for i in 0 ..< (self.rates.count ) {
self.rates[i].isHidden = true
}
}
func initializeElements(){
self.avatar.imageFromUrl(url: (self.user?.avatar)!)
self.username.text = self.user?.username
self.reply.text = self.user?.reply
self.date.text = post?.datetimeCreated
self.textPost.text = post?.text
if(self.flagOpinion)!{
self.initializeRatting(note: (post?.mark!)!)
}else{
self.hiddenRates()
}
if(post?.video != ""){
// Extract youtube ID from URL
let mediaId = post?.video.youtubeID!
let mediaURL = "http://img.youtube.com/vi/"+mediaId!+"/mqdefault.jpg"
//Use of extension for downloading youtube thumbnails
self.mediaImage.imageFromYoutube(url: mediaURL)
//On tap gesture display presentation view with media content
self.mediaImage.isUserInteractionEnabled = true;
//self.mediaImage.tag = indexPath.row
let tapGesture = UITapGestureRecognizer(target:self, action: #selector(self.showYoutubeModal(_:)))
self.mediaImage.addGestureRecognizer(tapGesture)
}else{
self.mediaImage.isUserInteractionEnabled = false
}
self.avatarUser.imageFromUrl(url: (self.user?.avatar)!)
}
func initializeRates(){
rates.append(self.rate1)
rates.append(rate2)
rates.append(rate3)
rates.append(rate4)
rates.append(rate5)
}
func getCommentByPostId()->Void{
let commentWB : WBComment = WBComment()
commentWB.getCommentByPostId(postId: (post?._id)!, accessToken: AuthenticationService.sharedInstance.accessToken!, offset: "0") {
(result: [Comment]) in
self.comments = result
self.refreshTableView()
self.getUsersComment()
}
}
func initializeRatting(note : Int){
if(note == 0){
return
}
for i in 0 ..< (note ) {
self.rates[i].image = UIImage(named: "selectedStarIcon.png")
}
}
func getUsersComment(){
if((post?.comments.count)! > 0){
var index : Int = 0
for _ in (post?.comments)!{
let userComment = User()
getUser(id: self.comments[index].userId, user : userComment)
index += 1
}
}
}
func getUser(id : String,user:User){
let userWB : WBUser = WBUser()
userWB.getUser(userId: id, accessToken: AuthenticationService.sharedInstance.accessToken!){
(result: User) in
self.users.append(result)
self.imageFromUrl(url: result.avatar!)
self.refreshTableView()
}
}
func getUserById(id : String){
let userWB : WBUser = WBUser()
userWB.getUser(userId: (post?.userId)!, accessToken: AuthenticationService.sharedInstance.accessToken!){
(result: User) in
DispatchQueue.main.async {
self.user = result
self.initializeElements()
}
}
}
@IBAction func sendComment(_ sender: Any) {
if(self.userComment.text == self.placeHolderUserComment && self.userComment.textColor == UIColor.lightGray){
emptyFields(title: "Comments", message: "Your messsage field is empty")
}else{
let commentWB : WBComment = WBComment()
commentWB.addComment(userId: (AuthenticationService.sharedInstance.currentUser?._id)!, postId: (post?._id)!, text: self.userComment.text, accessToken: AuthenticationService.sharedInstance.accessToken!){
(result: Bool) in
DispatchQueue.main.async {
let storyboard = UIStoryboard(name: "Home", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Home_ID") as! UITabBarController
self.present(vc, animated: true, completion: nil)
}
}
}
}
func showYoutubeModal(_ sender : UITapGestureRecognizer){
print("Tap image : ", sender.view?.tag ?? "no media content")
if let postVideo = post?.video {
// Instantiate a modal view when content media view is tapped
let modalViewController = ModalViewController()
modalViewController.videoURL = postVideo
modalViewController.modalPresentationStyle = .popover
present(modalViewController, animated: true, completion: nil)
}
}
func imageFromUrl(url : String) {
let imageUrlString = url
let imageUrl:URL = URL(string: imageUrlString)!
let imageData:NSData = NSData(contentsOf: imageUrl)!
self.avatars.append(UIImage(data: imageData as Data)!)
}
@IBAction func cancelBtn(_ sender: Any) {
let storyboard = UIStoryboard(name: "Home", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Home_ID") as! UITabBarController
self.present(vc, animated: true, completion: nil)
}
}
|
bsd-3-clause
|
ccae790a2324d096d0a6fed448603966
| 32.180812 | 214 | 0.58919 | 4.957001 | false | false | false | false |
HcomCoolCode/hotelowy
|
ListOfHotels/Hotel.swift
|
1
|
2628
|
//
// Hotel.swift
// ListOfHotels
//
// Created by Tomasz Kuzma on 24/03/2016.
// Copyright © 2016 Expedia. All rights reserved.
//
import Foundation
import ObjectMapper
public class Hotel : NSObject, Mappable {
var inExpandedArea: Int?
var guestReviewRating: Float?
var numberOfGuestReviews: Int?
var avgPrice: String?
var urgencyMessage: UrgencyMessage?
var avgPriceDetails: AveragePriceDetail?
var localizedCountryName: String?
var thumbnailUrl: NSURL?
var promoPrice: String?
var locality: String?
var lon: Float?
var starRating: Float?
var avgPriceDescription: String?
var location: String?
var postalCode: String?
var id: Int?
var address1: String?
var address2: String?
var promoPriceDescription: String?
var promoPriceDetails: PromoPriceDetail?
var qualitativeBadgeText: String?
var lat: Float?
var countryAlpha3Code: String?
var country: String?
var imageURL: NSURL?
var name: String?
var dealOfTheDay: Int?
var region: String?
public required init?(_ map: Map) {
}
public func mapping(map: Map) {
inExpandedArea <- map["inExpandedArea"]
guestReviewRating <- map["guestReviewRating"]
numberOfGuestReviews <- map["numberOfGuestReviews"]
avgPrice <- map["avgPrice"]
urgencyMessage <- map["urgencyMessage"]
avgPriceDetails <- map["avgPriceDetails"]
localizedCountryName <- map["localizedCountryName"]
thumbnailUrl <- (map["thumbnailUrl"], URLTransform())
promoPrice <- map["promoPrice"]
locality <- map["locality"]
lon <- map["lon"]
starRating <- map["starRating"]
avgPriceDescription <- map["avgPriceDescription"]
location <- map["location"]
postalCode <- map["postalCode"]
id <- map["hotelId"]
address1 <- map["address1"]
address2 <- map["address2"]
promoPriceDescription <- map["promoPriceDescription"]
promoPriceDetails <- map["promoPriceDetails"]
qualitativeBadgeText <- map["qualitativeBadgeText"]
lat <- map["lat"]
countryAlpha3Code <- map["countryAlpha3Code"]
country <- map["country"]
imageURL <- (map["imageUrl"], URLTransform())
name <- map["hotelName"]
dealOfTheDay <- map["dealOfTheDay"]
region <- map["region"]
}
}
public func ==(lhs: Hotel, rhs: Hotel) -> Bool {
guard lhs.name == rhs.name else {return false}
guard lhs.id == rhs.id else {return false}
guard lhs.imageURL == rhs.imageURL else {return false}
return true
}
|
mit
|
d29e0b7135cde1129829dde05e00c7e6
| 31.04878 | 61 | 0.644461 | 4.278502 | false | false | false | false |
kevcol/droppednews
|
TVCTest/AudioVC.swift
|
1
|
4274
|
/*
AudioVC.swift
DroppedNews: A Drupal-powered iOS News App
Copyright 2017, Kevin Colligan
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 AVFoundation
class AudioVC: UIViewController {
var audioPlayer = AVAudioPlayer()
var mp3: String!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var headline: UILabel!
@IBOutlet weak var timestamp: UILabel!
@IBOutlet weak var body: UITextView!
//@IBOutlet weak var pauseButton: UIButton!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var fwdButton: UIButton!
private var _contentItem: ContentItem!
var contentItem: ContentItem {
get {
return _contentItem
} set {
_contentItem = newValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
mainImage.image = contentItem.mainImage
headline.text = contentItem.headline
timestamp.text = contentItem.timestamp
body.text = contentItem.body
mp3 = contentItem.audioName
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: mp3, ofType: "mp3")!))
audioPlayer.prepareToPlay()
// slider
slider.maximumValue = Float(TimeInterval(audioPlayer.duration))
_ = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(AudioVC.updateSlider), userInfo: nil, repeats: true)
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch {
print(error)
}
}
catch {
print(error)
}
}
@IBAction func Play(_ sender: Any) {
if !audioPlayer.isPlaying {
audioPlayer.play()
playButton.setImage(UIImage(named:"pause.png"),for:UIControlState.normal)
} else {
audioPlayer.pause()
playButton.setImage(UIImage(named:"play.png"),for:UIControlState.normal)
}
}
@IBAction func rwd15(_ sender: Any) {
let currentTime = audioPlayer.currentTime
if currentTime < 15.0 {
audioPlayer.currentTime = 0
audioPlayer.play()
} else {
audioPlayer.currentTime = currentTime - 15
audioPlayer.play()
}
}
@IBAction func fwd15(_ sender: Any) {
let currentTime = audioPlayer.currentTime
let futureTime = currentTime + 15.0
if futureTime < audioPlayer.duration {
audioPlayer.pause()
audioPlayer.currentTime = futureTime
audioPlayer.play()
print(audioPlayer.currentTime)
} else {
// FEATURE REQUEST
// FWD button: Flash Red, then fade to gray in final 0:15 of the audio file
}
}
@IBAction func scrubAudio(_ sender: UISlider) {
audioPlayer.stop()
audioPlayer.currentTime = TimeInterval(slider.value)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
// func updateSlider() {
//
// slider.value = Float(audioPlayer.currentTime)
// print("SCRUB")
// }
func updateSlider() {
slider.value = Float(audioPlayer.currentTime)
}
}
|
apache-2.0
|
3ecdb8243fd638a2064030dedd18c8d3
| 20.054187 | 140 | 0.571362 | 5.237745 | false | false | false | false |
sbcmadn1/swift
|
swiftweibo05/GZWeibo05/Class/Tool/CZNetworkTools.swift
|
2
|
9622
|
//
// CZNetworkTools.swift
// GZWeibo05
//
// Created by zhangping on 15/10/28.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
import AFNetworking
// MARK: - 网络错误枚举
enum CZNetworkError: Int {
case emptyToken = -1
case emptyUid = -2
// 枚举里面可以有属性
var description: String {
get {
// 根据枚举的类型返回对应的错误
switch self {
case CZNetworkError.emptyToken:
return "accecc token 为空"
case CZNetworkError.emptyUid:
return "uid 为空"
}
}
}
// 枚举可以定义方法
func error() -> NSError {
return NSError(domain: "cn.itcast.error.network", code: rawValue, userInfo: ["errorDescription" : description])
}
}
class CZNetworkTools: NSObject {
// 属性
private var afnManager: AFHTTPSessionManager
// 创建单例
static let sharedInstance: CZNetworkTools = CZNetworkTools()
override init() {
let urlString = "https://api.weibo.com/"
afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlString))
afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
}
// 创建单例
// static let sharedInstance: CZNetworkTools = {
// let urlString = "https://api.weibo.com/"
//
// let tool = CZNetworkTools(baseURL: NSURL(string: urlString))
//// Set
// tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
//
// return tool
// }()
// MARK: - OAtuh授权
/// 申请应用时分配的AppKey
private let client_id = "3769988269"
/// 申请应用时分配的AppSecret
private let client_secret = "8c30d1e7d3754eca9076689b91531c6a"
/// 请求的类型,填写authorization_code
private let grant_type = "authorization_code"
/// 回调地址
let redirect_uri = "http://www.baidu.com/"
// OAtuhURL地址
func oauthRUL() -> NSURL {
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
return NSURL(string: urlString)!
}
// 使用闭包回调
// MARK: - 加载AccessToken
/// 加载AccessToken
func loadAccessToken(code: String, finshed: NetworkFinishedCallback) {
// url
let urlString = "oauth2/access_token"
// NSObject
// AnyObject, 任何 class
// 参数
let parameters = [
"client_id": client_id,
"client_secret": client_secret,
"grant_type": grant_type,
"code": code,
"redirect_uri": redirect_uri
]
// 测试返回结果类型
// responseSerializer = AFHTTPResponseSerializer()
// result: 请求结果
afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
// let data = String(data: result as! NSData, encoding: NSUTF8StringEncoding)
// print("data: \(data)")
finshed(result: result as? [String: AnyObject], error: nil)
}) { (_, error: NSError) -> Void in
finshed(result: nil, error: error)
}
}
// MARK: - 获取用户信息
func loadUserInfo(finshed: NetworkFinishedCallback) {
// 守卫,和可选绑定相反
// parameters 代码块里面和外面都能使用
guard var parameters = tokenDict() else {
// 能到这里来表示 parameters 没有值
print("没有accessToken")
let error = CZNetworkError.emptyToken.error()
// 告诉调用者
finshed(result: nil, error: error)
return
}
// 判断uid
if CZUserAccount.loadAccount()?.uid == nil {
print("没有uid")
let error = CZNetworkError.emptyUid.error()
// 告诉调用者
finshed(result: nil, error: error)
return
}
// url
let urlString = "https://api.weibo.com/2/users/show.json"
// 添加元素
parameters["uid"] = CZUserAccount.loadAccount()!.uid!
requestGET(urlString, parameters: parameters, finshed: finshed)
}
/// 判断access token是否有值,没有值返回nil,如果有值生成一个字典
func tokenDict() -> [String: AnyObject]? {
if CZUserAccount.loadAccount()?.access_token == nil {
return nil
}
return ["access_token": CZUserAccount.loadAccount()!.access_token!]
}
// MARK: - 获取微博数据
/**
加载微博数据
- parameter since_id: 若指定此参数,则返回ID比since_id大的微博,默认为0
- parameter max_id: 若指定此参数,则返回ID小于或等于max_id的微博,默认为0
- parameter finished: 回调
*/
func loadStatus(since_id: Int, max_id: Int, finished: NetworkFinishedCallback) {
guard var parameters = tokenDict() else {
// 能到这里来说明token没有值
// 告诉调用者
finished(result: nil, error: CZNetworkError.emptyToken.error())
return
}
// 添加参数 since_id和max_id
// 判断是否有传since_id,max_id
if since_id > 0 {
parameters["since_id"] = since_id
} else if max_id > 0 {
parameters["max_id"] = max_id - 1
}
// access token 有值
let urlString = "2/statuses/home_timeline.json"
// 网络不给力,加载本地数据
if true {
requestGET(urlString, parameters: parameters, finshed: finished)
} else {
loadLocalStatus(finished)
}
}
/// 加载本地微博数据
private func loadLocalStatus(finished: NetworkFinishedCallback) {
// 获取路径
let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")
// 加载文件数据
let data = NSData(contentsOfFile: path!)
// 转成json
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
// 有数据
finished(result: json as? [String : AnyObject], error: nil)
} catch {
// 如果do里面的代码出错了,不会崩溃,会走这里
print("出异常了")
}
// 强制try 如果这句代码有错误,程序立即停止运行
// let statusesJson = try! NSJSONSerialization.JSONObjectWithData(nsData, options: NSJSONReadingOptions(rawValue: 0))
}
// MARK: - 发布微博
/**
发布微博
- parameter image: 微博图片,可能有可能没有
- parameter status: 微博文本内容
- parameter finished: 回调闭包
*/
func sendStatus(image: UIImage?, status: String, finished: NetworkFinishedCallback) {
// 判断token
guard var parameters = tokenDict() else {
// 能到这里来说明token没有值
// 告诉调用者
finished(result: nil, error: CZNetworkError.emptyToken.error())
return
}
// token有值, 拼接参数
parameters["status"] = status
// 判断是否有图片
if let im = image {
// 有图片,发送带图片的微博
let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
afnManager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
let data = UIImagePNGRepresentation(im)!
// data: 上传图片的2进制
// name: api 上面写的传递参数名称 "pic"
// fileName: 上传到服务器后,保存的名称,没有指定可以随便写
// mimeType: 资源类型:
// image/png
// image/jpeg
// image/gif
formData.appendPartWithFileData(data, name: "pic", fileName: "sb", mimeType: "image/png")
}, success: { (_, result) -> Void in
finished(result: result as? [String: AnyObject], error: nil)
}, failure: { (_, error) -> Void in
finished(result: nil, error: error)
})
} else {
// url
let urlString = "2/statuses/update.json"
// 没有图片
afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
finished(result: result as? [String: AnyObject], error: nil)
}) { (_, error) -> Void in
finished(result: nil, error: error)
}
}
}
// 类型别名 = typedefined
typealias NetworkFinishedCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
// MARK: - 封装AFN.GET
func requestGET(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) {
afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in
finshed(result: result as? [String: AnyObject], error: nil)
}) { (_, error) -> Void in
finshed(result: nil, error: error)
}
}
}
|
mit
|
e8a1c514b448c872dfeba17d95ceee36
| 30.255396 | 125 | 0.54264 | 4.342329 | false | false | false | false |
lllyyy/LY
|
U17-master/U17/U17/Procedure/Comic/View/UChapterCHead.swift
|
1
|
2022
|
//
// UChapterCHead.swift
// U17
//
// Created by charles on 2017/11/23.
// Copyright © 2017年 None. All rights reserved.
//
import UIKit
typealias UChapterCHeadSortClosure = (_ button: UIButton) -> Void
class UChapterCHead: UBaseCollectionReusableView {
private var sortClosure: UChapterCHeadSortClosure?
private lazy var chapterLabel: UILabel = {
let vl = UILabel()
vl.textColor = UIColor.gray
vl.font = UIFont.systemFont(ofSize: 13)
return vl
}()
private lazy var sortButton: UIButton = {
let sn = UIButton(type: .system)
sn.setTitle("倒序", for: .normal)
sn.setTitleColor(UIColor.gray, for: .normal)
sn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
sn.addTarget(self, action: #selector(sortAction(for:)), for: .touchUpInside)
return sn
}()
@objc private func sortAction(for button: UIButton) {
guard let sortClosure = sortClosure else { return }
sortClosure(button)
}
func sortClosure(_ closure: @escaping UChapterCHeadSortClosure) {
sortClosure = closure
}
override func configUI() {
addSubview(sortButton)
sortButton.snp.makeConstraints {
$0.right.equalToSuperview()
$0.right.top.bottom.equalToSuperview()
$0.width.equalTo(44)
}
addSubview(chapterLabel)
chapterLabel.snp.makeConstraints {
$0.left.equalTo(10)
$0.top.bottom.equalToSuperview()
$0.right.equalTo(sortButton.snp.left).offset(-10)
}
}
var model: DetailStaticModel? {
didSet {
guard let model = model else { return }
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
chapterLabel.text = "目录 \(format.string(from: Date(timeIntervalSince1970: model.comic?.last_update_time ?? 0))) 更新 \(model.chapter_list?.last?.name ?? "")"
}
}
}
|
mit
|
ad99676fb0449e72ed21f7bb651aaa41
| 28.955224 | 167 | 0.601893 | 4.15528 | false | false | false | false |
77u4/Timetable
|
Timetable/Lesson.swift
|
1
|
1268
|
//
// Lesson.swift
// Timetable
//
// Created by Jannis on 04.01.15.
// Copyright (c) 2015 Jannis Hutt. All rights reserved.
//
import Foundation
class Lesson {
let name: String
let onTimetable: Int
let time: (h: Int, m:Int)
let duration: Duration
let weekday: Weekday
let teacher: String
let room: String
init(let name: String, let onTimetable: Int, let time: (h:Int, m:Int), let duration: Duration, let weekday: Weekday, let teacher: String, let room: String){
self.name = name
self.onTimetable = onTimetable
self.time = time
self.duration = duration
self.weekday = weekday
self.teacher = teacher
self.room = room
}
struct Duration {
func toTimeTuple(lessons:Int) -> (h: Int, m:Int){
var h = 0,
m = 0,
help = lessons
while help > 0 {
m += 45
help = help - 1
}
while m >= 60 {
m = m - 60
h += 1
}
return (h, m)
}
}
enum Weekday: Int {
case Monday = 1
case Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
}
|
gpl-3.0
|
5a8c03277159aa8b7e48982588c7bf59
| 22.481481 | 160 | 0.500789 | 4.130293 | false | false | false | false |
BalestraPatrick/Tweetometer
|
Carthage/Checkouts/Swifter/Sources/SwifterPlaces.swift
|
2
|
6017
|
//
// SwifterPlaces.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET geo/id/:place_id
Returns all the information about a known place.
*/
public func getGeoID(for placeID: String,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "geo/id/\(placeID).json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET geo/reverse_geocode
Given a latitude and a longitude, searches for up to 20 places that can be used as a place_id when updating a status.
This request is an informative call and will deliver generalized results about geography.
*/
public func getReverseGeocode(for coordinate: (lat: Double, long: Double),
accuracy: String? = nil,
granularity: String? = nil,
maxResults: Int? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "geo/reverse_geocode.json"
var parameters = [String: Any]()
parameters["lat"] = coordinate.lat
parameters["long"] = coordinate.long
parameters["accuracy"] ??= accuracy
parameters["granularity"] ??= granularity
parameters["max_results"] ??= maxResults
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET geo/search
Search for places that can be attached to a statuses/update. Given a latitude and a longitude pair, an IP address, or a name, this request will return a list of all the valid places that can be used as the place_id when updating a status.
Conceptually, a query can be made from the user's location, retrieve a list of places, have the user validate the location he or she is at, and then send the ID of this location with a call to POST statuses/update.
This is the recommended method to use find places that can be attached to statuses/update. Unlike GET geo/reverse_geocode which provides raw data access, this endpoint can potentially re-order places with regards to the user who is authenticated. This approach is also preferred for interactive place matching with the user.
*/
public func searchGeo(coordinate: (lat: Double, long: Double)? = nil,
query: String? = nil,
ipAddress: String? = nil,
accuracy: String? = nil,
granularity: String? = nil,
maxResults: Int? = nil,
containedWithin: String? = nil,
attributeStreetAddress: String? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
assert(coordinate != nil || query != nil || ipAddress != nil,
"At least one of the following parameters must be provided to access this resource: coordinate, ipAddress, or query")
let path = "geo/search.json"
var parameters = [String: Any]()
if let coordinate = coordinate {
parameters["lat"] = coordinate.lat
parameters["long"] = coordinate.long
} else if let query = query {
parameters["query"] = query
} else if let ip = ipAddress {
parameters["ip"] = ip
}
parameters["accuracy"] ??= accuracy
parameters["granularity"] ??= granularity
parameters["max_results"] ??= maxResults
parameters["contained_within"] ??= containedWithin
parameters["attribute:street_address"] ??= attributeStreetAddress
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
/**
GET geo/similar_places
Locates places near the given coordinates which are similar in name.
Conceptually you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to POST geo/place to create a new one.
The token contained in the response is the token needed to be able to create a new place.
*/
public func getSimilarPlaces(for coordinate: (lat: Double, long: Double),
name: String,
containedWithin: String? = nil,
attributeStreetAddress: String? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "geo/similar_places.json"
var parameters = [String: Any]()
parameters["lat"] = coordinate.lat
parameters["long"] = coordinate.long
parameters["name"] = name
parameters["contained_within"] ??= containedWithin
parameters["attribute:street_address"] ??= attributeStreetAddress
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
}
|
mit
|
62b90b5ea3853fe25c8e435d201cb2c7
| 41.373239 | 328 | 0.667276 | 4.480268 | false | false | false | false |
Zewo/Epoch
|
Sources/HTTP/Response/Response.swift
|
2
|
5967
|
import Core
import IO
import Media
import Venice
public final class Response : Message {
public typealias UpgradeConnection = (Request, DuplexStream) throws -> Void
public var status: Status
public var headers: Headers
public var version: Version
public var body: Body
public var storage: Storage = [:]
public var upgradeConnection: UpgradeConnection?
public var cookieHeaders: Set<String> = []
public init(
status: Status,
headers: Headers,
version: Version,
body: Body
) {
self.status = status
self.headers = headers
self.version = version
self.body = body
}
// TODO: Check http://www.iana.org/assignments/http-status-codes
public enum Status {
case `continue`
case switchingProtocols
case processing
case ok
case created
case accepted
case nonAuthoritativeInformation
case noContent
case resetContent
case partialContent
case multipleChoices
case movedPermanently
case found
case seeOther
case notModified
case useProxy
case switchProxy
case temporaryRedirect
case permanentRedirect
case badRequest
case unauthorized
case paymentRequired
case forbidden
case notFound
case methodNotAllowed
case notAcceptable
case proxyAuthenticationRequired
case requestTimeout
case conflict
case gone
case lengthRequired
case preconditionFailed
case requestEntityTooLarge
case requestURITooLong
case unsupportedMediaType
case requestedRangeNotSatisfiable
case expectationFailed
case imATeapot
case authenticationTimeout
case enhanceYourCalm
case unprocessableEntity
case locked
case failedDependency
case preconditionRequired
case tooManyRequests
case requestHeaderFieldsTooLarge
case internalServerError
case notImplemented
case badGateway
case serviceUnavailable
case gatewayTimeout
case httpVersionNotSupported
case variantAlsoNegotiates
case insufficientStorage
case loopDetected
case notExtended
case networkAuthenticationRequired
case other(statusCode: Int, reasonPhrase: String)
}
}
extension Response {
public convenience init(
status: Status,
headers: Headers = [:]
) {
self.init(
status: status,
headers: headers,
version: .oneDotOne,
body: .empty
)
contentLength = 0
}
public convenience init(
status: Status,
headers: Headers = [:],
body readable: Readable
) {
self.init(
status: status,
headers: headers,
version: .oneDotOne,
body: .readable(readable)
)
}
public convenience init(
status: Status,
headers: Headers = [:],
body write: @escaping Body.Write
) {
self.init(
status: status,
headers: headers,
version: .oneDotOne,
body: .writable(write)
)
}
public convenience init(
status: Status,
headers: Headers = [:],
body buffer: BufferRepresentable,
timeout: Duration = 5.minutes
) {
self.init(
status: status,
headers: headers,
body: { stream in
try stream.write(buffer, deadline: timeout.fromNow())
}
)
contentLength = buffer.bufferSize
}
public convenience init<Content : EncodingMedia>(
status: Status,
headers: Headers = [:],
content: Content,
timeout: Duration = 5.minutes
) throws {
self.init(
status: status,
headers: headers,
body: { writable in
try content.encode(to: writable, deadline: timeout.fromNow())
}
)
self.contentType = Content.mediaType
self.contentLength = nil
self.transferEncoding = "chunked"
}
public convenience init<Content : MediaEncodable>(
status: Status,
headers: Headers = [:],
content: Content,
timeout: Duration = 5.minutes
) throws {
let media = try Content.defaultEncodingMedia()
self.init(
status: status,
headers: headers,
body: { writable in
try media.encode(content, to: writable, deadline: timeout.fromNow())
}
)
self.contentType = media.mediaType
self.contentLength = nil
self.transferEncoding = "chunked"
}
public convenience init<Content : MediaEncodable>(
status: Status,
headers: Headers = [:],
content: Content,
contentType mediaType: MediaType,
timeout: Duration = 5.minutes
) throws {
let media = try Content.encodingMedia(for: mediaType)
self.init(
status: status,
headers: headers,
body: { writable in
try media.encode(content, to: writable, deadline: timeout.fromNow())
}
)
self.contentType = media.mediaType
self.contentLength = nil
self.transferEncoding = "chunked"
}
}
extension Response : CustomStringConvertible {
/// :nodoc:
public var statusLineDescription: String {
return version.description + " " + status.description + "\n"
}
/// :nodoc:
public var description: String {
return statusLineDescription + headers.description
}
}
|
mit
|
0c610770531ec8f46cdfa9e71f3cee0e
| 25.056769 | 84 | 0.569801 | 5.514787 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io
|
WikipediaSearch/WikipediaSearch/Common/Constants.swift
|
1
|
587
|
//
// Constants.swift
// WikipediaSearch
//
// Created by Anirudh Das on 8/11/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
public static let placeholderImage: UIImage = #imageLiteral(resourceName: "placeholder")
public static let wikiTableViewCell = "WikiCell"
public static let homeNavTitle = "Wiki Search"
public static let KEY_RECENT_SEARCH = "KEY_RECENT_SEARCH"
public static let NO_NETWORK_CONNECTIVITY = "The network connection appears to be offline, please check your connectivity."
}
|
apache-2.0
|
8b4f7fe0b73f57cb51497b77acc3d776
| 31.555556 | 127 | 0.742321 | 4.156028 | false | false | false | false |
haskellswift/swift-package-manager
|
Tests/BasicTests/LazyCacheTests.swift
|
2
|
1152
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
class LazyCacheTests: XCTestCase {
func testBasics() {
class Foo {
var numCalls = 0
var bar: Int { return barCache.getValue(self) }
var barCache = LazyCache(someExpensiveMethod)
func someExpensiveMethod() -> Int {
numCalls += 1
return 42
}
}
// FIXME: Make this a more interesting test once we have concurrency primitives.
for _ in 0..<10 {
let foo = Foo()
XCTAssertEqual(foo.numCalls, 0)
for _ in 0..<10 {
XCTAssertEqual(foo.bar, 42)
XCTAssertEqual(foo.numCalls, 1)
}
}
}
static var allTests = [
("testBasics", testBasics),
]
}
|
apache-2.0
|
b1783ab723690d77b5e597d31af6062f
| 25.790698 | 88 | 0.570313 | 4.721311 | false | true | false | false |
dmiedema/URLSessionMetrics
|
URLSessionMetrics/Classes/RequestMetricsCollectionViewController.swift
|
1
|
6818
|
//
// RequestMetricsCollectionView.swift
// URLSessionMetrics
//
// Created by Daniel Miedema on 6/16/16.
// Copyright © 2016 dmiedema. All rights reserved.
//
import UIKit
@available(iOS 10.0, *)
/// Collection View Controller for displaying basic Request Metrics
public class RequestMetricsCollectionViewController: UICollectionViewController {
private let CellReuseIdentifier = "RequestMetricsCollectionViewController.CellReuseIdentifier"
private let HeaderReuseIdentifier = "RequestMetricsCollectionViewController.HeaderReuseIdentifier"
/// Our default
public var metricsManager = DefaultMetricsManager.shared
/// Requests organized by host.
/// Each array will be grouped by the host and then internally sorted by newest request first.
/// For example, if we have requests to `google.com` and `youtube.com` we'll have 2 sub arrays
/// `[[Requests to Google], [Requests to YouTube]]`
private var requestMetrics = [[URLSessionTaskMetrics]]()
/// Helper function for automatically embedding the collection view
/// inside of a `UINavigationController`.
/// - returns: `UINavigationController` with the `RequestMetricsCollectionViewController` as its root controller
public class func requestMetricsCollectionView() -> UINavigationController {
let layout = UICollectionViewFlowLayout()
let controller = RequestMetricsCollectionViewController(collectionViewLayout: layout)
let navigationController = UINavigationController(rootViewController: controller)
return navigationController
}
//MARK: - View Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .lightGray
collectionView?.register(RequestMetricsCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: CellReuseIdentifier)
collectionView?.register(RequestMetricsCollectionViewHeader.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderReuseIdentifier)
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(RequestMetricsCollectionViewController.closeViewController))
title = "Network Requests"
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(RequestMetricsCollectionViewController.refresh), for: .valueChanged)
collectionView?.refreshControl = refreshControl
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
//MARK: - Actions
func closeViewController() {
self.dismiss(animated: true, completion: nil)
}
func refresh() {
var organized: [String : [URLSessionTaskMetrics]] = [:]
for metric in metricsManager.metrics {
var metrics = organized[metric.requestURL?.url?.host ?? "Unknown Host"] ?? []
metrics.append(metric)
organized[metric.requestURL?.url?.host ?? "Unknown Host"] = metrics
}
requestMetrics = organized.flatMap({ (dict) in
return dict.value.sorted(by: { (task1, task2) -> Bool in
guard let task1Start = task1.transactionMetrics.first?.fetchStartDate,
let task2Start = task2.transactionMetrics.first?.fetchStartDate else {
return false
}
return task1Start > task2Start
})
})
collectionView?.reloadData()
collectionView?.refreshControl?.endRefreshing()
}
//MARK: - UICollectionViewDelegate
override public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let metrics = requestMetrics[indexPath.section][indexPath.row]
let controller = RequestMetricsDetailView(metrics: metrics)
navigationController?.pushViewController(controller, animated: true)
}
//MARK: - UICollectionViewDatasource
override public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionElementKindSectionHeader,
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderReuseIdentifier, for: indexPath) as? RequestMetricsCollectionViewHeader
else {
return UICollectionReusableView()
}
header.requestBaseLabel.text = requestMetrics[indexPath.section].first?.requestURL?.url?.host ?? "Unknown Host"
return header
}
override public func numberOfSections(in collectionView: UICollectionView) -> Int {
return requestMetrics.count
}
override public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return requestMetrics[section].count
}
override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellReuseIdentifier, for: indexPath) as? RequestMetricsCollectionViewCell else {
return collectionView.dequeueReusableCell(withReuseIdentifier: CellReuseIdentifier, for: indexPath)
}
cell.configure(metrics: requestMetrics[indexPath.section][indexPath.row])
return cell
}
override public func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
}
}
@available(iOS 10.0, *)
/// Hacky way to show two cells side by side when running in `regular` horiztonal size class
extension RequestMetricsCollectionViewController: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat
if collectionView.traitCollection.horizontalSizeClass == .regular {
width = (collectionView.frame.size.width / 2.0) - 20
} else {
width = collectionView.frame.size.width
}
return CGSize(width: width, height: 120)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.size.width, height: 30)
}
}
|
mit
|
92bcb64b9eeb34a74e6a2e720935db5b
| 46.671329 | 213 | 0.72862 | 5.886874 | false | false | false | false |
rnystrom/GitHawk
|
Classes/Issues/Comments/Images/IssueCommentImageCell.swift
|
1
|
5071
|
//
// IssueCommentImageCell.swift
// Freetime
//
// Created by Ryan Nystrom on 5/19/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
import SDWebImage
import IGListKit
protocol IssueCommentImageCellDelegate: class {
func didTapImage(cell: IssueCommentImageCell, image: UIImage, animatedImageData: Data?)
}
protocol IssueCommentImageHeightCellDelegate: class {
func imageDidFinishLoad(cell: IssueCommentImageCell, url: URL, size: CGSize)
}
final class IssueCommentImageCell: IssueCommentBaseCell, ListBindable {
static let bottomInset = Styles.Sizes.rowSpacing
weak var delegate: IssueCommentImageCellDelegate?
weak var heightDelegate: IssueCommentImageHeightCellDelegate?
let imageView = FLAnimatedImageView()
private let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
private var tapGesture: UITapGestureRecognizer!
override init(frame: CGRect) {
super.init(frame: frame)
imageView.contentMode = .scaleAspectFit
imageView.accessibilityIgnoresInvertColors = true
contentView.addSubview(imageView)
spinner.hidesWhenStopped = true
contentView.addSubview(spinner)
spinner.snp.makeConstraints { make in
make.center.equalTo(imageView)
}
tapGesture = UITapGestureRecognizer(target: self, action: #selector(IssueCommentImageCell.onTap(recognizer:)))
tapGesture.require(toFail: doubleTapGesture)
tapGesture.delegate = self
contentView.addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var frame = contentView.bounds
frame.size.height -= IssueCommentImageCell.bottomInset
if let size = imageView.image?.size {
frame.size = BoundedImageSize(originalSize: size, containerWidth: frame.width)
}
imageView.frame = frame
}
// MARK: Private API
@objc func onTap(recognizer: UITapGestureRecognizer) {
// action will only trigger if shouldBegin returns true
guard let image = imageView.image else { return }
// If FLAnimatedImage is nil, access to implicit unwrapped optional will crash
if let animatedImage = imageView.animatedImage {
delegate?.didTapImage(cell: self, image: image, animatedImageData: animatedImage.data)
} else {
delegate?.didTapImage(cell: self, image: image, animatedImageData: nil)
}
}
// MARK: ListBindable
func bindViewModel(_ viewModel: Any) {
guard let viewModel = viewModel as? IssueCommentImageModel else { return }
configure(with: viewModel)
}
func configure(with model: IssueCommentImageModel) {
imageView.image = nil
imageView.backgroundColor = Styles.Colors.Gray.lighter.color
spinner.startAnimating()
let imageURL = model.url
imageView.sd_setImage(with: imageURL) { [weak self] (image, _, _, url) in
guard let strongSelf = self else { return }
strongSelf.imageView.backgroundColor = .clear
strongSelf.spinner.stopAnimating()
if let size = image?.size {
strongSelf.heightDelegate?.imageDidFinishLoad(cell: strongSelf, url: imageURL, size: size)
}
// forces the image view to lay itself out using the original image size
strongSelf.setNeedsLayout()
}
}
// MARK: UIGestureRecognizerDelegate
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer === tapGesture
else { return super.gestureRecognizerShouldBegin(gestureRecognizer) }
// only start the image tap gesture when an image exists
// and the tap is within the actual image's bounds
guard let image = imageView.image,
collapsed == false
else { return false }
let imageSize = image.size
let imageViewBounds = imageView.bounds
// https://stackoverflow.com/a/2351101/940936
let ratioX = imageViewBounds.width/imageSize.width
let ratioY = imageViewBounds.height/imageSize.height
let imageBounds: CGRect
if ratioX < ratioY {
let height = ratioX * imageSize.height
imageBounds = CGRect(
x: 0,
y: (imageViewBounds.height - height) / 2,
width: imageViewBounds.width,
height: height
)
} else {
let width = ratioY * imageSize.width
imageBounds = CGRect(
x: (imageViewBounds.width - width) / 2,
y: 0,
width: width,
height: imageViewBounds.height
)
}
let location = gestureRecognizer.location(in: imageView)
return imageBounds.contains(location)
}
}
|
mit
|
8f85df8a300011b3597ff4465d66b692
| 32.576159 | 118 | 0.656016 | 5.27027 | false | false | false | false |
darofar/lswc
|
p5-pokedex/Pokedex/AppDelegate.swift
|
1
|
3331
|
//
// AppDelegate.swift
// Pokedex
//
// Created by Santiago Pavón on 1/12/14.
// Copyright (c) 2014 UPM. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? WebViewController {
if topAsDetailController.race == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
|
apache-2.0
|
c35aa121bd61c030f2646598c75bc3d9
| 51.857143 | 285 | 0.74955 | 6.201117 | false | false | false | false |
diejmon/SugarRecord
|
library/CoreData/Base/NSManagedObject+SugarRecord.swift
|
1
|
9000
|
//
// NSManagedObject+SugarRecord.swift
// SugarRecord
//
// Created by Pedro Piñera Buendia on 07/09/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import Foundation
import CoreData
extension NSManagedObject
{
typealias SugarRecordObjectType = NSManagedObject
//MARK: - Custom Getter
/**
Returns the context where this object is alive
:returns: SugarRecord context
*/
public func context() -> SugarRecordContext
{
return SugarRecordCDContext(context: self.managedObjectContext!)
}
/**
Returns the class entity name
:returns: String with the entity name
*/
public class func modelName() -> String
{
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
/**
Returns the stack type compatible with this object
:returns: SugarRecordEngine with the type
*/
public class func stackType() -> SugarRecordEngine
{
return SugarRecordEngine.SugarRecordEngineCoreData
}
//MARK: - Filtering
/**
Returns a SugarRecord finder with the predicate set
:param: predicate NSPredicate to be set to the finder
:returns: SugarRecord finder with the predicate set
*/
public class func by(predicate: NSPredicate) -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder(predicate: predicate)
finder.objectClass = self
finder.stackType = stackType()
return finder
}
/**
Returns a SugarRecord finder with the predicate set
:param: predicateString Predicate in String format
:returns: SugarRecord finder with the predicate set
*/
public class func by(predicateString: NSString) -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.setPredicate(predicateString as String)
finder.objectClass = self
finder.stackType = stackType()
return finder
}
/**
Returns a SugarRecord finder with the predicate set
:param: key Key of the predicate to be filtered
:param: value Value of the predicate to be filtered
:returns: SugarRecord finder with the predicate set
*/
public class func by<T: Printable, R: Printable>(key: T, equalTo value: R) -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.setPredicate(byKey: "\(key)", andValue: "\(value)")
finder.objectClass = self
finder.stackType = stackType()
return finder
}
//MARK: - Sorting
/**
Returns a SugarRecord finder with the sort descriptor set
:param: sortingKey Sorting key
:param: ascending Sorting ascending value
:returns: SugarRecord finder with the predicate set
*/
public class func sorted<T: Printable>(by sortingKey: T, ascending: Bool) -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.addSortDescriptor(byKey: "\(sortingKey)", ascending: ascending)
finder.objectClass = self
finder.stackType = stackType()
return finder
}
/**
Returns a SugarRecord finder with the sort descriptor set
:param: sortDescriptor NSSortDescriptor to be set to the SugarRecord finder
:returns: SugarRecord finder with the predicate set
*/
public class func sorted(by sortDescriptor: NSSortDescriptor) -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.addSortDescriptor(sortDescriptor)
finder.objectClass = self
finder.stackType = stackType()
return finder
}
/**
Returns a SugarRecord finder with the sort descriptor set
:param: sortDescriptors Array with NSSortDescriptors
:returns: SugarRecord finder with the predicate set
*/
public class func sorted(by sortDescriptors: [NSSortDescriptor]) -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.setSortDescriptors(sortDescriptors)
finder.objectClass = self
finder.stackType = stackType()
return finder
}
//MARK: - All
/**
Returns a SugarRecord finder with .all elements enabled
:returns: SugarRecord finder
*/
public class func all() -> SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.all()
finder.objectClass = self
finder.stackType = stackType()
return finder
}
public class func first() ->SugarRecordFinder
{
var finder: SugarRecordFinder = SugarRecordFinder()
finder.first()
finder.objectClass = self
finder.stackType = stackType()
return finder
}
//MARK: - Count
/**
Returns a the count of elements of this type
:returns: Int
*/
public class func count() -> Int
{
return all().count()
}
//MARK: - Deletion
/**
* Deletes the object
*/
public func delete() -> SugarRecordContext
{
SugarRecordLogger.logLevelVerbose.log("Object \(self) deleted in its context")
return self.context().deleteObject(self)
}
//MARK: - Creation
/**
Creates a new object without inserting it in the context
:returns: Created database object
*/
public class func create() -> AnyObject
{
SugarRecordLogger.logLevelVerbose.log("Object created")
var object: AnyObject?
SugarRecord.operation(NSManagedObject.stackType(), closure: { (context) -> () in
object = context.createObject(self)
})
return object!
}
/**
Create a new object without inserting it in the passed context
:param: context Context where the object is going to be created
:returns: Created database object
*/
public class func create(inContext context: SugarRecordContext) -> AnyObject
{
SugarRecordLogger.logLevelVerbose.log("Object created")
return context.createObject(self)!
}
//MARK: - Saving
/**
Saves the object in the object context
:returns: Bool indicating if the object has been properly saved
*/
public func save () -> Bool
{
SugarRecordLogger.logLevelVerbose.log("Object saved in context")
var saved: Bool = false
self.save(false, completion: { (error) -> () in
saved = error == nil
})
return saved
}
/**
Saves the object in the object context asynchronously (or not) passing a completion closure
:param: asynchronously Bool indicating if the saving process is asynchronous or not
:param: completion Closure called when the saving operation has been completed
*/
public func save (asynchronously: Bool, completion: CompletionClosure)
{
SugarRecordLogger.logLevelVerbose.log("Saving \(self) in context")
let context: SugarRecordContext = self.context()
if asynchronously {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
context.endWriting()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(error: nil)
})
})
}
else {
context.endWriting()
completion(error: nil)
}
}
//MARK: - beginWriting
/**
Needed to be called when the object is going to be edited
:returns: returns the current object
*/
public func beginWriting() -> NSManagedObject
{
SugarRecordLogger.logLevelVerbose.log("Object did begin writing")
self.context().beginWriting()
return self
}
/**
Needed to be called when the edition/deletion has finished
*/
public func endWriting()
{
SugarRecordLogger.logLevelVerbose.log("Object did end writing")
self.context().endWriting()
}
/**
* Asks the context for writing cancellation
*/
public func cancelWriting()
{
SugarRecordLogger.logLevelVerbose.log("Object did end writing")
self.context().cancelWriting()
}
}
public func createManagedObject<T: NSManagedObject>() -> T
{
SugarRecordLogger.logLevelVerbose.log("Object created")
var object: T?
SugarRecord.operation(NSManagedObject.stackType(), closure: { (context) -> () in
object = context.createObject(T.self) as! T?
})
return object!
}
public func findFirstBy<T: NSManagedObject, KeyT: StringLiteralConvertible, ValueT: StringLiteralConvertible>(key: KeyT, value: ValueT) -> T?
{
SugarRecordLogger.logLevelVerbose.log("Find object")
var object: T? = T.self.first().by(key, equalTo: value).find().firstObject() as? T
return object
}
|
mit
|
16f3985847123d98da5c7b988840d1bd
| 26.950311 | 141 | 0.637515 | 5.139349 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/FontSetting.swift
|
1
|
1754
|
/**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** FontSetting. */
public struct FontSetting: Codable {
public var level: Int?
public var minSize: Int?
public var maxSize: Int?
public var bold: Bool?
public var italic: Bool?
public var name: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case level = "level"
case minSize = "min_size"
case maxSize = "max_size"
case bold = "bold"
case italic = "italic"
case name = "name"
}
/**
Initialize a `FontSetting` with member variables.
- parameter level:
- parameter minSize:
- parameter maxSize:
- parameter bold:
- parameter italic:
- parameter name:
- returns: An initialized `FontSetting`.
*/
public init(level: Int? = nil, minSize: Int? = nil, maxSize: Int? = nil, bold: Bool? = nil, italic: Bool? = nil, name: String? = nil) {
self.level = level
self.minSize = minSize
self.maxSize = maxSize
self.bold = bold
self.italic = italic
self.name = name
}
}
|
mit
|
d617147e56b4c1e1941bc3cf71c7b3f9
| 25.984615 | 139 | 0.644242 | 4.186158 | false | false | false | false |
STShenZhaoliang/STWeiBo
|
STWeiBo/STWeiBo/Classes/Compose/ComposeViewController.swift
|
1
|
9046
|
//
// ComposeViewController.swift
// STWeiBo
//
// Created by ST on 15/11/24.
// Copyright © 2015年 ST. All rights reserved.
//
import UIKit
import SVProgressHUD
/// 发布微博的最大长度
private let STStatusTextMaxLength = 10
class ComposeViewController: UIViewController, UITextViewDelegate {
/// 工具栏底部约束
private var toolbarBottomCons: NSLayoutConstraint?
/// 表情键盘控制器
private lazy var emoticonKeyboardVC: EmoticonViewController = EmoticonViewController { (emoticon) -> () in
self.tv.insertEmoticon(emoticon)
self.textViewDidChange(self.tv)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
// 1. 添加子控制器
addChildViewController(emoticonKeyboardVC)
// 准备导航条
prepareNavigationBar()
// 准备输入框
prepareTextView()
// 准备toolbar
prepareToolBar()
// 2.注册通知监听键盘
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
deinit {
// 注销通知
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardChange(notify: NSNotification)
{
print(notify)
// 获取最终的frame - OC 中将结构体保存在字典中,存成 NSValue
let rect = notify.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// toolbarBottomCons?.constant = -rect.height
toolbarBottomCons?.constant = -(view.bounds.height - rect!.origin.y)
// 获取动画时长
let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
// 获取动画曲线数值 - 7 苹果没有提供文档
let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
UIView.animateWithDuration(duration) { () -> Void in
// 设置动画曲线
UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
self.view.layoutIfNeeded()
}
let anim = toolbar.layer.animationForKey("position")
print(anim?.duration)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// 唤醒键盘
tv.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
tv.resignFirstResponder()
}
/**
准备导航条
*/
private func prepareNavigationBar(){
// 1. 左侧按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
// 2. 右侧按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
navigationItem.rightBarButtonItem?.enabled = false
// 3. 导航栏
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
let label1 = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
label1.text = "发微博"
label1.sizeToFit()
let label2 = UILabel(color: UIColor(white: 0.0, alpha: 0.5), fontSize: 13)
label2.text = UserAccount.loadAccount()?.name ?? ""
label2.sizeToFit()
titleView.addSubview(label1)
titleView.addSubview(label2)
label1.ST_AlignInner(type: ST_AlignType.TopCenter, referView: titleView, size: nil)
label2.ST_AlignInner(type: ST_AlignType.BottomCenter, referView: titleView, size: nil)
navigationItem.titleView = titleView
}
/// 关闭
func close() {
dismissViewControllerAnimated(true, completion: nil)
}
/// 发布微博
func sendStatus() {
// 1. 获取带表情符号的文本字符串
let text = self.tv.emoticonText()
// 2. 判断文本长度
if text.characters.count > STStatusTextMaxLength
{
SVProgressHUD.showInfoWithStatus("输入的内容过长", maskType: .Gradient)
return
}
let path = "2/statuses/update.json"
let params = ["access_token" : UserAccount.loadAccount()!.access_token! , "status" : text]
NetworkTools.sharedNetworkTools().POST(path, parameters: params, success: { (_, JSON) -> Void in
print(JSON)
SVProgressHUD.showSuccessWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
self.close()
}) { (_, error) -> Void in
print(error)
SVProgressHUD.showErrorWithStatus("发送失败", maskType: SVProgressHUDMaskType.Black)
}
}
/**
准备输入视图
*/
private func prepareTextView()
{
view.addSubview(tv)
tv.ST_Fill(view)
// 设置 占位标签
placeHolderLabel.text = "分享新鲜事..."
placeHolderLabel.sizeToFit()
tv.addSubview(placeHolderLabel)
placeHolderLabel.ST_AlignInner(type: ST_AlignType.TopLeft, referView: tv, size: nil, offset: CGPoint(x: 5, y: 8))
}
func prepareToolBar()
{
view.addSubview(toolbar)
// 提示:设置一个和按钮背景一样的颜色,具体的数值,`平面设计师`会告诉我们
toolbar.backgroundColor = UIColor(white: 0.4, alpha: 1.0)
let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
["imageName": "compose_mentionbutton_background"],
["imageName": "compose_trendbutton_background"],
["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
["imageName": "compose_addbutton_background"]]
// 所有按钮的数组
var items = [UIBarButtonItem]()
// 设置按钮 - 问题:图片名称(高亮图片) / 监听方法
for settings in itemSettings
{
items.append(UIBarButtonItem(imageName: settings["imageName"]!, highlightedImageName: nil, target: nil, actionName: settings["action"]))
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil))
}
// 删除末尾的弹簧
items.removeLast()
toolbar.items = items
// 布局toolbar
let w = UIScreen.mainScreen().bounds.width
let cons = toolbar.ST_AlignInner(type: ST_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: 44))
toolbarBottomCons = toolbar.ST_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
view.addSubview(lengthTipLabel)
lengthTipLabel.ST_AlignVertical(type: ST_AlignType.TopRight, referView: toolbar, size: nil, offset: CGPoint(x: -10, y: -10))
}
/// 选择照片
func selectPicture() {
print("选择照片")
}
/// 切换表情视图
func inputEmoticon() {
// 如果输入视图是 nil,说明使用的是系统键盘
print(tv.inputView)
// 要切换键盘之前,需要先关闭键盘
tv.resignFirstResponder()
// 更换键盘输入视图
tv.inputView = (tv.inputView == nil) ? emoticonKeyboardVC.view : nil
// 重新设置焦点
tv.becomeFirstResponder()
}
// MARK: - UITextViewDelegate
func textViewDidChange(textView: UITextView) {
// 1.修改提示文本状态
placeHolderLabel.hidden = textView.hasText()
// 2.修改发送按钮状态
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
// 3.修改文字数量
let len = STStatusTextMaxLength - textView.emoticonText().characters.count
print(len)
lengthTipLabel.text = (len == STStatusTextMaxLength) ? "" : String(len)
lengthTipLabel.textColor = len >= 0 ? UIColor.lightGrayColor() : UIColor.redColor()
}
// MARK: 懒加载
private lazy var tv: UITextView = {
let tv = UITextView()
tv.delegate = self
tv.font = UIFont.systemFontOfSize(18)
// 设置垂直滚动
tv.alwaysBounceVertical = true
// 滚动关闭键盘
tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
return tv
}()
/// 提示文本
private lazy var placeHolderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
/// 底部工具条
private lazy var toolbar = UIToolbar()
/// 长度提示标签
private lazy var lengthTipLabel: UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 12)
}
|
mit
|
4daa0f4050b1ea0ac1f6626a0e0b2c04
| 32.495968 | 149 | 0.609606 | 4.709184 | false | false | false | false |
cpmpercussion/microjam
|
chirpey/PerformerInfoHeader.swift
|
1
|
3841
|
//
// PerformerInfoHeader.swift
// microjam
//
// Created by Charles Martin on 1/5/18.
// Copyright © 2018 Charles Martin. All rights reserved.
//
import UIKit
/// The header view for a UserPerfController screen. This header shows a user's avatar and stagename.
class PerformerInfoHeader: UICollectionReusableView {
/// The assumed height for the header view.
static let headerHeight : CGFloat = 100
/// A UIImageView for the performer's avatar
let avatarImageView : UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "empty-profile-image")
imageView.layer.borderWidth = 1
imageView.layer.borderColor = UIColor(white: 0.8, alpha: 1).cgColor
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.isAccessibilityElement = true
imageView.accessibilityTraits = UIAccessibilityTraits.image
imageView.accessibilityLabel = "Avatar image"
imageView.accessibilityIdentifier = "Avatar image"
imageView.accessibilityHint = "Displays the user's avatar image"
return imageView
}()
/// A UILabel for the performer's stagename
let performerNameLabel : UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
initSubviews()
}
/// Set up the subviews and add constraints manually.
private func initSubviews() {
let avatarImageHeight : CGFloat = PerformerInfoHeader.headerHeight * 0.8
let avatarTopMargin : CGFloat = (PerformerInfoHeader.headerHeight - avatarImageHeight) / 2
let avatarSideMargin : CGFloat = 30
let stagenameSideMargin : CGFloat = 20
addSubview(avatarImageView)
addSubview(performerNameLabel)
avatarImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: avatarSideMargin).isActive = true
avatarImageView.topAnchor.constraint(equalTo: topAnchor, constant: avatarTopMargin).isActive = true
avatarImageView.heightAnchor.constraint(equalToConstant: avatarImageHeight).isActive = true
avatarImageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -avatarTopMargin).isActive = true
avatarImageView.widthAnchor.constraint(equalTo: avatarImageView.heightAnchor).isActive = true
performerNameLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
performerNameLabel.leftAnchor.constraint(equalTo: avatarImageView.rightAnchor, constant: stagenameSideMargin).isActive = true
performerNameLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -(stagenameSideMargin)).isActive = true
avatarImageView.backgroundColor = .lightGray
avatarImageView.contentMode = .scaleAspectFill
avatarImageView.layer.cornerRadius = avatarImageHeight / 2
avatarImageView.clipsToBounds = true
performerNameLabel.font = performerNameLabel.font.withSize(24)
setColourTheme() // Set dark/light theme
}
required init?(coder aDecoder: NSCoder) {
fatalError("Required init not implemented")
}
}
// Set up dark and light mode.
extension PerformerInfoHeader {
@objc func setColourTheme() {
if UserDefaults.standard.bool(forKey: SettingsKeys.darkMode) {
setDarkMode()
} else {
setLightMode()
}
}
func setDarkMode() {
backgroundColor = DarkMode.background
performerNameLabel.textColor = DarkMode.text
}
func setLightMode() {
backgroundColor = LightMode.background
performerNameLabel.textColor = LightMode.text
}
}
|
mit
|
852cbd0cc5a80a183c269fdff8878e16
| 38.183673 | 133 | 0.694531 | 5.385694 | false | false | false | false |
khizkhiz/swift
|
stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
|
1
|
7762
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported
import ObjectiveC
//===----------------------------------------------------------------------===//
// Objective-C Primitive Types
//===----------------------------------------------------------------------===//
public typealias Boolean = Swift.Boolean
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
public struct ObjCBool : Boolean, BooleanLiteralConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value : Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertBoolToObjCBool(x: Bool) -> ObjCBool {
return ObjCBool(x)
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertObjCBoolToBool(x: ObjCBool) -> Bool {
return Bool(x)
}
/// The Objective-C SEL type.
///
/// The Objective-C SEL type is typically an opaque pointer. Swift
/// treats it as a distinct struct type, with operations to
/// convert between C strings and selectors.
///
/// The compiler has special knowledge of this type.
public struct Selector : StringLiteralConvertible, NilLiteralConvertible {
var ptr : OpaquePointer
/// Create a selector from a string.
public init(_ str : String) {
ptr = str.withCString { sel_registerName($0).ptr }
}
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
/// Construct a selector from `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
// FIXME: Fast-path this in the compiler, so we don't end up with
// the sel_registerName call at compile time.
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = sel_registerName(value)
}
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
ptr = nil
}
}
@warn_unused_result
public func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
extension Selector : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return ptr.hashValue
}
}
extension Selector : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
let name = sel_getName(self)
if name == nil {
return "<NULL>"
}
return String(cString: name)
}
}
extension String {
/// Construct the C string representation of an Objective-C selector.
public init(_sel: Selector) {
// FIXME: This misses the ASCII optimization.
self = String(cString: sel_getName(_sel))
}
}
extension Selector : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: String(_sel: self))
}
}
//===----------------------------------------------------------------------===//
// NSZone
//===----------------------------------------------------------------------===//
public struct NSZone : NilLiteralConvertible {
var pointer : OpaquePointer
public init() { pointer = nil }
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
pointer = nil
}
}
// Note: NSZone becomes Zone in Swift 3.
typealias Zone = NSZone
//===----------------------------------------------------------------------===//
// FIXME: @autoreleasepool substitute
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("objc_autoreleasePoolPush")
func __pushAutoreleasePool() -> OpaquePointer
@_silgen_name("objc_autoreleasePoolPop")
func __popAutoreleasePool(pool: OpaquePointer)
public func autoreleasepool(@noescape code: () -> Void) {
let pool = __pushAutoreleasePool()
code()
__popAutoreleasePool(pool)
}
//===----------------------------------------------------------------------===//
// Mark YES and NO unavailable.
//===----------------------------------------------------------------------===//
@available(*, unavailable, message="Use 'Bool' value 'true' instead")
public var YES: ObjCBool {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, message="Use 'Bool' value 'false' instead")
public var NO: ObjCBool {
fatalError("can't retrieve unavailable property")
}
// FIXME: We can't make the fully-generic versions @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for ObjCBool
@_transparent
@warn_unused_result
public func && <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func || <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? true : rhs().boolValue
}
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// NSObject implements Equatable's == as -[NSObject isEqual:]
// NSObject implements Hashable's hashValue() as -[NSObject hash]
// FIXME: what about NSObjectProtocol?
extension NSObject : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return hash
}
}
@warn_unused_result
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
extension NSObject : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
public var _cVarArgEncoding: [Int] {
_autorelease(self)
return _encodeBitsAsWords(self)
}
}
|
apache-2.0
|
d7c75f6c26be281884778800c47c7be0
| 27.021661 | 80 | 0.60049 | 4.443045 | false | false | false | false |
fousa/trackkit
|
Example/Tests/Tests/FIT/FITHealthFitSpecs.swift
|
1
|
4379
|
//
// FITHealthFitSpecs.swift
// Tests
//
// Created by Jelle Vandebeeck on 15/05/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TrackKit
class FITHealthFitSpecs: QuickSpec {
override func spec() {
describe("FIT") {
context("HealthFit Export") {
var file: File!
beforeEach {
let url = Bundle(for: FITGarminBikeRideSpecs.self).url(forResource: "HealthFit", withExtension: "fit")!
let data = try! Data(contentsOf: url)
file = try! TrackParser(data: data, type: .fit).parse()
}
it("should not have routes") {
expect(file.courses?.count) == 0
}
it("should have one activity") {
expect(file.activities?.count) == 1
}
context("laps") {
var activity: Activity!
beforeEach {
activity = file.activities?.first!
}
it("should have some laps") {
expect(activity.laps?.count) == 1
}
it("should have a lap start time") {
expect(activity.laps?.last?.startTime?.description).to(beNil())
}
it("should have a lap total time") {
expect(activity.laps?.last?.totalTime).to(beNil())
}
it("should have a lap total distance") {
expect(activity.laps?.last?.totalDistance).to(beNil())
}
it("should have a lap maximum speed") {
expect(activity.laps?.last?.maximumSpeed).to(beNil())
}
it("should have a lap calories") {
expect(activity.laps?.last?.calories).to(beNil())
}
it("should have a lap average heart rate") {
expect(activity.laps?.last?.averageHeartRate).to(beNil())
}
it("should have a lap maximum heart rate") {
expect(activity.laps?.last?.maximumHeartRate).to(beNil())
}
it("should have a lap cadence") {
expect(activity.laps?.last?.cadence).to(beNil())
}
it("should have some points") {
expect(activity.laps?.last?.points?.count) == 1620
}
}
context("points") {
var point: Point!
beforeEach {
point = file.activities?.first?.laps?.last?.points?.last!
}
it("should have a track point time") {
expect(point.time?.description) == "2018-05-11 22:13:49 +0000"
}
it("should have a coordinate") {
expect(point.coordinate?.latitude).to(beCloseTo(49.8698, within: 0.0001))
expect(point.coordinate?.longitude).to(beCloseTo(-97.1051, within: 0.0001))
}
it("should have a altitude in meters") {
expect(point.elevation).to(beCloseTo(234, within: 0.1))
}
it("should have a distance in meters") {
expect(point.distance).to(beCloseTo(9625.7305, within: 0.0001))
}
it("should have a cadence") {
expect(point.cadence).to(beNil())
}
it("should have a heart rate") {
expect(point.heartRate).to(beNil())
}
}
}
}
}
}
|
mit
|
8bbb99427a1f18f34fcdbc801e3a5edb
| 37.403509 | 123 | 0.394472 | 5.760526 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/MigrationHubConfig/MigrationHubConfig_Paginator.swift
|
1
|
3502
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension MigrationHubConfig {
/// This API permits filtering on the ControlId and HomeRegion fields.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func describeHomeRegionControlsPaginator<Result>(
_ input: DescribeHomeRegionControlsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeHomeRegionControlsResult, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeHomeRegionControls,
tokenKey: \DescribeHomeRegionControlsResult.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func describeHomeRegionControlsPaginator(
_ input: DescribeHomeRegionControlsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeHomeRegionControlsResult, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeHomeRegionControls,
tokenKey: \DescribeHomeRegionControlsResult.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension MigrationHubConfig.DescribeHomeRegionControlsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> MigrationHubConfig.DescribeHomeRegionControlsRequest {
return .init(
controlId: self.controlId,
homeRegion: self.homeRegion,
maxResults: self.maxResults,
nextToken: token,
target: self.target
)
}
}
|
apache-2.0
|
3f8d35b530dc6de8815d12dc7959c2cc
| 40.690476 | 168 | 0.640777 | 5.104956 | false | false | false | false |
garygriswold/Bible.js
|
Plugins/AudioPlayer/src/ios_oldApp/AudioPlayer/AudioAnalyticsSessionId.swift
|
2
|
3365
|
//
// AudioAnalyticsSessionId.swift
// AnalyticsProto
//
// Created by Gary Griswold on 6/6/17.
// Copyright © 2017 ShortSands. All rights reserved.
//
/**
* Originally, this class was going to get new sessionId's from a single external source in order
* to guarantee uniqueness. However, I decided that the sequence of events including some access of
* to that server followed by other access to AWS could in itself become a signature that could be
* tracked. I instead use a random number UUID. Using a more official GUID would be better at
* guranteeing uniqueness, but it might be possible for someone to identify a MAC address from
* that kind of GUID. So, I use a random number UUID, i.e. version 4. For the purpose this
* sessionId serves, it will not cause much of a problem if identical sessionIds are created on
* some rare occasion. Gary Griswold June 7, 2017
*
* NOTE: A nearly identical class exists in the Video Player. This one has been updated to use Library/Caches
*/
import Foundation
class AudioAnalyticsSessionId {
static let SESSION_KEY: String = "ShortSandsSessionId"
let archiveURL: URL
init() {
let homeDir: URL = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
let libDir: URL = homeDir.appendingPathComponent("Library")
let cacheDir = libDir.appendingPathComponent("Caches")
archiveURL = cacheDir.appendingPathComponent(AudioAnalyticsSessionId.SESSION_KEY)
}
deinit {
print("***** Deinit AudioAnalyticsSessionId *****")
}
func getSessionId() -> String {
let sessionId: String? = retrieveSessionId()
if (sessionId != nil) {
return sessionId!
} else {
let newSessionId = UUID().uuidString
self.saveSessionId(sessionId: newSessionId)
return newSessionId
}
}
private func retrieveSessionId() -> String? {
let sessionId = NSKeyedUnarchiver.unarchiveObject(withFile: self.archiveURL.path) as? String
return sessionId
}
private func saveSessionId(sessionId: String) -> Void {
NSKeyedArchiver.archiveRootObject(sessionId, toFile: self.archiveURL.path)
}
/**
* Deprecated. This is a method for getting sessionId from an external source, but I decided
* that the timing of this query to a distinct non-AWS source, could become a signature, and
* so it was abandoned.
*/
private func getNewSessionIdDeprecated(complete: @escaping (_ sessionId:String) -> Void) {
let url = URL(string: "https://www.uuidgenerator.net/api/version1")!
let session = URLSession.shared
let task = session.dataTask(with: url) {
data, response, error in
if let err = error {
print(err.localizedDescription)
complete(UUID().uuidString)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
let guid = String(data: data!, encoding: String.Encoding.ascii)
complete(guid!)
}
} else {
print("Unexpected state in getNewSessionId! Create UUID instead")
complete(UUID().uuidString)
}
}
task.resume()
}
}
|
mit
|
6acf2396c3a72ed03c34c011aed75c96
| 38.116279 | 110 | 0.648335 | 4.751412 | false | false | false | false |
terut/Wayfaring
|
Example/Example/AppDelegate.swift
|
1
|
3220
|
//
// AppDelegate.swift
// Example
// Copyright (c) 2015年 terut. All rights reserved.
//
import UIKit
import Wayfaring
enum AppResource: Resource {
case first, second
// MARK: - Resource
static var all: [Resource] {
return [first, second]
}
// MARK: - Resource
var path: String {
switch self {
case .first:
return "/first"
case .second:
return "/second/:second_id"
}
}
var identifier: String {
switch self {
case .first:
return "firstView"
case .second:
return "secondView"
}
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Routes.sharedInstance.bootstrap(AppResource.all)
let navController = self.window?.rootViewController as! UINavigationController
//let targetURL = "com.example://first"
let targetURL = "com.example://second/secsec"
//let targetURL = "com.example://third/check"
(navController.topViewController as! ViewController).targetURL = targetURL
return true
}
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
6150bcc9d9498a622c22bd169a509802
| 37.309524 | 285 | 0.70261 | 5.408403 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainSuggestions/RegisterDomainSuggestionsViewController.swift
|
1
|
14448
|
import SwiftUI
import UIKit
import WebKit
import WordPressAuthenticator
import WordPressFlux
class RegisterDomainSuggestionsViewController: UIViewController {
@IBOutlet weak var buttonContainerBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonContainerViewHeightConstraint: NSLayoutConstraint!
private var constraintsInitialized = false
private var site: Blog!
var domainPurchasedCallback: ((String) -> Void)!
private var domain: FullyQuotedDomainSuggestion?
private var siteName: String?
private var domainsTableViewController: DomainSuggestionsTableViewController?
private var domainType: DomainType = .registered
private var includeSupportButton: Bool = true
private var webViewURLChangeObservation: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
configure()
hideButton()
}
@IBOutlet private var buttonViewContainer: UIView! {
didSet {
buttonViewController.move(to: self, into: buttonViewContainer)
}
}
private lazy var buttonViewController: NUXButtonViewController = {
let buttonViewController = NUXButtonViewController.instance()
buttonViewController.view.backgroundColor = .basicBackground
buttonViewController.delegate = self
buttonViewController.setButtonTitles(
primary: TextContent.primaryButtonTitle
)
return buttonViewController
}()
static func instance(site: Blog,
domainType: DomainType = .registered,
includeSupportButton: Bool = true,
domainPurchasedCallback: ((String) -> Void)? = nil) -> RegisterDomainSuggestionsViewController {
let storyboard = UIStoryboard(name: Constants.storyboardIdentifier, bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: Constants.viewControllerIdentifier) as! RegisterDomainSuggestionsViewController
controller.site = site
controller.domainType = domainType
controller.domainPurchasedCallback = domainPurchasedCallback
controller.includeSupportButton = includeSupportButton
controller.siteName = siteNameForSuggestions(for: site)
return controller
}
private static func siteNameForSuggestions(for site: Blog) -> String? {
if let siteTitle = site.settings?.name?.nonEmptyString() {
return siteTitle
}
if let siteUrl = site.url {
let components = URLComponents(string: siteUrl)
if let firstComponent = components?.host?.split(separator: ".").first {
return String(firstComponent)
}
}
return nil
}
private func configure() {
title = TextContent.title
WPStyleGuide.configureColors(view: view, tableView: nil)
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel,
target: self,
action: #selector(handleCancelButtonTapped))
navigationItem.leftBarButtonItem = cancelButton
guard includeSupportButton else {
return
}
let supportButton = UIBarButtonItem(title: TextContent.supportButtonTitle,
style: .plain,
target: self,
action: #selector(handleSupportButtonTapped))
navigationItem.rightBarButtonItem = supportButton
}
// MARK: - Bottom Hideable Button
/// Shows the domain picking button
///
private func showButton() {
buttonContainerBottomConstraint.constant = 0
}
/// Shows the domain picking button
///
/// - Parameters:
/// - animated: whether the transition is animated.
///
private func showButton(animated: Bool) {
guard animated else {
showButton()
return
}
UIView.animate(withDuration: WPAnimationDurationDefault, animations: { [weak self] in
guard let self = self else {
return
}
self.showButton()
// Since the Button View uses auto layout, need to call this so the animation works properly.
self.view.layoutIfNeeded()
}, completion: nil)
}
private func hideButton() {
buttonViewContainer.layoutIfNeeded()
buttonContainerBottomConstraint.constant = buttonViewContainer.frame.height
}
/// Hides the domain picking button
///
/// - Parameters:
/// - animated: whether the transition is animated.
///
func hideButton(animated: Bool) {
guard animated else {
hideButton()
return
}
UIView.animate(withDuration: WPAnimationDurationDefault, animations: { [weak self] in
guard let self = self else {
return
}
self.hideButton()
// Since the Button View uses auto layout, need to call this so the animation works properly.
self.view.layoutIfNeeded()
}, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let vc = segue.destination as? DomainSuggestionsTableViewController {
vc.delegate = self
vc.siteName = siteName
vc.blog = site
vc.domainType = domainType
vc.freeSiteAddress = site.freeSiteAddress
if site.hasBloggerPlan {
vc.domainSuggestionType = .allowlistedTopLevelDomains(["blog"])
}
domainsTableViewController = vc
}
}
// MARK: - Nav Bar Button Handling
@objc private func handleCancelButtonTapped(sender: UIBarButtonItem) {
dismiss(animated: true)
}
@objc private func handleSupportButtonTapped(sender: UIBarButtonItem) {
let supportVC = SupportTableViewController()
supportVC.showFromTabBar()
}
}
// MARK: - DomainSuggestionsTableViewControllerDelegate
extension RegisterDomainSuggestionsViewController: DomainSuggestionsTableViewControllerDelegate {
func domainSelected(_ domain: FullyQuotedDomainSuggestion) {
WPAnalytics.track(.automatedTransferCustomDomainSuggestionSelected)
self.domain = domain
showButton(animated: true)
}
func newSearchStarted() {
WPAnalytics.track(.automatedTransferCustomDomainSuggestionQueried)
hideButton(animated: true)
}
}
// MARK: - NUXButtonViewControllerDelegate
extension RegisterDomainSuggestionsViewController: NUXButtonViewControllerDelegate {
func primaryButtonPressed() {
guard let domain = domain else {
return
}
WPAnalytics.track(.domainsSearchSelectDomainTapped, properties: WPAnalytics.domainsProperties(for: site), blog: site)
switch domainType {
case .registered:
pushRegisterDomainDetailsViewController(domain)
case .siteRedirect:
setPrimaryButtonLoading(true)
createCartAndPresentWebView(domain)
default:
break
}
}
private func setPrimaryButtonLoading(_ isLoading: Bool, afterDelay delay: Double = 0.0) {
// We're dispatching here so that we can wait until after the webview has been
// fully presented before we switch the button back to its default state.
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.buttonViewController.setBottomButtonState(isLoading: isLoading,
isEnabled: !isLoading)
}
}
private func pushRegisterDomainDetailsViewController(_ domain: FullyQuotedDomainSuggestion) {
guard let siteID = site.dotComID?.intValue else {
DDLogError("Cannot register domains for sites without a dotComID")
return
}
let controller = RegisterDomainDetailsViewController()
controller.viewModel = RegisterDomainDetailsViewModel(siteID: siteID, domain: domain, domainPurchasedCallback: domainPurchasedCallback)
self.navigationController?.pushViewController(controller, animated: true)
}
private func createCartAndPresentWebView(_ domain: FullyQuotedDomainSuggestion) {
guard let siteID = site.dotComID?.intValue else {
DDLogError("Cannot register domains for sites without a dotComID")
return
}
let proxy = RegisterDomainDetailsServiceProxy()
proxy.createPersistentDomainShoppingCart(siteID: siteID,
domainSuggestion: domain.remoteSuggestion(),
privacyProtectionEnabled: domain.supportsPrivacy ?? false,
success: { [weak self] _ in
self?.presentWebViewForCurrentSite(domainSuggestion: domain)
self?.setPrimaryButtonLoading(false, afterDelay: 0.25)
},
failure: { error in })
}
static private let checkoutURLPrefix = "https://wordpress.com/checkout"
static private let checkoutSuccessURLPrefix = "https://wordpress.com/checkout/thank-you/"
/// Handles URL changes in the web view. We only allow the user to stay within certain URLs. Falling outside these URLs
/// results in the web view being dismissed. This method also handles the success condition for a successful domain registration
/// through said web view.
///
/// - Parameters:
/// - newURL: the newly set URL for the web view.
/// - siteID: the ID of the site we're trying to register the domain against.
/// - domain: the domain the user is purchasing.
/// - onCancel: the closure that will be executed if we detect the conditions for cancelling the registration were met.
/// - onSuccess: the closure that will be executed if we detect a successful domain registration.
///
private func handleWebViewURLChange(
_ newURL: URL,
siteID: Int,
domain: String,
onCancel: () -> Void,
onSuccess: (String) -> Void) {
let canOpenNewURL = newURL.absoluteString.starts(with: Self.checkoutURLPrefix)
guard canOpenNewURL else {
onCancel()
return
}
let domainRegistrationSucceeded = newURL.absoluteString.starts(with: Self.checkoutSuccessURLPrefix)
if domainRegistrationSucceeded {
onSuccess(domain)
}
}
private func presentWebViewForCurrentSite(domainSuggestion: FullyQuotedDomainSuggestion) {
guard let homeURL = site.homeURL,
let siteUrl = URL(string: homeURL as String), let host = siteUrl.host,
let url = URL(string: Constants.checkoutWebAddress + host),
let siteID = site.dotComID?.intValue else {
return
}
let webViewController = WebViewControllerFactory.controllerWithDefaultAccountAndSecureInteraction(url: url, source: "domains_register")
let navController = LightNavigationController(rootViewController: webViewController)
// WORKAROUND: The reason why we have to use this mechanism to detect success and failure conditions
// for domain registration is because our checkout process (for some unknown reason) doesn't trigger
// call to WKWebViewDelegate methods.
//
// This was last checked by @diegoreymendez on 2021-09-22.
//
webViewURLChangeObservation = webViewController.webView.observe(\.url, options: .new) { [weak self] _, change in
guard let self = self,
let newURL = change.newValue as? URL else {
return
}
self.handleWebViewURLChange(newURL, siteID: siteID, domain: domainSuggestion.domainName, onCancel: {
navController.dismiss(animated: true)
}) { domain in
self.dismiss(animated: true, completion: { [weak self] in
self?.domainPurchasedCallback(domain)
})
}
}
WPAnalytics.track(.domainsPurchaseWebviewViewed, properties: WPAnalytics.domainsProperties(for: site), blog: site)
if let storeSandboxCookie = (HTTPCookieStorage.shared.cookies?.first {
$0.properties?[.name] as? String == Constants.storeSandboxCookieName &&
$0.properties?[.domain] as? String == Constants.storeSandboxCookieDomain
}) {
// this code will only run if a store sandbox cookie has been set
let webView = webViewController.webView
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
cookieStore.getAllCookies { [weak self] cookies in
var newCookies = cookies
newCookies.append(storeSandboxCookie)
cookieStore.setCookies(newCookies) {
self?.present(navController, animated: true)
}
}
} else {
present(navController, animated: true)
}
}
}
// MARK: - Constants
extension RegisterDomainSuggestionsViewController {
enum TextContent {
static let title = NSLocalizedString("Search domains",
comment: "Search domain - Title for the Suggested domains screen")
static let primaryButtonTitle = NSLocalizedString("Select domain",
comment: "Register domain - Title for the Choose domain button of Suggested domains screen")
static let supportButtonTitle = NSLocalizedString("Help", comment: "Help button")
}
enum Constants {
// storyboard identifiers
static let storyboardIdentifier = "RegisterDomain"
static let viewControllerIdentifier = "RegisterDomainSuggestionsViewController"
static let checkoutWebAddress = "https://wordpress.com/checkout/"
// store sandbox cookie
static let storeSandboxCookieName = "store_sandbox"
static let storeSandboxCookieDomain = ".wordpress.com"
}
}
|
gpl-2.0
|
e4b2aebc3687025f5e616994df598e3d
| 37.425532 | 157 | 0.638704 | 5.64375 | false | false | false | false |
danielallsopp/Charts
|
Source/Charts/Highlight/ChartHighlight.swift
|
14
|
6733
|
//
// ChartHighlight.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
public class ChartHighlight: NSObject
{
/// the x-index of the highlighted value
private var _xIndex = Int(0)
/// the y-value of the highlighted value
private var _value = Double.NaN
/// the index of the data object - in case it refers to more than one
private var _dataIndex = Int(0)
/// the index of the dataset the highlighted value is in
private var _dataSetIndex = Int(0)
/// index which value of a stacked bar entry is highlighted
///
/// **default**: -1
private var _stackIndex = Int(-1)
/// the range of the bar that is selected (only for stacked-barchart)
private var _range: ChartRange?
public override init()
{
super.init()
}
/// - parameter xIndex: the index of the highlighted value on the x-axis
/// - parameter value: the y-value of the highlighted value
/// - parameter dataIndex: the index of the Data the highlighted value belongs to
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter range: the range the selected stack-value is in
public init(xIndex x: Int, value: Double, dataIndex: Int, dataSetIndex: Int, stackIndex: Int, range: ChartRange?)
{
super.init()
_xIndex = x
_value = value
_dataIndex = dataIndex
_dataSetIndex = dataSetIndex
_stackIndex = stackIndex
_range = range
}
/// - parameter xIndex: the index of the highlighted value on the x-axis
/// - parameter value: the y-value of the highlighted value
/// - parameter dataIndex: the index of the Data the highlighted value belongs to
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
public convenience init(xIndex x: Int, value: Double, dataIndex: Int, dataSetIndex: Int, stackIndex: Int)
{
self.init(xIndex: x, value: value, dataIndex: dataIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: nil)
}
/// - parameter xIndex: the index of the highlighted value on the x-axis
/// - parameter value: the y-value of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter range: the range the selected stack-value is in
public convenience init(xIndex x: Int, value: Double, dataSetIndex: Int, stackIndex: Int, range: ChartRange?)
{
self.init(xIndex: x, value: value, dataIndex: 0, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: range)
}
/// - parameter xIndex: the index of the highlighted value on the x-axis
/// - parameter value: the y-value of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter range: the range the selected stack-value is in
public convenience init(xIndex x: Int, value: Double, dataSetIndex: Int, stackIndex: Int)
{
self.init(xIndex: x, value: value, dataIndex: 0, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: nil)
}
/// - parameter xIndex: the index of the highlighted value on the x-axis
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
public convenience init(xIndex x: Int, dataSetIndex: Int, stackIndex: Int)
{
self.init(xIndex: x, value: Double.NaN, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: nil)
}
/// - parameter xIndex: the index of the highlighted value on the x-axis
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
public convenience init(xIndex x: Int, dataSetIndex: Int)
{
self.init(xIndex: x, value: Double.NaN, dataSetIndex: dataSetIndex, stackIndex: -1, range: nil)
}
public var xIndex: Int { return _xIndex }
public var value: Double { return _value }
public var dataIndex: Int { return _dataIndex }
public var dataSetIndex: Int { return _dataSetIndex }
public var stackIndex: Int { return _stackIndex }
/// - returns: the range of values the selected value of a stacked bar is in. (this is only relevant for stacked-barchart)
public var range: ChartRange? { return _range }
// MARK: NSObject
public override var description: String
{
return "Highlight, xIndex: \(_xIndex), dataIndex (combined charts): \(_dataIndex),dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex), value: \(_value)"
}
public override func isEqual(object: AnyObject?) -> Bool
{
if (object === nil)
{
return false
}
if (!object!.isKindOfClass(self.dynamicType))
{
return false
}
if (object!.xIndex != _xIndex)
{
return false
}
if (object!.dataIndex != dataIndex)
{
return false
}
if (object!.dataSetIndex != _dataSetIndex)
{
return false
}
if (object!.stackIndex != _stackIndex)
{
return false
}
if (object!.value != value)
{
return false
}
return true
}
}
func ==(lhs: ChartHighlight, rhs: ChartHighlight) -> Bool
{
if (lhs === rhs)
{
return true
}
if (!lhs.isKindOfClass(rhs.dynamicType))
{
return false
}
if (lhs._xIndex != rhs._xIndex)
{
return false
}
if (lhs._dataIndex != rhs._dataIndex)
{
return false
}
if (lhs._dataSetIndex != rhs._dataSetIndex)
{
return false
}
if (lhs._stackIndex != rhs._stackIndex)
{
return false
}
if (lhs._value != rhs._value)
{
return false
}
return true
}
|
apache-2.0
|
14cfbd3dc1ca45f16b3d41fe92136553
| 32.336634 | 191 | 0.6281 | 4.67245 | false | false | false | false |
kickstarter/ios-oss
|
Kickstarter-iOS/Features/SettingsNewsletters/Datasource/SettingsNewslettersDataSourceTests.swift
|
1
|
2024
|
@testable import Kickstarter_Framework
@testable import KsApi
@testable import Library
import Prelude
import XCTest
final class SettingsNewslettersDataSourceTests: XCTestCase {
let dataSource = SettingsNewslettersDataSource()
let tableView = UITableView()
func testLoadData() {
let newsletters = Newsletter.allCases
let user = User.template
let totalRows = newsletters.count + 1 // We add a cell (Subscribe to All) on top
self.dataSource.load(newsletters: newsletters, user: user)
XCTAssertEqual(1, self.dataSource.numberOfSections(in: self.tableView))
XCTAssertEqual(totalRows, self.dataSource.tableView(self.tableView, numberOfRowsInSection: 0))
}
func testSubscribeToAllCell_IsAddedOnTheTop() {
let newsletters = Newsletter.allCases
let user = User.template
self.dataSource.load(newsletters: newsletters, user: user)
XCTAssertEqual("SettingsNewslettersTopCell", self.dataSource.reusableId(item: 0, section: 0))
}
func testNewsletterCells_AreAddedAfterTopCell() {
let newsletters = Newsletter.allCases
let user = User.template
self.dataSource.load(newsletters: newsletters, user: user)
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 1, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 2, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 3, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 4, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 5, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 6, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 7, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 8, section: 0))
XCTAssertEqual("SettingsNewslettersCell", self.dataSource.reusableId(item: 9, section: 0))
}
}
|
apache-2.0
|
6fb363df6b52e89ccb6b7860d6a8fe9b
| 43.977778 | 98 | 0.769269 | 4.315565 | false | true | false | false |
Chaosspeeder/YourGoals
|
YourGoals/UI/Views/CalendarBarView/CalendarBarView.swift
|
1
|
4668
|
//
// CalendarBarView.swift
// YourGoals
//
// Created by André Claaßen on 25.07.19.
// Copyright © 2019 André Claaßen. All rights reserved.
//
import UIKit
protocol CalendarBarViewDelegate {
func activeDayChanged(newDate: Date)
}
/// calendar bar view
class CalendarBarView: NibLoadingView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
@IBOutlet weak var dayOfWeekTextView: UILabel!
@IBOutlet weak var weekDaysView: UICollectionView!
let spacingBetweenViewCells:CGFloat = 0.0
var delegate:CalendarBarViewDelegate!
var referenceDate = Date().day()
var numberOfDays = 360
let dayOfWeekTextViewColor = UIColor(red: 0.0, green: 0.478, blue: 1.00, alpha: 1.0)
override init(frame: CGRect) {
super.init(frame: frame)
setupControl()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupControl()
}
func setupControl() {
self.dayOfWeekTextView.textColor = dayOfWeekTextViewColor
weekDaysView.register(CalendarBarCell.self, forCellWithReuseIdentifier: CalendarBarCell.reuseIdentifier)
weekDaysView.delegate = self
weekDaysView.dataSource = self
weekDaysView.allowsSelection = true
weekDaysView.isPagingEnabled = true
weekDaysView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
weekDaysView.reloadData()
}
/// configure this view from the containing view controller
///
/// - Parameters:
/// - delegate: a delegate for events of this view
/// - activeDate: the initial date
func configure(delegate: CalendarBarViewDelegate, activeDate: Date) {
self.delegate = delegate
selectCalendarCell(forDate: activeDate)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfDays
}
/// calc a date from a reference and the row in the index path
func calcDateForPath(referenceDate: Date, path: IndexPath) -> Date {
let startOfWeek = referenceDate.startOfWeek
let date = startOfWeek.addDaysToDate(path.row)
return date
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let calendarBarCell = CalendarBarCell.dequeue(fromCollectionView: self.weekDaysView, atIndexPath: indexPath)
let date = calcDateForPath(referenceDate: self.referenceDate, path: indexPath)
let progress = 0.75
let value = CalendarBarCellValue(date: date, progress: progress)
calendarBarCell.dayNumberLabelSelectedColor = self.dayOfWeekTextViewColor
calendarBarCell.configure(value: value)
return calendarBarCell
}
/// calculate the indexpath in the range between 0 and self.number of days
///
/// - Parameter date: the date
/// - Returns: a indexpath for the date
func calcIndexPath(forDate date:Date) -> IndexPath? {
let days = min(0, max(date.numberOfDays(since: self.referenceDate), numberOfDays))
return IndexPath(row: days, section: 0)
}
func selectCalendarCell(forDate date:Date) {
let indexPath = calcIndexPath(forDate: date)
weekDaysView.selectItem(at: indexPath, animated: false, scrollPosition: .left)
}
// Mark: UICollectionViewDelegateFlowLayout
/// calculate the size of a cell in the flow layout so that 7 cells for seven days are horizontally arranged
///
/// - Parameters:
/// - collectionView: the collecton view
/// - collectionViewLayout: the layout
/// - indexPath: the item (ignored)
/// - Returns: a reasonayble size for a calendar view cell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 7.0 - 1.0
let size = CGSize(width: width, height: 45.0)
return size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
}
|
lgpl-3.0
|
558c1237b58bf24d7596afb66fa73926
| 36.604839 | 175 | 0.688827 | 5.079521 | false | false | false | false |
oxozle/oxkit-swift
|
Sources/Extensions/UIApplication.swift
|
1
|
4803
|
//
// UIApplication.swift
// OXKit
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Dmitriy Azarov. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
/// Animation type of change root view controller
///
/// - none: without animation
/// - transitionCrossDissolve: A transition that dissolves from one view to the next.
/// - scale: Custom scale transition
public enum ChangeRootViewControllerAnimation {
case none
case transitionCrossDissolve
case transitionFlipFromRight
case scale
}
extension UIApplication {
public func universalOpenUrl(_ url: URL) {
if #available(iOS 10, *) {
open(url, options: [:],
completionHandler: {
(success) in
print("Open \(url): \(success)")
})
} else {
let success = openURL(url)
print("Open \(url): \(success)")
}
}
/// Return the specific topViewController in application
public class func topViewController(_ viewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = viewController as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = viewController as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = viewController?.presentedViewController {
return topViewController(presented)
}
return viewController
}
public func switchRootViewController(_ window: UIWindow?, rootViewController: UIViewController, animation: ChangeRootViewControllerAnimation, completion: (() -> Void)?) {
if let window = window {
switch animation {
case .none:
window.rootViewController = rootViewController
case .transitionFlipFromRight:
UIView.transition(with: window, duration: 0.4, options: .transitionFlipFromRight, animations: {
let oldState: Bool = UIView.areAnimationsEnabled
UIView.setAnimationsEnabled(false)
window.rootViewController = rootViewController
UIView.setAnimationsEnabled(oldState)
}, completion: { (finished: Bool) -> () in
completion?()
})
case .transitionCrossDissolve:
UIView.transition(with: window, duration: 0.4, options: .transitionCrossDissolve, animations: {
let oldState: Bool = UIView.areAnimationsEnabled
UIView.setAnimationsEnabled(false)
window.rootViewController = rootViewController
UIView.setAnimationsEnabled(oldState)
}, completion: { (finished: Bool) -> () in
completion?()
})
case .scale:
let snapshot: UIView = window.snapshotView(afterScreenUpdates: true)!
rootViewController.view.addSubview(snapshot);
window.rootViewController = rootViewController;
UIView.animate(withDuration: 0.4, animations: {() in
snapshot.layer.opacity = 0;
snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5);
}, completion: {
(value: Bool) in
snapshot.removeFromSuperview();
completion?()
});
}
}
}
}
|
mit
|
26ea4b84ec30c363ae0c9e6c8181fbff
| 39.70339 | 174 | 0.612534 | 5.617544 | false | false | false | false |
milseman/swift
|
test/SILGen/erasure_reabstraction.swift
|
14
|
801
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
struct Foo {}
class Bar {}
// CHECK: [[CONCRETE:%.*]] = init_existential_addr [[EXISTENTIAL:%.*]] : $*Any, $Foo.Type
// CHECK: [[METATYPE:%.*]] = metatype $@thick Foo.Type
// CHECK: store [[METATYPE]] to [trivial] [[CONCRETE]] : $*@thick Foo.Type
let x: Any = Foo.self
// CHECK: [[CONCRETE:%.*]] = init_existential_addr [[EXISTENTIAL:%.*]] : $*Any, $() -> ()
// CHECK: [[CLOSURE:%.*]] = function_ref
// CHECK: [[CLOSURE_THICK:%.*]] = thin_to_thick_function [[CLOSURE]]
// CHECK: [[REABSTRACTION_THUNK:%.*]] = function_ref @_T0Ix_ytytIxir_TR
// CHECK: [[CLOSURE_REABSTRACTED:%.*]] = partial_apply [[REABSTRACTION_THUNK]]([[CLOSURE_THICK]])
// CHECK: store [[CLOSURE_REABSTRACTED]] to [init] [[CONCRETE]]
let y: Any = {() -> () in ()}
|
apache-2.0
|
372002ff915d48c5837fb0bdde9cf66e
| 41.157895 | 97 | 0.605493 | 3.482609 | false | false | false | false |
Rauleinstein/iSWAD
|
iSWAD/iSWAD/MasterViewController.swift
|
1
|
3294
|
//
// MasterViewController.swift
// iSWAD
//
// Created by Raul Alvarez on 16/05/16.
// Copyright © 2016 Raul Alvarez. All rights reserved.
//
import UIKit
import CryptoSwift
import SWXMLHash
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
//let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:)))
//self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
loginToServer()
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! String
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! String
cell.textLabel!.text = object
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
|
apache-2.0
|
2df20f692555fc4d709cfc19112a20e3
| 32.262626 | 154 | 0.763741 | 4.711016 | false | false | false | false |
krzysztofzablocki/LifetimeTracker
|
Sources/iOS/UI/LifetimeTracker+DashboardView.swift
|
1
|
9131
|
//
// LifetimeTracker+DashboardView.swift
// LifetimeTracker
//
// Created by Krzysztof Zablocki on 9/25/17.
//
import UIKit
fileprivate extension String {
#if swift(>=4.0)
typealias AttributedStringKey = NSAttributedString.Key
static let foregroundColorAttributeName = NSAttributedString.Key.foregroundColor
#else
typealias AttributedStringKey = String
static let foregroundColorAttributeName = NSForegroundColorAttributeName
#endif
func attributed(_ attributes: [AttributedStringKey: Any] = [:]) -> NSAttributedString {
return NSAttributedString(string: self, attributes: attributes)
}
}
extension NSAttributedString {
fileprivate static func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: left)
result.append(right)
return result
}
}
typealias EntryModel = (color: UIColor, description: String)
typealias GroupModel = (color: UIColor, title: String, groupName: String, groupCount: Int, groupMaxCount: Int, entries: [EntryModel])
@objc public final class LifetimeTrackerDashboardIntegration: NSObject {
public enum Style {
case bar
case circular
internal func makeViewable() -> UIViewController & LifetimeTrackerViewable {
switch self {
case .bar: return BarDashboardViewController.makeFromNib()
case .circular: return CircularDashboardViewController.makeFromNib()
}
}
}
public enum Visibility {
case alwaysHidden
case alwaysVisible
case visibleWithIssuesDetected
func windowIsHidden(hasIssuesToDisplay: Bool) -> Bool {
switch self {
case .alwaysHidden: return true
case .alwaysVisible: return false
case .visibleWithIssuesDetected: return !hasIssuesToDisplay
}
}
}
private lazy var lifetimeTrackerView: UIViewController & LifetimeTrackerViewable = {
return self.style.makeViewable()
}()
private lazy var window: UIWindow = {
var frame: CGRect = UIScreen.main.bounds
let window = UIWindow(frame: .zero)
if #available(iOS 13.0, *), let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
frame = windowScene.coordinateSpace.bounds
window.windowScene = windowScene
}
window.windowLevel = UIWindow.Level.statusBar
window.frame = frame
window.rootViewController = self.lifetimeTrackerView
return window
}()
public var style: Style = .bar
public var visibility: Visibility = .visibleWithIssuesDetected
convenience public init(visibility: Visibility, style: Style = .bar) {
self.init()
self.visibility = visibility
self.style = style
}
@objc public func refreshUI(trackedGroups: [String: LifetimeTracker.EntriesGroup]) {
DispatchQueue.main.async {
self.window.isHidden = self.visibility.windowIsHidden(hasIssuesToDisplay: self.hasIssuesToDisplay(from: trackedGroups))
let entries = self.entries(from: trackedGroups)
let vm = BarDashboardViewModel(leaksCount: entries.leaksCount, summary: self.summary(from: trackedGroups), sections: entries.groups)
self.lifetimeTrackerView.update(with: vm)
}
}
private func summary(from trackedGroups: [String: LifetimeTracker.EntriesGroup]) -> NSAttributedString {
let groupNames = trackedGroups.keys.sorted(by: >)
let leakyGroupSummaries = groupNames.filter { groupName in
return trackedGroups[groupName]?.lifetimeState == .leaky
}.map { groupName in
let group = trackedGroups[groupName]!
let maxCountString = group.maxCount == Int.max ? "macCount.notSpecified".lt_localized : "\(group.maxCount)"
return "\(group.name ?? "dashboard.sectionHeader.title.noGroup".lt_localized) (\(group.count)/\(maxCountString))"
}.joined(separator: ", ")
if leakyGroupSummaries.isEmpty {
return "dashboard.header.issue.description.noIssues".lt_localized.attributed([
String.foregroundColorAttributeName: UIColor.green
])
}
return ("\("dashboard.header.issue.description.leakDetected".lt_localized): ").attributed([
String.foregroundColorAttributeName: UIColor.red
]) + leakyGroupSummaries.attributed()
}
private func entries(from trackedGroups: [String: LifetimeTracker.EntriesGroup]) -> (groups: [GroupModel], leaksCount: Int) {
var leaksCount = 0
var sections = [GroupModel]()
let filteredGroups = trackedGroups.filter { (_, group: LifetimeTracker.EntriesGroup) -> Bool in
group.count > 0
}
filteredGroups
.sorted { (lhs: (key: String, value: LifetimeTracker.EntriesGroup), rhs: (key: String, value: LifetimeTracker.EntriesGroup)) -> Bool in
return (lhs.value.maxCount - lhs.value.count) < (rhs.value.maxCount - rhs.value.count)
}
.forEach { (groupName: String, group: LifetimeTracker.EntriesGroup) in
var groupColor: UIColor
switch group.lifetimeState {
case .valid: groupColor = .green
case .leaky: groupColor = .red
}
let groupMaxCountString = group.maxCount == Int.max ? "macCount.notSpecified".lt_localized : "\(group.maxCount)"
let title = "\(group.name ?? "dashboard.sectionHeader.title.noGroup".lt_localized) (\(group.count)/\(groupMaxCountString))"
var rows = [EntryModel]()
group.entries.sorted { (lhs: (key: String, value: LifetimeTracker.Entry), rhs: (key: String, value: LifetimeTracker.Entry)) -> Bool in
lhs.value.count > rhs.value.count
}
.filter { (_, entry: LifetimeTracker.Entry) -> Bool in
entry.count > 0
}.forEach { (_, entry: LifetimeTracker.Entry) in
var color: UIColor
switch entry.lifetimeState {
case .valid: color = .green
case .leaky:
color = .red
leaksCount += entry.count - entry.maxCount
}
let entryMaxCountString = entry.maxCount == Int.max ? "macCount.notSpecified".lt_localized : "\(entry.maxCount)"
let description = "\(entry.name) (\(entry.count)/\(entryMaxCountString)):\n\(entry.pointers.joined(separator: ", "))"
rows.append((color: color, description: description))
}
sections.append((color: groupColor, title: title, groupName: "\(group.name ?? "dashboard.sectionHeader.title.noGroup".lt_localized)", groupCount: group.count, groupMaxCount: group.maxCount, entries: rows))
}
return (groups: sections, leaksCount: leaksCount)
}
func hasIssuesToDisplay(from trackedGroups: [String: LifetimeTracker.EntriesGroup]) -> Bool {
let aDetectedIssue = trackedGroups.keys.first { trackedGroups[$0]?.lifetimeState == .leaky }
return aDetectedIssue != nil
}
}
// MARK: - Objective-C Configuration Helper
extension LifetimeTrackerDashboardIntegration {
@objc public func setVisibleWhenIssueDetected() {
self.visibility = .visibleWithIssuesDetected
}
@objc public func setAlwaysVisible() {
self.visibility = .alwaysVisible
}
@objc public func setAlwaysHidden() {
self.visibility = .alwaysHidden
}
@objc public func useBarStyle() {
self.style = .bar
}
@objc public func useCircularStyle() {
self.style = .circular
}
}
// MARK: - Deprecated Configuration Helper
extension LifetimeTrackerDashboardIntegration {
@available(*, deprecated, message: "Use `LifetimeTrackerDashboardIntegration(visibility: Visibility, style: Style)` in Swift or `setVisibleWhenIssueDetected` instead")
@objc public static func visibleWhenIssueDetected() -> LifetimeTrackerDashboardIntegration {
return LifetimeTrackerDashboardIntegration(visibility: .visibleWithIssuesDetected)
}
@available(*, deprecated, message: "Use `LifetimeTrackerDashboardIntegration(visibility: Visibility, style: Style)` in Swift or `setAlwaysVisible` instead")
@objc public static func alwaysVisible() -> LifetimeTrackerDashboardIntegration {
return LifetimeTrackerDashboardIntegration(visibility: .alwaysVisible)
}
@available(*, deprecated, message: "Use `LifetimeTrackerDashboardIntegration(visibility: Visibility, style: Style)` in Swift or `setAlwaysHidden` instead")
@objc public static func alwaysHidden() -> LifetimeTrackerDashboardIntegration {
return LifetimeTrackerDashboardIntegration(visibility: .alwaysHidden)
}
}
|
mit
|
b0ea021343e6179a582eb366a493f028
| 41.868545 | 221 | 0.649546 | 4.954422 | false | false | false | false |
appcorn/cordova-plugin-siths-manager
|
src/ios/SITHSManager/SmartcardAPDU.swift
|
1
|
4624
|
//
// Written by Martin Alléus, Appcorn AB, martin@appcorn.se
//
// Copyright 2017 Svensk e-identitet AB
//
// 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 SmartcardCommandError: Error {
case commandDataTooLarge
case responseTooSmall
}
struct SmartcardCommandAPDU {
let instructionClass: UInt8
let instructionCode: UInt8
let instructionParameters: [UInt8]
let commandData: Data?
let expectedResponseBytes: UInt16?
func mergedCommand() throws -> Data {
var returnCommand = Data()
returnCommand.append(instructionClass)
returnCommand.append(instructionCode)
returnCommand.append(contentsOf: instructionParameters)
var commandDataPresent: Bool
if let commandData = commandData {
commandDataPresent = true
if commandData.count <= Int(UInt8.max) {
returnCommand.append(UInt8(commandData.count))
} else if commandData.count <= Int(UInt16.max) {
returnCommand.append(0x00)
let length = UInt16(commandData.count)
returnCommand.append(UInt8(truncatingBitPattern: length >> 8))
returnCommand.append(UInt8(truncatingBitPattern: length))
} else {
throw SmartcardCommandError.commandDataTooLarge
}
returnCommand.append(contentsOf: commandData)
} else {
commandDataPresent = false
}
if let expectedResponseBytes = expectedResponseBytes {
if expectedResponseBytes <= UInt16(UInt8.max) {
returnCommand.append(UInt8(expectedResponseBytes))
} else {
if commandDataPresent {
returnCommand.append(0x00)
}
returnCommand.append(UInt8(truncatingBitPattern: expectedResponseBytes >> 8))
returnCommand.append(UInt8(truncatingBitPattern: expectedResponseBytes))
}
}
return returnCommand
}
}
enum ProcessingStatus {
case success
case successWithResponse(availableBytes: UInt8)
case incorrectExpectedResponseBytes(correctExpectedResponseBytes: UInt8)
case fileNotFound
case incorrectInstructionParameters
case unknown(statusCode: [UInt8])
init(data: Data) {
let bytes = [UInt8](data)
if bytes == [0x90, 0x00] {
self = .success
} else if bytes == [0x6a, 0x82] {
self = .fileNotFound
} else if bytes == [0x6a, 0x86] {
self = .incorrectInstructionParameters
} else if bytes[0] == 0x61 {
self = .successWithResponse(availableBytes: bytes[1])
} else if bytes[0] == 0x6c {
self = .incorrectExpectedResponseBytes(correctExpectedResponseBytes: bytes[1])
} else {
self = .unknown(statusCode: bytes)
}
}
}
struct SmartcardResponseAPDU: CustomStringConvertible {
let responseData: Data?
let processingStatus: ProcessingStatus
init(data: Data) throws {
guard data.count >= 2 else {
throw SmartcardCommandError.responseTooSmall
}
processingStatus = ProcessingStatus(data: data.subdata(in: data.count-2..<data.count))
if data.count > 2 {
responseData = data.subdata(in: 0..<data.count-2)
} else {
responseData = nil
}
}
var description: String {
return "<SmartcardResponseAPDU> processingStatus: \(processingStatus) responseData: \(responseData?.hexString() ?? "<Empty>")"
}
}
|
mit
|
137d591a5e52e2bcf16684f41370bf93
| 35.401575 | 139 | 0.659312 | 4.6 | false | false | false | false |
f1re/F1reBahnAPIManager
|
F1reBahnAPIManager.swift
|
1
|
7777
|
//
// OpenBahnApiManager.swift
// Connexions
//
// Created by Alex Deutsch on 20.09.14.
// Copyright (c) 2014 Alexander Deutsch. All rights reserved.
//
import Foundation
let kFireMBahnBaseURL = "http://mobile.bahn.de/bin/mobil/query.exe/"
let kFireRABahnBaseURL = "http://reiseauskunft.bahn.de/bin/ajax-getstop.exe/dn"
typealias OperationCallback = (success: Bool, result: AnyObject?) -> ()
class F1reBahnAPIManager {
var authorizationCallback: OperationCallback?
var operationQueue: NSOperationQueue
var callbackQueue: dispatch_queue_t?
init(){
operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 7;
callbackQueue = dispatch_get_main_queue();
}
/*
getStation retrieves Stations
@param stationName name of the station to search for
*/
func getStation(stationName : String, callback: OperationCallback) -> NSOperation
{
let parameters: Dictionary <String, String> = [
"start" : "1",
"tpl" : "sls",
"REQ0JourneyStopsB" : "12",
"REQ0JourneyStopsS0A" : "1",
"getstop" : "1",
"noSession" : "yes",
"iER" : "yes",
"S" : stationName,
"js" : "true"]
let operation : NSOperation = self.sendRequest(kFireRABahnBaseURL, parameters: parameters, httpMethod: "GET", callback: {
(success, result) -> () in
var jsonString : NSString = result as! String
var error : NSError?
// Apparently necessary for making the transforming the string to a valid json string
jsonString = jsonString.stringByReplacingOccurrencesOfString("SLs.sls=", withString: "")
jsonString = jsonString.stringByReplacingOccurrencesOfString(";SLs.showSuggestion();", withString: "")
// Transform back into NSData and create json Object
let jsonData : NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
let jsonObject : AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error: &error)
if(jsonObject != nil)
{
callback(success: true, result: jsonObject)
}
else {
callback(success: false, result: error)
}
})
return operation
}
func getConnections(start: String, destination: String, date: String, time: String, callback: OperationCallback) -> NSOperation {
let parameters: Dictionary <String, String> = [
"REQ0JourneyStopsS0G":start,
"REQ0JourneyStopsZ0G":destination,
"REQ0JourneyStopsS0A":"1",
"queryPageDisplayed":"yes",
"REQ0JourneyStopsZ0A":"1",
"REQ0JourneyDate":date,
"REQ0JourneyTime":time,
"REQ0HafasSearchForw":"0",
"existOptimizePrice":"1",
"REQ0HafasOptimize1":"0:1",
"REQ0Tariff_TravellerType.1":"E",
"REQ0Tariff_TravellerReductionClass.1":"0",
"REQ0JourneyStopsS0ID":"",
"REQ0JourneyStopsZ0ID":"",
"start":"",
"sotRequest:":"1",
"use_realtime_filter":"1",
"REQ0Tariff_Class":"2",
"n":"1"
]
let operation = self.sendRequest(kFireMBahnBaseURL + "dox", parameters: parameters, httpMethod: "GET", callback: { (success, result) -> () in
if(success) {
let html = result as! String
let htmlDocument : HTMLDocument = HTMLDocument(string: html)
let journeyTimes = NSMutableDictionary()
for node in htmlDocument.nodesMatchingSelector("a")
{
var error: NSError?
let htmlNode : HTMLNode = node as! HTMLNode
let regex = NSRegularExpression(pattern: "\\d\\d:\\d\\d\\d\\d:\\d\\d", options: .CaseInsensitive, error: &error)
// Check if the html node is matching a journey time
if regex?.matchesInString(htmlNode.textContent, options: nil, range: NSMakeRange(0, count(htmlNode.textContent))).count > 0
{
let stringIndex : String.Index = advance(htmlNode.textContent.startIndex,5)
let from = htmlNode.textContent.substringToIndex(stringIndex)
let to = htmlNode.textContent.substringFromIndex(stringIndex)
journeyTimes[from] = to
}
}
callback(success: true, result: journeyTimes)
}
else {
callback(success: false, result: nil)
println("error retrieving connections")
}
})
return operation
}
private func sendRequest(path: String, parameters: Dictionary <String, String>, httpMethod: String, callback:OperationCallback) -> NSOperation{
let url : NSURL = self.constructURL(path, parameters: parameters)
println("URL : \(url.absoluteString)")
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = httpMethod
let operation = Operation(request: request, callbackBlock: callback, callbackQueue: self.callbackQueue!)
self.operationQueue.addOperation(operation)
return operation
}
private func constructURL(path: String, parameters: Dictionary <String, String>) -> NSURL {
var parametersString = path
var firstItem = true
for key in parameters.keys {
let string = parameters[key]!
let mark = (firstItem ? "?" : "&")
parametersString += "\(mark)\(key)=\(string)"
firstItem = false
}
println("parameterstring = \(parametersString)")
let escapedString : NSString = parametersString.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding)!
return NSURL(string: escapedString as String)!
}
}
class Operation: NSOperation {
var callbackBlock: OperationCallback
var request: NSURLRequest
var callbackQueue: dispatch_queue_t
init(request: NSURLRequest, callbackBlock: OperationCallback, callbackQueue: dispatch_queue_t) {
self.request = request
self.callbackBlock = callbackBlock
self.callbackQueue = callbackQueue
}
override func main() {
var error: NSError?
var result: AnyObject?
var response: NSURLResponse?
var recievedData: NSData? = NSURLConnection.sendSynchronousRequest(self.request, returningResponse: &response, error: &error)
if self.cancelled {return}
if (recievedData != nil){
result = NSString(data: recievedData! as NSData, encoding: NSISOLatin1StringEncoding)
if result != nil {
if result!.isKindOfClass(NSClassFromString("NSError")){
error = result as? NSError
}
}
if self.cancelled {return}
dispatch_async(self.callbackQueue, {
if ((error) != nil) {
self.callbackBlock(success: false, result: error!);
} else {
self.callbackBlock(success: true, result: result);
}
})
}
else {
println("ERROR NO DATA RECEIVED")
}
var concurrent:Bool {get {return true}}
}
}
|
apache-2.0
|
518b5cc9315b018cc1422facdd49e809
| 37.315271 | 151 | 0.572714 | 4.966156 | false | false | false | false |
royratcliffe/ManagedObject
|
Sources/ObjectsDidChange.swift
|
1
|
6111
|
// ManagedObject ObjectsDidChange.swift
//
// Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
import Foundation
import CoreData
/// Wraps an objects-did-change notification's context and user
/// information. Also wraps the contents of a merge-changes notification; useful
/// for debugging by logging the debug description. Merge-changes notifications
/// also carry inserted, updated and deleted sets of objects.
public struct ObjectsDidChange: CustomDebugStringConvertible {
public let context: NSManagedObjectContext
let userInfo: [AnyHashable: Any]
/// Answers `nil` if the notification object is not a managed-object context,
/// or if the notification's user information does not exist. User information
/// should always be a dictionary.
init?(notification: Notification) {
guard let context = notification.object as? NSManagedObjectContext else { return nil }
guard let userInfo = notification.userInfo else { return nil }
self.context = context
self.userInfo = userInfo
}
public func objects(_ key: String) -> NSSet? {
return userInfo[key] as? NSSet
}
public func managedObjects(_ key: String) -> [NSManagedObject]? {
return objects(key)?.flatMap { $0 as? NSManagedObject }
}
public func managedObjectIDs(_ key: String) -> [NSManagedObjectID]? {
return managedObjects(key)?.map { $0.objectID }
}
public var insertedObjects: NSSet? {
return objects(NSInsertedObjectsKey)
}
public var updatedObjects: NSSet? {
return objects(NSUpdatedObjectsKey)
}
public var deletedObjects: NSSet? {
return objects(NSDeletedObjectsKey)
}
public var refreshedObjects: NSSet? {
return objects(NSRefreshedObjectsKey)
}
public var invalidatedObjects: NSSet? {
return objects(NSInvalidatedObjectsKey)
}
/// Identifies which if any keys apply to the given managed-object identifier.
/// - parameter objectID: Managed-object identifier to search for.
/// - returns: Array of zero-or-more string keys, one for each set of objects
/// the given identifier is a member of.
public func keys(for objectID: NSManagedObjectID) -> [String] {
var keys = [String]()
for key in ObjectsDidChange.keys {
if let objectIDs = managedObjectIDs(key), objectIDs.contains(objectID) {
keys.append(key)
}
}
return keys
}
public func keys(for object: NSManagedObject) -> [String] {
return keys(for: object.objectID)
}
/// Ignores non-managed objects and managed objects without entity names, if
/// those conditions are possible.
public var managedObjectsByEntityNameByChangeKey: [String: [String: [NSManagedObject]]] {
var objectsByEntityNameByChangeKey = [String: [String: [NSManagedObject]]]()
for changeKey in ObjectsDidChange.keys {
guard let objects = managedObjects(changeKey) else {
continue
}
for object in objects {
let entity = object.entity
guard let entityName = entity.name else {
continue
}
if var objectsByEntityName = objectsByEntityNameByChangeKey[changeKey] {
if var objects = objectsByEntityName[entityName] {
objects.append(object)
// Dictionary getters assigned to a variable make a mutable
// copy. Changes needs re-assigning to the dictionary after
// amending.
objectsByEntityName[entityName] = objects
} else {
objectsByEntityName[entityName] = [object]
}
// Update the key-pair; objectsByEntityName is only a mutable copy,
// not a mutable reference.
objectsByEntityNameByChangeKey[changeKey] = objectsByEntityName
} else {
objectsByEntityNameByChangeKey[changeKey] = [entityName: [object]]
}
}
}
return objectsByEntityNameByChangeKey
}
public static let keys = [
NSInsertedObjectsKey,
NSUpdatedObjectsKey,
NSDeletedObjectsKey,
NSRefreshedObjectsKey,
NSInvalidatedObjectsKey
]
public var debugDescription: String {
var description = [String]()
for (changeKey, objectsByEntityName) in managedObjectsByEntityNameByChangeKey.sorted(by: { (lhs, rhs) in
ObjectsDidChange.keys.index(of: lhs.key)! < ObjectsDidChange.keys.index(of: rhs.key)!
}) {
description.append("\(changeKey):")
for (entityName, objects) in objectsByEntityName.sorted(by: { (lhs, rhs) in
lhs.key < rhs.key
}) {
description.append("\(entityName)[\(objects.count)]")
for object in objects {
let identifier = object.objectID
var component = identifier.uriRepresentation().lastPathComponent
if identifier.isTemporaryID {
component = component.components(separatedBy: "-").last!
}
description.append(component)
}
}
}
return description.joined(separator: " ")
}
}
|
mit
|
eaec8231977f3a1c0f02a223b2181185
| 36.435583 | 108 | 0.689774 | 4.800944 | false | false | false | false |
skedgo/tripkit-ios
|
Sources/TripKitUI/view model/TKUIRoutingResultsViewModel+Content.swift
|
1
|
11502
|
//
// TKUIRoutingResultsViewModel+Content.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 01.04.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
import TripKit
// MARK: - List content
extension TKUIRoutingResultsViewModel {
}
// MARK: - Map Content
extension TKUIRoutingResultsViewModel {
typealias MapContent = (all: [TKUIRoutingResultsMapRouteItem], selection: TKUIRoutingResultsMapRouteItem?)
}
extension TKUIRoutingResultsViewModel {
static func buildMapContent(all groups: [TripGroup], selection: TKUIRoutingResultsMapRouteItem?) -> MapContent {
let routeItems = groups.compactMap { $0.preferredRoute }
let selectedTripGroup = selection?.trip.tripGroup
?? groups.first?.request.preferredGroup
?? groups.first
let selectedItem = routeItems.first {$0.trip.tripGroup == selectedTripGroup }
return (routeItems, selectedItem)
}
}
// MARK: - Building results
extension TKUIRoutingResultsViewModel {
static func fetchTripGroups(_ requests: Observable<(TripRequest, mutable: Bool)>) -> Observable<([TripGroup], mutable: Bool)> {
return requests.flatMapLatest { tuple -> Observable<([TripGroup], mutable: Bool)> in
let request = tuple.0
guard let context = request.managedObjectContext else {
return .just(([], mutable: tuple.mutable))
}
let predicate: NSPredicate
if tuple.mutable {
// user can hide them, filter by visibility
predicate = NSPredicate(format: "request = %@ AND visibilityRaw != %@", request, NSNumber(value: TripGroup.Visibility.hidden.rawValue))
} else {
// user can't show/hide them; show all
predicate = NSPredicate(format: "request = %@", request)
}
return context.rx
.fetchObjects(
TripGroup.self,
sortDescriptors: [NSSortDescriptor(key: "visibleTrip.totalScore", ascending: true)],
predicate: predicate,
relationshipKeyPathsForPrefetching: ["visibleTrip", "visibleTrip.segmentReferences"]
)
.throttle(.milliseconds(500), scheduler: MainScheduler.instance)
.map { ($0, mutable: tuple.mutable) }
}
}
static func buildSections(_ groups: Observable<([TripGroup], mutable: Bool)>, inputs: UIInput, progress: Observable<TKUIResultsFetcher.Progress>, advisory: Observable<TKAPI.Alert?>) -> Observable<[Section]> {
let expand = inputs.tappedSectionButton
.filter { action -> Bool in
switch action {
case .trigger: return false
case .collapse, .expand: return true
}
}.map { action -> TripGroup? in
switch action {
case .expand(let group): return group
default: return nil
}
}
return Observable
.combineLatest(
groups,
inputs.changedSortOrder.startWith(.score).asObservable(),
expand.startWith(nil).asObservable(),
progress,
advisory.startWith(nil)
)
.map(sections)
}
private static func sections(for groups: ([TripGroup], mutable: Bool), sortBy: TKTripCostType, expand: TripGroup?, progress: TKUIResultsFetcher.Progress, advisory: TKAPI.Alert?) -> [Section] {
let progressIndicatorSection = Section(items: [.progress])
let advisorySection = advisory.flatMap { Section(items: [.advisory($0)]) }
guard let first = groups.0.first else {
if case .finished = progress {
return []
} else {
// happens when progress is `locating` and `start`
return [advisorySection, progressIndicatorSection].compactMap { $0 }
}
}
let groupSorters = first.request.sortDescriptors(withPrimary: sortBy)
let byScoring = (groups.0 as NSArray)
.sortedArray(using: groupSorters)
.compactMap { $0 as? TripGroup }
let notCanceled = byScoring.filter { $0.visibleTrip?.isCanceled == false }
let cancelations = byScoring.filter { $0.visibleTrip?.isCanceled == true }
let sorted = notCanceled + cancelations
let tripSorters = first.request.tripTimeSortDescriptors()
var sections = sorted.compactMap { group -> Section? in
guard let best = group.visibleTrip else { return nil }
let items = (Array(group.trips) as NSArray)
.sortedArray(using: tripSorters)
.compactMap { $0 as? Trip }
.compactMap { Item(trip: $0, in: group, filter: groups.mutable) }
let show: [Item]
let action: SectionAction?
if let primaryAction = TKUIRoutingResultsCard.config.tripGroupActionFactory?(group) {
show = items
action = (
title: primaryAction.title,
accessibilityLabel: primaryAction.accessibilityLabel,
payload: .trigger(primaryAction, group)
)
} else if items.count > 2, expand == group {
show = items
action = (title: Loc.Less, accessibilityLabel: nil, payload: .collapse)
} else if items.count > 2 {
let good = items
.filter { $0.trip != nil }
.filter { !$0.trip!.showFaded }
if good.isEmpty {
show = Array(items.prefix(2))
} else {
show = Array(good.prefix(2))
}
action = (title: Loc.More, accessibilityLabel: nil, payload: .expand(group))
} else {
show = items
action = nil
}
let badge: TKMetricClassifier.Classification?
if let candidate = group.badge, TKUIRoutingResultsCard.config.tripBadgesToShow.contains(candidate) {
badge = candidate
} else {
badge = nil
}
return Section(
items: show,
badge: badge,
costs: best.costValues,
action: action
)
}
switch progress {
case .finished: break
default: sections.insert(progressIndicatorSection, at: 0)
}
if let advisory = advisorySection {
sections.insert(advisory, at: 0)
}
return sections
}
}
extension TripRequest {
var includedTransportModes: String {
let all = spanningRegion.modeIdentifiers
let enabled = TKSettings.enabledModeIdentifiers(all)
return Loc.Showing(enabled.count, ofTransportModes: all.count)
}
}
extension TripGroup {
var badge: TKMetricClassifier.Classification? {
return TKMetricClassifier.classification(for: self)
}
}
extension Trip {
var showFaded: Bool {
return missedBookingWindow // shuttle, etc., departing too soon
|| isCanceled
|| calculateOffset() < -60 // doesn't match query
}
}
extension TKUIRoutingResultsViewModel {
/// An item in a section on the results screen
enum Item {
/// A regular/expanded trip
case trip(Trip)
case progress
case advisory(TKAPI.Alert)
var trip: Trip? {
switch self {
case .trip(let trip): return trip
case .progress, .advisory: return nil
}
}
var alert: TKAPI.Alert? {
switch self {
case .advisory(let alert): return alert
case .trip, .progress: return nil
}
}
}
enum ActionPayload {
case expand(TripGroup)
case collapse
case trigger(TKUIRoutingResultsCard.TripGroupAction, TripGroup)
}
typealias SectionAction = (title: String, accessibilityLabel: String?, payload: ActionPayload)
/// A section on the results screen, which consists of various sorted items
struct Section {
var items: [Item]
var badge: TKMetricClassifier.Classification? = nil
var costs: [TKTripCostType: String] = [:]
var action: SectionAction? = nil
}
}
extension TKMetricClassifier.Classification {
var icon: UIImage? {
switch self {
case .cheapest: return .badgeMoney
case .easiest: return .badgeLike
case .fastest: return .badgeLightning
case .greenest: return .badgeLeaf
case .healthiest: return .badgeHeart
case .recommended: return .badgeCheck
}
}
var text: String {
switch self {
case .cheapest: return Loc.BadgeCheapest
case .easiest: return Loc.BadgeEasiest
case .fastest: return Loc.BadgeFastest
case .greenest: return Loc.BadgeGreenest
case .healthiest: return Loc.BadgeHealthiest
case .recommended: return Loc.BadgeRecommended
}
}
var color: UIColor {
switch self {
case .cheapest: return #colorLiteral(red: 1, green: 0.5529411765, blue: 0.1058823529, alpha: 1)
case .easiest: return #colorLiteral(red: 0.137254902, green: 0.6941176471, blue: 0.368627451, alpha: 1)
case .fastest: return #colorLiteral(red: 1, green: 0.7490196078, blue: 0, alpha: 1)
case .greenest: return #colorLiteral(red: 0, green: 0.6588235294, blue: 0.5607843137, alpha: 1)
case .healthiest: return #colorLiteral(red: 0.8823529412, green: 0.3568627451, blue: 0.4470588235, alpha: 1)
case .recommended: return #colorLiteral(red: 0.09411764706, green: 0.5019607843, blue: 0.9058823529, alpha: 1)
}
}
}
extension TKUIRoutingResultsViewModel.Item {
fileprivate init?(trip: Trip, in group: TripGroup, filter: Bool) {
guard filter else { self = .trip(trip); return }
switch group.visibility {
case .hidden: return nil
case .full: self = .trip(trip)
}
}
}
// MARK: - Map content
public func ==(lhs: TKUIRoutingResultsMapRouteItem, rhs: TKUIRoutingResultsMapRouteItem) -> Bool {
return lhs.trip.objectID == rhs.trip.objectID
}
extension TKUIRoutingResultsMapRouteItem: Equatable { }
extension TripGroup {
fileprivate var preferredRoute: TKUIRoutingResultsMapRouteItem? {
guard let trip = visibleTrip else { return nil }
return TKUIRoutingResultsMapRouteItem(trip)
}
}
extension Array where Element == TKUIRoutingResultsViewModel.Section {
func find(_ mapRoute: TKUIRoutingResultsMapRouteItem?) -> TKUIRoutingResultsViewModel.Item? {
guard let mapRoute = mapRoute else { return nil }
for section in self {
for item in section.items {
if item.trip == mapRoute.trip {
return item
}
}
}
return nil
}
var bestItem: TKUIRoutingResultsViewModel.Item? {
return first?.items.first // Assuming we're sorting by best
}
}
// MARK: - RxDataSources protocol conformance
func ==(lhs: TKUIRoutingResultsViewModel.Item, rhs: TKUIRoutingResultsViewModel.Item) -> Bool {
switch (lhs, rhs) {
case (.trip(let left), .trip(let right)): return left.objectID == right.objectID
case (.progress, .progress): return true
case (.advisory(let left), .advisory(let right)): return left.hashCode == right.hashCode
default: return false
}
}
extension TKUIRoutingResultsViewModel.Item: Equatable { }
extension TKUIRoutingResultsViewModel.Item: IdentifiableType {
typealias Identity = String
var identity: Identity {
switch self {
case .trip(let trip): return trip.objectID.uriRepresentation().absoluteString
case .progress: return "progress_indicator"
case .advisory: return "advisory" // should only ever have one
}
}
}
extension TKUIRoutingResultsViewModel.Section: AnimatableSectionModelType {
typealias Identity = String
typealias Item = TKUIRoutingResultsViewModel.Item
init(original: TKUIRoutingResultsViewModel.Section, items: [TKUIRoutingResultsViewModel.Item]) {
self = original
self.items = items
}
var identity: Identity {
let itemIdentity = items.first?.identity ?? "Empty"
return itemIdentity + (action?.title ?? "")
}
}
|
apache-2.0
|
a2ee83fb2fc3bb66716850029396d624
| 29.42328 | 210 | 0.666522 | 4.315197 | false | false | false | false |
vornet/mapdoodle-ios
|
Example/MapDoodle/ViewController.swift
|
1
|
5076
|
//
// ViewController.swift
// MapDoodle
//
// Created by Vorn Mom on 6/30/16.
// Copyright © 2016 Moonberry Tech, LLC. All rights reserved.
//
import UIKit
import MapKit
import MapDoodle
class ViewController: UIViewController {
@IBOutlet var mapView: MKMapView!
var mapDoodler: MapDoodler!
var doodles: [Doodle]!
var visibleDoodle: Int = 0
@IBAction func switchButtonProessed(sender: UIButton) {
visibleDoodle += 1
visibleDoodle = visibleDoodle % (doodles.count + 1)
if visibleDoodle < doodles.count {
mapDoodler.zoomToFitDoodle(doodles[visibleDoodle], padding: 0, shouldAnimate: true, shouldChangeBearing: true)
} else {
mapDoodler.zoomFitAllDoodles(150, shouldAnimate: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
mapDoodler = MapDoodler(mapView: mapView, refreshRate: 500)
let pathDoodleStyle = AnimatedPathDoodleStyle()
pathDoodleStyle.thickness = 10
pathDoodleStyle.color = UIColor.blueColor()
pathDoodleStyle.tracerThickness = 5.0
pathDoodleStyle.tracerColor = UIColor.grayColor()
pathDoodleStyle.speed = 60.0
// Shining Sea Bikeway
let shiningSeaBikewayPoints: [GeoPoint] = [
GeoPoint(latitude: 41.551490, longitude: -70.627179),
GeoPoint(latitude: 41.550410, longitude: -70.627761),
GeoPoint(latitude: 41.534456, longitude: -70.641752),
GeoPoint(latitude: 41.534319, longitude: -70.642047),
GeoPoint(latitude: 41.534032, longitude: -70.642455),
GeoPoint(latitude: 41.531242, longitude: -70.645581),
GeoPoint(latitude: 41.524383, longitude: -70.653310),
GeoPoint(latitude: 41.524383, longitude: -70.653310),
GeoPoint(latitude: 41.523319, longitude: -70.655396),
GeoPoint(latitude: 41.523034, longitude: -70.656157),
GeoPoint(latitude: 41.522540, longitude: -70.659166),
GeoPoint(latitude: 41.522524, longitude: -70.661014),
GeoPoint(latitude: 41.522825, longitude: -70.663299),
GeoPoint(latitude: 41.523331, longitude: -70.665032),
GeoPoint(latitude: 41.523395, longitude: -70.666019),
GeoPoint(latitude: 41.523001, longitude: -70.668535),
GeoPoint(latitude: 41.523049, longitude: -70.668605),
GeoPoint(latitude: 41.523061, longitude: -70.668922),
GeoPoint(latitude: 41.523001, longitude: -70.669019),
GeoPoint(latitude: 41.523017, longitude: -70.669158),
GeoPoint(latitude: 41.523101, longitude: -70.669233)
]
// Cape Cod Canal Service Road
let capeCodeCanalServiceRoadPoints: [GeoPoint] = [
GeoPoint(latitude: 41.743239, longitude: -70.613286),
GeoPoint(latitude: 41.745799, longitude: -70.601731),
GeoPoint(latitude: 41.747392, longitude: -70.594167),
GeoPoint(latitude: 41.749841, longitude: -70.587451),
GeoPoint(latitude: 41.755180, longitude: -70.577988),
GeoPoint(latitude: 41.758533, longitude: -70.574018),
GeoPoint(latitude: 41.760342, longitude: -70.572505),
GeoPoint(latitude: 41.766240, longitude: -70.568664),
GeoPoint(latitude: 41.768489, longitude: -70.566808),
GeoPoint(latitude: 41.771314, longitude: -70.563579),
GeoPoint(latitude: 41.771521, longitude: -70.563517),
GeoPoint(latitude: 41.771606, longitude: -70.563392),
GeoPoint(latitude: 41.771658, longitude: -70.563126),
GeoPoint(latitude: 41.774158, longitude: -70.558663),
GeoPoint(latitude: 41.776142, longitude: -70.553008),
GeoPoint(latitude: 41.776824, longitude: -70.549567),
GeoPoint(latitude: 41.777240, longitude: -70.545823),
GeoPoint(latitude: 41.777280, longitude: -70.545431),
GeoPoint(latitude: 41.777160, longitude: -70.540834),
GeoPoint(latitude: 41.773926, longitude: -70.512234),
GeoPoint(latitude: 41.774070, longitude: -70.511566),
GeoPoint(latitude: 41.774320, longitude: -70.511046),
GeoPoint(latitude: 41.774696, longitude: -70.510429),
GeoPoint(latitude: 41.774846, longitude: -70.509933),
GeoPoint(latitude: 41.775782, longitude: -70.503557),
GeoPoint(latitude: 41.775812, longitude: -70.502865),
GeoPoint(latitude: 41.775664, longitude: -70.501186),
GeoPoint(latitude: 41.775802, longitude: -70.500440),
GeoPoint(latitude: 41.776408, longitude: -70.498739),
GeoPoint(latitude: 41.776982, longitude: -70.497967)
]
let shiningSeaBikewayDoodle = mapDoodler.addAnimatedPathDoodle(pathDoodleStyle, points: shiningSeaBikewayPoints)
let capeCodeCanalServiceRoadDoodle = mapDoodler.addAnimatedPathDoodle(pathDoodleStyle, points: capeCodeCanalServiceRoadPoints)
doodles = [shiningSeaBikewayDoodle, capeCodeCanalServiceRoadDoodle ]
visibleDoodle = doodles.count
mapDoodler.zoomFitAllDoodles(150, shouldAnimate: false)
//mapDoodle.addPath(shiningSeaBikeway)
//mapDoodle.animatePath(100.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
d2c056e17b93b439f7e1eeac8a802730
| 40.598361 | 130 | 0.694975 | 3.272083 | false | false | false | false |
thecb4/SwifterCSV
|
Sources/StateMachine.swift
|
1
|
3777
|
//
// StateMachine.swift
// SwifterCSV
//
// Created by Will Richardson on 15/04/16.
// Copyright © 2016 JavaNut13. All rights reserved.
//
open class Accumulator {
private var field: [Character]
private var fields: [String]
private let block: ([String]) -> ()
var count = 0
private let startAt: Int
let delimiter: Character
var hasContent: Bool {
return field.count > 0 || fields.count > 0
}
init(block: @escaping ([String]) -> (), delimiter: Character, startAt: Int = 0) {
self.block = block
self.startAt = startAt
self.delimiter = delimiter
field = []
fields = []
}
func pushCharacter(_ char: Character) {
field.append(char)
}
func pushField() {
fields.append(String(field))
field = []
}
func pushRow() {
fields.append(String(field))
if count >= startAt {
block(fields)
}
count += 1
fields = [String]()
field = [Character]()
}
}
enum State {
case start // start of line or field
case parsingField // inside a field with no quotes
case parsingFieldInnerQuotes // escaped quotes in a field
case parsingQuotes // field with quotes
case parsingQuotesInner // escaped quotes in a quoted field
case error(String) // error or something
func nextState(_ hook: Accumulator, char: Character) -> State {
switch self {
case .start:
return stateFromStart(hook, char)
case .parsingField:
return stateFromParsingField(hook, char)
case .parsingFieldInnerQuotes:
return stateFromParsingFieldInnerQuotes(hook, char)
case .parsingQuotes:
return stateFromParsingQuotes(hook, char)
case .parsingQuotesInner:
return stateFromParsingQuotesInner(hook, char)
default:
return .error("Unexpected character: \(char)")
}
}
}
private func stateFromStart(_ hook: Accumulator, _ char: Character) -> State {
if char == "\"" {
return .parsingQuotes
} else if char == hook.delimiter {
hook.pushField()
return .start
} else if isNewline(char) {
hook.pushRow()
return .start
} else {
hook.pushCharacter(char)
return .parsingField
}
}
private func stateFromParsingField(_ hook: Accumulator, _ char: Character) -> State {
if char == "\"" {
return .parsingFieldInnerQuotes
} else if char == hook.delimiter {
hook.pushField()
return .start
} else if isNewline(char) {
hook.pushRow()
return .start
} else {
hook.pushCharacter(char)
return .parsingField
}
}
private func stateFromParsingFieldInnerQuotes(_ hook: Accumulator, _ char: Character) -> State {
if char == "\"" {
hook.pushCharacter(char)
return .parsingField
} else {
return .error("Can't have non-quote here: \(char)")
}
}
private func stateFromParsingQuotes(_ hook: Accumulator, _ char: Character) -> State {
if char == "\"" {
return .parsingQuotesInner
} else {
hook.pushCharacter(char)
return .parsingQuotes
}
}
private func stateFromParsingQuotesInner(_ hook: Accumulator, _ char: Character) -> State {
if char == "\"" {
hook.pushCharacter(char)
return .parsingQuotes
} else if char == hook.delimiter {
hook.pushField()
return .start
} else if isNewline(char) {
hook.pushRow()
return .start
} else {
return .error("Can't have non-quote here: \(char)")
}
}
private func isNewline(_ char: Character) -> Bool {
return char == "\n" || char == "\r" || char == "\r\n"
}
|
mit
|
50ad0900f25bc3eca9a891d66cd0e459
| 25.780142 | 96 | 0.591102 | 4.2049 | false | false | false | false |
johngoren/podcast-brimstone
|
PBC Swift/Show.swift
|
1
|
6044
|
//
// Show.swift
// PBC Swift
//
// Created by John Gorenfeld on 6/4/14.
// Copyright (c) 2014 John Gorenfeld. All rights reserved.
//
import UIKit
class Show:NSObject, NSCoding {
var title:String?
var blurb:String?
var link:NSURL?
var audioLink:NSURL?
var dateString:String?
private var date:NSDate?
var durationString:String?
private var bookmarkSeconds:Float?
private var totalSeconds:Float?
let toFix: [String: String] = ["’" : "", "“": "", "”" : "\"", "[…]": "...", "…" : "...", "–": "", "Free Preview Clip ": "", "#038;": "", "&": "", "[…]" : "...", "Share this" : "", ":TwitterFacebookEmail" : ""]
init(title: String, description: String, link:String, dateString:String, enclosureString:String) {
super.init()
self.title = cleanText(title)
self.blurb = cleanText(stringByRemovingHTMLFromString(description))
self.link = NSURL(string: link)!
self.dateString = dateString
self.date = NSDateForString(dateString)
let enclosure = Show.retrieveValuesFromEnclosureString(enclosureString)
self.audioLink = enclosure.audioURL
self.durationString = enclosure.durationString
}
required init(coder aDecoder: NSCoder) {
self.title = aDecoder.decodeObjectForKey("title") as? String
self.blurb = aDecoder.decodeObjectForKey("blurb") as? String
self.link = aDecoder.decodeObjectForKey("link") as? NSURL
self.audioLink = aDecoder.decodeObjectForKey("audiolink") as? NSURL
self.date = aDecoder.decodeObjectForKey("date") as? NSDate
self.dateString = aDecoder.decodeObjectForKey("datestring") as? String
}
}
// MARK: Convenience classes
extension Show {
static func calculateProgress(show:Show) -> Float {
let currentSeconds = show.getBookmarkSeconds()
let totalSeconds = show.getTotalSeconds()
if let currentSeconds = currentSeconds, totalSeconds = show.getTotalSeconds() {
let fraction = currentSeconds / totalSeconds
return fraction
}
else {
return 0
}
}
static func retrieveValuesFromEnclosureString(rawEnclosureString: String) -> (audioURL: NSURL?, durationString: String?) {
var enclosureString:NSString = rawEnclosureString as NSString
if enclosureString == "" {
var audioURL = NSURL(string: "#")
var duration = "#"
return (audioURL, duration)
}
else {
var filenameRange:NSRange = enclosureString.rangeOfString(".mp3")
var endIndex = filenameRange.location + filenameRange.length
var filenameString:String = enclosureString.substringToIndex(endIndex) as String
var audioURL:NSURL?
audioURL = NSURL(string: filenameString)
var roughArray = rawEnclosureString.componentsSeparatedByString("\n")
var duration:String?
if count(roughArray) > 3 {
if roughArray[3] != "" {
duration = roughArray[3].componentsSeparatedByString("\"")[3]
}
}
return (audioURL, duration)
}
}
private func NSDateForString(text: String) -> NSDate {
var dateLength = count(text)
var text = (text as NSString).substringToIndex(dateLength - 9)
var dateFormatter = NSDateFormatter()
dateFormatter.lenient = true
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateObject:NSDate? = dateFormatter.dateFromString(text)
return dateObject!
}
private func stringByRemovingHTMLFromString(str: String) -> String {
let regex:NSRegularExpression = NSRegularExpression(
pattern: "<.*?>",
options: NSRegularExpressionOptions.CaseInsensitive,
error: nil)!
let range = NSMakeRange(0, count(str))
let stringDenudedOfHTML :String = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.allZeros,
range:range ,
withTemplate: "")
return stringDenudedOfHTML
}
private func cleanText(text: String) -> String {
var ourText = text
for (unwanted, replacement) in self.toFix {
ourText = ourText.stringByReplacingOccurrencesOfString(unwanted, withString: replacement)
}
return ourText
}
func getFriendlyDate() -> String? {
let myDate = self.date
if myDate != nil {
let dateFormatter = NSDateFormatter()
dateFormatter.doesRelativeDateFormatting = true
dateFormatter.timeStyle = .NoStyle
dateFormatter.dateStyle = .LongStyle
dateFormatter.timeZone = NSTimeZone.defaultTimeZone()
dateFormatter.locale = NSLocale.currentLocale()
var friendlyDateString:NSString = dateFormatter.stringFromDate(myDate!)
return friendlyDateString as String
}
else {
return nil
}
}
func getTotalSeconds() -> Float? {
return self.totalSeconds
}
func getBookmarkSeconds() -> Float? {
return self.bookmarkSeconds
}
func setBookmarkSeconds(seconds: Seconds) {
self.bookmarkSeconds = seconds
}
func setTotalSeconds(seconds: Seconds) {
self.totalSeconds = seconds
}
}
// Encoding
extension Show {
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(blurb, forKey: "blurb")
aCoder.encodeObject(link, forKey: "link")
aCoder.encodeObject(audioLink, forKey: "audiolink")
aCoder.encodeObject(dateString, forKey: "datestring")
aCoder.encodeObject(date, forKey: "date")
aCoder.encodeObject(durationString, forKey: "durationstring")
aCoder.encodeObject(bookmarkSeconds, forKey: "bookmarksecondslistenedto")
}
}
|
mit
|
3a3efca51ea60a43066f61885647c8cb
| 34.769231 | 260 | 0.62591 | 4.789223 | false | true | false | false |
tatey/Lighting
|
Widget/LightTargetCollectionView.swift
|
1
|
646
|
//
// Created by Tate Johnson on 17/06/2015.
// Copyright (c) 2015 Tate Johnson. All rights reserved.
//
import Cocoa
class LightTargetCollectionView: NSCollectionView {
func sizeThatFits(_ size: NSSize) -> NSSize {
let count = content.count
if let itemPrototype = self.itemPrototype, count > 0 {
let itemSize = itemPrototype.view.frame.size
let itemsPerRow = floor(size.width / itemSize.width)
let numberOfRows = Int(ceil(CGFloat(count) / itemsPerRow))
return NSSize(width: itemSize.width * CGFloat(itemsPerRow), height: itemSize.height * CGFloat(numberOfRows))
} else {
return NSSize(width: 0.0, height: 0.0)
}
}
}
|
gpl-3.0
|
38b05c92d3ba7664cf57ab2726c2b0ab
| 31.3 | 111 | 0.716718 | 3.549451 | false | false | false | false |
tad-iizuka/swift-sdk
|
Source/RelationshipExtractionV1Beta/Models/Mention.swift
|
3
|
4652
|
/**
* Copyright IBM Corporation 2016
*
* 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 RestKit
/** A Mention object contains annotations about a word or phrase that refers to an actual thing, or
entity, such as a person or location. */
public struct Mention: JSONDecodable {
/// The alphanumberic identifier of the mention. The identifier consist of the id from the doc
/// tag, followed by `-M` and the numeric identifier for the mention: doc_id-Mn.
public let mentionID: String
/// The type of the mention.
public let type: MentionType
/// The beginning character offset of the mention among all the text in the input.
public let begin: Int
/// The ending character offset of the mention among all the text in the input.
public let end: Int
/// The beginning character offset of the head word of the phrase. This will usually be the same
/// as the value for begin.
public let headBegin: Int
/// The ending character offset of the head word of the phrase. This will usually be the same as
/// the value for end.
public let headEnd: Int
/// The alphanumeric identifier of the specific entity referred to by this mention. Multiple
/// mentions can refer to the same entity.
public let entityID: String
/// The type of the entity that this mention refers to.
public let entityType: String
/// The role the entity holds within this mention.
public let entityRole: String
/// Indicates whether this mention is a substitution used to refer to another entity.
public let metonymy: Bool
/// The class of this mention.
public let mentionClass: MentionClass
/// The confidence level for the accuracy of the mention annotation, on a range from 0 to 1.
public let score: Double
/// The confidence level for the accuracy of a mention that coreferences, or refers to, another
/// mention, on a range from 0 to 1. Mentions that don't refer to other mentions will always
/// have a corefScore of 1.
public let corefScore: Double
/// The specific text for this mention.
public let text: String
/// Used internally to initialize a `Mention` model from JSON.
public init(json: JSON) throws {
mentionID = try json.getString(at: "mid")
begin = try json.getInt(at: "begin")
end = try json.getInt(at: "end")
headBegin = try json.getInt(at: "head-begin")
headEnd = try json.getInt(at: "head-end")
entityID = try json.getString(at: "eid")
entityType = try json.getString(at: "etype")
entityRole = try json.getString(at: "role")
metonymy = try json.getBool(at: "metonymy")
score = try json.getDouble(at: "score")
corefScore = try json.getDouble(at: "corefScore")
text = try json.getString(at: "text")
guard let mentionType = MentionType(rawValue: try json.getString(at: "mtype")) else {
throw JSON.Error.valueNotConvertible(value: json, to: MentionType.self)
}
type = mentionType
guard let mClass = MentionClass(rawValue: try json.getString(at: "class")) else {
throw JSON.Error.valueNotConvertible(value: json, to: MentionClass.self)
}
mentionClass = mClass
}
}
/** The type of mention. */
public enum MentionType: String {
/// A named entity mention, in the form of a proper name.
case named = "NAM"
/// A nominal entity mention, not composed solely of a named entity or pronoun.
case nominal = "NOM"
/// A pronoun mention.
case pronoun = "PRO"
/// A mention that does not match any of the other types.
case none = "NONE"
}
/** The class of the mention. */
public enum MentionClass: String {
/// The mention is a reference to a specific thing.
case specific = "SPC"
/// The mention is a negated reference to a specific thing.
case negated = "NEG"
/// A generic mention that does not fit the other class types.
case generic = "GEN"
}
|
apache-2.0
|
7663139eeaafac2a96545140e8ff4dbf
| 35.920635 | 100 | 0.66509 | 4.331471 | false | false | false | false |
gvsucis/mobile-app-dev-book
|
iOS/ch13/TraxyApp/TraxyApp/LoginViewController.swift
|
2
|
3405
|
//
// ViewController.swift
// TraxyApp
//
// Created by Jonathan Engelsma on 1/5/17.
// Copyright © 2017 Jonathan Engelsma. All rights reserved.
//
import UIKit
import FirebaseAuth
class LoginViewController: TraxyLoginViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
var validationErrors = ""
override func viewDidLoad() {
super.viewDidLoad()
// dismiss keyboard when tapping outside oftext fields
let detectTouch = UITapGestureRecognizer(target: self, action:
#selector(self.dismissKeyboard))
self.view.addGestureRecognizer(detectTouch)
// make this controller the delegate of the text fields.
self.emailField.delegate = self
self.passwordField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func dismissKeyboard() {
self.view.endEditing(true)
}
func validateFields() -> Bool {
let pwOk = self.isEmptyOrNil(password: self.passwordField.text)
if !pwOk {
self.validationErrors += "Password cannot be blank. "
}
let emailOk = self.isValidEmail(emailStr: self.emailField.text)
if !emailOk {
self.validationErrors += "Invalid email address."
}
return emailOk && pwOk
}
@IBAction func signupButtonPressed(_ sender: UIButton) {
if self.validateFields() {
print("Congratulations! You entered correct values.")
Auth.auth().signIn(withEmail: self.emailField.text!, password:
self.passwordField.text!) { (user, error) in
if let _ = user {
//self.performSegue(withIdentifier: "segueToMain", sender: self)
self.dismiss(animated: true, completion: nil)
} else {
self.reportError(msg: (error?.localizedDescription)!)
self.passwordField.text = ""
self.passwordField.becomeFirstResponder()
}
}
} else {
self.reportError(msg: self.validationErrors)
}
}
// @IBAction func logout(segue : UIStoryboardSegue) {
// do {
// try FIRAuth.auth()?.signOut()
// print("Logged out")
// } catch let signOutError as NSError {
// print ("Error signing out: %@", signOutError)
// }
//
// self.passwordField.text = ""
// }
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// if segue.identifier == "segueToMain" {
// if let destVC = segue.destination.childViewControllers[0] as? MainViewController {
// destVC.userEmail = self.emailField.text
// }
// }
// }
}
extension LoginViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.emailField {
self.passwordField.becomeFirstResponder()
} else {
if self.validateFields() {
print(NSLocalizedString("Congratulations! You entered correct values.", comment: ""))
}
}
return true
}
}
|
gpl-3.0
|
f0a748b228bd7d40da7a245d8c067323
| 31.113208 | 101 | 0.585488 | 4.998532 | false | false | false | false |
groue/GRDB.swift
|
Tests/GRDBTests/DatabaseValueConversionErrorTests.swift
|
1
|
36391
|
import XCTest
@testable import GRDB
class DatabaseValueConversionErrorTests: GRDBTestCase {
func testFetchableRecord1() throws {
struct Record: FetchableRecord {
var name: String
init(row: Row) throws {
name = try row.decode(forKey: "name")
}
}
let dbQueue = try makeDatabaseQueue()
// conversion error
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS name")
statement.arguments = [nil]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil])
XCTAssertEqual(context.sql, "SELECT ? AS name")
XCTAssertEqual(context.statementArguments, [nil])
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL], \
sql: `SELECT ? AS name`, \
arguments: [NULL]
""")
default:
XCTFail("Unexpected Error")
}
}
}
// missing column
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
column not found: "name" - \
row: [unused:"ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, "SELECT ? AS unused")
XCTAssertEqual(context.statementArguments, ["ignored"])
XCTAssertEqual(error.description, """
column not found: "name" - \
row: [unused:"ignored"], \
sql: `SELECT ? AS unused`, \
arguments: ["ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testFetchableRecord2() throws {
enum Value: String, DatabaseValueConvertible {
case valid
}
struct Record: FetchableRecord {
var value: Value
init(row: Row) throws {
value = try row.decode(forKey: "value")
}
}
let dbQueue = try makeDatabaseQueue()
// conversion error
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT 1, ? AS value")
statement.arguments = ["invalid"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["1": 1, "value": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value "invalid" - \
column: "value", \
column index: 1, \
row: [1:1 value:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["1": 1, "value": "invalid"])
XCTAssertEqual(context.sql, "SELECT 1, ? AS value")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value "invalid" - \
column: "value", \
column index: 1, \
row: [1:1 value:"invalid"], \
sql: `SELECT 1, ? AS value`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
// missing column
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
column not found: "value" - \
row: [unused:"ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, "SELECT ? AS unused")
XCTAssertEqual(context.statementArguments, ["ignored"])
XCTAssertEqual(error.description, """
column not found: "value" - \
row: [unused:"ignored"], \
sql: `SELECT ? AS unused`, \
arguments: ["ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testDecodableFetchableRecord1() throws {
struct Record: Decodable, FetchableRecord {
var name: String
var team: String
}
let dbQueue = try makeDatabaseQueue()
// conversion error
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS team")
statement.arguments = ["invalid"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"], \
sql: `SELECT NULL AS name, ? AS team`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
// missing column
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
column not found: "name" - \
row: [unused:"ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("name"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, "SELECT ? AS unused")
XCTAssertEqual(context.statementArguments, ["ignored"])
XCTAssertEqual(error.description, """
column not found: "name" - \
row: [unused:"ignored"], \
sql: `SELECT ? AS unused`, \
arguments: ["ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testDecodableFetchableRecord2() throws {
enum Value: String, DatabaseValueConvertible, Decodable {
case valid
}
struct Record: Decodable, FetchableRecord {
var value: Value
}
let dbQueue = try makeDatabaseQueue()
// conversion error
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS value")
statement.arguments = ["invalid"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["name": nil, "value": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value "invalid" - \
column: "value", \
column index: 1, \
row: [name:NULL value:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["name": nil, "value": "invalid"])
XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS value")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value "invalid" - \
column: "value", \
column index: 1, \
row: [name:NULL value:"invalid"], \
sql: `SELECT NULL AS name, ? AS value`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
// missing column
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
column not found: "value" - \
row: [unused:"ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, "SELECT ? AS unused")
XCTAssertEqual(context.statementArguments, ["ignored"])
XCTAssertEqual(error.description, """
column not found: "value" - \
row: [unused:"ignored"], \
sql: `SELECT ? AS unused`, \
arguments: ["ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testDecodableFetchableRecord3() throws {
enum Value: String, Decodable {
case valid
}
struct Record: Decodable, FetchableRecord {
var value: Value
}
let dbQueue = try makeDatabaseQueue()
// conversion error
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS value")
statement.arguments = ["invalid"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as DecodingError {
switch error {
case .dataCorrupted:
break
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"], \
sql: `SELECT NULL AS name, ? AS team`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
} catch let error as DecodingError {
switch error {
case .dataCorrupted:
break
default:
XCTFail("Unexpected Error")
}
}
}
// missing column
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS unused")
statement.arguments = ["ignored"]
do {
let row = try Row.fetchOne(statement)!
_ = try Record(row: row)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
column not found: "value" - \
row: [unused:"ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Record.fetchOne(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("value"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["unused": "ignored"])
XCTAssertEqual(context.sql, "SELECT ? AS unused")
XCTAssertEqual(context.statementArguments, ["ignored"])
XCTAssertEqual(error.description, """
column not found: "value" - \
row: [unused:"ignored"], \
sql: `SELECT ? AS unused`, \
arguments: ["ignored"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testStatementColumnConvertible1() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS team")
statement.arguments = ["invalid"]
do {
_ = try String.fetchAll(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"], \
sql: `SELECT NULL AS name, ? AS team`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(String.self, forKey: "name")
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(String.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode String from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testStatementColumnConvertible2() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT ? AS foo")
statement.arguments = [1000]
do {
_ = try Row.fetchCursor(statement)
.map { try $0.decode(Int8.self, forKey: "missing") }
.next()
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .keyNotFound(key, context):
XCTAssertEqual(key, .columnName("missing"))
XCTAssertEqual(context.key, nil)
XCTAssertEqual(context.row, ["foo": 1000])
XCTAssertEqual(context.sql, "SELECT ? AS foo")
XCTAssertEqual(context.statementArguments, [1000])
XCTAssertEqual(error.description, """
column not found: "missing" - \
row: [foo:1000], \
sql: `SELECT ? AS foo`, \
arguments: [1000]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Int8.fetchAll(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["foo": 1000])
XCTAssertEqual(context.sql, "SELECT ? AS foo")
XCTAssertEqual(context.statementArguments, [1000])
XCTAssertEqual(error.description, """
could not decode Int8 from database value 1000 - \
column: "foo", \
column index: 0, \
row: [foo:1000], \
sql: `SELECT ? AS foo`, \
arguments: [1000]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(Int8.self, forKey: "foo")
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["foo": 1000])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode Int8 from database value 1000 - \
column: "foo", \
column index: 0, \
row: [foo:1000]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(Int8.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["foo": 1000])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode Int8 from database value 1000 - \
column: "foo", \
column index: 0, \
row: [foo:1000]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testDecodableDatabaseValueConvertible() throws {
enum Value: String, DatabaseValueConvertible, Decodable {
case valid
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let statement = try db.makeStatement(sql: "SELECT NULL AS name, ? AS team")
statement.arguments = ["invalid"]
do {
_ = try Value.fetchAll(statement)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"], \
sql: `SELECT NULL AS name, ? AS team`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
_ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(1))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team")
XCTAssertEqual(context.statementArguments, ["invalid"])
XCTAssertEqual(error.description, """
could not decode \(Optional<Value>.self) from database value "invalid" - \
column: "team", \
column index: 1, \
row: [name:NULL team:"invalid"], \
sql: `SELECT NULL AS name, ? AS team`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(Value.self, forKey: "name")
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement)!
_ = try row.decode(Value.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["name": nil, "team": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value NULL - \
column: "name", \
column index: 0, \
row: [name:NULL team:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
let row = try Row.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))!
_ = try row.decode(Value.self, atIndex: 0)
XCTFail("Expected error")
} catch let error as RowDecodingError {
switch error {
case let .valueMismatch(_, context):
XCTAssertEqual(context.key, .columnIndex(0))
XCTAssertEqual(context.row, ["team": "invalid"])
XCTAssertEqual(context.sql, nil)
XCTAssertEqual(context.statementArguments, nil)
XCTAssertEqual(error.description, """
could not decode \(Value.self) from database value "invalid" - \
column: "team", \
column index: 0, \
row: [team:"invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
}
|
mit
|
61766dcc2d3729e935b749229c964a7f
| 41.26597 | 98 | 0.445357 | 6.067189 | false | false | false | false |
lyimin/EyepetizerApp
|
EyepetizerApp/EyepetizerApp/Extensions/Presenter.swift
|
1
|
2148
|
//
// LoadingPresenter.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/17.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import Foundation
protocol LoadingPresenter : class {
// 加载控件
var loaderView : EYELoaderView! { get set }
// 初始化加载控件
// func setupLoaderView ()
// // 设置控件状态
// func setLoaderViewHidden(hidden : Bool)
// // 启动动画
// func startLoadingAnimation()
// // 停止动画
// func stopLoadingAnimation()
}
extension LoadingPresenter where Self: UIViewController {
/**
初始化
*/
func setupLoaderView() {
if loaderView == nil {
loaderView = EYELoaderView(frame: CGRect(x: 0, y: 0, width: UIConstant.SCREEN_WIDTH, height: 100))
loaderView.center = CGPoint(x: UIConstant.SCREEN_WIDTH*0.5, y: UIConstant.SCREEN_HEIGHT*0.4)
self.view.addSubview(loaderView)
}
}
/**
设置显示隐藏
*/
func setLoaderViewHidden(hidden : Bool) {
if let view = loaderView {
view.hidden = hidden
if hidden {
view.stopLoadingAnimation()
} else {
view.startLoadingAnimation()
}
}
}
/**
开启动画
*/
func startLoadingAnimation () {
if let view = loaderView {
view.startLoadingAnimation()
}
}
/**
停止动画
*/
func stopLoadingAnimation() {
if let view = loaderView {
view.stopLoadingAnimation()
}
}
}
protocol MenuPresenter: class {
var menuBtn : EYEMenuBtn! { get set }
func menuBtnDidClick()
}
extension MenuPresenter where Self: UIViewController {
/**
初始化按钮
*/
func setupMenuBtn (type : EYEMenuBtnType = .None) {
menuBtn = EYEMenuBtn(frame: CGRect(x: 0, y: 0, width: 40, height: 40), type: type)
menuBtn.addTarget(self, action: Selector("menuBtnDidClick"), forControlEvents: .TouchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuBtn)
}
}
|
mit
|
d8b82290e4827a1d30aebdac86629e96
| 23.345238 | 110 | 0.584352 | 4.207819 | false | false | false | false |
QuarkX/Quark
|
Tests/QuarkTests/Venice/TCPTests.swift
|
1
|
4383
|
import XCTest
import Quark
class TCPTests : XCTestCase {
func testConnectionRefused() throws {
let connection = try TCPConnection(host: "127.0.0.1", port: 1111)
XCTAssertThrowsError(try connection.open())
}
func testSendClosedSocket() throws {
let host = try TCPHost(configuration: [])
co {
do {
let connection = try TCPConnection(host: "127.0.0.1", port: 8080)
try connection.open()
connection.close()
XCTAssertThrowsError(try connection.write(Data(), deadline: .never))
} catch {
XCTFail()
}
}
_ = try host.accept()
nap(for: 1.millisecond)
}
func testFlushClosedSocket() throws {
let port = 3333
let host = try TCPHost(configuration: ["host": "127.0.0.1", "port": Map(port), "reusePort": true])
co {
do {
let connection = try TCPConnection(host: "127.0.0.1", port: port)
try connection.open()
connection.close()
XCTAssertThrowsError(try connection.flush())
} catch {
XCTFail()
}
}
_ = try host.accept()
nap(for: 1.millisecond)
}
func testReceiveClosedSocket() throws {
let port = 4444
let host = try TCPHost(configuration: ["host": "127.0.0.1", "port": Map(port), "reusePort": true])
co {
do {
let connection = try TCPConnection(host: "127.0.0.1", port: port)
try connection.open()
connection.close()
var buffer = Data(count: 1)
XCTAssertThrowsError(try connection.read(into: &buffer))
} catch {
XCTFail()
}
}
_ = try host.accept()
nap(for: 1.millisecond)
}
func testSendReceive() throws {
let port = 5555
let host = try TCPHost(configuration: ["host": "127.0.0.1", "port": Map(port), "reusePort": true])
co {
do {
let connection = try TCPConnection(host: "127.0.0.1", port: port)
try connection.open()
try connection.write(Data([123]))
try connection.flush()
} catch {
XCTAssert(false)
}
}
let connection = try host.accept()
var buffer = Data(count: 1)
let bytesRead = try connection.read(into: &buffer)
XCTAssertEqual(bytesRead, 1)
XCTAssertEqual(buffer, Data([123]))
connection.close()
}
func testClientServer() throws {
let port = 6666
let host = try TCPHost(configuration: ["host": "127.0.0.1", "port": Map(port), "reusePort": true])
co {
do {
let connection = try TCPConnection(host: "127.0.0.1", port: port)
try connection.open()
var buffer = Data(count: 3)
let bytesRead = try connection.read(into: &buffer)
XCTAssertEqual(buffer, Data("ABC"))
XCTAssertEqual(bytesRead, 3)
try connection.write("123456789")
try connection.flush()
} catch {
XCTFail()
}
}
let connection = try host.accept()
let deadline = 30.milliseconds.fromNow()
var buffer = Data(count: 16)
XCTAssertThrowsError(try connection.read(into: &buffer, deadline: deadline))
let diff = now() - deadline
XCTAssert(diff > -300 && diff < 300)
try connection.write("ABC")
try connection.flush()
buffer = Data(count: 9)
let bytesRead = try connection.read(into: &buffer)
XCTAssertEqual(bytesRead, 9)
XCTAssertEqual(buffer, Data("123456789"))
}
}
extension TCPTests {
static var allTests : [(String, (TCPTests) -> () throws -> Void)] {
return [
("testConnectionRefused", testConnectionRefused),
("testSendClosedSocket", testSendClosedSocket),
("testFlushClosedSocket", testFlushClosedSocket),
("testReceiveClosedSocket", testReceiveClosedSocket),
("testSendReceive", testSendReceive),
("testClientServer", testClientServer),
]
}
}
|
mit
|
526b147d8bd31862e2f9dc659c3af004
| 30.085106 | 106 | 0.528405 | 4.551402 | false | true | false | false |
JockerLUO/ShiftLibra
|
ShiftLibra/ShiftLibra/Class/View/Home/View/SLHomeDetailView.swift
|
1
|
2866
|
//
// SLHomeDetailView.swift
// ShiftLibra
//
// Created by LUO on 2017/7/24.
// Copyright © 2017年 JockerLuo. All rights reserved.
//
import UIKit
class SLHomeDetailView: UIView {
var closure : (()->())?
static let detailID = "detailID"
var fromMoneyDetailList : [String]? {
didSet {
tableView.reloadData()
}
}
var toMoneyDetailList : [String]? {
didSet {
tableView.reloadData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupUI() -> () {
addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalTo(self)
}
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = homeDetailTableViewCellHight
tableView.bounces = false
tableView.separatorInset = .zero
tableView.separatorStyle = .none
tableView.register(SLHomeDetailCell.self, forCellReuseIdentifier:SLHomeDetailView.detailID)
let swipLeft = UISwipeGestureRecognizer(target: self, action: #selector(swipeGesture(swipe:)))
swipLeft.direction = .left
let swipRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeGesture(swipe:)))
swipRight.direction = .right
tableView.addGestureRecognizer(swipRight)
tableView.addGestureRecognizer(swipLeft)
}
@objc fileprivate func swipeGesture(swipe : UISwipeGestureRecognizer) -> () {
}
fileprivate lazy var tableView : UITableView = {
let tableView = UITableView()
return tableView
}()
}
extension SLHomeDetailView : UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 9
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SLHomeDetailView.detailID, for: indexPath) as! SLHomeDetailCell
cell.selectionStyle = .none
cell.labLeft.text = fromMoneyDetailList?[indexPath.row]
cell.labRight.text = toMoneyDetailList?[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
closure?()
}
}
|
mit
|
cde41de234c1202cd6d0ee4e7749189c
| 23.681034 | 128 | 0.582606 | 5.505769 | false | false | false | false |
imodeveloperlab/ImoCollectionView
|
ImoCollectionView/Example/ImoCollectionView_Example/PictureCell.swift
|
1
|
975
|
//
// PictureCell.swift
// ImoCollectionView_Example
//
// Created by Borinschi Ivan on 11/2/16.
// Copyright (c) 2016 Imodeveloperlab. All rights reserved.
//
// This file was generated by the ImoCollectionView Xcode Templates
//
import UIKit
import ImoCollectionView
class PictureCellSource: ImoCollectionViewCellSource {
var pictureName : String
public init(picture:String) {
self.pictureName = picture
super.init(cellClass: "PictureCell")
self.height = 100
self.width = 100
self.nib = UINib(nibName: self.cellClass, bundle: Bundle.init(for: self.classForCoder))
}
}
class PictureCell: ImoCollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
public override func setUpWithSource(source:AnyObject) {
if source is PictureCellSource {
imageView.image = UIImage(named: source.pictureName)
}
}
}
|
gpl-3.0
|
959db1038f39863f3cb24669b2fd4b33
| 22.214286 | 95 | 0.647179 | 4.431818 | false | false | false | false |
ImranRaheem/iOS-11-samples
|
Drag and Drop/DragAndDropExample/ViewController.swift
|
1
|
5098
|
//
// ViewController.swift
// DragAndDropExample
//
// Created by imran on 28/6/17.
// Copyright © 2017 Imran. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: ivars
@IBOutlet weak var collectionView: UICollectionView!
private lazy var images: [UIImage] = {
var array = [UIImage]()
for i in 1...10 {
if let image = UIImage(named: "Image\(i)") {
array.append(image)
}
}
return array
}()
private var draggedIndexPaths = [IndexPath]()
private let kCellIdentifier = "ImageCell"
//MARK: view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Drag Cars"
collectionView.register(ImageCell.self, forCellWithReuseIdentifier: kCellIdentifier)
// Drag & Drop delegates
collectionView.dragDelegate = self
collectionView.dropDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateCollection(with imageItems: [NSItemProviderReading], coordinator: UICollectionViewDropCoordinator) {
var i = 0
let destinationIndexPath = coordinator.destinationIndexPath ?? IndexPath(item: 0, section: 0)
for item in imageItems {
if let image = item as? UIImage {
// Local drag
if case .move = coordinator.proposal.operation {
// replace images
images.remove(at: self.draggedIndexPaths[i].row)
images.insert(image, at: destinationIndexPath.row)
}
else if case .copy = coordinator.proposal.operation {
// add images
images.insert(image, at: destinationIndexPath.row)
collectionView.insertItems(at: [destinationIndexPath])
}
}
i += 1
}
}
}
// MARK: Drag
extension ViewController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
draggedIndexPaths.removeAll()
draggedIndexPaths.append(indexPath)
let cell = collectionView.cellForItem(at: indexPath) as! ImageCell
let imageItemProvider = NSItemProvider(object: cell.imageView.image!)
return [UIDragItem(itemProvider: imageItemProvider)]
}
func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
draggedIndexPaths.append(indexPath)
let cell = collectionView.cellForItem(at: indexPath) as! ImageCell
let imageItemProvider = NSItemProvider(object: cell.imageView.image!)
return [UIDragItem(itemProvider: imageItemProvider)]
}
}
// MARK: Drop
extension ViewController: UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
// loads objects on main thread
coordinator.session.loadObjects(ofClass: UIImage.self) { imageItems in
self.updateCollection(with: imageItems, coordinator: coordinator)
collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)
// The following results in crash with reason: 'attempt to create view animation for nil view'
// Reported here: http://www.openradar.me/28163205
//
// let indexSet = IndexSet(integer: 0)
// collectionView.reloadSections(indexSet)
}
}
// Drop proposal
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
if session.localDragSession != nil {
return UICollectionViewDropProposal(dropOperation: .move, intent: .insertAtDestinationIndexPath)
}
else {
return UICollectionViewDropProposal(dropOperation: .copy, intent: .insertIntoDestinationIndexPath)
}
}
}
// MARK: UICollectionView Data Source
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellIdentifier, for: indexPath) as! ImageCell
cell.imageView.image = images[indexPath.row]
return cell
}
}
|
mit
|
2443ad1bef74cbd7d4d5e965cc97d423
| 35.407143 | 197 | 0.651167 | 5.558342 | false | false | false | false |
mohitathwani/swift-corelibs-foundation
|
Foundation/NSTextCheckingResult.swift
|
3
|
4396
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
/* NSTextCheckingType in this project is limited to regular expressions. */
extension NSTextCheckingResult {
public struct CheckingType : OptionSet {
public let rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
public static let RegularExpression = CheckingType(rawValue: 1 << 10) // regular expression matches
}
}
open class NSTextCheckingResult: NSObject, NSCopying, NSCoding {
public override init() {
if type(of: self) == NSTextCheckingResult.self {
NSRequiresConcreteImplementation()
}
}
open class func regularExpressionCheckingResultWithRanges(_ ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) -> NSTextCheckingResult {
return _NSRegularExpressionNSTextCheckingResultResult(ranges: ranges, count: count, regularExpression: regularExpression)
}
public required init?(coder aDecoder: NSCoder) {
if type(of: self) == NSTextCheckingResult.self {
NSRequiresConcreteImplementation()
}
}
open func encode(with aCoder: NSCoder) {
NSRequiresConcreteImplementation()
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
/* Mandatory properties, used with all types of results. */
open var resultType: CheckingType { NSRequiresConcreteImplementation() }
open var range: NSRange { return range(at: 0) }
/* A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups). The range at index 0 always matches the range property. Additional ranges, if any, will have indexes from 1 to numberOfRanges-1. */
open func range(at idx: Int) -> NSRange { NSRequiresConcreteImplementation() }
open var regularExpression: NSRegularExpression? { return nil }
open var numberOfRanges: Int { return 1 }
}
internal class _NSRegularExpressionNSTextCheckingResultResult : NSTextCheckingResult {
var _ranges = [NSRange]()
let _regularExpression: NSRegularExpression
init(ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) {
_regularExpression = regularExpression
super.init()
let notFound = NSRange(location: NSNotFound,length: 0)
for i in 0..<count {
ranges[i].location == kCFNotFound ? _ranges.append(notFound) : _ranges.append(ranges[i])
}
}
internal required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
internal override func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
override var resultType: CheckingType { return .RegularExpression }
override func range(at idx: Int) -> NSRange { return _ranges[idx] }
override var numberOfRanges: Int { return _ranges.count }
override var regularExpression: NSRegularExpression? { return _regularExpression }
}
extension NSTextCheckingResult {
public func resultByAdjustingRangesWithOffset(_ offset: Int) -> NSTextCheckingResult {
let count = self.numberOfRanges
var newRanges = [NSRange]()
for idx in 0..<count {
let currentRange = self.range(at: idx)
if (currentRange.location == NSNotFound) {
newRanges.append(currentRange)
} else if ((offset > 0 && NSNotFound - currentRange.location <= offset) || (offset < 0 && currentRange.location < -offset)) {
NSInvalidArgument(" \(offset) invalid offset for range {\(currentRange.location), \(currentRange.length)}")
} else {
newRanges.append(NSRange(location: currentRange.location + offset,length: currentRange.length))
}
}
let result = NSTextCheckingResult.regularExpressionCheckingResultWithRanges(&newRanges, count: count, regularExpression: self.regularExpression!)
return result
}
}
|
apache-2.0
|
7731189c73c5b359c7afcb2b6e490fcd
| 40.084112 | 271 | 0.684031 | 5.165687 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.