hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
64ba48d2c3173fa1ceca4fa5f4f9d31ef55db21b | 11,781 | //
// SheetContentViewController.swift
// FittedSheetsPod
//
// Created by Gordon Tucker on 7/29/20.
// Copyright © 2020 Gordon Tucker. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
public class SheetContentViewController: UIViewController {
public private(set) var childViewController: UIViewController
private var options: SheetOptions
private (set) var size: CGFloat = 0
private (set) var preferredHeight: CGFloat
public var contentBackgroundColor: UIColor? {
get { self.childContainerView.backgroundColor }
set { self.childContainerView.backgroundColor = newValue }
}
public var cornerRadius: CGFloat = 0 {
didSet {
self.updateCornerRadius()
}
}
public var gripSize: CGSize = CGSize(width: 50, height: 6) {
didSet {
self.gripSizeConstraints.forEach({ $0.isActive = false })
Constraints(for: self.gripView) {
self.gripSizeConstraints = $0.size.set(self.gripSize)
}
self.gripView.layer.cornerRadius = self.gripSize.height / 2
}
}
public var gripColor: UIColor? {
get { return self.gripView.backgroundColor }
set { self.gripView.backgroundColor = newValue }
}
public var pullBarBackgroundColor: UIColor? {
get { return self.pullBarView.backgroundColor }
set { self.pullBarView.backgroundColor = newValue }
}
public var treatPullBarAsClear: Bool = SheetViewController.treatPullBarAsClear {
didSet {
if self.isViewLoaded {
self.updateCornerRadius()
}
}
}
weak var delegate: SheetContentViewDelegate?
public var contentWrapperView = UIView()
public var contentView = UIView()
private var contentTopConstraint: NSLayoutConstraint?
private var contentBottomConstraint: NSLayoutConstraint?
private var navigationHeightConstraint: NSLayoutConstraint?
private var gripSizeConstraints: [NSLayoutConstraint] = []
public var childContainerView = UIView()
public var pullBarView = UIView()
public var gripView = UIView()
private let overflowView = UIView()
public init(childViewController: UIViewController, options: SheetOptions) {
self.options = options
self.childViewController = childViewController
self.preferredHeight = 0
super.init(nibName: nil, bundle: nil)
if options.setIntrinsicHeightOnNavigationControllers, let navigationController = self.childViewController as? UINavigationController {
navigationController.delegate = self
}
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
self.setupContentView()
self.setupChildContainerView()
self.setupPullBarView()
self.setupChildViewController()
self.updatePreferredHeight()
self.updateCornerRadius()
self.setupOverflowView()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIView.performWithoutAnimation {
self.view.layoutIfNeeded()
}
self.updatePreferredHeight()
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.updatePreferredHeight()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.updateAfterLayout()
}
func updateAfterLayout() {
self.size = self.childViewController.view.bounds.height
//self.updatePreferredHeight()
}
func adjustForKeyboard(height: CGFloat) {
self.updateChildViewControllerBottomConstraint(adjustment: -height)
}
private func updateCornerRadius() {
self.contentWrapperView.layer.cornerRadius = self.treatPullBarAsClear ? 0 : self.cornerRadius
self.childContainerView.layer.cornerRadius = self.treatPullBarAsClear ? self.cornerRadius : 0
}
private func setupOverflowView() {
switch (self.options.transitionOverflowType) {
case .view(view: let view):
overflowView.backgroundColor = .clear
overflowView.addSubview(view) {
$0.edges.pinToSuperview()
}
case .automatic:
overflowView.backgroundColor = self.childViewController.view.backgroundColor
case .color(color: let color):
overflowView.backgroundColor = color
case .none:
overflowView.backgroundColor = .clear
}
}
private func updateNavigationControllerHeight() {
// UINavigationControllers don't set intrinsic size, this is a workaround to fix that
guard self.options.setIntrinsicHeightOnNavigationControllers, let navigationController = self.childViewController as? UINavigationController else { return }
self.navigationHeightConstraint?.isActive = false
self.contentTopConstraint?.isActive = false
if let viewController = navigationController.visibleViewController {
let size = viewController.view.systemLayoutSizeFitting(CGSize(width: view.bounds.width, height: 0))
if self.navigationHeightConstraint == nil {
self.navigationHeightConstraint = navigationController.view.heightAnchor.constraint(equalToConstant: size.height)
} else {
self.navigationHeightConstraint?.constant = size.height
}
}
self.navigationHeightConstraint?.isActive = true
self.contentTopConstraint?.isActive = true
}
func updatePreferredHeight() {
self.updateNavigationControllerHeight()
let width = self.view.bounds.width > 0 ? self.view.bounds.width : UIScreen.main.bounds.width
let oldPreferredHeight = self.preferredHeight
var fittingSize = UIView.layoutFittingCompressedSize;
fittingSize.width = width;
self.contentTopConstraint?.isActive = false
UIView.performWithoutAnimation {
self.contentView.layoutSubviews()
}
self.preferredHeight = self.contentView.systemLayoutSizeFitting(fittingSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow).height + (self.contentBottomConstraint?.constant ?? 0)
self.contentTopConstraint?.isActive = true
UIView.performWithoutAnimation {
self.contentView.layoutSubviews()
}
self.delegate?.preferredHeightChanged(oldHeight: oldPreferredHeight, newSize: self.preferredHeight)
}
private func updateChildViewControllerBottomConstraint(adjustment: CGFloat) {
self.contentBottomConstraint?.constant = adjustment
}
private func setupChildViewController() {
self.childViewController.willMove(toParent: self)
self.addChild(self.childViewController)
self.childContainerView.addSubview(self.childViewController.view)
Constraints(for: self.childViewController.view) { view in
view.left.pinToSuperview()
view.right.pinToSuperview()
self.contentBottomConstraint = view.bottom.pinToSuperview()
view.top.pinToSuperview()
}
if self.options.shouldExtendBackground, self.options.pullBarHeight > 0 {
self.childViewController.compatibleAdditionalSafeAreaInsets = UIEdgeInsets(top: self.options.pullBarHeight, left: 0, bottom: 0, right: 0)
}
self.childViewController.didMove(toParent: self)
self.childContainerView.layer.masksToBounds = true
self.childContainerView.layer.compatibleMaskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
}
private func setupContentView() {
self.view.addSubview(self.contentView)
Constraints(for: self.contentView) {
$0.left.pinToSuperview()
$0.right.pinToSuperview()
$0.bottom.pinToSuperview()
self.contentTopConstraint = $0.top.pinToSuperview()
}
self.contentView.addSubview(self.contentWrapperView) {
$0.edges.pinToSuperview()
}
self.contentWrapperView.layer.masksToBounds = true
self.contentWrapperView.layer.compatibleMaskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
self.contentView.addSubview(overflowView) {
$0.edges(.left, .right).pinToSuperview()
$0.height.set(200)
$0.top.align(with: self.contentView.al.bottom - 1)
}
}
private func setupChildContainerView() {
self.contentWrapperView.addSubview(self.childContainerView)
Constraints(for: self.childContainerView) { view in
if self.options.shouldExtendBackground {
view.top.pinToSuperview()
} else {
view.top.pinToSuperview(inset: self.options.pullBarHeight)
}
view.left.pinToSuperview()
view.right.pinToSuperview()
view.bottom.pinToSuperview()
}
}
private func setupPullBarView() {
// If they didn't specify pull bar options, they don't want a pull bar
guard self.options.pullBarHeight > 0 else { return }
let pullBarView = self.pullBarView
pullBarView.isUserInteractionEnabled = true
pullBarView.backgroundColor = self.pullBarBackgroundColor
self.contentWrapperView.addSubview(pullBarView)
Constraints(for: pullBarView) {
$0.top.pinToSuperview()
$0.left.pinToSuperview()
$0.right.pinToSuperview()
$0.height.set(options.pullBarHeight)
}
self.pullBarView = pullBarView
let gripView = self.gripView
gripView.backgroundColor = self.gripColor
gripView.layer.cornerRadius = self.gripSize.height / 2
gripView.layer.masksToBounds = true
pullBarView.addSubview(gripView)
self.gripSizeConstraints.forEach({ $0.isActive = false })
Constraints(for: gripView) {
$0.centerY.alignWithSuperview()
$0.centerX.alignWithSuperview()
self.gripSizeConstraints = $0.size.set(self.gripSize)
}
pullBarView.isAccessibilityElement = true
pullBarView.accessibilityIdentifier = "pull-bar"
// This will be overriden whenever the sizes property is changed on SheetViewController
pullBarView.accessibilityLabel = Localize.dismissPresentation.localized
pullBarView.accessibilityTraits = [.button]
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(pullBarTapped))
pullBarView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func pullBarTapped(_ gesture: UITapGestureRecognizer) {
self.delegate?.pullBarTapped()
}
}
extension SheetContentViewController: UINavigationControllerDelegate {
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
navigationController.view.endEditing(true)
}
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
self.navigationHeightConstraint?.isActive = true
self.updatePreferredHeight()
}
}
#endif // os(iOS) || os(tvOS) || os(watchOS)
| 39.009934 | 219 | 0.663186 |
ccb5c6e4b8ddeacd85985023ee9e4abfe958a6a2 | 414 | //
// SavedFudaSetTest.swift
// Shuffle100Tests
//
// Created by 里 佳史 on 2019/05/29.
// Copyright © 2019 里 佳史. All rights reserved.
//
import XCTest
class SavedFudaSetTest: XCTestCase {
func test_initWithParameters() {
// given, when
let set = SavedFudaSet()
// then
XCTAssertEqual(set.name, "名前を付けましょう")
XCTAssertEqual(set.state100.selectedNum, 100)
}
}
| 19.714286 | 53 | 0.630435 |
d771f6381f11e6ff23a5ad4471785551fcaf384a | 1,542 | //
// TaskViewCell.swift
// DribbbleTodo
//
// Created by tskim on 04/05/2019.
// Copyright © 2019 hucet. All rights reserved.
//
import Foundation
import ReactorKit
import UIKit
class TaskViewCell: UICollectionViewCell, SwiftNameIdentifier {
struct Metric {
static let height: CGFloat = 100
}
let titleView = UILabel()
let roundShadowView = RoundShadowView()
override init(frame: CGRect) {
super.init(frame: frame)
roundShadowView.do {
$0.backgroundColor = ColorName.bgTaskCell
$0.cornerRadius = 5.0
contentView.addSubview($0)
$0.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
titleView.do {
roundShadowView.addSubview($0)
$0.numberOfLines = 0
$0.lineBreakMode = .byWordWrapping
$0.snp.makeConstraints {
$0.edges.equalToSuperview().inset(10)
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
titleView.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.right
layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
}
| 29.653846 | 142 | 0.650454 |
23ad7194ce526cc53a0820d14f418a324dd63b36 | 1,305 | import Foundation
import SpriteKit
public class GameScene: SKScene {
var gameController: GameController!
var mapLineNode: SKSpriteNode!
var headerNode: SKSpriteNode!
var startButtonNode: SKNode!
public override func sceneDidLoad() {
// Setup Assets
// Get nodes reference
if let node = self.childNode(withName: "mapLineNode") as? SKSpriteNode {
self.mapLineNode = node
}
if let node = self.childNode(withName: "startButtonNode") {
self.startButtonNode = node
}
if let node = self.childNode(withName: "headerNode") as? SKSpriteNode {
self.headerNode = node
}
}
override public func didMove(to view: SKView) {
let startButton = ButtonNode(backgroundNamed: "bg_button_home", labelText: "") {
self.gameController.presentScene()
}
startButton.xScale = 1
startButton.yScale = 1
if (self.startButtonNode != nil) {
self.startButtonNode.addChild(startButton)
}
// Create Audio Node
let bgAudioNode = SKAudioNode(fileNamed: "bgAudio")
bgAudioNode.autoplayLooped = true
self.addChild(bgAudioNode)
}
}
| 27.765957 | 88 | 0.590805 |
bb07e0040459a5f0ec9910e45b1fa623a8a3efc7 | 5,556 | //
// LemonadeButton.swift
// LemonadeUI
//
// Created by Hasan Özgür Elmaslı on 17.08.2021.
//
import UIKit
@objc class ClosureSleeve: NSObject {
let closure: ()->()
init( _ closure: @escaping ()->()) {
self.closure = closure
}
@objc func invoke(){
closure()
}
}
extension UIControl {
public func addAction(for controlEvents: UIControl.Event = .touchUpInside, _ closure: @escaping ()->()) {
let sleeve = ClosureSleeve(closure)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
objc_setAssociatedObject(self, "[\(arc4random())]", sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
public class LemonadeButton : UIButton {
///Switch Button type delegate
public weak var lemonadeSwitchButtonDelegate : LemonadeSwitchButtonDelegate?
/// Button Click animation
public var clickAnimation : LemonadeAnimation?
private weak var toggleView : UIView?
private var toggleLeftAnchor : NSLayoutConstraint?
private var switchButtonConfig : LemonadeSwitchButtonConfig?
private var toggleConfig : LemonadeSwitchToggleConfig?
public override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public convenience init(frame : CGRect , _ text : LemonadeText) {
self.init(frame:frame)
if text.kern != 0.0 || text.underLine != nil { self.attributedText(text) }
else { self.text(text) }
}
public convenience init(frame : CGRect , _ text : LemonadeText, handler: @escaping (()->Void)) {
self.init(frame: frame, text)
self.onClick {
handler()
}
}
}
extension LemonadeButton {
/**
Switch button settings
- parameter config: LemonadeSwitchButtonConfig.
- parameter toggleConfig: LemonadeSwitchToggleConfig.
- returns: none
- warning: Can't add onClick function after setting up
*/
public func switchButton( _ config : LemonadeSwitchButtonConfig , toggleConfig : LemonadeSwitchToggleConfig){
self.layoutIfNeeded()
color(toggleConfig.isOn ? config.activeColor : config.deActiveColor)
createToggledView(toggleConfig)
self.onClick { [weak self] in
self?.toggleClick()
}
self.switchButtonConfig = config
self.toggleConfig = toggleConfig
}
///Creating toogling view
private func createToggledView( _ config : LemonadeSwitchToggleConfig){
let view : UIView = .init(frame: .zero
, color: config.isOn ? config.activeColor : config.deActiveColor, radius: .init(radius: config.width / 2.0)
, border: config.border)
view.isUserInteractionEnabled = false
self.addSubview(view)
view.height(constant: config.height)
view.width(constant: config.width)
view.centerY(self, equalTo: .centerY)
toggleLeftAnchor = view.leftAnchor.constraint(equalTo: self.leftAnchor , constant: config.isOn ? self.bounds.width - ( config.width + config.padding ) : config.padding)
toggleLeftAnchor?.isActive = true
self.toggleView = view
}
/// Toggle trigger with param
@objc public func toggle( _ value : Bool) {
if toggleLeftAnchor == nil || toggleView == nil || switchButtonConfig == nil || toggleConfig == nil { return }
toggleLeftAnchor?.constant = value ? self.bounds.width - ( toggleConfig!.width + toggleConfig!.padding ) : toggleConfig!.padding
self.toggleConfig?.onChange(value)
self.lemonadeSwitchButtonDelegate?.didToggle(self, isOn: value)
UIView.animate(withDuration: switchButtonConfig!.animationDuration) {
self.color(value ? self.switchButtonConfig!.activeColor : self.switchButtonConfig!.deActiveColor)
self.toggleView?.color(self.toggleConfig!.isOn ? self.toggleConfig!.activeColor : self.toggleConfig!.deActiveColor)
self.layoutIfNeeded()
}
}
/// Toggle trigger without param
@objc public func toggleClick(){ toggle( (!(toggleConfig?.isOn ?? false) ) ) }
}
extension LemonadeButton {
/// Text configuration function
public func text( _ text : LemonadeText) {
self.setTitle(text.text, for: .normal)
self.setTitleColor(text.color, for: .normal)
self.titleLabel?.font = text.font
self.titleLabel?.textAlignment = text.alignment
}
/// Atrributed Text configuration function
public func attributedText( _ text : LemonadeText) {
self.setAttributedTitle(text.attributeText(), for: .normal)
}
/// Adding click
public func onClick(target : Any? , _ action : Selector) {
if target == nil && superview == nil {
fatalError("SuperView can't be empty. That's illegal.")
}
}
// Adding click
public func onClick( _ handler: @escaping (()->())) {
self.addAction {
handler()
}
}
}
extension LemonadeButton {
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let animation = self.clickAnimation {
self.layoutIfNeeded()
self.animate(animation, config: .init(duration: 0.3, repeatCount: 1, autoReverse: true))
}
}
}
| 34.08589 | 176 | 0.639849 |
2fd0ba7330a4f316fa8b83c0b4a52ee3462b688c | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T
func g {
{
}
protocol C {
{
{
}
}
{
}
typealias d: B<d>
func b
| 13.444444 | 87 | 0.698347 |
f989109d03ab0e6728d5a8fd1bd82ccdafc8964d | 220 | //
// File.swift
//
//
// Created by Andrés Pesate on 01/01/2022.
//
import Foundation
import protocol GraphQLClient.Service
struct ServiceDummy: Service {
var url: URL
var additionalHeaders: [String: String]?
}
| 14.666667 | 43 | 0.709091 |
220e7571b68f90a606a8f872417e093d2984dbb1 | 1,135 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "CombinedContacts",
platforms: [
.iOS(.v13),
.macOS(.v10_15)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "CombinedContacts",
targets: ["CombinedContacts"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "CombinedContacts",
dependencies: []),
.testTarget(
name: "CombinedContactsTests",
dependencies: ["CombinedContacts"]),
]
)
| 34.393939 | 122 | 0.620264 |
018ff996fffb89a934ee1ba22775d6ff107fbe91 | 2,045 | //
// Modified MIT License
//
// Copyright (c) 2010-2018 Kite Tech Ltd. https://www.kite.ly
//
// 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 software MAY ONLY be used with the Kite Tech Ltd platform and MAY NOT be modified
// to be used with any competitor platforms. This means the software MAY NOT be modified
// to place orders with any competitors to Kite Tech Ltd, all orders MUST go through the
// Kite Tech Ltd platform servers.
//
// 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
@objc public protocol Product: NSCoding {
var selectedShippingMethod: ShippingMethod? { get set }
var identifier: String { get }
var itemCount: Int { get set }
var template: Template { get }
var hash: Int { get }
func assetsToUpload() -> [PhotobookAsset]?
func orderParameters() -> [String: Any]?
func costParameters() -> [String: Any]?
func previewImage(size: CGSize, completionHandler: @escaping (UIImage?) -> Void)
func processUploadedAssets(completionHandler: @escaping (Error?) -> Void)
}
| 46.477273 | 89 | 0.73154 |
0a737f06f5b7ec0b8935b72bc18e4d4c7ba2dab4 | 995 | // swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Rope",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Rope",
targets: ["Rope"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Rope",
dependencies: []),
.testTarget(
name: "RopeTests",
dependencies: ["Rope"]),
]
)
| 34.310345 | 122 | 0.609045 |
75c814c046439f6c6067735c5e358bcfc6b00e75 | 293 | extension Set {
func sample() -> Set.Element? {
if count > 0 {
let offset = Int(arc4random()) % count
let nIndex = index(startIndex, offsetBy: offset)//index.index(startIndex, offsetBy: offset)
return self[nIndex]
} else {
return nil
}
}
}
| 22.538462 | 99 | 0.573379 |
381c26c1eb185c1f4928270d9893dcd2c1ab3781 | 1,117 | //
// RunLengthEncoding.swift
// swift-algorithms
//
// Created by Aaron Hinton on 8/25/20.
// Copyright © 2020 No Name Software. All rights reserved.
//
import Foundation
class RunLengthEncoding {
static func runLengthEncoding(_ input: String) -> String {
if input.isEmpty {
return ""
}
var currentCharacter: Character?
var count = 0
var compressedString = ""
for index in input.indices {
if input[index] == currentCharacter {
count += 1
} else {
if let current = currentCharacter {
let normalizedCount = count == 1 ? "": "\(count)"
compressedString += "\(current)\(normalizedCount)"
}
count = 1
currentCharacter = input[index]
}
}
if let character = currentCharacter {
let normalizedCount = count == 1 ? "": "\(count)"
compressedString += "\(character)\(normalizedCount)"
}
return compressedString
}
}
| 27.243902 | 70 | 0.514772 |
cc42ecba3185faabef2d25789b3f7b0e122b7dfb | 550 | //
// UIView+ParentViewController.swift
// iOSBaseProject
//
// Created by admin on 16/8/10.
// Copyright © 2016年 Ding. All rights reserved.
//
import UIKit
public extension UIView {
public var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
| 23.913043 | 74 | 0.634545 |
e41410a7ca1bc8fa4a6c839c82020669541176ef | 11,750 | //
// PlanManageViewController.swift
// Tireless
//
// Created by Hao on 2022/4/22.
//
import UIKit
class PlanManageViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
}
}
let viewModel = PlanManageViewModel()
private var planEmptyView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
setPlanEmptyView()
self.view.backgroundColor = .themeBG
planEmptyView.isHidden = true
self.navigationController?.navigationBar.titleTextAttributes =
[NSAttributedString.Key.foregroundColor: UIColor.white]
self.navigationController?.navigationBar.barTintColor = .themeBG
configureCollectionView()
viewModel.planViewModels.bind { [weak self] _ in
DispatchQueue.main.async {
self?.collectionView.reloadData()
}
}
viewModel.groupPlanViewModels.bind { [weak self] _ in
DispatchQueue.main.async {
self?.collectionView.reloadData()
}
}
}
override func viewWillAppear(_ animated: Bool) {
if AuthManager.shared.currentUser != "" {
self.viewModel.fetchPlan()
} else {
self.viewModel.logoutReset()
}
}
private func setPlanEmptyView() {
planEmptyView.image = UIImage(named: "tireless_noplan")
planEmptyView.contentMode = .scaleAspectFit
self.view.addSubview(planEmptyView)
planEmptyView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
planEmptyView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
planEmptyView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
planEmptyView.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height / 3),
planEmptyView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width / 2)
])
}
private func configureCollectionView() {
collectionView.collectionViewLayout = createLayout()
collectionView.backgroundColor = .themeBG
collectionView.register(UINib(nibName: "\(PlanManageViewCell.self)", bundle: nil),
forCellWithReuseIdentifier: "\(PlanManageViewCell.self)")
collectionView.register(HomeHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "\(HomeHeaderView.self)")
}
private func createLayout() -> UICollectionViewLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(130))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: itemSize,
subitems: [item])
let section = NSCollectionLayoutSection(group: group)
let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(60))
let header = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSize,
elementKind:
UICollectionView.elementKindSectionHeader,
alignment: .top)
section.boundarySupplementaryItems = [header]
section.interGroupSpacing = 5
section.contentInsets = .init(top: 5, leading: 15, bottom: 5, trailing: 15)
return UICollectionViewCompositionalLayout(section: section)
}
private func present(target: String, plan: Plan) {
guard let poseVC = UIStoryboard.poseDetect.instantiateViewController(
withIdentifier: "\(PoseDetectViewController.self)")
as? PoseDetectViewController
else {
return
}
poseVC.viewModel = PoseDetectViewModel(plan: plan)
poseVC.modalPresentationStyle = .fullScreen
self.present(poseVC, animated: true)
}
private func groupPlanPresent(plan: Plan) {
guard let groupVC = storyboard?.instantiateViewController(
withIdentifier: "\(GroupPlanStatusViewController.self)")
as? GroupPlanStatusViewController
else {
return
}
groupVC.plan = plan
self.navigationItem.backButtonTitle = ""
self.navigationController?.pushViewController(groupVC, animated: true)
}
private func planReviewPresent(plan: Plan) {
guard let reviewVC = storyboard?.instantiateViewController(
withIdentifier: "\(PlanReviewViewController.self)")
as? PlanReviewViewController
else {
return
}
reviewVC.plan = plan
self.navigationItem.backButtonTitle = ""
self.navigationController?.pushViewController(reviewVC, animated: true)
}
private func planModifyPresent(plan: Plan) {
guard let modifyVC = UIStoryboard.plan.instantiateViewController(
withIdentifier: "\(PlanModifyViewController.self)")
as? PlanModifyViewController
else {
return
}
modifyVC.plan = plan
modifyVC.modalPresentationStyle = .overCurrentContext
modifyVC.modalTransitionStyle = .crossDissolve
present(modifyVC, animated: true)
}
}
extension PlanManageViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
2
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
if (viewModel.planViewModels.value.count + viewModel.groupPlanViewModels.value.count) == 0 {
collectionView.isHidden = true
planEmptyView.isHidden = false
} else {
collectionView.isHidden = false
planEmptyView.isHidden = true
}
if section == 0 {
return viewModel.planViewModels.value.count
} else {
return viewModel.groupPlanViewModels.value.count
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "\(PlanManageViewCell.self)", for: indexPath) as? PlanManageViewCell else {
return UICollectionViewCell()
}
if indexPath.section == 0 {
let cellViewModel = self.viewModel.planViewModels.value[indexPath.row]
cell.setup(viewModel: cellViewModel)
cell.isDeleteButtonTap = {
self.setUserAlert(plan: cellViewModel.plan)
}
cell.isStartButtonTap = {
self.present(target: cellViewModel.plan.planTimes, plan: cellViewModel.plan)
}
} else {
let cellViewModel = self.viewModel.groupPlanViewModels.value[indexPath.row]
cell.setup(viewModel: cellViewModel)
cell.isStartButtonTap = {
self.present(target: cellViewModel.plan.planTimes, plan: cellViewModel.plan)
}
cell.isDeleteButtonTap = {
self.setUserAlert(plan: cellViewModel.plan)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
guard let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: "\(HomeHeaderView.self)",
for: indexPath) as? HomeHeaderView else {
return UICollectionReusableView()
}
if indexPath.section == 0 {
headerView.textLabel.text = "個人計畫"
} else {
headerView.textLabel.text = "團體計畫"
}
return headerView
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.section == 0 {
let cellViewModel = self.viewModel.planViewModels.value[indexPath.row]
planReviewPresent(plan: cellViewModel.plan)
} else {
let cellViewModel = self.viewModel.groupPlanViewModels.value[indexPath.row]
groupPlanPresent(plan: cellViewModel.plan)
}
}
}
extension PlanManageViewController {
private func showDeleteAlert(plan: Plan) {
let alertController = UIAlertController(title: "確認刪除!",
message: "刪除的計畫無法再度復原!",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "確定", style: .destructive) { _ in
PlanManager.shared.deletePlan(userId: AuthManager.shared.currentUser, plan: plan) { result in
switch result {
case .success(let text):
ProgressHUD.showSuccess(text: "刪除計畫成功")
print(text)
case .failure(let error):
ProgressHUD.showFailure()
print(error)
}
}
alertController.dismiss(animated: true)
}
let cancelAction = UIAlertAction(title: "取消", style: .default) { _ in
alertController.dismiss(animated: true)
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// iPad specific code
alertController.popoverPresentationController?.sourceView = self.view
let xOrigin = self.view.bounds.width / 2
let popoverRect = CGRect(x: xOrigin, y: self.view.bounds.height, width: 1, height: 1)
alertController.popoverPresentationController?.sourceRect = popoverRect
alertController.popoverPresentationController?.permittedArrowDirections = .down
self.present(alertController, animated: true)
}
private func setUserAlert(plan: Plan) {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let adjust = UIAlertAction(title: "修改計畫次數", style: .default) { _ in
self.planModifyPresent(plan: plan)
}
let delete = UIAlertAction(title: "刪除計畫", style: .destructive) { _ in
self.showDeleteAlert(plan: plan)
}
if plan.planGroup == false {
controller.addAction(adjust)
}
controller.addAction(delete)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
controller.addAction(cancelAction)
// iPad specific code
controller.popoverPresentationController?.sourceView = self.view
let xOrigin = self.view.bounds.width / 2
let popoverRect = CGRect(x: xOrigin, y: self.view.bounds.height, width: 1, height: 1)
controller.popoverPresentationController?.sourceRect = popoverRect
controller.popoverPresentationController?.permittedArrowDirections = .down
present(controller, animated: true, completion: nil)
}
}
| 41.22807 | 119 | 0.61566 |
7a05b4e6ae2aef72f8cd9a556dc534907887a68d | 15,881 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/ImportPath)
// RUN: %{python} %utils/split_file.py -o %t %s
// RUN: %target-swift-frontend -disable-availability-checking -emit-module %t/Lib.swift -o %t/ImportPath/Lib.swiftmodule -emit-module-interface-path %t/ImportPath/Lib.swiftinterface
// BEGIN Lib.swift
public protocol MyBaseProto {}
public protocol MyProto: MyBaseProto {}
public protocol MyOtherProto {}
public struct Foo: MyProto {
public init() {}
}
public struct Bar: MyOtherProto {
public init() {}
}
public struct FooBar: MyProto, MyOtherProto {
public init() {}
}
public func makeFoo() -> Foo {
return Foo()
}
public let GLOBAL_FOO = Foo()
public class MyClass {}
public class MySubclass: MyClass {}
public class MySubclassConformingToMyProto: MyClass, MyProto {}
public func makeMyClass() -> MyClass { return MyClass() }
public func makeMySubclass() -> MySubclass { return MySubclass() }
public func returnSomeMyProto() -> some MyProto { return Foo() }
public protocol ProtoWithAssocType {
associatedtype MyAssoc
}
public struct StructWithAssocType: ProtoWithAssocType {
public typealias MyAssoc = Int
}
public func makeProtoWithAssocType() -> some ProtoWithAssocType { return StructWithAssocType() }
@propertyWrapper
public struct MyPropertyWrapper {
public var wrappedValue: String
public init(wrappedValue: String) {
self.wrappedValue = wrappedValue
}
}
// BEGIN test.swift
import Lib
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token COMPLETE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s
// Perform the same completion again, this time using the code completion cache that implicitly gets added to swift-ide-test
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token COMPLETE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s
func test() -> MyProto {
return #^COMPLETE^#
}
// CHECK: Begin completions
// CHECK-DAG: Decl[Struct]/OtherModule[Lib]/TypeRelation[Convertible]: Foo[#Foo#];
// CHECK-DAG: Decl[GlobalVar]/OtherModule[Lib]/TypeRelation[Convertible]: GLOBAL_FOO[#Foo#];
// CHECK-DAG: Decl[Struct]/OtherModule[Lib]: Bar[#Bar#];
// CHECK-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]/TypeRelation[Convertible]: MyProto[#MyProto#];
// CHECK-DAG: Decl[FreeFunction]/OtherModule[Lib]/TypeRelation[Convertible]: makeFoo()[#Foo#];
// CHECK-DAG: Decl[FreeFunction]/OtherModule[Lib]/TypeRelation[Convertible]: returnSomeMyProto()[#MyProto#];
// CHECK: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token COMPLETE_OPAQUE_COMPOSITION -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=COMPLETE_OPAQUE_COMPOSITION
// Perform the same completion again, this time using the code completion cache that implicitly gets added to swift-ide-test
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token COMPLETE_OPAQUE_COMPOSITION -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=COMPLETE_OPAQUE_COMPOSITION
func testOpaqueComposition() -> some MyProto & MyOtherProto {
return #^COMPLETE_OPAQUE_COMPOSITION^#
}
// COMPLETE_OPAQUE_COMPOSITION: Begin completions
// COMPLETE_OPAQUE_COMPOSITION-DAG: Decl[Struct]/OtherModule[Lib]: Foo[#Foo#];
// COMPLETE_OPAQUE_COMPOSITION-DAG: Decl[GlobalVar]/OtherModule[Lib]: GLOBAL_FOO[#Foo#];
// COMPLETE_OPAQUE_COMPOSITION-DAG: Decl[Struct]/OtherModule[Lib]: Bar[#Bar#];
// COMPLETE_OPAQUE_COMPOSITION-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]: MyProto[#MyProto#];
// COMPLETE_OPAQUE_COMPOSITION-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeFoo()[#Foo#];
// COMPLETE_OPAQUE_COMPOSITION-DAG: Decl[Struct]/OtherModule[Lib]/TypeRelation[Convertible]: FooBar[#FooBar#];
// COMPLETE_OPAQUE_COMPOSITION: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token ALSO_CONSIDER_METATYPE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=ALSO_CONSIDER_METATYPE
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token ALSO_CONSIDER_METATYPE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=ALSO_CONSIDER_METATYPE
func testAlsoConsiderMetatype() -> MyClass.Type {
return #^ALSO_CONSIDER_METATYPE^#
}
// ALSO_CONSIDER_METATYPE: Begin completions
// ALSO_CONSIDER_METATYPE-DAG: Decl[Class]/OtherModule[Lib]/TypeRelation[Convertible]: MyClass[#MyClass#];
// FIXME: MySubclass should be 'Convertible' but we don't currently store metatype supertypes in USRBasedType.
// ALSO_CONSIDER_METATYPE-DAG: Decl[Class]/OtherModule[Lib]: MySubclass[#MySubclass#];
// ALSO_CONSIDER_METATYPE: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token OPAQUE_WITH_CLASS -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=OPAQUE_WITH_CLASS
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token OPAQUE_WITH_CLASS -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=OPAQUE_WITH_CLASS
func testOpaqueWithClass<T: MyClass & MyProto>() -> T {
return #^OPAQUE_WITH_CLASS^#
}
// FIXME: We don't support USR-based type comparison in generic contexts. MySubclassConformingToMyProto should be 'Convertible'
// OPAQUE_WITH_CLASS: Begin completions
// OPAQUE_WITH_CLASS-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeMySubclass()[#MySubclass#];
// OPAQUE_WITH_CLASS-DAG: Decl[Class]/OtherModule[Lib]: MySubclass[#MySubclass#];
// OPAQUE_WITH_CLASS-DAG: Decl[Class]/OtherModule[Lib]: MySubclassConformingToMyProto[#MySubclassConformingToMyProto#];
// OPAQUE_WITH_CLASS-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeMyClass()[#MyClass#];
// OPAQUE_WITH_CLASS-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]: MyProto[#MyProto#];
// OPAQUE_WITH_CLASS-DAG: Decl[FreeFunction]/OtherModule[Lib]: returnSomeMyProto()[#MyProto#];
// OPAQUE_WITH_CLASS: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token GENERIC_RETURN -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=GENERIC_RETURN
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token GENERIC_RETURN -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=GENERIC_RETURN
func testGenericReturn<T: MyProto>() -> T {
return #^GENERIC_RETURN^#
}
// FIXME: We don't support USR-based type comparison in generic contexts. MyProto, returnMyProto, makeFoo and FooBar should be 'Convertible'
// GENERIC_RETURN: Begin completions
// GENERIC_RETURN-DAG: Decl[Struct]/OtherModule[Lib]: Foo[#Foo#];
// GENERIC_RETURN-DAG: Decl[GlobalVar]/OtherModule[Lib]: GLOBAL_FOO[#Foo#];
// GENERIC_RETURN-DAG: Decl[Struct]/OtherModule[Lib]: Bar[#Bar#];
// GENERIC_RETURN-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]: MyProto[#MyProto#];
// GENERIC_RETURN-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeFoo()[#Foo#];
// GENERIC_RETURN-DAG: Decl[Struct]/OtherModule[Lib]: FooBar[#FooBar#];
// GENERIC_RETURN-DAG: Decl[FreeFunction]/OtherModule[Lib]: returnSomeMyProto()[#MyProto#];
// GENERIC_RETURN: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token OPAQUE_CLASS_AND_PROTOCOL -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=OPAQUE_CLASS_AND_PROTOCOL
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token OPAQUE_CLASS_AND_PROTOCOL -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=OPAQUE_CLASS_AND_PROTOCOL
func testGenericReturn() -> some MyClass & MyProto {
return #^OPAQUE_CLASS_AND_PROTOCOL^#
}
// OPAQUE_CLASS_AND_PROTOCOL: Begin completions
// OPAQUE_CLASS_AND_PROTOCOL-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeMySubclass()[#MySubclass#];
// OPAQUE_CLASS_AND_PROTOCOL-DAG: Decl[Class]/OtherModule[Lib]: MySubclass[#MySubclass#];
// OPAQUE_CLASS_AND_PROTOCOL-DAG: Decl[Class]/OtherModule[Lib]/TypeRelation[Convertible]: MySubclassConformingToMyProto[#MySubclassConformingToMyProto#];
// OPAQUE_CLASS_AND_PROTOCOL-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeMyClass()[#MyClass#];
// OPAQUE_CLASS_AND_PROTOCOL-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]: MyProto[#MyProto#];
// OPAQUE_CLASS_AND_PROTOCOL-DAG: Decl[FreeFunction]/OtherModule[Lib]: returnSomeMyProto()[#MyProto#];
// OPAQUE_CLASS_AND_PROTOCOL: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token TRANSITIVE_CONFORMANCE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=TRANSITIVE_CONFORMANCE
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token TRANSITIVE_CONFORMANCE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=TRANSITIVE_CONFORMANCE
func testGenericReturn() -> MyBaseProto {
return #^TRANSITIVE_CONFORMANCE^#
}
// TRANSITIVE_CONFORMANCE: Begin completions
// TRANSITIVE_CONFORMANCE-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]: MyOtherProto[#MyOtherProto#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Class]/OtherModule[Lib]: MyClass[#MyClass#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[FreeFunction]/OtherModule[Lib]/TypeRelation[Convertible]: makeFoo()[#Foo#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Struct]/OtherModule[Lib]/TypeRelation[Convertible]: Foo[#Foo#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[FreeFunction]/OtherModule[Lib]/TypeRelation[Convertible]: returnSomeMyProto()[#MyProto#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[GlobalVar]/OtherModule[Lib]/TypeRelation[Convertible]: GLOBAL_FOO[#Foo#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]/TypeRelation[Convertible]: MyBaseProto[#MyBaseProto#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Struct]/OtherModule[Lib]: Bar[#Bar#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Class]/OtherModule[Lib]/TypeRelation[Convertible]: MySubclassConformingToMyProto[#MySubclassConformingToMyProto#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Struct]/OtherModule[Lib]/TypeRelation[Convertible]: FooBar[#FooBar#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeMyClass()[#MyClass#];
// TRANSITIVE_CONFORMANCE-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]/TypeRelation[Convertible]: MyProto[#MyProto#];
// TRANSITIVE_CONFORMANCE: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROTO_WITH_ASSOC_TYPE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROTO_WITH_ASSOC_TYPE
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROTO_WITH_ASSOC_TYPE -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROTO_WITH_ASSOC_TYPE
func protoWithAssocType() -> ProtoWithAssocType {
return #^PROTO_WITH_ASSOC_TYPE^#
}
// PROTO_WITH_ASSOC_TYPE: Begin completions
// PROTO_WITH_ASSOC_TYPE-DAG: Decl[Struct]/OtherModule[Lib]/TypeRelation[Convertible]: StructWithAssocType[#StructWithAssocType#];
// PROTO_WITH_ASSOC_TYPE-DAG: Decl[FreeFunction]/OtherModule[Lib]/TypeRelation[Convertible]: makeProtoWithAssocType()[#ProtoWithAssocType#];
// PROTO_WITH_ASSOC_TYPE-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]/TypeRelation[Convertible]: ProtoWithAssocType[#ProtoWithAssocType#];
// PROTO_WITH_ASSOC_TYPE: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROTO_WITH_ASSOC_TYPE_OPAQUE_CONTEXT -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROTO_WITH_ASSOC_TYPE
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROTO_WITH_ASSOC_TYPE_OPAQUE_CONTEXT -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROTO_WITH_ASSOC_TYPE
func protoWithAssocTypeInOpaqueContext() -> some ProtoWithAssocType {
return #^PROTO_WITH_ASSOC_TYPE_OPAQUE_CONTEXT^#
}
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT
func protoWithAssocTypeInGenericContext<T: ProtoWithAssocType>() -> T {
return #^PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT^#
}
// PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT: Begin completions
// PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT-DAG: Decl[Struct]/OtherModule[Lib]: StructWithAssocType[#StructWithAssocType#];
// PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT-DAG: Decl[FreeFunction]/OtherModule[Lib]: makeProtoWithAssocType()[#ProtoWithAssocType#];
// PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT-DAG: Decl[Protocol]/OtherModule[Lib]/Flair[RareType]: ProtoWithAssocType[#ProtoWithAssocType#];
// PROTO_WITH_ASSOC_TYPE_GENERIC_RETURN_CONTEXT: End completions
// RUN: %empty-directory(%t/completion-cache)
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROPERTY_WRAPPER -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROPERTY_WRAPPER
// Perform the same completion again, this time using the code completion cache
// RUN: %target-swift-ide-test -code-completion -source-filename %t/test.swift -code-completion-token PROPERTY_WRAPPER -completion-cache-path %t/completion-cache -I %t/ImportPath | %FileCheck %s --check-prefix=PROPERTY_WRAPPER
struct TestPropertyWrapper {
@#^PROPERTY_WRAPPER^# var foo: String
}
// PROPERTY_WRAPPER: Begin completions
// PROPERTY_WRAPPER-DAG: Decl[Struct]/OtherModule[Lib]/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#];
// PROPERTY_WRAPPER-DAG: Decl[Struct]/OtherModule[Lib]: StructWithAssocType[#StructWithAssocType#];
// PROPERTY_WRAPPER: End completions
| 65.623967 | 282 | 0.784459 |
0a0fd41f11ab7c9f0ccad076ab567c00d479f4fd | 1,330 | //
// AHNetworkResponseAdapter.swift
// Pods
//
// Created by Alex Hmelevski on 2017-06-05.
//
//
import Foundation
import ALEither
protocol INetworkResponseAdapter {
func response(from data: Data?, with response: URLResponse?, and error: Error?) -> ALEither<AHNetworkResponse,Error>
}
protocol INetworkDownloadAdapter {
func response(from url: URL?, with response: URLResponse?, and error: Error?) -> ALEither<AHNetworkResponse,Error>
}
struct AHNetworkResponseAdapter: INetworkResponseAdapter, INetworkDownloadAdapter {
func response(from data: Data?, with response: URLResponse?, and error: Error?) -> ALEither<AHNetworkResponse, Error> {
let resp = AHNetworkResponse.init(data: data, response: response)
guard let result = ALEither(value: resp, error: error) else {
fatalError("Cannont create ALEither")
}
return result
}
func response(from url: URL?, with response: URLResponse?, and error: Error?) -> ALEither<AHNetworkResponse, Error> {
let data = url?.absoluteString.data(using: .utf8)
let resp = AHNetworkResponse.init(data: data, response: response)
guard let result = ALEither(value: resp, error: error) else {
fatalError("Cannont create ALEither")
}
return result
}
}
| 34.102564 | 123 | 0.681203 |
1ecf4c9a80843f00df5400dec49592865094a6ca | 1,566 | //
// Neumorphic.swift
// Created by Costa Chung on 2/3/2020.
// Copyright © 2020 Costa Chung. All rights reserved.
// Neumorphism Soft UI
import SwiftUI
public struct NeumorphicKit {
public enum ColorSchemeType {
case auto, light, dark
}
public static var colorSchemeType : ColorSchemeType = .auto
#if os(macOS)
public typealias ColorType = NSColor
public static func colorType(red: CGFloat, green: CGFloat, blue: CGFloat) -> ColorType {
.init(red: red, green: green, blue: blue, alpha: 1.0)
}
#else
public typealias ColorType = UIColor
public static func colorType(red: CGFloat, green: CGFloat, blue: CGFloat) -> ColorType {
.init(red: red, green: green, blue: blue, alpha: 1.0)
}
#endif
public static func color(light: ColorType, dark: ColorType) -> Color {
#if os(macOS)
switch NeumorphicKit.colorSchemeType {
case .light:
return Color(light)
case .dark:
return Color(dark)
case .auto:
return Color(.init(name: nil, dynamicProvider: { (appearance) -> NSColor in
return appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light
}))
}
#else
switch NeumorphicKit.colorSchemeType {
case .light:
return Color(light)
case .dark:
return Color(dark)
case .auto:
return Color(.init { $0.userInterfaceStyle == .light ? light : dark })
}
#endif
}
}
| 27 | 97 | 0.590677 |
7a92dca853834059e9e2eff69c0aec4e9a9506ed | 3,040 | //
// GetMessageDeliverList.swift
// FanapPodChatSDK
//
// Created by Mahyar Zhiani on 3/18/1398 AP.
// Copyright © 1398 Mahyar Zhiani. All rights reserved.
//
import Foundation
import SwiftyJSON
import SwiftyBeaver
import FanapPodAsyncSDK
extension Chat {
func responseOfMessageDeliveryList(withMessage message: ChatMessage) {
log.verbose("Message of type 'GET_MESSAGE_DELEVERY_PARTICIPANTS' recieved", context: "Chat")
let returnData = CreateReturnData(hasError: false,
errorMessage: "",
errorCode: 0,
result: nil,
resultAsArray: message.content?.convertToJSON().array,
resultAsString: nil,
contentCount: message.contentCount,
subjectId: message.subjectId)
if Chat.map[message.uniqueId] != nil {
let callback: CallbackProtocol = Chat.map[message.uniqueId]!
callback.onResultCallback(uID: message.uniqueId,
response: returnData,
success: { (successJSON) in
self.getMessageDeliverListCallbackToUser?(successJSON)
}) { _ in }
Chat.map.removeValue(forKey: message.uniqueId)
}
}
public class GetMessageDeliverList: CallbackProtocol {
var sendParams: SendChatMessageVO
init(parameters: SendChatMessageVO) {
self.sendParams = parameters
}
func onResultCallback(uID: String,
response: CreateReturnData,
success: @escaping callbackTypeAlias,
failure: @escaping callbackTypeAlias) {
log.verbose("GetMessageDeliverListCallback", context: "Chat")
if let arrayContent = response.resultAsArray as? [JSON] {
let content = sendParams.content?.convertToJSON()
let getBlockedModel = GetThreadParticipantsModel(messageContent: arrayContent,
contentCount: response.contentCount,
count: content?["count"].intValue ?? 0,
offset: content?["offset"].intValue ?? 0,
hasError: response.hasError,
errorMessage: response.errorMessage,
errorCode: response.errorCode)
success(getBlockedModel)
}
}
}
}
| 43.428571 | 113 | 0.467105 |
4a009fd74007bec909e8401557000f62033a97e7 | 1,540 | //
// EmeraldInputMask.swift
// EmeraldComponents
//
// Created by Luan Kalume | Stone on 15/06/2018.
// Copyright © 2018 StoneCo. All rights reserved.
//
import Foundation
/// An enum representing the possible masks for EmeraldInput basic component.
public enum EmeraldInputMask {
case none
case email
case phone
case cep
case cpf
case cnpj
case password
case currency
case custom(mask: String)
public static func getMaskFormat(for mask: EmeraldInputMask) -> String {
let maskFormat: String
switch mask {
case .cnpj: maskFormat = "[00].[000].[000]/[0000]-[00]"
case .cpf: maskFormat = "[000].[000].[000]-[00]"
case .cep: maskFormat = "[00000]-[000]"
case .phone: maskFormat = "([00]) [0000]-[00009]"
case .custom(let mask): maskFormat = mask
default: maskFormat = "[…]"
}
return maskFormat
}
}
extension EmeraldInputMask: Equatable {
public static func == (lhs: EmeraldInputMask, rhs: EmeraldInputMask) -> Bool {
switch (lhs, rhs) {
case (.none, .none),
(.email, .email),
(.phone, .phone),
(.cep, .cep),
(.cpf, .cpf),
(.cnpj, .cnpj),
(.currency, .currency),
(.password, .password):
return true
case (.custom(let value1), .custom(let value2)):
return value1 == value2
default:
return false
}
}
}
| 25.245902 | 82 | 0.545455 |
28601d19bcb5c424c100544c40c8a3ca56c0deaa | 11,443 | //
// SettingsEditorViewController.swift
// FSNotes iOS
//
// Created by Олександр Глущенко on 07.08.2020.
// Copyright © 2020 Oleksandr Glushchenko. All rights reserved.
//
import UIKit
import NightNight
class SettingsEditorViewController: UITableViewController {
private var noteTableUpdater = Timer()
private var sections = [
NSLocalizedString("Settings", comment: ""),
NSLocalizedString("View", comment: ""),
NSLocalizedString("Line Spacing", comment: "Settings"),
NSLocalizedString("Font", comment: ""),
NSLocalizedString("Code", comment: "")
]
private var rowsInSection = [2, 2, 1, 3, 2]
private var counter = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
private var rows = [
[
NSLocalizedString("Autocorrection", comment: "Settings"),
NSLocalizedString("Spell Checking", comment: "Settings"),
],
[
NSLocalizedString("Code block live highlighting", comment: "Settings"),
NSLocalizedString("Live images preview", comment: "Settings"),
],
[""],
[
NSLocalizedString("Family", comment: "Settings"),
NSLocalizedString("Dynamic Type", comment: "Settings"),
NSLocalizedString("Font size", comment: "Settings")
],
[
NSLocalizedString("Font", comment: "Settings"),
NSLocalizedString("Theme", comment: "Settings"),
]
]
override func viewDidLoad() {
view.mixedBackgroundColor = MixedColor(normal: 0xffffff, night: 0x000000)
navigationItem.leftBarButtonItem = Buttons.getBack(target: self, selector: #selector(cancel))
title = NSLocalizedString("Editor", comment: "Settings")
super.viewDidLoad()
}
@objc func cancel() {
self.navigationController?.popViewController(animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowsInSection[section]
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.mixedBackgroundColor = MixedColor(normal: 0xffffff, night: 0x000000)
cell.textLabel?.mixedTextColor = MixedColor(normal: 0x000000, night: 0xffffff)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 3 && indexPath.row == 0 {
let controller = FontViewController()
self.navigationController?.pushViewController(controller, animated: true)
}
if indexPath.section == 4 && indexPath.row == 0 {
let controller = CodeFontViewController()
self.navigationController?.pushViewController(controller, animated: true)
}
if indexPath.section == 4 && indexPath.row == 1 {
let controller = CodeThemeViewController()
self.navigationController?.pushViewController(controller, animated: true)
}
tableView.deselectRow(at: indexPath, animated: false)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let uiSwitch = UISwitch()
uiSwitch.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
let cell = UITableViewCell()
cell.textLabel?.text = rows[indexPath.section][indexPath.row]
let view = UIView()
view.mixedBackgroundColor = MixedColor(normal: 0xe2e5e4, night: 0x686372)
cell.selectedBackgroundView = view
if indexPath.section == 0 {
switch indexPath.row {
case 0:
cell.accessoryView = uiSwitch
uiSwitch.isOn = UserDefaultsManagement.editorAutocorrection
case 1:
cell.accessoryView = uiSwitch
uiSwitch.isOn = UserDefaultsManagement.editorSpellChecking
default:
return cell
}
}
if indexPath.section == 1 {
switch indexPath.row {
case 0:
cell.accessoryView = uiSwitch
uiSwitch.isOn = UserDefaultsManagement.codeBlockHighlight
case 1:
cell.accessoryView = uiSwitch
uiSwitch.isOn = UserDefaultsManagement.liveImagesPreview
default:
return cell
}
}
if indexPath.section == 2 {
let brightness = UserDefaultsManagement.editorLineSpacing
let slider = UISlider(frame: CGRect(x: 10, y: 3, width: tableView.frame.width - 20, height: 40))
slider.minimumValue = 0
slider.maximumValue = 25
slider.addTarget(self, action: #selector(didChangeLineSpacingSlider), for: .touchUpInside)
slider.setValue(brightness, animated: true)
cell.addSubview(slider)
}
if indexPath.section == 3 {
switch indexPath.row {
case 0:
cell.accessoryType = .disclosureIndicator
case 1:
cell.accessoryView = uiSwitch
uiSwitch.isOn = UserDefaultsManagement.dynamicTypeFont
case 2:
if UserDefaultsManagement.dynamicTypeFont {
cell.isHidden = true
return cell
}
let stepper = UIStepper(frame: CGRect(x: 20, y: 20, width: 100, height: 20))
stepper.stepValue = 1
stepper.minimumValue = 10
stepper.maximumValue = 40
stepper.value = Double(UserDefaultsManagement.fontSize)
stepper.translatesAutoresizingMaskIntoConstraints = false
stepper.addTarget(self, action: #selector(fontSizeChanged), for: .valueChanged)
let label = UILabel()
label.text = ""
label.translatesAutoresizingMaskIntoConstraints = false
counter.text = String(Double(UserDefaultsManagement.fontSize))
counter.mixedTextColor = MixedColor(normal: UIColor.gray, night: UIColor.white)
counter.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(label)
cell.contentView.addSubview(counter)
cell.contentView.addSubview(stepper)
cell.selectionStyle = .none
cell.accessoryType = .none
let views = ["name" : label, "counter": counter, "stepper" : stepper] as [String : Any]
cell.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[name]-[counter(40)]-15-[stepper(100)]-20-|", options: NSLayoutConstraint.FormatOptions.alignAllCenterY, metrics: nil, views: views))
cell.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[name(stepper)]-10-|", options: [], metrics: nil, views: views))
default:
return cell
}
}
if indexPath.section == 4 {
switch indexPath.row {
case 0:
cell.accessoryType = .disclosureIndicator
break
case 1:
cell.accessoryType = .disclosureIndicator
break
default:
break
}
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath.section == 3 && indexPath.row == 2 && UserDefaultsManagement.dynamicTypeFont) {
return 0
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
@objc public func switchValueDidChange(_ sender: UISwitch) {
guard let cell = sender.superview as? UITableViewCell,
let tableView = cell.superview as? UITableView,
let indexPath = tableView.indexPath(for: cell) else { return }
if indexPath.section == 0 {
switch indexPath.row {
case 0:
guard let uiSwitch = cell.accessoryView as? UISwitch else { return }
UserDefaultsManagement.editorAutocorrection = uiSwitch.isOn
UIApplication.getEVC().editArea.autocorrectionType = UserDefaultsManagement.editorAutocorrection ? .yes : .no
case 1:
guard let uiSwitch = cell.accessoryView as? UISwitch else { return }
UserDefaultsManagement.editorSpellChecking = uiSwitch.isOn
UIApplication.getEVC().editArea.spellCheckingType = UserDefaultsManagement.editorSpellChecking ? .yes : .no
default:
return
}
}
if indexPath.section == 1 {
switch indexPath.row {
case 1:
guard let uiSwitch = cell.accessoryView as? UISwitch else { return }
UserDefaultsManagement.codeBlockHighlight = uiSwitch.isOn
case 2:
guard let uiSwitch = cell.accessoryView as? UISwitch else { return }
UserDefaultsManagement.liveImagesPreview = uiSwitch.isOn
default:
return
}
}
if indexPath.section == 2 {
return
}
if indexPath.section == 3 {
switch indexPath.row {
case 0:
return
case 1:
guard let uiSwitch = cell.accessoryView as? UISwitch else { return }
UserDefaultsManagement.dynamicTypeFont = uiSwitch.isOn
if uiSwitch.isOn {
UserDefaultsManagement.fontSize = 17
}
if let dynamicCell = tableView.cellForRow(at: IndexPath(row: 2, section: 3)) {
dynamicCell.isHidden = uiSwitch.isOn
}
tableView.reloadRows(at: [IndexPath(row: 2, section: 3)], with: .automatic)
noteTableUpdater.invalidate()
noteTableUpdater = Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(self.reloadNotesTable), userInfo: nil, repeats: false)
return
case 2:
return
default:
return
}
}
}
@IBAction func fontSizeChanged(stepper: UIStepper) {
UserDefaultsManagement.fontSize = Int(stepper.value)
counter.text = String(stepper.value)
noteTableUpdater.invalidate()
noteTableUpdater = Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(self.reloadNotesTable), userInfo: nil, repeats: false)
}
@IBAction func reloadNotesTable() {
UIApplication.getVC().notesTable.reloadData()
}
@objc func didChangeLineSpacingSlider(sender: UISlider) {
MPreviewView.template = nil
UserDefaultsManagement.editorLineSpacing = sender.value
}
}
| 37.641447 | 239 | 0.602552 |
c1df937bc8500c0a76d7901f6a1aef3e34a7569f | 8,550 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import Cocoa
// FIXME: trackPage has been hidden in MSAnalytics temporarily. Use internal until the feature comes back.
class AnalyticsViewController : NSViewController, NSTableViewDataSource, NSTableViewDelegate {
class EventProperty : NSObject {
@objc var key: String = ""
@objc var type: String = EventPropertyType.string.rawValue
@objc var string: String = ""
@objc var double: NSNumber = 0
@objc var long: NSNumber = 0
@objc var boolean: Bool = false
@objc var dateTime: Date = Date.init()
}
enum EventPropertyType : String {
case string = "String"
case double = "Double"
case long = "Long"
case boolean = "Boolean"
case dateTime = "DateTime"
static let allValues = [string, double, long, boolean, dateTime]
}
enum Priority: String {
case defaultType = "Default"
case normal = "Normal"
case critical = "Critical"
case invalid = "Invalid"
var flags: MSFlags {
switch self {
case .normal:
return [.normal]
case .critical:
return [.critical]
case .invalid:
return MSFlags.init(rawValue: 42)
default:
return []
}
}
static let allValues = [defaultType, normal, critical, invalid]
}
var appCenter: AppCenterDelegate = AppCenterProvider.shared().appCenter!
@IBOutlet weak var name: NSTextField!
@IBOutlet var setEnabledButton : NSButton?
@IBOutlet var table : NSTableView?
@IBOutlet weak var pause: NSButton!
@IBOutlet weak var resume: NSButton!
@IBOutlet weak var priorityValue: NSComboBox!
@IBOutlet weak var countLabel: NSTextField!
@IBOutlet weak var countSlider: NSSlider!
@IBOutlet var arrayController: NSArrayController!
private var textBeforeEditing : String = ""
private var totalPropsCounter : Int = 0
private var priority = Priority.defaultType
@objc dynamic var eventProperties = [EventProperty]()
override func viewDidLoad() {
super.viewDidLoad()
setEnabledButton?.state = appCenter.isAnalyticsEnabled() ? .on : .off
table?.delegate = self
self.countLabel.stringValue = "Count: \(Int(countSlider.intValue))"
}
override func viewWillAppear() {
setEnabledButton?.state = appCenter.isAnalyticsEnabled() ? .on : .off
}
override func viewDidDisappear() {
super.viewDidDisappear()
NotificationCenter.default.removeObserver(self)
}
@IBAction func trackEvent(_ : AnyObject) {
let eventProperties = eventPropertiesSet()
let eventName = name.stringValue
for _ in 0..<Int(countSlider.intValue) {
if let properties = eventProperties as? MSEventProperties {
if priority != .defaultType {
appCenter.trackEvent(eventName, withTypedProperties: properties, flags: priority.flags)
} else {
appCenter.trackEvent(eventName, withTypedProperties: properties)
}
} else if let dictionary = eventProperties as? [String: String] {
if priority != .defaultType {
appCenter.trackEvent(eventName, withProperties: dictionary, flags: priority.flags)
} else {
appCenter.trackEvent(eventName, withProperties: dictionary)
}
} else {
if priority != .defaultType {
appCenter.trackEvent(eventName, withTypedProperties: nil, flags: priority.flags)
} else {
appCenter.trackEvent(eventName)
}
}
for targetToken in TransmissionTargets.shared.transmissionTargets.keys {
if TransmissionTargets.shared.targetShouldSendAnalyticsEvents(targetToken: targetToken) {
let target = TransmissionTargets.shared.transmissionTargets[targetToken]!
if let properties = eventProperties as? MSEventProperties {
if priority != .defaultType {
target.trackEvent(eventName, withProperties: properties, flags: priority.flags)
} else {
target.trackEvent(eventName, withProperties: properties)
}
} else if let dictionary = eventProperties as? [String: String] {
if priority != .defaultType {
target.trackEvent(eventName, withProperties: dictionary, flags: priority.flags)
} else {
target.trackEvent(eventName, withProperties: dictionary)
}
} else {
if priority != .defaultType {
target.trackEvent(eventName, withProperties: [:], flags: priority.flags)
} else {
target.trackEvent(eventName)
}
}
}
}
}
}
@IBAction func resume(_ sender: NSButton) {
appCenter.resume()
}
@IBAction func pause(_ sender: NSButton) {
appCenter.pause()
}
@IBAction func countChanged(_ sender: Any) {
self.countLabel.stringValue = "Count: \(Int(countSlider.intValue))"
}
@IBAction func priorityChanged(_ sender: NSComboBox) {
self.priority = Priority(rawValue: self.priorityValue.stringValue)!
}
@IBAction func trackPage(_ : AnyObject) {
NSLog("trackPageWithProperties: %d", eventProperties.count)
}
@IBAction func addProperty(_ : AnyObject) {
let property = EventProperty()
let eventProperties = arrayController.content as! [EventProperty]
let count = eventProperties.count
property.key = "key\(count)"
property.string = "value\(count)"
property.addObserver(self, forKeyPath: #keyPath(EventProperty.type), options: .new, context: nil)
arrayController.addObject(property)
}
@IBAction func deleteProperty(_ : AnyObject) {
if let selectedProperty = arrayController.selectedObjects.first as? EventProperty {
arrayController.removeObject(selectedProperty)
selectedProperty.removeObserver(self, forKeyPath: #keyPath(EventProperty.type), context: nil)
}
}
@IBAction func setEnabled(sender : NSButton) {
appCenter.setAnalyticsEnabled(sender.state == .on)
sender.state = appCenter.isAnalyticsEnabled() ? .on : .off
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let identifier = tableColumn?.identifier else {
return nil
}
let view = tableView.makeView(withIdentifier: identifier, owner: self)
if (identifier.rawValue == "value") {
updateValue(property: eventProperties[row], cell: view as! NSTableCellView)
}
return view
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let property = object as? EventProperty else {
return
}
guard let row = eventProperties.index(of: property) else {
return
}
let column = table?.column(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "value"))
guard let cell = table?.view(atColumn: column!, row: row, makeIfNecessary: false) as? NSTableCellView else {
return
}
updateValue(property: property, cell: cell)
}
func updateValue(property: EventProperty, cell: NSTableCellView) {
cell.isHidden = false
for subview in cell.subviews {
subview.isHidden = true
}
guard let type = EventPropertyType(rawValue: property.type) else {
return
}
if let view = cell.viewWithTag(EventPropertyType.allValues.index(of: type)!) {
view.isHidden = false
} else {
cell.isHidden = true
}
}
func eventPropertiesSet() -> Any? {
if eventProperties.count < 1 {
return nil
}
var onlyStrings = true
var propertyDictionary = [String: String]()
let properties = MSEventProperties()
for property in eventProperties {
let key = property.key
guard let type = EventPropertyType(rawValue: property.type) else {
continue
}
switch type {
case .string:
properties.setEventProperty(property.string, forKey: key);
propertyDictionary[property.key] = property.string
case .double:
properties.setEventProperty(property.double.doubleValue, forKey: key)
onlyStrings = false
case .long:
properties.setEventProperty(property.long.int64Value, forKey: key)
onlyStrings = false
case .boolean:
properties.setEventProperty(property.boolean, forKey: key)
onlyStrings = false
case .dateTime:
properties.setEventProperty(property.dateTime, forKey: key)
onlyStrings = false
}
}
return onlyStrings ? propertyDictionary : properties
}
}
| 34.337349 | 149 | 0.673333 |
b9f1b3628c4ed38b803918b5b91b60886b459c67 | 815 | //
// AppDelegate.swift
// GitHubPublicSwiftRepos
//
// Created by Mena Yousif on 10/29/19.
// Copyright © 2019 Mena Soft. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
| 29.107143 | 115 | 0.704294 |
7157729c802b9019bcb1c0f626d7bc69b7931332 | 1,716 | #if os(macOS)
import XCTest
import ApolloTestSupport
import ApolloCodegenTestSupport
@testable import ApolloCodegenLib
class StarWarsApolloSchemaDownloaderTests: XCTestCase {
func testDownloadingSchema_usingIntrospection_shouldOutputSDL() throws {
let testOutputFolderURL = CodegenTestHelper.outputFolderURL()
let configuration = ApolloSchemaDownloadConfiguration(using: .introspection(endpointURL: TestServerURL.starWarsServer.url),
outputFolderURL: testOutputFolderURL)
// Delete anything existing at the output URL
try FileManager.default.apollo.deleteFile(at: configuration.outputURL)
XCTAssertFalse(FileManager.default.apollo.fileExists(at: configuration.outputURL))
try ApolloSchemaDownloader.fetch(with: configuration)
// Does the file now exist?
XCTAssertTrue(FileManager.default.apollo.fileExists(at: configuration.outputURL))
// Is it non-empty?
let data = try Data(contentsOf: configuration.outputURL)
XCTAssertFalse(data.isEmpty)
// It should not be JSON
XCTAssertNil(try? JSONSerialization.jsonObject(with: data, options: []) as? [AnyHashable:Any])
// Can it be turned into the expected schema?
let frontend = try ApolloCodegenFrontend()
let source = try frontend.makeSource(from: configuration.outputURL)
let schema = try frontend.loadSchemaFromSDL(source)
let episodeType = try schema.getType(named: "Episode")
XCTAssertEqual(episodeType?.name, "Episode")
// OK delete it now
try FileManager.default.apollo.deleteFile(at: configuration.outputURL)
XCTAssertFalse(FileManager.default.apollo.fileExists(at: configuration.outputURL))
}
}
#endif
| 39 | 127 | 0.752914 |
162891451e6fdc59b36b2b69802ee23c4dc701e7 | 75 | import PackageDescription
let package = Package(
name: "PlayAlways"
)
| 12.5 | 25 | 0.733333 |
232f2e8a98931b337e614566a052c97fd1548073 | 1,436 | import XCTest
@testable import GoldenRetriever
final class EndpointTests: XCTestCase {
func testOneEmptyParameter() {
let endpoint = TestEndpoint.tickets(param1: nil, param2: "singleparam")
guard let url = endpoint.url, let queryItems = URLComponents(string: url.absoluteString)?.queryItems else {
XCTAssert(false, "URL construction failed")
return
}
XCTAssertEqual(queryItems.count, 2, "Wrong number of URL queries")
XCTAssertTrue(queryItems.contains(URLQueryItem(name: "param1", value: "")))
XCTAssertTrue(queryItems.contains(URLQueryItem(name: "param2", value: "singleparam")))
}
func testTwoParameters() {
let endpoint = TestEndpoint.tickets(param1: "testparam", param2: "string with spaces")
guard let url = endpoint.url, let queryItems = URLComponents(string: url.absoluteString)?.queryItems else {
XCTAssert(false, "URL construction failed")
return
}
XCTAssertEqual(queryItems.count, 2, "Wrong number of URL queries")
XCTAssertTrue(queryItems.contains(URLQueryItem(name: "param1", value: "testparam")))
XCTAssertTrue(queryItems.contains(URLQueryItem(name: "param2", value: "string with spaces")))
}
static var allTests = [
("testOneEmptyParameter", testOneEmptyParameter),
("testTwoParameters", testTwoParameters),
]
}
| 41.028571 | 115 | 0.669916 |
75d8c3cd797bc1b49a9e251d0c473d2453e90f09 | 332 | //
// ISOPaddingFormat.swift
// ISO8583
//
// Created by Evgeny Seliverstov on 01/12/2020.
//
import Foundation
public enum ISOPaddingFormat {
/// Left padding (e.g. left padded value of `123` is `[0x01, 0x12]`)
case left
/// Right padding (e.g. right padded value of `123` is `[0x12, 0x30]`)
case right
}
| 19.529412 | 74 | 0.635542 |
484c4d6b4a402ee0121b9d08f382a6c987b2a05e | 670 | //
// SpriteKitTests.swift
// SwifterSwift
//
// Created by Olivia Brown on 5/28/18.
// Copyright © 2018 SwifterSwift
//
import XCTest
@testable import SwifterSwift
#if canImport(SpriteKit)
import SpriteKit
@testable import SwifterSwift
final class SpriteKitTests: XCTestCase {
func testDescendants() {
let scene = SKScene()
let childOne = SKNode()
scene.addChild(childOne)
let childTwo = SKNode()
childOne.addChild(childTwo)
XCTAssertEqual(scene.descendants(), [childOne, childTwo])
XCTAssertEqual(childOne.descendants(), [childTwo])
XCTAssertEqual(childTwo.descendants(), [])
}
}
#endif
| 21.612903 | 65 | 0.677612 |
7a2e60d1b641d0e28154d62e402a436615909848 | 3,229 | //
// UserLoginViewController.swift
// Diurna
//
// Created by Nicolas Gaulard-Querol on 29/07/2020.
// Copyright © 2020 Nicolas Gaulard-Querol. All rights reserved.
//
import AppKit
import HackerNewsAPI
import OSLog
// MARK: - UserLoginViewControllerDelegate
@objc protocol UserLoginViewControllerDelegate: class {
func userDidLogin(with user: String)
func userDidCancelLogin()
}
// MARK: - UserLoginViewController
class UserLoginViewController: NSViewController {
// MARK: Outlets
@IBOutlet weak var userNameTextField: NSTextField! {
didSet {
userNameTextField.delegate = self
}
}
@IBOutlet weak var userPasswordTextField: NSSecureTextField! {
didSet {
userPasswordTextField.delegate = self
}
}
@IBOutlet weak var cancelButton: NSButton! {
didSet {
cancelButton.action = #selector(self.cancel(_:))
}
}
@IBOutlet weak var loginButton: NSButton! {
didSet {
loginButton.isEnabled = false
loginButton.action = #selector(self.login(_:))
}
}
// MARK: Properties
weak var delegate: UserLoginViewControllerDelegate?
var progressOverlayView: NSView?
// MARK: Methods
@objc private func login(_ sender: Any?) {
showProgressOverlay(
with: "Logging in as \"\(userNameTextField.stringValue)\"…"
)
webClient.login(
withAccount: userNameTextField.stringValue,
andPassword: userPasswordTextField.stringValue
) { [weak self] loginResult in
switch loginResult {
case let .success(user):
self?.delegate?.userDidLogin(with: user)
case let .failure(error):
self?.handleError(error)
}
self?.hideProgressOverlay()
}
}
@objc private func cancel(_ sender: Any?) {
delegate?.userDidCancelLogin()
}
private func handleError(_ error: Error) {
os_log(
"Failed to authenticate user \"%s\": %s",
log: .webRequests,
type: .error,
userNameTextField.stringValue,
error.localizedDescription
)
NSAlert.showModal(
withTitle: "Failed to log in",
andText: """
You may need to verify your login using a captcha;
For now this is unsupported.
"""
)
}
}
// MARK: - NSNib.Name
extension NSNib.Name {
static let userLoginViewController = "UserLoginViewController"
}
// MARK: - NSTextFieldDelegate
extension UserLoginViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
func isNotBlank(_ string: String) -> Bool {
string.trimmingCharacters(in: .whitespaces).count > 0
}
let inputs = [
userNameTextField.stringValue,
userPasswordTextField.stringValue,
]
loginButton.isEnabled = inputs.allSatisfy(isNotBlank)
}
}
// MARK: - HNWebConsumer
extension UserLoginViewController: HNWebConsumer {}
// MARK: - ProgressShowing
extension UserLoginViewController: ProgressShowing {}
| 24.462121 | 71 | 0.61629 |
0321c9bb17280b5b7781192032211764fbe62a29 | 1,125 | class Solution {
func isAlienSorted(_ words: [String], _ order: String) -> Bool {
var alphabetIndexes: [Character: Int] = [:]
for i in 0..<order.count {
alphabetIndexes[order[i]] = i
}
for i in 0..<words.count-1 {
let lenFirst = words[i].count
let lenSecond = words[i + 1].count
var j = 0
var sorted = false
while j < lenFirst && j < lenSecond {
let orderFirst = alphabetIndexes[words[i][j], default: 0]
let orderSecond = alphabetIndexes[words[i + 1][j], default: 0]
if orderFirst > orderSecond {
return false
} else if orderFirst < orderSecond {
sorted = true
break
}
j += 1
}
if lenFirst > lenSecond && !sorted {
return false
}
}
return true
}
}
extension String {
subscript(index: Int) -> Character {
return self[self.index(startIndex, offsetBy: index)]
}
}
| 30.405405 | 78 | 0.470222 |
481bc9e5a5d40a9b35b1d086a084a03253011c5b | 1,682 | //
// CropperConfiguration.swift
// BannerImageCropper
//
// Created by Yulia Novikova on 2/10/22.
//
import UIKit
public typealias BannerCropperCompletion = (_ croppedImage: UIImage?, _ cropController: UIViewController) -> Void
public typealias BannerCropperDismissCompletion = (_ cropController: UIViewController) -> Void
public enum ImageAlignment {
case top
case center
case bottom
}
public struct BannerCropperCofiguration {
public var bannerHeight: CGFloat = 120
public var image: UIImage
public var displayGrid = false
public var gridColor: UIColor?
public var dimColor: UIColor?
public var cropAreaBorderColor: UIColor?
public var cropAreaBorderWidth: CGFloat?
public var closeButtonText = "Back"
public var saveButtonText = "Save"
public var saveButtonFont: UIFont = .systemFont(ofSize: 14)
public var closeButtonFont: UIFont = .systemFont(ofSize: 14)
public var saveButtonTint: UIColor = .white
public var closeButtonTint: UIColor = .white
public var saveButtonBackground: UIColor = .blue
public var closeButtonBackground: UIColor = .white
public var cropperViewBackgroundColor: UIColor = .black
public var closeButtonCornerRadius: CGFloat = 0
public var cropButtonCornerRadius: CGFloat = 0
public var cropperViewCornerRadius: CGFloat = 0
public var topBarSeparatorColor: UIColor = .separator
public var cropperImagePosition: ImageAlignment = .center
public var titleText: String?
public var titleFont: UIFont = .systemFont(ofSize: 14)
public var titleColor: UIColor = .black
public init(image: UIImage) {
self.image = image
}
}
| 32.346154 | 113 | 0.734839 |
dd0864e9d79409aa66639a419da511f9aa5a6f2c | 2,170 | //
// AppDelegate.swift
// HUD-Example
//
// Created by chuck lee on 2019/5/13.
// Copyright © 2019年 chuck. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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:.
}
}
| 46.170213 | 285 | 0.754378 |
ab64763c58a695bf20a082a0cbe25a53c572adc0 | 420 | //
// ArrayFormField.swift
// ViewKit
//
// Created by Tibor Bodecs on 2020. 04. 23..
//
/// can be used to store multiple text values
public struct ArrayFormField: FormField {
///values to store
public var values: [String]
///error message
public var error: String?
public init(values: [String] = [], error: String? = nil) {
self.values = values
self.error = error
}
}
| 20 | 62 | 0.611905 |
1ee8c91007aff562e5742e77193a8366f928df13 | 272 | //
// AuthResponse.swift
// Monchify
//
// Created by DJ perrier on 12/2/22.
//
import Foundation
struct AuthResponse: Codable {
let access_token: String
let expires_in: Int
let refresh_token: String?
let scope: String
let token_type: String
}
| 14.315789 | 38 | 0.672794 |
90b6c7a970eaf84aef7d1985d94fff5c8f8aae7c | 2,904 | //
// BotonesMainVC.swift
// demoAr
//
// Created by Vero on 06/04/2020.
// Copyright © 2020 Vero. All rights reserved.
//
import UIKit
class BotonesMainVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tabBar: UITabBar!
var options = ["Botones por defecto", "Botones outline", "Botones gris", "Botones flotantes", "Mostrar tab bar"]
var itemSelected = 0
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
title = "Acciones"
tableView.tableFooterView = UIView()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension BotonesMainVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 4 {
let cell: CellTabBar = tableView.dequeueReusableCell(withIdentifier: "CellTabBar", for: indexPath) as! CellTabBar
cell.loadData(title: options[indexPath.row])
cell.delegate = self
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellTypeButton", for: indexPath)
cell.textLabel?.text = options[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
performSegue(withIdentifier: "showBotonesPorDefecto", sender: nil)
}else if indexPath.row == 1 {
performSegue(withIdentifier: "showBotonesOutline", sender: nil)
}else if indexPath.row == 2 {
performSegue(withIdentifier: "showBotonesGrises", sender: nil)
}else if indexPath.row == 3 {
performSegue(withIdentifier: "showBotonesFlotantes", sender: nil)
}
}
}
extension BotonesMainVC: CellTabBarDelegate {
func switchChangeValue(enable: Bool) {
tabBar.isHidden = !enable
}
}
| 33 | 125 | 0.644972 |
db75ac11fadd4b873ff5880935b139393d73a22f | 1,826 | //
// Copyright © 2020 NHSX. All rights reserved.
//
import Common
import Domain
import Foundation
import UIKit
import UserNotifications
class SandboxUserNotificationsManager: UserNotificationManaging {
typealias AlertText = Sandbox.Text.UserNotification
private let host: SandboxHost
var authorizationStatus: AuthorizationStatus
init(host: SandboxHost) {
self.host = host
if let allowed = host.initialState.userNotificationsAuthorized {
authorizationStatus = allowed ? .authorized : .denied
} else {
authorizationStatus = .notDetermined
}
}
func requestAuthorization(options: AuthorizationOptions, completionHandler: @escaping (Bool, Error?) -> Void) {
let alert = UIAlertController(
title: AlertText.authorizationAlertTitle.rawValue,
message: AlertText.authorizationAlertMessage.rawValue,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: AlertText.authorizationAlertDoNotAllow.rawValue, style: .default, handler: { _ in
}))
alert.addAction(UIAlertAction(title: AlertText.authorizationAlertAllow.rawValue, style: .default, handler: { [weak self] _ in
self?.authorizationStatus = .authorized
completionHandler(true, nil)
}))
host.container?.show(alert, sender: nil)
}
func getAuthorizationStatus(completionHandler: @escaping AuthorizationStatusHandler) {
completionHandler(authorizationStatus)
}
func add(type: UserNotificationType, at: DateComponents?, withCompletionHandler completionHandler: ((Error?) -> Void)?) {}
func removePending(type: UserNotificationType) {}
func removeAllDelivered(for type: UserNotificationType) {}
}
| 34.45283 | 133 | 0.687842 |
874452f8a9cfb1c95f876a35f37903eb628e8b45 | 157 | //
// dummy.swift
// RNVideoProcessingDemo
//
// Created by Bunhouth on 3/2/20.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
| 15.7 | 51 | 0.687898 |
f7599b402b9540c43271adc7d0d401bacb4a03a5 | 4,698 | //
// AppDelegate.swift
// CuteBunnyApp
//
// Created by Monte's Pro 13" on 2/17/16.
// Copyright © 2016 MonteThakkar. All rights reserved.
//
import UIKit
import UIColor_Hex_Swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = UITabBarController()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
setupTabBars()
return true
}
func setupTabBars() {
// Set up the Home (cute bunny) View Controller
let homeNavigationController = storyboard.instantiateViewControllerWithIdentifier("HomeNavigationController") as! UINavigationController
let homeViewController = homeNavigationController.topViewController as! ViewController
homeViewController.isTrending = false
homeViewController.tabBarItem.title = "Home"
//Customize Home navigation bar UI
homeNavigationController.navigationBar.barTintColor = UIColor.blackColor()
homeNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor(rgba: "#55acee")]
homeNavigationController.tabBarItem.image = UIImage(named: "rabbit")
homeNavigationController.navigationBar.topItem?.title = "CuteBunny Gifs"
// Set up the Trending View Controller
let trendingNavigationController = storyboard.instantiateViewControllerWithIdentifier("HomeNavigationController") as! UINavigationController
let trendingViewController = homeNavigationController.topViewController as! ViewController
trendingViewController.isTrending = true
trendingViewController.tabBarItem.title = "Trending"
//Customize Trending navigation bar UI
trendingNavigationController.navigationBar.barTintColor = UIColor.blackColor()
trendingNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor(rgba: "#55acee")]
trendingNavigationController.tabBarItem.image = UIImage(named: "trending")
trendingNavigationController.navigationBar.topItem?.title = "Trending Gifs"
// Set up the Tab Bar Controller to have two tabs
tabBarController.viewControllers = [homeNavigationController, trendingNavigationController]
// UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor(rgba: "#55acee")], forState: UIControlState.Normal)
UITabBar.appearance().tintColor =
UIColor(rgba: "#55acee")
UITabBar.appearance().barTintColor = UIColor.blackColor()
// Make the Tab Bar Controller the root view controller
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
}
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:.
}
}
| 48.9375 | 285 | 0.736696 |
67946f969ff0e28499f8b1fb5568d48b0aa2ef5b | 3,250 | //
// SQFeedbackGenerator.swift
// Cryptospace
//
// Created by Matteo Comisso on 24/04/2017.
// Copyright © 2017 mcomisso. All rights reserved.
//
import Foundation
import AudioToolbox
import UIKit
public typealias SQNotificationCompletionBlock = () -> Void
public final class SQFeedbackGenerator {
/// Fallback for unsupported devices, magic numbers
final class SQHaptic {
/// These are sounds code for triggering a haptic feedback on iPhone 6S generation.
///
/// - weak: single weak
/// - strong: single strong
/// - error: three consecutive strong
enum LegacyHapticFeedbackIntensity: UInt32 {
case weak = 1519
case strong = 1520
case error = 1521
}
static func generateFeedback(intensity: LegacyHapticFeedbackIntensity) {
if UIDevice.current.hasHapticFeedback, #available(iOS 10.0, *) {
let notificationGenerator = UINotificationFeedbackGenerator()
notificationGenerator.prepare()
switch intensity {
case .error:
notificationGenerator.notificationOccurred(.error)
case .strong:
notificationGenerator.notificationOccurred(.warning)
case .weak:
notificationGenerator.notificationOccurred(.success)
}
} else {
AudioServicesPlaySystemSound(intensity.rawValue)
}
}
}
/// Feedback types
///
/// - notification: Notification declares a light feedback, with default theme (accent colors) and weak feedback
/// - error: Error declares a triple haptic feedback, with red color as whistle
public enum SQFeedbackType {
case notification
case error
case success
}
public init() { }
fileprivate func generateSuccessFeedback(_ completion: SQNotificationCompletionBlock?) {
defer { SQHaptic.generateFeedback(intensity: .weak) }
guard let completion = completion else { return }
completion()
}
fileprivate func generateErrorFeedback(_ completion: SQNotificationCompletionBlock?) {
defer { SQHaptic.generateFeedback(intensity: .error) }
guard let completion = completion else { return }
completion()
}
fileprivate func generateNotificationFeedback(_ completion: SQNotificationCompletionBlock?) {
defer { SQHaptic.generateFeedback(intensity: .weak) }
guard let completion = completion else { return }
completion()
}
}
extension SQFeedbackGenerator {
/// Generates a feedback for the selected feedback type
///
/// - Parameters:
/// - type: Type can be .notification, .error, .success
/// - completion: Optional completion block to execute
public func generateFeedback(type: SQFeedbackType, completion: SQNotificationCompletionBlock? = nil) {
switch type {
case .success:
self.generateSuccessFeedback(completion)
case .error:
self.generateErrorFeedback(completion)
case .notification:
self.generateNotificationFeedback(completion)
}
}
}
| 31.862745 | 116 | 0.637231 |
46c59ead8d02248e8daba59ceb260661df0eaac5 | 231 | //
// RoomlistController.swift
// HandongAppSwift
//
// Created by ghost on 2015. 7. 29..
// Copyright (c) 2015년 GHOST. All rights reserved.
//
import Foundation
import UIKit
class RoomListController: UIViewController{
} | 16.5 | 51 | 0.709957 |
149362953ce44c43aa9c75acb526505a712fa1e1 | 1,454 | //
// SortSpectacleUITests.swift
// SortSpectacleUITests
//
// Created by Antti Juustila on 19.2.2020.
// Copyright © 2020 Antti Juustila. All rights reserved.
//
import XCTest
class SortSpectacleUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.045455 | 182 | 0.658184 |
39867797924e4adf36211fbc9f21e41b09566b47 | 309 | //
// imageble.swift
// WeatherApp
//
// Created by Kary Martinez on 10/17/19.
// Copyright © 2019 David Rifkin. All rights reserved.
//
import Foundation
import UIKit
struct imagable {
let image: Data
}
//protocol imageble {
// var imageName: String {get}
// func getImage() -> UIImage
//}
| 14.714286 | 55 | 0.653722 |
7a604295d78dac41207ea6834bc0850623d09a48 | 354 | //
// Protocol.swift
// uidesign
//
// Created by Baris Cem Baykara on 3/2/18.
// Copyright © 2018 Baris Cem Baykara. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
struct socialColor {
static let facebook = UIColor(displayP3Red: 59.0/255.0, green: 89.0/255.0, blue: 152.0/255.0, alpha: 1.0)
}
}
| 19.666667 | 112 | 0.649718 |
1ac71734ff1e30d821958254c41d783cf180221e | 691 | //
// NSMutableAttributedString+Attributes.swift
// SZMentionsSwift
//
// Created by Steve Zweier on 2/1/16.
// Copyright © 2016 Steven Zweier. All rights reserved.
//
internal extension NSMutableAttributedString {
/**
@brief Applies attributes to a given string and range
@param attributes: the attributes to apply
@param range: the range to apply the attributes to
*/
func apply(_ attributes: [AttributeContainer], range: NSRange) {
attributes.forEach { attribute in
addAttribute(NSAttributedString.Key(rawValue: attribute.name),
value: attribute.value,
range: range)
}
}
}
| 30.043478 | 74 | 0.643994 |
1de838cdd141aa2cb1b5d2aedeaf660453cf5e07 | 1,101 | //
// ViewPictureCell.swift
// Sedo
//
// Created by Aries Yang on 2018/1/3.
// Copyright © 2018年 Aries Yang. All rights reserved.
//
import UIKit
class ViewPictureCell: UICollectionViewCell, UIScrollViewDelegate {
@IBOutlet weak var placeholderImageView: UIImageView!
@IBOutlet weak var selectedImageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
override func awakeFromNib() {
super.awakeFromNib()
setupImageViews()
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 3.0
scrollView.zoomScale = 1.0
}
func setupImageViews() {
placeholderImageView.image = #imageLiteral(resourceName: "placeholder").withRenderingMode(.alwaysTemplate)
placeholderImageView.tintColor = .lightGray
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return selectedImageView
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.zoomScale = 1.0
}
}
| 24.466667 | 114 | 0.694823 |
ed3794abcb6ce70a44fa21f8ce7d0fa3c6a47458 | 1,341 | //
// Animations.swift
//
// Created by Nick Lockwood on 23/04/2019.
// Copyright © 2019 Nick Lockwood. All rights reserved.
//
import Foundation
enum AnimationMode {
case loop
case reset
case clamp
}
struct Animation {
var duration: TimeInterval
var mode: AnimationMode
var frames: [Int]
private(set) var onCompletion: () -> Void = {}
init(duration: TimeInterval, mode: AnimationMode, frames: [Int]) {
self.duration = duration
self.mode = mode
self.frames = frames
}
func then(_ onCompletion: @escaping () -> Void) -> Animation {
var animation = self
let oldCompletion = animation.onCompletion
animation.onCompletion = {
oldCompletion()
onCompletion()
}
return animation
}
func frame(at time: TimeInterval) -> Int {
guard duration > 0, frames.count > 1 else {
return frames.first ?? 0
}
var t = time / duration
if t >= 1 {
switch mode {
case .loop:
t = t.truncatingRemainder(dividingBy: 1)
case .clamp:
t = 1
case .reset:
t = 0
}
}
let count = frames.count
return frames[min(Int(Double(count) * t), count - 1)]
}
}
| 23.526316 | 70 | 0.540641 |
4885aecdb206c303eed7a0f4ccc54937fb8454b6 | 273 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{struct S{struct d<T where h:B{enum b{func b<f:t{let g=b{
| 34.125 | 87 | 0.736264 |
72e9fa81b5a6a628f9ab0a335d06108cb31bce9a | 253 | //
// Setting.swift
// Diner
//
// Created by Prithvi Prabahar on 9/24/17.
// Copyright © 2017 Prithvi Prabahar. All rights reserved.
//
import Foundation
protocol Setting {
var name: String { get }
var preferences: [Preference] { get }
}
| 16.866667 | 59 | 0.660079 |
1cd6593fec8fe2115a1b55a1c8d24ea3b2d36f5f | 1,496 | //
// UITableViewCell+Ext.swift
// Pods-TKUIKitModule_Example
//
// Created by 聂子 on 2018/12/9.
//
import Foundation
fileprivate var kindexPath = "kindexPath"
extension UITableViewCell {
var indexPath:IndexPath?
{
get {
return (objc_getAssociatedObject(self, &kindexPath) as? IndexPath)
}
set(newValue) {
objc_setAssociatedObject(self, &kindexPath, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
// MARK: - UITableViewCell
extension TypeWrapperProtocol where WrappedType : UITableViewCell {
/// 获取一个 identifier 根据当前类名
///
/// - Returns: identifier
public static func identifier() -> String {
return String(describing: self.WrappedType.classForCoder)
}
/// dequeue cell for tableView
///
/// - Parameters:
/// - tableView: tableView
/// - indexPath: indexPath
/// - reuseIdentifier: reuseIdentifier
/// - Returns: UITableViewCell
public static func dequeueReusableCell<T:UITableViewCell>(tableView: UITableView,indexPath: IndexPath?, reuseIdentifier: String = "") -> T {
var id = reuseIdentifier
if id.isEmpty {
id = String(describing: self.WrappedType.classForCoder())
}
var cell = tableView.dequeueReusableCell(withIdentifier: id)
if cell == nil {
cell = T(style: .default, reuseIdentifier: id)
}
cell?.indexPath = indexPath
return cell as! T
}
}
| 26.245614 | 144 | 0.625668 |
906e272f40562cd45168e3e03ebb7fc04bca11b0 | 1,386 | import UIKit
protocol MedicineSearchHandable: class {
func presentUBSMedicineSelection(with medicineName: String)
}
class MedicineSearchTableViewController: UITableViewController {
var medicines: [String] = [] {
didSet {
self.tableView.reloadData()
}
}
weak var delegate: MedicineSearchHandable?
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return medicines.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = medicines[indexPath.row]
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let medicineName = tableView.cellForRow(at: indexPath)?.textLabel?.text else { return }
delegate?.presentUBSMedicineSelection(with: medicineName)
}
}
extension MedicineSearchTableViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchBarText = searchController.searchBar.text else { return }
medicines = UBSManager.getList().medicinesNameWhere(contains: searchBarText)
}
}
| 33.804878 | 107 | 0.768398 |
acf3927b49486606239c7a40a962f3404c79b072 | 946 | //
// GenreCollectionViewCell.swift
// Galaxy App
//
// Created by Ko Kyaw on 21/07/2021.
//
import UIKit
class GenreCollectionViewCell: UICollectionViewCell {
var genreName: String? {
didSet {
guard let genreName = genreName else { return }
label.text = genreName
}
}
private let label = UILabel(text: "", font: .poppinsLight, size: 16, color: .galaxyBlack)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(label)
label.snp.makeConstraints { make in
make.centerX.centerY.equalToSuperview()
}
layer.cornerRadius = frame.height / 2
layer.borderWidth = 0.5
layer.borderColor = UIColor.galaxyLightBlack.cgColor
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 23.65 | 93 | 0.591966 |
71d18bd82541ee74ac2c82dc3a7b9136796ec918 | 4,436 | import Foundation
private let kVersion = "1.0"
/*
* USAGE:
* sentinel [debug|release] [json]
*/
let arguments = CommandLine.arguments
if arguments.count > 2 {
let configuration = arguments[1]
let path = arguments[2]
do {
var settings: [String: Any] = [:]
let url = URL(fileURLWithPath: path)
let data = try Data(contentsOf: url)
let pathExtension = (path as NSString).pathExtension.lowercased()
if pathExtension == "json" {
if let json = data.json as? [String: Any] {
settings = json
}
}
if settings.count > 0 {
if configuration.lowercased() == "debug" {
if let debug = settings["debug"] as? [[String: Any]] {
for instruction in debug {
if let rule = instruction["rule"] as? String, let message = instruction["message"] as? String, let type = instruction["type"] as? String, let file = instruction["file"] as? String {
if type == "warning" || type == "error" {
var line = "rules=\"\(rule)\""
line.append("\nfind \"$SRCROOT\" \\( -name \"\(file)\" \\) -print0 ")
line.append("| xargs -0 egrep --with-filename --line-number")
line.append(" --only-matching \"($rules)\" ")
line.append("| perl -p -e \"s/($rules)/ \(type): \(message)/\"")
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", line]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
debugPrint(output as AnyObject)
}
}
}
}
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| USAGE: sentinel [debug|release] [json] |" as AnyObject)
debugPrint("| VERSION: \(kVersion) |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| DEBUG: Done |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
}
} else if configuration.lowercased() == "release" {
if let release = settings["release"] as? [[String: Any]] {
for instruction in release {
if let rule = instruction["rule"] as? String, let message = instruction["message"] as? String, let type = instruction["type"] as? String, let file = instruction["file"] as? String {
if type == "warning" || type == "error" {
var line = "rules=\"\(rule)\""
line.append("\nfind \"${SRCROOT}\" \\( -name \"\(file)\" \\) -print0 ")
line.append("| xargs -0 egrep --with-filename --line-number")
line.append(" --only-matching \"($rules).*\\$\" ")
line.append("| perl -p -e \"s/($rules)/ \(type): \(message)/\"")
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", line]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
debugPrint(output as AnyObject)
}
}
}
}
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| USAGE: sentinel [debug|release] [json] |" as AnyObject)
debugPrint("| VERSION: \(kVersion) |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| RELEASE: Done |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
}
}
}
} catch {
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| USAGE: sentinel [debug|release] [json] |" as AnyObject)
debugPrint("| VERSION: \(kVersion) |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| ERROR: Could not parse json |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
}
} else {
debugPrint("+----------------------------------------+" as AnyObject)
debugPrint("| USAGE: sentinel [debug|release] [json] |" as AnyObject)
debugPrint("| VERSION: \(kVersion) |" as AnyObject)
debugPrint("+----------------------------------------+" as AnyObject)
}
| 38.573913 | 187 | 0.510144 |
b922520acec1827ddeb7ad50d5e5da78c275c298 | 2,512 | //
// COGcalculate.swift
// PoseEstimation-CoreML
//
// Created by Vibteam on 2019/08/01.
// Copyright © 2019 tucan9389. All rights reserved.
//
import UIKit
class COGcalculate {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
// "COG_ue", //14 ={(R shoulder + L shoulder)/2}*61/100 + {(R hip + L hip)/2}*39/100
// "R COG_sita", //15 =R hip * 56/100 + R knee * 44/100
// "L COG_sita", //16 =L hip * 56/100 + L knee * 44/100
// "COG_sita", //17 =(R COG_sita + L COG_sita) /2
//
// "COG", //18 =(COG_ue + COG_sita) /2
open func show_COG_ue(R_shoulder : CGFloat? , L_shoulder : CGFloat? , R_hip : CGFloat? , L_hip : CGFloat?) -> CGFloat{
if(R_shoulder != nil && L_shoulder != nil && R_hip != nil && L_hip != nil ){
let syoulder = (R_shoulder! + L_shoulder!)/2 * (61/100)
let hip = (R_hip! + L_hip!)/2 * (39/100)
let COG_ue = syoulder + hip
// print(COG_ue)
return COG_ue
}else{
// print("計測不可")
return (0.0000)
// super.COG.text = "計測不可"
}
}
open func show_R_COG_sita(R_hip : CGFloat? , R_knee : CGFloat?) -> CGFloat{
if(R_hip != nil && R_knee != nil){
let R_COG_sita = (R_hip!) * (56/100) + (R_knee!) * (44/100)
return R_COG_sita
}else{
return (0.0000)
}
}
open func show_L_COG_sita(L_hip : CGFloat? , L_knee : CGFloat?) -> CGFloat{
if(L_hip != nil && L_knee != nil){
let L_COG_sita = (L_hip!) * (56/100) + (L_knee!) * (44/100)
return L_COG_sita
}else{
return (0.0000)
}
}
open func show_COG_sita(R_COG_sita : CGFloat? , L_COG_sita : CGFloat?) -> CGFloat{
if(R_COG_sita == 0.0000 || L_COG_sita == 0.0000){
return (0.0000)
}else{
let COG_sita = (R_COG_sita! + L_COG_sita!)/2
return COG_sita
}
}
open func show_COG(COG_ue : CGFloat? , COG_sita : CGFloat?) -> CGFloat{
if(COG_ue == 0.0000 || COG_sita == 0.0000){
return (0.0000)
}else{
let COG = (COG_ue! + COG_sita!)/2
return COG
}
}
}
//xy座標で出したい.
| 30.634146 | 122 | 0.50199 |
79f5ba1fbe66292fd0906d684c04f4678168641f | 307 | //
// UIScreenExtension.swift
// Panda-Saza
//
// Created by Jae Heo on 2021/02/24.
//
import SwiftUI
extension UIScreen{
static let screenWidth = UIScreen.main.bounds.size.width
static let screenHeight = UIScreen.main.bounds.size.height
static let screenSize = UIScreen.main.bounds.size
}
| 20.466667 | 62 | 0.726384 |
eb363ee905346ff083701dde867b998a00874fcb | 215 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b {
init {
case
var {
for {
class
case ,
| 17.916667 | 87 | 0.739535 |
4abf535ff2b01cf9b0f0f2572a43b2617113c6ab | 489 | extension KeychainStored: Equatable where Value: Equatable {
public static func == (lhs: KeychainStored<Value, ValueEncoder, ValueDecoder>, rhs: KeychainStored<Value, ValueEncoder, ValueDecoder>) -> Bool {
lhs.service == rhs.service && lhs.wrappedValue == rhs.wrappedValue
}
}
extension KeychainStored: Hashable where Value: Hashable {
public func hash(into hasher: inout Hasher) {
service.hash(into: &hasher)
wrappedValue?.hash(into: &hasher)
}
}
| 37.615385 | 148 | 0.703476 |
89fb0ce714be5f823539253439475ab3906251a2 | 9,035 | import GraphQL
public class Field<ObjectType, Context, FieldType, Arguments : Decodable> : FieldComponent<ObjectType, Context> {
let name: String
let arguments: [ArgumentComponent<Arguments>]
let resolve: GraphQLFieldResolve
override func field(typeProvider: TypeProvider) throws -> (String, GraphQLField) {
let field = GraphQLField(
type: try typeProvider.getOutputType(from: FieldType.self, field: name),
description: description,
deprecationReason: deprecationReason,
args: try arguments(typeProvider: typeProvider),
resolve: resolve
)
return (name, field)
}
func arguments(typeProvider: TypeProvider) throws -> GraphQLArgumentConfigMap {
var map: GraphQLArgumentConfigMap = [:]
for argument in arguments {
let (name, argument) = try argument.argument(typeProvider: typeProvider)
map[name] = argument
}
return map
}
init(
name: String,
arguments: [ArgumentComponent<Arguments>],
resolve: @escaping GraphQLFieldResolve
) {
self.name = name
self.arguments = arguments
self.resolve = resolve
}
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
asyncResolve: @escaping AsyncResolve<ObjectType, Context, Arguments, ResolveType>
) {
let resolve: GraphQLFieldResolve = { source, arguments, context, eventLoopGroup, _ in
guard let s = source as? ObjectType else {
throw GraphQLError(message: "Expected source type \(ObjectType.self) but got \(type(of: source))")
}
guard let c = context as? Context else {
throw GraphQLError(message: "Expected context type \(Context.self) but got \(type(of: context))")
}
let a = try MapDecoder().decode(Arguments.self, from: arguments)
return try asyncResolve(s)(c, a, eventLoopGroup).map({ $0 })
}
self.init(name: name, arguments: arguments, resolve: resolve)
}
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
simpleAsyncResolve: @escaping SimpleAsyncResolve<ObjectType, Context, Arguments, ResolveType>
) {
let asyncResolve: AsyncResolve<ObjectType, Context, Arguments, ResolveType> = { type in
{ context, arguments, group in
// We hop to guarantee that the future will
// return in the same event loop group of the execution.
try simpleAsyncResolve(type)(context, arguments).hop(to: group.next())
}
}
self.init(name: name, arguments: arguments, asyncResolve: asyncResolve)
}
convenience init<ResolveType>(
name: String,
arguments: [ArgumentComponent<Arguments>],
syncResolve: @escaping SyncResolve<ObjectType, Context, Arguments, ResolveType>
) {
let asyncResolve: AsyncResolve<ObjectType, Context, Arguments, ResolveType> = { type in
{ context, arguments, group in
let result = try syncResolve(type)(context, arguments)
return group.next().makeSucceededFuture(result)
}
}
self.init(name: name, arguments: arguments, asyncResolve: asyncResolve)
}
}
// MARK: AsyncResolve Initializers
public extension Field where FieldType : Encodable {
convenience init(
_ name: String,
at function: @escaping AsyncResolve<ObjectType, Context, Arguments, FieldType>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], asyncResolve: function)
}
convenience init(
_ name: String,
at function: @escaping AsyncResolve<ObjectType, Context, Arguments, FieldType>,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> [ArgumentComponent<Arguments>] = {[]}
) {
self.init(name: name, arguments: arguments(), asyncResolve: function)
}
}
public extension Field {
convenience init<ResolveType>(
_ name: String,
at function: @escaping AsyncResolve<ObjectType, Context, Arguments, ResolveType>,
as: FieldType.Type,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], asyncResolve: function)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping AsyncResolve<ObjectType, Context, Arguments, ResolveType>,
as: FieldType.Type,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> [ArgumentComponent<Arguments>] = {[]}
) {
self.init(name: name, arguments: arguments(), asyncResolve: function)
}
}
// MARK: SimpleAsyncResolve Initializers
public extension Field where FieldType : Encodable {
convenience init(
_ name: String,
at function: @escaping SimpleAsyncResolve<ObjectType, Context, Arguments, FieldType>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], simpleAsyncResolve: function)
}
convenience init(
_ name: String,
at function: @escaping SimpleAsyncResolve<ObjectType, Context, Arguments, FieldType>,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> [ArgumentComponent<Arguments>] = {[]}
) {
self.init(name: name, arguments: arguments(), simpleAsyncResolve: function)
}
}
public extension Field {
convenience init<ResolveType>(
_ name: String,
at function: @escaping SimpleAsyncResolve<ObjectType, Context, Arguments, ResolveType>,
as: FieldType.Type,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], simpleAsyncResolve: function)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping SimpleAsyncResolve<ObjectType, Context, Arguments, ResolveType>,
as: FieldType.Type,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> [ArgumentComponent<Arguments>] = {[]}
) {
self.init(name: name, arguments: arguments(), simpleAsyncResolve: function)
}
}
// MARK: SyncResolve Initializers
public extension Field where FieldType : Encodable {
convenience init(
_ name: String,
at function: @escaping SyncResolve<ObjectType, Context, Arguments, FieldType>,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], syncResolve: function)
}
convenience init(
_ name: String,
at function: @escaping SyncResolve<ObjectType, Context, Arguments, FieldType>,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> [ArgumentComponent<Arguments>] = {[]}
) {
self.init(name: name, arguments: arguments(), syncResolve: function)
}
}
public extension Field {
convenience init<ResolveType>(
_ name: String,
at function: @escaping SyncResolve<ObjectType, Context, Arguments, ResolveType>,
as: FieldType.Type,
@ArgumentComponentBuilder<Arguments> _ argument: () -> ArgumentComponent<Arguments>
) {
self.init(name: name, arguments: [argument()], syncResolve: function)
}
convenience init<ResolveType>(
_ name: String,
at function: @escaping SyncResolve<ObjectType, Context, Arguments, ResolveType>,
as: FieldType.Type,
@ArgumentComponentBuilder<Arguments> _ arguments: () -> [ArgumentComponent<Arguments>] = {[]}
) {
self.init(name: name, arguments: arguments(), syncResolve: function)
}
}
// MARK: Keypath Initializers
public extension Field where Arguments == NoArguments {
convenience init(
_ name: String,
at keyPath: KeyPath<ObjectType, FieldType>
) {
let syncResolve: SyncResolve<ObjectType, Context, NoArguments, FieldType> = { type in
{ context, _ in
type[keyPath: keyPath]
}
}
self.init(name: name, arguments: [], syncResolve: syncResolve)
}
}
public extension Field where Arguments == NoArguments {
convenience init<ResolveType>(
_ name: String,
at keyPath: KeyPath<ObjectType, ResolveType>,
as: FieldType.Type
) {
let syncResolve: SyncResolve<ObjectType, Context, NoArguments, ResolveType> = { type in
return { context, _ in
return type[keyPath: keyPath]
}
}
self.init(name: name, arguments: [], syncResolve: syncResolve)
}
}
| 36.727642 | 114 | 0.636746 |
72349359536f4a728c7dc823365e05bc144176d7 | 229 | //
// Constants.swift
// MyComics
//
// Created by Silvia España on 2/11/21.
//
import Foundation
struct Constants {
static let baseURL = "https://comicvine.gamespot.com/api/"
static let apiKey = "yourApiKey"
}
| 15.266667 | 62 | 0.655022 |
0989b6fb38814a5600be526c45bc1205bd7992c8 | 1,859 | import Foundation
import LibraryDemo_PhoneNumberKit
extension Libraries {
static let PhoneNumberKit = Library(
id: "PhoneNumberKit",
name: "Phone\nNumberKit",
description: .init(
short: "Framework for parsing, formatting and validating international phone numbers",
full: nil
),
preview: .init(
logo: Image(
name: "library_PhoneNumberKit",
bundleIdentifier: Bundle.AwesomeData_identifier
),
title: "PhoneNumberKit",
subtitle: "Framework for parsing, formatting and validating international phone numbers"
),
developers: [
.init(
name: "Roy Marmelstein",
contactInformation: ContactInformation(
email: "[email protected]",
website: "http://marmelroy.github.io"
),
isCompany: false
)
],
links: LibraryLinks(
github: GitHubRepositoryLink(
user: "marmelroy",
repository: "PhoneNumberKit"
),
other: []
),
integration: LibraryPackageManagers(
cocoapods: CocoaPodsIntegration(
podName: "PhoneNumberKit"
),
carthage: CarthageIntegration.github(
withPath: "marmelroy/PhoneNumberKit"
),
swiftPackageManager: nil
),
tags: [
.ui
],
license: .mit(),
demo: LibraryDemo(
screen: DemoScreen(
viewControllerClass: LibraryDemoViewController.self,
nibName: "",
bundleIdentifier: Bundle.PhoneNumberKit_identifier,
enabled: true
)
)
)
}
| 30.47541 | 100 | 0.513179 |
4b8afbf67792cc5b7f5b0850e8d9f566e91b2c4f | 1,714 | import XCTest
@testable import SwiftyJWT
final class SwiftyJWTIntegrationTests: XCTestCase {
func testVerificationFailureWithoutLeeway() {
let token = SwiftyJWT.encode(.none) { builder in
builder.issuer = "fuller.li"
builder.audience = "cocoapods"
builder.expiration = Date().addingTimeInterval(-1) // Token expired one second ago
builder.notBefore = Date().addingTimeInterval(1) // Token starts being valid in one second
builder.issuedAt = Date().addingTimeInterval(1) // Token is issued one second in the future
}
do {
let _ = try SwiftyJWT.decode(token, algorithm: .none, leeway: 0)
XCTFail("InvalidToken error should have been thrown.")
} catch is SwiftyJWT.JWTErrors.InvalidToken {
// Correct error thrown
} catch {
XCTFail("Unexpected error type while verifying token.")
}
}
func testVerificationSuccessWithLeeway() {
let token = SwiftyJWT.encode(.none) { builder in
builder.issuer = "fuller.li"
builder.audience = "cocoapods"
builder.expiration = Date().addingTimeInterval(-1) // Token expired one second ago
builder.notBefore = Date().addingTimeInterval(1) // Token starts being valid in one second
builder.issuedAt = Date().addingTimeInterval(1) // Token is issued one second in the future
}
do {
let _ = try SwiftyJWT.decode(token, algorithm: .none, leeway: 2)
// Due to leeway no error gets thrown.
} catch {
XCTFail("Unexpected error type while verifying token.")
}
}
}
| 41.804878 | 103 | 0.616103 |
39af3f1033bbaf95b08f8c3849229a8c5465f431 | 2,209 | //
// AppDelegate.swift
// IOSDeleteItemsCollectionViewTutorial
//
// Created by Arthur Knopper on 24/04/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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:.
}
}
| 47 | 285 | 0.758714 |
5b74a6ef9766814058f754f57b409e9c1207722f | 20,771 | import XCTest
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif os(Linux)
import CSQLite
#else
import SQLite3
#endif
@testable import SQLite
class QueryTests : XCTestCase {
let users = Table("users")
let id = Expression<Int64>("id")
let email = Expression<String>("email")
let age = Expression<Int?>("age")
let admin = Expression<Bool>("admin")
let optionalAdmin = Expression<Bool?>("admin")
let posts = Table("posts")
let userId = Expression<Int64>("user_id")
let categoryId = Expression<Int64>("category_id")
let published = Expression<Bool>("published")
let categories = Table("categories")
let tag = Expression<String>("tag")
func test_select_withExpression_compilesSelectClause() {
AssertSQL("SELECT \"email\" FROM \"users\"", users.select(email))
}
func test_select_withStarExpression_compilesSelectClause() {
AssertSQL("SELECT * FROM \"users\"", users.select(*))
}
func test_select_withNamespacedStarExpression_compilesSelectClause() {
AssertSQL("SELECT \"users\".* FROM \"users\"", users.select(users[*]))
}
func test_select_withVariadicExpressions_compilesSelectClause() {
AssertSQL("SELECT \"email\", count(*) FROM \"users\"", users.select(email, count(*)))
}
func test_select_withExpressions_compilesSelectClause() {
AssertSQL("SELECT \"email\", count(*) FROM \"users\"", users.select([email, count(*)]))
}
func test_selectDistinct_withExpression_compilesSelectClause() {
AssertSQL("SELECT DISTINCT \"age\" FROM \"users\"", users.select(distinct: age))
}
func test_selectDistinct_withExpressions_compilesSelectClause() {
AssertSQL("SELECT DISTINCT \"age\", \"admin\" FROM \"users\"", users.select(distinct: [age, admin]))
}
func test_selectDistinct_withStar_compilesSelectClause() {
AssertSQL("SELECT DISTINCT * FROM \"users\"", users.select(distinct: *))
}
func test_join_compilesJoinClause() {
AssertSQL(
"SELECT * FROM \"users\" INNER JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\")",
users.join(posts, on: posts[userId] == users[id])
)
}
func test_join_withExplicitType_compilesJoinClauseWithType() {
AssertSQL(
"SELECT * FROM \"users\" LEFT OUTER JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\")",
users.join(.leftOuter, posts, on: posts[userId] == users[id])
)
AssertSQL(
"SELECT * FROM \"users\" CROSS JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\")",
users.join(.cross, posts, on: posts[userId] == users[id])
)
}
func test_join_withTableCondition_compilesJoinClauseWithTableCondition() {
AssertSQL(
"SELECT * FROM \"users\" INNER JOIN \"posts\" ON ((\"posts\".\"user_id\" = \"users\".\"id\") AND \"published\")",
users.join(posts.filter(published), on: posts[userId] == users[id])
)
}
func test_join_whenChained_compilesAggregateJoinClause() {
AssertSQL(
"SELECT * FROM \"users\" " +
"INNER JOIN \"posts\" ON (\"posts\".\"user_id\" = \"users\".\"id\") " +
"INNER JOIN \"categories\" ON (\"categories\".\"id\" = \"posts\".\"category_id\")",
users.join(posts, on: posts[userId] == users[id]).join(categories, on: categories[id] == posts[categoryId])
)
}
func test_filter_compilesWhereClause() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.filter(admin == true))
}
func test_filter_compilesWhereClause_false() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.filter(admin == false))
}
func test_filter_compilesWhereClause_optional() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.filter(optionalAdmin == true))
}
func test_filter_compilesWhereClause_optional_false() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.filter(optionalAdmin == false))
}
func test_where_compilesWhereClause() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.where(admin == true))
}
func test_where_compilesWhereClause_false() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.where(admin == false))
}
func test_where_compilesWhereClause_optional() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 1)", users.where(optionalAdmin == true))
}
func test_where_compilesWhereClause_optional_false() {
AssertSQL("SELECT * FROM \"users\" WHERE (\"admin\" = 0)", users.where(optionalAdmin == false))
}
func test_filter_whenChained_compilesAggregateWhereClause() {
AssertSQL(
"SELECT * FROM \"users\" WHERE ((\"age\" >= 35) AND \"admin\")",
users.filter(age >= 35).filter(admin)
)
}
func test_group_withSingleExpressionName_compilesGroupClause() {
AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\"",
users.group(age))
}
func test_group_withVariadicExpressionNames_compilesGroupClause() {
AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\", \"admin\"", users.group(age, admin))
}
func test_group_withExpressionNameAndHavingBindings_compilesGroupClause() {
AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\" HAVING \"admin\"", users.group(age, having: admin))
AssertSQL("SELECT * FROM \"users\" GROUP BY \"age\" HAVING (\"age\" >= 30)", users.group(age, having: age >= 30))
}
func test_group_withExpressionNamesAndHavingBindings_compilesGroupClause() {
AssertSQL(
"SELECT * FROM \"users\" GROUP BY \"age\", \"admin\" HAVING \"admin\"",
users.group([age, admin], having: admin)
)
AssertSQL(
"SELECT * FROM \"users\" GROUP BY \"age\", \"admin\" HAVING (\"age\" >= 30)",
users.group([age, admin], having: age >= 30)
)
}
func test_order_withSingleExpressionName_compilesOrderClause() {
AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\"", users.order(age))
}
func test_order_withVariadicExpressionNames_compilesOrderClause() {
AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\", \"email\"", users.order(age, email))
}
func test_order_withArrayExpressionNames_compilesOrderClause() {
AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\", \"email\"", users.order([age, email]))
}
func test_order_withExpressionAndSortDirection_compilesOrderClause() {
// AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\" DESC, \"email\" ASC", users.order(age.desc, email.asc))
}
func test_order_whenChained_resetsOrderClause() {
AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\"", users.order(email).order(age))
}
func test_reverse_withoutOrder_ordersByRowIdDescending() {
// AssertSQL("SELECT * FROM \"users\" ORDER BY \"ROWID\" DESC", users.reverse())
}
func test_reverse_withOrder_reversesOrder() {
// AssertSQL("SELECT * FROM \"users\" ORDER BY \"age\" DESC, \"email\" ASC", users.order(age, email.desc).reverse())
}
func test_limit_compilesLimitClause() {
AssertSQL("SELECT * FROM \"users\" LIMIT 5", users.limit(5))
}
func test_limit_withOffset_compilesOffsetClause() {
AssertSQL("SELECT * FROM \"users\" LIMIT 5 OFFSET 5", users.limit(5, offset: 5))
}
func test_limit_whenChained_overridesLimit() {
let query = users.limit(5)
AssertSQL("SELECT * FROM \"users\" LIMIT 10", query.limit(10))
AssertSQL("SELECT * FROM \"users\"", query.limit(nil))
}
func test_limit_whenChained_withOffset_overridesOffset() {
let query = users.limit(5, offset: 5)
AssertSQL("SELECT * FROM \"users\" LIMIT 10 OFFSET 20", query.limit(10, offset: 20))
AssertSQL("SELECT * FROM \"users\"", query.limit(nil))
}
func test_alias_aliasesTable() {
let managerId = Expression<Int64>("manager_id")
let managers = users.alias("managers")
AssertSQL(
"SELECT * FROM \"users\" " +
"INNER JOIN \"users\" AS \"managers\" ON (\"managers\".\"id\" = \"users\".\"manager_id\")",
users.join(managers, on: managers[id] == users[managerId])
)
}
func test_insert_compilesInsertExpression() {
AssertSQL(
"INSERT INTO \"users\" (\"email\", \"age\") VALUES ('[email protected]', 30)",
users.insert(email <- "[email protected]", age <- 30)
)
}
func test_insert_withOnConflict_compilesInsertOrOnConflictExpression() {
AssertSQL(
"INSERT OR REPLACE INTO \"users\" (\"email\", \"age\") VALUES ('[email protected]', 30)",
users.insert(or: .replace, email <- "[email protected]", age <- 30)
)
}
func test_insert_compilesInsertExpressionWithDefaultValues() {
AssertSQL("INSERT INTO \"users\" DEFAULT VALUES", users.insert())
}
func test_insert_withQuery_compilesInsertExpressionWithSelectStatement() {
let emails = Table("emails")
AssertSQL(
"INSERT INTO \"emails\" SELECT \"email\" FROM \"users\" WHERE \"admin\"",
emails.insert(users.select(email).filter(admin))
)
}
func test_insert_encodable() throws {
let emails = Table("emails")
let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: nil, sub: nil)
let insert = try emails.insert(value)
AssertSQL(
"INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\") VALUES (1, '2', 1, 3.0, 4.0)",
insert
)
}
func test_insert_encodable_with_nested_encodable() throws {
let emails = Table("emails")
let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: nil, sub: nil)
let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: "optional", sub: value1)
let insert = try emails.insert(value)
let encodedJSON = try JSONEncoder().encode(value1)
let encodedJSONString = String(data: encodedJSON, encoding: .utf8)!
AssertSQL(
"INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"optional\", \"sub\") VALUES (1, '2', 1, 3.0, 4.0, 'optional', '\(encodedJSONString)')",
insert
)
}
func test_update_compilesUpdateExpression() {
AssertSQL(
"UPDATE \"users\" SET \"age\" = 30, \"admin\" = 1 WHERE (\"id\" = 1)",
users.filter(id == 1).update(age <- 30, admin <- true)
)
}
func test_update_compilesUpdateLimitOrderExpression() {
AssertSQL(
"UPDATE \"users\" SET \"age\" = 30 ORDER BY \"id\" LIMIT 1",
users.order(id).limit(1).update(age <- 30)
)
}
func test_update_encodable() throws {
let emails = Table("emails")
let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: nil, sub: nil)
let update = try emails.update(value)
AssertSQL(
"UPDATE \"emails\" SET \"int\" = 1, \"string\" = '2', \"bool\" = 1, \"float\" = 3.0, \"double\" = 4.0",
update
)
}
func test_update_encodable_with_nested_encodable() throws {
let emails = Table("emails")
let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: nil, sub: nil)
let value = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: nil, sub: value1)
let update = try emails.update(value)
let encodedJSON = try JSONEncoder().encode(value1)
let encodedJSONString = String(data: encodedJSON, encoding: .utf8)!
AssertSQL(
"UPDATE \"emails\" SET \"int\" = 1, \"string\" = '2', \"bool\" = 1, \"float\" = 3.0, \"double\" = 4.0, \"sub\" = '\(encodedJSONString)'",
update
)
}
func test_delete_compilesDeleteExpression() {
AssertSQL(
"DELETE FROM \"users\" WHERE (\"id\" = 1)",
users.filter(id == 1).delete()
)
}
func test_delete_compilesDeleteLimitOrderExpression() {
AssertSQL(
"DELETE FROM \"users\" ORDER BY \"id\" LIMIT 1",
users.order(id).limit(1).delete()
)
}
func test_delete_compilesExistsExpression() {
AssertSQL(
"SELECT EXISTS (SELECT * FROM \"users\")",
users.exists
)
}
func test_count_returnsCountExpression() {
AssertSQL("SELECT count(*) FROM \"users\"", users.count)
}
func test_scalar_returnsScalarExpression() {
AssertSQL("SELECT \"int\" FROM \"table\"", table.select(int) as ScalarQuery<Int>)
AssertSQL("SELECT \"intOptional\" FROM \"table\"", table.select(intOptional) as ScalarQuery<Int?>)
AssertSQL("SELECT DISTINCT \"int\" FROM \"table\"", table.select(distinct: int) as ScalarQuery<Int>)
AssertSQL("SELECT DISTINCT \"intOptional\" FROM \"table\"", table.select(distinct: intOptional) as ScalarQuery<Int?>)
}
func test_subscript_withExpression_returnsNamespacedExpression() {
let query = Table("query")
AssertSQL("\"query\".\"blob\"", query[data])
AssertSQL("\"query\".\"blobOptional\"", query[dataOptional])
AssertSQL("\"query\".\"bool\"", query[bool])
AssertSQL("\"query\".\"boolOptional\"", query[boolOptional])
AssertSQL("\"query\".\"date\"", query[date])
AssertSQL("\"query\".\"dateOptional\"", query[dateOptional])
AssertSQL("\"query\".\"double\"", query[double])
AssertSQL("\"query\".\"doubleOptional\"", query[doubleOptional])
AssertSQL("\"query\".\"int\"", query[int])
AssertSQL("\"query\".\"intOptional\"", query[intOptional])
AssertSQL("\"query\".\"int64\"", query[int64])
AssertSQL("\"query\".\"int64Optional\"", query[int64Optional])
AssertSQL("\"query\".\"string\"", query[string])
AssertSQL("\"query\".\"stringOptional\"", query[stringOptional])
AssertSQL("\"query\".*", query[*])
}
func test_tableNamespacedByDatabase() {
let table = Table("table", database: "attached")
AssertSQL("SELECT * FROM \"attached\".\"table\"", table)
}
}
class QueryIntegrationTests : SQLiteTestCase {
let id = Expression<Int64>("id")
let email = Expression<String>("email")
override func setUp() {
super.setUp()
CreateUsersTable()
}
// MARK: -
func test_select() {
let managerId = Expression<Int64>("manager_id")
let managers = users.alias("managers")
let alice = try! db.run(users.insert(email <- "[email protected]"))
_ = try! db.run(users.insert(email <- "[email protected]", managerId <- alice))
for user in try! db.prepare(users.join(managers, on: managers[id] == users[managerId])) {
_ = try! user.unwrapOrThrow()[users[managerId]]
}
}
func test_prepareRowIterator() {
let names = ["a", "b", "c"]
try! InsertUsers(names)
let emailColumn = Expression<String>("email")
let emails = try! db.prepareRowIterator(users).map { $0[emailColumn] }
XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
func test_ambiguousMap() {
let names = ["a", "b", "c"]
try! InsertUsers(names)
let emails = try! db.prepare("select email from users", []).map { (try! $0.unwrapOrThrow()[0]) as! String }
XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
func test_select_optional() {
let managerId = Expression<Int64?>("manager_id")
let managers = users.alias("managers")
let alice = try! db.run(users.insert(email <- "[email protected]"))
_ = try! db.run(users.insert(email <- "[email protected]", managerId <- alice))
for user in try! db.prepare(users.join(managers, on: managers[id] == users[managerId])) {
_ = try! user.unwrapOrThrow()[users[managerId]]
}
}
func test_select_codable() throws {
let table = Table("codable")
try db.run(table.create { builder in
builder.column(Expression<Int>("int"))
builder.column(Expression<String>("string"))
builder.column(Expression<Bool>("bool"))
builder.column(Expression<Double>("float"))
builder.column(Expression<Double>("double"))
builder.column(Expression<String?>("optional"))
builder.column(Expression<Data>("sub"))
})
let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4, optional: nil, sub: nil)
let value = TestCodable(int: 5, string: "6", bool: true, float: 7, double: 8, optional: "optional", sub: value1)
try db.run(table.insert(value))
let rows = try db.prepare(table)
let values: [TestCodable] = try rows.map({ try $0.unwrapOrThrow().decode() })
XCTAssertEqual(values.count, 1)
XCTAssertEqual(values[0].int, 5)
XCTAssertEqual(values[0].string, "6")
XCTAssertEqual(values[0].bool, true)
XCTAssertEqual(values[0].float, 7)
XCTAssertEqual(values[0].double, 8)
XCTAssertEqual(values[0].optional, "optional")
XCTAssertEqual(values[0].sub?.int, 1)
XCTAssertEqual(values[0].sub?.string, "2")
XCTAssertEqual(values[0].sub?.bool, true)
XCTAssertEqual(values[0].sub?.float, 3)
XCTAssertEqual(values[0].sub?.double, 4)
XCTAssertNil(values[0].sub?.optional)
XCTAssertNil(values[0].sub?.sub)
}
func test_scalar() {
XCTAssertEqual(0, try! db.scalar(users.count))
XCTAssertEqual(false, try! db.scalar(users.exists))
try! InsertUsers("alice")
XCTAssertEqual(1, try! db.scalar(users.select(id.average)))
}
func test_pluck() {
let rowid = try! db.run(users.insert(email <- "[email protected]"))
XCTAssertEqual(rowid, try! db.pluck(users)![id])
}
func test_insert() {
let id = try! db.run(users.insert(email <- "[email protected]"))
XCTAssertEqual(1, id)
}
func test_update() {
let changes = try! db.run(users.update(email <- "[email protected]"))
XCTAssertEqual(0, changes)
}
func test_delete() {
let changes = try! db.run(users.delete())
XCTAssertEqual(0, changes)
}
func test_union() throws {
let expectedIDs = [
try db.run(users.insert(email <- "[email protected]")),
try db.run(users.insert(email <- "[email protected]"))
]
let query1 = users.filter(email == "[email protected]")
let query2 = users.filter(email == "[email protected]")
let actualIDs = try db.prepare(query1.union(query2)).map { (try $0.unwrapOrThrow())[id] }
XCTAssertEqual(expectedIDs, actualIDs)
let query3 = users.select(users[*], Expression<Int>(literal: "1 AS weight")).filter(email == "[email protected]")
let query4 = users.select(users[*], Expression<Int>(literal: "2 AS weight")).filter(email == "[email protected]")
print(query3.union(query4).order(Expression<Int>(literal: "weight")).asSQL())
let orderedIDs = try db.prepare(query3.union(query4).order(Expression<Int>(literal: "weight"), email)).map { (try $0.unwrapOrThrow())[id] }
XCTAssertEqual(Array(expectedIDs.reversed()), orderedIDs)
}
func test_no_such_column() throws {
let doesNotExist = Expression<String>("doesNotExist")
try! InsertUser("alice")
let row = try! db.pluck(users.filter(email == "[email protected]"))!
XCTAssertThrowsError(try row.get(doesNotExist)) { error in
if case QueryError.noSuchColumn(let name, _) = error {
XCTAssertEqual("\"doesNotExist\"", name)
} else {
XCTFail("unexpected error: \(error)")
}
}
}
func test_catchConstraintError() {
try! db.run(users.insert(email <- "[email protected]"))
do {
try db.run(users.insert(email <- "[email protected]"))
XCTFail("expected error")
} catch let Result.error(_, code, _) where code == SQLITE_CONSTRAINT {
// expected
} catch let error {
XCTFail("unexpected error: \(error)")
}
}
}
| 38.252302 | 180 | 0.601367 |
21259e2b02db209e2dca8262ca01e31dd0c145ed | 865 | //
// AccountController.swift
// Swiper
//
// Created by Charlie Wang on 11/14/16.
// Copyright © 2016 BookishParakeet. All rights reserved.
//
import UIKit
class AccountController: UIViewController {
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.027778 | 106 | 0.671676 |
221587f85c095a922ff80b373db06ed326fb293a | 6,123 | // RUN: %empty-directory(%t)
// RUN: %swiftppc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %swiftppc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s -sdk %S/../Inputs/clang-importer-sdk -Xfrontend -foo -Xfrontend -bar -Xllvm -baz -Xcc -garply -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks -I /path/to/headers -I path/to/more/headers -module-cache-path /tmp/modules -incremental 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftppc_driver -driver-print-jobs -dump-ast -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ast.txt
// RUN: %FileCheck %s < %t.ast.txt
// RUN: %FileCheck -check-prefix AST-STDOUT %s < %t.ast.txt
// RUN: %swiftppc_driver -driver-print-jobs -dump-ast -target x86_64-apple-macosx10.9 %s -o output.ast > %t.ast.txt
// RUN: %FileCheck %s < %t.ast.txt
// RUN: %FileCheck -check-prefix AST-O %s < %t.ast.txt
// RUN: %swiftppc_driver -driver-print-jobs -emit-silgen -target x86_64-apple-macosx10.9 %s 2>&1 > %t.silgen.txt
// RUN: %FileCheck %s < %t.silgen.txt
// RUN: %FileCheck -check-prefix SILGEN %s < %t.silgen.txt
// RUN: %swiftppc_driver -driver-print-jobs -emit-sil -target x86_64-apple-macosx10.9 %s 2>&1 > %t.sil.txt
// RUN: %FileCheck %s < %t.sil.txt
// RUN: %FileCheck -check-prefix SIL %s < %t.sil.txt
// RUN: %swiftppc_driver -driver-print-jobs -emit-ir -target x86_64-apple-macosx10.9 %s 2>&1 > %t.ir.txt
// RUN: %FileCheck %s < %t.ir.txt
// RUN: %FileCheck -check-prefix IR %s < %t.ir.txt
// RUN: %swiftppc_driver -driver-print-jobs -emit-bc -target x86_64-apple-macosx10.9 %s 2>&1 > %t.bc.txt
// RUN: %FileCheck %s < %t.bc.txt
// RUN: %FileCheck -check-prefix BC %s < %t.bc.txt
// RUN: %swiftppc_driver -driver-print-jobs -S -target x86_64-apple-macosx10.9 %s 2>&1 > %t.s.txt
// RUN: %FileCheck %s < %t.s.txt
// RUN: %FileCheck -check-prefix ASM %s < %t.s.txt
// RUN: %swiftppc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s 2>&1 > %t.c.txt
// RUN: %FileCheck %s < %t.c.txt
// RUN: %FileCheck -check-prefix OBJ %s < %t.c.txt
// RUN: not %swiftppc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %s 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: cp %s %t
// RUN: not %swiftppc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %t/driver-compile.swift 2>&1 | %FileCheck -check-prefix DUPLICATE-NAME %s
// RUN: %swiftppc_driver -driver-print-jobs -c -target x86_64-apple-macosx10.9 %s %S/../Inputs/empty.swift -module-name main -driver-filelist-threshold=0 2>&1 | %FileCheck -check-prefix=FILELIST %s
// RUN: %empty-directory(%t)/DISTINCTIVE-PATH/usr/bin/
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftppc)
// RUN: ln -s "swiftppc" %t/DISTINCTIVE-PATH/usr/bin/swift-update
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftppc -driver-print-jobs -c -update-code -target x86_64-apple-macosx10.9 %s 2>&1 > %t.upd.txt
// RUN: %FileCheck -check-prefix UPDATE-CODE %s < %t.upd.txt
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftppc
// RUN: %swiftppc_driver -driver-print-jobs -whole-module-optimization -incremental %s 2>&1 > %t.wmo-inc.txt
// RUN: %FileCheck %s < %t.wmo-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.wmo-inc.txt
// RUN: %swiftppc_driver -driver-print-jobs -embed-bitcode -incremental %s 2>&1 > %t.embed-inc.txt
// RUN: %FileCheck %s < %t.embed-inc.txt
// RUN: %FileCheck -check-prefix NO-REFERENCE-DEPENDENCIES %s < %t.embed-inc.txt
// REQUIRES: CODEGENERATOR=X86
// CHECK: bin{{/|\\\\}}swift
// CHECK: Driver{{/|\\\\}}driver-compile.swift
// CHECK: -o
// COMPLEX: bin{{/|\\\\}}swift
// COMPLEX: -c
// COMPLEX: Driver{{/|\\\\}}driver-compile.swift
// COMPLEX-DAG: -sdk {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -foo -bar
// COMPLEX-DAG: -Xllvm -baz
// COMPLEX-DAG: -Xcc -garply
// COMPLEX-DAG: -F /path/to/frameworks -Fsystem /path/to/systemframeworks -F /path/to/more/frameworks
// COMPLEX-DAG: -I /path/to/headers -I path/to/more/headers
// COMPLEX-DAG: -module-cache-path /tmp/modules
// COMPLEX-DAG: -emit-reference-dependencies-path {{(.*(/|\\))?driver-compile[^ /]+}}.swiftdeps
// COMPLEX: -o {{.+}}.o
// AST-STDOUT: bin{{/|\\\\}}swift
// AST-STDOUT: -dump-ast
// AST-STDOUT: -o -
// AST-O: bin{{/|\\\\}}swift
// AST-O: -dump-ast
// AST-O: -o output.ast
// SILGEN: bin{{/|\\\\}}swift
// SILGEN: -emit-silgen
// SILGEN: -o -
// SIL: bin{{/|\\\\}}swift
// SIL: -emit-sil{{ }}
// SIL: -o -
// IR: bin{{/|\\\\}}swift
// IR: -emit-ir
// IR: -o -
// BC: bin{{/|\\\\}}swift
// BC: -emit-bc
// BC: -o {{[^-]}}
// ASM: bin{{/|\\\\}}swift
// ASM: -S{{ }}
// ASM: -o -
// OBJ: bin{{/|\\\\}}swift
// OBJ: -c{{ }}
// OBJ: -o {{[^-]}}
// DUPLICATE-NAME: error: filename "driver-compile.swift" used twice: '{{.*}}test{{[/\\]}}Driver{{[/\\]}}driver-compile.swift' and '{{.*}}driver-compile.swift'
// DUPLICATE-NAME: note: filenames are used to distinguish private declarations with the same name
// FILELIST: bin{{/|\\\\}}swift
// FILELIST: -filelist [[SOURCES:(["][^"]+sources[^"]+["]|[^ ]+sources[^ ]+)]]
// FILELIST: -primary-filelist {{(["][^"]+primaryInputs[^"]+["]|[^ ]+primaryInputs[^ ]+)}}
// FILELIST: -supplementary-output-file-map {{(["][^"]+supplementaryOutputs[^"]+["]|[^ ]+supplementaryOutputs[^ ]+)}}
// FILELIST: -output-filelist {{[^-]}}
// FILELIST-NEXT: bin{{/|\\\\}}swift
// FILELIST: -filelist [[SOURCES]]
// FILELIST: -primary-filelist {{(["][^"]+primaryInputs[^"]+["]|[^ ]+primaryInputs[^ ]+)}}
// FILELIST: -supplementary-output-file-map {{(["][^"]+supplementaryOutputs[^"]+["]|[^ ]+supplementaryOutputs[^ ]+)}}
// FILELIST: -output-filelist {{[^-]}}
// UPDATE-CODE: DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}swift
// UPDATE-CODE: -frontend -c
// UPDATE-CODE: -emit-remap-file-path {{.+}}.remap
// NO-REFERENCE-DEPENDENCIES: bin{{/|\\\\}}swift
// NO-REFERENCE-DEPENDENCIES-NOT: -emit-reference-dependencies
| 44.693431 | 369 | 0.646415 |
d58693e00b72899c97ba45ce7e33a57c5b134a95 | 7,766 | //
// AppDelegate.swift
// Mhusic
//
// Created by Juan David Cruz Serrano on 7/16/16.
// Copyright © 2016 dhamova. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, SPTAudioStreamingDelegate {
var window: UIWindow?
var spotifySession: SPTSession!
var spotifyPlayer: SPTAudioStreamingController!
var userSession: SPTSession!
var currentUser: SPTUser!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
SPTAuth.defaultInstance().clientID = "9439315b7013474a9f83e3048d1eb45d"
SPTAuth.defaultInstance().redirectURL = NSURL(string: "mhusic://callback")
SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope]
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if SPTAuth.defaultInstance().canHandleURL(url) {
SPTAuth.defaultInstance().handleAuthCallbackWithTriggeredAuthURL(url, callback: { (error, session) in
if error != nil {
print("Error: \(error)")
} else {
self.userSession = session
self.spotifyPlayer = SPTAudioStreamingController.sharedInstance()
self.spotifyPlayer.delegate = self
do {
try self.spotifyPlayer.startWithClientId(SPTAuth.defaultInstance().clientID)
self.spotifyPlayer.loginWithAccessToken(session.accessToken)
} catch _ {
}
}
})
}
return false;
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.dhamova.Mhusic" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Mhusic", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 46.783133 | 291 | 0.670229 |
18a280b140c393ec18e3efaec60598302221a5f3 | 1,795 | //
// Created by Jim van Zummeren on 08/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
/*
* Image view that can retrieve images from a remote http location
*/
class RemoteImageView: UIImageView {
let file: String
let altText: String
init(file: String, altText: String) {
self.file = file
self.altText = altText
super.init(frame: CGRect.zero)
contentMode = .scaleAspectFit
if let image = UIImage(named: file) {
self.image = image
self.addAspectConstraint()
} else if let url = URL(string: file) {
loadImageFromURL(url.addHTTPSIfSchemeIsMissing())
} else {
print("Should display alt text instead: \(altText)")
}
}
// MARK: Private
private func loadImageFromURL(_ url: URL) {
DispatchQueue.global(qos: .default).async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async(execute: {
if let data = data, let image = UIImage(data: data) {
self.image = image
self.addAspectConstraint()
}
})
}
}
private func addAspectConstraint() {
if let image = image {
let constraint = NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: image.size.height / image.size.width,
constant: 0
)
self.addConstraint(constraint)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 23.933333 | 69 | 0.545961 |
640a3c75b9d57fde7cbe9a5247ad0f848b4c11ff | 2,070 | import SwiftSyntaxHighlighter
import Highlighter
import Xcode
import Pygments
import ArgumentParser
import Foundation
let fileManager = FileManager.default
let fileAttributes: [FileAttributeKey : Any] = [.posixPermissions: 0o744]
var standardInput = FileHandle.standardInput
var standardOutput = FileHandle.standardOutput
var standardError = FileHandle.standardError
struct SwiftHighlight: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "A utility for syntax highlighting Swift code.",
version: "1.2.0"
)
enum Scheme: String, ExpressibleByArgument {
case xcode
case pygments
static var `default`: Scheme = .xcode
var type: TokenizationScheme.Type {
switch self {
case .xcode:
return Xcode.self
case .pygments:
return Pygments.self
}
}
}
struct Options: ParsableArguments {
@Argument(help: "Swift code or a path to a Swift file")
var input: String?
@Option(name: .shortAndLong,
help: "The tokenization scheme.")
var scheme: Scheme = .default
}
@OptionGroup()
var options: Options
func run() throws {
let scheme = options.scheme.type
var output: String
if let input = options.input {
if fileManager.fileExists(atPath: input) {
let url = URL(fileURLWithPath: input)
output = try SwiftSyntaxHighlighter.highlight(file: url, using: scheme)
} else {
output = try SwiftSyntaxHighlighter.highlight(source: input, using: scheme)
}
} else {
let inputData = standardInput.readDataToEndOfFile()
let source = String(data: inputData, encoding: .utf8)!
output = try SwiftSyntaxHighlighter.highlight(source: source, using: scheme)
}
if let data = output.data(using: .utf8) {
standardOutput.write(data)
}
}
}
SwiftHighlight.main()
| 27.972973 | 91 | 0.622705 |
16e15da66d228203e864a0cb728e9fe42cadef20 | 1,914 | import UIKit
import Flutter
public class SwiftLblelinkpluginPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "lblelinkplugin", binaryMessenger: registrar.messenger())
let instance = SwiftLblelinkpluginPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
LMLBEventChannelSupport.register(with: registrar);
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let dict = call.arguments as? [String:String]
switch call.method {
case "initLBSdk":
LMLBSDKManager.shareInstance.initLBSDK(appid: dict?["iosAppid"] ?? "", secretKey: dict?["iosSecretKey"] ?? "",result: result);
break
case "beginSearchEquipment":
LMLBSDKManager.shareInstance.beginSearchEquipment()
break
case "connectToService":
LMLBSDKManager.shareInstance.linkToService(ipAddress: dict?["ipAddress"] ?? "");
break
case "disConnect":
LMLBSDKManager.shareInstance.disConnect();
break
case "pause":
LBPlayerManager.shareInstance.pause();
break
case "resumePlay":
LBPlayerManager.shareInstance.resumePlay();
break
case "stop":
LBPlayerManager.shareInstance.stop();
break
case "play":
LBPlayerManager.shareInstance.beginPlay(connection: LMLBSDKManager.shareInstance.linkConnection, playUrl: dict?["playUrlString"] ?? "",header: dict?["header"] ?? "");
break
case "getLastConnectService":
LMLBSDKManager.shareInstance.getLastConnectService(result: result)
break
default:
result(FlutterMethodNotImplemented)
break;
}
//result("iOS " + UIDevice.current.systemVersion)
}
}
| 33.578947 | 178 | 0.65674 |
fcafa07b7eaa4ccae46c9a0e9b03f0a25b406e3c | 1,613 | //
// SFCollectionViewCell.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 10/02/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
open class SFCollectionViewCell: UICollectionViewCell, SFViewColorStyle, SFLayoutView {
// MARK: - Class Properties
open class var identifier: String {
return "SFCollectionViewCell"
}
// MARK: - Instance Properties
open var customConstraints: Constraints = []
open var automaticallyAdjustsColorStyle: Bool = true
open var useAlternativeColors: Bool = false
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
prepareSubviews()
setConstraints()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Instance Methods
open func prepareSubviews() {
if automaticallyAdjustsColorStyle {
updateColors()
}
}
open func setConstraints() {
}
open func updateColors() {
backgroundColor = useAlternativeColors ? colorStyle.alternativeColor : colorStyle.mainColor
updateSubviewsColors()
}
public func updateSubviewsColors() {
for view in self.contentView.subviews {
if let subview = view as? SFViewColorStyle {
if subview.automaticallyAdjustsColorStyle == true {
subview.updateColors()
}
}
}
}
}
| 24.074627 | 99 | 0.608184 |
fe3881453346ac00af28304af27fd79a2da349e0 | 1,682 | //
// MockBase.swift
// web
//
// Created by Azmi SAHIN on 27/08/2017.
// Copyright © 2017 Azmi SAHIN. All rights reserved.
//
// MARK: - Mock Base
/// Base
///
/// Mock Taban Model
///
/// - Parameters:
///
/// - Returns: Base
///
/// Usage
///
/// let mockBase = MockBase()
///
@testable import web
public class MockBase
{
// MARK: - Property
/// E-Mail
public var Email : String = ""
/// Kullanici Adi
public var UserName : String = ""
/// Parola
public var Password : String = ""
/// Grant
public var Grant : Bool = false
/// Sipariş Numarası
public var OrderId : Int = -1
/// Sipariş Satır Numarası
public var OrderLine : Int = -1
/// Domain
public var Domain : String = ""
/// Protokol
public var DomainProtocol : String = ""
/// Servis Adresi
public var DomainApi : String = ""
/// Servis Uugulaması
public var DomainApiApplication : String = ""
/// Servis Version Numarası
public var DomainApiApplicationVersion : String = ""
/// Servis Erişim Türü
public var GrantType : String = ""
/// Initalize
init() {
Email = "[email protected]"
UserName = "test"
Password = "password"
Grant = true
OrderId = 0
OrderLine = 0
Domain = "azmisahin.com"
DomainProtocol = "http"
DomainApi = "api.azmisahin.com"
DomainApiApplication = "ios"
DomainApiApplicationVersion = "v1"
GrantType = "password"
}
/// Test Performans Kontrol
public var testPerformance : Bool = true
}
| 20.02381 | 57 | 0.550535 |
564bb3ed4f1de8854f407b6f97f978fac369227d | 3,537 | //
// FITFitValueStatistics.swift
// GarminConnect
//
// Created by Brice Rosenzweig on 31/12/2016.
// Copyright © 2016 Brice Rosenzweig. All rights reserved.
//
import Foundation
import RZFitFile
class FITFitValueStatistics: NSObject {
enum StatsType : String {
case avg = "avg", total = "total", min = "min", max = "max", count = "count"
}
var distanceMeters : Double = 0
var timeSeconds : Double = 0
var sum : GCNumberWithUnit? = nil
var count : UInt = 0
var max : GCNumberWithUnit? = nil
var min : GCNumberWithUnit? = nil
var nonZeroSum :GCNumberWithUnit? = nil
var nonZeroCount : UInt = 0
func value(stats: StatsType, field: RZFitFieldKey?) -> GCNumberWithUnit?{
switch stats {
case StatsType.avg:
return self.sum?.numberWithUnitMultiplied(by: 1.0/Double(self.count))
case StatsType.total:
if let field = field {
if field.hasSuffix("distance"){
return GCNumberWithUnit(GCUnit.meter(), andValue: self.distanceMeters)
}
else if field.hasSuffix("time"){
return GCNumberWithUnit(GCUnit.second(), andValue: self.timeSeconds)
}else{
return self.sum
}
}else {
return self.sum
}
case StatsType.count:
return GCNumberWithUnit(GCUnit.dimensionless(), andValue: Double(self.count))
case StatsType.max:
return self.max
case StatsType.min:
return self.min
}
}
func preferredStatisticsForField(fieldKey : RZFitFieldKey) -> [StatsType] {
if( fieldKey.hasPrefix("total")){
return [StatsType.total,StatsType.count]
}else if( fieldKey.hasPrefix("max") || fieldKey.hasPrefix("avg") || fieldKey.hasPrefix("min") || fieldKey.hasPrefix( "enhanced" )){
return [StatsType.avg,StatsType.count,StatsType.max,StatsType.min]
}else{
if let field = FITFitEnumMap.activityField(fromFitField: fieldKey, forActivityType: nil){
if field.isWeightedAverage() || field.isMax() || field.isMin() || field.validForGraph(){
return [StatsType.avg,StatsType.count,StatsType.max,StatsType.min]
}else if field.canSum() {
return [StatsType.total,StatsType.count]
}
}
}
// fall back
return [StatsType.count]
}
func add(fieldValue: RZFitFieldValue, weight : FITFitStatisticsWeight){
if let nu = fieldValue.numberWithUnit {
self.count += 1
self.timeSeconds += weight.time
self.distanceMeters += weight.distance
if sum == nil {
self.sum = nu
}else{
self.sum = self.sum?.add(nu, weight: 1.0)
}
if max == nil {
self.max = nu
}else{
self.max = self.max?.maxNumber(nu)
}
if min == nil {
self.min = nu
}else{
self.min = self.min?.minNumber(nu)
}
if fabs(nu.value) > 1.0e-8 {
nonZeroCount += 1
if nonZeroSum == nil{
nonZeroSum = nu
}else{
nonZeroSum = nonZeroSum?.add(nu, weight: 1.0)
}
}
}
}
}
| 33.056075 | 139 | 0.529545 |
e4cbade0c4a832ea038c104814abb9054b1bb16a | 3,289 | /*:
[< Previous](@previous) [Home](Introduction) [Next >](@next)
## Basic Examples With Modifiers
This page demonstrates some simple examples of using SFSymbols and applying size and color modifiers.
> Symbols can accept some text and image modifiers\
[Documentation](https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/)
*/
import SwiftUI
import PlaygroundSupport
struct Example1: View {
var body: some View {
SampleView(title: "Modify as an Image") {
Image(systemName: "cloud")
.imageScale(.large)
.foregroundStyle(Color.blue)
}
}
}
struct Example2: View {
var body: some View {
SampleView(title: "Modify as Text") {
Image(systemName: "umbrella")
.font(.largeTitle)
.foregroundColor(.green)
}
}
}
struct Example3: View {
var body: some View {
SampleView(title: "Mix and Match") {
Image(systemName: "sun.max")
.font(.system(size: 40, weight: .bold))
.foregroundStyle(.linearGradient(Gradient(colors: [.yellow,.red]), startPoint: .top, endPoint: .bottom))
}
}
}
struct Example4: View {
var body: some View {
SampleView(title: "More Mix and Match") {
VStack(alignment: .leading) {
Image(systemName: "wind.snow")
.font(.title)
Image(systemName: "wind.snow")
.imageScale(.large)
Image(systemName: "wind.snow")
.font(.title)
.imageScale(.large)
}
.foregroundColor(.gray)
}
}
}
struct Example5: View {
var body: some View {
SampleView(title: "As a Label") {
Button(role: .destructive) {
} label: {
Label("Delete", systemImage: "trash")
.font(.largeTitle)
}
}
}
}
struct Example6: View {
var body: some View {
SampleView(title: "Label Image Size only") {
VStack(alignment: .trailing) {
Label("Rain", systemImage: "cloud.drizzle")
Label("Rain", systemImage: "cloud.drizzle")
.imageScale(.large)
}
}
}
}
struct Example7: View {
var body: some View {
SampleView(title: "String Interpolation") {
Text("New idea **\(Image(systemName: "lightbulb"))**")
.foregroundColor(.yellow)
.font(.title)
}
}
}
struct PagePreview : View {
let title: String
var body: some View {
VStack {
Text(title).font(.largeTitle)
Divider()
VStack {
Example1()
Example2()
Example3()
Example4()
Example5()
Example6()
Example7()
}
}
.padding()
.overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 1))
.padding()
}
}
PlaygroundPage.current.setLiveView(PagePreview(title: "Basic Examples"))
| 21.219355 | 120 | 0.503192 |
ed046c1dfb0829feedb711bbcfb6a5f098422094 | 564 | //
// SplashResolution.swift
// ZhihuDaily
//
// Created by syxc on 15/12/5.
// Copyright © 2015年 syxc. All rights reserved.
//
import Foundation
/**
* 图像分辨率
*/
enum SplashResolution: String {
case _320 = "320*432"
case _480 = "480*728"
case _720 = "720*1184"
case _1080 = "1080*1776"
static let allValues = [_320, _480, _720, _1080]
var description: String {
return self.rawValue
}
var debugDescription: String {
return "SplashResolution (rawValue: \(rawValue))"
}
var raw: String {
return description
}
}
| 16.114286 | 53 | 0.634752 |
f73b9301ace9335cb93746eb56a6d08dcc49d6de | 1,808 | //
// UsersTableViewController.swift
// PeopleAndAppleStockPrices
//
// Created by David Rifkin on 9/9/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import UIKit
class UsersTableViewController: UIViewController {
var users = [User](){
didSet {
userTableView.reloadData()
}
}
var searchedText = "" {
didSet {
userTableView.reloadData()
}
}
var filteredUsers: [User] {
guard searchedText != "" else { return users }
return users.filter{ $0.name.fullName.lowercased().contains(searchedText.lowercased())
}
}
@IBOutlet weak var usersSearchBar: UISearchBar!
@IBOutlet weak var userTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
loadUsers()
userTableView.dataSource = self
usersSearchBar.delegate = self
}
private func loadUsers() {
users = User.getUsers()
}
}
extension UsersTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let user = filteredUsers[indexPath.row]
let subtitleCell = userTableView.dequeueReusableCell(withIdentifier: "subtitleCell", for: indexPath)
subtitleCell.textLabel?.text = user.name.fullName.capitalized
subtitleCell.detailTextLabel?.text = user.location.address
return subtitleCell
}
}
extension UsersTableViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchedText = searchText
}
}
| 27.393939 | 108 | 0.661504 |
5d07bc69040b42c716003404c54813572ca7cd53 | 2,787 | //
// SceneDelegate.swift
// SwiftUIGeometryReaderTutorial
//
// Created by Arthur Knopper on 15/11/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.876923 | 147 | 0.708647 |
e2b228a8ff3ee4b7e9122b638688f5308586571e | 352 | extension List {
// Reverses the elements of the list in place.
public mutating func reverse() {
let temp = firstNode
firstNode = lastNode
lastNode = temp
}
// Returns a view presenting the elements of the list in reverse order.
public func reversed() -> List {
var list = clone(self)
list.reverse()
return list
}
} | 23.466667 | 73 | 0.661932 |
b97fb10814aa9e364336ef0b5d5513296d0d4c62 | 1,003 | //
// SX_GuideViewController.swift
// ShixiUS
//
// Created by Michael 柏 on 6/19/18.
// Copyright © 2018 Shixi (Beijing) Tchnology Limited. All rights reserved.
//
/*
如果有一天你觉得越相爱越是场意外
那就请你悄悄在月光下
找个男孩把我取代
*/
import UIKit
class SX_GuideViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
}
// =========================================================
// MARK: - Other Method
// =========================================================
extension SX_GuideViewController {
func setUI() {
// gif和jpg类型的资源数组
let imageGifArray = ["引导页1", "引导页2", "引导页3"]
let guideView = SX_GuidePageView.init(images: imageGifArray, loginRegistCompletion: {
SXLog("登录/注册")
}) {
SXLog("开始使用App")
let tabVC = SX_TabBarController()
UIApplication.shared.keyWindow?.rootViewController = tabVC
}
self.view.addSubview(guideView)
}
}
| 23.880952 | 97 | 0.541376 |
fbfd7eb86c575a7add88061177495f1433e5166b | 11,948 | //
// Copyright (c) 2019 Reimar Twelker
//
// 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
/// Draws two colored lines at the bottom on top of one another that extend from the left to the right edge.
///
/// The foreground line is initially not visible. It can be expanded to fully cover the background line.
/// The expansion can be animated in different ways.
///
/// - Note
/// The view is meant to be used with `RAGTextField`. Set it as the `textBackgroundView` to approximate the look and feel of a
/// Material text field. The expansion of the line has to be controlled manually, for example from the text field delegate.
open class UnderlineView: UIView {
/// The different ways in which the expanding line is animated.
public enum Mode {
/// The line equally expands from the center of the view to its left and right edges.
case expandsFromCenter
/// The line expands from the right edge of the view to the left.
case expandsFromRight
/// The line expands from the left edge of the view to the right.
case expandsFromLeft
/// The line expands from the leading edge of the view to the trailing one.
case expandsInUserInterfaceDirection
/// The line is not animated.
case notAnimated
}
/// The width of both the foreground line in points.
@IBInspectable open var foregroundLineWidth: CGFloat = 1.0 {
didSet {
heightConstraint?.constant = foregroundLineWidth
}
}
/// The color of the background line.
@IBInspectable open var backgroundLineColor: UIColor = .clear {
didSet {
underlineBackgroundView.backgroundColor = backgroundLineColor
}
}
/// The color of the foreground line.
@IBInspectable open var foregroundLineColor: UIColor = .black {
didSet {
underlineView.backgroundColor = foregroundLineColor
}
}
/// The way the foreground line is expanded.
open var expandMode: Mode = .expandsFromCenter {
didSet {
setNeedsUpdateConstraints()
}
}
/// The duration of the animation of the foreground line.
open var expandDuration: TimeInterval = 0.2
private let underlineView = UIView()
private let underlineBackgroundView = UIView()
/// Used to pin the foreground line to the leading edge of the view.
///
/// Enabled and disabled depending on the `expandMode` value.
private var leadingConstraint: NSLayoutConstraint?
/// Used to pin the foreground line to the trailing edge of the view.
///
/// Enabled and disabled depending on the `expandMode` value.
private var trailingConstraint: NSLayoutConstraint?
/// Used to animate the foreground line.
private var widthConstraint: NSLayoutConstraint?
/// Updated when `lineWidth` is changed.
private var heightConstraint: NSLayoutConstraint?
/// If `true`, the foreground line is currently expanded.
private var isExpanded = false
/// Whether the underline is animated when the associated text field begins editing.
///
/// If `false`, the underline is updated but not animated. The default value is `true`.
///
/// - Note
/// For this property to take effect, the `textField` property must be set.
open var animatesWhenEditingBegins = true
/// Whether the underline is animated when the associated text field ends editing.
///
/// If `false`, the underline is updated but not animated. The default value is `true`.
///
/// - Note
/// For this property to take effect, the `textField` property must be set.
open var animatesWhenEditingEnds = true
/// Refers to the text field whose editing state is used to update the appearance of the underline automatically.
///
/// If `nil`, the appearance of the underline must be updated manually, for example from a view controller or text field delegate.
open weak var textField: UITextField? {
didSet {
if let oldTextField = oldValue {
stopObserving(oldTextField)
}
if let newTextField = textField {
startObserving(newTextField)
}
}
}
/// The tint color of the `UIView` overwrites the current `expandedLineColor`.
open override var tintColor: UIColor! {
didSet {
foregroundLineColor = tintColor
}
}
/// Returns the layout direction, if the textfield object is of `RAGTextfield`, returns its direction. Otherwise, returns the device's direction.
var layoutDirection: UIUserInterfaceLayoutDirection {
guard let textField = textField as? RAGTextField else { return UIApplication.shared.userInterfaceLayoutDirection }
return textField.layoutDirection
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
addSubview(underlineBackgroundView)
addSubview(underlineView)
setUpUnderlineBackground()
setUpUnderline()
}
/// Sets up the underline background view. Sets properties and configures constraints.
private func setUpUnderlineBackground() {
underlineBackgroundView.backgroundColor = backgroundLineColor
underlineBackgroundView.translatesAutoresizingMaskIntoConstraints = false
let views = ["v": underlineBackgroundView]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v]|", options: [], metrics: nil, views: views))
// Cling to the bottom of the view
underlineBackgroundView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
// Always be as high as the underline
let onePixel = 1.0 / UIScreen.main.scale
underlineBackgroundView.heightAnchor.constraint(equalToConstant: onePixel).isActive = true
}
/// Sets up the underline view. Sets properties and configures constraints.
private func setUpUnderline() {
underlineView.backgroundColor = foregroundLineColor
underlineView.translatesAutoresizingMaskIntoConstraints = false
// Cling to the bottom of the view
underlineView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
heightConstraint = underlineView.heightAnchor.constraint(equalToConstant: foregroundLineWidth)
heightConstraint?.isActive = true
// (De)activating the higher priority width constraint animates the underline
widthConstraint = underlineView.widthAnchor.constraint(equalTo: widthAnchor)
widthConstraint?.priority = .defaultHigh
let zeroWidthConstraint = underlineView.widthAnchor.constraint(equalToConstant: 0.0)
zeroWidthConstraint.priority = .defaultHigh - 1
zeroWidthConstraint.isActive = true
leadingConstraint = underlineView.leadingAnchor.constraint(equalTo: leadingAnchor)
// Do not activate just yet
trailingConstraint = underlineView.trailingAnchor.constraint(equalTo: trailingAnchor)
// Do not activate just yet
// Center with low priority
let centerConstraint = underlineView.centerXAnchor.constraint(equalTo: centerXAnchor)
centerConstraint.priority = .defaultLow
centerConstraint.isActive = true
setNeedsUpdateConstraints()
}
private func stopObserving(_ textField: UITextField) {
NotificationCenter.default.removeObserver(self, name: UITextField.textDidBeginEditingNotification, object: textField)
NotificationCenter.default.removeObserver(self, name: UITextField.textDidEndEditingNotification, object: textField)
}
private func startObserving(_ textField: UITextField) {
NotificationCenter.default.addObserver(self,
selector: #selector(onDidBeginEditing(_:)),
name: UITextField.textDidBeginEditingNotification,
object: textField)
NotificationCenter.default.addObserver(self,
selector: #selector(onDidEndEditing(_:)),
name: UITextField.textDidEndEditingNotification,
object: textField)
}
@objc private func onDidBeginEditing(_ notification: Notification) {
setExpanded(true, animated: animatesWhenEditingBegins)
}
@objc private func onDidEndEditing(_ notification: Notification) {
setExpanded(false, animated: animatesWhenEditingEnds)
}
open override func updateConstraints() {
// Enable the leading and trailing constraints depending on the `expandMode`.
switch expandMode {
case .expandsFromCenter, .notAnimated:
leadingConstraint?.isActive = false
trailingConstraint?.isActive = false
case .expandsFromRight where layoutDirection == .leftToRight:
leadingConstraint?.isActive = false
trailingConstraint?.isActive = true
case .expandsFromRight:
leadingConstraint?.isActive = true
trailingConstraint?.isActive = false
case .expandsFromLeft where layoutDirection == .leftToRight:
leadingConstraint?.isActive = true
trailingConstraint?.isActive = false
case .expandsFromLeft:
leadingConstraint?.isActive = false
trailingConstraint?.isActive = true
case .expandsInUserInterfaceDirection:
leadingConstraint?.isActive = true
trailingConstraint?.isActive = false
}
super.updateConstraints()
}
/// Sets the foreground line to its expanded or contracted state depending on the given parameter. Optionally, the change is animated.
///
/// - Parameters:
/// - expanded: If `true`, the line is expanded.
/// - animated: If `true`, the change is animated.
open func setExpanded(_ expanded: Bool, animated: Bool) {
guard expanded != isExpanded else {
return
}
widthConstraint?.isActive = expanded
if animated && expandMode != .notAnimated {
UIView.animate(withDuration: expandDuration) { [unowned self] in
self.layoutIfNeeded()
}
}
isExpanded = expanded
}
}
| 40.228956 | 149 | 0.656763 |
fc3781feb7409f292954df46528b582f7e3b5852 | 38,218 | /**
* Copyright (c) 2017 Håvard Fossli.
*
* Licensed under the MIT license, as follows:
*
* 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
import LocalAuthentication
@available(OSX 10.12.1, iOS 9.0, *)
public enum EllipticCurveKeyPair {
public typealias Logger = (String) -> ()
public static var logger: Logger?
public struct Config {
// The label used to identify the public key in keychain
public var publicLabel: String
// The label used to identify the private key on the secure enclave
public var privateLabel: String
// The text presented to the user about why we need his/her fingerprint / device pin
// If you are passing an LAContext to sign or decrypt this value will be rejected
public var operationPrompt: String?
// The access control used to manage the access to the public key
public var publicKeyAccessControl: AccessControl
// The access control used to manage the access to the private key
public var privateKeyAccessControl: AccessControl
// The access group e.g. "BBDV3R8HVV.no.agens.demo"
// Useful for shared keychain items
public var publicKeyAccessGroup: String?
// The access group e.g. "BBDV3R8HVV.no.agens.demo"
// Useful for shared keychain items
public var privateKeyAccessGroup: String?
// Should it be stored on .secureEnclave or in .keychain ?
public var token: Token
public init(publicLabel: String,
privateLabel: String,
operationPrompt: String?,
publicKeyAccessControl: AccessControl,
privateKeyAccessControl: AccessControl,
publicKeyAccessGroup: String? = nil,
privateKeyAccessGroup: String? = nil,
token: Token) {
self.publicLabel = publicLabel
self.privateLabel = privateLabel
self.operationPrompt = operationPrompt
self.publicKeyAccessControl = publicKeyAccessControl
self.privateKeyAccessControl = privateKeyAccessControl
self.publicKeyAccessGroup = publicKeyAccessGroup
self.privateKeyAccessGroup = privateKeyAccessGroup
self.token = token
}
}
// A stateful and opiniated manager for using the secure enclave and keychain
// If the private or public key is not found this manager will naively just recreate a new keypair
// If the device doesn't have a Secure Enclave it will store the private key in keychain just like the public key
//
// If you think this manager is "too smart" in that sense you may use this manager as an example
// and create your own manager
public final class Manager {
private let config: Config
private let helper: Helper
private var cachedPublicKey: PublicKey? = nil
private var cachedPrivateKey: PrivateKey? = nil
public init(config: Config) {
self.config = config
self.helper = Helper(config: config)
}
public func deleteKeyPair() throws {
clearCache()
try helper.delete()
}
public func publicKey() throws -> PublicKey {
do {
if let key = cachedPublicKey {
return key
}
let key = try helper.getPublicKey()
cachedPublicKey = key
return key
} catch EllipticCurveKeyPair.Error.underlying(_, let underlying) where underlying.code == errSecItemNotFound {
let keys = try helper.generateKeyPair()
cachedPublicKey = keys.public
cachedPrivateKey = keys.private
return keys.public
} catch {
throw error
}
}
public func privateKey(context: LAContext? = nil) throws -> PrivateKey {
do {
if cachedPrivateKey?.context !== context {
cachedPrivateKey = nil
}
if let key = cachedPrivateKey {
return key
}
let key = try helper.getPrivateKey(context: context)
cachedPrivateKey = key
return key
} catch EllipticCurveKeyPair.Error.underlying(_, let underlying) where underlying.code == errSecItemNotFound {
if config.publicKeyAccessControl.flags.contains(.privateKeyUsage) == false, (try? helper.getPublicKey()) != nil {
throw Error.probablyAuthenticationError(underlying: underlying)
}
let keys = try helper.generateKeyPair(context: nil)
cachedPublicKey = keys.public
cachedPrivateKey = keys.private
return keys.private
} catch {
throw error
}
}
public func keys(context: LAContext? = nil) throws -> (`public`: PublicKey, `private`: PrivateKey) {
let privateKey = try self.privateKey(context: context)
let publicKey = try self.publicKey()
return (public: publicKey, private: privateKey)
}
public func clearCache() {
cachedPublicKey = nil
cachedPrivateKey = nil
}
@available(iOS 10, *)
public func sign(_ digest: Data, hash: Hash, context: LAContext? = nil) throws -> Data {
return try helper.sign(digest, privateKey: privateKey(context: context), hash: hash)
}
@available(OSX, unavailable)
@available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.")
public func signUsingSha256(_ digest: Data, context: LAContext? = nil) throws -> Data {
#if os(iOS)
return try helper.signUsingSha256(digest, privateKey: privateKey(context: context))
#else
throw Error.inconcistency(message: "Should be unreachable.")
#endif
}
@available(iOS 10, *)
public func verify(signature: Data, originalDigest: Data, hash: Hash) throws {
try helper.verify(signature: signature, digest: originalDigest, publicKey: publicKey(), hash: hash)
}
@available(OSX, unavailable)
@available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.")
public func verifyUsingSha256(signature: Data, originalDigest: Data) throws {
#if os(iOS)
try helper.verifyUsingSha256(signature: signature, digest: originalDigest, publicKey: publicKey())
#else
throw Error.inconcistency(message: "Should be unreachable.")
#endif
}
@available(iOS 10.3, *) // API available at 10.0, but bugs made it unusable on versions lower than 10.3
public func encrypt(_ digest: Data, hash: Hash = .sha256) throws -> Data {
return try helper.encrypt(digest, publicKey: publicKey(), hash: hash)
}
@available(iOS 10.3, *) // API available at 10.0, but bugs made it unusable on versions lower than 10.3
public func decrypt(_ encrypted: Data, hash: Hash = .sha256, context: LAContext? = nil) throws -> Data {
return try helper.decrypt(encrypted, privateKey: privateKey(context: context), hash: hash)
}
}
// Helper is a stateless class for querying the secure enclave and keychain
// You may create a small stateful facade around this
// `Manager` is an example of such an opiniated facade
public struct Helper {
// The user visible label in the device's key chain
public let config: Config
public func getPublicKey() throws -> PublicKey {
return try Query.getPublicKey(labeled: config.publicLabel, accessGroup: config.publicKeyAccessGroup)
}
public func getPrivateKey(context: LAContext? = nil) throws -> PrivateKey {
let context = context ?? LAContext()
return try Query.getPrivateKey(labeled: config.privateLabel, accessGroup: config.privateKeyAccessGroup, prompt: config.operationPrompt, context: context)
}
public func getKeys(context: LAContext? = nil) throws -> (`public`: PublicKey, `private`: PrivateKey) {
let privateKey = try getPrivateKey(context: context)
let publicKey = try getPublicKey()
return (public: publicKey, private: privateKey)
}
public func generateKeyPair(context: LAContext? = nil) throws -> (`public`: PublicKey, `private`: PrivateKey) {
guard config.privateLabel != config.publicLabel else{
throw Error.inconcistency(message: "Public key and private key can not have same label")
}
let context = context ?? LAContext()
let query = try Query.generateKeyPairQuery(config: config, token: config.token, context: context)
var publicOptional, privateOptional: SecKey?
logger?("SecKeyGeneratePair: \(query)")
let status = SecKeyGeneratePair(query as CFDictionary, &publicOptional, &privateOptional)
guard status == errSecSuccess else {
if status == errSecAuthFailed {
throw Error.osStatus(message: "Could not generate keypair. Security probably doesn't like the access flags you provided. Specifically if this device doesn't have secure enclave and you pass `.privateKeyUsage`. it will produce this error.", osStatus: status)
} else {
throw Error.osStatus(message: "Could not generate keypair.", osStatus: status)
}
}
guard let publicSec = publicOptional, let privateSec = privateOptional else {
throw Error.inconcistency(message: "Created private public key pair successfully, but weren't able to retreive it.")
}
let publicKey = PublicKey(publicSec)
let privateKey = PrivateKey(privateSec, context: context)
try Query.forceSavePublicKey(publicKey, label: config.publicLabel)
return (public: publicKey, private: privateKey)
}
public func delete() throws {
try Query.deletePublicKey(labeled: config.publicLabel, accessGroup: config.publicKeyAccessGroup)
try Query.deletePrivateKey(labeled: config.privateLabel, accessGroup: config.privateKeyAccessGroup)
}
@available(iOS 10.0, *)
public func sign(_ digest: Data, privateKey: PrivateKey, hash: Hash) throws -> Data {
Helper.logToConsoleIfExecutingOnMainThread()
var error : Unmanaged<CFError>?
let result = SecKeyCreateSignature(privateKey.underlying, hash.signatureMessage, digest as CFData, &error)
guard let signature = result else {
throw Error.fromError(error?.takeRetainedValue(), message: "Could not create signature.")
}
return signature as Data
}
@available(OSX, unavailable)
@available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.")
public func signUsingSha256(_ digest: Data, privateKey: PrivateKey) throws -> Data {
#if os(iOS)
Helper.logToConsoleIfExecutingOnMainThread()
let digestToSign = digest.sha256()
var digestToSignBytes = [UInt8](repeating: 0, count: digestToSign.count)
digestToSign.copyBytes(to: &digestToSignBytes, count: digestToSign.count)
var signatureBytes = [UInt8](repeating: 0, count: 128)
var signatureLength = 128
let signErr = SecKeyRawSign(privateKey.underlying, .PKCS1, &digestToSignBytes, digestToSignBytes.count, &signatureBytes, &signatureLength)
guard signErr == errSecSuccess else {
throw Error.osStatus(message: "Could not create signature.", osStatus: signErr)
}
let signature = Data(bytes: &signatureBytes, count: signatureLength)
return signature
#else
throw Error.inconcistency(message: "Should be unreachable.")
#endif
}
@available(iOS 10.0, *)
public func verify(signature: Data, digest: Data, publicKey: PublicKey, hash: Hash) throws {
var error : Unmanaged<CFError>?
let valid = SecKeyVerifySignature(publicKey.underlying, hash.signatureMessage, digest as CFData, signature as CFData, &error)
if let error = error?.takeRetainedValue() {
throw Error.fromError(error, message: "Could not verify signature.")
}
guard valid == true else {
throw Error.inconcistency(message: "Signature yielded no error, but still marks itself as unsuccessful")
}
}
@available(OSX, unavailable)
@available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.")
public func verifyUsingSha256(signature: Data, digest: Data, publicKey: PublicKey) throws {
#if os(iOS)
let sha = digest.sha256()
var shaBytes = [UInt8](repeating: 0, count: sha.count)
sha.copyBytes(to: &shaBytes, count: sha.count)
var signatureBytes = [UInt8](repeating: 0, count: signature.count)
signature.copyBytes(to: &signatureBytes, count: signature.count)
let status = SecKeyRawVerify(publicKey.underlying, .PKCS1, &shaBytes, shaBytes.count, &signatureBytes, signatureBytes.count)
guard status == errSecSuccess else {
throw Error.osStatus(message: "Could not verify signature.", osStatus: status)
}
#else
throw Error.inconcistency(message: "Should be unreachable.")
#endif
}
@available(iOS 10.3, *)
public func encrypt(_ digest: Data, publicKey: PublicKey, hash: Hash) throws -> Data {
var error : Unmanaged<CFError>?
let result = SecKeyCreateEncryptedData(publicKey.underlying, hash.encryptionEciesEcdh, digest as CFData, &error)
guard let data = result else {
throw Error.fromError(error?.takeRetainedValue(), message: "Could not encrypt.")
}
return data as Data
}
@available(iOS 10.3, *)
public func decrypt(_ encrypted: Data, privateKey: PrivateKey, hash: Hash) throws -> Data {
Helper.logToConsoleIfExecutingOnMainThread()
var error : Unmanaged<CFError>?
let result = SecKeyCreateDecryptedData(privateKey.underlying, hash.encryptionEciesEcdh, encrypted as CFData, &error)
guard let data = result else {
throw Error.fromError(error?.takeRetainedValue(), message: "Could not decrypt.")
}
return data as Data
}
public static func logToConsoleIfExecutingOnMainThread() {
if Thread.isMainThread {
let _ = LogOnce.shouldNotBeMainThread
}
}
}
private struct LogOnce {
static var shouldNotBeMainThread: Void = {
print("[WARNING] \(EllipticCurveKeyPair.self): Decryption and signing should be done off main thread because LocalAuthentication may need the thread to show UI. This message is logged only once.")
}()
}
private struct Query {
static func getKey(_ query: [String: Any]) throws -> SecKey {
var raw: CFTypeRef?
logger?("SecItemCopyMatching: \(query)")
let status = SecItemCopyMatching(query as CFDictionary, &raw)
guard status == errSecSuccess, let result = raw else {
throw Error.osStatus(message: "Could not get key for query: \(query)", osStatus: status)
}
return result as! SecKey
}
static func publicKeyQuery(labeled: String, accessGroup: String?) -> [String:Any] {
var params: [String:Any] = [
kSecClass as String: kSecClassKey,
kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
kSecAttrLabel as String: labeled,
kSecReturnRef as String: true,
]
if let accessGroup = accessGroup {
params[kSecAttrAccessGroup as String] = accessGroup
}
return params
}
static func privateKeyQuery(labeled: String, accessGroup: String?, prompt: String?, context: LAContext?) -> [String: Any] {
var params: [String:Any] = [
kSecClass as String: kSecClassKey,
kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
kSecAttrLabel as String: labeled,
kSecReturnRef as String: true,
]
if let accessGroup = accessGroup {
params[kSecAttrAccessGroup as String] = accessGroup
}
if let prompt = prompt {
params[kSecUseOperationPrompt as String] = prompt
}
if let context = context {
params[kSecUseAuthenticationContext as String] = context
}
return params
}
static func generateKeyPairQuery(config: Config, token: Token, context: LAContext? = nil) throws -> [String:Any] {
/* ========= private ========= */
var privateKeyParams: [String: Any] = [
kSecAttrLabel as String: config.privateLabel,
kSecAttrIsPermanent as String: true,
kSecUseAuthenticationUI as String: kSecUseAuthenticationUIAllow,
]
if let privateKeyAccessGroup = config.privateKeyAccessGroup {
privateKeyParams[kSecAttrAccessGroup as String] = privateKeyAccessGroup
}
if let context = context {
privateKeyParams[kSecUseAuthenticationContext as String] = context
}
// On iOS 11 and lower: access control with empty flags doesn't work
if !config.privateKeyAccessControl.flags.isEmpty {
privateKeyParams[kSecAttrAccessControl as String] = try config.privateKeyAccessControl.underlying()
} else {
privateKeyParams[kSecAttrAccessible as String] = config.privateKeyAccessControl.protection
}
/* ========= public ========= */
var publicKeyParams: [String: Any] = [
kSecAttrLabel as String: config.publicLabel,
]
if let publicKeyAccessGroup = config.publicKeyAccessGroup {
publicKeyParams[kSecAttrAccessGroup as String] = publicKeyAccessGroup
}
// On iOS 11 and lower: access control with empty flags doesn't work
if !config.publicKeyAccessControl.flags.isEmpty {
publicKeyParams[kSecAttrAccessControl as String] = try config.publicKeyAccessControl.underlying()
} else {
publicKeyParams[kSecAttrAccessible as String] = config.publicKeyAccessControl.protection
}
/* ========= combined ========= */
var params: [String: Any] = [
kSecAttrKeyType as String: Constants.attrKeyTypeEllipticCurve,
kSecPrivateKeyAttrs as String: privateKeyParams,
kSecPublicKeyAttrs as String: publicKeyParams,
kSecAttrKeySizeInBits as String: 256,
]
if token == .secureEnclave {
params[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave
}
return params
}
static func getPublicKey(labeled: String, accessGroup: String?) throws -> PublicKey {
let query = publicKeyQuery(labeled: labeled, accessGroup: accessGroup)
return PublicKey(try getKey(query))
}
static func getPrivateKey(labeled: String, accessGroup: String?, prompt: String?, context: LAContext? = nil) throws -> PrivateKey {
let query = privateKeyQuery(labeled: labeled, accessGroup: accessGroup, prompt: prompt, context: context)
return PrivateKey(try getKey(query), context: context)
}
static func deletePublicKey(labeled: String, accessGroup: String?) throws {
let query = publicKeyQuery(labeled: labeled, accessGroup: accessGroup) as CFDictionary
logger?("SecItemDelete: \(query)")
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw Error.osStatus(message: "Could not delete public key.", osStatus: status)
}
}
static func deletePrivateKey(labeled: String, accessGroup: String?) throws {
let query = privateKeyQuery(labeled: labeled, accessGroup: accessGroup, prompt: nil, context: nil) as CFDictionary
logger?("SecItemDelete: \(query)")
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw Error.osStatus(message: "Could not delete private key.", osStatus: status)
}
}
static func forceSavePublicKey(_ publicKey: PublicKey, label: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrLabel as String: label,
kSecValueRef as String: publicKey.underlying
]
var raw: CFTypeRef?
logger?("SecItemAdd: \(query)")
var status = SecItemAdd(query as CFDictionary, &raw)
if status == errSecDuplicateItem {
logger?("SecItemDelete: \(query)")
status = SecItemDelete(query as CFDictionary)
logger?("SecItemAdd: \(query)")
status = SecItemAdd(query as CFDictionary, &raw)
}
if status == errSecInvalidRecord {
throw Error.osStatus(message: "Could not save public key. It is possible that the access control you have provided is not supported on this OS and/or hardware.", osStatus: status)
} else if status != errSecSuccess {
throw Error.osStatus(message: "Could not save public key", osStatus: status)
}
}
}
public struct Constants {
public static let noCompression: UInt8 = 4
public static let attrKeyTypeEllipticCurve: String = {
if #available(iOS 10.0, *) {
return kSecAttrKeyTypeECSECPrimeRandom as String
} else {
return kSecAttrKeyTypeEC as String
}
}()
}
public final class PublicKeyData {
// As received from Security framework
public let raw: Data
// The open ssl compatible DER format X.509
//
// We take the raw key and prepend an ASN.1 headers to it. The end result is an
// ASN.1 SubjectPublicKeyInfo structure, which is what OpenSSL is looking for.
//
// See the following DevForums post for more details on this.
// https://forums.developer.apple.com/message/84684#84684
//
// End result looks like this
// https://lapo.it/asn1js/#3059301306072A8648CE3D020106082A8648CE3D030107034200041F4E3F6CD8163BCC14505EBEEC9C30971098A7FA9BFD52237A3BCBBC48009162AAAFCFC871AC4579C0A180D5F207316F74088BF01A31F83E9EBDC029A533525B
//
public lazy var DER: Data = {
var x9_62HeaderECHeader = [UInt8]([
/* sequence */ 0x30, 0x59,
/* |-> sequence */ 0x30, 0x13,
/* |---> ecPublicKey */ 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, // http://oid-info.com/get/1.2.840.10045.2.1 (ANSI X9.62 public key type)
/* |---> prime256v1 */ 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, // http://oid-info.com/get/1.2.840.10045.3.1.7 (ANSI X9.62 named elliptic curve)
/* |-> bit headers */ 0x07, 0x03, 0x42, 0x00
])
var result = Data()
result.append(Data(x9_62HeaderECHeader))
result.append(self.raw)
return result
}()
public lazy var PEM: String = {
var lines = String()
lines.append("-----BEGIN PUBLIC KEY-----\n")
lines.append(self.DER.base64EncodedString(options: [.lineLength64Characters, .endLineWithCarriageReturn]))
lines.append("\n-----END PUBLIC KEY-----")
return lines
}()
internal init(_ raw: Data) {
self.raw = raw
}
}
public class Key {
public let underlying: SecKey
internal init(_ underlying: SecKey) {
self.underlying = underlying
}
private var cachedAttributes: [String:Any]? = nil
public func attributes() throws -> [String:Any] {
if let attributes = cachedAttributes {
return attributes
} else {
let attributes = try queryAttributes()
cachedAttributes = attributes
return attributes
}
}
public func label() throws -> String {
guard let attribute = try self.attributes()[kSecAttrLabel as String] as? String else {
throw Error.inconcistency(message: "We've got a private key, but we are missing its label.")
}
return attribute
}
public func accessGroup() throws -> String? {
return try self.attributes()[kSecAttrAccessGroup as String] as? String
}
public func accessControl() throws -> SecAccessControl {
guard let attribute = try self.attributes()[kSecAttrAccessControl as String] else {
throw Error.inconcistency(message: "We've got a private key, but we are missing its access control.")
}
return attribute as! SecAccessControl
}
private func queryAttributes() throws -> [String:Any] {
var matchResult: AnyObject? = nil
let query: [String:Any] = [
kSecClass as String: kSecClassKey,
kSecValueRef as String: underlying,
kSecReturnAttributes as String: true
]
logger?("SecItemCopyMatching: \(query)")
let status = SecItemCopyMatching(query as CFDictionary, &matchResult)
guard status == errSecSuccess else {
throw Error.osStatus(message: "Could not read attributes for key", osStatus: status)
}
guard let attributes = matchResult as? [String:Any] else {
throw Error.inconcistency(message: "Tried reading key attributes something went wrong. Expected dictionary, but received \(String(describing: matchResult)).")
}
return attributes
}
}
public final class PublicKey: Key {
private var cachedData: PublicKeyData? = nil
public func data() throws -> PublicKeyData {
if let data = cachedData {
return data
} else {
let data = try queryData()
cachedData = data
return data
}
}
private func queryData() throws -> PublicKeyData {
let keyRaw: Data
if #available(iOS 10.0, *) {
keyRaw = try export()
} else {
keyRaw = try exportWithOldApi()
}
guard keyRaw.first == Constants.noCompression else {
throw Error.inconcistency(message: "Tried reading public key bytes, but its headers says it is compressed and this library only handles uncompressed keys.")
}
return PublicKeyData(keyRaw)
}
@available(iOS 10.0, *)
private func export() throws -> Data {
var error : Unmanaged<CFError>?
guard let raw = SecKeyCopyExternalRepresentation(underlying, &error) else {
throw EllipticCurveKeyPair.Error.fromError(error?.takeRetainedValue(), message: "Tried reading public key bytes.")
}
return raw as Data
}
private func exportWithOldApi() throws -> Data {
var matchResult: AnyObject? = nil
let query: [String:Any] = [
kSecClass as String: kSecClassKey,
kSecValueRef as String: underlying,
kSecReturnData as String: true
]
logger?("SecItemCopyMatching: \(query)")
let status = SecItemCopyMatching(query as CFDictionary, &matchResult)
guard status == errSecSuccess else {
throw Error.osStatus(message: "Could not generate keypair", osStatus: status)
}
guard let keyRaw = matchResult as? Data else {
throw Error.inconcistency(message: "Tried reading public key bytes. Expected data, but received \(String(describing: matchResult)).")
}
return keyRaw
}
}
public final class PrivateKey: Key {
public private(set) var context: LAContext?
internal init(_ underlying: SecKey, context: LAContext?) {
super.init(underlying)
self.context = context
}
public func isStoredOnSecureEnclave() throws -> Bool {
let attribute = try self.attributes()[kSecAttrTokenID as String] as? String
return attribute == (kSecAttrTokenIDSecureEnclave as String)
}
}
public final class AccessControl {
// E.g. kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
public let protection: CFTypeRef
// E.g. [.userPresence, .privateKeyUsage]
public let flags: SecAccessControlCreateFlags
public init(protection: CFTypeRef, flags: SecAccessControlCreateFlags) {
self.protection = protection
self.flags = flags
}
public func underlying() throws -> SecAccessControl {
if flags.contains(.privateKeyUsage) {
let flagsWithOnlyPrivateKeyUsage: SecAccessControlCreateFlags = [.privateKeyUsage]
guard flags != flagsWithOnlyPrivateKeyUsage else {
throw EllipticCurveKeyPair.Error.inconcistency(message: "Couldn't create access control flag. Keychain chokes if you try to create access control with only [.privateKeyUsage] on devices older than iOS 11 and macOS 10.13.x")
}
}
var error: Unmanaged<CFError>?
let result = SecAccessControlCreateWithFlags(kCFAllocatorDefault, protection, flags, &error)
guard let accessControl = result else {
throw EllipticCurveKeyPair.Error.fromError(error?.takeRetainedValue(), message: "Tried creating access control object with flags \(flags) and protection \(protection)")
}
return accessControl
}
}
public enum Error: LocalizedError {
case underlying(message: String, error: NSError)
case inconcistency(message: String)
case authentication(error: LAError)
public var errorDescription: String? {
switch self {
case let .underlying(message: message, error: error):
return "\(message) \(error.localizedDescription)"
case let .authentication(error: error):
return "Authentication failed. \(error.localizedDescription)"
case let .inconcistency(message: message):
return "Inconcistency in setup, configuration or keychain. \(message)"
}
}
internal static func osStatus(message: String, osStatus: OSStatus) -> Error {
let error = NSError(domain: NSOSStatusErrorDomain, code: Int(osStatus), userInfo: [
NSLocalizedDescriptionKey: message,
NSLocalizedRecoverySuggestionErrorKey: "See https://www.osstatus.com/search/results?platform=all&framework=all&search=\(osStatus)"
])
return .underlying(message: message, error: error)
}
internal static func probablyAuthenticationError(underlying: NSError) -> Error {
return Error.authentication(error: .init(_nsError: NSError(domain: LAErrorDomain, code: LAError.authenticationFailed.rawValue, userInfo: [
NSLocalizedFailureReasonErrorKey: "Found public key, but couldn't find or access private key. The errSecItemNotFound error is sometimes wrongfully reported when LAContext authentication fails",
NSUnderlyingErrorKey: underlying
])))
}
internal static func fromError(_ error: CFError?, message: String) -> Error {
let any = error as Any
if let authenticationError = any as? LAError {
return .authentication(error: authenticationError)
}
if let error = error,
let domain = CFErrorGetDomain(error) as String? {
let code = Int(CFErrorGetCode(error))
var userInfo = (CFErrorCopyUserInfo(error) as? [String:Any]) ?? [String:Any]()
if userInfo[NSLocalizedRecoverySuggestionErrorKey] == nil {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = "See https://www.osstatus.com/search/results?platform=all&framework=all&search=\(code)"
}
let underlying = NSError(domain: domain, code: code, userInfo: userInfo)
return .underlying(message: message, error: underlying)
}
return .inconcistency(message: "\(message) Unknown error occured.")
}
}
@available(iOS 10.0, *)
public enum Hash: String {
case sha1
case sha224
case sha256
case sha384
case sha512
@available(iOS 10.0, *)
var signatureMessage: SecKeyAlgorithm {
switch self {
case .sha1:
return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA1
case .sha224:
return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA224
case .sha256:
return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA256
case .sha384:
return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA384
case .sha512:
return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA512
}
}
@available(iOS 10.0, *)
var encryptionEciesEcdh: SecKeyAlgorithm {
switch self {
case .sha1:
return SecKeyAlgorithm.eciesEncryptionStandardX963SHA1AESGCM
case .sha224:
return SecKeyAlgorithm.eciesEncryptionStandardX963SHA224AESGCM
case .sha256:
return SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM
case .sha384:
return SecKeyAlgorithm.eciesEncryptionStandardX963SHA384AESGCM
case .sha512:
return SecKeyAlgorithm.eciesEncryptionStandardX963SHA512AESGCM
}
}
}
public enum Token {
case secureEnclave
case keychain
public static var secureEnclaveIfAvailable: Token {
return Device.hasSecureEnclave ? .secureEnclave : .keychain
}
}
public enum Device {
public static var hasTouchID: Bool {
if #available(OSX 10.12.2, *) {
return LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
} else {
return false
}
}
public static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
public static var hasSecureEnclave: Bool {
return hasTouchID && !isSimulator
}
}
}
| 45.715311 | 277 | 0.596499 |
727a60e5ef6145d6f2f30859fe13f4328f25c552 | 1,352 | //
// AppDelegate.swift
// persistence
//
// Created by Bailey Yingling on 2/8/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.540541 | 179 | 0.746302 |
eb54ab74d060bd556e3dd3c10f63843338b27f67 | 3,185 | //
// GeradorDePagamentoTests.swift
// LeilaoTests
//
// Created by Ana Carolina on 11/12/20.
// Copyright © 2020 Alura. All rights reserved.
//
import XCTest
@testable import Leilao
import Cuckoo
class GeradorDePagamentoTests: XCTestCase {
var daoFalso: MockLeilaoDao!
var avaliadorFalso: Avaliador!
var pagamentos: MockRepositorioDePagamento!
override func setUp() {
super.setUp()
daoFalso = MockLeilaoDao().withEnabledSuperclassSpy()
avaliadorFalso = Avaliador() // MockAvaliador().withEnabledSuperclassSpy()
pagamentos = MockRepositorioDePagamento().withEnabledSuperclassSpy()
}
override func tearDown() {
super.tearDown()
}
func testDeveGerarPagamentoParaUmLeilaoEncerrado() {
let playstation = CriadorDeLeilao().para(descricao: "Playstation")
.lance(Usuario(nome: "José"), 2000.0)
.lance(Usuario(nome: "Maria"), 2500.0)
.constroi()
// let daoFalso = MockLeilaoDao().withEnabledSuperclassSpy()
// let avaliadorFalso = Avaliador() // MockAvaliador().withEnabledSuperclassSpy()
// let pagamentos = MockRepositorioDePagamento().withEnabledSuperclassSpy()
stub(daoFalso) { (daoFalso) in
when(daoFalso.encerrados()).thenReturn([playstation])
}
// stub(avaliadorFalso) { (avaliadorFalso) in
// when(avaliadorFalso.maiorLance()).thenReturn(2500.0)
// }
let geradorDePagamento = GeradorDePagamento(daoFalso, avaliadorFalso, pagamentos)
geradorDePagamento.gera()
let capturadorDeArgumento = ArgumentCaptor<Pagamento>()
verify(pagamentos).salva(capturadorDeArgumento.capture())
let pagamentoGerado = capturadorDeArgumento.value
XCTAssertEqual(2500.0, pagamentoGerado?.getValor())
}
func testDeveEmpurrarParaProximoDiaUtil() {
let iphone = CriadorDeLeilao().para(descricao: "iPhone")
.lance(Usuario(nome: "José"), 2000.0)
.lance(Usuario(nome: "Maria"), 2500.0)
.constroi()
stub(daoFalso) { (daoFalso) in
when(daoFalso.encerrados()).thenReturn([iphone])
}
let formatador = DateFormatter()
formatador.dateFormat = "yyyy/MM/dd"
guard let dataAntiga = formatador.date(from: "2018/05/19") else { return }
let geradorDePagamento = GeradorDePagamento(daoFalso, avaliadorFalso, pagamentos, dataAntiga)
geradorDePagamento.gera()
let capturadorDeArgumento = ArgumentCaptor<Pagamento>()
verify(pagamentos).salva(capturadorDeArgumento.capture())
let pagamentoGerado = capturadorDeArgumento.value
let formatadorDeData = DateFormatter()
formatadorDeData.dateFormat = "ccc"
guard let dataDoPagamento = pagamentoGerado?.getData() else { return }
let diaDaSemana = formatadorDeData.string(from: dataDoPagamento)
XCTAssertEqual("Mon", diaDaSemana)
}
}
| 32.5 | 101 | 0.627316 |
e938a85adbbf2645780ad40b867b1fb7154dac1a | 1,455 | //
// EditTableCell.swift
// VirtualTrainr
//
// Created by Anthony Ma on 2017-08-04.
// Copyright © 2017 Apptist. All rights reserved.
//
import Foundation
import UIKit
class EditTableCell: UITableViewCell, UITextViewDelegate {
// bio text view
var bioLbl = UILabel()
// MARK: - Init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
// bio label
bioLbl.adjustsFontSizeToFitWidth = true
bioLbl.font = self.createFontWithSize(fontName: standardFont, size: 15.0)
bioLbl.textAlignment = .left
bioLbl.textColor = UIColor.black
bioLbl.numberOfLines = 0
bioLbl.lineBreakMode = NSLineBreakMode.byWordWrapping
self.contentView.addSubview(bioLbl)
bioLbl.translatesAutoresizingMaskIntoConstraints = false
bioLbl.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
bioLbl.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
bioLbl.widthAnchor.constraint(equalTo: self.contentView.widthAnchor).isActive = true
bioLbl.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.068182 | 96 | 0.689347 |
f85cda55810c0af7ef3384b32e9baa134636fa20 | 848 | import Foundation
import SDWebImage
import UIKit
import UI
protocol ImageLoader {
func set(imageView: UIImageView, with url: String)
}
class UIImageLoader: ImageLoader {
func set(imageView: UIImageView, with url: String) {
guard let url = URL(string: url) else {
debugPrint("Malformed string")
return
}
imageView.sd_imageIndicator = SDWebImageActivityIndicator.grayLarge
imageView.sd_imageTransition = .fade
imageView.sd_setImage(with: url, placeholderImage: .none, options: SDWebImageOptions.progressiveLoad) { (image, error, _, _) in
if let _ = error {
imageView.image = UIImage(named: "notFound", in: Bundle(for: type(of: self)), with: .none)
imageView.contentMode = .center
}
}
}
}
| 28.266667 | 135 | 0.625 |
5b805c8ed03e1b556937fa1a60d0a79346b167bd | 2,230 | //
// InsertionSort.swift
// DataAndAlgorimTotal
//
// Created by 9tong on 2020/1/11.
// Copyright © 2020 liyuchen. All rights reserved.
//
import Foundation
/**
Insertion sort will iterate once through the cards, from left to right.
Each card is shifted to the left until it reaches its correct position
the best case scenario for insertion sort occurs when the sequence of values are
already in sorted order, and no left shifting is necessary
*/
public func insertionSort<Element>(_ array: inout [Element]) where Element: Comparable {
guard array.count > 1 else {
return
}
for current in 1..<array.count {
for shifting in (1...current).reversed() {
if array[shifting] < array[shifting - 1] {
array.swapAt(shifting, shifting - 1)
}else {
break
}
}
}
}
public func insertionSortTwo<Element>(_ array: inout [Element]) where Element: Comparable {
guard array.count > 1 else {
return
}
print("Array: \(array)")
for begin in (1..<array.count) {
// 找到要插入的位置
let des = search(begin, array)
print("begin: \(begin), des: \(des)")
// 插入元素
insert(begin, des, &array)
}
}
/*
将 source 位置的元素插入到dest位置
*/
private func insert<Element>(_ source: Int, _ dest: Int, _ sourceArray: inout [Element]) where Element: Comparable{
// 对source处的值进行备份
let e = sourceArray[source]
if dest == source {
print("排序后的Array: \(sourceArray)")
return
}
// 将 [dest, source)区间的元素后移
for i in (dest...source).reversed() where i > 0 {
sourceArray[i] = sourceArray[i - 1]
}
sourceArray[dest] = e
print("排序后的Array: \(sourceArray)")
}
/*
利用二分搜索找到 index位置元素的待插入位置
已经排好序数组的范围时 [0, index)
*/
private func search<Element>(_ index: Int, _ sourceArray: [Element]) -> Int where Element: Comparable {
var begin = 0
var end = index
// 当 begin == end 时,查找结束,这时的 begin 就是插入位置的索引。
while begin < end {
let mid = (begin + end) >> 1
if sourceArray[index] < sourceArray[mid] {
end = mid
} else {
begin = mid + 1
}
}
return begin;
}
| 24.23913 | 115 | 0.595516 |
e5966ca0bb5042dcd8d259e998a75222121a0c2e | 1,523 | //
// IssueReferencedCell.swift
// Freetime
//
// Created by Ryan Nystrom on 7/9/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
final class IssueReferencedCell: AttributedStringCell {
static let inset = UIEdgeInsets(
top: Styles.Sizes.inlineSpacing,
left: Styles.Sizes.eventGutter,
bottom: Styles.Sizes.inlineSpacing,
right: Styles.Sizes.eventGutter + Styles.Sizes.icon.width + Styles.Sizes.rowSpacing
)
let statusButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
statusButton.setupAsLabel(icon: false)
statusButton.isUserInteractionEnabled = false
contentView.addSubview(statusButton)
statusButton.snp.makeConstraints { make in
make.right.equalTo(contentView).offset(-Styles.Sizes.eventGutter)
make.size.equalTo(Styles.Sizes.icon)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public API
func configure(_ model: IssueReferencedModel) {
set(attributedText: model.attributedText)
let buttonState: UIButton.State
switch model.state {
case .closed: buttonState = .closed
case .merged: buttonState = .merged
case .open: buttonState = .open
}
statusButton.config(pullRequest: model.pullRequest, state: buttonState)
}
}
| 27.690909 | 91 | 0.664478 |
f4e290a0b301374454ad86b65dd545b7e6e12b95 | 104 | //
// Created by 多鹿豊 on 2021/04/18.
//
import Foundation
struct ProjectCard {
let note: String?
}
| 10.4 | 32 | 0.653846 |
46b370fc5869985b736e96b02a9ca81166bdfcaf | 439 | //
// BaseViewController.swift
// CreateAccountPOC
//
// Created by Pramod Kumar on 23/03/20.
// Copyright © 2020 Pramod Kumar. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
//MARK:- View Controller Life Cycle
//MARK:-
override func viewDidLoad() {
super.viewDidLoad()
self.initialSetup()
}
//MARK:- Methods
func initialSetup() {
}
}
| 16.884615 | 55 | 0.617312 |
cc71ad23de682c020efeb379f8c265ccba7cbc1c | 4,677 | import ARHeadsetKit
import Metal
class MyRenderer: CustomRenderer {
unowned let renderer: MainRenderer
var numFrames: Int = 0
var objects: [ARObject] = []
required init(renderer: MainRenderer, library: MTLLibrary!) {
self.renderer = renderer
generateObjects()
}
func updateResources() {
numFrames += 1
let red: simd_half3 = [1.00, 0.00, 0.00]
let skyBlue: simd_half3 = [0.33, 0.75, 1.00]
let coordinator = renderer.coordinator as! Coordinator
let renderingRed = coordinator.renderingRed
let userSelectedColor = renderingRed ? red : skyBlue
objects[0].color = userSelectedColor
objects[1].color = userSelectedColor
objects[2].color = [0.70, 0.60, 0.05]
objects[3].color = [0.20, 0.85, 0.30]
func HSL_toRGB(hue: Float, saturation: Float = 1.00,
lightness: Float = 0.50) -> simd_half3
{
var majorColor = (lightness * 2 - 1).magnitude
majorColor = (1 - majorColor) * saturation
// Distance from the nearest primary color
var primaryDistance = positiveRemainder(hue / 60, 2)
primaryDistance = 1 - (primaryDistance - 1).magnitude
let minorColor = majorColor * primaryDistance
// Every 60 degrees, change how colors are selected
let clampedHue = positiveRemainder(hue, 360)
let hueRangeID = Int(clampedHue / 60)
let majorIndices = simd_long8(0, 1, 1, 2, 2, 0, 0, 0)
let minorIndices = simd_long8(1, 0, 2, 1, 0, 2, 2, 2)
var output = simd_float3.zero
output[majorIndices[hueRangeID]] = majorColor
output[minorIndices[hueRangeID]] = minorColor
// Adjust output so it falls between 0% and 100%
output += lightness - majorColor / 2
return simd_half3(output)
// To learn more about this conversion formula, check out
// https://www.rapidtables.com/convert/color/hsl-to-rgb.html
}
let numSeconds = Float(numFrames) / 60
let angleDegrees = 360 * (numSeconds / 4)
objects[4].color = HSL_toRGB(hue: angleDegrees, saturation: 0.5)
objects[5].color = HSL_toRGB(hue: angleDegrees + 180)
}
func drawGeometry(renderEncoder: ARMetalRenderCommandEncoder) {
}
func generateObjects() {
func createShape(shapeType: ARShapeType,
position: simd_float3,
scale: simd_float3,
upDirection: simd_float3) -> ARObject
{
let yAxis: simd_float3 = [0.0, 1.0, 0.0]
let orientation = simd_quatf(from: yAxis,
to: normalize(upDirection))
return ARObject(shapeType: shapeType,
position: position,
orientation: orientation,
scale: scale)
}
// User-selected color
objects.append(createShape(
shapeType: .squarePyramid,
position: [0.00, 0.00, -0.26],
scale: [0.08, 0.04, 0.04],
upDirection: [1.00, 2.00, 6.00])
)
objects.append(createShape(
shapeType: .cylinder,
position: [0.00, -0.12, -0.14],
scale: [0.10, 0.04, 0.10],
upDirection: [0.00, -9.00, 1.00])
)
// Static color
objects.append(createShape(
shapeType: .sphere,
position: [0.07, 0.00, -0.14],
scale: [0.06, 0.06, 0.06],
upDirection: [0.00, 1.00, 0.00])
)
objects.append(createShape(
shapeType: .cone,
position: [-0.04, 0.00, -0.16],
scale: [ 0.03, 0.10, 0.03],
upDirection: [ 3.00, 2.00, 2.00])
)
// Animated color
objects.append(createShape(
shapeType: .cube,
position: [0.00, 0.08, -0.14],
scale: [0.06, 0.10, 0.06],
upDirection: [1.00, -1.00, 1.00])
)
objects.append(createShape(
shapeType: .octahedron,
position: [ 0.00, -0.06, -0.14],
scale: [ 0.06, 0.06, 0.06],
upDirection: [-5.00, 1.00, 5.00])
)
}
}
| 34.389706 | 72 | 0.495831 |
abd56899381493090974d175969a850c23f7b634 | 1,782 | import Foundation
import RxSwift
import TSCBasic
import TuistCore
public final class Cache: CacheStoring {
// MARK: - Attributes
private let storageProvider: CacheStorageProviding
/// An instance that returns the storages to be used.
private var storages: [CacheStoring] {
(try? storageProvider.storages()) ?? []
}
// MARK: - Init
/// Initializes the cache with its attributes.
/// - Parameter storageProvider: An instance that returns the storages to be used.
public init(storageProvider: CacheStorageProviding) {
self.storageProvider = storageProvider
}
// MARK: - CacheStoring
public func exists(name: String, hash: String) -> Single<Bool> {
/// It calls exists sequentially until one of the storages returns true.
return storages.reduce(Single.just(false)) { result, next -> Single<Bool> in
result.flatMap { exists in
guard !exists else { return result }
return next.exists(name: name, hash: hash)
}.catchError { _ -> Single<Bool> in
next.exists(name: name, hash: hash)
}
}
}
public func fetch(name: String, hash: String) -> Single<AbsolutePath> {
return storages
.reduce(nil) { result, next -> Single<AbsolutePath> in
if let result = result {
return result.catchError { _ in next.fetch(name: name, hash: hash) }
} else {
return next.fetch(name: name, hash: hash)
}
}!
}
public func store(name: String, hash: String, paths: [AbsolutePath]) -> Completable {
return Completable.zip(storages.map { $0.store(name: name, hash: hash, paths: paths) })
}
}
| 33.622642 | 95 | 0.602694 |
7a8808368573f97d9adf1e1e2e4b2909f615ca85 | 4,422 | //
// BeamsView.Builder.swift
// RhythmView
//
// Created by James Bean on 7/2/17.
//
//
import DataStructures
import SpelledRhythm
import Geometry
import Path
import Rendering
extension BeamsView {
public final class Builder {
/// Configuration of `BeamsView`.
private let configuration: BeamsView.Configuration
/// Start and end values for each beam segment.
private var beamSegments: [Int: [(Double, Double)]]
/// Beamlet positions with direction.
private var beamlets: [Int: [(Double, Beaming.BeamletDirection)]]
/// Previous x-values by level.
private var start: [Int: Double]
// MARK: - Initializers
/// Creates a `BeamsRenderer` ready to receive commands in order to render beams.
public init(configuration: Configuration) {
self.configuration = configuration
self.beamSegments = [:]
self.beamlets = [:]
self.start = [:]
}
/// Start a beam at the given horizontal position, on the given `level`.
public func startBeam(at x: Double, on level: Int) {
start[level] = x
}
/// Stop the beam at the given horizontal position, on the given `level`.
public func stopBeam(at x: Double, on level: Int) {
let start = self.start[level]!
beamSegments[level, default: []].append((start,x))
self.start[level] = nil
}
/// Add a beamlet at the given `x`, on the given `level`, going the given `direction`.
public func addBeamlet(
at x: Double,
on level: Int,
direction: Beaming.BeamletDirection
)
{
beamlets[level, default: []].append((x,direction))
}
/// Add all of the nececessary components for the given `rhythmSpelling` at the given
/// `positions`.
public func prepare(_ beaming: Beaming, at positions: [Double]) {
prepare(beaming.map { $0 }, at: positions)
}
/// Add all of the nececessary components for the given `junctions` at the given
/// `positions`.
public func prepare(_ verticals: [Beaming.Point.Vertical], at positions: [Double]) {
precondition(verticals.count == positions.count)
zip(verticals, positions).forEach(handle)
}
private func handle(_ vertical: Beaming.Point.Vertical, at position: Double) {
vertical.points.enumerated().forEach { (level, point) in
switch point {
case .start:
startBeam(at: position, on: level)
case .stop:
stopBeam(at: position, on: level)
case .beamlet(let direction):
addBeamlet(at: position, on: level, direction: direction)
default:
break
}
}
}
public func build() -> BeamsView {
var beams: [Beam] {
return beamSegments.flatMap { level, beamSegments -> [Beam] in
let displacement = Double(level - 1) * configuration.displacement
return beamSegments.map { left, right in
let start = Point(x: left, y: left * configuration.slope + displacement)
let end = Point(x: right, y: right * configuration.slope + displacement)
return Beam(start: start, end: end, width: configuration.width)
}
}
}
var beamlets: [Beam] {
return self.beamlets.flatMap { level, beamlets -> [Beam] in
let displacement = Double(level - 1) * configuration.displacement
return beamlets.map { x, direction in
let left = x
let right = x + direction.rawValue * configuration.beamletLength
let start = Point(x: left, y: left * configuration.slope + displacement)
let end = Point(x: right, y: right * configuration.slope + displacement)
return Beam(start: start, end: end, width: configuration.width)
}
}
}
return BeamsView(beams: beams + beamlets, color: configuration.color)
}
}
}
| 36.545455 | 96 | 0.546585 |
ed5ec470ae11ca3b889b4d23ef49d96088b65a06 | 6,658 | //
// SignInScreenView.swift
// Athenaeum
//
// Created by Adem Deliaslan on 19.04.2022.
//
import SwiftUI
import Firebase
class FireBaseManager: NSObject {
let auth: Auth
static let shared = FireBaseManager()
override init() {
FirebaseApp.configure()
self.auth = Auth.auth()
super.init()
}
}
struct SignInScreenView: View {
@State private var email: String = "" //deafult empty
@State private var password: String = ""
@State var isSecureField: Bool = true
@State private var isUserLogedIn: Bool = false
var body: some View {
if isUserLogedIn {
//go somewhere
HomeView()
} else {
content
}
}
var content: some View {
NavigationView {
ZStack {
Color.green_bluish_color.edgesIgnoringSafeArea(.all)
VStack{
Image(systemName: "figure.walk.diamond.fill")
.font(.system(size: 100, weight: .ultraLight))
.foregroundColor(.red_primary_color)
VStack {
Text("Giriş Yap")
.font(.largeTitle)
.bold()
.padding(.bottom, 5)
NavigationLink(destination: HomeView().navigationBarHidden(true) ) {
SocialLoginButton(image: "applelogo", title: "Apple Hesabınla Giriş Yap")
.foregroundColor(Color.black)
.padding(.bottom, 5)
}
Text("ya da e-posta ve şifrenle giriş için")
.font(.callout)
TextField("E-posta adresinizi giriniz", text: $email)
.autocapitalization(.none)
.disableAutocorrection(true)
.font(.title3)
.padding(14)
.frame(maxWidth: .infinity)
.foregroundColor(Color.black)
.background(Color.gray_3)
.cornerRadius(50)
.shadow(color: Color.black.opacity(0.2), radius: 60, x: 0, y: 20)
HStack {
if isSecureField{
SecureField("Şifrenizi giriniz", text: $password)
.autocapitalization(.none)
.disableAutocorrection(true)
.font(.title3)
.padding(14)
.frame(maxWidth: .infinity)
.foregroundColor(Color.black)
.background(Color.gray_3)
.cornerRadius(50)
.shadow(color: Color.black.opacity(0.2), radius: 60, x: 0, y: 20)
} else {
TextFieldArea(placeHolder: "Şifrenizi Giriniz", text: password)
}
}.overlay(alignment: .trailing) {
Image(systemName: isSecureField ? "eye.slash" : "eye")
.foregroundColor(Color.gray_5)
.padding(.trailing)
.onTapGesture {
isSecureField.toggle()
}
}
Button {
FireBaseManager.shared.auth.signIn(withEmail: email, password: password) { result, error in
if email == "" && password == "" {
print("Şifre ve eposta alanı boş bırakılamaz")
} else {
if error == nil {
print("Giriş Başarılı")
isUserLogedIn = true
} else {
print("kullanıcı hatalı girildi")
}
}
}
} label: {
PrimaryButton(title: "Giriş Yap")
}
}
HStack {
Button {
} label: {
NavigationLink(destination: SignUpScreenView().navigationBarHidden(true)) { // .navigationBarHidden(true)
// PrimaryButton(title: "Buradan Başlayın")
Text("Hasabın yok mu? Kayıt Ol!")
}//.navigationBarHidden(true)
}
Spacer()
Button {
} label: {
Text("Şifremi Unuttum!")
}
}
.padding(.horizontal)
.foregroundColor(Color.black)
Divider()
Text("Kural ve Koşullarımızı Okuyunuz.")
.foregroundColor(.red)
Spacer()
}.padding()
Spacer()
}
}
// .navigationBarHidden(true)
}
}
struct SocialLoginButton: View {
var image: String
var title: String
var body: some View {
HStack {
Image(systemName: image)
.font(.system(size: 18, weight: .ultraLight))
Spacer()
Text(title)
.font(.title2)
.padding(.vertical, 1)
Spacer()
}
.padding(14)
.frame(maxWidth: .infinity)
.background(Color.white_color)
.cornerRadius(50)
.shadow(color: Color.black.opacity(0.2), radius: 60, x: 0, y: 20)
}
}
struct SignInScreenView_Previews: PreviewProvider {
static var previews: some View {
SignInScreenView()
}
}
| 36.988889 | 133 | 0.378792 |
bb51c04158a451ceaa341be1469c0fd67ce92703 | 1,264 | //
// CSStoreFactory.swift
// CSMobileBase
//
// Created by Mayank Bhayana on 10/01/19.
//
import Foundation
open class CSStoreFactory: NSObject {
open static let instance: CSStoreFactory = CSStoreFactory()
fileprivate let settingsDidChange: Selector = #selector(CSStoreFactory.settingsDidChange(_:))
fileprivate var stores: [String : CSRecordStore]
fileprivate override init() {
self.stores = [:]
}
open func retrieveStore(_ objectType: String) -> CSRecordStore {
if let recordStore: CSRecordStore = stores[objectType] {
return recordStore
}
return CSRecordStore(objectType: objectType)
}
open func registerStore(_ recordStore: CSRecordStore) {
stores[recordStore.objectType] = recordStore
}
open func syncUp() {
for recordStore: CSRecordStore in stores.values {
recordStore.syncUp(onCompletion: nil)
}
}
func settingsDidChange(_ notification: Notification) {
if let settings: CSSettings = notification.object as? CSSettings {
for objectType: String in settings.objectTypes {
retrieveStore(objectType).indexStore()
}
}
}
}
| 25.28 | 97 | 0.635285 |
9127ab5e1936176040f3a81974573c9151f7bed0 | 2,328 | import Foundation
@testable import KsApi
@testable import Library
import Prelude
import XCTest
final class FeatureHelpersTests: TestCase {
// MARK: - goRewardless
func testFeatureGoRewardlessIsEnabled_isTrue() {
let config = Config.template
|> \.features .~ [Feature.goRewardless.rawValue: true]
withEnvironment(config: config) {
XCTAssertTrue(featureGoRewardlessIsEnabled())
}
}
func testFeatureGoRewardlessIsEnabled_isFalse() {
let config = Config.template
|> \.features .~ [Feature.goRewardless.rawValue: false]
withEnvironment(config: config) {
XCTAssertFalse(featureGoRewardlessIsEnabled())
}
}
func testFeatureGoRewardlessIsEnabled_isFalse_whenNil() {
withEnvironment(config: .template) {
XCTAssertFalse(featureGoRewardlessIsEnabled())
}
}
// MARK: - nativeCheckout
func testFeatureNativeCheckoutIsEnabled_isTrue() {
let config = Config.template
|> \.features .~ [Feature.nativeCheckout.rawValue: true]
withEnvironment(config: config) {
XCTAssertTrue(featureNativeCheckoutIsEnabled())
}
}
func testFeatureNativeCheckoutIsEnabled_isFalse() {
let config = Config.template
|> \.features .~ [Feature.nativeCheckout.rawValue: false]
withEnvironment(config: config) {
XCTAssertFalse(featureNativeCheckoutIsEnabled())
}
}
func testFeatureNativeCheckoutIsEnabled_isFalse_whenNil() {
withEnvironment(config: .template) {
XCTAssertFalse(featureNativeCheckoutIsEnabled())
}
}
// MARK: - nativeCheckoutPledgeView
func testFeatureNativeCheckoutPledgeViewEnabled_isTrue() {
let config = Config.template
|> \.features .~ [Feature.nativeCheckoutPledgeView.rawValue: true]
withEnvironment(config: config) {
XCTAssertTrue(featureNativeCheckoutPledgeViewIsEnabled())
}
}
func testFeatureNativeCheckoutPledgeViewEnabled_isFalse() {
let config = Config.template
|> \.features .~ [Feature.nativeCheckoutPledgeView.rawValue: false]
withEnvironment(config: config) {
XCTAssertFalse(featureNativeCheckoutPledgeViewIsEnabled())
}
}
func testFeatureNativeCheckoutPledgeViewEnabled_isFalse_whenNil() {
withEnvironment(config: .template) {
XCTAssertFalse(featureNativeCheckoutPledgeViewIsEnabled())
}
}
}
| 27.069767 | 73 | 0.7311 |
48502897c3e35c15d2daa230d95683ceaa814027 | 461 | //
// Video.swift
// one
//
// Created by sidney on 2021/4/11.
//
import Foundation
import UIKit
struct Video {
var id: String = ""
var type: String = ""
var title: String = ""
var subtitle: String = ""
var poster: String = ""
var url: String = ""
var avatar: String = ""
}
struct ImageInfo {
var url: String = ""
var height: CGFloat = 0
var width: CGFloat = 0
var name: String = ""
var type: String = ""
}
| 16.464286 | 35 | 0.559653 |
1caf7150d74ffc8f9e1649d92fa23c4746766d58 | 1,037 | //
// TransferHistoryViewModel.swift
// Commun
//
// Created by Chung Tran on 12/18/19.
// Copyright © 2019 Commun Limited. All rights reserved.
//
import Foundation
import CyberSwift
import RxCocoa
class TransferHistoryViewModel: ListViewModel<ResponseAPIWalletGetTransferHistoryItem> {
var filter: BehaviorRelay<TransferHistoryListFetcher.Filter>
init(symbol: String? = nil) {
let filter = TransferHistoryListFetcher.Filter(userId: Config.currentUser?.id, symbol: symbol)
self.filter = BehaviorRelay<TransferHistoryListFetcher.Filter>(value: filter)
super.init(fetcher: TransferHistoryListFetcher(filter: filter))
defer {
bindFilter()
}
}
func bindFilter() {
filter.distinctUntilChanged()
.subscribe(onNext: { (filter) in
self.fetcher.reset()
(self.fetcher as! TransferHistoryListFetcher).filter = filter
self.fetchNext()
})
.disposed(by: disposeBag)
}
}
| 29.628571 | 102 | 0.654773 |
140606f75897c336f1c11086fbc48fd7c1de3819 | 13,789 | //
// TableView.swift
// Pods
//
// Created by Hamza Ghazouani on 20/07/2017.
//
//
import UIKit
/// The delegate of a TableView/CollectionView object must adopt the PlaceholderDelegate protocol. the method of the protocol allow the delegate to perform placeholders action.
public protocol PaginateDelegate {
func didCallRefreshTableView(for tableView:TableView)
func paginate(to page: Int,for tableView:TableView)
}
public protocol PlaceholderDelegate: class {
/// Performs the action to the delegate of the table or collection view
///
/// - Parameters:
/// - view: the table view or the collection
/// - placeholder: The placeholder source of the action
func view(_ view: Any, actionButtonTappedFor placeholder: Placeholder)
}
/// A table view that allows to show easily placeholders like no results, no internet connection, etc
open class TableView: UITableView {
private let refresh = UIRefreshControl()
private var loadingView: UIView!
private var indicator: UIActivityIndicatorView!
internal var page: Int = 0
internal var previousItemCount: Int = 0
public var pagingDelegate:PaginateDelegate?
open var currentPage: Int {
get {
return page
}
}
open var isLoading: Bool = false {
didSet {
isLoading ? showLoading() : hideLoading()
}
}
// MARK: - Public properties
/// The placeholdersProvider property is responsible for the placeholders views and data
final public var placeholdersProvider = PlaceholdersProvider.default {
willSet {
/// before changing the placeholders data, we should be sure that the tableview is in the default configuration. Otherwise If the dataSource and the delegate are in placeholder configuration, and we set the new data, the old one will be released and we will lose the defaultDataSource and defaultDelegate (they will be set to nil)
showDefault()
}
}
/**
* The object that acts as the delegate of the table view placeholders.
* The delegate must adopt the PlaceholderDelegate protocol. The delegate is not retained.
*/
public weak var placeholderDelegate: PlaceholderDelegate?
/**
* The object that acts as the data source of the table view.
* The data source must adopt the UITableViewDataSource protocol. The data source is not retained.
*/
weak open override var dataSource: UITableViewDataSource? {
didSet {
/* we save only the initial data source (and not a placeholder datasource) to allow to go back to the initial data */
if dataSource is PlaceholderDataSourceDelegate {
return
}
defaultDataSource = dataSource
}
}
/**
* The object that acts as the delegate of the table view.
* The delegate must adopt the UITableViewDelegate protocol. The delegate is not retained.
*/
open override weak var delegate: UITableViewDelegate? {
didSet {
/* we save only the initial delegate (and not the placeholder delegate) to allow to go back to the initial one */
if delegate is PlaceholderDataSourceDelegate {
return
}
defaultDelegate = delegate
}
}
/**
* Returns an accessory view that is displayed above the table.
* The default value is nil. The table header view is different from a section header.
*/
open override var tableHeaderView: UIView? {
didSet {
if tableHeaderView == nil {
return
}
defaultTableHeaderView = tableHeaderView
}
}
/**
* Returns an accessory view that is displayed below the table.
* The default value is nil. The table footer view is different from a section footer.
*/
open override var tableFooterView: UIView? {
didSet {
if tableFooterView == nil { return }
defaultTableFooterView = tableFooterView
}
}
/**
* Keeps user seperatorStyle instead of overriding with system default
* The default value is UITableViewCellSeparatorStyle.singleLine
*/
open override var separatorStyle: UITableViewCell.SeparatorStyle {
didSet {
defaultSeparatorStyle = separatorStyle
}
}
/**
* A Boolean value that determines whether bouncing always occurs when the placeholder is shown.
* The default value is false
*/
open var placeholdersAlwaysBounceVertical = true
// MARK: - Private properties
/// The defaultDataSource is used to allow to go back to the initial data source of the table view after switching to a placeholder data source
internal weak var defaultDataSource: UITableViewDataSource?
/// The defaultDelegate is used to allow to go back to the initial delegate of the table view after switching to a placeholder delegate
internal weak var defaultDelegate: UITableViewDelegate?
/// The defaultSeparatorStyle is used to save the tableview separator style, because, when you switch to a placeholder, is changed to `.none`
fileprivate var defaultSeparatorStyle: UITableViewCell.SeparatorStyle!
/// The defaultAlwaysBounceVertical is used to save the tableview bouncing setup, because, when you switch to a placeholder, the vertical bounce is disabled
fileprivate var defaultAlwaysBounceVertical: Bool!
/// The defaultTableViewHeader is used to save the tableview header when you switch to placeholders
fileprivate var defaultTableHeaderView: UIView?
/// The defaultTableViewFooter is used to save the tableview footer when you switch to placeholders
fileprivate var defaultTableFooterView: UIView?
// MARK: - init methods
/**
Returns an table view initialized from data in a given unarchiver.
- parameter aDecoder: An unarchiver object.
- returns: self, initialized using the data in decoder.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Initializes and returns a table view object having the given frame and style.
Returns an initialized TableView object, or nil if the object could not be successfully initialized.
- parameter frame: A rectangle specifying the initial location and size of the table view in its superview’s coordinates. The frame of the table view changes as table cells are added and deleted.
- parameter style: A constant that specifies the style of the table view. See Table View Style for descriptions of valid constants.
- returns: Returns an initialized TableView object, or nil if the object could not be successfully initialized.
*/
override public init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
setup()
}
/**
* Config the table view to be able to show placeholders
*/
private func setup() {
// register the placeholder view cell
register(cellType: PlaceholderTableViewCell.self)
defaultSeparatorStyle = separatorStyle
defaultAlwaysBounceVertical = alwaysBounceVertical
defaultTableHeaderView = tableHeaderView
defaultTableFooterView = tableFooterView
customSetup()
}
/// Implement this method of you want to add new default placeholdersProvider, new default cell, etc
open func customSetup() {
refresh.addTarget(self, action: #selector(didPulltoRefresh), for: .valueChanged)
self.refreshControl = refresh
}
@objc func didPulltoRefresh(){
self.refreshControl?.beginRefreshing()
page = 0
previousItemCount = 0
self.pagingDelegate?.didCallRefreshTableView(for: self)
}
// MARK: - Manage table view data and placeholders
/**
Switch to different data sources and delegate of the table view (placeholders and initial data source & delegate)
- parameter theSource: the selected data source
- parameter theDelegate: the selected delegate
*/
internal func switchTo(dataSource theDataSource: UITableViewDataSource?, delegate theDelegate: UITableViewDelegate? = nil) {
// if the data source and delegate are already set, no need to switch
if dataSource === theDataSource && delegate === theDelegate {
return
}
if let placeholderDataSource = theDataSource as? PlaceholderDataSourceDelegate {
// placeholder configuration
super.separatorStyle = .none
alwaysBounceVertical = placeholdersAlwaysBounceVertical
let style = placeholderDataSource.placeholder.style
if style?.shouldShowTableViewHeader != true { // style = nil or shouldShowTableViewHeader == false
tableHeaderView = nil
}
if style?.shouldShowTableViewFooter != true {
tableFooterView = nil
}
}
else {
// default configuration
separatorStyle = defaultSeparatorStyle
alwaysBounceVertical = defaultAlwaysBounceVertical
tableHeaderView = defaultTableHeaderView
tableFooterView = defaultTableFooterView
}
dataSource = theDataSource
delegate = theDelegate
super.reloadData()
}
/// The total number of rows in all sections of the tableView
private func numberOfRowsInAllSections() -> Int {
let numberOfSections = defaultDataSource?.numberOfSections?(in: self) ?? 1
var rows = 0
for i in 0 ..< numberOfSections {
rows += defaultDataSource?.tableView(self, numberOfRowsInSection: i) ?? 0
}
return rows
}
/**
Reloads the rows and sections of the table view.
If the number of rows == 0 it shows no results placeholder
*/
open override func reloadData() {
// if the tableview is empty we switch automatically to no data placeholder
if numberOfRowsInAllSections() == 0 {
showLoadingPlaceholder()
return
}
// if the data source is in no data placeholder, and the user tries to reload data, we will switch automatically to default
if dataSource is PlaceholderDataSourceDelegate {
showDefault()
return
}
super.reloadData()
}
open func justReload(){
page = 0
previousItemCount = 0
pagingDelegate?.paginate(to: page, for: self)
}
/**
Called when the adjusted content insets of the scroll view change.
*/
open override func adjustedContentInsetDidChange() {
if dataSource is PlaceholderDataSourceDelegate {
// Force table view to recalculate the cell height, because the method tableView:heightForRowAt: is called before adjusting the content of the scroll view
guard let indexPaths = indexPathsForVisibleRows else { return }
reloadRows(at: indexPaths, with: .automatic)
}
}
}
extension UITableView {
/**
Register a NIB-Based `UITableViewCell` subclass (conforming to `Reusable` & `NibLoadable`)
- parameter cellType: the `UITableViewCell` (`Reusable` & `NibLoadable`-conforming) subclass to register
- seealso: `register(_:,forCellReuseIdentifier:)`
*/
final func register<T: UITableViewCell>(cellType: T.Type)
where T: Reusable & NibLoadable {
self.register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier)
}
}
extension TableView:UIScrollViewDelegate{
private func paginate(_ tableView: TableView, forIndexAt indexPath: IndexPath) {
let itemCount = tableView.dataSource?.tableView(tableView, numberOfRowsInSection: indexPath.section) ?? 0
guard indexPath.row == itemCount - 1 else { return }
guard previousItemCount != itemCount else { return }
page += 1
previousItemCount = itemCount
print("PAGE: \(page)")
pagingDelegate?.paginate(to: page, for: self)
}
private func showLoading() {
if loadingView == nil {
createLoadingView()
}
tableFooterView = loadingView
}
private func hideLoading() {
reloadData()
tableFooterView = nil
}
private func createLoadingView() {
loadingView = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 50))
indicator = UIActivityIndicatorView()
indicator.color = UIColor.lightGray
indicator.translatesAutoresizingMaskIntoConstraints = false
indicator.startAnimating()
loadingView.addSubview(indicator)
centerIndicator()
tableFooterView = loadingView
}
private func centerIndicator() {
let xCenterConstraint = NSLayoutConstraint(
item: loadingView, attribute: .centerX, relatedBy: .equal,
toItem: indicator, attribute: .centerX, multiplier: 1, constant: 0
)
loadingView.addConstraint(xCenterConstraint)
let yCenterConstraint = NSLayoutConstraint(
item: loadingView, attribute: .centerY, relatedBy: .equal,
toItem: indicator, attribute: .centerY, multiplier: 1, constant: 0
)
loadingView.addConstraint(yCenterConstraint)
}
public override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell {
paginate(self, forIndexAt: indexPath)
return super.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
}
| 38.733146 | 342 | 0.667851 |
ed7cb8df8d27e2834676cd106f1ce99e315db6bc | 11,069 | //
// UIImage_Effect.swift
// JXExtensionKit_Swift
//
// Created by Barnett on 2020/7/10.
// Copyright © 2020 Barnett. All rights reserved.
//
import Foundation
import UIKit
import Accelerate
extension UIImage
{
// MARK:实例方法
/// 使用CoreImage技术使图片模糊
/// - Parameter blurNum: 模糊数值 0~100 (默认100)
func blurImageWithCoreImageBlurNumber(_ blurNum:CGFloat) -> UIImage? {
let context = CIContext.init()
guard let oldCGimage = self.cgImage, cgImage != nil else {
return nil
}
let inputImage = CIImage.init(cgImage: oldCGimage)
// 创建滤镜
let filter = CIFilter.init(name: "CIGaussianBlur")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
filter.setValue(blurNum, forKey: kCIInputRadiusKey)
let result = filter.value(forKey: kCIOutputImageKey) as! CIImage
let outImage = context.createCGImage(result, from: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))!
let blurImage = UIImage.init(cgImage: outImage)
return blurImage
}
/// 使用Accelerate技术模糊图片,模糊效果比CoreImage效果更美观,效率要比CoreImage要高,处理速度快
/// - Parameter blurValue: 模糊数值 0 ~ 1.0,默认0.1
func blurImageWithAccelerateBlurValue(_ blurValue:CGFloat) -> UIImage? {
var newBlurValue : CGFloat = blurValue
if blurValue < 0.0 {
newBlurValue = 0.1
}else if blurValue > 1.0
{
newBlurValue = 1.0
}
//boxSize必须大于0
var boxSize = Int(newBlurValue * 100.0)
boxSize -= (boxSize % 2) + 1
//图像处理
let imgRef = self.cgImage
//图像缓存,输入缓存,输出缓存
var inBuffer = vImage_Buffer()
var outBuffer = vImage_Buffer()
var error = vImage_Error()
let inProvider = imgRef?.dataProvider
let inBitmapData = inProvider!.data
//宽,高,字节/行,data
inBuffer.width = vImagePixelCount((imgRef?.width)!)
inBuffer.height = vImagePixelCount((imgRef?.height)!)
inBuffer.rowBytes = (imgRef?.bytesPerRow)!
// void *
inBuffer.data = UnsafeMutableRawPointer.init(mutating:CFDataGetBytePtr(inBitmapData!))
// 像素缓存
let pixelBuffer = malloc(imgRef!.bytesPerRow * imgRef!.height)
outBuffer.data = pixelBuffer
outBuffer.width = vImagePixelCount((imgRef?.width)!)
outBuffer.height = vImagePixelCount((imgRef?.height)!)
outBuffer.rowBytes = (imgRef?.bytesPerRow)!
error = vImageBoxConvolve_ARGB8888(&inBuffer,
&outBuffer,
nil,
0,
0,
UInt32(boxSize),
UInt32(boxSize),
nil,
vImage_Flags(kvImageEdgeExtend))
if(kvImageNoError != error)
{
error = vImageBoxConvolve_ARGB8888(&inBuffer,
&outBuffer,
nil,
vImagePixelCount(0),
vImagePixelCount(0),
UInt32(boxSize),
UInt32(boxSize),
nil,
vImage_Flags(kvImageEdgeExtend))
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let ctx = CGContext(data: outBuffer.data,
width:Int(outBuffer.width),
height:Int(outBuffer.height),
bitsPerComponent:8,
bytesPerRow: outBuffer.rowBytes,
space: colorSpace,
bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)
let imageRef = ctx!.makeImage()
free(pixelBuffer)
return UIImage(cgImage: imageRef!)
}
/// 模糊图片
/// - Parameters:
/// - blurRadius: 模糊半径
/// - tintColor: 颜色
/// - saturationDeltaFactor: 饱和增量因子 0 图片色为黑白 小于0颜色反转 大于0颜色增深
/// - maskImage: 遮罩图像
/// - Returns: 图片
func applyBlurWith(blurRadius : Float,tintColor : UIColor?,saturationDeltaFactor : Float,maskImage : UIImage?) -> UIImage? {
if self.size.width < 1 || self.size.height < 1 || self.cgImage == nil || (maskImage != nil && maskImage!.cgImage == nil) {
return nil
}
let imageRect = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
var effectImage = self
let hasBlur = blurRadius > Float.ulpOfOne
let hasSaturationChange = fabsf(saturationDeltaFactor - 1.0) > Float.ulpOfOne
if hasBlur || hasSaturationChange {
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let effectInContext = UIGraphicsGetCurrentContext()!
effectInContext.ctm.scaledBy(x: 1, y: -1)
effectInContext.ctm.translatedBy(x: 0, y: -self.size.height)
effectInContext.draw(self.cgImage!, in: imageRect)
var effectInBuffer : vImage_Buffer = vImage_Buffer.init()
effectInBuffer.data = effectInContext.data
effectInBuffer.rowBytes = effectInContext.bytesPerRow
effectInBuffer.width = vImagePixelCount(effectInContext.width)
effectInBuffer.height = vImagePixelCount(effectInContext.height)
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let effectOutContext = UIGraphicsGetCurrentContext()!
var effectOutBuffer : vImage_Buffer = vImage_Buffer.init()
effectOutBuffer.data = effectOutContext.data
effectOutBuffer.rowBytes = effectOutContext.bytesPerRow
effectOutBuffer.width = vImagePixelCount(effectOutContext.width)
effectOutBuffer.height = vImagePixelCount(effectOutContext.height)
if hasBlur {
let inputRadius = blurRadius * Float(UIScreen.main.scale)
var radius = UInt(floorf(inputRadius * 3.0 * sqrtf(2 * Float.pi)/4 + 0.5))
if radius % 2 != 1 {
radius += 1
}
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, UInt32(radius), UInt32(radius), nil, vImage_Flags(kvImageEdgeExtend))
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, UInt32(radius), UInt32(radius), nil, vImage_Flags(kvImageEdgeExtend))
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, UInt32(radius), UInt32(radius), nil, vImage_Flags(kvImageEdgeExtend))
}
if hasSaturationChange {
let s = saturationDeltaFactor
let floatingPointSaturationMatrix = [0.0722+0.9278 * s,0.0722-0.0722 * s,0.0722-0.0722 * s,0,
0.7152-0.7152 * s,0.7152+0.2848 * s,0.7152-0.7152 * s,0,
0.2126-0.2126 * s,0.2126-0.2126 * s,0.2126+0.7873 * s,0,
0,0,0,1,]
let divisor = 256
let matrixSize = MemoryLayout.size(ofValue: floatingPointSaturationMatrix) / MemoryLayout.size(ofValue: floatingPointSaturationMatrix[0])
var saturationMatrix : Array<Int16> = Array.init()
for i in 0 ..< matrixSize {
saturationMatrix[i] = Int16(roundf(floatingPointSaturationMatrix[i] * Float(divisor)))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer,&effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags));
}
}
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.ctm.scaledBy(x: 1.0, y: -1.0)
outputContext?.ctm.translatedBy(x: 0, y: -self.size.height)
outputContext?.draw(self.cgImage!, in: imageRect)
if hasBlur {
outputContext?.saveGState()
if maskImage != nil {
outputContext?.clip(to: imageRect, mask: maskImage!.cgImage!)
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
if tintColor != nil {
outputContext?.saveGState()
outputContext?.setFillColor(tintColor!.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
/// 高亮模糊
func applyLightEffect() -> UIImage? {
let tintColor = UIColor.init(white: 1.0, alpha: 0.3)
return self.applyBlurWith(blurRadius: 30, tintColor: tintColor, saturationDeltaFactor: 1.8, maskImage: nil)
}
/// 轻度亮模糊
func applyExtraLightEffect() -> UIImage? {
let tintColor = UIColor.init(white: 0.97, alpha: 0.82)
return self.applyBlurWith(blurRadius: 20, tintColor: tintColor, saturationDeltaFactor: 1.8, maskImage: nil)
}
/// 暗色模糊
func applyDarkEffect() -> UIImage? {
let tintColor = UIColor.init(white: 0.11, alpha: 0.73)
return self.applyBlurWith(blurRadius: 20, tintColor: tintColor, saturationDeltaFactor: 1.8, maskImage: nil)
}
/// 自定义颜色模糊图片
/// - Parameter tintColor: 影响颜色
func applyTintEffectWithColor(_ tintColor : UIColor) -> UIImage? {
let effectColorAlpha : CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.components
if componentCount?.count == 2 {
var b : CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor.init(white: b, alpha: effectColorAlpha)
}
} else {
var r : CGFloat = 0,g : CGFloat = 0,b : CGFloat = 0
if tintColor.getRed(&r, green: &g, blue: &b, alpha: nil) {
effectColor = UIColor.init(red: r, green: g, blue: b, alpha: effectColorAlpha)
}
}
return self.applyBlurWith(blurRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
}
| 46.508403 | 158 | 0.568705 |
e4e689055fc227b183ddd9f64e3ae118df62e569 | 287 | //
// File.swift
//
//
// Created by ben on 6/20/21.
//
import Foundation
public struct InvoiceModel: BaseResponse {
public let date:String
public let id:Int
public let label:String
public let subtotal:Double
public let tax:Double
public let total:Double
}
| 15.944444 | 42 | 0.675958 |
3a52ec7fc409811288cab632fac6dbcdc1ffc5ed | 449 | // swiftlint:disable all
import Amplify
import Foundation
public struct Task: Model {
public let id: String
public var title: String
public var description: String?
public var status: String?
public init(id: String = UUID().uuidString,
title: String,
description: String? = nil,
status: String? = nil) {
self.id = id
self.title = title
self.description = description
self.status = status
}
} | 22.45 | 45 | 0.657016 |
dd3594ccf1c3485f84f88d2bd82e6a4598bf4e50 | 909 | //
// WYNetworkCoreTests.swift
// WYNetworkCoreTests
//
// Created by mac on 2021/4/4.
//
import XCTest
@testable import WYNetworkCore
class WYNetworkCoreTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.735294 | 111 | 0.668867 |
bbaf5e2903dcd013a8681fac2074d66e8d60be11 | 2,045 | //
// MLModelUnexpectedOutputError.swift
// StripeIdentity
//
// Created by Mel Ludowise on 1/27/22.
//
import Foundation
import CoreML
import Vision
@_spi(STP) import StripeCore
/**
Error thrown when parsing output from an ML model if the output does
not match the expected features or shape.
*/
struct MLModelUnexpectedOutputError: Error {
/**
Represents the format of a model feature that will be logged in the event
the model's feature formats are unexpected
*/
struct ModelFeatureFormat {
/// Name of the feature
let name: String
/// Type of the feature
let type: MLFeatureType
/// If this feature is a multi-array, its shape
let multiArrayShape: [NSNumber]?
}
/// The actual format of the model's features
let actual: [ModelFeatureFormat]
}
extension MLModelUnexpectedOutputError {
/**
Convenience method to creating an `unexpectedOutput` from feature observations
- Parameter observations: The observations that were returned from the ML model.
*/
@available(iOS 13.0, *)
init(observations: [VNCoreMLFeatureValueObservation]) {
self.init(actual: observations.map {
return .init(
name: $0.featureName,
type: $0.featureValue.type,
multiArrayShape: $0.featureValue.multiArrayValue?.shape
)
})
}
}
// MARK: - AnalyticLoggableError
extension MLModelUnexpectedOutputError: AnalyticLoggableError {
func serializeForLogging() -> [String : Any] {
return [
"type": String(describing: type(of: self)),
"actual": actual.map { featureFormat -> [String: Any] in
var dict: [String: Any] = [
"n": featureFormat.name,
"t": featureFormat.type.rawValue
]
if let shape = featureFormat.multiArrayShape {
dict["s"] = shape
}
return dict
}
]
}
}
| 28.402778 | 85 | 0.60489 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.