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
|
---|---|---|---|---|---|
295449d36cde4e083d588a5d1a162e9d49304a3a | 1,009 | //
// Badge.swift
// Landmarks
//
// Created by ming on 2019/6/5.
// Copyright © 2019 Apple. All rights reserved.
//
import SwiftUI
struct Badge : View {
static let rotationCount = 8
var badgeSymbols: some View {
ForEach(0..<Badge.rotationCount) { i in
RotatedBadgeSymbol(
angle: .init(degrees: Double(i) / Double(Badge.rotationCount)) * 360)
}
.opacity(0.5)
}
var body: some View {
ZStack {
BadgeBackground()
GeometryReader { geometry in
self.badgeSymbols
.scaleEffect(1.0 / 4.0, anchor: .top)
.position(x: geometry.size.width / 2.0,
y: (3.0 / 4.0) * geometry.size.height)
}
}
.scaledToFit()
}
}
#if DEBUG
struct Badge_Previews : PreviewProvider {
static var previews: some View {
Badge()
}
}
#endif
| 21.020833 | 85 | 0.489594 |
390f26d1402963308a8933ac2d70d0fadba8f9da | 2,176 | /// Copyright (c) 2020 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
public class GoToDropoffLocationPickerUseCase: UseCase {
// MARK: - Properties
let actionDispatcher: ActionDispatcher
// MARK: - Methods
public init(actionDispatcher: ActionDispatcher) {
self.actionDispatcher = actionDispatcher
}
public func start() {
let action = PickMeUpActions.GoToDropoffLocationPicker()
actionDispatcher.dispatch(action)
}
}
public protocol GoToDropoffLocationPickerUseCaseFactory {
func makeGoToDropoffLocationPickerUseCase() -> UseCase
}
| 42.666667 | 83 | 0.761949 |
b922890d0ad8c169574e170a2ce255722f16eb6b | 1,131 | //
// ReadableAssignment.swift
// PlanoutKit
//
// Created by David Christiandy on 14/08/19.
// Copyright © 2019 Traveloka. All rights reserved.
//
/// Provide ways to access assignment values.
public protocol ReadableAssignment {
/// Get value from assignment.
///
/// - Parameter name: The variable name.
/// - Returns: Assignment value.
/// - Throws: OperationError
func get(_ name: String) throws -> Any?
/// Get value from assignment, with default value.
///
/// The method will return defaultValue if there is no assignment value with matching variable name, or if the assignment value cannot be typecasted to type `T`.
///
/// - Parameters:
/// - name: The variable name
/// - defaultValue: The fallback value
/// - Returns: Assignment value or default value
/// - Throws: OperationError
func get<T>(_ name: String, defaultValue: T) throws -> T
/// Get a dictionary of evaluated values from the experiment.
///
/// - Returns: Dictionary of evaluated values
/// - Throws: OperationError
func getParams() throws -> [String: Any]
}
| 32.314286 | 165 | 0.653404 |
29ffc671e741b529d10cf8691ed302108d4c0ff5 | 438 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
struct A{class d:a{protocol a{func<}}let a=S<
| 43.8 | 78 | 0.746575 |
6a0c23e2ac32a4078e6d7ef9486ce3d449f6babd | 9,877 | //
// Evidence.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/Evidence) on 2019-11-19.
// 2019, SMART Health IT.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/**
A research context or question.
The Evidence resource describes the conditional state (population and any exposures being compared within the
population) and outcome (if specified) that the knowledge (evidence, assertion, recommendation) is about.
*/
open class Evidence: DomainResource {
override open class var resourceType: String {
get { return "Evidence" }
}
/// When the evidence was approved by publisher.
public var approvalDate: FHIRDate?
/// Who authored the content.
public var author: [ContactDetail]?
/// Contact details for the publisher.
public var contact: [ContactDetail]?
/// Use and/or publishing restrictions.
public var copyright: FHIRString?
/// Date last changed.
public var date: DateTime?
/// Natural language description of the evidence.
public var description_fhir: FHIRString?
/// Who edited the content.
public var editor: [ContactDetail]?
/// When the evidence is expected to be used.
public var effectivePeriod: Period?
/// Who endorsed the content.
public var endorser: [ContactDetail]?
/// What population?.
public var exposureBackground: Reference?
/// What exposure?.
public var exposureVariant: [Reference]?
/// Additional identifier for the evidence.
public var identifier: [Identifier]?
/// Intended jurisdiction for evidence (if applicable).
public var jurisdiction: [CodeableConcept]?
/// When the evidence was last reviewed.
public var lastReviewDate: FHIRDate?
/// Name for this evidence (computer friendly).
public var name: FHIRString?
/// Used for footnotes or explanatory notes.
public var note: [Annotation]?
/// What outcome?.
public var outcome: [Reference]?
/// Name of the publisher (organization or individual).
public var publisher: FHIRString?
/// Additional documentation, citations, etc..
public var relatedArtifact: [RelatedArtifact]?
/// Who reviewed the content.
public var reviewer: [ContactDetail]?
/// Title for use in informal contexts.
public var shortTitle: FHIRString?
/// The status of this evidence. Enables tracking the life-cycle of the content.
public var status: PublicationStatus?
/// Subordinate title of the Evidence.
public var subtitle: FHIRString?
/// Name for this evidence (human friendly).
public var title: FHIRString?
/// The category of the Evidence, such as Education, Treatment, Assessment, etc..
public var topic: [CodeableConcept]?
/// Canonical identifier for this evidence, represented as a URI (globally unique).
public var url: FHIRURL?
/// The context that the content is intended to support.
public var useContext: [UsageContext]?
/// Business version of the evidence.
public var version: FHIRString?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(exposureBackground: Reference, status: PublicationStatus) {
self.init()
self.exposureBackground = exposureBackground
self.status = status
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
approvalDate = createInstance(type: FHIRDate.self, for: "approvalDate", in: json, context: &instCtx, owner: self) ?? approvalDate
author = createInstances(of: ContactDetail.self, for: "author", in: json, context: &instCtx, owner: self) ?? author
contact = createInstances(of: ContactDetail.self, for: "contact", in: json, context: &instCtx, owner: self) ?? contact
copyright = createInstance(type: FHIRString.self, for: "copyright", in: json, context: &instCtx, owner: self) ?? copyright
date = createInstance(type: DateTime.self, for: "date", in: json, context: &instCtx, owner: self) ?? date
description_fhir = createInstance(type: FHIRString.self, for: "description", in: json, context: &instCtx, owner: self) ?? description_fhir
editor = createInstances(of: ContactDetail.self, for: "editor", in: json, context: &instCtx, owner: self) ?? editor
effectivePeriod = createInstance(type: Period.self, for: "effectivePeriod", in: json, context: &instCtx, owner: self) ?? effectivePeriod
endorser = createInstances(of: ContactDetail.self, for: "endorser", in: json, context: &instCtx, owner: self) ?? endorser
exposureBackground = createInstance(type: Reference.self, for: "exposureBackground", in: json, context: &instCtx, owner: self) ?? exposureBackground
if nil == exposureBackground && !instCtx.containsKey("exposureBackground") {
instCtx.addError(FHIRValidationError(missing: "exposureBackground"))
}
exposureVariant = createInstances(of: Reference.self, for: "exposureVariant", in: json, context: &instCtx, owner: self) ?? exposureVariant
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
jurisdiction = createInstances(of: CodeableConcept.self, for: "jurisdiction", in: json, context: &instCtx, owner: self) ?? jurisdiction
lastReviewDate = createInstance(type: FHIRDate.self, for: "lastReviewDate", in: json, context: &instCtx, owner: self) ?? lastReviewDate
name = createInstance(type: FHIRString.self, for: "name", in: json, context: &instCtx, owner: self) ?? name
note = createInstances(of: Annotation.self, for: "note", in: json, context: &instCtx, owner: self) ?? note
outcome = createInstances(of: Reference.self, for: "outcome", in: json, context: &instCtx, owner: self) ?? outcome
publisher = createInstance(type: FHIRString.self, for: "publisher", in: json, context: &instCtx, owner: self) ?? publisher
relatedArtifact = createInstances(of: RelatedArtifact.self, for: "relatedArtifact", in: json, context: &instCtx, owner: self) ?? relatedArtifact
reviewer = createInstances(of: ContactDetail.self, for: "reviewer", in: json, context: &instCtx, owner: self) ?? reviewer
shortTitle = createInstance(type: FHIRString.self, for: "shortTitle", in: json, context: &instCtx, owner: self) ?? shortTitle
status = createEnum(type: PublicationStatus.self, for: "status", in: json, context: &instCtx) ?? status
if nil == status && !instCtx.containsKey("status") {
instCtx.addError(FHIRValidationError(missing: "status"))
}
subtitle = createInstance(type: FHIRString.self, for: "subtitle", in: json, context: &instCtx, owner: self) ?? subtitle
title = createInstance(type: FHIRString.self, for: "title", in: json, context: &instCtx, owner: self) ?? title
topic = createInstances(of: CodeableConcept.self, for: "topic", in: json, context: &instCtx, owner: self) ?? topic
url = createInstance(type: FHIRURL.self, for: "url", in: json, context: &instCtx, owner: self) ?? url
useContext = createInstances(of: UsageContext.self, for: "useContext", in: json, context: &instCtx, owner: self) ?? useContext
version = createInstance(type: FHIRString.self, for: "version", in: json, context: &instCtx, owner: self) ?? version
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.approvalDate?.decorate(json: &json, withKey: "approvalDate", errors: &errors)
arrayDecorate(json: &json, withKey: "author", using: self.author, errors: &errors)
arrayDecorate(json: &json, withKey: "contact", using: self.contact, errors: &errors)
self.copyright?.decorate(json: &json, withKey: "copyright", errors: &errors)
self.date?.decorate(json: &json, withKey: "date", errors: &errors)
self.description_fhir?.decorate(json: &json, withKey: "description", errors: &errors)
arrayDecorate(json: &json, withKey: "editor", using: self.editor, errors: &errors)
self.effectivePeriod?.decorate(json: &json, withKey: "effectivePeriod", errors: &errors)
arrayDecorate(json: &json, withKey: "endorser", using: self.endorser, errors: &errors)
self.exposureBackground?.decorate(json: &json, withKey: "exposureBackground", errors: &errors)
if nil == self.exposureBackground {
errors.append(FHIRValidationError(missing: "exposureBackground"))
}
arrayDecorate(json: &json, withKey: "exposureVariant", using: self.exposureVariant, errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
arrayDecorate(json: &json, withKey: "jurisdiction", using: self.jurisdiction, errors: &errors)
self.lastReviewDate?.decorate(json: &json, withKey: "lastReviewDate", errors: &errors)
self.name?.decorate(json: &json, withKey: "name", errors: &errors)
arrayDecorate(json: &json, withKey: "note", using: self.note, errors: &errors)
arrayDecorate(json: &json, withKey: "outcome", using: self.outcome, errors: &errors)
self.publisher?.decorate(json: &json, withKey: "publisher", errors: &errors)
arrayDecorate(json: &json, withKey: "relatedArtifact", using: self.relatedArtifact, errors: &errors)
arrayDecorate(json: &json, withKey: "reviewer", using: self.reviewer, errors: &errors)
self.shortTitle?.decorate(json: &json, withKey: "shortTitle", errors: &errors)
self.status?.decorate(json: &json, withKey: "status", errors: &errors)
if nil == self.status {
errors.append(FHIRValidationError(missing: "status"))
}
self.subtitle?.decorate(json: &json, withKey: "subtitle", errors: &errors)
self.title?.decorate(json: &json, withKey: "title", errors: &errors)
arrayDecorate(json: &json, withKey: "topic", using: self.topic, errors: &errors)
self.url?.decorate(json: &json, withKey: "url", errors: &errors)
arrayDecorate(json: &json, withKey: "useContext", using: self.useContext, errors: &errors)
self.version?.decorate(json: &json, withKey: "version", errors: &errors)
}
}
| 49.883838 | 150 | 0.731599 |
f9540c0c9c1ba464ceb834678bfce74a33e73ef7 | 1,748 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension SFSymbol {
public static var _17: OneSeven { .init(name: "17") }
open class OneSeven: SFSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circle: SFSymbol { ext(.start.circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circleFill: SFSymbol { ext(.start.circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var square: SFSymbol { ext(.start.square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var squareFill: SFSymbol { ext(.start.square.fill) }
}
} | 46 | 81 | 0.731121 |
67ca1da1f4961fd16b9ad08d2c394a652f453860 | 399 | //
// FetchItemsPayload.swift
// TinyStorage
//
// Created by Roy Hsu on 2018/9/22.
//
// MARK: - FetchItemsPayload
import TinyCore
public struct FetchItemsPayload<Item> where Item: Unique {
public let items: [Item]
public let next: Page?
public init(
items: [Item] = [],
next: Page? = nil
) {
self.items = items
self.next = next
}
}
| 13.3 | 58 | 0.578947 |
48b49930de634d6e3c864a891c956f960e0f52ed | 904 | //
// ViewController.swift
// ExtentionSwift
//
// Created by 田彬彬 on 2017/6/10.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var testImageV: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// 类的扩展
"tianbin".printSelf()
let Values:Int = 10
let floatValue = Values.FloatValue
let doubleValue = Values.DoubleValue
// 压缩图片
// testImageV.image = UIImage(named: "1492263285555.jpg")?.ImageCompress(targetWidth: 100)
// 这个模糊 倒是 模糊了。不过有点耗时
testImageV.image = UIImage(named: "1492263285555.jpg")?.BlurImage(value: 6.0)
}
override func viewDidAppear(_ animated: Bool) {
self.testImageV.MoveToXwithDuration(toX: 0, duration: 0.5)
}
}
| 22.6 | 97 | 0.59292 |
14b583db774ddd2340aee0d602bfc3d871f7d070 | 10,117 | // Header.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class HeaderView: UIView {
weak var logoView: UIImageView?
weak var titleView: UILabel?
weak var closeButton: UIButton?
weak var backButton: UIButton?
weak var maskImageView: UIImageView?
weak var blurView: UIVisualEffectView?
public var onClosePressed: () -> Void = {}
public var showClose: Bool {
get {
return !(self.closeButton?.isHidden ?? true)
}
set {
self.closeButton?.isHidden = !newValue
}
}
public var onBackPressed: () -> Void = {}
public var showBack: Bool {
get {
return !(self.backButton?.isHidden ?? true)
}
set {
self.backButton?.isHidden = !newValue
}
}
public var title: String? {
get {
return self.titleView?.text
}
set {
self.titleView?.text = newValue
}
}
public var titleColor: UIColor = Style.Auth0.titleColor {
didSet {
self.titleView?.textColor = titleColor
self.setNeedsUpdateConstraints()
}
}
public var logo: UIImage? {
get {
return self.logoView?.image
}
set {
self.logoView?.image = newValue
self.setNeedsUpdateConstraints()
}
}
public var maskImage: UIImage? {
get {
return self.maskImageView?.image
}
set {
self.maskImageView?.image = newValue
self.setNeedsUpdateConstraints()
}
}
public var blurred: Bool = Style.Auth0.headerColor == nil {
didSet {
self.applyBackground()
self.setNeedsDisplay()
}
}
public var blurStyle: A0BlurEffectStyle = .light {
didSet {
self.applyBackground()
self.setNeedsDisplay()
}
}
public var maskColor: UIColor = UIColor(red: 0.8745, green: 0.8745, blue: 0.8745, alpha: 1.0) {
didSet {
self.mask?.tintColor = self.maskColor
}
}
public convenience init() {
self.init(frame: CGRect.zero)
}
required override public init(frame: CGRect) {
super.init(frame: frame)
self.layoutHeader()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layoutHeader()
}
private func layoutHeader() {
let titleView = UILabel()
let logoView = UIImageView()
let closeButton = CloseButton(type: .system)
let backButton = CloseButton(type: .system)
let centerGuide = UILayoutGuide()
self.addLayoutGuide(centerGuide)
self.addSubview(titleView)
self.addSubview(logoView)
self.addSubview(closeButton)
self.addSubview(backButton)
constraintEqual(anchor: centerGuide.centerYAnchor, toAnchor: self.centerYAnchor, constant: 10)
constraintEqual(anchor: centerGuide.centerXAnchor, toAnchor: self.centerXAnchor)
constraintEqual(anchor: titleView.bottomAnchor, toAnchor: centerGuide.bottomAnchor)
constraintEqual(anchor: titleView.centerXAnchor, toAnchor: centerGuide.centerXAnchor)
titleView.setContentCompressionResistancePriority(UILayoutPriority.priorityRequired, for: .horizontal)
titleView.setContentHuggingPriority(UILayoutPriority.priorityRequired, for: .horizontal)
titleView.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: logoView.centerXAnchor, toAnchor: self.centerXAnchor)
constraintEqual(anchor: logoView.bottomAnchor, toAnchor: titleView.topAnchor, constant: -15)
constraintEqual(anchor: logoView.topAnchor, toAnchor: centerGuide.topAnchor)
logoView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
constraintEqual(anchor: closeButton.topAnchor, toAnchor: self.safeAreaLayoutGuide.topAnchor, constant: 5)
} else {
constraintEqual(anchor: closeButton.centerYAnchor, toAnchor: self.topAnchor, constant: 45)
}
constraintEqual(anchor: closeButton.rightAnchor, toAnchor: self.rightAnchor, constant: -20)
closeButton.widthAnchor.constraint(equalToConstant: 25).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
closeButton.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
constraintEqual(anchor: backButton.topAnchor, toAnchor: self.safeAreaLayoutGuide.topAnchor, constant: 5)
} else {
constraintEqual(anchor: backButton.centerYAnchor, toAnchor: self.topAnchor, constant: 45)
}
constraintEqual(anchor: backButton.leftAnchor, toAnchor: self.leftAnchor, constant: 20)
backButton.widthAnchor.constraint(equalToConstant: 25).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
backButton.translatesAutoresizingMaskIntoConstraints = false
self.applyBackground()
self.apply(style: Style.Auth0)
titleView.font = regularSystemFont(size: 20)
logoView.image = UIImage(named: "ic_auth0", in: bundleForLock(), compatibleWith: self.traitCollection)
closeButton.setImage(UIImage(named: "ic_close", in: bundleForLock(), compatibleWith: self.traitCollection)?.withRenderingMode(.alwaysOriginal), for: .normal)
closeButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
backButton.setImage(UIImage(named: "ic_back", in: bundleForLock(), compatibleWith: self.traitCollection)?.withRenderingMode(.alwaysOriginal), for: .normal)
backButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
self.titleView = titleView
self.logoView = logoView
self.closeButton = closeButton
self.backButton = backButton
self.showBack = false
self.clipsToBounds = true
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 200, height: 128)
}
@objc func buttonPressed(_ sender: UIButton) {
if sender == self.backButton {
self.onBackPressed()
}
if sender == self.closeButton {
self.onClosePressed()
}
}
// MARK: - Blur
private var canBlur: Bool {
return self.blurred && !accessibilityIsReduceTransparencyEnabled
}
private func applyBackground() {
self.maskImageView?.removeFromSuperview()
self.blurView?.removeFromSuperview()
self.backgroundColor = self.canBlur ? .white : UIColor(red: 0.9451, green: 0.9451, blue: 0.9451, alpha: 1.0)
guard self.canBlur else { return }
let maskView = UIImageView()
let blur = UIBlurEffect(style: self.blurStyle)
let blurView = UIVisualEffectView(effect: blur)
self.insertSubview(maskView, at: 0)
self.insertSubview(blurView, at: 1)
constraintEqual(anchor: blurView.leftAnchor, toAnchor: self.leftAnchor)
constraintEqual(anchor: blurView.topAnchor, toAnchor: self.topAnchor)
constraintEqual(anchor: blurView.rightAnchor, toAnchor: self.rightAnchor)
constraintEqual(anchor: blurView.bottomAnchor, toAnchor: self.bottomAnchor)
blurView.translatesAutoresizingMaskIntoConstraints = false
maskView.translatesAutoresizingMaskIntoConstraints = false
dimension(dimension: maskView.widthAnchor, withValue: 400)
dimension(dimension: maskView.heightAnchor, withValue: 400)
constraintEqual(anchor: maskView.centerYAnchor, toAnchor: self.centerYAnchor)
constraintEqual(anchor: maskView.centerXAnchor, toAnchor: self.centerXAnchor)
maskView.contentMode = .scaleToFill
maskView.image = UIImage(named: "ic_auth0", in: bundleForLock(), compatibleWith: self.traitCollection)?.withRenderingMode(.alwaysTemplate)
maskView.tintColor = self.maskColor
self.maskImageView = maskView
self.blurView = blurView
}
}
extension HeaderView: Stylable {
func apply(style: Style) {
if let color = style.headerColor {
self.blurred = false
self.backgroundColor = color
} else {
self.blurred = true
self.blurStyle = style.headerBlur
}
self.title = style.hideTitle ? nil : style.title
self.titleColor = style.titleColor
self.logo = style.logo
self.maskImage = style.headerMask
self.backButton?.setImage(style.headerBackIcon?.withRenderingMode(.alwaysOriginal), for: .normal)
self.closeButton?.setImage(style.headerCloseIcon?.withRenderingMode(.alwaysOriginal), for: .normal)
}
}
private class CloseButton: UIButton {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return bounds.insetBy(dx: -10, dy: -10).contains(point)
}
}
| 37.194853 | 165 | 0.671246 |
fe8dbfc9f1332c189a91f1b00b7f8a41181d6227 | 399 | //
// TibTextField.swift
// ti-broish
//
// Created by Krasimir Slavkov on 29.04.21.
//
import UIKit
final class TibTextField: UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 8.0, dy: 8.0)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 8.0, dy: 8.0)
}
}
| 19.95 | 67 | 0.631579 |
91b7fac6cd8df337052d507e08e30b1aedd993d2 | 16,275 | //
// RoutesTableViewController.swift
// tpg offline
//
// Created by Rémy Da Costa Faro on 09/09/2017.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import UIKit
import Crashlytics
protocol RouteSelectionDelegate: class {
func routeSelected(_ newRoute: Route)
}
class RoutesTableViewController: UITableViewController {
public var route = Route() {
didSet {
self.tableView.reloadData()
}
}
weak var delegate: RouteSelectionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.splitViewController?.delegate = self
self.splitViewController?.preferredDisplayMode = .allVisible
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 44
navigationItem.rightBarButtonItems = [
self.editButtonItem,
UIBarButtonItem(image: #imageLiteral(resourceName: "reverse"),
style: .plain,
target: self,
action: #selector(self.reverseStops))
]
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.largeTitleTextAttributes =
[NSAttributedString.Key.foregroundColor: App.textColor]
}
navigationController?.navigationBar.titleTextAttributes =
[NSAttributedString.Key.foregroundColor: App.textColor]
if App.darkMode {
self.navigationController?.navigationBar.barStyle = .black
self.tableView.backgroundColor = .black
self.tableView.separatorColor = App.separatorColor
}
ColorModeManager.shared.addColorModeDelegate(self)
guard let rightNavController = self.splitViewController?.viewControllers.last
as? UINavigationController,
let detailViewController = rightNavController.topViewController
as? RouteResultsTableViewController else { return }
self.delegate = detailViewController
}
deinit {
ColorModeManager.shared.removeColorModeDelegate(self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
@objc func reverseStops() {
let from = self.route.from
let to = self.route.to
self.route.from = to
self.route.to = from
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
if section == 1 {
return App.favoritesRoutes.count
}
return 5 + ((self.route.via?.count ?? 0) >= 5 ? 4 : (self.route.via?.count ?? 0))
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 4 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "routesCell",
for: indexPath)
cell.backgroundColor = App.darkMode ? App.cellBackgroundColor : #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1)
let titleAttributes =
[NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .headline)]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.textColor = App.darkMode ? #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1) : .white
cell.imageView?.image = #imageLiteral(resourceName: "magnify").maskWith(color: App.darkMode ? #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1) : .white)
cell.textLabel?.attributedText =
NSAttributedString(string: Text.search,
attributes: titleAttributes)
cell.detailTextLabel?.text = ""
cell.accessoryType = .disclosureIndicator
let selectedView = UIView()
selectedView.backgroundColor = cell.backgroundColor?.darken(by: 0.1)
cell.selectedBackgroundView = selectedView
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "routesCell",
for: indexPath)
let titleAttributes =
[NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .headline)]
let subtitleAttributes =
[NSAttributedString.Key.font:
UIFont.preferredFont(forTextStyle: .subheadline)]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.textColor = App.textColor
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.textColor = App.textColor
cell.backgroundColor = App.cellBackgroundColor
cell.accessoryType = .disclosureIndicator
if App.darkMode {
let selectedView = UIView()
selectedView.backgroundColor = .black
cell.selectedBackgroundView = selectedView
} else {
let selectedView = UIView()
selectedView.backgroundColor = UIColor.white.darken(by: 0.1)
cell.selectedBackgroundView = selectedView
}
switch indexPath.row {
case 0:
cell.imageView?.image = #imageLiteral(resourceName: "firstStep@20").maskWith(color: App.textColor)
cell.textLabel?.attributedText =
NSAttributedString(string: Text.from, attributes: titleAttributes)
cell.detailTextLabel?.attributedText =
NSAttributedString(string: self.route.from?.name ?? "",
attributes: subtitleAttributes)
case 2 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
cell.imageView?.image = #imageLiteral(resourceName: "endStep@20").maskWith(color: App.textColor)
cell.textLabel?.attributedText =
NSAttributedString(string: Text.to,
attributes: titleAttributes)
cell.detailTextLabel?.attributedText =
NSAttributedString(string: self.route.to?.name ?? "",
attributes: subtitleAttributes)
case 3 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
cell.imageView?.image = #imageLiteral(resourceName: "clock").maskWith(color: App.textColor)
cell.textLabel?.attributedText =
NSAttributedString(string: self.route.arrivalTime ?
Text.arrivalAt : Text.departureAt,
attributes: titleAttributes)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = Calendar.current.isDateInToday(self.route.date) ?
.none : .short
dateFormatter.timeStyle = .short
cell.detailTextLabel?.attributedText =
NSAttributedString(string: dateFormatter.string(from: self.route.date),
attributes: subtitleAttributes)
default:
cell.imageView?.image = #imageLiteral(resourceName: "middleStep@20").maskWith(color: App.textColor)
let viaNumber = indexPath.row - 1
if (self.route.via?.count ?? 0) == 0 {
cell.textLabel?.attributedText =
NSAttributedString(string: Text.via,
attributes: titleAttributes)
} else {
cell.textLabel?.attributedText =
NSAttributedString(string: Text.via(number: viaNumber),
attributes: titleAttributes)
}
if let stop = self.route.via?[safe: viaNumber] {
cell.detailTextLabel?.attributedText =
NSAttributedString(string: stop.name, attributes: subtitleAttributes)
} else {
cell.detailTextLabel?.attributedText =
NSAttributedString(string: Text.optional,
attributes: subtitleAttributes)
cell.detailTextLabel?.textColor = App.textColor.lighten()
}
}
return cell
}
} else {
self.tableView.deselectRow(at: indexPath, animated: true)
guard let cell =
tableView.dequeueReusableCell(withIdentifier: "favoriteRouteCell",
for: indexPath) as? FavoriteRouteTableViewCell
else { return UITableViewCell() }
cell.route = App.favoritesRoutes[indexPath.row]
if indexPath.row % 2 == 0 {
cell.backgroundColor = App.cellBackgroundColor
} else {
cell.backgroundColor = App.cellBackgroundColor.darken(by: 0.025)
}
return cell
}
}
@objc func search() {
if route.to == nil, let stop = route.via?.last {
route.to = stop
route.via?.removeLast()
}
if route.validRoute == .valid {
self.delegate?.routeSelected(self.route)
if let detailViewController = delegate as? RouteResultsTableViewController,
let detailNavigationController = detailViewController.navigationController {
splitViewController?.showDetailViewController(detailNavigationController,
sender: nil)
detailNavigationController.popToRootViewController(animated: false)
}
} else {
let message: String
switch route.validRoute {
case .departureAndArrivalMissing:
message = Text.departureAndArrivalMissing
case .departureMissing:
message = Text.departureMissing
case .arrivalMissing:
message = Text.arrivalMissing
case .sameDepartureAndArrival:
message = Text.sameDepartureAndArrival
default:
message = Text.missingErrorMessage
}
let alertView = UIAlertController(title: Text.invalidRoute,
message: message,
preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: Text.ok,
style: .default,
handler: nil))
self.present(alertView, animated: true, completion: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showStopsForRoute" {
guard let indexPath = sender as? IndexPath else { return }
guard let destinationViewController = segue.destination as?
StopsForRouteTableViewController else {
return
}
switch indexPath.row {
case 0:
destinationViewController.fromToVia = .from
case 2 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
destinationViewController.fromToVia = .to
default:
destinationViewController.fromToVia = .via(indexPath.row - 1)
}
}
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
self.route = App.favoritesRoutes[indexPath.row]
self.route.date = Date()
self.route.arrivalTime = false
search()
return
}
switch indexPath.row {
case 0:
App.log("Selected from stop select")
performSegue(withIdentifier: "showStopsForRoute", sender: indexPath)
case 2 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
App.log("Selected to stop select")
performSegue(withIdentifier: "showStopsForRoute", sender: indexPath)
case 3 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
App.log("Selected date select")
DatePickerDialog(showCancelButton: false)
.show("Select date".localized,
doneButtonTitle: "OK".localized,
cancelButtonTitle: "Cancel".localized,
nowButtonTitle: "Now".localized,
defaultDate: self.route.date,
minimumDate: nil,
maximumDate: nil,
datePickerMode: .dateAndTime,
arrivalTime: self.route.arrivalTime) { arrivalTime, date in
if let date = date {
self.route.date = date
self.route.arrivalTime = arrivalTime
print(arrivalTime)
}
}
case 4 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
search()
default:
App.log("Selected to stop select")
performSegue(withIdentifier: "showStopsForRoute", sender: indexPath)
}
}
override func tableView(_ tableView: UITableView,
canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 1 {
return true
} else {
switch indexPath.row {
case 0:
return false
case 2 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
return false
case 3 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
return !self.tableView.isEditing
case 4 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0):
return false
case 1 + (self.route.via?.count ?? 0):
return false
default:
return self.route.via?.count != 0
}
}
}
override func tableView(_ tableView: UITableView,
editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// swiftlint:disable:previous line_length
if indexPath.section == 0,
indexPath.row == 3 + (self.route.via?.count ?? 0) -
((self.route.via?.count ?? 0) >= 5 ? 1 : 0) {
let setToNowAction = UITableViewRowAction(style: .normal,
title: Text.now) { (_, _) in
self.route.date = Date()
}
if App.darkMode {
setToNowAction.backgroundColor = .black
} else {
setToNowAction.backgroundColor = #colorLiteral(red: 0.2470588235, green: 0.3176470588, blue: 0.7098039216, alpha: 1)
}
return [setToNowAction]
} else if indexPath.section == 1 {
let reverseAction = UITableViewRowAction(style: .normal,
title: Text.reversed) { (_, _) in
self.route = App.favoritesRoutes[indexPath.row]
let from = self.route.from
let to = self.route.to
self.route.from = to
self.route.to = from
self.route.date = Date()
self.search()
}
if App.darkMode {
reverseAction.backgroundColor = .black
} else {
reverseAction.backgroundColor = #colorLiteral(red: 0.6117647059, green: 0.1529411765, blue: 0.6901960784, alpha: 1)
}
return [reverseAction, UITableViewRowAction(style: .destructive,
title: Text.delete,
handler: { (_, indexPath) in
App.favoritesRoutes.remove(at: indexPath.row)
self.tableView.reloadData()
})]
} else {
return [UITableViewRowAction(style: .destructive,
title: Text.delete,
handler: { (_, indexPath) in
self.route.via?.remove(at: indexPath.row - 1)
self.tableView.reloadData()
})]
}
}
override func tableView(_ tableView: UITableView,
moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
App.favoritesRoutes.rearrange(from: fromIndexPath.row, to: to.row)
}
override func tableView(_ tableView: UITableView,
canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 1
}
}
extension RoutesTableViewController: UISplitViewControllerDelegate {
func splitViewController(_ splitViewController: UISplitViewController,
collapseSecondary secondaryViewController: UIViewController, // swiftlint:disable:this line_length
onto primaryViewController: UIViewController) -> Bool {
return true
}
}
| 39.122596 | 184 | 0.608295 |
fb46c329725450d4d63a57e32a52a0745185c80b | 1,960 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import XCTest
import AeroGearHttp
class JSONRequestSerializer: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testHeadersShouldExistOnRequestWhenPUT() {
let url = "http://api.icndb.com/jokes/12"
let serialiser = JsonRequestSerializer()
let result = serialiser.request(url: URL(string: url)!, method:.put, parameters: ["param1": "value1"], headers: ["CUSTOM_HEADER": "a value"])
// header should be contained on the returned request
let header = result.allHTTPHeaderFields!["CUSTOM_HEADER"]
XCTAssertNotNil(header)
XCTAssertTrue(header == "a value", "header should match")
}
func testHeadersShouldExistOnRequestWhenPOST() {
let url = "http://api.icndb.com/jokes/12"
let serialiser = JsonRequestSerializer()
let result = serialiser.request(url: URL(string: url)!, method:.post, parameters: ["param1": "value1"], headers: ["CUSTOM_HEADER": "a value"])
// header should be contained on the returned request
let header = result.allHTTPHeaderFields!["CUSTOM_HEADER"]
XCTAssertNotNil(header)
XCTAssertTrue(header == "a value", "header should match")
}
}
| 35.636364 | 150 | 0.684184 |
1c1b8c9f224f21b838a942b9953c86f9dbee3251 | 1,781 | //
// Copyright (c) 2016 Adam Shin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension UITableView {
private struct AssociatedKeys {
static var reorderController: UInt8 = 0
}
/// An object that manages drag-and-drop reordering of table view cells.
public var reorder: ReorderController {
if let controller = objc_getAssociatedObject(self, &AssociatedKeys.reorderController) as? ReorderController {
return controller
} else {
let controller = ReorderController(tableView: self)
objc_setAssociatedObject(self, &AssociatedKeys.reorderController, controller, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return controller
}
}
}
| 41.418605 | 125 | 0.730488 |
2852035b547381f5ab4099e0e45ad5c906b3d8c3 | 909 | //
// On_The_MapTests.swift
// On The MapTests
//
// Created by Luis Matute on 5/21/15.
// Copyright (c) 2015 Luis Matute. All rights reserved.
//
import UIKit
import XCTest
class On_The_MapTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.567568 | 111 | 0.614961 |
1dd27ab58bcc50bf6d06ac1f7141396f0b229e7e | 2,187 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// PostAttributionDataOperation.swift
//
// Created by Joshua Liebowitz on 11/19/21.
import Foundation
class PostAttributionDataOperation: NetworkOperation {
private let configuration: UserSpecificConfiguration
private let attributionData: [String: Any]
private let network: AttributionNetwork
private let responseHandler: SimpleResponseHandler?
init(configuration: UserSpecificConfiguration,
attributionData: [String: Any],
network: AttributionNetwork,
responseHandler: SimpleResponseHandler?) {
self.attributionData = attributionData
self.network = network
self.configuration = configuration
self.responseHandler = responseHandler
super.init(configuration: configuration)
}
override func begin(completion: @escaping () -> Void) {
self.post(completion: completion)
}
private func post(completion: @escaping () -> Void) {
guard let appUserID = try? self.configuration.appUserID.escapedOrError() else {
self.responseHandler?(ErrorUtils.missingAppUserIDError())
completion()
return
}
let request = HTTPRequest(method: .post(Body(network: self.network, attributionData: self.attributionData)),
path: .postAttributionData(appUserID: appUserID))
self.httpClient.perform(request, authHeaders: self.authHeaders) { response in
defer {
completion()
}
self.responseHandler?(response.error)
}
}
}
private extension PostAttributionDataOperation {
struct Body: Encodable {
let network: AttributionNetwork
let data: AnyEncodable
init(network: AttributionNetwork, attributionData: [String: Any]) {
self.network = network
self.data = AnyEncodable(attributionData)
}
}
}
| 28.776316 | 116 | 0.661637 |
d955ddea4fc605f05411d10aaa4436df6c1d486e | 1,406 | //
// UIApplication+MailComposer.swift
// Test
//
// Created by Sauvik Dolui on 25/02/19.
// Copyright © 2019 Sauvik Dolui. All rights reserved.
//
import Foundation
import UIKit
/// Public protocol to be confirmed to open a mail composer
public protocol UIApplicationMailComposer {
/// Checks whether an URL from `LSApplicationQueriesSchemes` can be opened
///
/// - Parameter url: The URL which is to be opened
/// - Returns: `true` or `false` based on it's availability
func canOpenURL(_ url: URL) -> Bool
func openMailURL(_ url: URL, completionHandler: ((Bool) -> Void)?)
}
// MARK: - `UIApplication` conforming to `UIApplicationMailComposer`
extension UIApplication: UIApplicationMailComposer {
public func openMailURL(_ url: URL, completionHandler: ((Bool) -> Void)?) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: completionHandler)
} else {
openURL(url)
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
| 36.051282 | 153 | 0.715505 |
871639d58d7343e604431c34699a8207d8b0b261 | 3,702 | //
// ArgumentMatcher.swift
// Mockingbird
//
// Created by Andrew Chang on 7/29/19.
//
import Foundation
/// Matches argument values with a comparator.
@objc(MKBArgumentMatcher) public class ArgumentMatcher: NSObject {
/// Necessary for custom comparators such as `any()` that only work on the lhs.
enum Priority: UInt {
case low = 0, `default` = 500, high = 1000
}
/// A base instance to compare using `comparator`.
let base: Any?
/// The original type of the base instance.
let baseType: Any?
/// A debug description for verbose test failure output.
let internalDescription: String
public override var description: String { return internalDescription }
/// The declaration of the matcher to use in test failure examples.
let declaration: String
/// The commutativity of the matcher comparator.
let priority: Priority
/// The method to compare base instances, returning `true` if they should be considered the same.
let comparator: (_ lhs: Any?, _ rhs: Any?) -> Bool
func compare(with rhs: Any?) -> Bool {
return comparator(base, rhs)
}
init<T: Equatable>(_ base: T?,
description: String? = nil,
declaration: String? = nil,
priority: Priority = .default) {
self.base = base
self.baseType = T.self
self.priority = priority
self.comparator = { base == $1 as? T }
let internalDescription = description ?? "\(String.describe(base))"
self.internalDescription = internalDescription
self.declaration = declaration ?? internalDescription
}
convenience init(description: String,
declaration: String? = nil,
priority: Priority = .low,
comparator: @escaping () -> Bool) {
self.init(Optional<ArgumentMatcher>(nil), description: description, priority: priority) {
(_, _) -> Bool in
return comparator()
}
}
init<T>(_ base: T? = nil,
description: String? = nil,
declaration: String? = nil,
priority: Priority = .low,
comparator: ((Any?, Any?) -> Bool)? = nil) {
self.base = base
self.baseType = type(of: base)
self.priority = priority
self.comparator = comparator ?? { $0 as AnyObject === $1 as AnyObject }
let annotation = comparator == nil ? " (by reference)" : ""
let internalDescription = description ?? "\(String.describe(base))\(annotation)"
self.internalDescription = internalDescription
self.declaration = declaration ?? internalDescription
}
@objc public init(_ base: Any? = nil,
description: String? = nil,
comparator: @escaping (Any?, Any?) -> Bool) {
self.base = base
self.baseType = type(of: base)
self.priority = .low
self.comparator = comparator
let internalDescription = description ?? String.describe(base)
self.internalDescription = internalDescription
self.declaration = internalDescription
}
init(_ matcher: ArgumentMatcher) {
self.base = matcher.base
self.baseType = type(of: matcher.base)
self.priority = matcher.priority
self.comparator = matcher.comparator
self.internalDescription = matcher.description
self.declaration = matcher.declaration
}
}
// MARK: - Equatable
extension ArgumentMatcher {
public static func == (lhs: ArgumentMatcher, rhs: ArgumentMatcher) -> Bool {
if lhs.priority.rawValue >= rhs.priority.rawValue {
return lhs.compare(with: rhs.base)
} else {
return rhs.compare(with: lhs.base)
}
}
public static func != (lhs: ArgumentMatcher, rhs: ArgumentMatcher) -> Bool {
return !(lhs == rhs)
}
}
| 31.372881 | 99 | 0.641815 |
e4c8ba0624b8cfe77f0d6f9c5d6335a9cd419f1c | 19,199 | /*
ViewController.swift
MobileSyncExplorerSwift
Created by Raj Rao on 05/16/18.
Copyright (c) 2018-present, salesforce.com, inc. All rights reserved.
Redistribution and use of this software in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written
permission of salesforce.com, inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import SmartStore
import MobileSync
import Combine
enum SObjectConstants {
static let kSObjectIdField = "Id"
}
extension Dictionary {
func nonNullObject(forKey key: Key) -> Any? {
let result = self[key]
if (result as? NSNull) == NSNull() {
return nil
}
if (result is String) {
let res = result as! String
if ((res == "<nil>") || (res == "<null>")) {
return nil
}
}
return result
}
}
extension Optional where Wrapped == String {
var _bound: String? {
get {
return self
}
set {
self = newValue
}
}
public var bound: String {
get {
return _bound ?? ""
}
set {
_bound = newValue.isEmpty ? nil : newValue
}
}
}
class SObjectData {
var soupDict = [String: Any]()
init(soupDict: [String: Any]?) {
if soupDict != nil {
self.updateSoup(soupDict)
}
}
init() {
soupDict = [:]
let spec = type(of: self).dataSpec()
self.initSoupValues(spec?.fieldNames)
updateSoup(forFieldName: "attributes", fieldValue: ["type": spec?.objectType])
}
class func dataSpec() -> SObjectDataSpec? {
return nil
}
func initSoupValues(_ fieldNames: [Any]?) {
self.soupDict.forEach { (key,value) in
self.soupDict[key] = nil
}
}
func fieldValue(forFieldName fieldName: String) -> Any? {
return self.soupDict[fieldName]
}
func updateSoup(forFieldName fieldName: String, fieldValue: Any?) {
self.soupDict[fieldName] = fieldValue
}
func updateSoup(_ soupDict: [String: Any]?) -> Void {
guard let soupDict = soupDict else {
return;
}
soupDict.forEach({ (key, value) in
self.soupDict[key] = value
})
}
func nonNullFieldValue(_ fieldName: String?) -> Any? {
return self.soupDict.nonNullObject(forKey: fieldName!)
}
}
class SObjectDataSpec {
var objectType = ""
var objectFieldSpecs = [SObjectDataFieldSpec]()
var soupName = ""
var orderByFieldName = ""
var fieldNames :[String] {
get {
var mutableFieldNames = [String]()
objectFieldSpecs.forEach { (spec) in
if (spec.fieldName != "") {
mutableFieldNames.append(spec.fieldName)
}
}
return mutableFieldNames
}
}
var soupFieldNames :[String] {
get {
var retNames = [String]()
objectFieldSpecs.forEach { (spec) in
if (spec.fieldName != "") {
retNames.append(spec.fieldName)
}
}
return retNames
}
}
init(objectType: String?, objectFieldSpecs: [SObjectDataFieldSpec], soupName: String, orderByFieldName: String) {
self.objectType = objectType ?? ""
self.objectFieldSpecs = buildObjectFieldSpecs(objectFieldSpecs)
self.soupName = soupName
self.orderByFieldName = orderByFieldName
}
func buildObjectFieldSpecs(_ origObjectFieldSpecs: [SObjectDataFieldSpec]) -> [SObjectDataFieldSpec] {
let spec: [SObjectDataFieldSpec] = origObjectFieldSpecs.filter({ (fieldSpec) -> Bool in
return fieldSpec.fieldName == SObjectConstants.kSObjectIdField
})
if (spec.count > 0) {
var objectFieldSpecsWithId: [SObjectDataFieldSpec] = [SObjectDataFieldSpec]()
let idSpec = SObjectDataFieldSpec(fieldName: SObjectConstants.kSObjectIdField, searchable: false)
objectFieldSpecsWithId.insert(idSpec, at: 0)
return objectFieldSpecsWithId
} else {
return origObjectFieldSpecs
}
}
func buildSoupIndexSpecs(_ origIndexSpecs: [SoupIndex]?) -> [SoupIndex]? {
var mutableIndexSpecs: [SoupIndex] = []
guard let origIndexSpecs = origIndexSpecs else {
return mutableIndexSpecs
}
let isLocalDataIndexSpec = SoupIndex(path: kSyncTargetLocal, indexType: kSoupIndexTypeString, columnName: kSyncTargetLocal)
mutableIndexSpecs.insert(isLocalDataIndexSpec!, at: 0)
let foundIdSpec:[SoupIndex]? = origIndexSpecs.filter { (index) -> Bool in
return index.path == SObjectConstants.kSObjectIdField
}
if (foundIdSpec == nil || (foundIdSpec?.count)! < 1) {
let dataIndexSpec = SoupIndex(path: SObjectConstants.kSObjectIdField, indexType: kSoupIndexTypeString, columnName: SObjectConstants.kSObjectIdField)
mutableIndexSpecs.insert(dataIndexSpec!, at: 0)
}
return mutableIndexSpecs
}
class func createSObjectData(_ soupDict: [String : Any]?) throws -> SObjectData? {
return nil
}
}
class SObjectDataFieldSpec {
var fieldName: String = ""
var isSearchable = false
init(fieldName: String?, searchable isSearchable: Bool) {
self.fieldName = fieldName ?? ""
self.isSearchable = isSearchable
}
}
class SObjectDataManager: ObservableObject {
static private var managers = SafeMutableDictionary<NSString, SObjectDataManager>()
@Published var contacts: [ContactSObjectData] = []
private var cancellableSet: Set<AnyCancellable> = []
//Constants
let kSyncDownName = "syncDownContacts"
let kSyncUpName = "syncUpContacts"
private let kMaxQueryPageSize: UInt = 1000
var store: SmartStore
var syncMgr: SyncManager
var dataSpec: SObjectDataSpec
init(dataSpec: SObjectDataSpec, userAccount: UserAccount) {
syncMgr = SyncManager.sharedInstance(forUserAccount: userAccount)
store = SmartStore.shared(withName: SmartStore.defaultStoreName, forUserAccount: userAccount)!
self.dataSpec = dataSpec
// Setup store and syncs if needed
MobileSyncSDKManager.shared.setupUserStoreFromDefaultConfig()
MobileSyncSDKManager.shared.setupUserSyncsFromDefaultConfig()
NotificationCenter.default.addObserver(forName: UserAccountManager.didLogoutUser, object: nil, queue: nil) { _ in
let key = NSString(string: SFKeyForUserAndScope(userAccount, UserAccount.AccountScope.community)!)
SObjectDataManager.managers[key] = nil
}
}
static func sharedInstance(for userAccount: UserAccount) -> SObjectDataManager {
let key = NSString(string: SFKeyForUserAndScope(userAccount, UserAccount.AccountScope.community)!)
if let manager = managers[key] {
return manager
} else {
let newManager = SObjectDataManager(dataSpec: ContactSObjectData.dataSpec()!, userAccount: userAccount)
managers[key] = newManager
return newManager
}
}
func syncUpDown(completion: @escaping (Bool) -> ()) {
syncMgr.publisher(for: kSyncUpName)
.flatMap { _ in
self.syncMgr.publisher(for: self.kSyncDownName)
}
.flatMap { _ in
self.syncMgr.cleanGhostsPublisher(for: self.kSyncDownName)
}
.receive(on: RunLoop.main)
.sink(receiveCompletion: { [weak self] result in
switch result {
case .failure(let mobileSyncError):
MobileSyncLogger.e(SObjectDataManager.self, message: "Sync failed: \(mobileSyncError.localizedDescription)")
completion(false)
case .finished:
self?.loadLocalData()
completion(true)
}
}, receiveValue: { _ in })
.store(in: &cancellableSet)
loadLocalData()
}
func fetchContact(id: String, completion: @escaping (ContactSObjectData?) -> ()) {
let request = RestClient.shared.request(forQuery: "SELECT Id, FirstName, LastName, Title, MobilePhone, Email, Department, HomePhone FROM Contact WHERE Id = '\(id)'", apiVersion: nil)
RestClient.shared.publisher(for: request)
.receive(on: RunLoop.main)
.sink(receiveCompletion: { _ in
}, receiveValue: { [weak self] response in
do {
guard let json = try response.asJson() as? [String: Any],
let records = json["records"] as? [[String: Any]],
records.count > 0 else {
completion(nil)
return
}
try self?.store.upsert(entries: records, forSoupNamed: "contacts", withExternalIdPath: "Id")
self?.loadLocalData() // Keep list in sync
} catch {
MobileSyncLogger.e(SObjectDataManager.self, message: "Contact error: \(error)")
completion(ContactSObjectData.init(soupDict: self?.localRecord(id: id)))
}
let localRecord = ContactSObjectData.init(soupDict: self?.localRecord(id: id))
completion(localRecord)
})
.store(in: &cancellableSet)
}
func loadLocalData() {
let sobjectsQuerySpec = QuerySpec.buildAllQuerySpec(soupName: dataSpec.soupName, orderPath: dataSpec.orderByFieldName, order: .ascending, pageSize: kMaxQueryPageSize)
store.publisher(for: sobjectsQuerySpec.smartSql)
.receive(on: RunLoop.main)
.tryMap {
$0.map { (data) -> ContactSObjectData in
let record = data as! [Any]
return ContactSObjectData(soupDict: record[0] as? [String : Any])
}
}
.catch { error -> Just<[ContactSObjectData]> in
MobileSyncLogger.e(SObjectDataManager.self, message: "Query failed: \(error)")
return Just([ContactSObjectData]())
}
.assign(to: \.contacts, on: self)
.store(in: &cancellableSet)
}
func createLocalData(_ newData: SObjectData?) {
guard let newData = newData else {
return
}
newData.updateSoup(forFieldName: kSyncTargetLocal, fieldValue: true)
newData.updateSoup(forFieldName: kSyncTargetLocallyCreated, fieldValue: true)
let sobjectSpec = type(of: newData).dataSpec()
store.upsert(entries: [newData.soupDict], forSoupNamed: (sobjectSpec?.soupName)!)
loadLocalData()
}
func updateLocalData(_ updatedData: SObjectData?) {
guard let updatedData = updatedData else {
return
}
updatedData.updateSoup(forFieldName: kSyncTargetLocal, fieldValue: true)
updatedData.updateSoup(forFieldName: kSyncTargetLocallyUpdated, fieldValue: true)
let sobjectSpec = type(of: updatedData).dataSpec()
store.upsert(entries: [updatedData.soupDict], forSoupNamed: (sobjectSpec?.soupName)!)
loadLocalData()
}
func deleteLocalData(_ dataToDelete: SObjectData?) {
guard let dataToDelete = dataToDelete else {
return
}
dataToDelete.updateSoup(forFieldName: kSyncTargetLocal, fieldValue: true)
dataToDelete.updateSoup(forFieldName: kSyncTargetLocallyDeleted, fieldValue: true)
let sobjectSpec = type(of: dataToDelete).dataSpec()
store.upsert(entries: [dataToDelete.soupDict], forSoupNamed: (sobjectSpec?.soupName)!)
loadLocalData()
}
func undeleteLocalData(_ dataToUnDelete: SObjectData?) {
guard let dataToUnDelete = dataToUnDelete else {
return
}
dataToUnDelete.updateSoup(forFieldName: kSyncTargetLocallyDeleted, fieldValue: false)
let locallyCreatedOrUpdated = SObjectDataManager.dataLocallyCreated(dataToUnDelete) || SObjectDataManager.dataLocallyUpdated(dataToUnDelete) ? 1 : 0
dataToUnDelete.updateSoup(forFieldName: kSyncTargetLocal, fieldValue: locallyCreatedOrUpdated)
let sobjectSpec = type(of: dataToUnDelete).dataSpec()
do {
_ = try store.upsert(entries: [dataToUnDelete.soupDict], forSoupNamed: (sobjectSpec?.soupName)!, withExternalIdPath: SObjectConstants.kSObjectIdField)
loadLocalData()
} catch let error as NSError {
MobileSyncLogger.e(SObjectDataManager.self, message: "Undelete local data failed \(error)")
}
}
static func dataLocallyCreated(_ data: SObjectData?) -> Bool {
guard let data = data else {
return false
}
let value = data.fieldValue(forFieldName: kSyncTargetLocallyCreated) as? Bool
return value ?? false
}
static func dataLocallyUpdated(_ data: SObjectData?) -> Bool {
guard let data = data else {
return false
}
let value = data.fieldValue(forFieldName: kSyncTargetLocallyUpdated) as? Bool
return value ?? false
}
static func dataLocallyDeleted(_ data: SObjectData?) -> Bool {
guard let data = data else {
return false
}
let value = data.fieldValue(forFieldName: kSyncTargetLocallyDeleted) as? Bool
return value ?? false
}
func clearLocalData() {
store.clearSoup(dataSpec.soupName)
resetSync(kSyncDownName)
resetSync(kSyncUpName)
loadLocalData()
}
func stopSyncManager() {
syncMgr.stop()
}
func resumeSyncManager(_ completion: @escaping (SyncState) -> Void) throws -> Void {
try self.syncMgr.restart(restartStoppedSyncs:true, onUpdate:{ [weak self] (syncState) in
if (syncState.status == .done) {
self?.loadLocalData()
}
completion(syncState)
})
}
func cleanGhosts(onError: @escaping (MobileSyncError) -> (), onValue: @escaping (UInt) -> ()) {
syncMgr.cleanGhostsPublisher(for: kSyncDownName)
.receive(on: RunLoop.main)
.sink(receiveCompletion: { result in
if case .failure(let mobileSyncError) = result {
onError(mobileSyncError)
}
}, receiveValue: { numRecords in
onValue(numRecords)
})
.store(in: &cancellableSet)
}
func sync(syncName: String, onError: @escaping (MobileSyncError) -> (), onValue: @escaping (SyncState) -> ()) {
syncMgr.publisher(for: kSyncDownName)
.receive(on: RunLoop.main)
.sink(receiveCompletion: { result in
if case .failure(let mobileSyncError) = result {
onError(mobileSyncError)
}
}, receiveValue: { syncState in
onValue(syncState)
})
.store(in: &cancellableSet)
}
func getSync(_ syncName: String) -> SyncState? {
return syncMgr.syncStatus(forName: syncName)
}
func isSyncManagerStopping() -> Bool {
return syncMgr.isStopping()
}
func isSyncManagerStopped() -> Bool {
return syncMgr.isStopped()
}
func countContacts() -> Int {
var count = -1
if let querySpec = QuerySpec.buildSmartQuerySpec(smartSql: "select * from {\(dataSpec.soupName)}", pageSize: UInt.max) {
do {
count = try store.count(using:querySpec).intValue
} catch {
MobileSyncLogger.e(SObjectDataManager.self, message: "countContacts \(error)" )
}
}
return count
}
private func resetSync(_ syncName: String) {
let sync = syncMgr.syncStatus(forName:syncName)
sync?.maxTimeStamp = -1
sync?.progress = 0
sync?.status = .new
sync?.totalSize = -1
sync?.save(store)
}
private func localRecord(id: String) -> [String: Any]? {
let queryResult = store.query("select {\(dataSpec.soupName):_soup} from {\(dataSpec.soupName)} where {\(dataSpec.soupName):Id} = '\(id)'")
switch queryResult {
case .success(let results):
guard let arr = results as? [[Any]], let soup = arr.first?.first as? [String: Any] else {
MobileSyncLogger.e(SObjectDataManager.self, message: "Unable to parse local record")
return nil
}
return soup
case .failure(let error):
MobileSyncLogger.e(SObjectDataManager.self, message: "Error getting local record: \(error)")
return nil
}
}
func localRecord(soupID: String) -> ContactSObjectData? {
let queryResult = store.query("select {\(dataSpec.soupName):_soup} from {\(dataSpec.soupName)} where {\(dataSpec.soupName):_soupEntryId} = '\(soupID)'")
switch queryResult {
case .success(let results):
guard let arr = results as? [[Any]], let soup = arr.first?.first as? [String: Any] else {
MobileSyncLogger.e(SObjectDataManager.self, message: "Unable to parse local record")
return nil
}
return ContactSObjectData.init(soupDict: soup)
case .failure(let error):
MobileSyncLogger.e(SObjectDataManager.self, message: "Error getting local record: \(error)")
return nil
}
}
deinit {
cancellableSet.forEach { $0.cancel() }
}
}
| 37.135397 | 190 | 0.614876 |
56e36bd92dc8b26d7750a54e7e3c67c5f5078200 | 279 | //
// Carrier.swift
// WAL
//
// Created by Christian Braun on 22.08.18.
//
import Foundation
struct Carrier <A: Codable>: Codable {
let data: A
let from: String
enum CodingKeys: String, CodingKey {
case data = "Data"
case from = "From"
}
}
| 14.684211 | 43 | 0.587814 |
61f1147940738c565fd5f2f88cc5e4ecaab4db15 | 19,502 | //
// SimpleSolver.swift
// Cassowary
//
// Created by nangezao on 2017/10/22.
// Copyright © 2017年 nange. All rights reserved.
//
public enum ConstraintError: Error {
case requiredFailure
case objectiveUnbound
case constraintNotFound
case internalError(String)
case requiredFailureWithExplanation([Constraint])
}
typealias VarSet = RefBox<Set<Variable>>
fileprivate typealias Row = [Variable: Expression]
fileprivate typealias Column = [Variable: VarSet]
private struct ConstraintInfo {
let marker: Variable
let errors: [Variable]
init(marker: Variable,errors: [Variable]) {
self.marker = marker
self.errors = errors
}
}
final public class SimplexSolver {
// whether call solve() when add or remove constraint
// if false, remeber to call solve() to get right result
public var autoSolve = false
public var explainFailure = true
private var rows = Row()
private var columns = Column()
// used to record infeasible rows when edit constarint
// which means marker of this row is not external variable,but constant of expr < 0
// we need to optimize this later
private var infeasibleRows = Set<Variable>()
// pivotable and coefficient < 0 variables in objective,we track this variables to avoid traverse when optimize
private var entryVars = Set<Variable>()
private var constraintMarkered = [Variable: Constraint]()
// mapper for constraint and marker, errors variable
private var constraintInfos = [Constraint: ConstraintInfo]()
// objective function, out goal is to minimize this function
private var objective = Expression()
public init() {}
public func add(constraint: Constraint) throws {
let expr = expression(for: constraint)
let addedOKDirectly = tryToAdd(expr: expr)
if !addedOKDirectly {
let result = try addArtificalVariable(to: expr)
if !result.0 {
try remove(constraint: constraint)
throw ConstraintError.requiredFailureWithExplanation(result.1)
}
}
if autoSolve {
try solve()
}
}
public func remove(constraint: Constraint) throws {
guard let info = constraintInfos[constraint] else {
throw ConstraintError.constraintNotFound
}
// remove errorVar from objective function
info.errors.forEach {
add(expr: objective, variable: $0, delta: -constraint.weight)
entryVars.remove($0)
if isBasicVar($0) {
removeRow(for: $0)
}
}
constraintInfos.removeValue(forKey: constraint)
let marker = info.marker
constraintMarkered.removeValue(forKey: marker)
if !isBasicVar(marker) {
if let exitVar = findExitVar(for: marker) {
pivot(entry: marker, exit: exitVar)
}
}
if isBasicVar(marker) {
removeRow(for: marker)
}
if autoSolve {
try solve()
}
}
/// update constant for constraint to value
///
/// - Parameters:
/// - constraint: constraint to update
/// - value: target constant
public func updateConstant(for constraint: Constraint,to value: Double) {
assert(constraintInfos.keys.contains(constraint))
if !constraintInfos.keys.contains(constraint) {
return
}
var delta = -(value + constraint.expression.constant)
if constraint.relation == .lessThanOrEqual {
delta = (value - constraint.expression.constant)
}
if approx(a: delta, b: 0) {
return
}
editConstant(for: constraint, delta: delta)
constraint.updateConstant(to: value)
resolve()
}
/// update strength for constraint
/// required constraint is not allowed to modify
/// - Parameters:
/// - constraint: constraint to update
/// - strength: target strength
public func updateStrength(for constraint: Constraint, to strength: Strength) throws {
if constraint.strength == strength {
return
}
guard let errorVars = constraintInfos[constraint]?.errors else {
return
}
let delta = strength.rawValue - constraint.weight
constraint.strength = strength
// strength only affact objective function
errorVars.forEach {
add(expr: objective, variable: $0, delta: delta)
updateEntryIfNeeded(for: $0)
}
if autoSolve {
try solve()
}
}
/// solver this simplex problem
public func solve() throws {
try optimize(objective)
}
private func resolve() {
_ = try? dualOptimize()
infeasibleRows.removeAll()
}
public func valueFor(_ variable: Variable) -> Double? {
return rows[variable]?.constant
}
/// optimize objective function,minimize expr
/// objective = a1*s1 + a2 * s2 + a3 * e3 + a4 * e4 ...+ an*(sn,or en)
/// if s(i) is not basic, it will be treated as 0
/// so if coefficient a of s or e is less than 0, make s to becomne basic,
// this will increase value of s, decrease the value of expr
/// - Parameter row: expression to optimize
/// - Throws:
private func optimize(_ row: Expression) throws {
var entry: Variable? = nil
var exit: Variable? = nil
while true {
entry = nil
exit = nil
// use entryVars to find entry for objective to avoid traverse
if row === objective {
entry = entryVars.popFirst()
} else {
for (v, c) in row.terms {
if v.isPivotable && c < 0 {
entry = v
break
}
}
}
guard let entry = entry else {
return
}
var minRadio = Double.greatestFiniteMagnitude
var r = 0.0
columns[entry]?.value.forEach {
if !$0.isPivotable {
return
}
let expr = rows[$0]!
let coeff = expr.coefficient(for: entry)
if coeff > 0 {
return
}
r = -expr.constant/coeff
if r < minRadio {
minRadio = r
exit = $0
}
}
if minRadio == .greatestFiniteMagnitude {
throw ConstraintError.objectiveUnbound
}
if let exit = exit {
pivot(entry: entry, exit: exit)
}
}
}
private func dualOptimize() throws {
while !infeasibleRows.isEmpty {
let exitVar = infeasibleRows.removeFirst()
if !isBasicVar(exitVar) {
continue
}
let expr = rowExpression(for: exitVar)
if expr.constant >= 0 {
continue
}
var ratio = Double.greatestFiniteMagnitude
var r = 0.0
var entryVar: Variable? = nil
for (v, c) in expr.terms {
if c > 0 && v.isPivotable {
r = objective.coefficient(for: v)/c
if r < ratio {
entryVar = v
ratio = r
}
}
}
guard let entry = entryVar else {
throw ConstraintError.internalError("dual_optimize: no pivot found")
}
pivot(entry: entry, exit: exitVar)
}
}
/// exchange basic var and parametic var
/// example: row like rows[x] = 2*y + z which means x = 2*y + z, pivot(entry: z, exit: x)
/// result: rows[y] = 1/2*x - 1/2*z which is y = 1/2*x - 1/2*z
/// - Parameters:
/// - entry: variable to become basic var
/// - exit: variable to exit from basic var
private func pivot(entry: Variable, exit: Variable) {
let expr = removeRow(for: exit)
expr.changeSubject(from: exit, to: entry)
substituteOut(old: entry, expr: expr)
addRow(header: entry, expr: expr)
}
/// try to add expr to tableu
/// - Parameter expr: expression to add
/// - Returns: if we can't find a variable in expr to become basic, return false; else return true
private func tryToAdd(expr: Expression) -> Bool {
guard let subject = chooseSubject(expr: expr) else {
return false
}
expr.solve(for: subject)
substituteOut(old: subject, expr: expr)
addRow(header: subject, expr: expr)
return true
}
/// choose a subject to become basic var from expr
/// if expr constains external variable, return external variable
/// if expr doesn't contain external, find a slack or error var which has a negtive coefficient
/// else return nil
/// - Parameter expr: expr to choose subject from
/// - Returns: subject to become basic
private func chooseSubject(expr: Expression) -> Variable? {
var subject: Variable? = nil
var subjectExternal: Variable? = nil
for (variable, coeff) in expr.terms {
if variable.isExternal {
if !variable.isRestricted {
return variable
} else if coeff < 0 || expr.constant == 0 {
subjectExternal = variable
}
} else if variable.isPivotable && coeff < 0 {
subject = variable
}
}
if subjectExternal != nil {
return subjectExternal
}
return subject
}
private func addArtificalVariable(to expr: Expression) throws -> (Bool,[Constraint]) {
let av = Variable.slack()
addRow(header: av, expr: expr)
try optimize(expr)
if !nearZero(expr.constant) {
// there may be problem here
removeColumn(for: av)
if explainFailure {
return (false, buildExplanation(for: av, row: expr))
}
return (false, [Constraint]())
}
if isBasicVar(av) {
let expr = rowExpression(for: av)
if expr.isConstant {
assert(nearZero(expr.constant))
removeRow(for: av)
return (true, [Constraint]())
}
// this is different with the original implement,but it does't make sense to return false
guard let entry = expr.pivotableVar else {
return (true, [Constraint]())
}
pivot(entry: entry, exit: av)
}
assert(!isBasicVar(av))
return (true, [Constraint]())
}
private func buildExplanation(for marker: Variable, row: Expression) -> [Constraint] {
var explanation = [Constraint]()
if let constraint = constraintMarkered[marker] {
explanation.append(constraint)
}
for variable in row.terms.keys {
if let constraint = constraintMarkered[variable] {
explanation.append(constraint)
}
}
return explanation
}
/// make a new linear expression to represent constraint
/// this will replace all basic var in constraint.expr with related expression
/// add slack and dummpy var if necessary
/// - Parameter constraint: constraint to be represented
private func expression(for constraint: Constraint) -> Expression {
let expr = Expression()
let cexpr = constraint.expression
expr.constant = cexpr.constant
for term in cexpr.terms {
add(expr: expr, variable: term.key, delta: term.value)
}
var marker: Variable!
var errors = [Variable]()
if constraint.isInequality {
// if is Inequality,add slack var
// expr <(>)= 0 to expr - slack = 0
let slack = Variable.slack()
expr -= slack
marker = slack
if !constraint.isRequired {
let minus = Variable.error()
expr += minus
objective += minus * constraint.weight
errors.append(minus)
}
} else {
if constraint.isRequired {
let dummp = Variable.dummpy()
expr -= dummp
marker = dummp
} else {
let eplus = Variable.error()
let eminus = Variable.error()
expr -= eplus
expr += eminus
marker = eplus
objective += eplus*constraint.weight
errors.append(eplus)
objective += eminus * constraint.weight
errors.append(eminus)
}
}
constraintInfos[constraint] = ConstraintInfo(marker: marker, errors: errors)
constraintMarkered[marker] = constraint
if expr.constant < 0 {
expr *= -1
}
return expr
}
private func editConstant(for constraint: Constraint,delta: Double) {
let info = constraintInfos[constraint]!
let marker = info.marker
if isBasicVar(marker) {
let expr = rowExpression(for: marker)
expr.increaseConstant(by: -delta)
if expr.constant < 0 {
infeasibleRows.insert(marker)
}
} else {
columns[marker]?.value.forEach {
let expr = rows[$0]!
expr.increaseConstant(by: expr.coefficient(for: marker)*delta)
if $0.isRestricted && expr.constant < 0 {
infeasibleRows.insert($0)
}
}
}
}
private func rowExpression(for marker: Variable) -> Expression {
assert(rows.keys.contains(marker))
return rows[marker]!
}
/// find a variable to exit from basic var
/// this will travese all rows contains v
/// choose one that coefficient
/// - Returns: variable to become parametic
private func findExitVar(for v: Variable) -> Variable? {
var minRadio1 = Double.greatestFiniteMagnitude
var minRadio2 = Double.greatestFiniteMagnitude
var exitVar1: Variable? = nil
var exitVar2: Variable? = nil
var exitVar3: Variable? = nil
columns[v]?.value.forEach({ (variable) in
let expr = rows[variable]!
let c = expr.coefficient(for: v)
if variable.isExternal {
exitVar3 = variable
}
else if c < 0 {
let r = -expr.constant/c
if r < minRadio1 {
minRadio1 = r
exitVar1 = variable
}
} else {
let r = -expr.constant/c
if r < minRadio2 {
minRadio2 = r
exitVar2 = variable
}
}
})
var exitVar = exitVar1
if exitVar == nil {
if exitVar2 == nil {
exitVar = exitVar3
} else {
exitVar = exitVar2
}
}
return exitVar
}
// add delta*variable to expr
// if variable is basicVar, replace variable with expr
private func add(expr: Expression, variable: Variable, delta: Double) {
if isBasicVar(variable) {
let row = rowExpression(for: variable)
expr.add(expr: row, multiply: delta)
} else {
expr.add(variable, multiply: delta)
}
}
private func addRow(header: Variable, expr: Expression) {
rows[header] = expr
for v in expr.terms.keys {
addValue(header, toColumn: v)
}
}
@discardableResult
private func removeRow(for marker: Variable) -> Expression {
assert(rows.keys.contains(marker))
infeasibleRows.remove(marker)
let expr = rows.removeValue(forKey: marker)!
for (key, _) in expr.terms {
removeValue(marker, from: key)
}
return expr
}
fileprivate func removeColumn(for key: Variable) {
columns[key]?.value.forEach {
rows[$0]?.earse(key)
}
objective.earse(key)
entryVars.remove(key)
return
}
func addValue(_ value: Variable, toColumn key: Variable) {
if let column = columns[key] {
column.value.insert(value)
} else {
columns[key] = VarSet([value])
}
}
func removeValue(_ value: Variable, from key: Variable) {
guard let column = columns[key] else {
return
}
column.value.remove(value)
if column.value.isEmpty {
columns.removeValue(forKey: key)
}
}
/// replace all old variable in rows and objective function with expr
/// such as if one row = x + 2*y + 3*z, expr is 5*m + n
/// after substitutionOut(old: y, expr: expr),row = x + 10*m + 2*n + 3*z
/// - Parameters:
/// - old: variable to be replaced
/// - expr: expression to replace
private func substituteOut(old: Variable, expr: Expression) {
columns[old]?.value.forEach {
let rowExpr = rows[$0]!
rowExpr.substituteOut(old, with: expr,solver: self,marker: $0)
if $0.isRestricted && rowExpr.constant < 0 {
infeasibleRows.insert($0)
}
}
columns.removeValue(forKey: old)
objective.substituteOut(old, with: expr)
expr.terms.forEach {
updateEntryIfNeeded(for: $0.key)
}
}
func updateEntryIfNeeded(for variable: Variable) {
if variable.isPivotable {
let c = objective.coefficient(for: variable)
if c == 0 {
entryVars.remove(variable)
} else if c < 0 {
entryVars.insert(variable)
}
}
}
/// check vhether variable is a basic Variable
/// basic var means variable only appear in rows.keys
/// - Parameter vairable: variable to be checked
/// - Returns: whether variable is a basic var
private func isBasicVar(_ variable: Variable) -> Bool {
return rows[variable] != nil
}
public func printRow() {
print("=============== ROW ===============")
print("objctive = \(objective)")
for (v, expr) in rows {
print("V: \(v) = \(expr)")
}
}
}
| 31.404187 | 115 | 0.523126 |
8935f104f452f710d566bb2ef4feabe66a6a9661 | 1,369 | //
// GetSuggestionUseCase.swift
// YASD
//
// Created by Vyacheslav Konopkin on 22.04.2021.
// Copyright © 2021 yac. All rights reserved.
//
import Foundation
import RxSwift
class GetSuggestionUseCase: UseCase {
typealias Input = String
typealias Output = SuggestionItemResult
private let suggestions: AnyDictionaryRepository<SuggestionResult>
private let settings: SettingsRepository
private let history: AnyStorageRepository<Suggestion>
init(suggestions: AnyDictionaryRepository<SuggestionResult>,
settings: SettingsRepository,
history: AnyStorageRepository<Suggestion>) {
self.suggestions = suggestions
self.settings = settings
self.history = history
}
func execute(with input: String) -> Observable<SuggestionItemResult> {
let word = input.lowercased()
let foundSuggestions = settings.getLanguage().flatMap { [weak self] result -> Observable<SuggestionResult> in
guard let self = self else { return .just(.success([])) }
switch result {
case let .success(language):
return self.suggestions.search(word, language)
case let .failure(error):
return .just(.failure(error))
}
}
return history.getSuggestionAndHistory(suggestions: foundSuggestions, word)
}
}
| 32.595238 | 117 | 0.673484 |
d9b3513670078c3b14ca836833b24454979383ae | 13,998 | import SwiftAST
import KnownType
import Intentions
import TypeSystem
/// Simplified API interface to find usages of symbols across intentions
public protocol UsageAnalyzer {
/// Finds all usages of a known method
func findUsagesOf(method: KnownMethod) -> [DefinitionUsage]
/// Finds all usages of a known property
func findUsagesOf(property: KnownProperty) -> [DefinitionUsage]
}
/// A refined usage analyzer capable of inspecting usages of local variables by
/// name within a method body.
public protocol LocalsUsageAnalyzer: UsageAnalyzer {
/// Finds all usages of a local with a given name.
/// Returns all usages of any local named `local`, even those which are shadowed
/// by other, deeper scoped definitions.
func findUsagesOf(localNamed local: String,
in functionBody: FunctionBodyIntention) -> [DefinitionUsage]
/// Finds all usages of a local with a given name in the scope of a given
/// `SyntaxNode`.
/// `syntaxNode` must either be a `Statement` node, or any node which is a
/// descendent of a `Statement` node, otherwise a fatal error is raised.
func findUsagesOf(localNamed local: String,
inScopeOf syntaxNode: SyntaxNode,
in functionBody: FunctionBodyIntention) -> [DefinitionUsage]
/// Finds the definition of a local with a given name within the scope of a
/// given `SyntaxNode`.
/// `syntaxNode` must either be a `Statement` node, or any node which is a
/// descendent of a `Statement` node, otherwise a fatal error is raised.
/// Returns `nil`, in case no definition with the given name could be found
/// within scope of `syntaxNode`
func findDefinitionOf(localNamed local: String,
inScopeOf syntaxNode: SyntaxNode,
in functionBody: FunctionBodyIntention) -> LocalCodeDefinition?
}
public class BaseUsageAnalyzer: UsageAnalyzer {
var typeSystem: TypeSystem
init(typeSystem: TypeSystem) {
self.typeSystem = typeSystem
}
public func findUsagesOf(method: KnownMethod) -> [DefinitionUsage] {
let bodies = functionBodies()
var usages: [DefinitionUsage] = []
for functionBody in bodies {
let body = functionBody.body
let visitor = AnonymousSyntaxNodeVisitor { node in
guard let exp = node as? PostfixExpression else {
return
}
guard let expMethod = exp.member?.memberDefinition as? KnownMethod else {
return
}
guard expMethod.signature == method.signature else {
return
}
if expMethod.ownerType?.asTypeName == method.ownerType?.asTypeName {
let usage =
DefinitionUsage(
intention: functionBody,
definition: .forKnownMember(method),
expression: exp,
isReadOnlyUsage: true
)
usages.append(usage)
}
}
visitor.visitStatement(body)
}
return usages
}
public func findUsagesOf(property: KnownProperty) -> [DefinitionUsage] {
let bodies = functionBodies()
var usages: [DefinitionUsage] = []
for functionBody in bodies {
let body = functionBody.body
let visitor = AnonymousSyntaxNodeVisitor { node in
guard let exp = node as? PostfixExpression else {
return
}
guard let expProperty = exp.member?.memberDefinition as? KnownProperty else {
return
}
guard expProperty.name == property.name else {
return
}
if expProperty.ownerType?.asTypeName == property.ownerType?.asTypeName {
let readOnly = self.isReadOnlyContext(exp)
let usage =
DefinitionUsage(
intention: functionBody,
definition: .forKnownMember(property),
expression: exp,
isReadOnlyUsage: readOnly
)
usages.append(usage)
}
}
visitor.visitStatement(body)
}
return usages
}
func isReadOnlyContext(_ expression: Expression) -> Bool {
if let assignment = expression.parentExpression?.asAssignment {
return expression !== assignment.lhs
}
// Unary '&' is interpreted as 'address-of', which is a mutable operation.
if let unary = expression.parentExpression?.asUnary {
return unary.op != .bitwiseAnd
}
if let postfix = expression.parentExpression?.asPostfix {
let root = postfix.topPostfixExpression
// If at any point we find a function call, the original value cannot
// be mutated due to any change on the returned value, so we just
// assume it's never written.
let chain = PostfixChainInverter.invert(expression: root)
if let call = chain.first(where: { $0.postfix is FunctionCallPostfix }),
let member = call.postfixExpression?.exp.asPostfix?.member {
// Skip checking mutating methods on reference types, since those
// don't mutate variables.
if let type = chain.first?.expression?.resolvedType,
!typeSystem.isScalarType(type) {
return true
}
if let method = member.memberDefinition as? KnownMethod {
return !method.signature.isMutating
}
return true
}
// Writing to a reference type at any point invalidates mutations
// to the original value.
let types = chain.compactMap(\.resolvedType)
if types.contains(where: { typeSystem.isClassInstanceType($0) }) {
return true
}
return isReadOnlyContext(root)
}
return true
}
func functionBodies() -> [FunctionBodyIntention] {
[]
}
}
/// Default implementation of UsageAnalyzer which searches for definitions in all
/// method bodies.
public class IntentionCollectionUsageAnalyzer: BaseUsageAnalyzer {
public var intentions: IntentionCollection
private let numThreads: Int
// TODO: Passing `numThreads` here seems arbitrary (it is passed to
// `FunctionBodyQueue` when collecting function bodies). Maybe we could store
// the maximal thread count in a global, and replace all of its usages,
// instead?
public init(intentions: IntentionCollection, typeSystem: TypeSystem, numThreads: Int) {
self.intentions = intentions
self.numThreads = numThreads
super.init(typeSystem: typeSystem)
}
override func functionBodies() -> [FunctionBodyIntention] {
let queue =
FunctionBodyQueue.fromIntentionCollection(
intentions, delegate: EmptyFunctionBodyQueueDelegate(),
numThreads: numThreads)
return queue.items.map(\.body)
}
}
/// Usage analyzer that specializes in lookup of usages of locals within function
/// bodies.
public class LocalUsageAnalyzer: BaseUsageAnalyzer {
public override init(typeSystem: TypeSystem) {
super.init(typeSystem: typeSystem)
}
public func findUsagesOf(localNamed local: String,
in functionBody: FunctionBodyIntention) -> [DefinitionUsage] {
var usages: [DefinitionUsage] = []
let body = functionBody.body
let visitor =
AnonymousSyntaxNodeVisitor { node in
guard let identifier = node as? IdentifierExpression else {
return
}
guard let def = identifier.definition as? LocalCodeDefinition else {
return
}
if def.name == local {
let readOnly = self.isReadOnlyContext(identifier)
let usage =
DefinitionUsage(
intention: functionBody,
definition: def,
expression: identifier,
isReadOnlyUsage: readOnly
)
usages.append(usage)
}
}
visitor.visitStatement(body)
return usages
}
public func findUsagesOf(localNamed local: String,
inScopeOf syntaxNode: SyntaxNode,
in functionBody: FunctionBodyIntention) -> [DefinitionUsage] {
guard let definition = findDefinitionOf(localNamed: local, inScopeOf: syntaxNode) else {
return []
}
return findUsagesOf(definition: definition, inScopeOf: syntaxNode, in: functionBody)
}
public func findUsagesOf(definition: LocalCodeDefinition,
inScopeOf syntaxNode: SyntaxNode,
in functionBody: FunctionBodyIntention) -> [DefinitionUsage] {
var usages: [DefinitionUsage] = []
let body = functionBody.body
let visitor =
AnonymousSyntaxNodeVisitor { node in
guard let identifier = node as? IdentifierExpression else {
return
}
guard let def = identifier.definition as? LocalCodeDefinition else {
return
}
if def != definition {
let readOnly = self.isReadOnlyContext(identifier)
let usage =
DefinitionUsage(
intention: functionBody,
definition: def,
expression: identifier,
isReadOnlyUsage: readOnly
)
usages.append(usage)
}
}
visitor.visitStatement(body)
return usages
}
public func findAllUsages(in syntaxNode: SyntaxNode,
functionBody: FunctionBodyIntention) -> [DefinitionUsage] {
var usages: [DefinitionUsage] = []
let visitor =
AnonymousSyntaxNodeVisitor { node in
guard let identifier = node as? IdentifierExpression else {
return
}
guard let definition = identifier.definition else {
return
}
let readOnly = self.isReadOnlyContext(identifier)
let usage =
DefinitionUsage(
intention: functionBody,
definition: definition,
expression: identifier,
isReadOnlyUsage: readOnly
)
usages.append(usage)
}
switch syntaxNode {
case let stmt as Statement:
visitor.visitStatement(stmt)
case let exp as Expression:
visitor.visitExpression(exp)
default:
fatalError("Cannot search for definitions in statement node of type \(type(of: syntaxNode))")
}
return usages
}
public func findDefinitionOf(localNamed local: String, inScopeOf syntaxNode: SyntaxNode) -> LocalCodeDefinition? {
let scope = scopeFor(syntaxNode: syntaxNode)
return scope?.firstDefinition(named: local) as? LocalCodeDefinition
}
private func scopeFor(syntaxNode: SyntaxNode) -> CodeScope? {
if let statement = syntaxNode as? Statement {
return statement.nearestScope
}
if let statement = syntaxNode.firstAncestor(ofType: Statement.self) {
return scopeFor(syntaxNode: statement)
}
fatalError("Unknown syntax node type \(type(of: syntaxNode)) with no \(Statement.self)-typed parent node!")
}
}
/// Reports the usage of a type member or global declaration
public struct DefinitionUsage {
/// Intention for function body which this member usage is contained wihin.
public var intention: FunctionBodyIntention
/// The definition that was effectively used
public var definition: CodeDefinition
/// The expression the usage is effectively used.
///
/// In case the usage is of a type member, this expression is a
/// `PostfixExpression` where the `Postfix.member("")` points to the actual
/// member name.
/// In case the usage is of a local variable, the expression points to the
/// identifier node referencing the variable.
public var expression: Expression
/// Whether, in the context of this usage, the referenced definition is being
/// used in a read-only context.
public var isReadOnlyUsage: Bool
}
| 36.836842 | 118 | 0.544078 |
1d83d075f6a63956508bb331956a45195180d775 | 678 | //
// CustomButtonStyles.swift
// App Review
//
// Created by Stewart Lynch on 2020-11-02.
//
import SwiftUI
struct FilledRoundedCornerButtonStyle: ButtonStyle {
var font: Font = .title2
var padding: CGFloat = 8
var bgColor = Color.blue
var fgColor = Color.white
var cornerRadius: CGFloat = 8
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(font)
.padding(padding)
.background(bgColor)
.foregroundColor(fgColor)
.cornerRadius(cornerRadius)
.scaleEffect(configuration.isPressed ? 0.9 : 1.0)
.animation(.spring())
}
}
| 25.111111 | 62 | 0.620944 |
8a09442e91a3085b263bfd25a1ee5b18217c230d | 2,347 | //
// SceneDelegate.swift
// Split It!
//
// Created by Dylan Kuster on 5/6/20.
// Copyright © 2020 Dylan Kuster. All rights reserved.
//
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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.
}
}
| 43.462963 | 147 | 0.712399 |
9c209727b888288336856dd288ee797dbd5e4ab3 | 1,762 | //
// AuthenticationRepository.swift
// Login
//
// Created by Wellington Soares on 26/03/21.
//
import Combine
import Foundation
struct User: Equatable {
let id: String
let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
}
enum AuthenticationRepositoryError: Error, Equatable {
case incorrectCredentials(_ username: String, _ password: String)
case unauthenticated
}
protocol AuthenticationRepository {
func logIn(username: String, password: String)
func logOut()
var user: AnyPublisher<Result<User, AuthenticationRepositoryError>, Never> {
get
}
}
final class MockAuthRepository: AuthenticationRepository {
var user: AnyPublisher<Result<User, AuthenticationRepositoryError>, Never> {
subject.eraseToAnyPublisher()
}
func logOut() {
cancellable = Just(
Result
.failure(AuthenticationRepositoryError.unauthenticated)
).assign(
to: \.subject.value,
on: self
)
}
func logIn(username: String, password: String) {
if username == "user", password == "pass" {
cancellable = Just(Result.success(User(id: "123", name: username)))
.delay(for: 2, scheduler: RunLoop.main)
.assign(to: \.subject.value, on: self)
} else {
cancellable = Just(
Result
.failure(
AuthenticationRepositoryError
.incorrectCredentials(username, password)
)
)
.delay(for: 2, scheduler: RunLoop.main)
.assign(to: \.subject.value, on: self)
}
}
private var subject = CurrentValueSubject<
Result<User, AuthenticationRepositoryError>,
Never
>(Result.failure(AuthenticationRepositoryError.unauthenticated))
private var cancellable: AnyCancellable?
}
| 24.136986 | 78 | 0.673099 |
3913704ef97a03d67ece0d4e36ebc91bb36fb507 | 49,705 | import Foundation
import PusherPlatform
public final class PCCurrentUser {
public let id: String
public let createdAt: String
public var updatedAt: String
public var name: String?
public var avatarURL: String?
public var customData: [String: Any]?
private let lock = DispatchSemaphore(value: 1)
let userStore: PCGlobalUserStore
let roomStore: PCRoomStore
let cursorStore: PCCursorStore
let typingIndicatorManager: PCTypingIndicatorManager
var delegate: PCChatManagerDelegate {
didSet {
userSubscription?.delegate = delegate
userPresenceSubscriptions.forEach { ($0.value).delegate = delegate }
}
}
// TODO: This should probably be [PCUser] instead, like the users property
// in PCRoom, or something even simpler
public var users: Set<PCUser> {
return self.userStore.users
}
public var rooms: [PCRoom] {
return self.roomStore.rooms.clone()
}
public let pathFriendlyID: String
public internal(set) var userSubscription: PCUserSubscription?
private var _presenceSubscription: PCPresenceSubscription?
public internal(set) var presenceSubscription: PCPresenceSubscription? {
get { return self.lock.synchronized { self._presenceSubscription } }
set(v) { self.lock.synchronized { self._presenceSubscription = v } }
}
public var createdAtDate: Date { return PCDateFormatter.shared.formatString(self.createdAt) }
public var updatedAtDate: Date { return PCDateFormatter.shared.formatString(self.updatedAt) }
private let chatkitBeamsTokenProviderInstance: Instance
let instance: Instance
let v6Instance: Instance
let filesInstance: Instance
let cursorsInstance: Instance
let presenceInstance: Instance
let connectionCoordinator: PCConnectionCoordinator
private lazy var readCursorDebouncerManager: PCReadCursorDebouncerManager = {
return PCReadCursorDebouncerManager(currentUser: self)
}()
public internal(set) var userPresenceSubscriptions = PCSynchronizedDictionary<String, PCUserPresenceSubscription>()
public init(
id: String,
pathFriendlyID: String,
createdAt: String,
updatedAt: String,
name: String?,
avatarURL: String?,
customData: [String: Any]?,
instance: Instance,
v6Instance: Instance,
chatkitBeamsTokenProviderInstance: Instance,
filesInstance: Instance,
cursorsInstance: Instance,
presenceInstance: Instance,
userStore: PCGlobalUserStore,
roomStore: PCRoomStore,
cursorStore: PCCursorStore,
connectionCoordinator: PCConnectionCoordinator,
delegate: PCChatManagerDelegate
) {
self.id = id
self.pathFriendlyID = pathFriendlyID
self.createdAt = createdAt
self.updatedAt = updatedAt
self.name = name
self.avatarURL = avatarURL
self.customData = customData
self.instance = instance
self.v6Instance = v6Instance
self.chatkitBeamsTokenProviderInstance = chatkitBeamsTokenProviderInstance
self.filesInstance = filesInstance
self.cursorsInstance = cursorsInstance
self.presenceInstance = presenceInstance
self.userStore = userStore
self.roomStore = roomStore
self.cursorStore = cursorStore
self.connectionCoordinator = connectionCoordinator
self.delegate = delegate
self.typingIndicatorManager = PCTypingIndicatorManager(instance: v6Instance)
self.userStore.onUserStoredHooks.append { [weak self] user in
guard let strongSelf = self else {
v6Instance.logger.log(
"PCCurrentUser (self) is nil when going to subscribe to user presence after storing user in store",
logLevel: .verbose
)
return
}
strongSelf.subscribeToUserPresence(user: user)
}
}
public func createRoom(
id: String? = nil,
name: String,
pushNotificationTitleOverride: String? = nil,
isPrivate: Bool = false,
addUserIDs userIDs: [String]? = nil,
customData: [String: Any]? = nil,
completionHandler: @escaping PCRoomCompletionHandler
) {
var roomObject: [String: Any] = [
"name": name,
"created_by_id": self.id,
"private": isPrivate,
]
if id != nil {
roomObject["id"] = id!
}
if pushNotificationTitleOverride != nil {
roomObject["push_notification_title_override"] = pushNotificationTitleOverride
}
if userIDs != nil && userIDs!.count > 0 {
roomObject["user_ids"] = userIDs
}
if customData != nil {
roomObject["custom_data"] = customData!
}
guard JSONSerialization.isValidJSONObject(roomObject) else {
completionHandler(nil, PCError.invalidJSONObjectAsData(roomObject))
return
}
guard let data = try? JSONSerialization.data(withJSONObject: roomObject, options: []) else {
completionHandler(nil, PCError.failedToJSONSerializeData(roomObject))
return
}
let path = "/rooms"
let generalRequest = PPRequestOptions(method: HTTPMethod.POST.rawValue, path: path, body: data)
self.v6Instance.requestWithRetry(
using: generalRequest,
onSuccess: { data in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
completionHandler(nil, PCError.failedToDeserializeJSON(data))
return
}
guard let roomPayload = jsonObject as? [String: Any] else {
completionHandler(nil, PCError.failedToCastJSONObjectToDictionary(jsonObject))
return
}
do {
let room = self.roomStore.addOrMerge(try PCPayloadDeserializer.createRoomFromPayload(roomPayload))
self.populateRoomUserStore(room) { room in
completionHandler(room, nil)
}
} catch let err {
completionHandler(nil, err)
}
},
onError: { error in
completionHandler(nil, error)
}
)
}
// MARK: Room membership-related interactions
public func addUser(_ user: PCUser, to room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
self.addUsers([user], to: room, completionHandler: completionHandler)
}
public func addUser(id: String, to roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
self.addOrRemoveUsers(in: roomID, userIDs: [id], membershipChange: .add, completionHandler: completionHandler)
}
public func addUsers(_ users: [PCUser], to room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
let userIDs = users.map { $0.id }
self.addUsers(ids: userIDs, to: room.id, completionHandler: completionHandler)
}
public func addUsers(ids: [String], to roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
self.addOrRemoveUsers(in: roomID, userIDs: ids, membershipChange: .add, completionHandler: completionHandler)
}
public func removeUser(_ user: PCUser, from room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
self.removeUsers([user], from: room, completionHandler: completionHandler)
}
public func removeUser(id: String, from roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
self.removeUsers(ids: [id], from: roomID, completionHandler: completionHandler)
}
public func removeUsers(_ users: [PCUser], from room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
let userIDs = users.map { $0.id }
self.removeUsers(ids: userIDs, from: room.id, completionHandler: completionHandler)
}
public func removeUsers(ids: [String], from roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
self.addOrRemoveUsers(in: roomID, userIDs: ids, membershipChange: .remove, completionHandler: completionHandler)
}
public enum RoomPushNotificationTitle {
case Override(String)
case NoOverride
}
//MARK: Update Room
/**
* Update a room
*
* - parameter room: The room which should be updated.
* - parameter name: Name of the room.
* - parameter isPrivate: Indicates if a room should be private or public.
* - parameter customData: Optional custom data associated with a room.
* - parameter completionHandler: Invoked when request failed or completed.
*/
public func updateRoom(
_ room: PCRoom,
name: String? = nil,
pushNotificationTitleOverride: RoomPushNotificationTitle? = nil,
isPrivate: Bool? = nil,
customData: [String: Any]? = nil,
completionHandler: @escaping PCErrorCompletionHandler
) {
self.updateRoom(
roomID: room.id,
name: name,
pushNotificationTitleOverride: pushNotificationTitleOverride,
isPrivate: isPrivate,
customData: customData,
completionHandler: completionHandler
)
}
/**
* Update a room by providing the room id
*
* - parameter id: The id of the room which should be updated.
* - parameter name: Name of the room.
* - parameter isPrivate: Indicates if a room should be private or public.
* - parameter customData: Optional custom data associated with a room.
* - parameter completionHandler: Invoked when request failed or completed.
*/
public func updateRoom(
id: String,
name: String? = nil,
pushNotificationTitleOverride: RoomPushNotificationTitle? = nil,
isPrivate: Bool? = nil,
customData: [String: Any]? = nil,
completionHandler: @escaping PCErrorCompletionHandler
) {
self.updateRoom(
roomID: id,
name: name,
pushNotificationTitleOverride: pushNotificationTitleOverride,
isPrivate: isPrivate,
customData: customData,
completionHandler: completionHandler
)
}
fileprivate func updateRoom(
roomID: String,
name: String?,
pushNotificationTitleOverride: RoomPushNotificationTitle?,
isPrivate: Bool?,
customData: [String: Any]?,
completionHandler: @escaping PCErrorCompletionHandler
) {
guard name != nil || pushNotificationTitleOverride != nil || isPrivate != nil || customData != nil else {
completionHandler(nil)
return
}
var roomPayload: [String: Any] = [:]
roomPayload["name"] = name
if let pnTitleOverride = pushNotificationTitleOverride {
switch pnTitleOverride {
case .Override(let title):
roomPayload["push_notification_title_override"] = title
case .NoOverride:
roomPayload["push_notification_title_override"] = NSNull() // Forcing `null` to be serialized.
}
}
roomPayload["private"] = isPrivate
if customData != nil {
roomPayload["custom_data"] = customData
}
guard JSONSerialization.isValidJSONObject(roomPayload) else {
completionHandler(PCError.invalidJSONObjectAsData(roomPayload))
return
}
guard let data = try? JSONSerialization.data(withJSONObject: roomPayload, options: []) else {
completionHandler(PCError.failedToJSONSerializeData(roomPayload))
return
}
let path = "/rooms/\(roomID)"
let generalRequest = PPRequestOptions(method: HTTPMethod.PUT.rawValue, path: path, body: data)
self.v6Instance.requestWithRetry(
using: generalRequest,
onSuccess: { _ in
completionHandler(nil)
},
onError: { error in
completionHandler(error)
}
)
}
//MARK: Delete Room
/**
* Delete a room
*
* - parameter room: The room which should be deleted.
* - parameter completionHandler: Invoked when request failed or completed.
*/
public func deleteRoom(_ room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
self.deleteRoom(roomID: room.id, completionHandler: completionHandler)
}
/**
* Delete a room by providing the room id
*
* - parameter id: The id of the room which should be deleted.
* - parameter completionHandler: Invoked when request failed or completed.
*/
public func deleteRoom(id: String, completionHandler: @escaping PCErrorCompletionHandler) {
self.deleteRoom(roomID: id, completionHandler: completionHandler)
}
fileprivate func deleteRoom(roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
let path = "/rooms/\(roomID)"
let generalRequest = PPRequestOptions(method: HTTPMethod.DELETE.rawValue, path: path)
self.instance.requestWithRetry(
using: generalRequest,
onSuccess: { _ in
completionHandler(nil)
},
onError: { error in
completionHandler(error)
}
)
}
fileprivate func addOrRemoveUsers(
in roomID: String,
userIDs: [String],
membershipChange: PCUserMembershipChange,
completionHandler: @escaping PCErrorCompletionHandler
) {
let userPayload = ["user_ids": userIDs]
guard JSONSerialization.isValidJSONObject(userPayload) else {
completionHandler(PCError.invalidJSONObjectAsData(userPayload))
return
}
guard let data = try? JSONSerialization.data(withJSONObject: userPayload, options: []) else {
completionHandler(PCError.failedToJSONSerializeData(userPayload))
return
}
let path = "/rooms/\(roomID)/users/\(membershipChange.rawValue)"
let generalRequest = PPRequestOptions(method: HTTPMethod.PUT.rawValue, path: path, body: data)
self.v6Instance.requestWithRetry(
using: generalRequest,
onSuccess: { _ in
completionHandler(nil)
},
onError: { error in
completionHandler(error)
}
)
}
fileprivate enum PCUserMembershipChange: String {
case add
case remove
}
public func joinRoom(_ room: PCRoom, completionHandler: @escaping PCRoomCompletionHandler) {
self.joinRoom(roomID: room.id, completionHandler: completionHandler)
}
public func joinRoom(id: String, completionHandler: @escaping PCRoomCompletionHandler) {
self.joinRoom(roomID: id, completionHandler: completionHandler)
}
fileprivate func joinRoom(roomID: String, completionHandler: @escaping PCRoomCompletionHandler) {
if let room = self.rooms.first(where: { $0.id == roomID }) {
completionHandler(room, nil)
return
}
let path = "/users/\(self.pathFriendlyID)/rooms/\(roomID)/join"
let generalRequest = PPRequestOptions(method: HTTPMethod.POST.rawValue, path: path)
self.v6Instance.requestWithRetry(
using: generalRequest,
onSuccess: { data in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
completionHandler(nil, PCError.failedToDeserializeJSON(data))
return
}
guard let roomPayload = jsonObject as? [String: Any] else {
completionHandler(nil, PCError.failedToCastJSONObjectToDictionary(jsonObject))
return
}
do {
let room = self.roomStore.addOrMerge(try PCPayloadDeserializer.createRoomFromPayload(roomPayload))
self.populateRoomUserStore(room) { room in
completionHandler(room, nil)
}
} catch let err {
self.v6Instance.logger.log(err.localizedDescription, logLevel: .debug)
completionHandler(nil, err)
return
}
},
onError: { error in
completionHandler(nil, error)
}
)
}
fileprivate func populateRoomUserStore(_ room: PCRoom, completionHandler: @escaping (PCRoom) -> Void) {
let roomUsersProgressCounter = PCProgressCounter(totalCount: room.userIDs.count, labelSuffix: "room-users")
// TODO: Use the soon-to-be-created new version of fetchUsersWithIDs from the
// userStore
room.userIDs.forEach { userID in
self.userStore.user(id: userID) { [weak self] user, err in
guard let strongSelf = self else {
print("self is nil when user store returns user during population of room user store")
return
}
guard let user = user, err == nil else {
strongSelf.v6Instance.logger.log(
"Unable to add user with id \(userID) to room \(room.name): \(err!.localizedDescription)",
logLevel: .debug
)
if roomUsersProgressCounter.incrementFailedAndCheckIfFinished() {
room.subscription?.delegate?.onUsersUpdated()
strongSelf.v6Instance.logger.log("Users updated in room \(room.name)", logLevel: .verbose)
completionHandler(room)
}
return
}
room.userStore.addOrMerge(user)
if roomUsersProgressCounter.incrementSuccessAndCheckIfFinished() {
room.subscription?.delegate?.onUsersUpdated()
strongSelf.v6Instance.logger.log("Users updated in room \(room.name)", logLevel: .verbose)
completionHandler(room)
}
}
}
}
public func leaveRoom(_ room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
self.leaveRoom(roomID: room.id, completionHandler: completionHandler)
}
public func leaveRoom(id roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
self.leaveRoom(roomID: roomID, completionHandler: completionHandler)
}
fileprivate func leaveRoom(roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
let path = "/users/\(self.pathFriendlyID)/rooms/\(roomID)/leave"
let generalRequest = PPRequestOptions(method: HTTPMethod.POST.rawValue, path: path)
self.v6Instance.requestWithRetry(
using: generalRequest,
onSuccess: { _ in
completionHandler(nil)
},
onError: { error in
completionHandler(error)
}
)
}
// MARK: Room fetching
public func getJoinableRooms(completionHandler: @escaping PCRoomsCompletionHandler) {
self.getUserRooms(onlyJoinable: true, completionHandler: completionHandler)
}
fileprivate func getUserRooms(onlyJoinable: Bool = false, completionHandler: @escaping PCRoomsCompletionHandler) {
let path = "/users/\(self.pathFriendlyID)/rooms"
let generalRequest = PPRequestOptions(method: HTTPMethod.GET.rawValue, path: path)
let joinableQueryItemValue = onlyJoinable ? "true" : "false"
generalRequest.addQueryItems([URLQueryItem(name: "joinable", value: joinableQueryItemValue)])
self.getRooms(request: generalRequest, completionHandler: completionHandler)
}
fileprivate func getRooms(request: PPRequestOptions, completionHandler: @escaping PCRoomsCompletionHandler) {
self.v6Instance.requestWithRetry(
using: request,
onSuccess: { data in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
completionHandler(nil, PCError.failedToDeserializeJSON(data))
return
}
guard let roomsPayload = jsonObject as? [[String: Any]] else {
completionHandler(nil, PCError.failedToCastJSONObjectToDictionary(jsonObject))
return
}
let rooms = roomsPayload.compactMap { roomPayload -> PCRoom? in
do {
// TODO: Do we need to fetch users in the room here?
return try PCPayloadDeserializer.createRoomFromPayload(roomPayload)
} catch let err {
self.v6Instance.logger.log(err.localizedDescription, logLevel: .debug)
return nil
}
}
completionHandler(rooms, nil)
},
onError: { error in
completionHandler(nil, error)
}
)
}
// MARK: Typing-indicator-related interactions
public func typing(in roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
typingIndicatorManager.sendThrottledRequest(
roomID: roomID,
completionHandler: completionHandler
)
}
public func typing(in room: PCRoom, completionHandler: @escaping PCErrorCompletionHandler) {
typing(in: room.id, completionHandler: completionHandler)
}
// MARK: Message-related interactions
func sendMessage(instance: Instance, _ messageObject: [String: Any], roomID: String, completionHandler: @escaping (Int?, Error?) -> Void) {
guard JSONSerialization.isValidJSONObject(messageObject) else {
completionHandler(nil, PCError.invalidJSONObjectAsData(messageObject))
return
}
guard let data = try? JSONSerialization.data(withJSONObject: messageObject, options: []) else {
completionHandler(nil, PCError.failedToJSONSerializeData(messageObject))
return
}
let path = "/rooms/\(roomID)/messages"
let generalRequest = PPRequestOptions(method: HTTPMethod.POST.rawValue, path: path, body: data)
instance.requestWithRetry(
using: generalRequest,
onSuccess: { data in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
completionHandler(nil, PCError.failedToDeserializeJSON(data))
return
}
guard let messageIDPayload = jsonObject as? [String: Int] else {
completionHandler(nil, PCError.failedToCastJSONObjectToDictionary(jsonObject))
return
}
guard let messageID = messageIDPayload["message_id"] else {
completionHandler(nil, PCMessageError.messageIDKeyMissingInMessageCreationResponse(messageIDPayload))
return
}
completionHandler(messageID, nil)
},
onError: { error in
completionHandler(nil, error)
}
)
}
func uploadAttachmentAndSendMessage(
_ messageObject: [String: Any],
attachment: PCAttachmentType,
roomID: String,
completionHandler: @escaping (Int?, Error?) -> Void,
progressHandler: ((Int64, Int64) -> Void)? = nil
) {
var multipartFormData: ((PPMultipartFormData) -> Void)
var reqOptions: PPRequestOptions
switch attachment {
case .fileData(let data, let name):
multipartFormData = { $0.append(data, withName: "file", fileName: name) }
let pathSafeName = pathFriendlyVersion(of: name)
reqOptions = PPRequestOptions(method: HTTPMethod.POST.rawValue, path: "/rooms/\(roomID)/users/\(pathFriendlyID)/files/\(pathSafeName)")
break
case .fileURL(let url, let name):
multipartFormData = { $0.append(url, withName: "file", fileName: name) }
let pathSafeName = pathFriendlyVersion(of: name)
reqOptions = PPRequestOptions(method: HTTPMethod.POST.rawValue, path: "/rooms/\(roomID)/users/\(pathFriendlyID)/files/\(pathSafeName)")
break
default:
sendMessage(instance: self.instance, messageObject, roomID: roomID, completionHandler: completionHandler)
return
}
self.filesInstance.upload(
using: reqOptions,
multipartFormData: multipartFormData,
onSuccess: { data in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
completionHandler(nil, PCError.failedToDeserializeJSON(data))
return
}
guard let uploadPayload = jsonObject as? [String: Any] else {
completionHandler(nil, PCError.failedToCastJSONObjectToDictionary(jsonObject))
return
}
do {
let attachmentUploadResponse = try PCPayloadDeserializer.createAttachmentUploadResponseFromPayload(uploadPayload)
var mutableMessageObject = messageObject
mutableMessageObject["attachment"] = [
"resource_link": attachmentUploadResponse.link,
"type": attachmentUploadResponse.type
]
self.sendMessage(instance: self.instance, mutableMessageObject, roomID: roomID, completionHandler: completionHandler)
} catch let err {
completionHandler(nil, err)
self.instance.logger.log("Response from uploading attachment to room \(roomID) was invalid", logLevel: .verbose)
return
}
},
onError: { err in
completionHandler(nil, err)
self.instance.logger.log("Failed to upload attachment to room \(roomID)", logLevel: .verbose)
},
progressHandler: progressHandler
)
}
@available(*, deprecated, message: "Please use sendMultipartMessage")
public func sendMessage(
roomID: String,
text: String,
attachment: PCAttachmentType? = nil,
completionHandler: @escaping (Int?, Error?) -> Void
) {
var messageObject: [String: Any] = [
"user_id": self.id,
"text": text
]
guard let attachment = attachment else {
sendMessage(instance: self.instance, messageObject, roomID: roomID, completionHandler: completionHandler)
return
}
switch attachment {
case .fileData(_, _), .fileURL(_, _):
uploadAttachmentAndSendMessage(
messageObject,
attachment: attachment,
roomID: roomID,
completionHandler: completionHandler
)
break
case .link(let url, let type):
messageObject["attachment"] = [
"resource_link": url,
"type": type
]
sendMessage(instance: self.instance, messageObject, roomID: roomID, completionHandler: completionHandler)
break
}
}
public func sendSimpleMessage(roomID: String, text: String, completionHandler: @escaping (Int?, Error?) -> Void) {
let messageObject: [String: Any] = [
"parts": [
["content": text, "type": "text/plain"]
]
]
sendMessage(instance: self.v6Instance, messageObject, roomID: roomID, completionHandler: completionHandler)
}
public func sendMultipartMessage(
roomID: String,
parts: [PCPartRequest],
completionHandler: @escaping (Int?, Error?) -> Void
) {
var partObjects: [PartObjectWithIndex] = []
var uploadTasks: [PCMultipartAttachmentUploadTask] = []
var partIndex: Int = 0
for part in parts {
partIndex += 1
switch part.payload {
case .inline(let payload):
partObjects.append(PartObjectWithIndex(object: payload.toMap(), index: partIndex))
case .url(let payload):
partObjects.append(PartObjectWithIndex(object: payload.toMap(), index: partIndex))
case .attachment(let payload):
uploadTasks.append(
PCMultipartAttachmentUploadTask(
uploadRequest: PCMultipartAttachmentUploadRequest(
contentType: payload.type,
contentLength: payload.file.count,
name: payload.name,
customData: payload.customData
),
roomID: roomID,
file: payload.file,
partNumber: partIndex
)
)
}
}
let sendMessage: ([[String: Any]]) -> Void = { partsToSend in
self.sendMessage(
instance: self.v6Instance,
["parts": partsToSend],
roomID: roomID,
completionHandler: completionHandler
)
}
if uploadTasks.count > 0 {
let uploader = PCMultipartAttachmentUploader(instance: self.v6Instance, uploadTasks: uploadTasks)
uploader.upload() { results, errors in
guard errors == nil else {
completionHandler(nil, errors!.first!)
return
}
let uploadResultObjectsWithIndex = results!.map { PartObjectWithIndex(object: $0.payload, index: $0.partNumber)}
partObjects = (partObjects + uploadResultObjectsWithIndex).sorted(by: { $0.index < $1.index })
sendMessage(partObjects.map { $0.object })
}
} else {
sendMessage(partObjects.map { $0.object })
}
}
public func downloadAttachment(
_ link: String,
to destination: PCDownloadFileDestination? = nil,
onSuccess: ((URL) -> Void)? = nil,
onError: ((Error) -> Void)? = nil,
progressHandler: ((Int64, Int64) -> Void)? = nil
) {
let reqOptions = PPRequestOptions(
method: HTTPMethod.GET.rawValue,
destination: .absolute(link),
shouldFetchToken: false
)
self.instance.download(
using: reqOptions,
to: destination,
onSuccess: onSuccess,
onError: onError,
progressHandler: progressHandler
)
}
@available(*, deprecated, message: "Please use subscribeToRoomMultipart")
public func subscribeToRoom(
room: PCRoom,
roomDelegate: PCRoomDelegate,
messageLimit: Int = 20,
completionHandler: @escaping PCErrorCompletionHandler
) {
self.subscribeToRoom(
room,
delegate: roomDelegate,
messageLimit: messageLimit,
instance: self.instance,
version: "v2",
completionHandler: completionHandler
)
}
// TODO: Do we need a Last-Event-ID option here? Probably yes if we get to the point
// of supporting offline or caching, or someone wants to do that themselves, then
// offering this as a point to hook into would be an optimisation opportunity
@available(*, deprecated, message: "Please use subscribeToRoomMultipart")
public func subscribeToRoom(
id roomID: String,
roomDelegate: PCRoomDelegate,
messageLimit: Int = 20,
completionHandler: @escaping PCErrorCompletionHandler
) {
self.roomStore.room(id: roomID) { r, err in
guard err == nil, let room = r else {
self.instance.logger.log(
"Error getting room from room store as part of room subscription process \(err!.localizedDescription)",
logLevel: .error
)
completionHandler(err)
return
}
self.subscribeToRoom(
room,
delegate: roomDelegate,
messageLimit: messageLimit,
instance: self.instance,
version: "v2",
completionHandler: completionHandler
)
}
}
public func subscribeToRoomMultipart(
room: PCRoom,
roomDelegate: PCRoomDelegate,
messageLimit: Int = 20,
completionHandler: @escaping PCErrorCompletionHandler
) {
self.subscribeToRoom(
room,
delegate: roomDelegate,
messageLimit: messageLimit,
instance: self.v6Instance,
version: "v6",
completionHandler: completionHandler
)
}
public func subscribeToRoomMultipart(
id roomID: String,
roomDelegate: PCRoomDelegate,
messageLimit: Int = 20,
completionHandler: @escaping PCErrorCompletionHandler
) {
self.roomStore.room(id: roomID) { r, err in
guard err == nil, let room = r else {
self.v6Instance.logger.log(
"Error getting room from room store as part of multipart message subscription \(err!.localizedDescription)",
logLevel: .error
)
completionHandler(err)
return
}
self.subscribeToRoom(
room,
delegate: roomDelegate,
messageLimit: messageLimit,
instance: self.v6Instance,
version: "v6",
completionHandler: completionHandler
)
}
}
fileprivate func subscribeToRoom(
_ room: PCRoom,
delegate: PCRoomDelegate,
messageLimit: Int = 20,
instance: Instance,
version: String,
completionHandler: @escaping PCErrorCompletionHandler
) {
instance.logger.log(
"About to subscribe to room \(room.debugDescription)",
logLevel: .verbose
)
self.joinRoom(roomID: room.id) { innerRoom, err in
guard let roomToSubscribeTo = innerRoom, err == nil else {
instance.logger.log(
"Error joining room as part of room subscription process \(room.debugDescription)",
logLevel: .error
)
return
}
if room.subscription != nil {
room.subscription!.end()
room.subscription = nil
}
room.subscription = PCRoomSubscription(
room: roomToSubscribeTo,
messageLimit: messageLimit,
currentUserID: self.id,
roomDelegate: delegate,
chatManagerDelegate: self.delegate,
userStore: self.userStore,
roomStore: self.roomStore,
cursorStore: self.cursorStore,
typingIndicatorManager: self.typingIndicatorManager,
instance: instance,
cursorsInstance: self.cursorsInstance,
version: version,
logger: self.instance.logger,
completionHandler: completionHandler
)
}
}
@available(*, deprecated, message: "Please use fetchMultipartMessages")
public func fetchMessagesFromRoom(
_ room: PCRoom,
initialID: String? = nil,
limit: Int? = nil,
direction: PCRoomMessageFetchDirection = .older,
completionHandler: @escaping ([PCMessage]?, Error?) -> Void
) {
self.fetchEnrichedMessages(
room,
initialID: initialID,
limit: limit,
direction: direction,
instance: self.instance,
deserialise: PCPayloadDeserializer.createBasicMessageFromPayload,
messageFactory: { (basicMessage, room, user) in
return PCMessage(
id: basicMessage.id,
text: basicMessage.text,
createdAt: basicMessage.createdAt,
updatedAt: basicMessage.updatedAt,
deletedAt: basicMessage.deletedAt,
attachment: basicMessage.attachment,
sender: user,
room: room
)
},
completionHandler: completionHandler
)
}
public func fetchMultipartMessages(
_ room: PCRoom,
initialID: String? = nil,
limit: Int? = nil,
direction: PCRoomMessageFetchDirection = .older,
completionHandler: @escaping ([PCMultipartMessage]?, Error?) -> Void
) {
self.fetchEnrichedMessages(
room,
initialID: initialID,
limit: limit,
direction: direction,
instance: self.v6Instance,
deserialise: { rawPayload in
return try PCPayloadDeserializer.createMultipartMessageFromPayload(
rawPayload,
urlRefresher: PCMultipartAttachmentUrlRefresher(client: self.v6Instance)
)
},
messageFactory: { (basicMessage, room, user) in
return PCMultipartMessage(
id: basicMessage.id,
sender: user,
room: room,
parts: basicMessage.parts,
createdAt: basicMessage.createdAt,
updatedAt: basicMessage.updatedAt
)
},
completionHandler: completionHandler
)
}
fileprivate func fetchEnrichedMessages<A: PCCommonBasicMessage, B: PCEnrichedMessage>(
_ room: PCRoom,
initialID: String? = nil,
limit: Int? = nil,
direction: PCRoomMessageFetchDirection = .older,
instance: Instance,
deserialise: @escaping ([String: Any]) throws -> A,
messageFactory: @escaping (A, PCRoom, PCUser) -> B,
completionHandler: @escaping ([B]?, Error?) -> Void
) {
let path = "/rooms/\(room.id)/messages"
let generalRequest = PPRequestOptions(method: HTTPMethod.GET.rawValue, path: path)
if let initialID = initialID {
generalRequest.addQueryItems([URLQueryItem(name: "initial_id", value: initialID)])
}
if let limit = limit {
generalRequest.addQueryItems([URLQueryItem(name: "limit", value: String(limit))])
}
generalRequest.addQueryItems([URLQueryItem(name: "direction", value: direction.rawValue)])
instance.requestWithRetry(
using: generalRequest,
onSuccess: { data in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) else {
completionHandler(nil, PCError.failedToDeserializeJSON(data))
return
}
guard let messagesPayload = jsonObject as? [[String: Any]] else {
completionHandler(nil, PCError.failedToCastJSONObjectToDictionary(jsonObject))
return
}
guard messagesPayload.count > 0 else {
completionHandler([], nil)
return
}
let progressCounter = PCProgressCounter(totalCount: messagesPayload.count, labelSuffix: "message-enricher")
let messages = PCSynchronizedArray<B>()
var basicMessages: [A] = []
let messageUserIDs = messagesPayload.compactMap { messagePayload -> String? in
do {
let basicMessage = try deserialise(messagePayload)
basicMessages.append(basicMessage)
return basicMessage.senderID
} catch let err {
instance.logger.log(err.localizedDescription, logLevel: .debug)
return nil
}
}
let messageUserIDsSet = Set<String>(messageUserIDs)
self.userStore.fetchUsersWithIDs(messageUserIDsSet) { _, err in
if let err = err {
instance.logger.log(err.localizedDescription, logLevel: .debug)
}
let messageEnricher = PCBasicMessageEnricher<A, B>(
userStore: self.userStore,
room: room,
messageFactory: messageFactory,
logger: instance.logger
)
basicMessages.forEach { basicMessage in
messageEnricher.enrich(basicMessage) { message, err in
guard let message = message, err == nil else {
instance.logger.log(err!.localizedDescription, logLevel: .debug)
if progressCounter.incrementFailedAndCheckIfFinished() {
completionHandler(messages.clone().sorted(by: { $0.id > $1.id }), nil)
}
return
}
messages.append(message)
if progressCounter.incrementSuccessAndCheckIfFinished() {
completionHandler(
messages.clone().sorted(
by: { $0.id < $1.id }
),
nil
)
}
}
}
}
},
onError: { error in
completionHandler(nil, error)
}
)
}
public func readCursor(roomID: String, userID: String? = nil) throws -> PCCursor? {
guard let room = self.rooms.filter({ $0.id == roomID }).first else {
throw PCCurrentUserError.mustBeMemberOfRoom
}
let userIDToCheck = userID ?? self.id
if userIDToCheck != self.id && room.subscription == nil {
throw PCCurrentUserError.noSubscriptionToRoom(room)
}
return self.cursorStore.getSync(userID: userIDToCheck, roomID: roomID)
}
public func setReadCursor(position: Int, roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
readCursorDebouncerManager.set(cursorPosition: position, inRoomID: roomID, completionHandler: completionHandler)
}
func sendReadCursor(position: Int, roomID: String, completionHandler: @escaping PCErrorCompletionHandler) {
let cursorObject = ["position": position]
guard JSONSerialization.isValidJSONObject(cursorObject) else {
completionHandler(PCError.invalidJSONObjectAsData(cursorObject))
return
}
guard let data = try? JSONSerialization.data(withJSONObject: cursorObject, options: []) else {
completionHandler(PCError.failedToJSONSerializeData(cursorObject))
return
}
let path = "/cursors/\(PCCursorType.read.rawValue)/rooms/\(roomID)/users/\(self.pathFriendlyID)"
let cursorRequest = PPRequestOptions(method: HTTPMethod.PUT.rawValue, path: path, body: data)
self.cursorsInstance.request(
using: cursorRequest,
onSuccess: { data in
self.cursorsInstance.logger.log("Successfully set cursor in room \(roomID)", logLevel: .verbose)
completionHandler(nil)
},
onError: { err in
self.cursorsInstance.logger.log("Error setting cursor in room \(roomID): \(err.localizedDescription)", logLevel: .debug)
completionHandler(err)
}
)
}
fileprivate func subscribeToUserPresence(user: PCUser) {
guard user.id != self.id else {
return // don't subscribe to own presence
}
guard self.userPresenceSubscriptions[user.id] == nil else {
return // already subscribed to presence for user
}
let path = "/users/\(user.pathFriendlyID)"
let subscribeRequest = PPRequestOptions(
method: HTTPMethod.SUBSCRIBE.rawValue,
path: path
)
var resumableSub = PPResumableSubscription(
instance: self.presenceInstance,
requestOptions: subscribeRequest
)
let userPresenceSubscription = PCUserPresenceSubscription(
userID: user.id,
resumableSubscription: resumableSub,
userStore: self.userStore,
roomStore: self.roomStore,
logger: self.presenceInstance.logger,
delegate: delegate
)
self.userPresenceSubscriptions[user.id] = userPresenceSubscription
self.presenceInstance.subscribeWithResume(
with: &resumableSub,
using: subscribeRequest,
onEvent: { [unowned userPresenceSubscription] eventID, headers, data in
userPresenceSubscription.handleEvent(eventID: eventID, headers: headers, data: data)
},
onError: { err in
// TODO: What to do with an error? Just log?
self.cursorsInstance.logger.log(
"Error with user presence subscription for user with ID \(user.id): \(err.localizedDescription)",
logLevel: .error
)
}
)
}
}
struct PartObjectWithIndex {
let object: [String: Any]
let index: Int
}
func reconcileMemberships(
new: [PCUser],
old: [PCUser],
onUserJoinedHook: ((PCUser) -> Void)?,
onUserLeftHook: ((PCUser) -> Void)?
) {
let oldSet = Set(old)
let newSet = Set(new)
let newMembers = newSet.subtracting(oldSet)
let membersRemoved = oldSet.subtracting(newSet)
newMembers.forEach { onUserJoinedHook?($0) }
membersRemoved.forEach { m in
onUserLeftHook?(m)
}
}
public enum PCCurrentUserError: Error {
case noSubscriptionToRoom(PCRoom)
case mustBeMemberOfRoom
}
extension PCCurrentUser: PCUpdatable {
@discardableResult
func updateWithPropertiesOf(_ currentUser: PCCurrentUser) -> PCCurrentUser {
self.updatedAt = currentUser.updatedAt
self.name = currentUser.name
self.avatarURL = currentUser.avatarURL
self.customData = currentUser.customData
self.delegate = currentUser.delegate
return self
}
}
extension PCCurrentUserError: LocalizedError {
public var errorDescription: String? {
switch self {
case let .noSubscriptionToRoom(room):
return "You must be subscribed to room \(room.name) to get read cursors from it"
case .mustBeMemberOfRoom:
return "You must be a member of a room to get the read cursors for it"
}
}
}
public enum PCMessageError: Error {
case messageIDKeyMissingInMessageCreationResponse([String: Int])
}
extension PCMessageError: LocalizedError {
public var errorDescription: String? {
switch self {
case let .messageIDKeyMissingInMessageCreationResponse(payload):
return "\"message_id\" key missing from response after message creation: \(payload)"
}
}
}
public enum PCRoomMessageFetchDirection: String {
case older
case newer
}
public typealias PCErrorCompletionHandler = (Error?) -> Void
public typealias PCRoomCompletionHandler = (PCRoom?, Error?) -> Void
public typealias PCRoomsCompletionHandler = ([PCRoom]?, Error?) -> Void
// MARK: Beams
#if os(iOS) || os(macOS)
import PushNotifications
private let pushNotifications: PushNotifications = PushNotifications.shared
extension PCCurrentUser {
/**
Start PushNotifications service.
*/
public func enablePushNotifications() {
pushNotifications.start(instanceId: self.v6Instance.id)
self.setUser(self.id)
ChatManager.registerForRemoteNotifications()
}
private func setUser(_ userId: String) {
let chatkitBeamsTokenProvider = ChatkitBeamsTokenProvider(instance: self.chatkitBeamsTokenProviderInstance)
pushNotifications.setUserId(userId, tokenProvider: chatkitBeamsTokenProvider) { error in
guard error == nil else {
return self.v6Instance.logger.log("Error occured while setting the user: \(error!)", logLevel: .error)
}
self.v6Instance.logger.log("Push Notifications service enabled 🎉", logLevel: .debug)
}
}
}
#endif
| 37.884909 | 147 | 0.590866 |
ef0310312fe740b2d92781a5c31c744d56cabfd1 | 17,886 | @testable import SteamPress
import XCTest
import Vapor
class RSSFeedTests: XCTestCase {
// MARK: - Properties
private var testWorld: TestWorld!
private var rssPath = "/rss.xml"
private var blogRSSPath = "/blog-path/rss.xml"
private let dateFormatter = DateFormatter()
// MARK: - Overrides
override func setUp() {
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
}
override func tearDown() {
XCTAssertNoThrow(try testWorld.tryAsHardAsWeCanToShutdownApplication())
}
// MARK: - Tests
func testNoPostsReturnsCorrectRSSFeed() throws {
testWorld = try TestWorld.create()
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testOnePostReturnsCorrectRSSFeed() throws {
testWorld = try TestWorld.create()
let testData = try testWorld.createPost()
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testMultiplePostsReturnsCorrectRSSFeed() throws {
testWorld = try TestWorld.create()
let testData = try testWorld.createPost()
let post = testData.post
let author = testData.author
let anotherTitle = "Another Title"
let contents = "This is some short contents"
let post2 = try testWorld.createPost(title: anotherTitle, contents: contents, slugUrl: "another-title", author: author).post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post2.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(anotherTitle)\n</title>\n<description>\n\(contents)\n</description>\n<link>\n/posts/another-title/\n</link>\n<pubDate>\(dateFormatter.string(from: post2.created))</pubDate>\n</item>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testDraftsAreNotIncludedInFeed() throws {
testWorld = try TestWorld.create()
let testData = try testWorld.createPost()
let post = testData.post
_ = try testWorld.createPost(title: "A Draft Post", published: false)
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testBlogTitleCanBeConfigured() throws {
let title = "SteamPress - The Open Source Blog"
let feedInformation = FeedInformation(title: title)
testWorld = try TestWorld.create(feedInformation: feedInformation)
let testData = try testWorld.createPost()
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>\(title)</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search \(title)</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testBlogDescriptionCanBeConfigured() throws {
let description = "Our fancy new RSS-feed blog"
let feedInformation = FeedInformation(description: description)
testWorld = try TestWorld.create(feedInformation: feedInformation)
let testData = try testWorld.createPost()
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>\(description)</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testRSSFeedEndpointAddedToCorrectEndpointWhenBlogInSubPath() throws {
testWorld = try TestWorld.create(path: "blog-path")
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/blog-path/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/blog-path/search?</link>\n<name>term</name>\n</textinput>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: blogRSSPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testPostLinkWhenBlogIsPlacedAtSubPath() throws {
testWorld = try TestWorld.create(path: "blog-path")
let testData = try testWorld.createPost()
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/blog-path/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/blog-path/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/blog-path/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: blogRSSPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testCopyrightCanBeAddedToRSS() throws {
let copyright = "Copyright ©️ 2017 SteamPress"
let feedInformation = FeedInformation(copyright: copyright)
testWorld = try TestWorld.create(feedInformation: feedInformation)
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<copyright>\(copyright)</copyright>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testThatTagsAreAddedToPostCorrectly() throws {
testWorld = try TestWorld.create()
let testData = try testWorld.createPost(tags: ["Vapor 2", "Engineering"])
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<category>Vapor 2</category>\n<category>Engineering</category>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testThatLinksComesFromRequestCorrectly() throws {
testWorld = try TestWorld.create(path: "blog-path")
let testData = try testWorld.createPost()
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>http://geeks.brokenhands.io/blog-path/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>http://geeks.brokenhands.io/blog-path/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\nhttp://geeks.brokenhands.io/blog-path/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let fullPath = "/blog-path/rss.xml"
let actualXmlResponse = try testWorld.getResponseString(to: fullPath, headers: [
"X-Forwarded-Proto": "http",
"X-Forwarded-For": "geeks.brokenhands.io"
])
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testThatLinksSpecifyHTTPSWhenComingFromReverseProxy() throws {
testWorld = try TestWorld.create(path: "blog-path")
let testData = try testWorld.createPost()
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>https://geeks.brokenhands.io/blog-path/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>https://geeks.brokenhands.io/blog-path/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\nhttps://geeks.brokenhands.io/blog-path/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let fullPath = "/blog-path/rss.xml"
let actualXmlResponse = try testWorld.getResponseString(to: fullPath, headers: [
"X-Forwarded-Proto": "https",
"X-Forwarded-For": "geeks.brokenhands.io"
])
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testImageIsProvidedIfSupplied() throws {
let image = "https://static.brokenhands.io/images/brokenhands.png"
let feedInformation = FeedInformation(imageURL: image)
testWorld = try TestWorld.create(feedInformation: feedInformation)
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<image>\n<url>\(image)</url>\n<title>SteamPress Blog</title>\n<link>/</link>\n</image>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testCorrectHeaderSetForRSSFeed() throws {
testWorld = try TestWorld.create()
let actualXmlResponse = try testWorld.getResponse(to: rssPath)
XCTAssertEqual(actualXmlResponse.http.headers.firstValue(name: .contentType), "application/rss+xml")
}
func testThatDateFormatterIsCorrect() throws {
let createDate = Date(timeIntervalSince1970: 1505867108)
testWorld = try TestWorld.create()
let testData = try testWorld.createPost(createdDate: createDate)
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>Wed, 20 Sep 2017 00:25:08 GMT</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\n\(try post.description())\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>Wed, 20 Sep 2017 00:25:08 GMT</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
func testThatDescriptionContainsOnlyText() throws {
testWorld = try TestWorld.create()
let contents = "[This is](https://www.google.com) a post that contains some **text**. \n# Formatting should be removed"
let testData = try testWorld.createPost(contents: contents)
let post = testData.post
let expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n\n<channel>\n<title>SteamPress Blog</title>\n<link>/</link>\n<description>SteamPress is an open-source blogging engine written for Vapor in Swift</description>\n<generator>SteamPress</generator>\n<ttl>60</ttl>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n<textinput>\n<description>Search SteamPress Blog</description>\n<title>Search</title>\n<link>/search?</link>\n<name>term</name>\n</textinput>\n<item>\n<title>\n\(post.title)\n</title>\n<description>\nThis is a post that contains some text. Formatting should be removed\n</description>\n<link>\n/posts/\(post.slugUrl)/\n</link>\n<pubDate>\(dateFormatter.string(from: post.created))</pubDate>\n</item>\n</channel>\n\n</rss>"
let actualXmlResponse = try testWorld.getResponseString(to: rssPath)
XCTAssertEqual(actualXmlResponse, expectedXML)
}
}
| 82.045872 | 952 | 0.706922 |
3808bc5a60eda903bb3987d6d10350d1e19d0306 | 609 | //
// CircleImage.swift
// LabShare-Front
//
// Created by Alexander Frazis on 20/9/20.
// Copyright © 2020 CITS3200. All rights reserved.
//
import SwiftUI
import Combine
struct CircleImage: View {
var body: some View {
Image(systemName: "person")
.resizable()
.scaledToFit()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
.padding(5)
}
}
struct CircleImage_Previews: PreviewProvider {
static var previews: some View {
CircleImage()
}
}
| 20.3 | 64 | 0.581281 |
676b530ca18f7f71e42511976ac197628ab0ebd2 | 721 | import ArgumentParser
import Foundation
import TSCBasic
/// A command to update project's dependencies.
struct DependenciesUpdateCommand: ParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(commandName: "update",
_superCommandName: "dependencies",
abstract: "Updates the project's dependencies defined in `Dependencies.swift`.")
}
@Option(
name: .shortAndLong,
help: "The path to the directory that contains the definition of the project.",
completion: .directory
)
var path: String?
func run() throws {
try DependenciesUpdateService().run(path: path)
}
}
| 30.041667 | 109 | 0.654646 |
618dc43c08662c0c24f38cef1a78a23d77552f6a | 3,269 | //
// AppStoreValidationRequest.swift
// SpotIAP iOS
//
// Created by Shawn Clovie on 14/3/2018.
// Copyright © 2018 Shawn Clovie. All rights reserved.
//
import Foundation
import Spot
private let ReceiptStatusValid = 0
private let ReceiptStatusReadDataFailed = 21000
private let ReceiptStatusNoData = 21002
private let ReceiptStatusAuthenticateFailed = 21003
private let ReceiptStatusSharedSecretInvalid = 21004
private let ReceiptStatusServerNotAvailiable = 21005
private let ReceiptStatusTestReceiptSentToProductServer = 21007
private let ReceiptStatusProductReceiptSentToTestServer = 21008
final class AppStoreValidationRequest {
/// Validate receipt, this may query receipt content information.
///
/// - Parameters:
/// - sharedSecret: App's shared secret (hexadecimal). Only used for contains auto-renewable subscriptions.
/// - excludeOldTransaction: Should include only the latest renewal transacion for any subscriptions. Only used for subscriptions.
/// - sandbox: Is the receipt from sandbox environment.
func start(receipt: Data, sharedSecret: String,
excludeOldTransaction: Bool, sandbox: Bool,
completion: @escaping (AttributedResult<IAPValidationResponse>)->Void) {
var params: [AnyHashable: Any] = ["receipt-data": receipt.base64EncodedString()]
if !sharedSecret.isEmpty {
params["password"] = sharedSecret
}
if excludeOldTransaction {
params["exclude-old-transactions"] = true
}
let url = URL(string: sandbox
? "https://sandbox.itunes.apple.com/verifyReceipt"
: "https://buy.itunes.apple.com/verifyReceipt")!
var request = URLRequest.spot(.post, url)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params)
} catch {
DispatchQueue.main.spot.async(.failure(.init(.operationFailed, object: params, original: error)), completion)
return
}
URLTask(request).request { task, result in
switch result {
case .failure(let err):
completion(.failure(err))
case .success(let data):
let err: AttributedError
do {
let json = try JSONSerialization.jsonObject(with: data) as? [AnyHashable: Any] ?? [:]
let status = json["status"] as? Int ?? ReceiptStatusReadDataFailed
switch status {
case ReceiptStatusValid:
completion(.success(IAPValidationResponse(receiptValid: true, responseData: json)))
return
case ReceiptStatusTestReceiptSentToProductServer,
ReceiptStatusProductReceiptSentToTestServer:
self.start(receipt: receipt, sharedSecret: sharedSecret, excludeOldTransaction: excludeOldTransaction, sandbox: !sandbox, completion: completion)
return
case ReceiptStatusSharedSecretInvalid:
err = AttributedError(.invalidArgument, userInfo: ["message": "shared_secret_invalid"])
case ReceiptStatusServerNotAvailiable:
err = AttributedError(.serviceMissing)
case ReceiptStatusAuthenticateFailed,
ReceiptStatusNoData,
ReceiptStatusReadDataFailed:
completion(.success(IAPValidationResponse(receiptValid: false, responseData: json)))
return
default:
err = AttributedError(.operationFailed, object: status)
}
} catch {
err = AttributedError(.invalidFormat, original: error)
}
completion(.failure(err))
}
}
}
}
| 38.011628 | 151 | 0.741205 |
e4007e38143ced0a56d9fd6d2854f0274b0b561c | 2,064 | //
// HSDate+Extensions.swift
// HeadStart
//
// Created by Ashfauck on 3/22/19.
// Copyright © 2019 Ashfauck. All rights reserved.
//
import Foundation
extension Date
{
public func toString(with dateFormatter:DateFormatter) -> String?
{
return dateFormatter.string(from: self)
}
public func toString(dateFormat: String,timezone:TimeZone? = nil) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
if let timeZ = timezone
{
dateFormatter.timeZone = timeZ
}
else
{
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
}
dateFormatter.dateFormat = dateFormat
return (dateFormatter.string(from: self))
}
public func currentDate(dateFormat:String) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateFormat = dateFormat
return (dateFormatter.string(from: self))
}
public func getComponents(component: Set<Calendar.Component>) -> DateComponents
{
return Calendar.current.dateComponents(component, from: self)
}
public var age: Int {
return Calendar.current.dateComponents([.year], from: self, to: Date()).year!
}
public func local() -> Date
{
let nowUTC = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {return Date()}
return localDate
}
public func localTime() -> Date
{
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
public func timeStamp() -> Int
{
return Int(self.timeIntervalSince1970)
}
}
| 25.481481 | 131 | 0.601744 |
09bb56ecef80188fd4a2282d2900ec2a5ff348f0 | 2,762 | //
// PlayerView.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 05/06/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
import UI
struct VisualEffectView: UIViewRepresentable {
var effect: UIVisualEffect?
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView {
let view = UIVisualEffectView()
view.isUserInteractionEnabled = false
return view
}
func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) { uiView.effect = effect }
}
struct PlayerView: View {
@EnvironmentObject private var playerManager: MusicPlayerManager
@EnvironmentObject private var items: Items
@State private var playerMode = PlayerMode.playerSmall
@Namespace private var namespace
static let ANIMATION: Animation = .spring(response: 0.5,
dampingFraction: 0.85,
blendDuration: 0)
func togglePlayerMode() {
withAnimation(Self.ANIMATION) {
playerMode.toggleExpanded()
}
}
@ViewBuilder
var body: some View {
VStack {
switch playerMode {
case .playerSmall:
PlayerViewSmall(playerMode: $playerMode, namespace: _namespace.wrappedValue)
.onTapGesture {
togglePlayerMode()
}
case .playerExpanded:
PlayerViewExpanded(playerMode: $playerMode, namespace: _namespace.wrappedValue)
case .playerMusicList:
PlayerViewMusicList(playerMode: $playerMode, namespace: _namespace.wrappedValue)
}
}
.frame(height: playerMode.height())
.background(VisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterial)))
.padding(.bottom, 48)
.gesture(DragGesture()
.onEnded { value in
if value.translation.width > 100 {
playerManager.previous()
}
else if value.translation.width < -100 {
playerManager.next()
} else if value.translation.height > 50 {
withAnimation(Self.ANIMATION) {
playerMode = .playerSmall
}
} else if value.translation.height > -50 {
withAnimation(Self.ANIMATION) {
playerMode = .playerExpanded
}
}
})
}
}
struct PlayerView_Previews: PreviewProvider {
static var previews: some View {
PlayerView()
}
}
| 32.880952 | 121 | 0.569153 |
214c8deb4a85da1dbf505fcd91f14b7212339d89 | 529 | struct Subject: Codable {
let weekDay: String
let weekDayNumber: Int
let startTime: String
let endTime: String
let classRoom: String
let professor: String
let subject: String
enum CodingKeys: String, CodingKey {
case weekDay = "diaDaSemana"
case weekDayNumber = "numeroDiaDaSemana"
case startTime = "horaInicio"
case endTime = "horaTermino"
case classRoom = "numeroSala"
case professor = "professor"
case subject = "nomeDaMateria"
}
}
| 25.190476 | 48 | 0.642722 |
e0b5b82791f21b1b63674f738b10f1366bfd1299 | 675 | import UIKit
@testable import twiliochat
class MockMessagingManager: MessagingManager {
static let mockManager = MockMessagingManager()
static var loginWithUsernameCalled = false
static var registerWithUsernameCalled = false
static var passwordUsed = ""
static var usernameUsed = ""
override class func sharedManager() -> MessagingManager {
return mockManager
}
override func loginWithUsername(username: String,
completion: @escaping (Bool, NSError?) -> Void) {
MockMessagingManager.loginWithUsernameCalled = true
MockMessagingManager.usernameUsed = username
}
}
| 30.681818 | 85 | 0.682963 |
3a458b2662717ebf8f9cbb51c1697b628cc2a90a | 763 | //
// SelectionView.swift
// CurrencyConverterCalculator
//
// Created by Mustafa Ozhan on 16/08/2019.
// Copyright © 2019 Mustafa Ozhan. All rights reserved.
//
import SwiftUI
struct BarItemView: View {
var item: Currency
var body: some View {
HStack {
Image(item.name.lowercased())
.shadow(radius: 3)
Text(item.name).frame(width: 45)
Text(item.longName).font(.footnote)
Text(item.symbol).font(.footnote)
Spacer()
}
.lineLimit(1)
}
}
#if DEBUG
struct BarItemViewPreviews: PreviewProvider {
static var previews: some View {
BarItemView(item: Currency())
.previewLayout(.fixed(width: 300, height: 60))
}
}
#endif
| 22.441176 | 58 | 0.592398 |
694d4d722727abbec6911db7f22031c84177f508 | 371 | //
// GiftShopModel.swift
// StarbucksClone
//
// Created by 박지승 on 2020/05/29.
// Copyright © 2020 momo. All rights reserved.
//
import UIKit
class GSViewSize {
static let shared = GSViewSize()
var navigationBarHeight: CGFloat = 0
let segementHeight: CGFloat = 56
}
class GSCartModel {
static let shared = GSCartModel()
var cart: [String]? = [""]
}
| 16.130435 | 47 | 0.673854 |
0983b2777da73c8bc27c6da60e4e5057e25ea78d | 1,787 | //
// InsertSort.swift
// CoderAlgorithm
//
// Created by HanLiu on 16/5/25.
// Copyright © 2016年 HanLiu. All rights reserved.
//
import Foundation
/*
插入排序
时间复杂度:O(n^2)
算法核心:将i(i>0)前面的每一个元素依次与第i个元素作比较。 a:每次比较后满足循环条件都交换元素;
b:直到比较后不满足循环条件时再交换元素。
与选择排序的区别:插入排序可以提前结束的机会,理论上会比选择排序用时少一点。
当一个数组近似有序时,插入排序的时间复杂度将趋于O(n)
稳定排序
*/
public func insertSort<T:Comparable>( array:[T]) -> [T] {
var a = array
let startTime = CFAbsoluteTimeGetCurrent()
//注意起始位置是从第1个元素开始的,不需要考虑第0个元素
for i in 1..<a.count {
var x = i
//判决条件
while x > 0 && a[x] < a[x-1]{
a.swapAt(x, x-1)
x -= 1
}
}
let finishTime = CFAbsoluteTimeGetCurrent()
print("InsertSort Time =",finishTime - startTime)
return a
}
///上面的经典插入排序耗时是非常高的,因为如果第i个元素比前面的元素都小(或者说满足条件)则每次比较后都会交换元素。我们知道swap函数是一个耗时操作,因为要操作指针(即内存)。
///改进后的插入排序:延迟交换元素的时机,做完所有比较后再赋值。
public func insertSort2<T:Comparable>(array:[T]) -> [T]{
var a = array
let startTime = CFAbsoluteTimeGetCurrent()
for i in 1..<a.count {
//注意:必须要记录当前第i个元素的下标和值,一个i不够用
var x = i
let temp = a[x]
//重点:真正退出while(不满足循环条件)时再交换赋值
while x > 0 && temp<a[x-1] {
a[x] = a[x-1]
x -= 1
}
a[x] = temp
}
let finishTime = CFAbsoluteTimeGetCurrent()
print("InsertSort2 Time =",finishTime - startTime)
return a
}
/*
插入排序的变体:把条件作为入参,用指针函数替代(即block)
*/
public func insertSort<T>( array:[T],isOrderedBefore:(T,T)->Bool) -> [T] {
var a = array
for i in 1..<a.count {
var x = i
let temp = a[x]
while x > 0 && isOrderedBefore(temp,a[x-1]) {
a[x] = a[x-1]
x -= 1
}
a[x] = temp
}
return a
}
| 21.792683 | 90 | 0.56911 |
e620bbb1cbd76a2d5e5c11481d0196081a589669 | 5,342 | @testable import DangerSwiftCoverage
import XCTest
final class XcodeBuildCoverageParserTests: XCTestCase {
override func setUp() {
super.setUp()
MockedXcCovJSONParser.receivedFile = nil
MockedXcCovJSONParser.result = XcCovJSONResponse.data(using: .utf8)
FakeXcodeCoverageFileFinder.receivedXcresultBundlePath = nil
}
func testItParsesTheJSONCorrectly() {
let files = ["/Users/franco/Projects/swift/Sources/Danger/BitBucketServerDSL.swift",
"/Users/franco/Projects/swift/Sources/Danger/Danger.swift",
"/Users/franco/Projects/swift/Sources/RunnerLib/Files Import/ImportsFinder.swift",
"/Users/franco/Projects/swift/Sources/RunnerLib/HelpMessagePresenter.swift"]
let result = try! XcodeBuildCoverageParser.coverage(xcresultBundlePath: "derived", files: files, excludedTargets: [], coverageFileFinder: FakeXcodeCoverageFileFinder.self, xcCovParser: MockedXcCovJSONParser.self)
XCTAssertEqual("derived", FakeXcodeCoverageFileFinder.receivedXcresultBundlePath)
XCTAssertEqual(FakeXcodeCoverageFileFinder.result, MockedXcCovJSONParser.receivedFile)
XCTAssertEqual(result.messages, ["Project coverage: 50.09%"])
let firstSection = result.sections[0]
XCTAssertEqual(firstSection.titleText, "Danger.framework: Coverage: 43.44")
XCTAssertEqual(firstSection.items, [
ReportFile(fileName: "BitBucketServerDSL.swift", coverage: 100),
ReportFile(fileName: "Danger.swift", coverage: 0),
])
let secondSection = result.sections[1]
XCTAssertEqual(secondSection.titleText, "RunnerLib.framework: Coverage: 66.67")
XCTAssertEqual(secondSection.items, [
ReportFile(fileName: "ImportsFinder.swift", coverage: 100),
ReportFile(fileName: "HelpMessagePresenter.swift", coverage: 100),
])
}
func testItFiltersTheExcludedTarget() {
MockedXcCovJSONParser.result = XcCovXcTestJSONResponse.data(using: .utf8)
let files = ["/Users/franco/Projects/swift/Sources/Danger/BitBucketServerDSL.swift",
"/Users/franco/Projects/swift/Sources/Danger/Danger.swift",
"/Users/franco/Projects/swift/Sources/RunnerLib/Files Import/ImportsFinder.swift",
"/Users/franco/Projects/swift/Sources/RunnerLib/HelpMessagePresenter.swift"]
let result = try! XcodeBuildCoverageParser.coverage(xcresultBundlePath: "derived", files: files, excludedTargets: ["RunnerLib.xctest"], coverageFileFinder: FakeXcodeCoverageFileFinder.self, xcCovParser: MockedXcCovJSONParser.self)
XCTAssertEqual("derived", FakeXcodeCoverageFileFinder.receivedXcresultBundlePath)
XCTAssertEqual(FakeXcodeCoverageFileFinder.result, MockedXcCovJSONParser.receivedFile)
XCTAssertEqual(result.messages, ["Project coverage: 50.09%"])
let firstSection = result.sections[0]
XCTAssertEqual(firstSection.titleText, "Danger.framework: Coverage: 43.44")
XCTAssertEqual(firstSection.items, [
ReportFile(fileName: "BitBucketServerDSL.swift", coverage: 100),
ReportFile(fileName: "Danger.swift", coverage: 0),
])
XCTAssertEqual(result.sections.count, 1)
}
func testItFiltersTheEmptyTargets() {
let files = ["/Users/franco/Projects/swift/Sources/Danger/BitBucketServerDSL.swift",
"/Users/franco/Projects/swift/Sources/Danger/Danger.swift"]
let result = try! XcodeBuildCoverageParser.coverage(xcresultBundlePath: "derived", files: files, excludedTargets: [], coverageFileFinder: FakeXcodeCoverageFileFinder.self, xcCovParser: MockedXcCovJSONParser.self)
let firstSection = result.sections[0]
XCTAssertEqual(firstSection.titleText, "Danger.framework: Coverage: 43.44")
XCTAssertEqual(firstSection.items, [
ReportFile(fileName: "BitBucketServerDSL.swift", coverage: 100),
ReportFile(fileName: "Danger.swift", coverage: 0),
])
XCTAssertEqual(result.sections.count, 1)
}
func testItReturnsTheCoverageWhenThereAreNoTargets() {
let files: [String] = []
let result = try! XcodeBuildCoverageParser.coverage(xcresultBundlePath: "derived", files: files, excludedTargets: [], coverageFileFinder: FakeXcodeCoverageFileFinder.self, xcCovParser: MockedXcCovJSONParser.self)
XCTAssertEqual(result.messages, [])
XCTAssertEqual(result.sections.count, 0)
}
}
private struct FakeXcodeCoverageFileFinder: XcodeCoverageFileFinding {
static let result = "result.xccoverage"
static var receivedXcresultBundlePath: String?
static func coverageFile(xcresultBundlePath: String) throws -> String {
receivedXcresultBundlePath = xcresultBundlePath
return result
}
}
private struct MockedXcCovJSONParser: XcCovJSONParsing {
static var result: Data?
static var receivedFile: String?
static func json(fromXCoverageFile file: String) throws -> Data {
receivedFile = file
return result!
}
}
extension ReportFile: Equatable {
public static func == (lhs: ReportFile, rhs: ReportFile) -> Bool {
return lhs.fileName == rhs.fileName &&
lhs.coverage == rhs.coverage
}
}
| 45.65812 | 238 | 0.709659 |
50e01d41d54c065a40f7003f7ecad87b13dbd86b | 6,110 | //
// ObservableType+Extensions.swift
// RxFeedback
//
// Created by Krunoslav Zaher on 4/30/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
extension ObservableType where E == Any {
/// Feedback loop
public typealias FeedbackLoop<State, Event> = (ObservableSchedulerContext<State>) -> Observable<Event>
/**
System simulation will be started upon subscription and stopped after subscription is disposed.
System state is represented as a `State` parameter.
Events are represented by `Event` parameter.
- parameter initialState: Initial state of the system.
- parameter accumulator: Calculates new system state from existing state and a transition event (system integrator, reducer).
- parameter feedback: Feedback loops that produce events depending on current system state.
- returns: Current state of the system.
*/
public static func system<State, Event>(
initialState: State,
reduce: @escaping (State, Event) -> State,
scheduler: ImmediateSchedulerType,
scheduledFeedback: [FeedbackLoop<State, Event>]
) -> Observable<State> {
return Observable<State>.deferred {
let replaySubject = ReplaySubject<State>.create(bufferSize: 1)
let asyncScheduler = scheduler.async
let events: Observable<Event> = Observable.merge(scheduledFeedback.map { feedback in
let state = ObservableSchedulerContext(source: replaySubject.asObservable(), scheduler: asyncScheduler)
let events = feedback(state)
return events
// This is protection from accidental ignoring of scheduler so
// reentracy errors can be avoided
.observeOn(CurrentThreadScheduler.instance)
})
return events.scan(initialState, accumulator: reduce)
.do(onNext: { output in
replaySubject.onNext(output)
}, onSubscribed: {
replaySubject.onNext(initialState)
})
.subscribeOn(scheduler)
.startWith(initialState)
.observeOn(scheduler)
}
}
public static func system<State, Event>(
initialState: State,
reduce: @escaping (State, Event) -> State,
scheduler: ImmediateSchedulerType,
scheduledFeedback: FeedbackLoop<State, Event>...
) -> Observable<State> {
return system(initialState: initialState, reduce: reduce, scheduler: scheduler, scheduledFeedback: scheduledFeedback)
}
}
extension SharedSequenceConvertibleType where E == Any {
/// Feedback loop
public typealias FeedbackLoop<State, Event> = (SharedSequence<SharingStrategy, State>) -> SharedSequence<SharingStrategy, Event>
/**
System simulation will be started upon subscription and stopped after subscription is disposed.
System state is represented as a `State` parameter.
Events are represented by `Event` parameter.
- parameter initialState: Initial state of the system.
- parameter accumulator: Calculates new system state from existing state and a transition event (system integrator, reducer).
- parameter feedback: Feedback loops that produce events depending on current system state.
- returns: Current state of the system.
*/
public static func system<State, Event>(
initialState: State,
reduce: @escaping (State, Event) -> State,
feedback: [FeedbackLoop<State, Event>]
) -> SharedSequence<SharingStrategy, State> {
let observableFeedbacks: [(ObservableSchedulerContext<State>) -> Observable<Event>] = feedback.map { feedback in
return { sharedSequence in
return feedback(sharedSequence.source.asSharedSequence(onErrorDriveWith: .empty()))
.asObservable()
}
}
return Observable<Any>.system(
initialState: initialState,
reduce: reduce,
scheduler: SharingStrategy.scheduler,
scheduledFeedback: observableFeedbacks
)
.asSharedSequence(onErrorDriveWith: .empty())
}
public static func system<State, Event>(
initialState: State,
reduce: @escaping (State, Event) -> State,
feedback: FeedbackLoop<State, Event>...
) -> SharedSequence<SharingStrategy, State> {
return system(initialState: initialState, reduce: reduce, feedback: feedback)
}
}
extension ImmediateSchedulerType {
var async: ImmediateSchedulerType {
// This is a hack because of reentrancy. We need to make sure events are being sent async.
// In case MainScheduler is being used MainScheduler.asyncInstance is used to make sure state is modified async.
// If there is some unknown scheduler instance (like TestScheduler), just use it.
return (self as? MainScheduler).map { _ in MainScheduler.asyncInstance } ?? self
}
}
/// Tuple of observable sequence and corresponding scheduler context on which that observable
/// sequence receives elements.
public struct ObservableSchedulerContext<Element>: ObservableType {
public typealias E = Element
/// Source observable sequence
public let source: Observable<Element>
/// Scheduler on which observable sequence receives elements
public let scheduler: ImmediateSchedulerType
/// Initializes self with source observable sequence and scheduler
///
/// - parameter source: Source observable sequence.
/// - parameter scheduler: Scheduler on which source observable sequence receives elements.
public init(source: Observable<Element>, scheduler: ImmediateSchedulerType) {
self.source = source
self.scheduler = scheduler
}
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
return self.source.subscribe(observer)
}
}
| 41.006711 | 132 | 0.660393 |
f8c32897c124a51b54d56225d8fde90a933965d2 | 4,293 | //
// LogTimeViewController.swift
// TimeCrumbs
//
// Created by Landon Epps on 12/7/19.
// Copyright © 2019 Landon Epps. All rights reserved.
//
import UIKit
class LogTimeViewController: UIViewController {
// MARK: - Properties
var project: Project?
var task: Task?
// MARK: - Outlets
@IBOutlet weak var projectNameLabel: UILabel!
@IBOutlet weak var taskNameTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var durationPicker: UIDatePicker!
@IBOutlet weak var projectColorView: UIView!
@IBOutlet weak var saveButton: UIButton!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
dismissKeyboardOnTap()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// block double-tap on tab bar to navigate to root
tabBarController?.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// disable blocking double-tap on tab bar
tabBarController?.delegate = nil
}
// MARK: - Actions
@IBAction func cancelButtonTapped(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
@IBAction func saveButtonTapped(_ sender: Any) {
guard let project = project,
let moc = project.managedObjectContext
else { return }
var taskName = taskNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines)
if taskName?.isEmpty ?? false {
taskName = nil
}
let duration: Double = durationPicker.countDownDuration
let date = datePicker.date
if let task = task {
TaskController.updateTask(task, name: taskName, date: date, duration: duration)
} else {
TaskController.createTask(project: project, name: taskName, duration: duration, date: date, moc: moc)
}
saveButton.setImage(UIImage(named: "saveButtonCheck"), for: .normal)
saveButton.setTitle("", for: .normal)
saveButton.tintColor = UIColor(named: "saveButtonColor")
saveButton.imageView?.tintColor = UIColor.white
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.navigationController?.popViewController(animated: true)
}
}
// MARK: - Helper Methods
func setupViews() {
guard let project = project else { return }
projectNameLabel.text = project.name
taskNameTextField.delegate = self
if let projectColorName = project.color,
let projectColor = UIColor(named: projectColorName) {
projectColorView.backgroundColor = projectColor
saveButton.tintColor = projectColor
}
if let taskName = task?.name {
taskNameTextField.text = taskName
}
let currentDate = Date()
datePicker.maximumDate = currentDate
if let date = task?.date {
datePicker.date = date
} else {
datePicker.date = currentDate
}
if let duration = task?.duration {
durationPicker.minuteInterval = 1
durationPicker.countDownDuration = duration
} else {
durationPicker.countDownDuration = 1_800 // 30 minutes in seconds
}
}
func dismissKeyboardOnTap() {
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tap)
}
}
extension LogTimeViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
}
}
extension LogTimeViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let indexOfNewVC = tabBarController.viewControllers?.firstIndex(of: viewController)
return (indexOfNewVC != 0) || (indexOfNewVC != tabBarController.selectedIndex)
}
}
| 30.664286 | 122 | 0.631027 |
f9b205c3ab14af220c10b5bf72e6bcf5db700b96 | 2,369 | //
// MovieListViewController.swift
// RedCarpetVIPER
//
// Created by Göksel Köksal on 8.10.2017.
// Copyright © 2017 Packt. All rights reserved.
//
import UIKit
import Commons
final class MovieListViewController: UITableViewController {
var presenter: MovieListPresenterProtocol!
private var moviePresentations: [MovieListPresentation] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Movie List"
presenter.didLoad()
}
}
extension MovieListViewController: MovieListViewProtocol {
func updateMoviePresentations(_ presentations: [MovieListPresentation]) {
self.moviePresentations = presentations
tableView.reloadData()
}
func handleError(_ error: Error) {
let alert = UIAlertController(
title: "API Error",
message: "Could not fetch movies at this time.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
func setLoading(_ flag: Bool) {
UIApplication.shared.isNetworkActivityIndicatorVisible = flag
}
}
// MARK: - UITableViewDataSource
extension MovieListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moviePresentations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
let cellId = "defaultCell"
if let someCell = tableView.dequeueReusableCell(withIdentifier: cellId) {
cell = someCell
} else {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
}
let presentation = moviePresentations[indexPath.row]
cell.textLabel?.text = presentation.title
cell.detailTextLabel?.text = presentation.detail
return cell
}
}
// MARK: - UITableViewDelegate
extension MovieListViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
presenter.didTapOnMovie(at: indexPath.row)
}
}
| 27.870588 | 109 | 0.658928 |
f44e4c0000c68a01f7a876865f1b38c0386fc930 | 4,392 | import Foundation
import azureSwiftRuntime
public protocol TaskList {
var nextLink: String? { get }
var hasAdditionalPages : Bool { get }
var headerParameters: [String: String] { get set }
var jobId : String { get set }
var filter : String? { get set }
var select : String? { get set }
var expand : String? { get set }
var maxResults : Int32? { get set }
var timeout : Int32? { get set }
var apiVersion : String { get set }
var clientRequestId : String? { get set }
var returnClientRequestId : Bool? { get set }
var ocpDate : Date? { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (CloudTaskListResultProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.Task {
// List for multi-instance tasks, information such as affinityId, executionInfo and nodeInfo refer to the primary task.
// Use the list subtasks API to retrieve information about subtasks.
internal class ListCommand : BaseCommand, TaskList {
var nextLink: String?
public var hasAdditionalPages : Bool {
get {
return nextLink != nil
}
}
public var jobId : String
public var filter : String?
public var select : String?
public var expand : String?
public var maxResults : Int32?
public var timeout : Int32?
public var apiVersion = "2017-09-01.6.0"
public var clientRequestId : String?
public var returnClientRequestId : Bool?
public var ocpDate : Date?
public init(jobId: String) {
self.jobId = jobId
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/jobs/{jobId}/tasks"
self.headerParameters = ["Content-Type":"application/json; odata=minimalmetadata; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{jobId}"] = String(describing: self.jobId)
if self.filter != nil { queryParameters["$filter"] = String(describing: self.filter!) }
if self.select != nil { queryParameters["$select"] = String(describing: self.select!) }
if self.expand != nil { queryParameters["$expand"] = String(describing: self.expand!) }
if self.maxResults != nil { queryParameters["maxresults"] = String(describing: self.maxResults!) }
if self.timeout != nil { queryParameters["timeout"] = String(describing: self.timeout!) }
self.queryParameters["api-version"] = String(describing: self.apiVersion)
if self.clientRequestId != nil { headerParameters["client-request-id"] = String(describing: self.clientRequestId!) }
if self.returnClientRequestId != nil { headerParameters["return-client-request-id"] = String(describing: self.returnClientRequestId!) }
if self.ocpDate != nil { headerParameters["ocp-date"] = String(describing: self.ocpDate!) }
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
if var pageDecoder = decoder as? PageDecoder {
pageDecoder.isPagedData = true
pageDecoder.nextLinkName = "OdatanextLink"
}
let result = try decoder.decode(CloudTaskListResultData?.self, from: data)
if var pageDecoder = decoder as? PageDecoder {
self.nextLink = pageDecoder.nextLink
}
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (CloudTaskListResultProtocol?, Error?) -> Void) -> Void {
if self.nextLink != nil {
self.path = nextLink!
self.nextLink = nil;
self.pathType = .absolute
}
client.executeAsync(command: self) {
(result: CloudTaskListResultData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 46.231579 | 148 | 0.595173 |
cce337ec7a71bbfe5e54c240acc109e85acd726a | 1,065 | //
// ConverterViewModel.swift
// UnitCoverter WatchKit Extension
//
// Created by Alfian Losari on 14/09/19.
// Copyright © 2019 Alfian Losari. All rights reserved.
//
import SwiftUI
class ConverterViewModel: ObservableObject {
@Published var fromValue: Double = 0
@Published var toValue: Double = 0
@Published var unit = MainUnit.area {
didSet {
unitChanged()
}
}
@Published var fromUnit: Dimension = UnitArea.squareMeters {
didSet {
calculateUnitDimensionValue()
}
}
@Published var toUnit: Dimension = UnitArea.squareCentimeters {
didSet {
calculateUnitDimensionValue()
}
}
func unitChanged() {
fromUnit = unit.units[0]
toUnit = unit.units[1]
fromValue = 1.0
calculateUnitDimensionValue()
}
func calculateUnitDimensionValue() {
let measurement = Measurement(value: fromValue, unit: fromUnit)
toValue = measurement.converted(to: toUnit).value
}
}
| 23.152174 | 71 | 0.610329 |
6117d178ab47e6fa2fe23a84bfeeaac038e8270a | 575 | //
// WithLockedTrait.swift
// XConcurrencyKit
//
// Created by Serge Bouts on 3/29/20.
// Copyright © 2020 iRiZen.com. All rights reserved.
//
import Foundation
protocol WithLockedTrait: NSLocking {}
extension WithLockedTrait {
@inline(__always) @discardableResult
func withLocked<T>(_ exec: () -> T) -> T {
lock()
defer { unlock() }
return exec()
}
@inline(__always) @discardableResult
func withLocked<T>(_ exec: () throws -> T) rethrows -> T {
lock()
defer { unlock() }
return try exec()
}
}
| 20.535714 | 62 | 0.6 |
90ce9704b55aa3f724d19a749ac0847e769e5e01 | 308 | //
// URLSessionDataTaskProtocol.swift
// CurrencyConverter
//
// Created by mani on 2020-10-31.
// Copyright © 2020 mani. All rights reserved.
//
import Foundation
protocol URLSessionDataTaskProtocol {
func resume()
func cancel()
}
extension URLSessionDataTask: URLSessionDataTaskProtocol {}
| 18.117647 | 59 | 0.74026 |
20c2bb63fafdbcacad8695c4adc1b0961086393c | 2,008 | //
// UIViewFrameExtension.swift
// RAMSport
//
// Created by rambo on 2020/2/17.
// Copyright © 2020 rambo. All rights reserved.
//
import UIKit
extension UIView {
var x: CGFloat {
get {
frame.minX
}
set {
var newFrame = frame
newFrame.origin.x = newValue
frame = newFrame
}
}
var y: CGFloat {
get {
frame.minY
}
set {
var newFrame = frame
newFrame.origin.y = newValue
frame = newFrame
}
}
var width: CGFloat {
get {
frame.width
}
set {
var newFrame = frame
newFrame.size.width = newValue
frame = newFrame
}
}
var height: CGFloat {
get {
frame.height
}
set {
var newFrame = frame
newFrame.size.height = newValue
frame = newFrame
}
}
var bottom: CGFloat {
get {
frame.maxY
}
set {
var newFrame = frame
newFrame.origin.y = newValue - newFrame.size.height
frame = newFrame
}
}
var tail: CGFloat {
get {
frame.maxX
}
set {
var newFrame = frame
newFrame.origin.x = newValue - newFrame.size.width
frame = newFrame
}
}
var midX: CGFloat {
get {
frame.midX
}
set {
var newFrame = frame
newFrame.origin.x = newValue - newFrame.size.width / 2
frame = newFrame
}
}
var midY: CGFloat {
get {
frame.midY
}
set {
var newFrame = frame
newFrame.origin.y = newValue - newFrame.size.height / 2
frame = newFrame
}
}
func ceilFrameXY() {
self.x = ceil(self.x);
self.y = ceil(self.y);
}
}
| 20.489796 | 67 | 0.441733 |
75848202ba822ae868572e68e4b48c98521891f1 | 21,014 | import Foundation
import SourceKittenFramework
@testable import SwiftLintFramework
import XCTest
// swiftlint:disable file_length
private let violationMarker = "↓"
private extension SwiftLintFile {
static func temporary(withContents contents: String) -> SwiftLintFile {
let url = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension("swift")
_ = try? contents.data(using: .utf8)!.write(to: url)
return SwiftLintFile(path: url.path)!
}
func makeCompilerArguments() -> [String] {
return ["-sdk", sdkPath(), "-j4", path!]
}
}
extension String {
func stringByAppendingPathComponent(_ pathComponent: String) -> String {
return bridge().appendingPathComponent(pathComponent)
}
}
let allRuleIdentifiers = Array(primaryRuleList.list.keys)
func violations(_ example: Example, config: Configuration = Configuration()!,
requiresFileOnDisk: Bool = false) -> [StyleViolation] {
SwiftLintFile.clearCaches()
let stringStrippingMarkers = example.removingViolationMarkers()
guard requiresFileOnDisk else {
let file = SwiftLintFile(contents: stringStrippingMarkers.code)
let storage = RuleStorage()
let linter = Linter(file: file, configuration: config).collect(into: storage)
return linter.styleViolations(using: storage)
}
let file = SwiftLintFile.temporary(withContents: stringStrippingMarkers.code)
let storage = RuleStorage()
let collecter = Linter(file: file, configuration: config, compilerArguments: file.makeCompilerArguments())
let linter = collecter.collect(into: storage)
return linter.styleViolations(using: storage).withoutFiles()
}
extension Collection where Element == String {
func violations(config: Configuration = Configuration()!, requiresFileOnDisk: Bool = false)
-> [StyleViolation] {
let makeFile = requiresFileOnDisk ? SwiftLintFile.temporary : SwiftLintFile.init(contents:)
return map(makeFile).violations(config: config, requiresFileOnDisk: requiresFileOnDisk)
}
func corrections(config: Configuration = Configuration()!, requiresFileOnDisk: Bool = false) -> [Correction] {
let makeFile = requiresFileOnDisk ? SwiftLintFile.temporary : SwiftLintFile.init(contents:)
return map(makeFile).corrections(config: config, requiresFileOnDisk: requiresFileOnDisk)
}
}
extension Collection where Element: SwiftLintFile {
func violations(config: Configuration = Configuration()!, requiresFileOnDisk: Bool = false)
-> [StyleViolation] {
let storage = RuleStorage()
let violations = map({ file in
Linter(file: file, configuration: config,
compilerArguments: requiresFileOnDisk ? file.makeCompilerArguments() : [])
}).map({ linter in
linter.collect(into: storage)
}).flatMap({ linter in
linter.styleViolations(using: storage)
})
return requiresFileOnDisk ? violations.withoutFiles() : violations
}
func corrections(config: Configuration = Configuration()!, requiresFileOnDisk: Bool = false) -> [Correction] {
let storage = RuleStorage()
let corrections = map({ file in
Linter(file: file, configuration: config,
compilerArguments: requiresFileOnDisk ? file.makeCompilerArguments() : [])
}).map({ linter in
linter.collect(into: storage)
}).flatMap({ linter in
linter.correct(using: storage)
})
return requiresFileOnDisk ? corrections.withoutFiles() : corrections
}
}
private extension Collection where Element == StyleViolation {
func withoutFiles() -> [StyleViolation] {
return map { violation in
let locationWithoutFile = Location(file: nil, line: violation.location.line,
character: violation.location.character)
return violation.with(location: locationWithoutFile)
}
}
}
private extension Collection where Element == Correction {
func withoutFiles() -> [Correction] {
return map { correction in
let locationWithoutFile = Location(file: nil, line: correction.location.line,
character: correction.location.character)
return Correction(ruleDescription: correction.ruleDescription, location: locationWithoutFile)
}
}
}
extension Collection where Element == Example {
/// Returns a dictionary with SwiftLint violation markers (↓) removed from keys.
///
/// - returns: A new `Array`.
func removingViolationMarkers() -> [Element] {
return map { $0.removingViolationMarkers() }
}
}
private func cleanedContentsAndMarkerOffsets(from contents: String) -> (String, [Int]) {
var contents = contents.bridge()
var markerOffsets = [Int]()
var markerRange = contents.range(of: violationMarker)
while markerRange.location != NSNotFound {
markerOffsets.append(markerRange.location)
contents = contents.replacingCharacters(in: markerRange, with: "").bridge()
markerRange = contents.range(of: violationMarker)
}
return (contents.bridge(), markerOffsets.sorted())
}
private func render(violations: [StyleViolation], in contents: String) -> String {
var contents = StringView(contents).lines.map { $0.content }
for violation in violations.sorted(by: { $0.location > $1.location }) {
guard let line = violation.location.line,
let character = violation.location.character else { continue }
let message = String(repeating: " ", count: character - 1) + "^ " + [
"\(violation.severity.rawValue): ",
"\(violation.ruleName) Violation: ",
violation.reason,
" (\(violation.ruleIdentifier))"].joined()
if line >= contents.count {
contents.append(message)
} else {
contents.insert(message, at: line)
}
}
return """
```
\(contents)
```
"""
}
private func render(locations: [Location], in contents: String) -> String {
var contents = StringView(contents).lines.map { $0.content }
for location in locations.sorted(by: > ) {
guard let line = location.line, let character = location.character else { continue }
let content = NSMutableString(string: contents[line - 1])
content.insert("↓", at: character - 1)
contents[line - 1] = content.bridge()
}
return """
```
\(contents)
```
"""
}
private extension Configuration {
// swiftlint:disable:next function_body_length
func assertCorrection(_ before: Example, expected: Example) {
let (cleanedBefore, markerOffsets) = cleanedContentsAndMarkerOffsets(from: before.code)
let file = SwiftLintFile.temporary(withContents: cleanedBefore)
// expectedLocations are needed to create before call `correct()`
let expectedLocations = markerOffsets.map { Location(file: file, characterOffset: $0) }
let includeCompilerArguments = self.rules.contains(where: { $0 is AnalyzerRule })
let compilerArguments = includeCompilerArguments ? file.makeCompilerArguments() : []
let storage = RuleStorage()
let collecter = Linter(file: file, configuration: self, compilerArguments: compilerArguments)
let linter = collecter.collect(into: storage)
let corrections = linter.correct(using: storage).sorted { $0.location < $1.location }
if expectedLocations.isEmpty {
XCTAssertEqual(
corrections.count, before.code != expected.code ? 1 : 0, #function + ".expectedLocationsEmpty",
file: before.file, line: before.line)
} else {
XCTAssertEqual(
corrections.count,
expectedLocations.count,
#function + ".expected locations: \(expectedLocations.count)",
file: before.file, line: before.line)
for (correction, expectedLocation) in zip(corrections, expectedLocations) {
XCTAssertEqual(
correction.location,
expectedLocation,
#function + ".correction location",
file: before.file, line: before.line)
}
}
XCTAssertEqual(
file.contents,
expected.code,
#function + ".file contents",
file: before.file, line: before.line)
let path = file.path!
do {
let corrected = try String(contentsOfFile: path, encoding: .utf8)
XCTAssertEqual(
corrected,
expected.code,
#function + ".corrected file equals expected",
file: before.file, line: before.line)
} catch {
XCTFail(
"couldn't read file at path '\(path)': \(error)",
file: before.file, line: before.line)
}
}
}
private extension String {
func toStringLiteral() -> String {
return "\"" + replacingOccurrences(of: "\n", with: "\\n") + "\""
}
}
internal func makeConfig(_ ruleConfiguration: Any?, _ identifier: String,
skipDisableCommandTests: Bool = false) -> Configuration? {
let superfluousDisableCommandRuleIdentifier = SuperfluousDisableCommandRule.description.identifier
let identifiers = skipDisableCommandTests ? [identifier] : [identifier, superfluousDisableCommandRuleIdentifier]
if let ruleConfiguration = ruleConfiguration, let ruleType = primaryRuleList.list[identifier] {
// The caller has provided a custom configuration for the rule under test
return (try? ruleType.init(configuration: ruleConfiguration)).flatMap { configuredRule in
let rules = skipDisableCommandTests ? [configuredRule] : [configuredRule, SuperfluousDisableCommandRule()]
return Configuration(rulesMode: .only(identifiers), configuredRules: rules)
}
}
return Configuration(rulesMode: .only(identifiers))
}
private func testCorrection(_ correction: (Example, Example),
configuration: Configuration,
testMultiByteOffsets: Bool) {
#if os(Linux)
guard correction.0.testOnLinux else {
return
}
#endif
var config = configuration
if let correctionConfiguration = correction.0.configuration,
case let .only(onlyRules) = configuration.rulesMode,
let firstRule = onlyRules.first,
case let configDict = ["only_rules": onlyRules, firstRule: correctionConfiguration],
let typedConfiguration = Configuration(dict: configDict) {
config = configuration.merge(with: typedConfiguration)
}
config.assertCorrection(correction.0, expected: correction.1)
if testMultiByteOffsets && correction.0.testMultiByteOffsets {
config.assertCorrection(addEmoji(correction.0), expected: addEmoji(correction.1))
}
}
private func addEmoji(_ example: Example) -> Example {
return example.with(code: "/* 👨👩👧👦👨👩👧👦👨👩👧👦 */\n\(example.code)")
}
private func addShebang(_ example: Example) -> Example {
return example.with(code: "#!/usr/bin/env swift\n\(example.code)")
}
extension XCTestCase {
func verifyRule(_ ruleDescription: RuleDescription,
ruleConfiguration: Any? = nil,
commentDoesntViolate: Bool = true,
stringDoesntViolate: Bool = true,
skipCommentTests: Bool = false,
skipStringTests: Bool = false,
skipDisableCommandTests: Bool = false,
testMultiByteOffsets: Bool = true,
testShebang: Bool = true,
file: StaticString = #file,
line: UInt = #line) {
guard ruleDescription.minSwiftVersion <= .current else {
return
}
guard let config = makeConfig(
ruleConfiguration,
ruleDescription.identifier,
skipDisableCommandTests: skipDisableCommandTests) else {
XCTFail("Failed to create configuration", file: (file), line: line)
return
}
let disableCommands: [String]
if skipDisableCommandTests {
disableCommands = []
} else {
disableCommands = ruleDescription.allIdentifiers.map { "// swiftlint:disable \($0)\n" }
}
self.verifyLint(ruleDescription, config: config, commentDoesntViolate: commentDoesntViolate,
stringDoesntViolate: stringDoesntViolate, skipCommentTests: skipCommentTests,
skipStringTests: skipStringTests, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets, testShebang: testShebang)
self.verifyCorrections(ruleDescription, config: config, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets)
}
func verifyLint(_ ruleDescription: RuleDescription,
config: Configuration,
commentDoesntViolate: Bool = true,
stringDoesntViolate: Bool = true,
skipCommentTests: Bool = false,
skipStringTests: Bool = false,
disableCommands: [String] = [],
testMultiByteOffsets: Bool = true,
testShebang: Bool = true,
file: StaticString = #file,
line: UInt = #line) {
func verify(triggers: [Example], nonTriggers: [Example]) {
verifyExamples(triggers: triggers, nonTriggers: nonTriggers, configuration: config,
requiresFileOnDisk: ruleDescription.requiresFileOnDisk,
file: file, line: line)
}
let triggers = ruleDescription.triggeringExamples
let nonTriggers = ruleDescription.nonTriggeringExamples
verify(triggers: triggers, nonTriggers: nonTriggers)
if testMultiByteOffsets {
verify(triggers: triggers.map(addEmoji), nonTriggers: nonTriggers.map(addEmoji))
}
if testShebang {
verify(triggers: triggers.map(addShebang), nonTriggers: nonTriggers.map(addShebang))
}
func makeViolations(_ example: Example) -> [StyleViolation] {
return violations(example, config: config, requiresFileOnDisk: ruleDescription.requiresFileOnDisk)
}
// Comment doesn't violate
if !skipCommentTests {
XCTAssertEqual(
triggers.flatMap({ makeViolations($0.with(code: "/*\n " + $0.code + "\n */")) }).count,
commentDoesntViolate ? 0 : triggers.count,
"Violation(s) still triggered when code was nested inside comment",
file: (file), line: line
)
}
// String doesn't violate
if !skipStringTests {
XCTAssertEqual(
triggers.flatMap({ makeViolations($0.with(code: $0.code.toStringLiteral())) }).count,
stringDoesntViolate ? 0 : triggers.count,
file: (file), line: line
)
}
// "disable" commands doesn't violate
for command in disableCommands {
XCTAssert(triggers.flatMap({ makeViolations($0.with(code: command + $0.code)) }).isEmpty,
file: (file), line: line)
}
}
func verifyCorrections(_ ruleDescription: RuleDescription, config: Configuration,
disableCommands: [String], testMultiByteOffsets: Bool) {
parserDiagnosticsDisabledForTests = true
// corrections
ruleDescription.corrections.forEach {
testCorrection($0, configuration: config, testMultiByteOffsets: testMultiByteOffsets)
}
// make sure strings that don't trigger aren't corrected
ruleDescription.nonTriggeringExamples.forEach {
testCorrection(($0, $0), configuration: config, testMultiByteOffsets: testMultiByteOffsets)
}
// "disable" commands do not correct
ruleDescription.corrections.forEach { before, _ in
for command in disableCommands {
let beforeDisabled = command + before.code
let expectedCleaned = before.with(code: cleanedContentsAndMarkerOffsets(from: beforeDisabled).0)
config.assertCorrection(expectedCleaned, expected: expectedCleaned)
}
}
}
// swiftlint:disable:next function_body_length
private func verifyExamples(triggers: [Example], nonTriggers: [Example],
configuration config: Configuration, requiresFileOnDisk: Bool,
file callSiteFile: StaticString = #file,
line callSiteLine: UInt = #line) {
// Non-triggering examples don't violate
for nonTrigger in nonTriggers {
let unexpectedViolations = violations(nonTrigger, config: config,
requiresFileOnDisk: requiresFileOnDisk)
if unexpectedViolations.isEmpty { continue }
let nonTriggerWithViolations = render(violations: unexpectedViolations, in: nonTrigger.code)
XCTFail(
"nonTriggeringExample violated: \n\(nonTriggerWithViolations)",
file: nonTrigger.file,
line: nonTrigger.line)
}
// Triggering examples violate
for trigger in triggers {
let triggerViolations = violations(trigger, config: config,
requiresFileOnDisk: requiresFileOnDisk)
// Triggering examples with violation markers violate at the marker's location
let (cleanTrigger, markerOffsets) = cleanedContentsAndMarkerOffsets(from: trigger.code)
if markerOffsets.isEmpty {
if triggerViolations.isEmpty {
XCTFail(
"triggeringExample did not violate: \n```\n\(trigger)\n```",
file: trigger.file,
line: trigger.line)
}
continue
}
let file = SwiftLintFile(contents: cleanTrigger)
let expectedLocations = markerOffsets.map { Location(file: file, characterOffset: $0) }
// Assert violations on unexpected location
let violationsAtUnexpectedLocation = triggerViolations
.filter { !expectedLocations.contains($0.location) }
if !violationsAtUnexpectedLocation.isEmpty {
XCTFail("triggeringExample violated at unexpected location: \n" +
"\(render(violations: violationsAtUnexpectedLocation, in: trigger.code))",
file: trigger.file,
line: trigger.line)
}
// Assert locations missing violation
let violatedLocations = triggerViolations.map { $0.location }
let locationsWithoutViolation = expectedLocations
.filter { !violatedLocations.contains($0) }
if !locationsWithoutViolation.isEmpty {
XCTFail("triggeringExample did not violate at expected location: \n" +
"\(render(locations: locationsWithoutViolation, in: cleanTrigger))",
file: trigger.file,
line: trigger.line)
}
XCTAssertEqual(triggerViolations.count, expectedLocations.count,
file: trigger.file, line: trigger.line)
for (triggerViolation, expectedLocation) in zip(triggerViolations, expectedLocations) {
XCTAssertEqual(
triggerViolation.location, expectedLocation,
"'\(trigger)' violation didn't match expected location.",
file: trigger.file,
line: trigger.line)
}
}
}
// file and line parameters are first so we can use trailing closure syntax with the closure
func checkError<T: Error & Equatable>(
file: StaticString = #file,
line: UInt = #line,
_ error: T,
closure: () throws -> Void) {
do {
try closure()
XCTFail("No error caught", file: (file), line: line)
} catch let rError as T {
if error != rError {
XCTFail("Wrong error caught. Got \(rError) but was expecting \(error)", file: (file), line: line)
}
} catch {
XCTFail("Wrong error caught", file: (file), line: line)
}
}
}
| 43.417355 | 118 | 0.614114 |
9c575e9f3aed289fff314646de73be8cccd87c08 | 615 | //
// AppDelegate.swift
// YPImagePickerExample
//
// Created by Sacha DSO on 17/03/2017.
// Copyright © 2017 Octopepper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ExampleViewController()
window?.makeKeyAndVisible()
return true
}
}
| 25.625 | 115 | 0.697561 |
9b0770eebbcdd1e62fc57b366a7d1f6452497438 | 3,723 | //
// DynamicContentExampleViewController.swift
// SwiftFortuneWheelDemo-tvOS
//
// Created by Sherzod Khashimov on 7/12/20.
// Copyright © 2020 Sherzod Khashimov. All rights reserved.
//
import UIKit
import SwiftFortuneWheel
class DynamicContentExampleViewController: UIViewController {
@IBOutlet weak var drawCurvedLineSegment: UISegmentedControl!
@IBOutlet weak var colorsTypeSegment: UISegmentedControl!
@IBOutlet weak var fortuneWheel: SwiftFortuneWheel! {
didSet {
fortuneWheel.onSpinButtonTap = { [weak self] in
self?.startAnimating()
}
}
}
var prizes: [Prize] = []
var drawCurvedLine: Bool = false {
didSet {
updateSlices()
}
}
var minimumPrize: Int {
return 4
}
var maximumPrize: Int {
return 12
}
var finishIndex: Int {
return Int.random(in: 0..<fortuneWheel.slices.count)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
drawCurvedLine = drawCurvedLineSegment.selectedSegmentIndex == 1
self.title = "Dynamic Content Example"
prizes.append(Prize(amount: 100, description: "Prize".uppercased(), priceType: .money))
prizes.append(Prize(amount: 200, description: "Prize".uppercased(), priceType: .money))
prizes.append(Prize(amount: 300, description: "Prize".uppercased(), priceType: .money))
prizes.append(Prize(amount: 400, description: "Prize".uppercased(), priceType: .money))
updateSlices()
fortuneWheel.configuration = .blackCyanColorsConfiguration
}
@IBAction func colorsTypeValueChanged(_ sender: Any) {
switch colorsTypeSegment.selectedSegmentIndex {
case 1:
fortuneWheel.configuration = .rainbowColorsConfiguration
default:
fortuneWheel.configuration = .blackCyanColorsConfiguration
}
updateSlices()
}
@IBAction func addPrizeAction(_ sender: Any) {
guard prizes.count < maximumPrize - 1 else { return }
let price = Prize(amount: (prizes.count + 1) * 100, description: "Prize".uppercased(), priceType: .money)
prizes.append(price)
updateSlices()
}
@IBAction func removePrizeAction(_ sender: Any) {
guard prizes.count > minimumPrize else { return }
_ = prizes.popLast()
updateSlices()
}
@IBAction func drawCurverLineSegmentChanged(_ sender: UISegmentedControl) {
drawCurvedLine = sender.selectedSegmentIndex == 1
}
func updateSlices() {
let slices: [Slice] = prizes.map({ Slice(contents: $0.sliceContentTypes(isMonotone: colorsTypeSegment.selectedSegmentIndex == 1, withLine: drawCurvedLine)) })
fortuneWheel.slices = slices
if prizes.count == maximumPrize - 1 {
let imageSliceContent = Slice.ContentType.assetImage(name: "crown", preferences: ImagePreferences(preferredSize: CGSize(width: 40, height: 40), verticalOffset: 40))
var slice = Slice(contents: [imageSliceContent])
if drawCurvedLine {
let linePreferences = LinePreferences(colorType: .customPatternColors(colors: nil, defaultColor: .black), height: 2, verticalOffset: 35)
let line = Slice.ContentType.line(preferences: linePreferences)
slice.contents.append(line)
}
fortuneWheel.slices.append(slice)
}
}
func startAnimating() {
fortuneWheel.startAnimating(indefiniteRotationTimeInSeconds: 1, finishIndex: finishIndex) { (finished) in
print(finished)
}
}
}
| 31.550847 | 176 | 0.648939 |
2254571eaeb03f2ffe5baa7b079ec86bd4c17a36 | 7,613 | //
// ContentView.swift
// Pipeliner
//
// Created by dx hero on 03.09.2020.
//
import SwiftUI
import WidgetKit
struct ContentView: View {
internal let pipelinerService: PipelinerService = PipelinerService()
static let serviceTypes = ServiceType.allCases.map { $0.rawValue }
@State private var serviceType = 0
@State private var projectId = ""
@State private var token = ""
@State private var baseUrl = ""
@State private var savedBaseUrl = ""
@State private var pipelines: [PipelineResult]
@State private var configurations: [Config]
@State private var selection: ServiceType = .GITLAB
@Environment(\.colorScheme) var colorScheme
let windowBackground = (dark: NSColor.darkGray, light: NSColor.white)
let headerIcon = (dark: Color.white, light: Color.purple)
let headerText = (dark: Color.gray, light: Color.black)
let miniIcon = (dark: Color.blue, light: Color.purple)
let formTitle = (dark: Color.white, light: Color.black)
let projectTitle = (dark: Color.white, light: Color.black)
let projectSubtitle = Color.gray
init() {
_pipelines = State(initialValue: pipelinerService.getPipelines(pipelineCount: 10))
_configurations = State(initialValue: ConfigurationService.getConfigurations())
}
private func isFormValid() -> Bool {
if projectId.isEmpty {
return false
}
if baseUrl.isEmpty {
return false
}
if token.isEmpty {
return false
}
return true
}
var body: some View {
ZStack {
Color(colorScheme == .dark ? windowBackground.dark: windowBackground.light).opacity(0.15).edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
HStack(content: {
VStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, content: {
Image(systemName: "gear")
.font(.system(size: 40))
.foregroundColor(colorScheme == .dark ? headerIcon.dark: headerIcon.light)
.padding(.bottom, 6)
Text("Add Configuration")
.font(.title2)
.multilineTextAlignment(.center)
.foregroundColor(colorScheme == .dark ? headerText.dark: headerText.light)
Divider()
Form {
Section{
Section{
Text("Base Url")
.font(.title3)
.padding(.horizontal)
TextField("http://gitlab.com",text: $baseUrl)
.cornerRadius(5)
.padding(.horizontal)
}
.padding(.bottom, 2)
Section{
Text("Project ID")
.font(.title3)
.padding(.horizontal)
TextField("1234",text: $projectId)
.cornerRadius(5)
.padding(.horizontal)
}
.padding(.bottom, 2)
HStack {
Text("Private Access Token")
.font(.title3)
.cornerRadius(15)
.padding(.leading)
Link(destination: URL(string: "https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#creating-a-personal-access-token")!) {
Image(systemName: "questionmark.circle").font(.title3).foregroundColor(colorScheme == .dark ? miniIcon.dark: miniIcon.light)
}
}
TextField("your-secret-token",text: $token)
.cornerRadius(5)
.padding(.horizontal)
}
}
Button(action: {
if let projectName = pipelinerService.getProjectName(baseUrl: baseUrl, projectId: projectId, token: token) {
configurations = ConfigurationService.addConfiguration(config: Config(id: UUID().uuidString, baseUrl: baseUrl, projectId: projectId, token: token, repositoryName: projectName))
pipelines = pipelinerService.getPipelines(pipelineCount: 10)
WidgetCenter.shared.reloadAllTimelines()
} else {
savedBaseUrl = "not found"
}
}) {
HStack {
Image(systemName: "plus")
.font(.system(size: 16))
.foregroundColor(.white)
Text("Save")
.font(.system(size: 12))
.fontWeight(.semibold)
.foregroundColor(.white)
}
}
.disabled(!self.isFormValid())
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(colorScheme == .dark ? miniIcon.dark: miniIcon.light)
)
.padding()
VStack {
Image(systemName: "square.and.arrow.down.on.square")
.font(.system(size: 40))
.foregroundColor(colorScheme == .dark ? headerIcon.dark: headerIcon.light)
.padding(.bottom, 6)
Text("Saved Configuration")
.font(.title2)
.multilineTextAlignment(.center)
.foregroundColor(colorScheme == .dark ? headerText.dark: headerText.light)
Divider()
VStack {
ForEach(configurations, id: \.self){ configuration in
HStack(content: {
VStack(alignment: .leading, content: {
Text(configuration.repositoryName.uppercased())
Text(configuration.baseUrl)
.foregroundColor(projectSubtitle)
})
Spacer()
VStack(alignment: .leading, content: {
Button(action: {
configurations = ConfigurationService.deleteConfiguration(id: configuration.id)
pipelines = pipelinerService.getPipelines(pipelineCount: 10)
WidgetCenter.shared.reloadAllTimelines()
}) {
Image(systemName: "minus.circle").font(.system(size: 24)).foregroundColor(colorScheme == .dark ? miniIcon.dark: miniIcon.light)
}
})
})
.foregroundColor(projectTitle.dark)
.padding(.horizontal)
.buttonStyle(BorderlessButtonStyle())
}
}
.padding(.bottom)
}
.padding(.top)
Spacer()
})
.padding()
Divider()
VStack {
Image(systemName: "waveform.path.ecg")
.font(.system(size: 40))
.foregroundColor(colorScheme == .dark ? headerIcon.dark: headerIcon.light)
.padding(.bottom, 6)
Text("Pipelines").font(.title2).multilineTextAlignment(.center).foregroundColor(colorScheme == .dark ? headerText.dark: headerText.light)
Divider()
if(pipelines.count != 0) {
ForEach(0..<pipelines.count){ index in
PipelineDetailView(pipeline: pipelines[index], isLastRow: index == pipelines.count - 1 ? true : false)
}
}
Spacer()
}
})
.foregroundColor(colorScheme == .dark ? formTitle.dark: formTitle.light)
.padding()
Spacer()
}
.padding(.bottom)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 34.447964 | 191 | 0.535663 |
7a5e9f50f06cf6d15c6a3293a2960b493403b021 | 2,895 | //
// TelegramApiProvider.swift
// TelegramBot
//
// Created by Koray Koska on 29.01.19.
//
import Foundation
public protocol TelegramApiProvider {
typealias TelegramApiResponseCompletion<Result: Codable> = (_ resp: TelegramResponse<Result>) -> Void
func send<Params: Codable, Result: Codable>(method: String, request: Params, response: @escaping TelegramApiResponseCompletion<Result>)
}
public struct TelegramResponse<Result: Codable> {
public enum Error: Swift.Error {
case emptyResponse
case requestFailed(Swift.Error?)
case connectionFailed(Swift.Error?)
case serverError(Swift.Error?)
case decodingError(Swift.Error?)
}
public enum Status<Result> {
case success(Result)
case failure(Swift.Error)
}
public let status: Status<Result>
public var result: Result? {
return status.result
}
public var error: Swift.Error? {
return status.error
}
// MARK: - Initialization
public init(status: Status<Result>) {
self.status = status
}
/// Initialize with any Error object
public init(error: Swift.Error) {
self.status = .failure(error)
}
/// Initialize with a response
public init(response: TelegramApiResponse<Result>) {
if let result = response.result {
self.status = .success(result)
} else if let error = response.error {
self.status = .failure(error)
} else {
self.status = .failure(Error.emptyResponse)
}
}
/// For convenience, initialize with one of the common errors
public init(error: Error) {
self.status = .failure(error)
}
}
/// Convenience properties
extension TelegramResponse.Status {
public var isSuccess: Bool {
switch self {
case .success:
return true
case .failure:
return false
}
}
public var isFailure: Bool {
return !isSuccess
}
public var result: Result? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
public var error: Error? {
switch self {
case .failure(let error):
return error
case .success:
return nil
}
}
}
extension TelegramResponse.Status: CustomStringConvertible {
public var description: String {
switch self {
case .success:
return "SUCCESS"
case .failure:
return "FAILURE"
}
}
}
extension TelegramResponse.Status: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .success(let value):
return "SUCCESS: \(value)"
case .failure(let error):
return "FAILURE: \(error)"
}
}
}
| 23.16 | 139 | 0.596546 |
ef32cda8a93e37b9081657acf5e1462e8d659fc5 | 336 | //
// FirstViewController.swift
// Ubike
//
// Created by kidnapper on 2019/11/24.
// Copyright © 2019 kidnapper. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 16 | 58 | 0.669643 |
dba0bb956cf726bf0caa300aa8036596ca1c7a59 | 1,123 | //
// MyCollectionViewCell.swift
// MobileClasswork
//
// Created by Macbook Pro 15 on 2/11/20.
// Copyright © 2020 SamuelFolledo. All rights reserved.
//
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
static var identifier: String = "Cell"
var textLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
let textLabel = UILabel(frame: .zero)
textLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(textLabel)
NSLayoutConstraint.activate([
self.contentView.centerXAnchor.constraint(equalTo: textLabel.centerXAnchor),
self.contentView.centerYAnchor.constraint(equalTo: textLabel.centerYAnchor),
])
self.backgroundColor = UIColor.lightGray
self.textLabel = textLabel
self.textLabel.font = UIFont(name: "Helvetica", size: 26)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
| 28.794872 | 88 | 0.669635 |
09c04988ebb02047138bcecb9e5b98139b95394b | 388 | //
// mRayonApp.swift
// wRayon WatchKit Extension
//
// Created by Rachel on 3/23/22.
//
import SwiftUI
@main
struct mRayonApp: App {
@SceneBuilder var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}
}
WKNotificationScene(controller: NotificationController.self, category: "myCategory")
}
}
| 17.636364 | 92 | 0.595361 |
fec16dd93297cc083a32390b4c63395f42d3b47a | 13,897 | // File created from ScreenTemplate
// $ createScreen.sh Room Room
/*
Copyright 2021 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
final class RoomCoordinator: NSObject, RoomCoordinatorProtocol {
// MARK: - Properties
// MARK: Private
private let parameters: RoomCoordinatorParameters
private let roomViewController: RoomViewController
private let activityIndicatorPresenter: ActivityIndicatorPresenterType
private var selectedEventId: String?
private var roomDataSourceManager: MXKRoomDataSourceManager {
return MXKRoomDataSourceManager.sharedManager(forMatrixSession: self.parameters.session)
}
/// Indicate true if the Coordinator has started once
private var hasStartedOnce: Bool {
return self.roomViewController.delegate != nil
}
private var navigationRouter: NavigationRouterType? {
var finalNavigationRouter: NavigationRouterType?
if let navigationRouter = self.parameters.navigationRouter {
finalNavigationRouter = navigationRouter
} else if let navigationRouterStore = self.parameters.navigationRouterStore, let currentNavigationController = self.roomViewController.navigationController {
// If no navigationRouter has been provided, try to get the navigation router from the current RoomViewController navigation controller if exists
finalNavigationRouter = navigationRouterStore.navigationRouter(for: currentNavigationController)
}
return finalNavigationRouter
}
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: RoomCoordinatorDelegate?
var canReleaseRoomDataSource: Bool {
// If the displayed data is not a preview, let the manager release the room data source
// (except if the view controller has the room data source ownership).
return self.parameters.previewData == nil && self.roomViewController.roomDataSource != nil && self.roomViewController.hasRoomDataSourceOwnership == false
}
// MARK: - Setup
init(parameters: RoomCoordinatorParameters) {
self.parameters = parameters
self.selectedEventId = parameters.eventId
self.roomViewController = RoomViewController.instantiate()
self.activityIndicatorPresenter = ActivityIndicatorPresenter()
if #available(iOS 14, *) {
PollTimelineProvider.shared.session = parameters.session
}
super.init()
}
deinit {
roomViewController.destroy()
}
// MARK: - Public
func start() {
self.start(withCompletion: nil)
}
// NOTE: Completion closure has been added for legacy architecture purpose.
// Remove this completion after LegacyAppDelegate refactor.
func start(withCompletion completion: (() -> Void)?) {
self.roomViewController.delegate = self
// Detect when view controller has been dismissed by gesture when presented modally (not in full screen).
// FIXME: Find a better way to manage modal dismiss. This makes the `roomViewController` to never be released
// self.roomViewController.presentationController?.delegate = self
if let previewData = self.parameters.previewData {
self.loadRoomPreview(withData: previewData, completion: completion)
} else if let eventId = self.selectedEventId {
self.loadRoom(withId: self.parameters.roomId, and: eventId, completion: completion)
} else {
self.loadRoom(withId: self.parameters.roomId, completion: completion)
}
// Add `roomViewController` to the NavigationRouter, only if it has been explicitly set as parameter
if let navigationRouter = self.parameters.navigationRouter {
if navigationRouter.modules.isEmpty == false {
navigationRouter.push(self.roomViewController, animated: true, popCompletion: nil)
} else {
navigationRouter.setRootModule(self.roomViewController, popCompletion: nil)
}
}
}
func start(withEventId eventId: String, completion: (() -> Void)?) {
self.selectedEventId = eventId
if self.hasStartedOnce {
self.loadRoom(withId: self.parameters.roomId, and: eventId, completion: completion)
} else {
self.start(withCompletion: completion)
}
}
func toPresentable() -> UIViewController {
return self.roomViewController
}
// MARK: - Private
private func loadRoom(withId roomId: String, completion: (() -> Void)?) {
// Present activity indicator when retrieving roomDataSource for given room ID
self.activityIndicatorPresenter.presentActivityIndicator(on: roomViewController.view, animated: false)
let roomDataSourceManager: MXKRoomDataSourceManager = MXKRoomDataSourceManager.sharedManager(forMatrixSession: self.parameters.session)
// LIVE: Show the room live timeline managed by MXKRoomDataSourceManager
roomDataSourceManager.roomDataSource(forRoom: roomId, create: true, onComplete: { [weak self] (roomDataSource) in
guard let self = self else {
return
}
self.activityIndicatorPresenter.removeCurrentActivityIndicator(animated: true)
if let roomDataSource = roomDataSource {
self.roomViewController.displayRoom(roomDataSource)
}
completion?()
})
}
private func loadRoom(withId roomId: String, and eventId: String, completion: (() -> Void)?) {
// Present activity indicator when retrieving roomDataSource for given room ID
self.activityIndicatorPresenter.presentActivityIndicator(on: roomViewController.view, animated: false)
// Open the room on the requested event
RoomDataSource.load(withRoomId: roomId,
initialEventId: eventId,
andMatrixSession: self.parameters.session) { [weak self] (dataSource) in
guard let self = self else {
return
}
self.activityIndicatorPresenter.removeCurrentActivityIndicator(animated: true)
guard let roomDataSource = dataSource as? RoomDataSource else {
return
}
roomDataSource.markTimelineInitialEvent = true
self.roomViewController.displayRoom(roomDataSource)
// Give the data source ownership to the room view controller.
self.roomViewController.hasRoomDataSourceOwnership = true
completion?()
}
}
private func loadRoomPreview(withData previewData: RoomPreviewData, completion: (() -> Void)?) {
self.roomViewController.displayRoomPreview(previewData)
completion?()
}
private func startLocationCoordinatorWithEvent(_ event: MXEvent? = nil, bubbleData: MXKRoomBubbleCellDataStoring? = nil) {
guard #available(iOS 14.0, *) else {
return
}
guard let navigationRouter = self.navigationRouter,
let mediaManager = mxSession?.mediaManager,
let user = mxSession?.myUser else {
MXLog.error("[RoomCoordinator] Invalid location sharing coordinator parameters. Returning.")
return
}
var avatarData: AvatarInputProtocol
if event != nil, let bubbleData = bubbleData {
avatarData = AvatarInput(mxContentUri: bubbleData.senderAvatarUrl,
matrixItemId: bubbleData.senderId,
displayName: bubbleData.senderDisplayName)
} else {
avatarData = AvatarInput(mxContentUri: user.avatarUrl,
matrixItemId: user.userId,
displayName: user.displayname)
}
var location: CLLocationCoordinate2D?
if let locationContent = event?.location {
location = CLLocationCoordinate2D(latitude: locationContent.latitude, longitude: locationContent.longitude)
}
let parameters = LocationSharingCoordinatorParameters(roomDataSource: roomViewController.roomDataSource,
mediaManager: mediaManager,
avatarData: avatarData,
location: location)
let coordinator = LocationSharingCoordinator(parameters: parameters)
coordinator.completion = { [weak self, weak coordinator] in
guard let self = self, let coordinator = coordinator else {
return
}
self.navigationRouter?.dismissModule(animated: true, completion: nil)
self.remove(childCoordinator: coordinator)
}
add(childCoordinator: coordinator)
navigationRouter.present(coordinator, animated: true)
coordinator.start()
}
}
// MARK: - RoomIdentifiable
extension RoomCoordinator: RoomIdentifiable {
var roomId: String? {
return self.parameters.roomId
}
var mxSession: MXSession? {
self.parameters.session
}
}
// MARK: - UIAdaptivePresentationControllerDelegate
extension RoomCoordinator: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
self.delegate?.roomCoordinatorDidDismissInteractively(self)
}
}
// MARK: - RoomViewControllerDelegate
extension RoomCoordinator: RoomViewControllerDelegate {
func roomViewController(_ roomViewController: RoomViewController, showRoomWithId roomID: String) {
self.delegate?.roomCoordinator(self, didSelectRoomWithId: roomID)
}
func roomViewController(_ roomViewController: RoomViewController, showMemberDetails roomMember: MXRoomMember) {
// TODO:
}
func roomViewControllerShowRoomDetails(_ roomViewController: RoomViewController) {
// TODO:
}
func roomViewControllerDidLeaveRoom(_ roomViewController: RoomViewController) {
self.delegate?.roomCoordinatorDidLeaveRoom(self)
}
func roomViewControllerPreviewDidTapCancel(_ roomViewController: RoomViewController) {
self.delegate?.roomCoordinatorDidCancelRoomPreview(self)
}
func roomViewController(_ roomViewController: RoomViewController, startChatWithUserId userId: String, completion: @escaping () -> Void) {
AppDelegate.theDelegate().createDirectChat(withUserId: userId, completion: completion)
}
func roomViewController(_ roomViewController: RoomViewController, showCompleteSecurityFor session: MXSession) {
AppDelegate.theDelegate().presentCompleteSecurity(for: session)
}
func roomViewController(_ roomViewController: RoomViewController, handleUniversalLinkWith parameters: UniversalLinkParameters) -> Bool {
return AppDelegate.theDelegate().handleUniversalLink(with: parameters)
}
func roomViewControllerDidRequestPollCreationFormPresentation(_ roomViewController: RoomViewController) {
guard #available(iOS 14.0, *) else {
return
}
let parameters = PollEditFormCoordinatorParameters(room: roomViewController.roomDataSource.room)
let coordinator = PollEditFormCoordinator(parameters: parameters)
coordinator.completion = { [weak self, weak coordinator] in
guard let self = self, let coordinator = coordinator else {
return
}
self.navigationRouter?.dismissModule(animated: true, completion: nil)
self.remove(childCoordinator: coordinator)
}
add(childCoordinator: coordinator)
navigationRouter?.present(coordinator, animated: true)
coordinator.start()
}
func roomViewControllerDidRequestLocationSharingFormPresentation(_ roomViewController: RoomViewController) {
startLocationCoordinatorWithEvent()
}
func roomViewController(_ roomViewController: RoomViewController, didRequestLocationPresentationFor event: MXEvent, bubbleData: MXKRoomBubbleCellDataStoring) {
startLocationCoordinatorWithEvent(event, bubbleData: bubbleData)
}
func roomViewController(_ roomViewController: RoomViewController, canEndPollWithEventIdentifier eventIdentifier: String) -> Bool {
guard #available(iOS 14.0, *) else {
return false
}
return PollTimelineProvider.shared.pollTimelineCoordinatorForEventIdentifier(eventIdentifier)?.canEndPoll() ?? false
}
func roomViewController(_ roomViewController: RoomViewController, endPollWithEventIdentifier eventIdentifier: String) {
guard #available(iOS 14.0, *) else {
return
}
PollTimelineProvider.shared.pollTimelineCoordinatorForEventIdentifier(eventIdentifier)?.endPoll()
}
}
| 39.257062 | 165 | 0.668705 |
c1e330c87a73672464e18f7dc4de58e763b14448 | 2,660 | //
// MIT License
//
// Copyright (c) 2017 Robert-Hein Hooijmans <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension TinyEdgeInsets {
public static func uniform(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: value, left: value, bottom: value, right: value)
}
public static func top(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: value, left: 0, bottom: 0, right: 0)
}
public static func left(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: 0, left: value, bottom: 0, right: 0)
}
public static func bottom(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: 0, left: 0, bottom: value, right: 0)
}
public static func right(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: 0, left: 0, bottom: 0, right: value)
}
public static func horizontal(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: 0, left: value, bottom: 0, right: value)
}
public static func vertical(_ value: CGFloat) -> TinyEdgeInsets {
return TinyEdgeInsets(top: value, left: 0, bottom: value, right: 0)
}
}
public func + (lhs: TinyEdgeInsets, rhs: TinyEdgeInsets) -> TinyEdgeInsets {
return .init(top: lhs.top + rhs.top, left: lhs.left + rhs.left, bottom: lhs.bottom + rhs.bottom, right: lhs.right + rhs.right)
}
| 37.464789 | 130 | 0.684586 |
f45e6f7611425ddeea95f02c35151577ac01d83c | 2,330 | // swift-tools-version: 5.4
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
#if os(macOS)
let excludeFiles = [
"./Browser/BrowserViewController.swift" // Because of inheriting iOS only class failed to build on macOS.
]
#elseif os(iOS)
let excludeFiles: String = []
#endif
let package = Package(
name: "Web3swift",
platforms: [
.macOS(.v10_12), .iOS(.v11)
],
products: [
.library(name: "web3swift", targets: ["web3swift"])
],
dependencies: [
.package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0"),
.package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.16.2"),
.package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.4"),
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .exact("1.4.3"))
],
targets: [
.target(name: "secp256k1"),
.target(
name: "web3swift",
dependencies: ["BigInt", "secp256k1", "PromiseKit", "Starscream", "CryptoSwift"],
exclude: excludeFiles,
resources: [
.copy("./Browser/browser.js"),
.copy("./Browser/browser.min.js"),
.copy("./Browser/wk.bridge.min.js")
]
),
.testTarget(
name: "localTests",
dependencies: ["web3swift"],
path: "Tests/web3swiftTests/localTests",
resources: [
.copy("../../../TestToken/Helpers/SafeMath/SafeMath.sol"),
.copy("../../../TestToken/Helpers/TokenBasics/ERC20.sol"),
.copy("../../../TestToken/Helpers/TokenBasics/IERC20.sol"),
.copy("../../../TestToken/Token/Web3SwiftToken.sol")
]
),
.testTarget(
name: "remoteTests",
dependencies: ["web3swift"],
path: "Tests/web3swiftTests/remoteTests",
resources: [
.copy("../../../TestToken/Helpers/SafeMath/SafeMath.sol"),
.copy("../../../TestToken/Helpers/TokenBasics/ERC20.sol"),
.copy("../../../TestToken/Helpers/TokenBasics/IERC20.sol"),
.copy("../../../TestToken/Token/Web3SwiftToken.sol")
]
)
]
)
| 35.846154 | 109 | 0.544206 |
750cceda1ec084d49f8be0aa278559caebca577a | 679 | //
// FeedSubscriptionCell.swift
// FeedApp
//
// Created by David Márquez Delgado on 24/11/2018.
// Copyright © 2018 David Márquez Delgado. All rights reserved.
//
import UIKit
class FeedSubscriptionCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myStatus: UILabel!
@IBOutlet weak var myUnreaded: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.633333 | 65 | 0.65243 |
4862a8e66f12517e64cb3d720fc6abf13336c83f | 3,046 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
// REQUIRES: concurrency
// REQUIRES: distributed
import Distributed
import FakeDistributedActorSystems
typealias DefaultDistributedActorSystem = FakeActorSystem
// ==== -----------------------------------------------------------------------
actor A: Actor {} // ok
class C: Actor, UnsafeSendable {
// expected-error@-1{{non-actor type 'C' cannot conform to the 'Actor' protocol}} {{1-6=actor}}
// expected-warning@-2{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
struct S: Actor {
// expected-error@-1{{non-class type 'S' cannot conform to class protocol 'AnyActor'}}
// expected-error@-2{{non-class type 'S' cannot conform to class protocol 'Actor'}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
struct E: Actor {
// expected-error@-1{{non-class type 'E' cannot conform to class protocol 'AnyActor'}}
// expected-error@-2{{non-class type 'E' cannot conform to class protocol 'Actor'}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
// ==== -----------------------------------------------------------------------
distributed actor DA: DistributedActor {
typealias ActorSystem = FakeActorSystem
}
// FIXME(distributed): error reporting is a bit whacky here; needs cleanup
// expected-error@+2{{actor type 'A2' cannot conform to the 'DistributedActor' protocol. Isolation rules of these actor types are not interchangeable.}}
// expected-error@+1{{actor type 'A2' cannot conform to the 'DistributedActor' protocol. Isolation rules of these actor types are not interchangeable.}}
actor A2: DistributedActor {
nonisolated var id: ID {
fatalError()
}
nonisolated var actorSystem: ActorSystem {
fatalError()
}
init(system: FakeActorSystem) {
fatalError()
}
static func resolve(id: ID, using system: FakeActorSystem) throws -> Self {
fatalError()
}
}
// expected-error@+1{{non-distributed actor type 'C2' cannot conform to the 'DistributedActor' protocol}}
final class C2: DistributedActor {
nonisolated var id: ID {
fatalError()
}
nonisolated var actorSystem: ActorSystem {
fatalError()
}
required init(system: FakeActorSystem) {
fatalError()
}
static func resolve(id: ID, using system: FakeActorSystem) throws -> Self {
fatalError()
}
}
struct S2: DistributedActor {
// expected-error@-1{{non-class type 'S2' cannot conform to class protocol 'DistributedActor'}}
// expected-error@-2{{non-class type 'S2' cannot conform to class protocol 'AnyActor'}}
// expected-error@-3{{type 'S2' does not conform to protocol 'Identifiable'}}
}
| 34.224719 | 219 | 0.69304 |
33fa41ee0ba9fc3df1a9037a13aac50f9f78c4fc | 533 | // RUN: %swift -target x86_64-apple-ios9 %S/objc_properties.swift -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NEW %S/objc_properties.swift
// RUN: %swift -target x86_64-apple-ios8 %S/objc_properties.swift -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-OLD %S/objc_properties.swift
// REQUIRES: OS=ios
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
| 76.142857 | 230 | 0.780488 |
9101fba94230d3bb9acc6f8e0b36eaea8d447a8d | 1,067 | //
// UICollectionView + ViewAnimator.swift
// ViewAnimator
//
// Created by Marcos Griselli on 15/04/2018.
//
import Foundation
import UIKit
public extension UICollectionView {
/// Checks for the IndexPath of a UICollectionView cell.
///
/// - Parameter cell: Cell to check it's path.
/// - Returns: Item position.
private func indexPathFor(cell: UICollectionViewCell) -> Int {
return indexPath(for: cell)?.item ?? -1
}
/// VisibleCells in the order they are displayed on screen.
var orderedVisibleCells: [UICollectionViewCell] {
let items = visibleCells
return items.sorted(by: { indexPathFor(cell: $1) > indexPathFor(cell: $0) })
}
/// Gets the currently visibleCells of a section.
///
/// - Parameter section: The section to filter the cells.
/// - Returns: Array of visible UICollectionViewCells in the argument section.
func visibleCells(in section: Int) -> [UICollectionViewCell] {
return visibleCells.filter { indexPath(for: $0)?.section == section }
}
}
| 30.485714 | 84 | 0.66448 |
bbba5e50d9b73bc8987961a0ec6cda2c66498315 | 1,403 | //
// PlayerViewController.swift
// MyNetflix
//
// Created by 조영우 on 2021/04/29.
//
import UIKit
import AVFoundation
class PlayerViewController: UIViewController {
@IBOutlet weak var playerView: PlayerView!
@IBOutlet weak var controlView: UIView!
@IBOutlet weak var playButton: UIButton!
let player = AVPlayer()
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .landscapeRight
}
override func viewDidLoad() {
super.viewDidLoad()
playerView.player = player
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.play()
}
@IBAction func togglePlayButton(_ sender: Any) {
if player.isPlaying {
pause()
} else {
play()
}
}
func play() {
player.play()
playButton.isSelected = true
}
func pause() {
player.pause()
playButton.isSelected = false
}
func reset() {
pause()
player.replaceCurrentItem(with: nil)
}
@IBAction func close(_ sender: Any) {
reset()
dismiss(animated: false, completion: nil)
}
}
extension AVPlayer {
var isPlaying: Bool {
guard self.currentItem != nil else {
return false
}
return self.rate != 0
}
}
| 20.333333 | 77 | 0.581611 |
e5ca538fd20be44efd10f1a259969b3a142d506f | 3,396 | //
// SupportVC.swift
// SSS Freshman App
//
// Created by James McCarthy on 8/15/16.
// Copyright © 2016 Digital Catnip. All rights reserved.
//
import UIKit
class SupportVC: UIViewController {
@IBOutlet var literacyButton:UIButton?
@IBOutlet var academicButton:UIButton?
@IBOutlet var eventsButton:UIButton?
@IBOutlet var johnButton:UIButton?
@IBOutlet var joyceButton:UIButton?
override func viewDidLoad() {
super.viewDidLoad()
setupButton(literacyButton)
setupButton(academicButton)
setupButton(eventsButton)
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBar.tintColor = UIColor.init(red: 10/255, green: 68/255, blue: 126/255, alpha: 1.0)
}
override func viewDidAppear(animated: Bool) {
registerScreen("Financial Literacy Screen")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "academicSegue"
{
if let destinationVC = segue.destinationViewController as? WebViewVC {
destinationVC.webAddress = "https://drive.google.com/file/d/0B35gGagDNpQBUVdMSy1HTTF0WWM/view?usp=sharing"
destinationVC.titleString = "Academic Services"
registerButtonAction("SSS Webpage", action: "View Page", label: "Academic Services")
}
}
else if segue.identifier == "financialSegue"
{
if let destinationVC = segue.destinationViewController as? WebViewVC {
destinationVC.webAddress = "https://drive.google.com/file/d/0B35gGagDNpQBTDFEc0JJU2dmWFE/view?usp=sharing"
destinationVC.titleString = "Financial Counseling"
registerButtonAction("SSS Webpage", action: "View Page", label: "Financial Counseling")
}
}
else if segue.identifier == "culturalSegue"
{
if let destinationVC = segue.destinationViewController as? WebViewVC {
destinationVC.webAddress = "http://www.pace.edu/dyson/centers/center-for-undergraduate-research-experiences/student-support-services#socialandculturalevents"
destinationVC.titleString = "Cultural Events"
registerButtonAction("SSS Webpage", action: "View Page", label: "Cultural Events")
}
}
}
func setupButton(button: UIButton?) {
button?.titleLabel?.numberOfLines = 1;
button?.titleLabel?.adjustsFontSizeToFitWidth = true;
button?.titleLabel?.lineBreakMode = NSLineBreakMode.ByClipping;
}
func setBorderRadius(button: UIButton?) {
if button != nil {
let width = button!.frame.width
button!.clipsToBounds = true
button!.layer.cornerRadius = width / 2.0;
}
}
@IBAction func emailJohn() {
registerButtonAction("Support", action: "Send Email", label: "Jonathan Hooker")
EmailAction.emailSomeone("[email protected]", message: "Hello Mr. Hooker,", subject: "From an SSS app user", presenter: self);
}
@IBAction func emailJoyce() {
registerButtonAction("Support", action: "Send Email", label: "Joyce Lau")
EmailAction.emailSomeone("[email protected]", message: "Hello Ms. Lau,", subject: "From an SSS app user", presenter: self)
}
}
| 39.034483 | 173 | 0.648115 |
5deeb7551f8c1e6a68b3565997c87b718d56b3d0 | 1,335 | //
// Bot.swift
// SwiftyBot
//
// The MIT License (MIT)
//
// Copyright (c) 2016 - 2019 Fabrizio Brancati.
//
// 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 Vapor
/// Google Assistant secret.
public let assistantSecret = Environment.get("ASSISTANT_SECRET") ?? ""
| 41.71875 | 82 | 0.745318 |
7af60d5822c447f4936ca0fdfe854a8fb5996b0f | 640 | //
// CacheControlMiddleware.swift
// App
//
// Created by Will McGinty on 5/2/18.
//
import Foundation
import Vapor
class CacheControlMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
return try next.respond(to: request).map { response in
//TODO: Figure out a more appropriate max-age based on resource path.
response.http.headers.add(name: .cacheControl, value: "public, max-age=600")
response.http.headers.add(name: .vary, value: "Accept-Encoding")
return response
}
}
}
| 27.826087 | 103 | 0.65 |
2f325d7b8c41ce2c2776b8985ce82798c3f26b36 | 2,776 | //
// Ratio.swift
// HealthSoftware
//
// Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/Ratio)
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
A ratio of two Quantity values - a numerator and a denominator.
A relationship of two Quantity values - expressed as a numerator and a denominator.
*/
open class Ratio: Element {
/// Numerator value
public var numerator: Quantity?
/// Denominator value
public var denominator: Quantity?
/// Designated initializer taking all required properties
override public init() {
super.init()
}
/// Convenience initializer
public convenience init(
denominator: Quantity? = nil,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
numerator: Quantity? = nil)
{
self.init()
self.denominator = denominator
self.`extension` = `extension`
self.id = id
self.numerator = numerator
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case denominator
case numerator
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.denominator = try Quantity(from: _container, forKeyIfPresent: .denominator)
self.numerator = try Quantity(from: _container, forKeyIfPresent: .numerator)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try denominator?.encode(on: &_container, forKey: .denominator)
try numerator?.encode(on: &_container, forKey: .numerator)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? Ratio else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return denominator == _other.denominator
&& numerator == _other.numerator
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(denominator)
hasher.combine(numerator)
}
}
| 27.76 | 88 | 0.712536 |
0ad6669b71d6469220208f51eca490d352f02234 | 843 | import XCTest
import RxSwiftPlus
import RxSwift
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
func testTemp(){
let subject = BehaviorSubject(value: 0)
}
}
| 24.794118 | 111 | 0.600237 |
4ba78fea6afe26f6c8e7d73e4696eabf03925bcb | 5,172 | //
// MockFunc.swift
// Wing
//
// Created by Tom Wilkinson on 5/11/16.
//
import Foundation
public struct MockFuncCall<Parameter, Return> {
var parameters: Parameter
var returned: Return
let actionTime: NSDate = NSDate()
}
class MockFunc<Parameter, Return>: MockableFunc, MockableFuncWithType {
typealias P = Parameter
typealias R = Return
var behavior: MockFuncBehavior<Parameter, Return>
var trackedCalls: [MockFuncCall<Parameter, Return>] = []
var callCount: Int {
return trackedCalls.count
}
/**
Creates a new MockFunc
- parameter parameterType: List in an unnamed tuple, for example: `(Int, String, Bool).self`
- parameter returnType: Return type for example: `Int.self`
- parameter behavior:
- returns:
*/
init(
parameterType: Parameter.Type, returnType: Return.Type,
behavior: MockFuncBehavior<Parameter, Return>? = nil)
{
self.behavior = behavior ?? MockFuncBehavior.defaultBehavor
}
/**
Performs the proper behavior given the super func and parameters
- parameter superFunc:
- parameter parameters:
- returns: Return
*/
func mockFunc(superFunc: Parameter throws -> Return, parameters: Parameter) rethrows -> Return {
let returned = try performBehavior(behavior, superFunc: superFunc, parameters: parameters)
trackCalls(behavior, parameters: parameters, returned: returned)
return returned
}
/**
Performs the proper behavior given the super func and parameters, and also possibly throws
- parameter superFunc:
- parameter parameters:
- returns: Return
*/
func mockThrowingFunc(superFunc: Parameter throws -> Return, parameters: Parameter) throws -> Return {
let returned: Return
switch behavior {
case .Throws(let stub):
returned = try stub(parameters)
default:
returned = try performBehavior(behavior, superFunc: superFunc, parameters: parameters)
}
trackCalls(behavior, parameters: parameters, returned: returned)
return returned
}
/**
Updates the call counter, if recording is on
- parameter behavior:
- parameter parameters
*/
private func trackCalls(behavior: MockFuncBehavior<Parameter, Return>, parameters: Parameter, returned: Return) {
switch behavior {
case .Repeats(let behavior, let times, let then):
if times > 0 {
trackCalls(behavior, parameters: parameters, returned: returned)
} else {
trackCalls(then, parameters: parameters, returned: returned)
}
case .Returns(_), .Spies, .SpiesAnd(_), .Stubs(_), .Throws(_):
trackedCalls.append(MockFuncCall(parameters: parameters, returned: returned))
default: break
}
}
/**
Perform behavior (possibly recursively)
- parameter behavior:
- parameter superFunc:
- parameter parameters:
- returns: Return
*/
private func performBehavior(
behavior: MockFuncBehavior<P, R>, superFunc: Parameter throws -> Return,
parameters: Parameter) rethrows -> R
{
switch behavior {
case .Repeats(let repeatBehavior, let times, let then):
if times > 0 {
self.behavior = MockFuncBehavior<P, R>.Repeats(behavior: repeatBehavior, times: times - 1, then: then)
return try performBehavior(repeatBehavior, superFunc: superFunc, parameters: parameters)
} else {
self.behavior = then
return try performBehavior(then, superFunc: superFunc, parameters: parameters)
}
case .SpiesAnd(let preProcess, let postProcess):
var parameters = parameters
if let preProcess = preProcess {
parameters = preProcess(parameters)
}
var returnValue = try superFunc(parameters)
if let postProcess = postProcess {
returnValue = postProcess(returnValue)
}
return returnValue
case .StopsTracking, .Spies, .Throws(_):
return try superFunc(parameters)
case .Stubs(let stub):
return stub(parameters)
case .Returns(let value):
return value
}
}
deinit {
// In case our behavior stores a reference to self
behavior = .Spies
}
}
extension MockableFuncWithType where Self.P == Void {
/**
Performs the proper behavior given the super func and parameters
- parameter superFunc:
- parameter parameters:
- returns: Return
*/
func mockFunc(superFunc: Void throws -> R) rethrows -> R {
return try mockFunc(superFunc, parameters: ())
}
/**
Performs the proper behavior given the super func and parameters, and also possibly throws
- parameter superFunc:
- parameter parameters:
- returns: Return
*/
func mockThrowingFunc(superFunc: Void throws -> R) throws -> R {
return try mockThrowingFunc(superFunc, parameters: ())
}
}
| 31.925926 | 118 | 0.62819 |
ffe8302a2a26c0064361fd8e074d8237020443a2 | 2,307 | //
// AppDelegate.swift
// Impact
//
// Created by Gonzalo Gonzalez on 9/14/19.
// Copyright © 2019 Gonzalo Gonzalez. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = LoginViewController()
window?.makeKeyAndVisible()
FirebaseApp.configure()
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.14 | 285 | 0.751192 |
d79fdfd99639f03b991fc5f9229ce6b5aceada28 | 1,242 | //
// AddressDetail.swift
// ios-shoppe-demo
//
// Created on 4/10/20.
// Copyright © 2020 FullStory All rights reserved.
//
import Foundation
enum AddressDetail {
case name, street, unit, city, state, zip, phone, email
var placeHolder: String {
switch self {
case .name:
return "Name"
case .street:
return "Street address or P.O.Box"
case .unit:
return "Apt, Suit, Unit, Building (optional)"
case .city:
return "City"
case .state:
return "State/Province/Region"
case .zip:
return "ZIP"
case .email:
return "Email"
case .phone:
return "Phone"
}
}
var template: String {
switch self {
case .name:
return "John Doe"
case .street:
return "1110 Downing Street"
case .unit:
return "Apt, Suit, Unit, Building (optional)"
case .city:
return "London"
case .state:
return "GG"
case .zip:
return "8966"
case .phone:
return "115-551-1555"
case .email:
return "Email"
}
}
}
| 22.178571 | 59 | 0.491948 |
fb3ad55e54a61ca50e53049136313fdef9df581a | 2,441 | //
// HomeViewController.swift
// Instagram
//
// Created by Thomas Clifford on 3/6/16.
// Copyright © 2016 Thomas Clifford. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var query = PFQuery(className: "Post")
var dictionary: [PFObject]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 300;
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let dictionary = dictionary {
return dictionary.count
}
else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("homeCell", forIndexPath: indexPath) as! HomeTableViewCell
cell.captionView.text = dictionary![indexPath.row]["caption"] as? String
cell.pictureView.file = dictionary![indexPath.row]["media"] as? PFFile
cell.pictureView.loadInBackground()
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
query.orderByDescending("createdAt")
query.includeKey("author")
query.limit = 20
query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
if let posts = posts {
self.dictionary = posts
self.tableView.reloadData()
} else {
print(error?.localizedDescription)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 30.135802 | 121 | 0.645637 |
118b1b274deddc5177ff94d829f0d6b61fb8a92e | 249 | //
// Quizzes.swift
// Quizzes
//
// Created by Joshua Viera on 2/1/19.
// Copyright © 2019 Alex Paul. All rights reserved.
//
import Foundation
struct Quizzes : Codable {
let id: String
let quizTitle: String
let facts: [String]
}
| 15.5625 | 52 | 0.650602 |
db080256b6d54fcac2eba34f9e14210f392c6b1f | 2,331 |
/// Applies a value transformation to an immutable setter function.
///
/// - Parameters:
/// - setter: An immutable setter function.
/// - f: A value transform function.
/// - Returns: A root transform function.
public func over<S, T, A, B>(
_ setter: (@escaping (A) -> B) -> (S) -> T,
_ f: @escaping (A) -> B
)
-> (S) -> T {
return setter(f)
}
/// Applies a value to an immutable setter function.
///
/// - Parameters:
/// - setter: An immutable setter function.
/// - value: A new value.
/// - Returns: A root transform function.
public func set<S, T, A, B>(
_ setter: (@escaping (A) -> B) -> (S) -> T,
_ value: B
)
-> (S) -> T {
return over(setter) { _ in value }
}
// MARK: - Mutation
/// Applies a mutable value transformation to a mutable setter function.
///
/// - Parameters:
/// - setter: A mutable setter function.
/// - f: A mutable value transform function.
/// - Returns: A mutable root transform function.
public func mver<S, A>(
_ setter: (@escaping (inout A) -> Void) -> (inout S) -> Void,
_ f: @escaping (inout A) -> Void
)
-> (inout S) -> Void {
return setter(f)
}
/// Applies a mutable value transformation to a reference-mutable setter function.
///
/// - Parameters:
/// - setter: A reference-mutable setter function.
/// - f: A mutable value transform function.
/// - Returns: A reference-mutable root transform function.
public func mver<S: AnyObject, A>(
_ setter: (@escaping (inout A) -> Void) -> (S) -> Void,
_ f: @escaping (inout A) -> Void
)
-> (S) -> Void {
return setter(f)
}
/// Applies a value to a mutable setter function.
///
/// - Parameters:
/// - setter: An mutable setter function.
/// - value: A new value.
/// - Returns: A mutable root transform function.
public func mut<S, A>(
_ setter: (@escaping (inout A) -> Void) -> (inout S) -> Void,
_ value: A
)
-> (inout S) -> Void {
return mver(setter) { $0 = value }
}
/// Applies a value to a reference-mutable setter function.
///
/// - Parameters:
/// - setter: An mutable setter function.
/// - value: A new value.
/// - Returns: A reference-mutable root transform function.
public func mut<S: AnyObject, A>(
_ setter: (@escaping (inout A) -> Void) -> (S) -> Void,
_ value: A
)
-> (S) -> Void {
return mver(setter) { $0 = value }
}
| 25.064516 | 82 | 0.602317 |
ccbe8329455635f0c06d96f405e83156e12b2eda | 2,363 | // autogenerated
// swiftlint:disable all
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
extension V1.AppPreviewSets {
public struct POST: Endpoint {
public typealias Parameters = AppPreviewSetCreateRequest
public typealias Response = AppPreviewSetResponse
public var path: String {
"/v1/appPreviewSets"
}
/// AppPreviewSet representation
public var parameters: Parameters
public init(parameters: Parameters) {
self.parameters = parameters
}
public func request(with baseURL: URL) throws -> URLRequest? {
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
components?.path = path
var urlRequest = components?.url.map { URLRequest(url: $0) }
urlRequest?.httpMethod = "POST"
var jsonEncoder: JSONEncoder {
let encoder = JSONEncoder()
return encoder
}
urlRequest?.httpBody = try jsonEncoder.encode(parameters)
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
return urlRequest
}
/// - Returns: **201**, Single AppPreviewSet as `AppPreviewSetResponse`
/// - Throws: **400**, Parameter error(s) as `ErrorResponse`
/// - Throws: **403**, Forbidden error as `ErrorResponse`
/// - Throws: **409**, Request entity error(s) as `ErrorResponse`
public static func response(from data: Data, urlResponse: HTTPURLResponse) throws -> Response {
var jsonDecoder: JSONDecoder {
let decoder = JSONDecoder()
return decoder
}
switch urlResponse.statusCode {
case 201:
return try jsonDecoder.decode(AppPreviewSetResponse.self, from: data)
case 400:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 403:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
case 409:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
default:
throw try jsonDecoder.decode(ErrorResponse.self, from: data)
}
}
}
}
// swiftlint:enable all
| 32.369863 | 103 | 0.603047 |
bf2c6e1edb1abcc55304ae0a4197f19499dce05d | 1,613 | //
// SegmentedControlCell.swift
// Yelp
//
// Created by Zekun Wang on 10/23/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
class SegmentedControlCell: UITableViewCell {
@IBOutlet var segmentedControl: UISegmentedControl!
let blue = UIColor(red:0, green:0.48, blue:1, alpha:1.0)
var option: Option! {
didSet {
if option == nil {
return
}
segmentedControl.selectedSegmentIndex = option.selected ? 1 : 0
setTintColor()
}
}
func setTintColor() {
if option.selected {
segmentedControl.subviews[1].tintColor = UIColor.lightGray
segmentedControl.subviews[0].tintColor = blue
} else {
segmentedControl.subviews[1].tintColor = blue
segmentedControl.subviews[0].tintColor = UIColor.lightGray
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let attr = NSDictionary(object: UIFont(name: "HelveticaNeue", size: 15.0)!, forKey: NSFontAttributeName as NSCopying)
segmentedControl.setTitleTextAttributes(attr as [NSObject : AnyObject], for: .normal)
}
@IBAction func onSegmentedControlChanged(_ sender: AnyObject) {
option.selected = segmentedControl.selectedSegmentIndex == 1
setTintColor()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 28.298246 | 125 | 0.621203 |
e08b1a8ec5d61f81f76e5104e28c17db93f6ba35 | 3,423 | //
// ChatControllerDocuments.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 10/08/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SimpleImageViewer
import FLAnimatedImage
// MARK: UIDocumentInteractionControllerDelegate
extension ChatViewController: UIDocumentInteractionControllerDelegate {
public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
// MARK: Open Attachments
extension ChatViewController {
func openDocument(attachment: Attachment) {
guard let fileURL = attachment.fullFileURL() else { return }
guard let filename = DownloadManager.filenameFor(attachment.titleLink) else { return }
guard let localFileURL = DownloadManager.localFileURLFor(filename) else { return }
// Open document itself
func open() {
documentController = UIDocumentInteractionController(url: localFileURL)
documentController?.delegate = self
documentController?.presentPreview(animated: true)
}
// Checks if we do have the file in the system, before downloading it
if DownloadManager.fileExists(localFileURL) {
open()
} else {
showHeaderStatusView()
let message = String(format: localized("chat.download.downloading_file"), filename)
chatHeaderViewStatus?.labelTitle.text = message
chatHeaderViewStatus?.buttonRefresh.isHidden = true
chatHeaderViewStatus?.backgroundColor = .RCLightGray()
chatHeaderViewStatus?.setTextColor(.RCDarkBlue())
chatHeaderViewStatus?.activityIndicator.startAnimating()
// Download file and cache it to be used later
DownloadManager.download(url: fileURL, to: localFileURL) {
DispatchQueue.main.async {
self.hideHeaderStatusView()
open()
}
}
}
}
func openImage(attachment: Attachment) {
guard let fileURL = attachment.fullFileURL() else { return }
guard let filename = DownloadManager.filenameFor(attachment.titleLink) else { return }
guard let localFileURL = DownloadManager.localFileURLFor(filename) else { return }
func open() {
let configuration = ImageViewerConfiguration { config in
if let data = try? Data(contentsOf: localFileURL),
let contentType = data.imageContentType {
if contentType == .gif {
config.animatedImage = FLAnimatedImage(gifData: data)
} else {
config.image = UIImage(data: data)
}
}
}
present(ImageViewerController(configuration: configuration), animated: false)
}
// Checks if we do have the file in the system, before downloading it
if DownloadManager.fileExists(localFileURL) {
open()
} else {
// Download file and cache it to be used later
DownloadManager.download(url: fileURL, to: localFileURL) {
DispatchQueue.main.async {
self.hideHeaderStatusView()
open()
}
}
}
}
}
| 36.031579 | 138 | 0.621677 |
bf426f3e7f45f8d2d57526a64b9cca317b08bfbf | 209 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let g = {
if true {
init {
class
case ,
| 20.9 | 87 | 0.736842 |
717da420b93c79fd56e31cddfb048fac13450045 | 2,496 | //
// ProfileViewController.swift
// Quizzes
//
// Created by Jason on 2/1/19.
// Copyright © 2019 Alex Paul. All rights reserved.
//
import UIKit
protocol Userprofile {
func user(name: String)
}
class ProfileViewController: UIViewController {
var image = UIImagePickerController()
var user: Userprofile?
var profileSetUp = ProfileViewSetup()
var texts = "kjnln"
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(profileSetUp)
profileSetUp.profileButton.addTarget(self, action: #selector(profile), for: .touchUpInside)
profileSetUp.photoButton.addTarget(self, action: #selector(showImageSelect), for: .touchUpInside)
profileSetUp.photoButton.layer.cornerRadius = profileSetUp.photoButton.bounds.width/2.0
image.delegate = self
}
@objc func showImageSelect (){
present(image, animated: true, completion: nil)
}
@objc func profile(test: UITextField){
let alert = UIAlertController(title: "Enter User Name", message: "", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = ""
}
// alert.addAction(UIAlertAction.init(title: "cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert!.textFields![0] // Force unwrapping because we know it exists.
let test = textField.text!
UserDefaults.standard.set(test, forKey: UserSavedDefaultName.userDefault)
print(test)
self.profileSetUp.profileButton.setTitle(textField.text, for: .normal)
}))
self.present(alert, animated: true)
//
}
}
extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
profileSetUp.photoButton.setImage(image, for: .normal)
}
else{
print("original Image is nil")
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
| 32.842105 | 144 | 0.65625 |
1cc61cb4935ecb2ac2b3220870c7eaec2fa13618 | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let : (n: String
class A {
{
}
protocol c : c {
func c
| 20.363636 | 87 | 0.723214 |
39dc5d4eabca18c8af6b0972df3506d0c5c78421 | 10,442 | //
// SharingGroupRepository.swift
// Server
//
// Created by Christopher G Prince on 6/23/18.
//
// A sharing group is a group of users who are sharing a collection of files.
import Foundation
import LoggerAPI
import SyncServerShared
class SharingGroup : NSObject, Model {
static let sharingGroupUUIDKey = "sharingGroupUUID"
var sharingGroupUUID: String!
static let sharingGroupNameKey = "sharingGroupName"
var sharingGroupName: String!
static let deletedKey = "deleted"
var deleted:Bool!
// Not a part of this table, but a convenience for doing joins with the MasterVersion table.
static let masterVersionKey = "masterVersion"
var masterVersion: MasterVersionInt!
// Similarly, not part of this table. For doing joins.
public static let permissionKey = "permission"
public var permission:Permission?
// Also not part of this table. For doing fetches of sharing group users for the sharing group.
public var sharingGroupUsers:[SyncServerShared.SharingGroupUser]!
static let accountTypeKey = "accountType"
var accountType: String!
static let owningUserIdKey = "owningUserId"
var owningUserId:UserId?
subscript(key:String) -> Any? {
set {
switch key {
case SharingGroup.sharingGroupUUIDKey:
sharingGroupUUID = newValue as! String?
case SharingGroup.sharingGroupNameKey:
sharingGroupName = newValue as! String?
case SharingGroup.deletedKey:
deleted = newValue as! Bool?
case SharingGroup.masterVersionKey:
masterVersion = newValue as! MasterVersionInt?
case SharingGroup.permissionKey:
permission = newValue as! Permission?
case SharingGroup.accountTypeKey:
accountType = newValue as! String?
case SharingGroup.owningUserIdKey:
owningUserId = newValue as! UserId?
default:
assert(false)
}
}
get {
return getValue(forKey: key)
}
}
override init() {
super.init()
}
func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? {
switch propertyName {
case SharingGroup.deletedKey:
return {(x:Any) -> Any? in
return (x as! Int8) == 1
}
case SharingGroupUser.permissionKey:
return {(x:Any) -> Any? in
return Permission(rawValue: x as! String)
}
default:
return nil
}
}
func toClient() -> SyncServerShared.SharingGroup {
let clientGroup = SyncServerShared.SharingGroup()
clientGroup.sharingGroupUUID = sharingGroupUUID
clientGroup.sharingGroupName = sharingGroupName
clientGroup.deleted = deleted
clientGroup.masterVersion = masterVersion
clientGroup.permission = permission
clientGroup.sharingGroupUsers = sharingGroupUsers
Log.debug("accountType: \(String(describing: accountType)) (expected to be nil for an owning user)")
if let accountType = accountType {
clientGroup.cloudStorageType = AccountScheme(.accountName(accountType))?.cloudStorageType
}
return clientGroup
}
}
class SharingGroupRepository: Repository, RepositoryLookup {
private(set) var db:Database!
required init(_ db:Database) {
self.db = db
}
var tableName:String {
return SharingGroupRepository.tableName
}
static var tableName:String {
return "SharingGroup"
}
func upcreate() -> Database.TableUpcreateResult {
let createColumns =
"(sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " +
// A name for the sharing group-- assigned by the client app.
"sharingGroupName VARCHAR(\(Database.maxSharingGroupNameLength)), " +
// true iff sharing group has been deleted. Like file references in the FileIndex, I'm never going to actually delete sharing groups.
"deleted BOOL NOT NULL, " +
"UNIQUE (sharingGroupUUID))"
let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns)
return result
}
enum LookupKey : CustomStringConvertible {
case sharingGroupUUID(String)
var description : String {
switch self {
case .sharingGroupUUID(let sharingGroupUUID):
return "sharingGroupUUID(\(sharingGroupUUID))"
}
}
}
func lookupConstraint(key:LookupKey) -> String {
switch key {
case .sharingGroupUUID(let sharingGroupUUID):
return "sharingGroupUUID = '\(sharingGroupUUID)'"
}
}
enum AddResult {
case success
case error(String)
}
func add(sharingGroupUUID:String, sharingGroupName: String? = nil) -> AddResult {
let insert = Database.PreparedStatement(repo: self, type: .insert)
insert.add(fieldName: SharingGroup.sharingGroupUUIDKey, value: .string(sharingGroupUUID))
insert.add(fieldName: SharingGroup.deletedKey, value: .bool(false))
if let sharingGroupName = sharingGroupName {
insert.add(fieldName: SharingGroup.sharingGroupNameKey, value: .string(sharingGroupName))
}
do {
try insert.run()
Log.info("Sucessfully created sharing group")
return .success
}
catch (let error) {
Log.error("Could not insert into \(tableName): \(error)")
return .error("\(error)")
}
}
func sharingGroups(forUserId userId: UserId, sharingGroupUserRepo: SharingGroupUserRepository, userRepo: UserRepository) -> [SharingGroup]? {
let masterVersionTableName = MasterVersionRepository.tableName
let sharingGroupUserTableName = SharingGroupUserRepository.tableName
let query = "select \(tableName).sharingGroupUUID, \(tableName).sharingGroupName, \(tableName).deleted, \(masterVersionTableName).masterVersion, \(sharingGroupUserTableName).permission, \(sharingGroupUserTableName).owningUserId FROM \(tableName),\(sharingGroupUserTableName), \(masterVersionTableName) WHERE \(sharingGroupUserTableName).userId = \(userId) AND \(sharingGroupUserTableName).sharingGroupUUID = \(tableName).sharingGroupUUID AND \(tableName).sharingGroupUUID = \(masterVersionTableName).sharingGroupUUID"
// The "owners" or "parents" of the sharing groups the sharing user is in
guard let owningUsers = userRepo.getOwningSharingGroupUsers(forSharingUserId: userId) else {
Log.error("Failed calling getOwningSharingGroupUsers")
return nil
}
guard let sharingGroups = self.sharingGroups(forSelectQuery: query, sharingGroupUserRepo: sharingGroupUserRepo) else {
Log.error("Failed calling sharingGroups")
return nil
}
// Now, get the accountTypes of the "owning" or "parent" users for each sharing group, for sharing users. This will be used downstream to determine the cloud sharing type of each sharing group for the sharing user.
for sharingGroup in sharingGroups {
let owningUser = owningUsers.filter {sharingGroup.owningUserId != nil && $0.userId == sharingGroup.owningUserId}
if owningUser.count == 1 {
sharingGroup.accountType = owningUser[0].accountType
}
}
return sharingGroups
}
private func sharingGroups(forSelectQuery selectQuery: String, sharingGroupUserRepo: SharingGroupUserRepository) -> [SharingGroup]? {
guard let select = Select(db:db, query: selectQuery, modelInit: SharingGroup.init, ignoreErrors:false) else {
return nil
}
var result = [SharingGroup]()
var errorGettingSgus = false
select.forEachRow { rowModel in
let sharingGroup = rowModel as! SharingGroup
if let sgus:[SyncServerShared.SharingGroupUser] = sharingGroupUserRepo.sharingGroupUsers(forSharingGroupUUID: sharingGroup.sharingGroupUUID) {
sharingGroup.sharingGroupUsers = sgus
}
else {
errorGettingSgus = true
return
}
result.append(sharingGroup)
}
if !errorGettingSgus && select.forEachRowStatus == nil {
return result
}
else {
return nil
}
}
enum MarkDeletionCriteria {
case sharingGroupUUID(String)
func toString() -> String {
switch self {
case .sharingGroupUUID(let sharingGroupUUID):
return "\(SharingGroup.sharingGroupUUIDKey)='\(sharingGroupUUID)'"
}
}
}
func markAsDeleted(forCriteria criteria: MarkDeletionCriteria) -> Int64? {
let query = "UPDATE \(tableName) SET \(SharingGroup.deletedKey)=1 WHERE " + criteria.toString()
if db.query(statement: query) {
return db.numberAffectedRows()
}
else {
let error = db.error
Log.error("Could not mark files as deleted in \(tableName): \(error)")
return nil
}
}
func update(sharingGroup: SharingGroup) -> Bool {
let update = Database.PreparedStatement(repo: self, type: .update)
guard let sharingGroupUUID = sharingGroup.sharingGroupUUID,
let sharingGroupName = sharingGroup.sharingGroupName else {
return false
}
update.add(fieldName: SharingGroup.sharingGroupNameKey, value: .string(sharingGroupName))
update.where(fieldName: SharingGroup.sharingGroupUUIDKey, value: .string(sharingGroupUUID))
do {
try update.run()
}
catch (let error) {
Log.error("Failed updating sharing group: \(error)")
return false
}
return true
}
}
| 35.638225 | 525 | 0.61674 |
de6bea2602321c94c0a6fe3ee2ec82d9fc91671b | 691 | //
// OnBoundsLayout.swift
// moVimento
//
// Created by Giuseppe Lanza on 11/09/2019.
// Copyright © 2019 MERLin Tech. All rights reserved.
//
import UIKit
public class OnBoundsChangedInvalidatedLayout: UICollectionViewFlowLayout {
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return collectionView?.bounds.size != newBounds.size
}
public override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = UICollectionViewFlowLayoutInvalidationContext()
context.invalidateFlowLayoutDelegateMetrics = true
return context
}
}
| 31.409091 | 126 | 0.751085 |
67bf59790657154ef4c283d3233e44e176ce8825 | 824 | import UIKit
class ViewController: UIViewController, CoordinatorNavigationControllerDelegate {
override open var prefersStatusBarHidden: Bool { false }
override open func viewDidLoad() {
super.viewDidLoad()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupCoordinatorNavigationController()
}
private func setupCoordinatorNavigationController() {
guard let navigationController = navigationController as? CoordinatorNavigationController else { return }
navigationController.coordinatorNavigationDelegate = self
}
func transitionBackDidFinish() {}
func customBackButtonDidTap() {}
func customCloseButtonDidTap() {}
open func updateLocalization() {}
open func refreshRequests() {}
}
| 29.428571 | 113 | 0.725728 |
09810e64dd28323ada6f0ad1a8e33bd4b03accf6 | 1,197 | //
// FctLiplisMsg.swift
// Liplis
//
// Created by sachin on 2015/04/18.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import Foundation
struct FctLiplisMsg {
internal static func createMsgMassageDlFaild()->MsgShortNews
{
let msg : MsgShortNews = MsgShortNews()
msg.nameList.append("データ")
msg.nameList.append("の");
msg.nameList.append("取得");
msg.nameList.append("に");
msg.nameList.append("失敗");
msg.nameList.append("し");
msg.nameList.append("まし");
msg.nameList.append("た。");
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.emotionList.append(1);
msg.pointList.append(-1);
msg.pointList.append(-1);
msg.pointList.append(-1);
msg.pointList.append(-1);
msg.pointList.append(-1);
msg.pointList.append(-1);
msg.pointList.append(-1);
msg.pointList.append(-1);
return msg;
}
} | 27.204545 | 64 | 0.568922 |
de37eaac741abfdcea0dc7a07d7bf2fbcd072d78 | 11,529 | //
// CurlyRecommendCell.swift
// martkurly
//
// Created by 천지운 on 2020/08/21.
// Copyright © 2020 Team3x3. All rights reserved.
//
import UIKit
protocol CurlyRecommendDelegate: class {
func tappedItem(selectedID: Int)
}
class CurlyRecommendCell: UICollectionViewCell {
// MARK: - Properties
static let identifier = "CurlyRecommendCell"
private let bannerHeightValue: CGFloat = 80
private let recommendTableView = UITableView()
var tappedMainEvent: ((Int) -> Void)?
var tappedBannerEvent: ((Int) -> Void)?
private var mainEventList = [MainEvent]()
private var recommendProducts = [Product]()
private var sqaureEvents = [EventSqaureModel]()
private var salesProducts = [Product]()
private var bannerEvent = [EventModel]()
private var healthProducts = [Product]()
private var mdRecommendProducts = [MDRecommendModel]()
// MARK: - LifeCycle
override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
configureTableView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Actions
func tappedBannerEvent(eventID: Int) {
tappedBannerEvent?(eventID)
}
// MARK: - Helpers
func configureUI() {
self.backgroundColor = .white
configureLayout()
}
func configureLayout() {
self.addSubview(recommendTableView)
recommendTableView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
func configureTableView() {
recommendTableView.backgroundColor = .white
recommendTableView.separatorStyle = .none
recommendTableView.allowsSelection = false
recommendTableView.dataSource = self
recommendTableView.delegate = self
recommendTableView.register(RecommendImageSliderCell.self,
forCellReuseIdentifier: RecommendImageSliderCell.identifier)
recommendTableView.register(MainProductListCell.self,
forCellReuseIdentifier: MainProductListCell.identifier)
recommendTableView.register(MainBannerViewCell.self,
forCellReuseIdentifier: MainBannerViewCell.identifier)
recommendTableView.register(MainMDRecommendCell.self,
forCellReuseIdentifier: MainMDRecommendCell.identifier)
recommendTableView.register(MainCurlyRecipeCell.self,
forCellReuseIdentifier: MainCurlyRecipeCell.identifier)
recommendTableView.register(MainCurlyInfomationCell.self,
forCellReuseIdentifier: MainCurlyInfomationCell.identifier)
}
func configure(mainEventList: [MainEvent],
recommendProducts: [Product],
salesProducts: [Product],
bannerEvent: [EventModel],
healthProducts: [Product],
sqaureEvents: [EventSqaureModel],
mdRecommendProducts: [MDRecommendModel]) {
self.mainEventList = mainEventList
self.recommendProducts = recommendProducts
self.sqaureEvents = sqaureEvents
self.salesProducts = salesProducts
self.bannerEvent = bannerEvent
self.healthProducts = healthProducts
self.mdRecommendProducts = mdRecommendProducts
self.recommendTableView.reloadData()
}
}
// MARK: - UITableViewDataSource
extension CurlyRecommendCell: UITableViewDataSource {
enum RecommendCellType: Int, CaseIterable {
case imageSlideCell
case productRecommendCell
case eventNewsCell
case frugalCell
case firstBannerCell
case mdRecommendCell
case secondBannerCell
case healthCell
// case hotProductsCell
// case deadlineSaleCell
// case immunityProductsCell
// case curlyRecipeCell
case deliveryInfoCell
case curlyInfomationCell
}
func numberOfSections(in tableView: UITableView) -> Int {
return RecommendCellType.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch RecommendCellType(rawValue: section)! {
case .curlyInfomationCell: return InfoCellType.allCases.count
default: return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch RecommendCellType(rawValue: indexPath.section)! {
case .imageSlideCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: RecommendImageSliderCell.identifier,
for: indexPath) as! RecommendImageSliderCell
cell.mainEventList = mainEventList
cell.delegate = self
return cell
case .productRecommendCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainProductListCell.identifier,
for: indexPath) as! MainProductListCell
cell.configure(directionType: .horizontal,
titleType: .none,
backgroundColor: .white,
titleText: "이 상품 어때요?")
cell.products = recommendProducts
return cell
case .eventNewsCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainProductListCell.identifier,
for: indexPath) as! MainProductListCell
cell.configure(directionType: .vertical,
titleType: .rightAllow,
backgroundColor: ColorManager.General.backGray.rawValue,
titleText: "이벤트 소식")
cell.sqaureEvents = sqaureEvents
return cell
case .frugalCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainProductListCell.identifier,
for: indexPath) as! MainProductListCell
cell.configure(directionType: .horizontal,
titleType: .rightAllow,
backgroundColor: .white,
titleText: "알뜰 상품")
cell.products = salesProducts
return cell
case .firstBannerCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainBannerViewCell.identifier,
for: indexPath) as! MainBannerViewCell
cell.eventModel = bannerEvent.count > 2 ? bannerEvent[0] : nil
cell.tappedBannerEvent = tappedBannerEvent(eventID:)
return cell
case .mdRecommendCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainMDRecommendCell.identifier,
for: indexPath) as! MainMDRecommendCell
cell.mdRecommendProducts = mdRecommendProducts
return cell
case .secondBannerCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainBannerViewCell.identifier,
for: indexPath) as! MainBannerViewCell
cell.eventModel = bannerEvent.count > 2 ? bannerEvent[1] : nil
cell.tappedBannerEvent = tappedBannerEvent(eventID:)
return cell
case .healthCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainProductListCell.identifier,
for: indexPath) as! MainProductListCell
cell.configure(directionType: .horizontal,
titleType: .rightAllowAndSubTitle,
backgroundColor: .white,
titleText: "건강 식품",
subTitleText: "컬리의 건강 식품들을 만나보세요")
cell.products = healthProducts
return cell
// case .hotProductsCell:
// let cell = tableView.dequeueReusableCell(
// withIdentifier: MainProductListCell.identifier,
// for: indexPath) as! MainProductListCell
// cell.configure(directionType: .horizontal,
// titleType: .rightAllow,
// backgroundColor: ColorManager.General.backGray.rawValue,
// titleText: "지금 가장 핫한 상품")
// return cell
// case .deadlineSaleCell:
// let cell = tableView.dequeueReusableCell(
// withIdentifier: MainProductListCell.identifier,
// for: indexPath) as! MainProductListCell
// cell.configure(directionType: .horizontal,
// titleType: .rightAllow,
// backgroundColor: .white,
// titleText: "마감세일")
// return cell
// case .immunityProductsCell:
// let cell = tableView.dequeueReusableCell(
// withIdentifier: MainProductListCell.identifier,
// for: indexPath) as! MainProductListCell
// cell.configure(directionType: .horizontal,
// titleType: .rightAllow,
// backgroundColor: .white,
// titleText: "면역력 증진",
// isTopPadding: false)
// return cell
// case .curlyRecipeCell:
// let cell = tableView.dequeueReusableCell(
// withIdentifier: MainCurlyRecipeCell.identifier,
// for: indexPath) as! MainCurlyRecipeCell
// return cell
case .deliveryInfoCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainBannerViewCell.identifier,
for: indexPath) as! MainBannerViewCell
cell.eventModel = bannerEvent.count > 2 ? bannerEvent[2] : nil
cell.tappedBannerEvent = tappedBannerEvent(eventID:)
return cell
case .curlyInfomationCell:
let cell = tableView.dequeueReusableCell(
withIdentifier: MainCurlyInfomationCell.identifier,
for: indexPath) as! MainCurlyInfomationCell
cell.configure(cellType: InfoCellType(rawValue: indexPath.row)!)
return cell
}
}
}
// MARK: - CurlyRecommendDelegate
extension CurlyRecommendCell: CurlyRecommendDelegate {
func tappedItem(selectedID: Int) {
tappedMainEvent?(selectedID)
}
}
// MARK: - UITableViewDelegate
extension CurlyRecommendCell: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch RecommendCellType(rawValue: indexPath.section)! {
case .imageSlideCell:
let screenWidth = UIScreen.main.bounds.width
return screenWidth * 0.92
case .firstBannerCell, .secondBannerCell, .deliveryInfoCell:
let width = UIScreen.main.bounds.width
return width * 0.22
case .curlyInfomationCell:
let cellType = InfoCellType(rawValue: indexPath.row)!
switch cellType.cellStyle {
case .basic, .lastHighlight, .centerHighlight: return 18
case .custom: return 68
default: return 20
}
default: return UITableView.automaticDimension
}
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 800
}
}
| 39.214286 | 103 | 0.610894 |
cce73329007b4d2c7a5b8b729ed841519d36e1ef | 322 | // RUN: not --crash %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
enum a
class b{var d:a{}
}func a{class a{enum a<d{struct S{struct Q<d{enum B{enum A{class b<f:f.
b
| 29.272727 | 87 | 0.726708 |
564d9ed698cac43a43d50a37a43d4c4e85881eea | 303 | //
// TransformationDelegate.swift
// VectorDisplayer
//
// Created by Jack Rosen on 4/20/19.
// Copyright © 2019 Jack Rosen. All rights reserved.
//
import Foundation
import UIKit
protocol TransformationDelegate: class {
// Perform a transformation
func perform(transform: CGAffineTransform)
}
| 18.9375 | 53 | 0.749175 |
fe7fcbc82d2e98e8cdc16fce009efbcbb463e560 | 916 | func hexToUiColor(hex: Any?) -> UIColor {
let defaultColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
guard var _hex = hex as? String else { return defaultColor }
let r, g, b, a: CGFloat
if _hex.hasPrefix("#") {
let start = _hex.index(_hex.startIndex, offsetBy: 1)
_hex = String(_hex[start...])
}
if _hex.count == 6 {
_hex = _hex + "ff"
}
if _hex.count != 8 {
return defaultColor
}
let scanner = Scanner(string: _hex)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
return UIColor(red: r, green: g, blue: b, alpha: a)
}
return defaultColor
} | 28.625 | 76 | 0.56441 |
14e33109a5fa70d7c470ba41fc9aee3848b124b8 | 1,960 | import SwiftUI
public struct StatePicker: View {
@EnvironmentObject var envi: CircuitEnvironment
public var body: some View {
GeometryReader { geo in
ZStack{
RoundedRectangle(cornerRadius: 8)
.fill(Color.blue.opacity(0.5))
.offset(x: envi.currentState == .design ? -88 : 0)
.offset(x: envi.currentState == .play ? 88 : 0)
.frame(width: 80, height: 40, alignment: .center)
HStack{
Button(action: {envi.currentState = .design} ) {
Text("DESIGN")
.fontWeight(.heavy)
}.buttonStyle(PickerButtonStyle())
Button(action: {envi.currentState = .setup} ) {
Text("SETUP")
.fontWeight(.heavy)
}.buttonStyle(PickerButtonStyle())
Button(action: {envi.solveCircuit()} ) {
Text("SOLVE")
.fontWeight(.heavy)
}.buttonStyle(PickerButtonStyle())
}.padding(8)
}.background(BlurView())
.background(Color.gray.opacity(0.25))
.cornerRadius(12)
.position(x: geo.frame(in: .global).midX, y: geo.frame(in: .global).minY + 120)
}.animation(.spring(), value: envi.currentState)
}
}
struct PickerButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.frame(width: 72, height: 32, alignment: .center)
.aspectRatio(1.0, contentMode: .fit)
.scaleEffect(configuration.isPressed ? 1.0 : 1.0)
.shadow(radius: configuration.isPressed ? 7.5 : 0)
.animation(.linear, value: configuration.isPressed)
.padding(4)
.foregroundColor(Color.primary)
}
}
| 40 | 91 | 0.511735 |
2605c83e5286e8674d1152a5114ab0d256ce41d8 | 270 | //
// CompsableArchitectureApp.swift
// CompsableArchitecture
//
// Created by Cédric Bahirwe on 25/06/2021.
//
import SwiftUI
@main
struct CompsableArchitectureApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 15 | 44 | 0.62963 |
dbfc3d278349dbbd265908db672bec638d00703e | 6,980 | import UIKit
import XCTest
import CheapRulerIOS
import JavaScriptCore
class Tests: XCTestCase {
var ruler: CheapRuler!
var milesRuler: CheapRuler!
var lines: [[[Double]]]?
var points: [[Double]]?
var expectations: [String: AnyObject]?
override func setUp() {
super.setUp()
self.ruler = CheapRuler(lat: 32.8351, units: nil)
self.milesRuler = CheapRuler(lat: 32.8351, units: CheapRuler.Factor.Miles)
let linesPath = Bundle(for: type(of: self)).path(forResource: "lines", ofType: "json")
let expectationsPath = Bundle(for: type(of: self)).path(forResource: "expectations", ofType: "json")
do {
var jsonData = try NSData(contentsOfFile: linesPath!) as Data
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [[[Double]]]
self.lines = json
self.points = Array(json.joined())
jsonData = try NSData(contentsOfFile: expectationsPath!) as Data
self.expectations = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: AnyObject]
}
catch {
assert(false, "Json error")
}
}
override func tearDown() {
super.tearDown()
}
func testDistance() {
let expected = self.expectations?["distance"] as! [Double]
for i in 0 ..< self.points!.count - 1 {
let actual = self.ruler.distance(a: points![i], b: points![i + 1])
XCTAssertLessThan(abs(expected[i] - actual), 1e-12)
}
}
func testDistanceInMiles() {
let d = self.ruler.distance(a: [30.5, 32.8351], b: [30.51, 32.8451])
let d2 = self.milesRuler.distance(a: [30.5, 32.8351], b: [30.51, 32.8451])
XCTAssertLessThan(abs(d / d2 - 1.609344), 1e-12)
}
func testBearing() {
let expected = self.expectations?["bearing"] as! [Double]
for i in 0 ..< self.points!.count - 1 {
let actual = self.ruler.bearing(a: points![i], b: points![i + 1])
XCTAssertLessThan(abs(expected[i] - actual), 1e-12)
}
}
func testDestination() {
let expected = self.expectations?["destination"] as! [[Double]]
for i in 0 ..< self.points!.count {
let bearing = Double((i % 360) - 180)
let actual = self.ruler.destination(p: self.points![i], dist: 1.0, bearing: bearing)
XCTAssertLessThan(abs(expected[i][0] - actual[0]), 1e-12)
XCTAssertLessThan(abs(expected[i][1] - actual[1]), 1e-12)
}
}
func testLineDistance() {
let expected = self.expectations?["lineDistance"] as! [Double]
for i in 0 ..< self.lines!.count {
let actual = self.ruler.lineDistance(points: self.lines![i])
XCTAssertLessThan(abs(expected[i] - actual), 1e-12)
}
}
func testArea() {
let expected = self.expectations?["area"] as! [Double]
let polygons = self.lines!.filter({ $0.count >= 3 })
for i in 0 ..< polygons.count {
let actual = self.ruler.area(polygon: [polygons[i]])
XCTAssertLessThan(abs(expected[i] - actual), 1e-12)
}
}
func testAlong() {
let expected = self.expectations?["along"] as! [[Double]]
for i in 0 ..< self.lines!.count {
let distance = self.ruler.lineDistance(points: self.lines![i]) / 2
let actual = self.ruler.along(line: self.lines![i], dist: distance)
XCTAssertLessThan(abs(expected[i][0] - actual[0]), 1e-12)
XCTAssertLessThan(abs(expected[i][1] - actual[1]), 1e-12)
}
}
func testAlongWithNegativeDistance() {
let line = self.lines![0]
XCTAssertEqual(self.ruler.along(line: line, dist: -5), line[0])
}
func testAlongWithExcessDistance() {
let line = self.lines![0]
XCTAssertEqual(self.ruler.along(line: line, dist: 1000), line.last!)
}
func testPointOnLine() {
let line = [[-77.031669, 38.878605], [-77.029609, 38.881946]];
let p = self.ruler.pointOnLine(line, p: [-77.034076, 38.882017]).point;
XCTAssertEqual(p, [-77.03052697027461, 38.880457194811896])
}
func testLineSlice() {
let expected = self.expectations?["lineSlice"] as! [Double]
var lines = self.lines!
lines.remove(at: 46)
for i in 0 ..< lines.count {
let line = lines[i]
let dist = self.ruler.lineDistance(points: line)
let start = self.ruler.along(line: line, dist: dist * 0.3)
let stop = self.ruler.along(line: line, dist: dist * 0.7)
let actual = self.ruler.lineDistance(points: ruler.lineSlice(start: start, stop: stop, line: line))
XCTAssertLessThan(abs(expected[i] - actual), 1e-12)
}
}
func testLineSliceAlong() {
let expected = self.expectations?["lineSliceAlong"] as! [Double]
var lines = self.lines!
lines.remove(at: 46)
for i in 0 ..< lines.count {
let line = lines[i]
let dist = self.ruler.lineDistance(points: line)
let actual = self.ruler.lineDistance(points: ruler.lineSliceAlong(start: dist * 0.3, stop: dist * 0.7, line: line))
XCTAssertLessThan(abs(expected[i] - actual), 1e-12)
}
}
func testLineSliceReverse() {
let line = lines![0]
let dist = self.ruler.lineDistance(points: line)
let start = self.ruler.along(line: line, dist: dist * 0.7)
let stop = self.ruler.along(line: line, dist: dist * 0.3)
let actual = self.ruler.lineDistance(points: ruler.lineSlice(start: start, stop: stop, line: line))
XCTAssertEqual(actual, 0.018676802802910702)
}
func testBufferPoint() {
let expected = self.expectations?["bufferPoint"] as! [[Double]]
for i in 0 ..< self.points!.count {
let actual = self.milesRuler.bufferPoint(p: self.points![i], buffer: 0.1)
XCTAssertLessThan(abs(expected[i][0] - actual[0]), 1e-12)
XCTAssertLessThan(abs(expected[i][1] - actual[1]), 1e-12)
XCTAssertLessThan(abs(expected[i][2] - actual[2]), 1e-12)
XCTAssertLessThan(abs(expected[i][3] - actual[3]), 1e-12)
}
}
func testBufferBBox() {
let bbox = [30.0, 38.0, 40.0, 39.0];
let bbox2 = self.ruler.bufferBBox(bbox: bbox, buffer: 1);
XCTAssertEqual(bbox2, [29.989319515875376, 37.99098271225711, 40.01068048412462, 39.00901728774289])
}
func testInsideBBox() {
let bbox = [30.0, 38.0, 40.0, 39.0];
XCTAssertTrue(self.ruler.insideBBox(p: [35, 38.5], bbox: bbox))
XCTAssertFalse(self.ruler.insideBBox(p: [45, 45], bbox: bbox))
}
}
| 37.934783 | 127 | 0.57106 |
f420bba2c074e51a0a3c196b2838ee94678284f1 | 1,452 | //
// checklist14Jan2021UITests.swift
// checklist14Jan2021UITests
//
// Created by Emin on 14.01.2022.
//
import XCTest
class checklist14Jan2021UITests: XCTestCase {
override func setUpWithError() throws {
// 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 tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// 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() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.767442 | 182 | 0.662534 |
7adafeb0dc4d438bf94d02eae7a65866aab10495 | 2,874 | //
// LocationService.swift
// Homehapp
//
// Created by Lari Tuominen on 1.2.2016.
// Copyright © 2016 Homehapp. All rights reserved.
//
import Foundation
import QvikNetwork
import MapKit
import GoogleMaps
struct ReverseGeocodeResponse {
var country: String = ""
var city: String = ""
var sublocality: String = ""
}
class LocationService: RemoteService {
private static let singletonInstance = LocationService()
// MARK: Public methods
/// Returns a shared (singleton) instance.
override class func sharedInstance() -> LocationService {
return singletonInstance
}
/// https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=3000&types=<type>&key=<your-api-key>
func fetchPlaces(pageToken: String?, centerCoordinate: CLLocationCoordinate2D, type: String, completionCallback: (RemoteResponse -> Void)? = nil) {
var url = ""
if let pageToken = pageToken {
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(centerCoordinate.latitude),\(centerCoordinate.longitude)&radius=3000&types=\(type)&pagetoken=\(pageToken)&key=AIzaSyDPzTlDi9dZ2otR47DLwUPHp4Y2Ge9VQ-U".urlEncoded!
} else {
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(centerCoordinate.latitude),\(centerCoordinate.longitude)&radius=3000&types=\(type)&key=AIzaSyDPzTlDi9dZ2otR47DLwUPHp4Y2Ge9VQ-U".urlEncoded!
}
remoteService.request(.GET, url, parameters: nil, encoding: .JSON, headers: nil) { response in
completionCallback?(response)
}
}
/// Reverse geocodes given coordinate and calls completionCallback with first placemark found
func reverseGeocodeCoordinate(coordinate: CLLocationCoordinate2D, completionCallback: (ReverseGeocodeResponse? -> Void)) {
let location = CLLocation.init(latitude: coordinate.latitude, longitude: coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(location) { (placemarks, error) in
if let placemarks = placemarks where error == nil {
var country = ""
var city = ""
var sublocality = ""
if placemarks[0].country != nil {
country = placemarks[0].country!
}
if placemarks[0].locality != nil {
city = placemarks[0].locality!
}
if placemarks[0].subLocality != nil {
sublocality = placemarks[0].subLocality!
}
let response = ReverseGeocodeResponse(country: country, city: city, sublocality: sublocality)
completionCallback(response)
}
completionCallback(nil)
}
}
}
| 39.916667 | 253 | 0.635351 |
e6f9721e280da24ee8dbe32b7fc34d1cdee0e472 | 1,291 | //
// NSImageView.swift
// Cashier
//
// Created by Saikiran.
// Copyright © 2016 c. All rights reserved.
//
import Foundation
import UIKit
extension UIImageView {
func downloadedFrom(_ link: AnyObject, contentMode mode: UIViewContentMode = .scaleAspectFit) {
var url : URL
if link is URL {
url = link as! URL
}
else if link is String {
if let unwrappedURL = URL (string: link as! String){
url = unwrappedURL
}
else {
return
}
}
else {
return
}
contentMode = mode
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async(execute: {
self.image = image
})
}) .resume()
}
}
| 24.358491 | 104 | 0.48567 |
ac4c153ed8f111779b3ea38b5249abc4a4127541 | 3,729 | //
// DetailViewController.swift
// LifeHash_Example
//
// Copyright © 2020 by Blockchain Commons, LLC
// Licensed under the "BSD-2-Clause Plus Patent License"
//
// Created by Wolf McNally on 12/6/18.
//
import UIKit
import LifeHash
class DetailViewController: UIViewController {
var hashTitle: String! {
get { label.text }
set { label.text = newValue }
}
var hashInput: Data! {
lifeHashView.hashInput
}
var version: LifeHashVersion {
lifeHashView.version
}
func set(hashInput: Data?, version: LifeHashVersion) {
lifeHashView.set(hashInput: hashInput, version: version)
}
static let fontSize: CGFloat = 24
static let font = UIFont.boldSystemFont(ofSize: fontSize)
static let width: CGFloat = 200
static let imageSize = CGSize(width: width, height: width)
private lazy var stackView: UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.axis = .vertical
view.spacing = 20
return view
}()
private lazy var blurView: UIVisualEffectView = {
let view = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = Self.font
label.textColor = .label
label.textAlignment = .center
return label
}()
private lazy var lifeHashView: LifeHashView = {
let view = LifeHashView(frame: .zero)
view.constrainAspect()
return view
}()
private func setup() {
modalPresentationStyle = .overCurrentContext
modalTransitionStyle = .crossDissolve
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private let tapRecognizer = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
// view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .clear
stackView.addArrangedSubview(lifeHashView)
stackView.addArrangedSubview(label)
view.addSubview(blurView)
view.addSubview(stackView)
blurView.constrainFrameToFrame()
stackView.constrainCenterToCenter()
let width: CGFloat = 0.6
NSLayoutConstraint.activate([
lifeHashView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: width).setPriority(to: .defaultHigh),
lifeHashView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: width).setPriority(to: .defaultHigh),
lifeHashView.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, multiplier: width),
lifeHashView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor, multiplier: width)
])
tapRecognizer.addTarget(self, action: #selector(didTap))
view.addGestureRecognizer(tapRecognizer)
}
@objc private func didTap(_ recognizer: UIGestureRecognizer) {
self.dismiss(animated: true)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if isDarkMode(self) {
blurView.effect = UIBlurEffect(style: .dark)
} else {
blurView.effect = UIBlurEffect(style: .light)
}
}
}
| 29.595238 | 126 | 0.666398 |
50c1ddc0ca780b86abda307542db9e158307eacd | 13,305 | //
// LoginView.swift
// MyApp
//
// Created by PandoraXY on 2018/11/5.
// Copyright © 2018 AppStudio. All rights reserved.
//
import UIKit
/// 自定义输入框类型
///
/// - none: 标准输入框
/// - phoneNumber: 手机号
/// - passwordNormal: 设置密码/确认密码
/// - passwordForget: 忘记密码
/// - verificationCode: 验证码
public enum MyTextFieldType: UInt {
case none
case phoneNumber
case passwordNormal
case passwordForget
case verificationCode
}
class MyTextField: UITextField {
// MARK: - Public Properties
/// 输入框内左侧图片名称
public var leftImageName: String?
/// 输入框内右则按钮名称
public var rightButtonTitle: String?
/// 自定义Placeholder字体
public var placeholderString: String?{
set {
guard newValue != nil else {
return
}
let attributes:[NSAttributedString.Key:Any] = [.foregroundColor:UIColor.myGray(),
.font:UIFont.regularFont32()]
self.attributedPlaceholder = NSAttributedString.init(string: newValue!, attributes: attributes)
}
get {
return self.placeholder
}
}
/// 输入框类型
private var type: MyTextFieldType = .phoneNumber
// MARK: - Private Properties
/// 边距
private let margin: CGFloat = 10.0
/// 输入框内左侧视图
fileprivate(set) lazy var leftImageView: UIImageView = {
let imageView = UIImageView.init(frame: .zero)
imageView.backgroundColor = UIColor.red
if let imageName = self.leftImageName {
imageView.image = UIImage.init(named: imageName)
} else {
imageView.isHidden = true
}
return imageView
}()
/// 输入框内右侧视图
fileprivate(set) lazy var rightButton: UIButton = {
let button = UIButton.init(type: .custom)
button.backgroundColor = UIColor.clear
if let aTitle = self.rightButtonTitle {
button.setTitle(aTitle, for: .normal)
button.titleLabel?.font = UIFont.regularFont24()
} else {
button.isHidden = true
}
if self.type == .passwordForget {
button.layer.borderWidth = 0.0
button.layer.borderColor = UIColor.clear.cgColor
button.layer.masksToBounds = false
} else if self.type == .verificationCode {
button.layer.borderWidth = 0.5
button.layer.borderColor = UIColor.myBlue().cgColor
button.layer.masksToBounds = true
} else {
button.isHidden = true
}
return button
}()
// MARK: - Initialization
convenience init(frame: CGRect, type: MyTextFieldType) {
self.init(frame: frame)
self.type = type
if type == .passwordForget || type == .verificationCode {
self.leftViewMode = .always
self.rightViewMode = .always
} else if type == .phoneNumber || type == .phoneNumber {
self.leftViewMode = .always
} else {
self.leftViewMode = .never
self.rightViewMode = .never
}
}
override init(frame: CGRect) {
super.init(frame: frame)
// self.borderStyle = UITextField.BorderStyle.line
// self.borderStyle = UITextField.BorderStyle.bezel
// self.borderStyle = UITextField.BorderStyle.roundedRect
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Override Functions
// override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
// let rect = super.placeholderRect(forBounds: bounds)
// let insets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
// return rect.inset(by: insets)
// }
override func textRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.textRect(forBounds: bounds)
if self.type == .none || (self.leftImageName == nil && self.rightButtonTitle == nil) {
return rect
}
let insets = UIEdgeInsets(top: 0, left: self.margin + 5, bottom: 0, right: self.margin)
return rect.inset(by: insets)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.textRect(forBounds: bounds)
if self.type == .none || (self.leftImageName == nil && self.rightButtonTitle == nil) {
return rect
}
let insets = UIEdgeInsets(top: 0, left: self.margin + 5, bottom: 0, right: self.margin)
return rect.inset(by: insets)
}
override func layoutSubviews() {
super.layoutSubviews()
if self.type == .none || (self.leftImageName == nil && self.rightButtonTitle == nil) {
return
}
if self.leftImageName != nil {
let leftViewW: CGFloat = 20.0
let leftViewH: CGFloat = self.frame.height - self.margin * 2
let leftViewX: CGFloat = self.margin
let leftViewY: CGFloat = self.margin
self.leftImageView.frame = CGRect(x: leftViewX, y: leftViewY, width: leftViewW, height: leftViewH)
self.leftView = self.leftImageView
}
if (self.type == .passwordForget || self.type == .verificationCode) && self.rightButtonTitle != nil {
let rightViewW: CGFloat = UIScreen.relativeWidth(80.0)
let rightViewH: CGFloat = UIScreen.relativeHeight(25.0)
let rightViewX: CGFloat = self.frame.width - rightViewW - self.margin
let rightViewY: CGFloat = (self.frame.height - rightViewH) / 2
self.rightButton.frame = CGRect(x: rightViewX, y: rightViewY, width: rightViewW, height: rightViewH)
if self.type == .verificationCode {
self.rightButton.layer.cornerRadius = rightViewH / 2
}
self.rightView = self.rightButton
}
}
// MARK: - Public Functions
// MARK: - Private Functions
}
// MARK: - LoginViewDelegate
public protocol LoginViewDelegate: NSObjectProtocol {
func forgetPassword()
func register()
}
// MARK: - LoginView
/// 登录视图
class LoginView: BaseView {
// MARK: - Private Properties
public weak var delegate: LoginViewDelegate?
/// 商品图标
private lazy var brandIconView: UIImageView = {
let imageView = UIImageView.init(frame: .zero)
imageView.image = UIImage.init(named: "")
imageView.backgroundColor = UIColor.red
self.addSubview(imageView)
return imageView
}()
/// 商品名称
private lazy var brandLabel: UILabel = {
let label = UILabel.init(frame: .zero)
label.textColor = UIColor.black
label.text = "启明跆拳道"
label.font = UIFont.init(name: "HanziPenSC-W3", size: 28.0)
label.textAlignment = .center
self.addSubview(label)
return label
}()
/// 手机输入框
private lazy var phoneTextField: MyTextField = {
let textField = MyTextField.init(frame: .zero, type: .phoneNumber)
textField.leftImageName = ""
textField.rightButtonTitle = "Code"
textField.backgroundColor = UIColor.myGrayWhite()
textField.placeholderString = "Your cell-phone number"
return textField
}()
/// 密码输入框
private lazy var pwdTextField: MyTextField = {
let textField = MyTextField.init(frame: .zero, type: .passwordForget)
textField.leftImageName = ""
textField.rightButtonTitle = "Forget"
textField.backgroundColor = UIColor.myGrayWhite()
textField.placeholderString = "Your password"
textField.rightButton.addTarget(self, action: #selector(self.forgetPwdAction(_:)), for: .touchUpInside)
return textField
}()
/// 登录按钮
private lazy var loginButton: UIButton = {
let button = UIButton.init(type: .custom)
button.setTitle("Login", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.textAlignment = .center
button.titleLabel?.font = UIFont.regularFont36()
button.backgroundColor = UIColor.myBlue()
self.addSubview(button)
return button
}()
/// 注册按钮
private lazy var regiserButton: UIButton = {
let button = UIButton.init(type: .custom)
button.setTitle("Register", for: .normal)
button.setTitleColor(UIColor.myBlue(), for: .normal)
button.titleLabel?.textAlignment = .center
button.titleLabel?.font = UIFont.regularFont24()
button.backgroundColor = UIColor.clear
button.addTarget(self, action: #selector(self.registerAction(_:)), for: .touchUpInside)
self.addSubview(button)
return button
}()
private lazy var splitLineLayer1: CALayer = {
let layer = CALayer.init()
layer.backgroundColor = UIColor.mySilverGray().cgColor
self.layer.addSublayer(layer)
return layer
}()
private lazy var splitLineLayer2: CALayer = {
let layer = CALayer.init()
layer.backgroundColor = UIColor.mySilverGray().cgColor
self.layer.addSublayer(layer)
return layer
}()
/// 输入框Statck
private lazy var statckView: UIStackView = {
let aStackView = UIStackView.init(frame: .zero)
aStackView.addArrangedSubview(self.phoneTextField)
aStackView.addArrangedSubview(self.pwdTextField)
aStackView.alignment = .fill
aStackView.distribution = .fillEqually
aStackView.axis = .vertical
aStackView.spacing = 10.0
self.addSubview(aStackView)
return aStackView
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func layoutSubviews() {
super.layoutSubviews()
let margin: CGFloat = UIScreen.relativeWidth(30.0)
let bandIconW: CGFloat = UIScreen.relativeWidth(82.0)
let bandIconH: CGFloat = UIScreen.relativeHeight(90.0)
let bandIconX: CGFloat = (self.frame.width - bandIconW) / 2
let bandIconY: CGFloat = UIScreen.relativeHeight(88.0)
self.brandIconView.frame = CGRect(x: bandIconX, y: bandIconY, width: bandIconW, height: bandIconH)
let bandLabelW: CGFloat = self.frame.width - margin * 2
let bandLabelH: CGFloat = UIScreen.relativeHeight(50.0)
let bandLabelX: CGFloat = (self.frame.width - bandLabelW) / 2
let bandLabelY: CGFloat = self.brandIconView.frame.maxY
self.brandLabel.frame = CGRect(x: bandLabelX, y: bandLabelY, width: bandLabelW, height: bandLabelH)
// self.phoneTextField.frame = CGRect(x: 20, y: 100, width: 300, height: 60)
let statckViewW: CGFloat = self.frame.width - margin * 2
let statckViewH: CGFloat = UIScreen.relativeHeight(100.0)
let statckViewX: CGFloat = margin
let statckViewY: CGFloat = self.brandLabel.frame.maxY + UIScreen.relativeHeight(34.0)
self.statckView.frame = CGRect(x: statckViewX, y: statckViewY, width: statckViewW, height: statckViewH)
let loginButtonW: CGFloat = statckViewW
let loginButtonH: CGFloat = UIScreen.relativeHeight(50.0)
let loginButtonX: CGFloat = margin
let loginButtonY: CGFloat = self.statckView.frame.maxY + UIScreen.relativeHeight(30.0)
self.loginButton.frame = CGRect(x: loginButtonX, y: loginButtonY, width: loginButtonW, height: loginButtonH)
let registerButtonW: CGFloat = UIScreen.relativeWidth(52.0)
let registerButtonH: CGFloat = UIScreen.relativeHeight(12.0)
let splitLineW: CGFloat = (self.frame.width - margin * 2 - registerButtonW - UIScreen.relativeWidth(20)) / 2
let splitLineH: CGFloat = 1.0
let splitLineX1: CGFloat = margin
let splitLineX2: CGFloat = self.frame.width - margin - splitLineW
let splitLineY: CGFloat = self.loginButton.frame.maxY + UIScreen.relativeHeight(28.0)
self.splitLineLayer1.frame = CGRect(x: splitLineX1, y: splitLineY, width: splitLineW, height: splitLineH)
self.splitLineLayer2.frame = CGRect(x: splitLineX2, y: splitLineY, width: splitLineW, height: splitLineH)
let registerButtonX: CGFloat = (self.frame.width - registerButtonW) / 2
let registerButtonY: CGFloat = self.loginButton.frame.maxY + UIScreen.relativeHeight(22.0)
self.regiserButton.frame = CGRect(x: registerButtonX, y: registerButtonY, width: registerButtonW, height: registerButtonH)
}
// MARK: - Setters and Getters
// MARK: - Private Functions
// MARK: - Public Functions
// MARK: - Target Actions
@objc private func forgetPwdAction(_ sender: UIButton) -> Void {
self.delegate?.forgetPassword()
}
@objc private func registerAction(_ sender: UIButton) -> Void {
self.delegate?.register()
}
}
| 34.738903 | 130 | 0.613228 |
ef77fc4b9bb7c0f1796d089596d004740f707725 | 18,133 | import Foundation
import XCTest
import MapboxDirections
import struct Polyline.Polyline
import Turf
@testable import MapboxCoreNavigation
class RouteProgressTests: XCTestCase {
func testRouteProgress() {
let routeProgress = RouteProgress(route: route)
XCTAssertEqual(routeProgress.fractionTraveled, 0)
XCTAssertEqual(routeProgress.distanceRemaining, 4054.2)
XCTAssertEqual(routeProgress.distanceTraveled, 0)
XCTAssertEqual(round(routeProgress.durationRemaining), 858)
}
func testRouteLegProgress() {
let routeProgress = RouteProgress(route: route)
XCTAssertEqual(routeProgress.currentLeg.description, "Hyde Street, Page Street")
XCTAssertEqual(routeProgress.currentLegProgress.distanceTraveled, 0)
XCTAssertEqual(round(routeProgress.currentLegProgress.durationRemaining), 858)
XCTAssertEqual(routeProgress.currentLegProgress.fractionTraveled, 0)
XCTAssertEqual(routeProgress.currentLegProgress.stepIndex, 0)
XCTAssertEqual(routeProgress.currentLegProgress.followOnStep?.description, "Turn left onto Hyde Street")
XCTAssertEqual(routeProgress.currentLegProgress.upcomingStep?.description, "Turn right onto California Street")
}
func testRouteStepProgress() {
let routeProgress = RouteProgress(route: route)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.distanceRemaining, 384.1)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.distanceTraveled, 0)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.durationRemaining, 86.6, accuracy: 0.001)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.fractionTraveled, 0)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation, 384.1)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.step.description, "Head south on Taylor Street")
}
func testNextRouteStepProgress() {
let routeProgress = RouteProgress(route: route)
routeProgress.currentLegProgress.stepIndex = 1
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex, 0)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.distanceRemaining, 439.1)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.distanceTraveled, 0)
XCTAssertEqual(round(routeProgress.currentLegProgress.currentStepProgress.durationRemaining), 73)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.fractionTraveled, 0)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation, 439.1)
XCTAssertEqual(routeProgress.currentLegProgress.currentStepProgress.step.description, "Turn right onto California Street")
}
func testRemainingWaypointsAlongRoute() {
let coordinates = [
CLLocationCoordinate2D(latitude: 0, longitude: 0),
CLLocationCoordinate2D(latitude: 2, longitude: 3),
CLLocationCoordinate2D(latitude: 4, longitude: 6),
CLLocationCoordinate2D(latitude: 6, longitude: 9),
CLLocationCoordinate2D(latitude: 8, longitude: 12),
CLLocationCoordinate2D(latitude: 10, longitude: 15),
CLLocationCoordinate2D(latitude: 12, longitude: 18),
]
// Single leg
var options = RouteOptions(coordinates: [coordinates.first!, coordinates.last!])
var waypoints = options.waypoints(fromLegAt: 0)
XCTAssertEqual(waypoints.0.map { $0.coordinate }, [coordinates.first!])
XCTAssertEqual(waypoints.1.map { $0.coordinate }, [coordinates.last!])
// Two legs
options = RouteOptions(coordinates: [coordinates[0], coordinates[1], coordinates.last!])
waypoints = options.waypoints(fromLegAt: 0)
XCTAssertEqual(waypoints.0.map { $0.coordinate }, [coordinates[0]])
XCTAssertEqual(waypoints.1.map { $0.coordinate }, [coordinates[1], coordinates.last!])
waypoints = options.waypoints(fromLegAt: 1)
XCTAssertEqual(waypoints.0.map { $0.coordinate }, [coordinates[1]])
XCTAssertEqual(waypoints.1.map { $0.coordinate }, [coordinates.last!])
// Every coordinate is a leg
options = RouteOptions(coordinates: coordinates)
waypoints = options.waypoints(fromLegAt: 0)
XCTAssertEqual(waypoints.0.map { $0.coordinate }, [coordinates.first!])
XCTAssertEqual(waypoints.1.map { $0.coordinate }, Array(coordinates.dropFirst()))
// Every coordinate is a via point
for waypoint in options.waypoints {
waypoint.separatesLegs = false
}
waypoints = options.waypoints(fromLegAt: 0)
XCTAssertEqual(waypoints.0.map { $0.coordinate }, Array(coordinates.dropLast()))
XCTAssertEqual(waypoints.1.map { $0.coordinate }, [coordinates.last!])
}
func routeLeg(options: RouteOptions, routeCoordinates: [CLLocationCoordinate2D]) -> RouteLeg {
let source = options.waypoints.first!
let destination = options.waypoints.last!
options.shapeFormat = .polyline
let steps = [
RouteStep(transportType: .automobile, maneuverLocation: source.coordinate, maneuverType: .depart, maneuverDirection: nil, instructions: "", initialHeading: nil, finalHeading: nil, drivingSide: .right, exitCodes: nil, exitNames: nil, phoneticExitNames: nil, distance: 0, expectedTravelTime: 0, names: nil, phoneticNames: nil, codes: nil, destinationCodes: nil, destinations: nil, intersections: nil, instructionsSpokenAlongStep: nil, instructionsDisplayedAlongStep: nil),
RouteStep(transportType: .automobile, maneuverLocation: destination.coordinate, maneuverType: .arrive, maneuverDirection: nil, instructions: "", initialHeading: nil, finalHeading: nil, drivingSide: .right, exitCodes: nil, exitNames: nil, phoneticExitNames: nil, distance: 0, expectedTravelTime: 0, names: nil, phoneticNames: nil, codes: nil, destinationCodes: nil, destinations: nil, intersections: nil, instructionsSpokenAlongStep: nil, instructionsDisplayedAlongStep: nil),
]
steps[0].shape = LineString(routeCoordinates)
return RouteLeg(steps: steps, name: "", distance: 0, expectedTravelTime: 0, profileIdentifier: .automobile)
}
func routeLegProgress(options: RouteOptions, routeCoordinates: [CLLocationCoordinate2D]) -> RouteLegProgress {
let leg = routeLeg(options: options, routeCoordinates: routeCoordinates)
return RouteLegProgress(leg: leg)
}
func testRemainingWaypointsAlongLeg() {
// Linear leg
var coordinates = [
CLLocationCoordinate2D(latitude: 0, longitude: 0),
CLLocationCoordinate2D(latitude: 2, longitude: 3),
CLLocationCoordinate2D(latitude: 4, longitude: 6),
CLLocationCoordinate2D(latitude: 6, longitude: 9),
CLLocationCoordinate2D(latitude: 8, longitude: 12),
CLLocationCoordinate2D(latitude: 10, longitude: 15),
CLLocationCoordinate2D(latitude: 12, longitude: 18),
]
// No via points
var options = RouteOptions(coordinates: [coordinates.first!, coordinates.last!])
var legProgress = routeLegProgress(options: options, routeCoordinates: coordinates)
var remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"With no via points, at the start of the leg, neither the source nor a via point should remain")
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[1]) / 2.0
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"With no via points, partway down the leg, neither the source nor a via point should remain")
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[1])
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"With no via points, partway down the leg, neither the source nor a via point should remain")
// Every coordinate is a via point.
options = RouteOptions(coordinates: coordinates)
legProgress = routeLegProgress(options: options, routeCoordinates: coordinates)
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, options.waypoints.count - 2,
"At the start of the leg, all but the source should remain")
legProgress = routeLegProgress(options: options, routeCoordinates: coordinates)
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[1]) / 2.0
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, options.waypoints.count - 2,
"Halfway to the first via point, all but the source should remain")
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[1])
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, options.waypoints.count - 3,
"At the first via point, all but the source and first via point should remain")
// Leg that backtracks
coordinates = [
CLLocationCoordinate2D(latitude: 0, longitude: 0),
CLLocationCoordinate2D(latitude: 2, longitude: 3),
CLLocationCoordinate2D(latitude: 4, longitude: 6),
CLLocationCoordinate2D(latitude: 6, longitude: 9), // begin backtracking
CLLocationCoordinate2D(latitude: 4, longitude: 6),
CLLocationCoordinate2D(latitude: 2, longitude: 3),
CLLocationCoordinate2D(latitude: 0, longitude: 0),
]
// No via points.
options = RouteOptions(coordinates: [coordinates.first!, coordinates.last!])
legProgress = routeLegProgress(options: options, routeCoordinates: coordinates)
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"With no via points, at the start of a leg that backtracks, neither the source nor a via point should remain")
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[1])
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"With no via points, partway down a leg before backtracking, neither the source nor a via point should remain")
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[3]) + coordinates[3].distance(to: coordinates[4])
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"With no via points, partway down a leg after backtracking, neither the source nor a via point should remain")
// Every coordinate is a via point.
options = RouteOptions(coordinates: coordinates)
legProgress = routeLegProgress(options: options, routeCoordinates: coordinates)
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 5,
"At the start of a leg that backtracks, all but the source should remain")
legProgress.currentStepProgress.distanceTraveled = coordinates[0].distance(to: coordinates[1])
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 4,
"At the first via point before backtracking, all but the source and first via point should remain")
legProgress.currentStepProgress.distanceTraveled = LineString(coordinates).distance() / 2.0
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 2,
"At the via point where the leg backtracks, only the via points after backtracking should remain")
legProgress.currentStepProgress.distanceTraveled = LineString(coordinates).distance() / 2.0 + coordinates[3].distance(to: coordinates[4]) / 2.0
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 2,
"Halfway to the via point where the leg backtracks, only the via points after backtracking should remain")
legProgress.currentStepProgress.distanceTraveled = LineString(coordinates).distance() / 2.0 + coordinates[3].distance(to: coordinates[4])
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 1,
"At the first via point after backtracking, all but one of the via points after backtracking should remain")
legProgress.currentStepProgress.distanceTraveled = LineString(coordinates).distance()
remainingWaypoints = legProgress.remainingWaypoints(among: Array(options.waypoints.dropLast()))
XCTAssertEqual(remainingWaypoints.count, 0,
"At the last via point after backtracking, nothing should remain")
}
func testSpeedLimits() {
let coordinates = [
CLLocationCoordinate2D(latitude: 0, longitude: 0),
CLLocationCoordinate2D(latitude: 2, longitude: 3),
CLLocationCoordinate2D(latitude: 4, longitude: 6),
CLLocationCoordinate2D(latitude: 6, longitude: 9),
CLLocationCoordinate2D(latitude: 8, longitude: 12),
CLLocationCoordinate2D(latitude: 10, longitude: 15),
CLLocationCoordinate2D(latitude: 12, longitude: 18),
]
let lineString = LineString(coordinates)
let options = RouteOptions(coordinates: [coordinates.first!, coordinates.last!])
let leg = routeLeg(options: options, routeCoordinates: coordinates)
leg.segmentMaximumSpeedLimits = [
.init(value: 10, unit: .kilometersPerHour),
.init(value: 20, unit: .milesPerHour),
nil,
.init(value: 40, unit: .milesPerHour),
.init(value: 50, unit: .kilometersPerHour),
.init(value: .infinity, unit: .kilometersPerHour),
]
let legProgress = RouteLegProgress(leg: leg)
XCTAssertEqual(legProgress.distanceTraveled, 0)
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 10, unit: UnitSpeed.kilometersPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[1]) / 2.0
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 10, unit: UnitSpeed.kilometersPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[1])
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 20, unit: UnitSpeed.milesPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[1]) + lineString.distance(from: coordinates[1], to: coordinates[2]) / 2.0
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 20, unit: UnitSpeed.milesPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[2])
XCTAssertNil(legProgress.currentSpeedLimit)
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[2]) + lineString.distance(from: coordinates[2], to: coordinates[3]) / 2.0
XCTAssertNil(legProgress.currentSpeedLimit)
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[3])
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 40, unit: UnitSpeed.milesPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[3]) + lineString.distance(from: coordinates[3], to: coordinates[4]) / 2.0
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 40, unit: UnitSpeed.milesPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[4])
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 50, unit: UnitSpeed.kilometersPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[4]) + lineString.distance(from: coordinates[4], to: coordinates[5]) / 2.0
XCTAssertEqual(legProgress.currentSpeedLimit, Measurement(value: 50, unit: UnitSpeed.kilometersPerHour))
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[5])
XCTAssertTrue(legProgress.currentSpeedLimit?.value.isInfinite ?? false)
legProgress.currentStepProgress.distanceTraveled = lineString.distance(to: coordinates[5]) + (lineString.distance() - lineString.distance(to: coordinates[5])) / 2.0
XCTAssertTrue(legProgress.currentSpeedLimit?.value.isInfinite ?? false)
}
}
| 65.938182 | 487 | 0.710638 |
5b3c4d6d6ca7ac46d52633caafc137a478317331 | 16,245 | //
// KPPhotoGalleryViewController.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/9.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
import SKPhotoBrowser
class KPPhotoGalleryViewController: KPViewController {
static let KPPhotoGalleryViewControllerCellReuseIdentifier = "cell";
static let KPPhotoGalleryViewControllerCellAddIdentifier = "cell_add";
var transitionController: KPPhotoDisplayTransition = KPPhotoDisplayTransition()
var hideSelectedCell: Bool = false
var dismissButton: KPBounceButton!
var collectionView: UICollectionView!;
var collectionLayout: UICollectionViewFlowLayout!;
var selectedIndexPath: IndexPath!
var selectedCellSnapshot: UIView {
get {
let selectedCell = collectionView.cellForItem(at: selectedIndexPath) as! KPShopPhotoCell
// UIGraphicsBeginImageContextWithOptions((selectedCell?.frameSize)!,
// true,
// 0.0)
// selectedCell?.layer.render(in: UIGraphicsGetCurrentContext()!)
// let img = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext();
// return img!;
let snapShotView = UIImageView(image: selectedCell.shopPhoto.image)
snapShotView.frame = selectedCell.frame
return snapShotView
}
}
var displayedPhotoInformations: [PhotoInformation] = [PhotoInformation]() {
didSet {
if collectionView != nil {
collectionView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = KPColorPalette.KPTextColor.whiteColor
navigationItem.title = "店家照片"
navigationItem.hidesBackButton = true
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace,
target: nil,
action: nil)
negativeSpacer.width = -8
navigationItem.leftBarButtonItems = [negativeSpacer, UIBarButtonItem(image: R.image.icon_back(),
style: .plain,
target: self,
action: #selector(KPPhotoGalleryViewController.handleBackButtonOnTapped))]
let itemSize = (UIScreen.main.bounds.size.width-(12*4))/3
//Collection view
collectionLayout = UICollectionViewFlowLayout()
collectionLayout.scrollDirection = .vertical
collectionLayout.minimumLineSpacing = 16.0
collectionLayout.sectionInset = UIEdgeInsetsMake(12, 12, 12, 12)
collectionLayout.itemSize = CGSize(width: itemSize, height: itemSize)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionLayout)
collectionView.backgroundColor = UIColor.clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.delaysContentTouches = true
collectionView.register(KPShopPhotoCell.self,
forCellWithReuseIdentifier:
KPPhotoGalleryViewController.KPPhotoGalleryViewControllerCellReuseIdentifier)
collectionView.register(KPPhotoAddCell.self,
forCellWithReuseIdentifier:
KPPhotoGalleryViewController.KPPhotoGalleryViewControllerCellAddIdentifier)
view.addSubview(collectionView)
collectionView.addConstraints(fromStringArray: ["H:|[$self]|",
"V:|[$self]|"])
SKPhotoBrowserOptions.displayAction = false
SKPhotoBrowserOptions.displayStatusbar = true
NotificationCenter.default.addObserver(self,
selector: #selector(refreshPhoto),
name: Notification.Name(KPNotification.information.photoInformation),
object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Photo Refresh
func refreshPhoto() {
KPServiceHandler.sharedHandler.getPhotos {
[weak self] (successed, photos) in
if let weSelf = self {
if successed == true && photos != nil {
var index: Int = 0
var photoInformations: [PhotoInformation] = []
for urlString in photos! {
if let url = URL(string: urlString["url"]!),
let thumbnailurl = URL(string: urlString["thumbnail"]!) {
photoInformations.append(PhotoInformation(title: "",
imageURL: url,
thumbnailURL: thumbnailurl,
index: index))
index += 1
}
}
weSelf.displayedPhotoInformations = photoInformations
} else {
// Handle Error
}
}
}
}
// MARK: UI Event
func photoUpload() {
if KPUserManager.sharedManager.currentUser == nil {
KPPopoverView.popoverLoginView()
} else {
if KPServiceHandler.sharedHandler.isCurrentShopClosed {
KPPopoverView.popoverClosedView()
} else {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "從相簿中選擇", style: .default) { (action) in
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = false
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
// imagePickerController.mediaTypes = [kUTTypeImage as String]
self.present(imagePickerController, animated: true, completion: nil)
})
controller.addAction(UIAlertAction(title: "開啟相機", style: .default) { (action) in
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = false
imagePickerController.sourceType = .camera
imagePickerController.delegate = self
// imagePickerController.mediaTypes = [kUTTypeImage as String]
self.present(imagePickerController, animated: true, completion: nil)
})
controller.addAction(UIAlertAction(title: "取消", style: .cancel) { (action) in
})
self.present(controller, animated: true) {
}
}
}
}
func handleBackButtonOnTapped() {
navigationController?.popViewController(animated: true)
}
}
extension KPPhotoGalleryViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return displayedPhotoInformations.count + 1;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KPPhotoGalleryViewController.KPPhotoGalleryViewControllerCellAddIdentifier,
for: indexPath) as! KPPhotoAddCell;
cell.layer.cornerRadius = 4.0
cell.layer.masksToBounds = true
return cell;
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KPPhotoGalleryViewController.KPPhotoGalleryViewControllerCellReuseIdentifier,
for: indexPath) as! KPShopPhotoCell;
cell.layer.cornerRadius = 4.0
cell.layer.masksToBounds = true
cell.isUserInteractionEnabled = true
cell.shopPhoto.af_setImage(withURL: displayedPhotoInformations[indexPath.row-1].imageURL,
placeholderImage: R.image.image_loading(),
filter: nil,
progress: nil,
progressQueue: DispatchQueue.global(),
imageTransition: UIImageView.ImageTransition.crossDissolve(0.2),
runImageTransitionIfCached: false,
completion: { (response) in
if response.error != nil {
cell.shopPhoto.image = R.image.image_failed_s()
cell.isUserInteractionEnabled = false
}
if let responseImage = response.result.value {
cell.shopPhoto.image = responseImage
cell.isUserInteractionEnabled = true
}
})
return cell;
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPath = indexPath
if indexPath.row == 0 {
photoUpload()
} else {
var photoSource: [SKPhotoProtocol] = [SKPhotoProtocol]()
for (index, photoInfo) in self.displayedPhotoInformations.enumerated() {
if let photoImage = (collectionView.cellForItem(at: indexPath) as! KPShopPhotoCell).shopPhoto.image,
index == selectedIndexPath.row-1 {
photoSource.append(SKPhoto.photoWithImage(photoImage))
} else {
photoSource.append(SKPhoto.photoWithImageURL(photoInfo.imageURL.absoluteString))
}
}
if let animatedCell = collectionView.cellForItem(at: indexPath) as? KPShopPhotoCell {
let browser = SKPhotoBrowser(originImage: animatedCell.shopPhoto.image!,
photos: photoSource,
animatedFromView: animatedCell)
browser.initializePageIndex(indexPath.row-1)
browser.delegate = self
present(browser, animated: true, completion: {})
}
}
}
}
extension KPPhotoGalleryViewController: SKPhotoBrowserDelegate {
func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView? {
return collectionView.cellForItem(at: IndexPath(item: index+1, section: 0))
}
func didShowPhotoAtIndex(_ index: Int) {
collectionView.visibleCells.forEach({$0.isHidden = false})
collectionView.cellForItem(at: IndexPath(item: index+1, section: 0))?.isHidden = true
}
func willDismissAtPageIndex(_ index: Int) {
collectionView.visibleCells.forEach({$0.isHidden = false})
collectionView.cellForItem(at: IndexPath(item: index+1, section: 0))?.isHidden = true
}
func didDismissAtPageIndex(_ index: Int) {
collectionView.cellForItem(at: IndexPath(item: index+1, section: 0))?.isHidden = false
}
func didDismissActionSheetWithButtonIndex(_ buttonIndex: Int, photoIndex: Int) {
// handle dismissing custom actions
}
}
// MARK: Image Picker
extension KPPhotoGalleryViewController: UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
KPServiceHandler.sharedHandler.uploadPhotos([image],
nil,
true,
{ (success) in
if success {
print("upload successed")
} else {
print("upload failed")
}
})
}
}
}
}
// MARK: View Transition
extension KPPhotoGalleryViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController,
presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let photoViewController = presented as! KPPhotoDisplayViewController
photoViewController.selectedIndexPath = IndexPath(row: selectedIndexPath.row - 1,
section: selectedIndexPath.section)
let cell = collectionView.cellForItem(at: selectedIndexPath) as! KPShopPhotoCell
transitionController.setupImageTransition(cell.shopPhoto.image!,
fromDelegate: self,
toDelegate: photoViewController)
transitionController.transitionType = .damping
return transitionController
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let photoViewController = dismissed as! KPPhotoDisplayViewController
selectedIndexPath = IndexPath(row: photoViewController.selectedIndexPath.row + 1,
section: photoViewController.selectedIndexPath.section)
let cell = collectionView.cellForItem(at: selectedIndexPath) as! KPShopPhotoCell
transitionController.setupImageTransition(cell.shopPhoto.image!,
fromDelegate: photoViewController,
toDelegate: self)
return transitionController
}
}
extension KPPhotoGalleryViewController: ImageTransitionProtocol {
// 1: hide selected cell for tranisition snapshot
func tranisitionSetup(){
hideSelectedCell = true
}
// 2: unhide selected cell after tranisition snapshot is taken
func tranisitionCleanup(){
hideSelectedCell = false
}
// 3: return window frame of selected image
func imageWindowFrame() -> CGRect{
let attributes = collectionView.layoutAttributesForItem(at: selectedIndexPath)
let cellRect = attributes!.frame
return collectionView.convert(cellRect, to: nil)
}
}
| 46.282051 | 156 | 0.552108 |
71cbf1c7395e36b8f2619aade0ac93431a055981 | 3,252 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import BitByteData
import Foundation
/// Represents the header of a Zlib archive.
public struct ZlibHeader {
/// Levels of compression which can be used to create Zlib archive.
public enum CompressionLevel: Int {
/// Fastest algorithm.
case fastestAlgorithm = 0
/// Fast algorithm.
case fastAlgorithm = 1
/// Default algorithm.
case defaultAlgorithm = 2
/// Slowest algorithm but with maximum compression.
case slowAlgorithm = 3
}
/// Compression method of archive. Always `.deflate` for Zlib archives.
public let compressionMethod: CompressionMethod = .deflate
/// Level of compression used in archive.
public let compressionLevel: CompressionLevel
/// Size of 'window': moving interval of data which was used to make archive.
public let windowSize: Int
/**
Initializes the structure with the values from Zlib `archive`.
If data passed is not actually a Zlib archive, `ZlibError` will be thrown.
- Parameter archive: Data archived with zlib.
- Throws: `ZlibError`. It may indicate that either archive is damaged or it might not be archived with Zlib at all.
*/
public init(archive data: Data) throws {
let reader = LsbBitReader(data: data)
try self.init(reader)
}
init(_ reader: LsbBitReader) throws {
// Valid Zlib header must contain at least 2 bytes of data.
guard reader.bytesLeft >= 2
else { throw ZlibError.wrongCompressionMethod }
// compressionMethod and compressionInfo combined are needed later for integrity check.
let cmf = reader.byte()
// First four bits are compression method.
// Only compression method = 8 (DEFLATE) is supported.
let compressionMethod = cmf & 0xF
guard compressionMethod == 8
else { throw ZlibError.wrongCompressionMethod }
// Remaining four bits indicate window size.
// For Deflate it must not be more than 7.
let compressionInfo = (cmf & 0xF0) >> 4
guard compressionInfo <= 7
else { throw ZlibError.wrongCompressionInfo }
let windowSize = 1 << (compressionInfo.toInt() + 8)
self.windowSize = windowSize
// fcheck, fdict and compresionLevel together make flags byte which is used in integrity check.
let flags = reader.byte()
// First five bits are fcheck bits which are used for integrity check:
// let fcheck = flags & 0x1F
// Sixth bit indicate if archive contain Adler-32 checksum of preset dictionary.
let fdict = (flags & 0x20) >> 5
// Remaining bits indicate compression level.
guard let compressionLevel = ZlibHeader.CompressionLevel(rawValue: (flags.toInt() & 0xC0) >> 6)
else { throw ZlibError.wrongCompressionLevel }
self.compressionLevel = compressionLevel
guard (UInt(cmf) * 256 + UInt(flags)) % 31 == 0
else { throw ZlibError.wrongFcheck }
// If preset dictionary is present 4 bytes will be skipped.
if fdict == 1 {
reader.offset += 4
}
}
}
| 35.736264 | 120 | 0.656827 |
674bf3415e4f8c0604655af6ed7e4ede7ca444bc | 1,334 | import XCTest
@testable import RImageAnnotation
class ApplySelectionToImageTests: XCTestCase {
var applySelectionToImage: ApplySelectionToImage!
var session: ImageAnnotatingSession!
override func setUpWithError() throws {
session = ImageAnnotatingSession()
applySelectionToImage = ApplySelectionToImage(imageAnnotatingSession: session)
}
func test_applySelection() {
let coordinates = NSRect.zero
let url = createRandomURL()
let label = UUID().uuidString
applySelectionToImage.applySelection(inImageCoordinates: coordinates, to: url, label: label)
XCTAssertEqual(1, session.annotationList.count)
XCTAssertEqual(url, session.annotationList.first!.imageURL)
XCTAssertEqual(label, session.annotationList.first!.label)
}
func test_replaceOldAnnotation_whenAddAnnotation() {
let coordinates = NSRect.zero
let url = createRandomURL()
var label = UUID().uuidString
applySelectionToImage.applySelection(inImageCoordinates: coordinates, to: url, label: label)
label = UUID().uuidString
applySelectionToImage.applySelection(inImageCoordinates: coordinates, to: url, label: label)
XCTAssertEqual(label, session.annotationList.first!.label)
}
}
| 35.105263 | 100 | 0.707646 |
8f075d0299057cf1b0ada5304a62b7da363c80f9 | 20,585 | //
// PXReviewViewController.swift
// MercadoPagoSDK
//
// Created by Demian Tejo on 27/2/18.
// Copyright © 2018 MercadoPago. All rights reserved.
//
import UIKit
class PXReviewViewController: PXComponentContainerViewController {
var footerView: UIView!
var floatingButtonView: UIView!
// MARK: Definitions
var termsConditionView: PXTermsAndConditionView!
var discountTermsConditionView: PXTermsAndConditionView?
lazy var itemViews = [UIView]()
private var viewModel: PXReviewViewModel!
var callbackPaymentData: ((PXPaymentData) -> Void)
var callbackConfirm: ((PXPaymentData) -> Void)
var finishButtonAnimation: (() -> Void)
var changePayerInformation: ((PXPaymentData) -> Void)
weak var loadingButtonComponent: PXAnimatedButton?
weak var loadingFloatingButtonComponent: PXAnimatedButton?
let timeOutPayButton: TimeInterval
let shouldAnimatePayButton: Bool
private let SHADOW_DELTA: CGFloat = 1
private var DID_ENTER_DYNAMIC_VIEW_CONTROLLER_SHOWED: Bool = false
internal var changePaymentMethodCallback: (() -> Void)?
// MARK: Lifecycle - Publics
init(viewModel: PXReviewViewModel, timeOutPayButton: TimeInterval = 15, shouldAnimatePayButton: Bool, callbackPaymentData : @escaping ((PXPaymentData) -> Void), callbackConfirm: @escaping ((PXPaymentData) -> Void), finishButtonAnimation: @escaping (() -> Void), changePayerInformation: @escaping ((PXPaymentData) -> Void)) {
self.viewModel = viewModel
self.callbackPaymentData = callbackPaymentData
self.callbackConfirm = callbackConfirm
self.finishButtonAnimation = finishButtonAnimation
self.changePayerInformation = changePayerInformation
self.timeOutPayButton = timeOutPayButton
self.shouldAnimatePayButton = shouldAnimatePayButton
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !DID_ENTER_DYNAMIC_VIEW_CONTROLLER_SHOWED {
trackScreen(path: TrackingPaths.Screens.getReviewAndConfirmPath(), properties: viewModel.getScreenProperties())
if let dynamicViewController = self.viewModel.getDynamicViewController() {
self.present(dynamicViewController, animated: true) { [weak self] in
self?.DID_ENTER_DYNAMIC_VIEW_CONTROLLER_SHOWED = true
}
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupUI()
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.showsHorizontalScrollIndicator = false
self.view.layoutIfNeeded()
self.checkFloatingButtonVisibility()
scrollView.isScrollEnabled = true
view.isUserInteractionEnabled = true
// Temporary fix for MP/Meli UX incompatibility
UIApplication.shared.statusBarStyle = .default
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if shouldAnimatePayButton {
unsubscribeFromNotifications()
showNavBarForAnimation()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
loadingButtonComponent?.resetButton()
loadingFloatingButtonComponent?.resetButton()
}
func update(viewModel: PXReviewViewModel) {
self.viewModel = viewModel
}
}
// MARK: UI Methods
extension PXReviewViewController {
private func setupUI() {
navBarTextColor = ThemeManager.shared.getTitleColorForReviewConfirmNavigation()
loadMPStyles()
navigationController?.navigationBar.barTintColor = ThemeManager.shared.highlightBackgroundColor()
navigationItem.leftBarButtonItem?.tintColor = ThemeManager.shared.getTitleColorForReviewConfirmNavigation()
if contentView.getSubviews().isEmpty {
HtmlStorage.shared.clean()
renderViews()
}
}
private func renderViews() {
unsubscribeFromNotifications()
self.contentView.prepareForRender()
// Add title view.
let titleView = getTitleComponentView()
contentView.addSubview(titleView)
PXLayout.pinTop(view: titleView).isActive = true
PXLayout.centerHorizontally(view: titleView).isActive = true
PXLayout.matchWidth(ofView: titleView).isActive = true
// Add summary view.
let summaryView = getSummaryComponentView()
contentView.addSubviewToBottom(summaryView)
PXLayout.centerHorizontally(view: summaryView).isActive = true
PXLayout.matchWidth(ofView: summaryView).isActive = true
// Payer info
if self.viewModel.shouldShowPayer() {
if let payerView = getPayerComponentView() {
contentView.addSubviewToBottom(payerView)
PXLayout.centerHorizontally(view: payerView).isActive = true
PXLayout.matchWidth(ofView: payerView).isActive = true
}
}
// Add CFT view.
if let cftView = getCFTComponentView() {
contentView.addSubviewToBottom(cftView)
PXLayout.centerHorizontally(view: cftView).isActive = true
PXLayout.matchWidth(ofView: cftView).isActive = true
}
// Add discount terms and conditions.
if self.viewModel.shouldShowDiscountTermsAndCondition() {
let discountTCView = viewModel.getDiscountTermsAndConditionView()
discountTermsConditionView = discountTCView
discountTCView.addSeparatorLineToBottom(height: 1, horizontalMarginPercentage: 100)
contentView.addSubviewToBottom(discountTCView)
PXLayout.matchWidth(ofView: discountTCView).isActive = true
PXLayout.centerHorizontally(view: discountTCView).isActive = true
discountTCView.delegate = self
}
// Add item views
itemViews = buildItemComponentsViews()
for itemView in itemViews {
contentView.addSubviewToBottom(itemView)
PXLayout.centerHorizontally(view: itemView).isActive = true
PXLayout.matchWidth(ofView: itemView).isActive = true
itemView.addSeparatorLineToBottom(height: 1)
}
// Top Dynamic Custom Views
if let topDynamicCustomViews = getTopDynamicCustomViews() {
for customView in topDynamicCustomViews {
customView.addSeparatorLineToBottom(height: 1)
customView.clipsToBounds = true
contentView.addSubviewToBottom(customView)
PXLayout.matchWidth(ofView: customView).isActive = true
PXLayout.centerHorizontally(view: customView).isActive = true
}
}
// Top Custom View
if let topCustomView = getTopCustomView() {
topCustomView.addSeparatorLineToBottom(height: 1)
topCustomView.clipsToBounds = true
contentView.addSubviewToBottom(topCustomView)
PXLayout.matchWidth(ofView: topCustomView).isActive = true
PXLayout.centerHorizontally(view: topCustomView).isActive = true
}
// Add payment method view.
if let paymentMethodView = getPaymentMethodComponentView() {
paymentMethodView.addSeparatorLineToBottom(height: 1)
contentView.addSubviewToBottom(paymentMethodView)
PXLayout.matchWidth(ofView: paymentMethodView).isActive = true
PXLayout.centerHorizontally(view: paymentMethodView).isActive = true
}
// Bottom Dynamic Custom Views
if let bottomDynamicCustomViews = getBottomDynamicCustomViews() {
for customView in bottomDynamicCustomViews {
customView.addSeparatorLineToBottom(height: 1)
customView.clipsToBounds = true
contentView.addSubviewToBottom(customView)
PXLayout.matchWidth(ofView: customView).isActive = true
PXLayout.centerHorizontally(view: customView).isActive = true
}
}
// Bottom Custom View
if let bottomCustomView = getBottomCustomView() {
bottomCustomView.addSeparatorLineToBottom(height: 1)
bottomCustomView.clipsToBounds = true
contentView.addSubviewToBottom(bottomCustomView)
PXLayout.matchWidth(ofView: bottomCustomView).isActive = true
PXLayout.centerHorizontally(view: bottomCustomView).isActive = true
}
// Add terms and conditions.
if viewModel.shouldShowTermsAndCondition() {
termsConditionView = getTermsAndConditionView()
contentView.addSubview(termsConditionView)
PXLayout.matchWidth(ofView: termsConditionView).isActive = true
PXLayout.centerHorizontally(view: termsConditionView).isActive = true
contentView.addSubviewToBottom(termsConditionView)
termsConditionView.delegate = self
}
//Add Footer
footerView = getFooterView()
footerView.backgroundColor = .clear
contentView.addSubviewToBottom(footerView)
PXLayout.matchWidth(ofView: footerView).isActive = true
PXLayout.centerHorizontally(view: footerView, to: contentView).isActive = true
self.view.layoutIfNeeded()
PXLayout.setHeight(owner: footerView, height: viewModel.getFloatingConfirmViewHeight() + SHADOW_DELTA).isActive = true
footerView.layoutIfNeeded()
// Add floating button
floatingButtonView = getFloatingButtonView()
view.addSubview(floatingButtonView)
PXLayout.setHeight(owner: floatingButtonView, height: viewModel.getFloatingConfirmViewHeight()).isActive = true
PXLayout.matchWidth(ofView: floatingButtonView).isActive = true
PXLayout.centerHorizontally(view: floatingButtonView).isActive = true
PXLayout.pinBottom(view: floatingButtonView, to: view, withMargin: 0).isActive = true
floatingButtonView.layoutIfNeeded()
contentView.backgroundColor = ThemeManager.shared.detailedBackgroundColor()
scrollView.backgroundColor = ThemeManager.shared.detailedBackgroundColor()
// Add elastic header.
addElasticHeader(headerBackgroundColor: summaryView.backgroundColor, navigationCustomTitle: PXReviewTitleComponentProps.DEFAULT_TITLE.localized, textColor: ThemeManager.shared.getTitleColorForReviewConfirmNavigation())
self.view.layoutIfNeeded()
PXLayout.pinFirstSubviewToTop(view: self.contentView)?.isActive = true
PXLayout.pinLastSubviewToBottom(view: self.contentView)?.isActive = true
self.scrollViewPinBottomConstraint.constant = 0
super.refreshContentViewSize()
self.checkFloatingButtonVisibility()
}
}
// MARK: Component Builders
extension PXReviewViewController {
private func buildItemComponentsViews() -> [UIView] {
var itemViews = [UIView]()
let itemComponents = viewModel.buildItemComponents()
for items in itemComponents {
itemViews.append(items.render())
}
return itemViews
}
private func isConfirmButtonVisible() -> Bool {
guard let floatingButton = self.floatingButtonView, let fixedButton = self.footerView else {
return false
}
let floatingButtonCoordinates = floatingButton.convert(CGPoint.zero, from: self.view.window)
let fixedButtonCoordinates = fixedButton.convert(CGPoint.zero, from: self.view.window)
return fixedButtonCoordinates.y > floatingButtonCoordinates.y
}
private func getPaymentMethodComponentView() -> UIView? {
let action = PXAction(label: "review_change_payment_method_action".localized, action: { [weak self] in
if let reviewViewModel = self?.viewModel {
self?.trackEvent(path: TrackingPaths.Events.ReviewConfirm.getChangePaymentMethodPath())
if let callBackAction = self?.changePaymentMethodCallback {
PXNotificationManager.UnsuscribeTo.attemptToClose(MercadoPagoCheckout.currentCheckout as Any)
callBackAction()
} else {
self?.callbackPaymentData(reviewViewModel.getClearPaymentData())
}
}
})
if let paymentMethodComponent = viewModel.buildPaymentMethodComponent(withAction: action) {
return paymentMethodComponent.render()
}
return nil
}
private func getSummaryComponentView() -> UIView {
let summaryComponent = viewModel.buildSummaryComponent(width: PXLayout.getScreenWidth())
let summaryView = summaryComponent.render()
return summaryView
}
fileprivate func getPayerComponentView() -> UIView? {
if let payerComponent = viewModel.buildPayerComponent() {
let payerView = payerComponent.render()
return payerView
}
return nil
}
private func getTitleComponentView() -> UIView {
let titleComponent = viewModel.buildTitleComponent()
return titleComponent.render()
}
private func getCFTComponentView() -> UIView? {
if viewModel.hasPayerCostAddionalInfo() {
let cftView = PXCFTComponentView(withCFTValue: self.viewModel.amountHelper.getPaymentData().payerCost?.getCFTValue(), titleColor: ThemeManager.shared.labelTintColor(), backgroundColor: ThemeManager.shared.highlightBackgroundColor())
return cftView
}
return nil
}
private func getFloatingButtonView() -> PXContainedActionButtonView {
let component = PXContainedActionButtonComponent(props: PXContainedActionButtonProps(title: "Pagar".localized, action: {
guard let targetButton = self.loadingFloatingButtonComponent else { return }
self.confirmPayment(targetButton)
}, animationDelegate: self, termsInfo: self.viewModel.creditsTermsAndConditions()), termsDelegate: self)
let containedButtonView = PXContainedActionButtonRenderer(termsDelegate: self).render(component)
loadingFloatingButtonComponent = containedButtonView.button
loadingFloatingButtonComponent?.layer.cornerRadius = 4
containedButtonView.backgroundColor = ThemeManager.shared.detailedBackgroundColor()
return containedButtonView
}
private func getFooterView() -> UIView {
let payAction = PXAction(label: "Pagar".localized) {
guard let targetButton = self.loadingButtonComponent else { return }
self.confirmPayment(targetButton)
}
let footerProps = PXFooterProps(buttonAction: payAction, animationDelegate: self, pinLastSubviewToBottom: false, termsInfo: self.viewModel.creditsTermsAndConditions())
let footerComponent = PXFooterComponent(props: footerProps)
let footerView = PXFooterRenderer(termsDelegate: self).render(footerComponent)
loadingButtonComponent = footerView.principalButton
loadingButtonComponent?.layer.cornerRadius = 4
footerView.backgroundColor = .clear
return footerView
}
private func getTermsAndConditionView() -> PXTermsAndConditionView {
let termsAndConditionView = PXTermsAndConditionView()
return termsAndConditionView
}
private func getTopDynamicCustomViews() -> [UIView]? {
return viewModel.buildTopDynamicCustomViews()
}
private func getBottomDynamicCustomViews() -> [UIView]? {
return viewModel.buildBottomDynamicCustomViews()
}
private func getTopCustomView() -> UIView? {
return viewModel.buildTopCustomView()
}
private func getBottomCustomView() -> UIView? {
return viewModel.buildBottomCustomView()
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
let loadingButtonAnimated = loadingButtonComponent?.isAnimated() ?? false
let loadingFloatingButtonAnimated = loadingFloatingButtonComponent?.isAnimated() ?? false
if !loadingButtonAnimated && !loadingFloatingButtonAnimated {
self.checkFloatingButtonVisibility()
}
}
func checkFloatingButtonVisibility() {
if !isConfirmButtonVisible() {
self.floatingButtonView.alpha = 1
self.footerView?.alpha = 0
} else {
self.floatingButtonView.alpha = 0
self.footerView?.alpha = 1
}
}
}
// MARK: Actions.
extension PXReviewViewController: PXTermsAndConditionViewDelegate {
private func confirmPayment(_ targetButton: PXAnimatedButton) {
if viewModel.shouldValidateWithBiometric() {
let biometricModule = PXConfiguratorManager.biometricProtocol
biometricModule.validate(config: PXConfiguratorManager.biometricConfig, onSuccess: { [weak self] in
DispatchQueue.main.async {
self?.doPayment(targetButton)
}
}) { [weak self] error in
// User abort validation or validation fail.
self?.trackEvent(path: TrackingPaths.Events.getErrorPath())
}
} else {
self.doPayment(targetButton)
}
}
private func doPayment(_ targetButton: PXAnimatedButton) {
if shouldAnimatePayButton {
subscribeLoadingButtonToNotifications(loadingButton: targetButton)
targetButton.startLoading(timeOut: self.timeOutPayButton)
}
scrollView.isScrollEnabled = false
view.isUserInteractionEnabled = false
trackEvent(path: TrackingPaths.Events.ReviewConfirm.getConfirmPath(), properties: viewModel.getConfirmEventProperties())
self.hideBackButton()
self.callbackConfirm(self.viewModel.amountHelper.getPaymentData())
}
func resetButton() {
progressButtonAnimationTimeOut()
}
func shouldOpenTermsCondition(_ title: String, url: URL) {
let webVC = WebViewController(url: url, navigationBarTitle: title)
webVC.title = title
self.navigationController?.pushViewController(webVC, animated: true)
}
}
// MARK: Payment Button animation delegate
@available(iOS 9.0, *)
extension PXReviewViewController: PXAnimatedButtonDelegate {
func shakeDidFinish() {
showNavBarForAnimation()
displayBackButton()
scrollView.isScrollEnabled = true
view.isUserInteractionEnabled = true
unsubscribeFromNotifications()
UIView.animate(withDuration: 0.3, animations: {
self.loadingButtonComponent?.backgroundColor = ThemeManager.shared.getAccentColor()
self.loadingFloatingButtonComponent?.backgroundColor = ThemeManager.shared.getAccentColor()
})
}
func expandAnimationInProgress() {
if isNavBarHidden() {
UIView.animate(withDuration: 0.3, animations: {
self.navigationController?.isNavigationBarHidden = true
})
} else {
hideNavBarForAnimation()
}
}
func didFinishAnimation() {
self.finishButtonAnimation()
}
func progressButtonAnimationTimeOut() {
loadingButtonComponent?.resetButton()
loadingFloatingButtonComponent?.resetButton()
if isConfirmButtonVisible() {
loadingButtonComponent?.showErrorToast()
} else {
loadingFloatingButtonComponent?.showErrorToast()
}
// MARK: Uncomment for Shake button
// loadingFloatingButtonComponent?.shake()
// loadingButtonComponent?.shake()
}
func hideNavBarForAnimation() {
self.navigationController?.navigationBar.layer.zPosition = -1
}
func showNavBarForAnimation() {
self.navigationController?.navigationBar.layer.zPosition = 0
}
}
// MARK: Notifications
extension PXReviewViewController {
func subscribeLoadingButtonToNotifications(loadingButton: PXAnimatedButton?) {
guard let loadingButton = loadingButton else {
return
}
PXNotificationManager.SuscribeTo.animateButton(loadingButton, selector: #selector(loadingButton.animateFinish))
}
func unsubscribeFromNotifications() {
PXNotificationManager.UnsuscribeTo.animateButton(loadingButtonComponent)
PXNotificationManager.UnsuscribeTo.animateButton(loadingFloatingButtonComponent)
}
}
| 41.335341 | 328 | 0.689143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.