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
|
---|---|---|---|---|---|
ffdca1d2ac180f82f27becaf2b7b166590c5ac12 | 12,387 | //===-------------------- Syntax.swift - Syntax Protocol ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// A Syntax node represents a tree of nodes with tokens at the leaves.
/// Each node has accessors for its known children, and allows efficient
/// iteration over the children through its `children` property.
public protocol Syntax:
CustomStringConvertible, TextOutputStreamable {}
internal protocol _SyntaxBase: Syntax {
/// The type of sequence containing the indices of present children.
typealias PresentChildIndicesSequence =
LazyFilterSequence<Range<Int>>
/// The root of the tree this node is currently in.
var _root: SyntaxData { get } // Must be of type SyntaxData
/// The data backing this node.
/// - note: This is unowned, because the reference to the root data keeps it
/// alive. This means there is an implicit relationship -- the data
/// property must be a descendent of the root. This relationship must
/// be preserved in all circumstances where Syntax nodes are created.
var _data: SyntaxData { get }
#if DEBUG
func validate()
#endif
}
extension _SyntaxBase {
public func validate() {
// This is for implementers to override to perform structural validation.
}
}
extension Syntax {
var data: SyntaxData {
guard let base = self as? _SyntaxBase else {
fatalError("only first-class syntax nodes can conform to Syntax")
}
return base._data
}
var _root: SyntaxData {
guard let base = self as? _SyntaxBase else {
fatalError("only first-class syntax nodes can conform to Syntax")
}
return base._root
}
/// Access the raw syntax assuming the node is a Syntax.
var raw: RawSyntax {
return data.raw
}
/// An iterator over children of this node.
public var children: SyntaxChildren {
return SyntaxChildren(node: self)
}
/// The number of children, `present` or `missing`, in this node.
/// This value can be used safely with `child(at:)`.
public var numberOfChildren: Int {
return data.childCaches.count
}
/// Whether or not this node is marked as `present`.
public var isPresent: Bool {
return raw.isPresent
}
/// Whether or not this node is marked as `missing`.
public var isMissing: Bool {
return raw.isMissing
}
/// Whether or not this node represents an Expression.
public var isExpr: Bool {
return raw.kind.isExpr
}
/// Whether or not this node represents a Declaration.
public var isDecl: Bool {
return raw.kind.isDecl
}
/// Whether or not this node represents a Statement.
public var isStmt: Bool {
return raw.kind.isStmt
}
/// Whether or not this node represents a Type.
public var isType: Bool {
return raw.kind.isType
}
/// Whether or not this node represents a Pattern.
public var isPattern: Bool {
return raw.kind.isPattern
}
/// The parent of this syntax node, or `nil` if this node is the root.
public var parent: Syntax? {
guard let parentData = data.parent else { return nil }
return makeSyntax(root: _root, data: parentData)
}
/// The index of this node in the parent's children.
public var indexInParent: Int {
return data.indexInParent
}
/// The absolute position of the starting point of this node. If the first token
/// is with leading trivia, the position points to the start of the leading
/// trivia.
public var position: AbsolutePosition {
return data.position
}
/// The absolute position of the starting point of this node, skipping any
/// leading trivia attached to the first token syntax.
public var positionAfterSkippingLeadingTrivia: AbsolutePosition {
return data.positionAfterSkippingLeadingTrivia
}
/// The textual byte length of this node including leading and trailing trivia.
public var byteSize: Int {
return data.byteSize
}
/// The leading trivia of this syntax node. Leading trivia is attached to
/// the first token syntax contained by this node. Without such token, this
/// property will return nil.
public var leadingTrivia: Trivia? {
return raw.leadingTrivia
}
/// The trailing trivia of this syntax node. Trailing trivia is attached to
/// the last token syntax contained by this node. Without such token, this
/// property will return nil.
public var trailingTrivia: Trivia? {
return raw.trailingTrivia
}
/// When isImplicit is true, the syntax node doesn't include any
/// underlying tokens, e.g. an empty CodeBlockItemList.
public var isImplicit: Bool {
return leadingTrivia == nil
}
/// The textual byte length of this node exluding leading and trailing trivia.
public var byteSizeAfterTrimmingTrivia: Int {
return data.byteSize - (leadingTrivia?.byteSize ?? 0) -
(trailingTrivia?.byteSize ?? 0)
}
/// The root of the tree in which this node resides.
public var root: Syntax {
return makeSyntax(root: _root, data: _root)
}
/// The sequence of indices that correspond to child nodes that are not
/// missing.
///
/// This property is an implementation detail of `SyntaxChildren`.
internal var presentChildIndices: _SyntaxBase.PresentChildIndicesSequence {
return raw.layout.indices.lazy.filter {
self.raw.layout[$0]?.isPresent == true
}
}
/// Gets the child at the provided index in this node's children.
/// - Parameter index: The index of the child node you're looking for.
/// - Returns: A Syntax node for the provided child, or `nil` if there
/// is not a child at that index in the node.
public func child(at index: Int) -> Syntax? {
guard raw.layout.indices.contains(index) else { return nil }
guard let childData = data.cachedChild(at: index) else { return nil }
return makeSyntax(root: _root, data: childData)
}
/// A source-accurate description of this node.
public var description: String {
var s = ""
self.write(to: &s)
return s
}
/// Prints the raw value of this node to the provided stream.
/// - Parameter stream: The stream to which to print the raw tree.
public func write<Target>(to target: inout Target)
where Target: TextOutputStream {
data.raw.write(to: &target)
}
/// The starting location, in the provided file, of this Syntax node.
/// - Parameters:
/// - file: The file URL this node resides in.
/// - afterLeadingTrivia: Whether to skip leading trivia when getting
/// the node's location. Defaults to `true`.
public func startLocation(
in file: URL,
afterLeadingTrivia: Bool = true
) -> SourceLocation {
let pos = afterLeadingTrivia ?
data.position.copy() :
data.positionAfterSkippingLeadingTrivia.copy()
return SourceLocation(file: file.path, position: pos)
}
/// The ending location, in the provided file, of this Syntax node.
/// - Parameters:
/// - file: The file URL this node resides in.
/// - afterTrailingTrivia: Whether to skip trailing trivia when getting
/// the node's location. Defaults to `false`.
public func endLocation(
in file: URL,
afterTrailingTrivia: Bool = false
) -> SourceLocation {
let pos = data.position.copy()
raw.accumulateAbsolutePosition(pos)
if afterTrailingTrivia {
raw.accumulateTrailingTrivia(pos)
}
return SourceLocation(file: file.path, position: pos)
}
/// The source range, in the provided file, of this Syntax node.
/// - Parameters:
/// - file: The file URL this node resides in.
/// - afterLeadingTrivia: Whether to skip leading trivia when getting
/// the node's start location. Defaults to `true`.
/// - afterTrailingTrivia: Whether to skip trailing trivia when getting
/// the node's end location. Defaults to `false`.
public func sourceRange(
in file: URL,
afterLeadingTrivia: Bool = true,
afterTrailingTrivia: Bool = false
) -> SourceRange {
let start = startLocation(in: file, afterLeadingTrivia: afterLeadingTrivia)
let end = endLocation(in: file, afterTrailingTrivia: afterTrailingTrivia)
return SourceRange(start: start, end: end)
}
}
/// Determines if two nodes are equal to each other.
public func ==(lhs: Syntax, rhs: Syntax) -> Bool {
return lhs.data === rhs.data
}
/// MARK: - Nodes
/// A Syntax node representing a single token.
public struct TokenSyntax: _SyntaxBase, Hashable {
let _root: SyntaxData
unowned let _data: SyntaxData
/// Creates a Syntax node from the provided root and data.
internal init(root: SyntaxData, data: SyntaxData) {
self._root = root
self._data = data
#if DEBUG
validate()
#endif
}
/// The text of the token as written in the source code.
public var text: String {
return tokenKind.text
}
/// Returns a new TokenSyntax with its kind replaced
/// by the provided token kind.
public func withKind(_ tokenKind: TokenKind) -> TokenSyntax {
guard raw.kind == .token else {
fatalError("TokenSyntax must have token as its raw")
}
let newRaw = RawSyntax(kind: tokenKind, leadingTrivia: raw.leadingTrivia!,
trailingTrivia: raw.trailingTrivia!,
presence: raw.presence)
let (root, newData) = data.replacingSelf(newRaw)
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its leading trivia replaced
/// by the provided trivia.
public func withLeadingTrivia(_ leadingTrivia: Trivia) -> TokenSyntax {
guard raw.kind == .token else {
fatalError("TokenSyntax must have token as its raw")
}
let newRaw = RawSyntax(kind: raw.tokenKind!, leadingTrivia: leadingTrivia,
trailingTrivia: raw.trailingTrivia!,
presence: raw.presence)
let (root, newData) = data.replacingSelf(newRaw)
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its trailing trivia replaced
/// by the provided trivia.
public func withTrailingTrivia(_ trailingTrivia: Trivia) -> TokenSyntax {
guard raw.kind == .token else {
fatalError("TokenSyntax must have token as its raw")
}
let newRaw = RawSyntax(kind: raw.tokenKind!,
leadingTrivia: raw.leadingTrivia!,
trailingTrivia: trailingTrivia,
presence: raw.presence)
let (root, newData) = data.replacingSelf(newRaw)
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its leading trivia removed.
public func withoutLeadingTrivia() -> TokenSyntax {
return withLeadingTrivia([])
}
/// Returns a new TokenSyntax with its trailing trivia removed.
public func withoutTrailingTrivia() -> TokenSyntax {
return withTrailingTrivia([])
}
/// Returns a new TokenSyntax with all trivia removed.
public func withoutTrivia() -> TokenSyntax {
return withoutLeadingTrivia().withoutTrailingTrivia()
}
/// The leading trivia (spaces, newlines, etc.) associated with this token.
public var leadingTrivia: Trivia {
guard raw.kind == .token else {
fatalError("TokenSyntax must have token as its raw")
}
return raw.leadingTrivia!
}
/// The trailing trivia (spaces, newlines, etc.) associated with this token.
public var trailingTrivia: Trivia {
guard raw.kind == .token else {
fatalError("TokenSyntax must have token as its raw")
}
return raw.trailingTrivia!
}
/// The kind of token this node represents.
public var tokenKind: TokenKind {
guard raw.kind == .token else {
fatalError("TokenSyntax must have token as its raw")
}
return raw.tokenKind!
}
public static func ==(lhs: TokenSyntax, rhs: TokenSyntax) -> Bool {
return lhs._data === rhs._data
}
public var hashValue: Int {
return ObjectIdentifier(_data).hashValue
}
}
| 33.478378 | 82 | 0.675143 |
03af5ba0fe05a9c5647a9cf6b4091c1f86ca9168 | 5,592 | // RUN: %target-swift-frontend -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
func modify<T>(_ x: inout T) {}
public struct S {
var i: Int
var o: AnyObject?
}
// CHECK-LABEL: sil hidden [noinline] @_T017access_marker_gen5initSAA1SVyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> @owned S {
// CHECK: bb0(%0 : @owned $Optional<AnyObject>):
// CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S }
// CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0
// CHECK: cond_br %{{.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS1]] : $*S
// CHECK: end_access [[ACCESS1]] : $*S
// CHECK: bb2:
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS2]] : $*S
// CHECK: end_access [[ACCESS2]] : $*S
// CHECK: bb3:
// CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S
// CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S
// CHECK: end_access [[ACCESS3]] : $*S
// CHECK: return [[RET]] : $S
// CHECK-LABEL: } // end sil function '_T017access_marker_gen5initSAA1SVyXlSgF'
@inline(never)
func initS(_ o: AnyObject?) -> S {
var s: S
if o == nil {
s = S(i: 0, o: nil)
} else {
s = S(i: 1, o: o)
}
return s
}
@inline(never)
func takeS(_ s: S) {}
// CHECK-LABEL: sil @_T017access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0
// CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S
// CHECK: %[[ADDRI:.*]] = struct_element_addr %15 : $*S, #S.i
// CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int
// CHECK: end_access %[[ACCESS1]] : $*S
// CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S
// CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S
// CHECK: end_access %[[ACCESS2]] : $*S
// CHECK-LABEL: } // end sil function '_T017access_marker_gen14modifyAndReadSyyF'
public func modifyAndReadS() {
var s = initS(nil)
s.i = 42
takeS(s)
}
var global = S(i: 0, o: nil)
func readGlobal() -> AnyObject? {
return global.o
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen10readGlobalyXlSgyF
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_T017access_marker_gen6globalAA1SVvau :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]()
// CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S
// CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]]
// CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o
// CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]]
// CHECK-NEXT: end_access [[T2]]
// CHECK-NEXT: return [[T4]]
public struct HasTwoStoredProperties {
var f: Int = 7
var g: Int = 9
// CHECK-LABEL: sil hidden @_T017access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> ()
// CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g
// CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f
// CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties
mutating func noOverlapOnAssignFromPropToProp() {
f = g
}
}
class C {
final var x: Int = 0
}
func testClassInstanceProperties(c: C) {
let y = c.x
c.x = y
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen27testClassInstancePropertiesyAA1CC1c_tF :
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: assign [[Y]] to [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
class D {
var x: Int = 0
}
// materializeForSet callback
// CHECK-LABEL: sil private [transparent] @_T017access_marker_gen1DC1xSivmytfU_
// CHECK: end_unpaired_access [dynamic] %1 : $*Builtin.UnsafeValueBuffer
// materializeForSet
// CHECK-LABEL: sil hidden [transparent] @_T017access_marker_gen1DC1xSivm
// CHECK: [[T0:%.*]] = ref_element_addr %2 : $D, #D.x
// CHECK-NEXT: begin_unpaired_access [modify] [dynamic] [[T0]] : $*Int
func testDispatchedClassInstanceProperty(d: D) {
modify(&d.x)
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen35testDispatchedClassInstancePropertyyAA1DC1d_tF
// CHECK: [[D:%.*]] = begin_borrow %0 : $D
// CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1
// CHECK: apply [[METHOD]]({{.*}}, [[D]])
// CHECK-NOT: begin_access
// CHECK: end_borrow [[D]] from %0 : $D
| 40.521739 | 171 | 0.616237 |
8ad69bd843301d8ea5b46d29ddf2c66f889f68bd | 272 | //
// DataSourceType.swift
// RepositoryBrowser
//
// Created by DDragutan on 3/31/20.
// Copyright © 2020 DDragutan. All rights reserved.
//
import Foundation
enum DataSourceType {
case GitHub
/*
case BitBucket
case SourceForge
...
*/
}
| 14.315789 | 52 | 0.632353 |
1d004b964027f10a4ad1356f2f10e742dc150bad | 4,256 | //
// WelcomeView.swift
// Informant
//
// Created by Ty Irvine on 2021-07-13.
//
import SwiftUI
struct AuthAccessibilityView: View {
var body: some View {
// Main stack
VStack(alignment: .center) {
// Image
ComponentsWindowAppIcon()
// Welcome: Authorize Informant
Text(ContentManager.WelcomeLabels.authorizeInformant)
.WelcomeHeaderFont()
.fixedSize(horizontal: false, vertical: true)
Spacer().frame(height: 5)
// How to authorize
Text(ContentManager.WelcomeLabels.authorizeNeedPermission)
.Body()
Spacer().frame(height: Style.Padding.welcomeWindow)
// What to do about lock
VStack {
// Accessibility check
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionSystemPreferences, color: .blue)
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionSecurity, color: .blue)
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionPrivacy, color: .blue)
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionScrollAndClick, color: .blue)
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionCheckInformant, color: .blue)
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionAutomationCheckFinder, color: .blue)
SecurityGuidanceBox(label: ContentManager.WelcomeLabels.authorizedInstructionRestartInformant, color: .purple, arrow: false) {
NSApp.terminate(nil)
}
}
Spacer().frame(height: Style.Padding.welcomeWindow)
// Lock description
VStack(spacing: 10) {
Text(ContentManager.WelcomeLabels.authorizedInstructionClickLock)
.Body(size: 13, weight: .medium)
HStack {
Image(systemName: ContentManager.Icons.authLockIcon)
.font(.system(size: 13, weight: .semibold))
Image(systemName: ContentManager.Icons.rightArrowIcon)
.font(.system(size: 11, weight: .bold))
.opacity(0.7)
Image(systemName: ContentManager.Icons.authUnlockIcon)
.font(.system(size: 13, weight: .semibold))
}
.opacity(0.85)
}
.opacity(0.5)
}
.padding([.horizontal, .bottom], Style.Padding.welcomeWindow)
.frame(width: 350)
}
}
/// This is the little blue box that shows where the user should navigate to
struct SecurityGuidanceBox: View {
let label: String
let color: Color
let arrow: Bool
let action: (() -> Void)?
private let radius: CGFloat = 10.0
internal init(label: String, color: Color, arrow: Bool = true, action: (() -> Void)? = nil) {
self.label = label
self.color = color
self.arrow = arrow
self.action = action
}
var body: some View {
VStack {
// Label
if action == nil {
AuthInstructionBlurb(label, color, radius)
} else if let action = action {
AuthInstructionBlurb(label, color, radius, hover: true)
.onTapGesture {
action()
}
}
// Arrow
if arrow {
Image(systemName: ContentManager.Icons.downArrowIcon)
.font(.system(size: 12, weight: .bold, design: .rounded))
.opacity(0.15)
.padding([.vertical], 2)
}
}
}
}
/// This is the actual text blurb used in the AuthAccessibilityView
struct AuthInstructionBlurb: View {
let label: String
let color: Color
let hover: Bool
let radius: CGFloat
internal init(_ label: String, _ color: Color, _ radius: CGFloat, hover: Bool = false) {
self.label = label
self.color = color
self.radius = radius
self.hover = hover
}
@State private var isHovering = false
var body: some View {
Text(label)
.font(.system(size: 14))
.fontWeight(.semibold)
.lineSpacing(2)
.multilineTextAlignment(.center)
.foregroundColor(color)
.padding([.horizontal], 10)
.padding([.vertical], 6)
.background(
RoundedRectangle(cornerRadius: radius)
.fill(color)
.opacity(isHovering ? 0.25 : 0.1)
)
.overlay(
RoundedRectangle(cornerRadius: radius)
.stroke(color, lineWidth: 1)
.opacity(0.2)
)
.fixedSize(horizontal: false, vertical: true)
.whenHovered { hovering in
if hover {
isHovering = hovering
if hovering {
NSCursor.pointingHand.push()
} else {
NSCursor.pop()
}
}
}
.animation(.easeInOut, value: isHovering)
}
}
| 25.48503 | 130 | 0.694784 |
ac1a4791e5686e494835b0095c9cf20d0e873416 | 1,401 | //
// VCBaseVC.swift
// MVVMVideoChat
//
// Created by Tran Manh Quy on 7/23/18.
// Copyright © 2018 DepTrai. All rights reserved.
//
import UIKit
class VCBaseVC: UIViewController, VCNavigationVMProtocol {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
var vmNavigation: VCNavigationVM?
override func viewDidLoad() {
super.viewDidLoad()
setNeedsStatusBarAppearanceUpdate()
vmNavigation = VCNavigationVM(self)
title = self.objectName
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func open(vc: VCBaseVC) {
navigationController?.pushViewController(vc, animated: true)
}
func close(toRoot: Bool) {
if toRoot {
navigationController?.popToRootViewController(animated: true)
} else {
navigationController?.popViewController(animated: true)
}
}
func closeToVC(_ vc: VCBaseVC) {
navigationController?.popToViewController(vc, animated: true)
}
}
| 24.578947 | 103 | 0.741613 |
ffd9e789d878b2411ef796209f1c6b8f3908d5f4 | 1,044 | // Generated by msgbuilder 2020-05-15 06:20:49 +0000
import StdMsgs
extension sensor_msgs {
public struct Temperature: MessageWithHeader {
public static let md5sum: String = "ff71b307acdbe7c871a5a6d7ed359100"
public static let datatype = "sensor_msgs/Temperature"
public static let definition = """
# Single temperature reading.
Header header # timestamp is the time the temperature was measured
# frame_id is the location of the temperature reading
float64 temperature # Measurement of the Temperature in Degrees Celsius
float64 variance # 0 is interpreted as variance unknown
"""
public var header: std_msgs.Header
public var temperature: Float64
public var variance: Float64
public init(header: std_msgs.Header, temperature: Float64, variance: Float64) {
self.header = header
self.temperature = temperature
self.variance = variance
}
public init() {
header = std_msgs.Header()
temperature = Float64()
variance = Float64()
}
}
} | 30.705882 | 81 | 0.707854 |
795ddc3fd53db25ae44127d12b1a96ba8edeb4e2 | 1,366 | //
// Copyright (C) Posten Norge AS
//
// 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
extension UIScrollView{
var totalPageProgressInPercentage:CGFloat {
get {
let maxHorizontalOffset = self.contentSize.width - pageSize.width
let currentHorizontalOffset = self.contentOffset.x
return currentHorizontalOffset / maxHorizontalOffset
}
}
var pageProgressInPercentage:CGFloat {
get { return self.contentOffset.x / pageSize.width }
}
var pageSize:CGSize {
get { return self.frame.size }
}
var currentPage:Int {
get { return Int(floor((self.contentOffset.x * 2.0 + self.frame.width) / (self.frame.width * 2.0)))}
}
var scrollableEdgeOffset:CGFloat {
get { return self.frame.width / 3}
}
}
| 30.355556 | 108 | 0.670571 |
23f76c5f8a713b9d4ef8fb89433919a4f58cc472 | 612 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "SwiftShell",
products: [
.library(
name: "SwiftShell",
targets: ["SwiftShell"])
],
targets: [
.target(
name: "SwiftShell"),
.testTarget(
name: "SwiftShellTests",
dependencies: ["SwiftShell"]),
.testTarget(
name: "StreamTests",
dependencies: ["SwiftShell"]),
.testTarget(
name: "GeneralTests",
dependencies: ["SwiftShell"]),
],
swiftLanguageVersions: [4]
)
| 23.538462 | 42 | 0.514706 |
28eeeeb2f61ef483de33d21fca94f3fa1a773d24 | 448 | //
// Quickly
//
public extension CGRect {
public func lerp(_ to: CGRect, progress: CGFloat) -> CGRect {
return CGRect(
x: self.origin.x.lerp(to.origin.x, progress: progress),
y: self.origin.y.lerp(to.origin.y, progress: progress),
width: self.size.width.lerp(to.size.width, progress: progress),
height: self.size.height.lerp(to.size.height, progress: progress)
)
}
}
| 26.352941 | 77 | 0.595982 |
d9c9b565529a0e5b648a56dc427f7da4b8d48a0e | 801 | //
// HTTPVersion.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 6/29/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
public extension HTTP {
/// Defines the HTTP protocol version.
public struct Version {
public typealias ValueType = UInt8
/// Major version number.
public var major: ValueType
/// Minor version number.
public var minor: ValueType
/// Defualts to HTTP 1.1
public init(_ major: ValueType = 1, _ minor: ValueType = 1) {
self.major = major
self.minor = minor
}
}
}
public func == (lhs: HTTP.Version, rhs: HTTP.Version) -> Bool {
return lhs.major == rhs.major && lhs.minor == rhs.minor
}
| 22.25 | 69 | 0.559301 |
91ef6678ed2abd36d2263dadffa5193b470641bf | 950 | //
// WeakObject.swift
// HackerNews
//
// Created by Никита Васильев on 28.05.2020.
// Copyright © 2020 Никита Васильев. All rights reserved.
//
import Foundation
class WeakObject<T> where T: AnyObject {
// MARK: Private Properties
/// Identifier.
private let identifier: ObjectIdentifier
/// Wrapped object.
fileprivate(set) weak var object: T?
// MARK: Initialization
/// Create a new `WeakObject` instance.
///
/// - Parameter object: Wrapped object.
init(object: T) {
self.identifier = ObjectIdentifier(object)
self.object = object
}
}
// MARK: Equatable
extension WeakObject: Equatable {
static func == (lhs: WeakObject<T>, rhs: WeakObject<T>) -> Bool {
return lhs.identifier == rhs.identifier
}
}
// MARK: Hashable
extension WeakObject: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
}
| 21.111111 | 69 | 0.631579 |
d666e16abd81d4314e7e173093d44bd34de80062 | 1,416 | //
// AppDelegate.swift
// SampleApplication
//
// Created by Amir on 27/9/19.
// Copyright © 2019 Amir Kamali. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.263158 | 179 | 0.747881 |
16ce251562d3b37356740c9ab95cb2c51b9d5e3a | 981 | //
// SwiftHubTests.swift
// SwiftHubTests
//
// Created by Khoren Markosyan on 1/4/17.
// Copyright © 2017 Khoren Markosyan. All rights reserved.
//
import XCTest
@testable import SwiftHub
class SwiftHubTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.513514 | 111 | 0.636086 |
0e393714894abf0308231b798b4548b5e9f85bfa | 3,642 | //
// TCXCommonTests.swift
// TrackKit
//
// Created by Jelle Vandebeeck on 30/09/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TrackKit
class TCXCommonSpec: QuickSpec {
override func spec() {
var file: File!
describe("common data") {
beforeEach {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'>"
// Author
+ "<Author>"
+ "<Name>Jelle Vandebeeck</Name>"
+ "<Build>"
+ "<Version>"
+ "<VersionMajor>1</VersionMajor>"
+ "<VersionMinor>2</VersionMinor>"
+ "<BuildMajor>3</BuildMajor>"
+ "<BuildMinor>4</BuildMinor>"
+ "</Version>"
+ "</Build>"
+ "<LangID>en</LangID>"
+ "<PartNumber>000-00000-00</PartNumber>"
+ "</Author>"
+ "</TrainingCenterDatabase>"
let data = content.data(using: .utf8)
file = try! TrackParser(data: data, type: .tcx).parse()
}
context("metadata") {
it("should have an author name") {
expect(file.applicationAuthor?.name) == "Jelle Vandebeeck"
}
it("should have an author version number") {
expect(file.applicationAuthor?.version?.versionNumber) == "1.2"
}
it("should have an author build number") {
expect(file.applicationAuthor?.version?.buildNumber) == "3.4"
}
it("should have an author language") {
expect(file.applicationAuthor?.language) == "en"
}
it("should have an author part number") {
expect(file.applicationAuthor?.partNumber) == "000-00000-00"
}
}
context("empty file") {
beforeEach {
let content = "<TrainingCenterDatabase xmlns='http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'></TrainingCenterDatabase>"
let data = content.data(using: .utf8)
file = try! TrackParser(data: data, type: .tcx).parse()
}
context("metadata") {
it("should not have an author name") {
expect(file.applicationAuthor?.name).to(beNil())
}
it("should not have an author version number") {
expect(file.applicationAuthor?.version?.versionNumber).to(beNil())
}
it("should not have an author build number") {
expect(file.applicationAuthor?.version?.buildNumber).to(beNil())
}
it("should not have an author language") {
expect(file.applicationAuthor?.language).to(beNil())
}
it("should not have an author part number") {
expect(file.applicationAuthor?.partNumber).to(beNil())
}
}
}
}
}
}
| 39.16129 | 152 | 0.43575 |
e2623d4492b78fb02d2747564c26e7234dfdc2f6 | 581 | //
// APIClientImp.swift
// Swift-DI
//
// Created by Ilya Puchka on 28.02.16.
// Copyright © 2016 Ilay Puchka. All rights reserved.
//
import Foundation
class APIClientImp: NSObject, APIClient {
let baseURL: NSURL
let session: NetworkSession
var logger: Logger?
init(baseURL: NSURL, session: NetworkSession) {
self.baseURL = baseURL
self.session = session
}
func get(path: String) {
let request = session.request(baseURL, path: path)
let message = "GET \(request)"
logger?.log(message)
}
}
| 20.034483 | 58 | 0.619621 |
c1dacee574e62269d315711c24a0d60b74125d9c | 5,041 | /**
* (C) Copyright IBM Corp. 2018, 2019.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Information about the new custom acoustic model.
*/
internal struct CreateAcousticModel: Codable, Equatable {
/**
The name of the base language model that is to be customized by the new custom acoustic model. The new custom model
can be used only with the base model that it customizes.
To determine whether a base model supports acoustic model customization, refer to [Language support for
customization](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customization#languageSupport).
*/
public enum BaseModelName: String {
case arArBroadbandmodel = "ar-AR_BroadbandModel"
case deDeBroadbandmodel = "de-DE_BroadbandModel"
case deDeNarrowbandmodel = "de-DE_NarrowbandModel"
case enGbBroadbandmodel = "en-GB_BroadbandModel"
case enGbNarrowbandmodel = "en-GB_NarrowbandModel"
case enUsBroadbandmodel = "en-US_BroadbandModel"
case enUsNarrowbandmodel = "en-US_NarrowbandModel"
case enUsShortformNarrowbandmodel = "en-US_ShortForm_NarrowbandModel"
case esEsBroadbandmodel = "es-ES_BroadbandModel"
case esEsNarrowbandmodel = "es-ES_NarrowbandModel"
case frFrBroadbandmodel = "fr-FR_BroadbandModel"
case frFrNarrowbandmodel = "fr-FR_NarrowbandModel"
case jaJpBroadbandmodel = "ja-JP_BroadbandModel"
case jaJpNarrowbandmodel = "ja-JP_NarrowbandModel"
case koKrBroadbandmodel = "ko-KR_BroadbandModel"
case koKrNarrowbandmodel = "ko-KR_NarrowbandModel"
case ptBrBroadbandmodel = "pt-BR_BroadbandModel"
case ptBrNarrowbandmodel = "pt-BR_NarrowbandModel"
case zhCnBroadbandmodel = "zh-CN_BroadbandModel"
case zhCnNarrowbandmodel = "zh-CN_NarrowbandModel"
}
/**
A user-defined name for the new custom acoustic model. Use a name that is unique among all custom acoustic models
that you own. Use a localized name that matches the language of the custom model. Use a name that describes the
acoustic environment of the custom model, such as `Mobile custom model` or `Noisy car custom model`.
*/
public var name: String
/**
The name of the base language model that is to be customized by the new custom acoustic model. The new custom model
can be used only with the base model that it customizes.
To determine whether a base model supports acoustic model customization, refer to [Language support for
customization](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customization#languageSupport).
*/
public var baseModelName: String
/**
A description of the new custom acoustic model. Use a localized description that matches the language of the custom
model.
*/
public var description: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case baseModelName = "base_model_name"
case description = "description"
}
/**
Initialize a `CreateAcousticModel` with member variables.
- parameter name: A user-defined name for the new custom acoustic model. Use a name that is unique among all
custom acoustic models that you own. Use a localized name that matches the language of the custom model. Use a
name that describes the acoustic environment of the custom model, such as `Mobile custom model` or `Noisy car
custom model`.
- parameter baseModelName: The name of the base language model that is to be customized by the new custom
acoustic model. The new custom model can be used only with the base model that it customizes.
To determine whether a base model supports acoustic model customization, refer to [Language support for
customization](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customization#languageSupport).
- parameter description: A description of the new custom acoustic model. Use a localized description that
matches the language of the custom model.
- returns: An initialized `CreateAcousticModel`.
*/
public init(
name: String,
baseModelName: String,
description: String? = nil
)
{
self.name = name
self.baseModelName = baseModelName
self.description = description
}
}
| 46.247706 | 125 | 0.721285 |
0e3fe87dc75e1b1d97743b88dac434b1eb26b1c0 | 2,165 | import Foundation
public protocol MusicalElement {}
public protocol HasLength {
var length: NoteLength { get }
}
public protocol TupletMember : MusicalElement, HasLength {}
public protocol BeamMember: MusicalElement, HasLength {}
public enum Simple : MusicalElement {
case BarLine
case DoubleBarLine
case SlurStart
case SlurEnd
case RepeatStart
case RepeatEnd
case Tie
case Space
case LineBreak
case End
}
public struct Note : TupletMember, BeamMember, Equatable {
public let length: NoteLength
public let pitch: Pitch
public init(length: NoteLength, pitch: Pitch) {
self.length = length
self.pitch = pitch
}
}
public func ==(lhs: Note, rhs: Note) -> Bool {
return lhs.length == rhs.length &&
lhs.pitch == rhs.pitch
}
public struct Rest: TupletMember, BeamMember, Equatable {
public let length: NoteLength
public init(length: NoteLength) {
self.length = length
}
}
public func ==(lhs: Rest, rhs: Rest) -> Bool {
return lhs.length == rhs.length
}
public struct MultiMeasureRest : MusicalElement, Equatable {
public let num: Int
}
public func ==(lhs: MultiMeasureRest, rhs: MultiMeasureRest) -> Bool {
return lhs.num == rhs.num
}
public struct Chord : TupletMember, BeamMember, Equatable {
public let length: NoteLength
public let pitches: [Pitch]
public init(length: NoteLength, pitches: [Pitch]) {
self.length = length
self.pitches = pitches
}
}
public func ==(lhs: Chord, rhs: Chord) -> Bool {
return lhs.length == rhs.length &&
lhs.pitches == rhs.pitches
}
public struct VoiceId : MusicalElement, Equatable {
public let id: String
}
public func ==(lhs: VoiceId, rhs: VoiceId) -> Bool {
return lhs.id == rhs.id
}
public struct Tuplet : MusicalElement {
public let notes: Int
public let inTimeOf: Int?
private let defaultTime: Int = 3
public let elements: [TupletMember]
public var time: Int {
if let t = inTimeOf {
return t
} else {
switch notes {
case 2, 4, 8: return 3
case 3, 6: return 2
default: return self.defaultTime
}
}
}
public var ratio: Float {
return Float(time) / Float(notes)
}
}
| 21.435644 | 70 | 0.684065 |
28c08b77cce73edfe709b376973b9648798e21b0 | 1,018 | import Foundation
import Data
public struct RequestObjectClient: RequestObject {
let client: HttpClient
public init(client: HttpClient) {
self.client = client
}
public func fetch<T: Decodable>(with request: URLRequest, completion: @escaping (Result<T, RequestError>) -> Void) {
client.send(from: request) { (result) in
switch result {
case .success(let data):
guard let data = data else { return completion(.failure(.responseUnsuccessful)) }
guard let model: T = data.toModel() else { return completion(.failure(.jsonParsingFailure)) }
completion(.success(model))
case .failure:
completion(.failure(.requestFailed))
}
}
}
}
extension Data {
func toModel<T: Decodable>() -> T? {
do {
return try JSONDecoder().decode(T.self, from: self)
} catch {
print(error)
return nil
}
}
}
| 27.513514 | 120 | 0.562868 |
d65adec8c854a531234f43c9b3df2d3f4031fdfb | 337 | //
// DetailView.swift
// Health
//
// Created by Ma Fo on 05.08.21.
//
import SwiftUI
struct DetailView: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView()
}
}
| 16.047619 | 71 | 0.620178 |
76e353ee10e780b6127f49dc7dc352e770783ad8 | 789 |
/*
* The following code is auto generated using webidl2swift
*/
import JavaScriptKit
public enum NodeOrString: JSBridgedType, ExpressibleByStringLiteral {
case node(Node)
case string(String)
public init?(from value: JSValue) {
if let decoded: Node = value.fromJSValue() {
self = .node(decoded)
} else if let decoded: String = value.fromJSValue() {
self = .string(decoded)
} else {
return nil
}
}
public init(stringLiteral value: String) {
self = .string(value)
}
public var value: JSValue { jsValue() }
public func jsValue() -> JSValue {
switch self {
case let .node(v): return v.jsValue()
case let .string(v): return v.jsValue()
}
}
}
| 22.542857 | 69 | 0.585551 |
e626381f3d1e46c462fae4f0eddca1ab7db478f3 | 1,609 | // SwiftUIPlayground
// https://github.com/ralfebert/SwiftUIPlayground/
import SwiftUI
/// List of all the environment values: https://developer.apple.com/documentation/swiftui/environmentvalues
/// Custom environment keys: https://swiftwithmajid.com/2019/08/21/the-power-of-environment-in-swiftui/#custom-environment-keys
/// Custom editable environment keys like editMode: https://stackoverflow.com/a/61847419/128083
struct EnvironmentView: View {
@Environment(\.locale) var locale
@Environment(\.sizeCategory) var sizeCategory
@Environment(\.font) var font
@Environment(\.isEnabled) var isEnabled
@Environment(\.colorScheme) var colorScheme
@Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
var body: some View {
VStack(alignment: .leading) {
Text("Locale: \(String(describing: locale))")
Text("Size category: \(String(describing: sizeCategory))")
Text("horizontalSizeClass: \(String(describing: horizontalSizeClass))")
Text("verticalSizeClass: \(String(describing: horizontalSizeClass))")
Text("font: \(String(describing: font))")
Text("isEnabled: \(String(describing: isEnabled))")
Text("colorScheme: \(String(describing: colorScheme))")
Button("Example Button") {}
}
.environment(\.isEnabled, false)
}
}
struct EnvironmentView_Previews: PreviewProvider {
static var previews: some View {
EnvironmentView()
}
}
| 41.25641 | 127 | 0.698571 |
904bcb04cd20334b678aa2208d1ee6fab12721f1 | 507 | //
// ViewController.swift
// LSPhotoBrowser
//
// Created by Lin Sheng on 2018/4/8.
// Copyright © 2018年 linsheng. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.5 | 80 | 0.670611 |
e5c4466f9c06dfe6e67dfd49712b7e1a09a354a9 | 373 | //
// SafariWebExtensionHandler.swift
// Develop Menu Extension
//
// Created by Watanabe Toshinori on 2022/01/08.
//
import SafariServices
import os.log
class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
func beginRequest(with context: NSExtensionContext) {
context.completeRequest(returningItems: [], completionHandler: nil)
}
}
| 23.3125 | 75 | 0.756032 |
e2fa90b9cfb58dc3027fac6ee98ebb046aec089e | 561 | //
// ArtificialOpponent.swift
// SudoChess
//
// Created by Daniel Panzer on 10/23/19.
// Copyright © 2019 Daniel Panzer. All rights reserved.
//
import Foundation
public protocol ArtificialOpponent : class {
/// Displayed name of the AI
var name: String {get}
/// This method is called by the game when it needs the AI to decide the next move. Implement your decision making code here
/// - Parameter game: The current state of the game
/// - Returns: The AI's move decision
func nextMove(in game: Game) -> Move
}
| 25.5 | 128 | 0.672014 |
9056acf7208ea4445afe2eca4b59c3b47f139296 | 3,049 | //
// AppDelegate.swift
// Twitter
//
// Created by Fatama on 2/16/16.
// Copyright © 2016 Fatama Rahman. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard = UIStoryboard(name: "Main", bundle: nil)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: userDidLogoutNotification, object: nil)
if User.currentUser != nil {
// Go to the logged in screen
var vc = storyboard.instantiateViewControllerWithIdentifier("TweetsViewController")
window?.rootViewController = vc
}
return true
}
func userDidLogout() {
var vc = storyboard.instantiateInitialViewController()! as UIViewController
window?.rootViewController = vc
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
{
TwitterClient.sharedInstance.openURL(url)
return true
}
}
| 38.594937 | 285 | 0.711053 |
09eef9b69765003175e2647b5eb2898be378e3b3 | 3,288 | #if canImport(UIKit)
import UIKit
import Nimble
extension UIColor {
// MARK: - Instance Methods
func isEquivalent(to otherColor: UIColor) -> Bool {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
var otherRed: CGFloat = 0.0
var otherGreen: CGFloat = 0.0
var otherBlue: CGFloat = 0.0
var otherAlpha: CGFloat = 0.0
otherColor.getRed(&otherRed, green: &otherGreen, blue: &otherBlue, alpha: &otherAlpha)
guard Int(red * 255.0) == Int(otherRed * 255.0) else {
return false
}
guard Int(green * 255.0) == Int(otherGreen * 255.0) else {
return false
}
guard Int(blue * 255.0) == Int(otherBlue * 255.0) else {
return false
}
guard Int(alpha * 255.0) == Int(otherAlpha * 255.0) else {
return false
}
return true
}
}
// MARK: -
func beEquivalentTo(_ expectedColor: UIColor?) -> Predicate<UIColor> {
return Predicate.defineNilable("be equivalent to <\(stringify(expectedColor))>") { actualExpression, message in
let color = try actualExpression.evaluate()
switch (expectedColor, color) {
case (nil, nil):
return PredicateResult(bool: true, message: message)
case (nil, _?):
return PredicateResult(bool: false, message: message.appendedBeNilHint())
case (_?, nil):
return PredicateResult(bool: false, message: message)
case let (expectedColor?, color?):
return PredicateResult(bool: color.isEquivalent(to: expectedColor), message: message)
}
}
}
func beEquivalentTo(_ expectedColor: CGColor?) -> Predicate<UIColor> {
return Predicate.defineNilable("be equivalent to <\(stringify(expectedColor))>") { actualExpression, message in
let color = try actualExpression.evaluate()
switch (expectedColor, color) {
case (nil, nil):
return PredicateResult(bool: true, message: message)
case (nil, _?):
return PredicateResult(bool: false, message: message.appendedBeNilHint())
case (_?, nil):
return PredicateResult(bool: false, message: message)
case let (expectedColor?, color?):
return PredicateResult(bool: color.isEquivalent(to: UIColor(cgColor: expectedColor)), message: message)
}
}
}
func beEquivalentTo(_ expectedColor: UIColor?) -> Predicate<CGColor> {
return Predicate.defineNilable("be equivalent to <\(stringify(expectedColor))>") { actualExpression, message in
let color = try actualExpression.evaluate()
switch (expectedColor, color) {
case (nil, nil):
return PredicateResult(bool: true, message: message)
case (nil, _?):
return PredicateResult(bool: false, message: message.appendedBeNilHint())
case (_?, nil):
return PredicateResult(bool: false, message: message)
case let (expectedColor?, color?):
return PredicateResult(bool: UIColor(cgColor: color).isEquivalent(to: expectedColor), message: message)
}
}
}
#endif
| 31.018868 | 115 | 0.615268 |
502c8d00db8a89a2378d27ad63ca0381a7581fb7 | 1,318 | //
// ModelSql.swift
// chopchop
//
// Created by Maor Eini on 18/03/2017.
// Copyright © 2017 Maor Eini. All rights reserved.
//
import Foundation
extension String {
public init?(validatingUTF8 cString: UnsafePointer<UInt8>) {
if let (result, _) = String.decodeCString(cString, as: UTF8.self,
repairingInvalidCodeUnits: false) {
self = result
}
else {
return nil
}
}
}
class ModelSql{
var database: OpaquePointer? = nil
init?(){
let dbFileName = "database.db"
if let dir = FileManager.default.urls(for: .documentDirectory, in:
.userDomainMask).first{
let path = dir.appendingPathComponent(dbFileName)
if sqlite3_open(path.absoluteString, &database) != SQLITE_OK {
print("Failed to open db file: \(path.absoluteString)")
return nil
}
}
if User.createTable(database: database) == false{
return nil
}
if FeedItem.createTable(database: database) == false{
return nil
}
if LastUpdateTableService.createTable(database: database) == false{
return nil
}
}
}
| 25.346154 | 85 | 0.537936 |
b974ad769005482d97f8d4c4520f98e7e8364394 | 246 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
{ }
}
protocol a {
protocol a {
extension A {
func e {
class
case c,
let h
| 16.4 | 87 | 0.723577 |
cc8b6accafe5532a410b980dd36e4c8c96f1b278 | 1,340 | //
// AssetCell.swift
// AelfApp
//
// Created by 晋先森 on 2019/6/4.
// Copyright © 2019 AELF. All rights reserved.
//
import UIKit
class AssetCell: BaseTableCell {
@IBOutlet weak var iconImgView: UIImageView!
@IBOutlet weak var coinLabel: UILabel!
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var bottomLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
var item: AssetItem? {
didSet {
guard let item = item else { return }
coinLabel.text = item.symbol
if App.isPrivateMode {
topLabel.text = "*****"
bottomLabel.text = "*****" + " \(App.currency)"
}else {
topLabel.text = item.balance
bottomLabel.text = item.total().format(maxDigits: 8, mixDigits: 8) + " \(App.currency)"
}
if let url = URL(string: item.logo) {
self.iconImgView.setImage(with: url)
} else {
iconImgView.image = UIImage(named: "")
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 25.283019 | 103 | 0.543284 |
ef5c800ff86990e0c3d9395f0e12aa6ce246a9e9 | 8,066 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 Combine
/// The lifecycle stages of a router scope.
public enum RouterLifecycle {
/// Router did load.
case didLoad
}
/// The scope of a `Router`, defining various lifecycles of a `Router`.
public protocol RouterScope: AnyObject {
/// A publisher that emits values when the router scope reaches its corresponding life-cycle stages. This
/// publisher completes when the router scope is deallocated.
var lifecycle: AnyPublisher<RouterLifecycle, Never> { get }
}
/// The base protocol for all routers.
public protocol Routing: RouterScope {
// The following methods must be declared in the base protocol, since `Router` internally invokes these methods.
// In order to unit test router with a mock child router, the mocked child router first needs to conform to the
// custom subclass routing protocol, and also this base protocol to allow the `Router` implementation to execute
// base class logic without error.
/// The base interactable associated with this `Router`.
var interactable: Interactable { get }
/// The list of children routers of this `Router`.
var children: [Routing] { get }
/// Loads the `Router`.
///
/// - note: This method is internally used by the framework. Application code should never
/// invoke this method explicitly.
func load()
// We cannot declare the attach/detach child methods to take in concrete `Router` instances,
// since during unit testing, we need to use mocked child routers.
/// Attaches the given router as a child.
///
/// - parameter child: The child router to attach.
func attachChild(_ child: Routing)
/// Detaches the given router from the tree.
///
/// - parameter child: The child router to detach.
func detachChild(_ child: Routing)
}
/// The base class of all routers that does not own view controllers, representing application states.
///
/// A router acts on inputs from its corresponding interactor, to manipulate application state, forming a tree of
/// routers. A router may obtain a view controller through constructor injection to manipulate view controller tree.
/// The DI structure guarantees that the injected view controller must be from one of this router's ancestors.
/// Router drives the lifecycle of its owned `Interactor`.
///
/// Routers should always use helper builders to instantiate children routers.
open class Router<InteractorType>: Routing {
/// The corresponding `Interactor` owned by this `Router`.
public let interactor: InteractorType
/// The base `Interactable` associated with this `Router`.
public let interactable: Interactable
/// The list of children `Router`s of this `Router`.
public final var children: [Routing] = []
/// The publisher that emits values when the router scope reaches its corresponding life-cycle stages.
///
/// This publisher completes when the router scope is deallocated.
public final var lifecycle: AnyPublisher<RouterLifecycle, Never> {
return lifecycleSubject.eraseToAnyPublisher()
}
/// Initializer.
///
/// - parameter interactor: The corresponding `Interactor` of this `Router`.
public init(interactor: InteractorType) {
self.interactor = interactor
guard let interactable = interactor as? Interactable else {
fatalError("\(interactor) should conform to \(Interactable.self)")
}
self.interactable = interactable
}
/// Loads the `Router`.
///
/// - note: This method is internally used by the framework. Application code should never invoke this method
/// explicitly.
public final func load() {
guard !didLoadFlag else {
return
}
didLoadFlag = true
internalDidLoad()
didLoad()
}
/// Called when the router has finished loading.
///
/// This method is invoked only once. Subclasses should override this method to perform one time setup logic,
/// such as attaching immutable children. The default implementation does nothing.
open func didLoad() {
// No-op
}
// We cannot declare the attach/detach child methods to take in concrete `Router` instances,
// since during unit testing, we need to use mocked child routers.
/// Attaches the given router as a child.
///
/// - parameter child: The child `Router` to attach.
public final func attachChild(_ child: Routing) {
assert(!(children.contains { $0 === child }), "Attempt to attach child: \(child), which is already attached to \(self).")
children.append(child)
// Activate child first before loading. Router usually attaches immutable children in didLoad.
// We need to make sure the RIB is activated before letting it attach immutable children.
child.interactable.activate()
child.load()
}
/// Detaches the given `Router` from the tree.
///
/// - parameter child: The child `Router` to detach.
public final func detachChild(_ child: Routing) {
child.interactable.deactivate()
children.removeElementByReference(child)
}
// MARK: - Internal
let deinitCancellable = CompositeCancellable()
func internalDidLoad() {
bindSubtreeActiveState()
lifecycleSubject.send(.didLoad)
}
// MARK: - Private
private let lifecycleSubject = PassthroughSubject<RouterLifecycle, Never>()
private var didLoadFlag: Bool = false
private func bindSubtreeActiveState() {
let cancellable = interactable.isActiveStream
// Do not retain self here to guarantee execution. Retaining self will cause the cancellables
// to never be cancelled, thus self is never deallocated. Also cannot just store the cancellable
// and call cancel(), since we want to keep the subscription alive until deallocation, in
// case the router is re-attached. Using weak does require the router to be retained until its
// interactor is deactivated.
.sink(receiveValue: { [weak self] (isActive: Bool) in
// When interactor becomes active, we are attached to parent, otherwise we are detached.
self?.setSubtreeActive(isActive)
})
deinitCancellable.insert(cancellable)
}
private func setSubtreeActive(_ active: Bool) {
if active {
iterateSubtree(self) { router in
if !router.interactable.isActive {
router.interactable.activate()
}
}
} else {
iterateSubtree(self) { router in
if router.interactable.isActive {
router.interactable.deactivate()
}
}
}
}
private func iterateSubtree(_ root: Routing, closure: (_ node: Routing) -> ()) {
closure(root)
for child in root.children {
iterateSubtree(child, closure: closure)
}
}
private func detachAllChildren() {
for child in children {
detachChild(child)
}
}
deinit {
interactable.deactivate()
if !children.isEmpty {
detachAllChildren()
}
lifecycleSubject.send(completion: .finished)
deinitCancellable.cancel()
LeakDetector.instance.expectDeallocate(object: interactable)
}
}
| 35.222707 | 129 | 0.665881 |
2393c6938864254d1240ac68f0e6c44c8183b8b9 | 1,345 | internal class AnyLocationBase {
}
internal class AnyLocation<Value>: AnyLocationBase {
internal let _value = UnsafeMutablePointer<Value>.allocate(capacity: 1)
init(value: Value) {
self._value.pointee = value
}
}
public struct _DynamicPropertyBuffer {
}
@propertyWrapper public struct State<Value>: DynamicProperty {
internal var _value: Value
internal var _location: AnyLocation<Value>?
public init(wrappedValue value: Value) {
self._value = value
self._location = AnyLocation(value: value)
}
public init(initialValue value: Value) {
self._value = value
self._location = AnyLocation(value: value)
}
public var wrappedValue: Value {
get { return _location?._value.pointee ?? _value }
nonmutating set { _location?._value.pointee = newValue }
}
public var projectedValue: Binding<Value> {
return Binding(get: { return self.wrappedValue }, set: { newValue in self.wrappedValue = newValue })
}
public static func _makeProperty<V>(in buffer: inout _DynamicPropertyBuffer, container: _GraphValue<V>, fieldOffset: Int, inputs: inout _GraphInputs) {
fatalError()
}
}
extension State where Value: ExpressibleByNilLiteral {
public init() {
self.init(wrappedValue: nil)
}
}
| 28.020833 | 155 | 0.671375 |
bb948ec50848e643a427b4845b227ea90a2f26fb | 1,878 | import Foundation
public protocol Directory {
var path: Path { get }
init(path: Path, create: Bool) throws
@discardableResult
init(path: Path, create: Bool, write: (Directory) throws -> Void) throws
func contents() throws -> [URL]
func file(_ name: String) -> File
@discardableResult
func file(_ name: String, write: () -> String) throws -> File
func remove() throws
}
struct DirectoryImpl: Directory {
enum Error: Swift.Error {
case nonDirectoryFileAlreadyExistsAtPath(String)
}
let path: Path
func contents() throws -> [URL] {
try FileManager.default.contentsOfDirectory(at: path.url, includingPropertiesForKeys: nil, options: [])
}
init(path: Path, create: Bool) throws {
try self.init(path: path, create: create, write: { _ in })
}
@discardableResult
init(path: Path, create: Bool, write: (Directory) throws -> Void) throws {
self.path = path
if create {
var isDirectory = ObjCBool(false)
let exists = FileManager.default.fileExists(atPath: path.url.absoluteString, isDirectory: &isDirectory)
if exists, !isDirectory.boolValue {
throw Error.nonDirectoryFileAlreadyExistsAtPath(path.url.absoluteString)
} else if !exists {
try FileManager.default.createDirectory(at: path.url, withIntermediateDirectories: false, attributes: nil)
}
}
try write(self)
}
func file(_ name: String) -> File {
Env.current.file.init(path: path.appending(name))
}
@discardableResult
func file(_ name: String, write: @autoclosure () -> String) throws -> File {
try Env.current.file.init(path: path.appending(name), write: write)
}
func remove() throws {
try FileManager.default.removeItem(at: path.url)
}
}
| 28.454545 | 122 | 0.634185 |
2189192eeb029f2e6f4aa3f5297ac706fb518f89 | 8,099 | /*
Copyright (C) 2017 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Resolves an IP address to a list of DNS names.
*/
import Foundation
/// This class uses CFHost to query an IP address for its DNS names. To do this:
///
/// 1. Create the `HostNameQuery` object with the IP address in question.
///
/// 2. Set a delegate.
///
/// 3. Call `start()`.
///
/// 4. Wait for `didComplete(names:hostNameQuery:)` or `didComplete(error:hostNameQuery:)`
/// to be called.
///
/// CFHost, and hence this class, is run loop based. The class remembers the run loop on which you
/// call `start()` and delivers the delegate callbacks on that run loop.
///
/// - Important: Reverse DNS queries are notoriously unreliable. Specifically, you must not
/// assume that:
///
/// - Every IP address has a valid reverse DNS name
/// - The reverse DNS name is unique
/// - There's any correlation between the forward and reverse DNS mappings
///
/// Unless you have domain specific knowledge (for example, you're working in an enterprise
/// environment where you know how the DNS is set up), reverse DNS queries are generally not
/// useful for anything other than logging.
final class HostNameQuery {
/// Creates an instance to query the specified IP address for its DNS name.
///
/// - Parameter address: The IP address to query, as a `Data` value containing some flavour of `sockaddr`.
init(address: Data) {
self.address = address
self.host = CFHostCreateWithAddress(nil, address as NSData).takeRetainedValue()
}
/// The IP address to query, as a `Data` value containing some flavour of `sockaddr`.
let address: Data
/// You must set this to learn about the results of your query.
weak var delegate: HostNameQueryDelegate? = nil
/// Starts the query process.
///
/// The query remembers the thread that called this method and calls any delegate
/// callbacks on that thread.
///
/// - Important: For the query to make progress, this thread must run its run loop in
/// the default run loop mode.
///
/// - Warning: It is an error to start a query that's running.
func start() {
precondition(self.targetRunLoop == nil)
self.targetRunLoop = RunLoop.current
var context = CFHostClientContext()
context.info = Unmanaged.passRetained(self).toOpaque()
var success = CFHostSetClient(self.host, { (_ host: CFHost, _: CFHostInfoType, _ streamErrorPtr: UnsafePointer<CFStreamError>?, _ info: UnsafeMutableRawPointer?) in
let obj = Unmanaged<HostNameQuery>.fromOpaque(info!).takeUnretainedValue()
if let streamError = streamErrorPtr?.pointee, (streamError.domain != 0 || streamError.error != 0) {
obj.stop(streamError: streamError, notify: true)
} else {
obj.stop(streamError: nil, notify: true)
}
}, &context)
assert(success)
CFHostScheduleWithRunLoop(self.host, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)
var streamError = CFStreamError()
success = CFHostStartInfoResolution(self.host, .names, &streamError)
if !success {
self.stop(streamError: streamError, notify: true)
}
}
/// Stops the query with the supplied error, notifying the delegate if `notify` is true.
private func stop(streamError: CFStreamError?, notify: Bool) {
let error: Error?
if let streamError = streamError {
// Convert a CFStreamError to a NSError. This is less than ideal because I only handle
// a limited number of error domains. Wouldn't it be nice if there was a public API to
// do this mapping <rdar://problem/5845848> or a CFHost API that used CFError
// <rdar://problem/6016542>.
switch streamError.domain {
case CFStreamErrorDomain.POSIX.rawValue:
error = NSError(domain: NSPOSIXErrorDomain, code: Int(streamError.error))
case CFStreamErrorDomain.macOSStatus.rawValue:
error = NSError(domain: NSOSStatusErrorDomain, code: Int(streamError.error))
case Int(kCFStreamErrorDomainNetServices):
error = NSError(domain: kCFErrorDomainCFNetwork as String, code: Int(streamError.error))
case Int(kCFStreamErrorDomainNetDB):
error = NSError(domain: kCFErrorDomainCFNetwork as String, code: Int(CFNetworkErrors.cfHostErrorUnknown.rawValue), userInfo: [
kCFGetAddrInfoFailureKey as String: streamError.error as NSNumber
])
default:
// If it's something we don't understand, we just assume it comes from
// CFNetwork.
error = NSError(domain: kCFErrorDomainCFNetwork as String, code: Int(streamError.error))
}
} else {
error = nil
}
self.stop(error: error, notify: notify)
}
/// Stops the query with the supplied error, notifying the delegate if `notify` is true.
private func stop(error: Error?, notify: Bool) {
precondition(RunLoop.current == self.targetRunLoop)
self.targetRunLoop = nil
CFHostSetClient(self.host, nil, nil)
CFHostUnscheduleFromRunLoop(self.host, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)
CFHostCancelInfoResolution(self.host, .names)
Unmanaged.passUnretained(self).release()
if notify {
if let error = error {
self.delegate?.didComplete(error: error, hostNameQuery: self)
} else {
let names = CFHostGetNames(self.host, nil)!.takeUnretainedValue() as NSArray as! [String]
self.delegate?.didComplete(names: names, hostNameQuery: self)
}
}
}
/// Cancels a running query.
///
/// If you successfully cancel a query, no delegate callback for that query will be
/// called.
///
/// If the query is running, you must call this from the thread that called `start()`.
///
/// - Note: It is acceptable to call this on a query that's not running; it does nothing
// in that case.
func cancel() {
if self.targetRunLoop != nil {
self.stop(error: NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil), notify: false)
}
}
/// The underlying CFHost object that does the resolution.
private var host: CFHost
/// The run loop on which the CFHost object is scheduled; this is set in `start()`
/// and cleared when the query stops (either via `cancel()` or by completing).
private var targetRunLoop: RunLoop? = nil
}
/// The delegate protocol for the HostNameQuery class.
protocol HostNameQueryDelegate: class {
/// Called when the query completes successfully.
///
/// This is called on the same thread that called `start()`.
///
/// - Parameters:
/// - names: The DNS names for the IP address.
/// - query: The query that completed.
func didComplete(names: [String], hostNameQuery query: HostNameQuery)
/// Called when the query completes with an error.
///
/// This is called on the same thread that called `start()`.
///
/// - Parameters:
/// - error: An error describing the failure.
/// - query: The query that completed.
///
/// - Important: In most cases the error will be in domain `kCFErrorDomainCFNetwork`
/// with a code of `kCFHostErrorUnknown` (aka `CFNetworkErrors.cfHostErrorUnknown`),
/// and the user info dictionary will contain an element with the `kCFGetAddrInfoFailureKey`
/// key whose value is an NSNumber containing an `EAI_XXX` value (from `<netdb.h>`).
func didComplete(error: Error, hostNameQuery query: HostNameQuery)
}
| 41.321429 | 173 | 0.639091 |
f9b3ea8e4804f8eca743ad76811c374334285ccc | 2,498 | //
// CreateInboxRulesetOptions.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import AnyCodable
import AnyCodable
/** Options for creating inbox rulesets. Inbox rulesets can be used to block, allow, filter, or forward emails when sending or receiving using the inbox. */
@objc public class CreateInboxRulesetOptions: NSObject, Codable {
public enum Action: String, Codable, CaseIterable {
case block = "BLOCK"
case allow = "ALLOW"
case filterRemove = "FILTER_REMOVE"
}
public enum Scope: String, Codable, CaseIterable {
case receivingEmails = "RECEIVING_EMAILS"
case sendingEmails = "SENDING_EMAILS"
}
/** Action to be taken when the ruleset matches an email for the given scope. For example: `BLOCK` action with target `*` and scope `SENDING_EMAILS` blocks sending to all recipients. Note `ALLOW` takes precedent over `BLOCK`. `FILTER_REMOVE` is like block but will remove offending email addresses during a send or receive event instead of blocking the action. */
public var action: Action?
/** What type of emails actions to apply ruleset to. Either `SENDING_EMAILS` or `RECEIVING_EMAILS` will apply action and target to any sending or receiving of emails respectively. */
public var scope: Scope?
/** Target to match emails with. Can be a wild-card type pattern or a valid email address. For instance `*@gmail.com` matches all gmail addresses while `[email protected]` matches one address exactly. The target is applied to every recipient field email address when `SENDING_EMAILS` is the scope and is applied to sender of email when `RECEIVING_EMAILS`. */
public var target: String?
public init(action: Action? = nil, scope: Scope? = nil, target: String? = nil) {
self.action = action
self.scope = scope
self.target = target
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case action
case scope
case target
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(action, forKey: .action)
try container.encodeIfPresent(scope, forKey: .scope)
try container.encodeIfPresent(target, forKey: .target)
}
}
| 46.259259 | 427 | 0.707366 |
0a4df443952eb32b3d92c9cbe5b2164b40c4e270 | 64,876 | // RUN: %target-swift-frontend -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
// UNSUPPORTED: resilient_stdlib
struct TrivialStruct {
var x: Int
}
protocol Foo {
func foo()
}
protocol P {
var x : Int { get }
}
protocol P2 : P {}
extension TrivialStruct : P2 {}
struct Box<T> {
let t: T
}
protocol EmptyP {}
struct AddressOnlyStruct : EmptyP {}
struct AnyStruct {
let a: Any
}
protocol Clonable {
func maybeClone() -> Self?
}
indirect enum IndirectEnum<T> {
case Nil
case Node(T)
}
protocol SubscriptableGet {
subscript(a : Int) -> Int { get }
}
protocol SubscriptableGetSet {
subscript(a : Int) -> Int { get set }
}
var subscriptableGet : SubscriptableGet
var subscriptableGetSet : SubscriptableGetSet
class OpaqueClass<T> {
typealias ObnoxiousTuple = (T, (T.Type, (T) -> T))
func inAndOut(x: T) -> T { return x }
func variantOptionalityTuples(x: ObnoxiousTuple) -> ObnoxiousTuple? { return x }
}
class StillOpaqueClass<T>: OpaqueClass<T> {
override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! }
}
class OpaqueTupleClass<U>: OpaqueClass<(U, U)> {
override func inAndOut(x: (U, U)) -> (U, U) { return x }
}
func unreachableF<T>() -> (Int, T)? { }
func s010_hasVarArg(_ args: Any...) {}
// Tests Address only enums's construction
// CHECK-LABEL: sil shared [transparent] @_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmF : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum {
// CHECK: bb0([[ARG0:%.*]] : $EmptyP, [[ARG1:%.*]] : $@thin AddressOnlyEnum.Type):
// CHECK: [[RETVAL:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.mere!enumelt.1, [[ARG0]] : $EmptyP
// CHECK: return [[RETVAL]] : $AddressOnlyEnum
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmF'
// CHECK-LABEL: sil shared [transparent] [thunk] @_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmFTc : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_owned (@in EmptyP) -> @out AddressOnlyEnum {
// CHECK: bb0([[ARG:%.*]] : $@thin AddressOnlyEnum.Type):
// CHECK: [[RETVAL:%.*]] = partial_apply {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum
// CHECK: return [[RETVAL]] : $@callee_owned (@in EmptyP) -> @out AddressOnlyEnum
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmFTc'
enum AddressOnlyEnum {
case nought
case mere(EmptyP)
case phantom(AddressOnlyStruct)
}
// Test vtables - OpaqueTupleClass
// ---
// CHECK-LABEL: sil private @_T020opaque_values_silgen16OpaqueTupleClassC8inAndOutx_xtx_xt1x_tFAA0dF0CADxxAE_tFTV : $@convention(method) <U> (@in (U, U), @guaranteed OpaqueTupleClass<U>) -> @out (U, U) {
// CHECK: bb0([[ARG0:%.*]] : $(U, U), [[ARG1:%.*]] : $OpaqueTupleClass<U>):
// CHECK: [[TELEM0:%.*]] = tuple_extract [[ARG0]] : $(U, U), 0
// CHECK: [[TELEM1:%.*]] = tuple_extract [[ARG0]] : $(U, U), 1
// CHECK: [[APPLY:%.*]] = apply {{.*}}<U>([[TELEM0]], [[TELEM1]], [[ARG1]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @guaranteed OpaqueTupleClass<τ_0_0>) -> (@out τ_0_0, @out τ_0_0)
// CHECK: [[BORROWED_T:%.*]] = begin_borrow [[APPLY]]
// CHECK: [[BORROWED_T_EXT0:%.*]] = tuple_extract [[BORROWED_T]] : $(U, U), 0
// CHECK: [[RETVAL0:%.*]] = copy_value [[BORROWED_T_EXT0]] : $U
// CHECK: [[BORROWED_T_EXT1:%.*]] = tuple_extract [[BORROWED_T]] : $(U, U), 1
// CHECK: [[RETVAL1:%.*]] = copy_value [[BORROWED_T_EXT1]] : $U
// CHECK: end_borrow [[BORROWED_T]]
// CHECK: [[RETVAL:%.*]] = tuple ([[RETVAL0]] : $U, [[RETVAL1]] : $U)
// CHECK: return [[RETVAL]]
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16OpaqueTupleClassC8inAndOutx_xtx_xt1x_tFAA0dF0CADxxAE_tFTV'
// Test vtables - StillOpaqueClass
// ---
// CHECK-LABEL: sil private @_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0eF0CAdEx_xm_xxcttAF_tFTV : $@convention(method) <T> (@in T, @thick T.Type, @owned @callee_owned (@in T) -> @out T, @guaranteed StillOpaqueClass<T>) -> @out Optional<(T, (@thick T.Type, @callee_owned (@in T) -> @out T))> {
// CHECK: bb0([[ARG0:%.*]] : $T, [[ARG1:%.*]] : $@thick T.Type, [[ARG2:%.*]] : $@callee_owned (@in T) -> @out T, [[ARG3:%.*]] : $StillOpaqueClass<T>):
// CHECK: [[TELEM0:%.*]] = tuple ([[ARG1]] : $@thick T.Type, [[ARG2]] : $@callee_owned (@in T) -> @out T)
// CHECK: [[TELEM1:%.*]] = tuple ([[ARG0]] : $T, [[TELEM0]] : $(@thick T.Type, @callee_owned (@in T) -> @out T))
// CHECK: [[ENUMOPT0:%.*]] = enum $Optional<(T, (@thick T.Type, @callee_owned (@in T) -> @out T))>, #Optional.some!enumelt.1, [[TELEM1]] : $(T, (@thick T.Type, @callee_owned (@in T) -> @out T))
// CHECK: [[APPLY:%.*]] = apply {{.*}}<T>([[ENUMOPT0]], [[ARG3]]) : $@convention(method) <τ_0_0> (@in Optional<(τ_0_0, (@thick τ_0_0.Type, @callee_owned (@in τ_0_0) -> @out τ_0_0))>, @guaranteed StillOpaqueClass<τ_0_0>) -> (@out τ_0_0, @thick τ_0_0.Type, @owned @callee_owned (@in τ_0_0) -> @out τ_0_0)
// CHECK: [[BORROWED_T:%.*]] = begin_borrow [[APPLY]]
// CHECK: [[BORROWED_T_EXT0:%.*]] = tuple_extract [[BORROWED_T]] : $(T, @thick T.Type, @callee_owned (@in T) -> @out T), 0
// CHECK: [[RETVAL0:%.*]] = copy_value [[BORROWED_T_EXT0]]
// CHECK: [[BORROWED_T_EXT1:%.*]] = tuple_extract [[BORROWED_T]] : $(T, @thick T.Type, @callee_owned (@in T) -> @out T), 1
// CHECK: [[BORROWED_T_EXT2:%.*]] = tuple_extract [[BORROWED_T]] : $(T, @thick T.Type, @callee_owned (@in T) -> @out T), 2
// CHECK: [[RETVAL1:%.*]] = copy_value [[BORROWED_T_EXT2]]
// CHECK: end_borrow [[BORROWED_T]]
// CHECK: [[RETTUPLE0:%.*]] = tuple ([[BORROWED_T_EXT1]] : $@thick T.Type, [[RETVAL1]] : $@callee_owned (@in T) -> @out T)
// CHECK: [[RETTUPLE1:%.*]] = tuple ([[RETVAL0]] : $T, [[RETTUPLE0]] : $(@thick T.Type, @callee_owned (@in T) -> @out T))
// CHECK: [[RETVAL:%.*]] = enum $Optional<(T, (@thick T.Type, @callee_owned (@in T) -> @out T))>, #Optional.some!enumelt.1, [[RETTUPLE1]] : $(T, (@thick T.Type, @callee_owned (@in T) -> @out T))
// CHECK: return [[RETVAL]]
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0eF0CAdEx_xm_xxcttAF_tFTV'
// part of s280_convExistTrivial: conversion between existential types - reabstraction thunk
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T020opaque_values_silgen1P_pAA13TrivialStructVIxid_AA2P2_pAaE_pIxir_TR : $@convention(thin) (@in P2, @owned @callee_owned (@in P) -> TrivialStruct) -> @out P2 {
// CHECK: bb0([[ARG0:%.*]] : $P2, [[ARG1:%.*]] : $@callee_owned (@in P) -> TrivialStruct):
// CHECK: [[OPENED_ARG:%.*]] = open_existential_opaque [[ARG0]] : $P2 to $@opened({{.*}}) P2
// CHECK: [[COPIED_VAL:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[INIT_P:%.*]] = init_existential_opaque [[COPIED_VAL]] : $@opened({{.*}}) P2, $@opened({{.*}}) P2, $P
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[INIT_P]]
// CHECK: [[APPLY_P:%.*]] = apply [[ARG1]]([[BORROWED_ARG]]) : $@callee_owned (@in P) -> TrivialStruct
// CHECK: [[RETVAL:%.*]] = init_existential_opaque [[APPLY_P]] : $TrivialStruct, $TrivialStruct, $P2
// CHECK: end_borrow [[BORROWED_ARG]] from [[INIT_P]] : $P, $P
// CHECK: destroy_value [[COPIED_VAL]]
// CHECK: destroy_value [[ARG0]]
// CHECK: return [[RETVAL]] : $P2
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen1P_pAA13TrivialStructVIxid_AA2P2_pAaE_pIxir_TR'
// part of s290_convOptExistTriv: conversion between existential types - reabstraction thunk - optionals case
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T020opaque_values_silgen1P_pSgAA13TrivialStructVIxid_AESgAA2P2_pIxyr_TR : $@convention(thin) (Optional<TrivialStruct>, @owned @callee_owned (@in Optional<P>) -> TrivialStruct) -> @out P2 {
// CHECK: bb0([[ARG0:%.*]] : $Optional<TrivialStruct>, [[ARG1:%.*]] : $@callee_owned (@in Optional<P>) -> TrivialStruct):
// CHECK: switch_enum [[ARG0]] : $Optional<TrivialStruct>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb1:
// CHECK: [[ONONE:%.*]] = enum $Optional<P>, #Optional.none!enumelt
// CHECK: br bb3([[ONONE]] : $Optional<P>)
// CHECK: bb2([[OSOME:%.*]] : $TrivialStruct):
// CHECK: [[INIT_S:%.*]] = init_existential_opaque [[OSOME]] : $TrivialStruct, $TrivialStruct, $P
// CHECK: [[ENUM_S:%.*]] = enum $Optional<P>, #Optional.some!enumelt.1, [[INIT_S]] : $P
// CHECK: br bb3([[ENUM_S]] : $Optional<P>)
// CHECK: bb3([[OPT_S:%.*]] : $Optional<P>):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[OPT_S]]
// CHECK: [[APPLY_P:%.*]] = apply [[ARG1]]([[BORROWED_ARG]]) : $@callee_owned (@in Optional<P>) -> TrivialStruct
// CHECK: [[RETVAL:%.*]] = init_existential_opaque [[APPLY_P]] : $TrivialStruct, $TrivialStruct, $P2
// CHECK: end_borrow [[BORROWED_ARG]] from [[OPT_S]] : $Optional<P>, $Optional<P>
// CHECK: destroy_value [[OPT_S]]
// CHECK: return [[RETVAL]] : $P2
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen1P_pSgAA13TrivialStructVIxid_AESgAA2P2_pIxyr_TR'
// Test array initialization - we are still (somewhat) using addresses
// ---
// CHECK-LABEL: sil @_T020opaque_values_silgen21s020_______callVarArgyyF : $@convention(thin) () -> () {
// CHECK: %[[APY:.*]] = apply %{{.*}}<Any>(%{{.*}}) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: %[[BRW:.*]] = begin_borrow %[[APY]]
// CHECK: %[[TPL:.*]] = tuple_extract %[[BRW]] : $(Array<Any>, Builtin.RawPointer), 1
// CHECK: end_borrow %[[BRW]] from %[[APY]] : $(Array<Any>, Builtin.RawPointer), $(Array<Any>, Builtin.RawPointer)
// CHECK: destroy_value %[[APY]]
// CHECK: %[[PTR:.*]] = pointer_to_address %[[TPL]] : $Builtin.RawPointer to [strict] $*Any
// CHECK: [[IOPAQUE:%.*]] = init_existential_opaque %{{.*}} : $Int, $Int, $Any
// CHECK: store [[IOPAQUE]] to [init] %[[PTR]] : $*Any
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s020_______callVarArgyyF'
public func s020_______callVarArg() {
s010_hasVarArg(3)
}
// Test emitSemanticStore.
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s030______assigninoutyxz_xtlF : $@convention(thin) <T> (@inout T, @in T) -> () {
// CHECK: bb0([[ARG0:%.*]] : $*T, [[ARG1:%.*]] : $T):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[CPY:%.*]] = copy_value [[BORROWED_ARG1]] : $T
// CHECK: assign [[CPY]] to [[ARG0]] : $*T
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]] : $T
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s030______assigninoutyxz_xtlF'
func s030______assigninout<T>(_ a: inout T, _ b: T) {
a = b
}
// Test that we no longer use copy_addr or tuple_element_addr when copy by value is possible
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s040___tupleReturnIntS2i_xt_tlF : $@convention(thin) <T> (Int, @in T) -> Int {
// CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $T):
// CHECK: [[TPL:%.*]] = tuple ([[ARG0]] : $Int, [[ARG1]] : $T)
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[TPL]] : $(Int, T)
// CHECK: [[CPY:%.*]] = copy_value [[BORROWED_ARG1]] : $(Int, T)
// CHECK: [[BORROWED_CPY:%.*]] = begin_borrow [[CPY]]
// CHECK: [[INT:%.*]] = tuple_extract [[BORROWED_CPY]] : $(Int, T), 0
// CHECK: [[GEN:%.*]] = tuple_extract [[BORROWED_CPY]] : $(Int, T), 1
// CHECK: [[COPY_GEN:%.*]] = copy_value [[GEN]]
// CHECK: destroy_value [[COPY_GEN]]
// CHECK: end_borrow [[BORROWED_CPY]] from [[CPY]]
// CHECK: destroy_value [[CPY]]
// CHECK: end_borrow [[BORROWED_ARG1]] from [[TPL]] : $(Int, T), $(Int, T)
// CHECK: destroy_value [[TPL]] : $(Int, T)
// CHECK: return [[INT]]
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s040___tupleReturnIntS2i_xt_tlF'
func s040___tupleReturnInt<T>(_ x: (Int, T)) -> Int {
let y = x.0
return y
}
// Test returning an opaque tuple of tuples.
// ---
// CHECK-LABEL: sil hidden [noinline] @_T020opaque_values_silgen21s050______multiResultx_x_xttxlF : $@convention(thin) <T> (@in T) -> (@out T, @out T, @out T) {
// CHECK: bb0(%0 : $T):
// CHECK: %[[CP1:.*]] = copy_value %{{.*}} : $T
// CHECK: %[[CP2:.*]] = copy_value %{{.*}} : $T
// CHECK: %[[CP3:.*]] = copy_value %{{.*}} : $T
// CHECK: destroy_value %0 : $T
// CHECK: %[[TPL:.*]] = tuple (%[[CP1]] : $T, %[[CP2]] : $T, %[[CP3]] : $T)
// CHECK: return %[[TPL]] : $(T, T, T)
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s050______multiResultx_x_xttxlF'
@inline(never)
func s050______multiResult<T>(_ t: T) -> (T, (T, T)) {
return (t, (t, t))
}
// Test returning an opaque tuple of tuples as a concrete tuple.
// ---
// CHECK-LABEL: sil @_T020opaque_values_silgen21s060__callMultiResultSi_Si_SittSi1i_tF : $@convention(thin) (Int) -> (Int, Int, Int) {
// CHECK: bb0(%0 : $Int):
// CHECK: %[[FN:.*]] = function_ref @_T020opaque_values_silgen21s050______multiResultx_x_xttxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0)
// CHECK: %[[TPL:.*]] = apply %[[FN]]<Int>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0)
// CHECK: %[[I1:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 0
// CHECK: %[[I2:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 1
// CHECK: %[[I3:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 2
// CHECK: %[[R:.*]] = tuple (%[[I1]] : $Int, %[[I2]] : $Int, %[[I3]] : $Int)
// CHECK: return %[[R]] : $(Int, Int, Int)
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s060__callMultiResultSi_Si_SittSi1i_tF'
public func s060__callMultiResult(i: Int) -> (Int, (Int, Int)) {
return s050______multiResult(i)
}
// SILGen, prepareArchetypeCallee. Materialize a
// non-class-constrainted self from a class-constrained archetype.
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s070__materializeSelfyx1t_ts9AnyObjectRzAA3FooRzlF : $@convention(thin) <T where T : AnyObject, T : Foo> (@owned T) -> () {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[WITNESS_METHOD:%.*]] = witness_method $T, #Foo.foo!1 : <Self where Self : Foo> (Self) -> () -> () : $@convention(witness_method) <τ_0_0 where τ_0_0 : Foo> (@in_guaranteed τ_0_0) -> ()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: apply [[WITNESS_METHOD]]<T>([[BORROWED_ARG]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Foo> (@in_guaranteed τ_0_0) -> ()
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $T
// CHECK: return %{{[0-9]+}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s070__materializeSelfyx1t_ts9AnyObjectRzAA3FooRzlF'
func s070__materializeSelf<T: Foo>(t: T) where T: AnyObject {
t.foo()
}
// Test open existential with opaque values
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s080______________barSiAA1P_p1p_tF : $@convention(thin) (@in P) -> Int {
// CHECK: bb0([[ARG:%.*]] : $P):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPENED_ARG:%.*]] = open_existential_opaque [[BORROWED_ARG]] : $P to $@opened
// CHECK: [[WITNESS_FUNC:%.*]] = witness_method $@opened
// CHECK: [[RESULT:%.*]] = apply [[WITNESS_FUNC]]<{{.*}}>([[OPENED_ARG]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> Int
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $P
// CHECK: return [[RESULT]] : $Int
func s080______________bar(p: P) -> Int {
return p.x
}
// Test OpaqueTypeLowering copyValue and destroyValue.
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s090___________callerxxlF : $@convention(thin) <T> (@in T) -> @out T {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY:%.*]] = copy_value [[BORROWED_ARG]] : $T
// CHECK: [[RESULT:%.*]] = apply {{%.*}}<T>([[COPY]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
// CHECK: end_borrow [[BORROWED_ARG:%.*]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $T
// CHECK: return %{{.*}} : $T
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s090___________callerxxlF'
func s090___________caller<T>(_ t: T) -> T {
return s090___________caller(t)
}
// Test a simple opaque parameter and return value.
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s100_________identityxxlF : $@convention(thin) <T> (@in T) -> @out T {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $T
// CHECK: return [[COPY_ARG]] : $T
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s100_________identityxxlF'
func s100_________identity<T>(_ t: T) -> T {
return t
}
// Test a guaranteed opaque parameter.
// ---
// CHECK-LABEL: sil private [transparent] [thunk] @_T020opaque_values_silgen21s110___GuaranteedSelfVAA3FooA2aDP3fooyyFTW : $@convention(witness_method) (@in_guaranteed s110___GuaranteedSelf) -> () {
// CHECK: bb0(%0 : $s110___GuaranteedSelf):
// CHECK: %[[F:.*]] = function_ref @_T020opaque_values_silgen21s110___GuaranteedSelfV3fooyyF : $@convention(method) (s110___GuaranteedSelf) -> ()
// CHECK: apply %[[F]](%0) : $@convention(method) (s110___GuaranteedSelf) -> ()
// CHECK: return
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s110___GuaranteedSelfVAA3FooA2aDP3fooyyFTW'
struct s110___GuaranteedSelf : Foo {
func foo() {}
}
// Tests a corner case wherein we used to do a temporary and return a pointer to T instead of T
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s120______returnValuexxlF : $@convention(thin) <T> (@in T) -> @out T {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG1:%.*]] = copy_value [[BORROWED_ARG1]] : $T
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG]]
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[COPY_ARG1]]
// CHECK: [[COPY_ARG2:%.*]] = copy_value [[BORROWED_ARG2]] : $T
// CHECK: end_borrow [[BORROWED_ARG2]] from [[COPY_ARG1]]
// CHECK: return [[COPY_ARG2]] : $T
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s120______returnValuexxlF'
func s120______returnValue<T>(_ x: T) -> T {
let y = x
return y
}
// Tests Optional initialization by value
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s130_____________wrapxSgxlF : $@convention(thin) <T> (@in T) -> @out Optional<T> {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T
// CHECK: [[OPTIONAL_ARG:%.*]] = enum $Optional<T>, #Optional.some!enumelt.1, [[COPY_ARG]] : $T
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $T
// CHECK: return [[OPTIONAL_ARG]] : $Optional<T>
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s130_____________wrapxSgxlF'
func s130_____________wrap<T>(_ x: T) -> T? {
return x
}
// Tests For-each statements
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s140______forEachStmtyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[PROJ_BOX_ARG:%.*]] = project_box %{{.*}} : ${ var IndexingIterator<CountableRange<Int>> }
// CHECK: [[APPLY_ARG1:%.*]] = apply
// CHECK-NOT: alloc_stack $Int
// CHECK-NOT: store [[APPLY_ARG1]] to [trivial]
// CHECK-NOT: alloc_stack $CountableRange<Int>
// CHECK-NOT: dealloc_stack
// CHECK: [[APPLY_ARG2:%.*]] = apply %{{.*}}<CountableRange<Int>>
// CHECK: store [[APPLY_ARG2]] to [trivial] [[PROJ_BOX_ARG]]
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NOT: alloc_stack $Optional<Int>
// CHECK: [[APPLY_ARG3:%.*]] = apply %{{.*}}<CountableRange<Int>>
// CHECK-NOT: dealloc_stack
// CHECK: switch_enum [[APPLY_ARG3]]
// CHECK: bb2:
// CHECK: br bb3
// CHECK: bb3:
// CHECK: return %{{.*}} : $()
// CHECK: bb4([[ENUM_ARG:%.*]] : $Int):
// CHECK-NOT: unchecked_enum_data
// CHECK: br bb1
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s140______forEachStmtyyF'
func s140______forEachStmt() {
for _ in 1..<42 {
}
}
func s150___________anyArg(_: Any) {}
// Tests init of opaque existentials
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s160_______callAnyArgyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[INT_TYPE:%.*]] = metatype $@thin Int.Type
// CHECK: [[INT_LIT:%.*]] = integer_literal $Builtin.Int2048, 42
// CHECK: [[INT_ARG:%.*]] = apply %{{.*}}([[INT_LIT]], [[INT_TYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: [[INIT_OPAQUE:%.*]] = init_existential_opaque [[INT_ARG]] : $Int, $Int, $Any
// CHECK: apply %{{.*}}([[INIT_OPAQUE]]) : $@convention(thin) (@in Any) -> ()
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s160_______callAnyArgyyF'
func s160_______callAnyArg() {
s150___________anyArg(42)
}
// Tests unconditional_checked_cast for opaque values
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s170____force_convertxylF : $@convention(thin) <T> () -> @out T {
// CHECK: bb0:
// CHECK-NOT: alloc_stack
// CHECK: [[INT_TYPE:%.*]] = metatype $@thin Int.Type
// CHECK: [[INT_LIT:%.*]] = integer_literal $Builtin.Int2048, 42
// CHECK: [[INT_ARG:%.*]] = apply %{{.*}}([[INT_LIT]], [[INT_TYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: [[INT_CAST:%.*]] = unconditional_checked_cast_value take_always [[INT_ARG]] : $Int to $T
// CHECK: [[CAST_BORROW:%.*]] = begin_borrow [[INT_CAST]] : $T
// CHECK: [[RETURN_VAL:%.*]] = copy_value [[CAST_BORROW]] : $T
// CHECK: end_borrow [[CAST_BORROW]] from [[INT_CAST]] : $T, $T
// CHECK: destroy_value [[INT_CAST]] : $T
// CHECK: return [[RETURN_VAL]] : $T
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s170____force_convertxylF'
func s170____force_convert<T>() -> T {
let x : T = 42 as! T
return x
}
// Tests supporting function for s190___return_foo_var - cast and return of protocol
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s180_______return_fooAA3Foo_pyF : $@convention(thin) () -> @out Foo {
// CHECK: bb0:
// CHECK: [[INT_LIT:%.*]] = integer_literal $Builtin.Int2048, 42
// CHECK: [[INT_ARG:%.*]] = apply %{{.*}}([[INT_LIT]], [[INT_TYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: [[INT_CAST:%.*]] = unconditional_checked_cast_value take_always [[INT_ARG]] : $Int to $Foo
// CHECK: return [[INT_CAST]] : $Foo
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s180_______return_fooAA3Foo_pyF'
func s180_______return_foo() -> Foo {
return 42 as! Foo
}
var foo_var : Foo = s180_______return_foo()
// Tests return of global variables by doing a load of copy
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s190___return_foo_varAA3Foo_pyF : $@convention(thin) () -> @out Foo {
// CHECK: bb0:
// CHECK: [[GLOBAL:%.*]] = global_addr {{.*}} : $*Foo
// CHECK: [[LOAD_GLOBAL:%.*]] = load [copy] [[GLOBAL]] : $*Foo
// CHECK: return [[LOAD_GLOBAL]] : $Foo
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s190___return_foo_varAA3Foo_pyF'
func s190___return_foo_var() -> Foo {
return foo_var
}
// Tests deinit of opaque existentials
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s200______use_foo_varyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[GLOBAL:%.*]] = global_addr {{.*}} : $*Foo
// CHECK: [[LOAD_GLOBAL:%.*]] = load [copy] [[GLOBAL]] : $*Foo
// CHECK: [[OPEN_VAR:%.*]] = open_existential_opaque [[LOAD_GLOBAL]] : $Foo
// CHECK: [[WITNESS:%.*]] = witness_method $@opened
// CHECK: apply [[WITNESS]]
// CHECK: destroy_value [[LOAD_GLOBAL]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s200______use_foo_varyyF'
func s200______use_foo_var() {
foo_var.foo()
}
// Tests composition erasure of opaque existentials + copy into of opaques
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s210______compErasures5Error_psAC_AA3FoopF : $@convention(thin) (@in Error & Foo) -> @owned Error {
// CHECK: bb0([[ARG:%.*]] : $Error & Foo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPAQUE_ARG:%.*]] = open_existential_opaque [[BORROWED_ARG]] : $Error & Foo to $@opened({{.*}}) Error & Foo
// CHECK: [[EXIST_BOX:%.*]] = alloc_existential_box $Error, $@opened({{.*}}) Error & Foo
// CHECK: [[PROJ_BOX:%.*]] = project_existential_box $@opened({{.*}}) Error & Foo in [[EXIST_BOX]]
// CHECK: [[COPY_OPAQUE:%.*]] = copy_value [[OPAQUE_ARG]] : $@opened({{.*}}) Error & Foo
// CHECK: store [[COPY_OPAQUE]] to [init] [[PROJ_BOX]] : $*@opened({{.*}}) Error & Foo
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $Error & Foo
// CHECK: return [[EXIST_BOX]] : $Error
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s210______compErasures5Error_psAC_AA3FoopF'
func s210______compErasure(_ x: Foo & Error) -> Error {
return x
}
// Tests that existential boxes can contain opaque types
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s220_____openExistBoxSSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String {
// CHECK: bb0([[ARG:%.*]] : $Error):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPAQUE_ARG:%.*]] = open_existential_box [[BORROWED_ARG]] : $Error to $*@opened({{.*}}) Error
// CHECK: [[LOAD_ALLOC:%.*]] = load [copy] [[OPAQUE_ARG]]
// CHECK: [[ALLOC_OPEN:%.*]] = alloc_stack $@opened({{.*}}) Error
// CHECK: store [[LOAD_ALLOC]] to [init] [[ALLOC_OPEN]]
// CHECK: dealloc_stack [[ALLOC_OPEN]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]] : $Error
// CHECK: return {{.*}} : $String
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s220_____openExistBoxSSs5Error_pF'
func s220_____openExistBox(_ x: Error) -> String {
return x._domain
}
// Tests conditional value casts and correspondingly generated reabstraction thunk
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s230______condFromAnyyypF : $@convention(thin) (@in Any) -> () {
// CHECK: bb0([[ARG:%.*]] : $Any):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: checked_cast_value_br [[COPY__ARG]] : $Any to $@callee_owned (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int), bb2, bb1
// CHECK: bb2([[THUNK_PARAM:%.*]] : $@callee_owned (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)):
// CHECK: [[THUNK_REF:%.*]] = function_ref @{{.*}} : $@convention(thin) (Int, Int, Int, Int, Int, @owned @callee_owned (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)) -> (Int, Int, Int, Int, Int)
// CHECK: partial_apply [[THUNK_REF]]([[THUNK_PARAM]])
// CHECK: bb6:
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s230______condFromAnyyypF'
func s230______condFromAny(_ x: Any) {
if let f = x as? (Int, (Int, (Int, Int)), Int) -> (Int, (Int, (Int, Int)), Int) {
_ = f(24, (4,(2, 42)), 42)
}
}
// Tests LValue of error types / existential boxes
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s240_____propOfLValueSSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String {
// CHECK: bb0([[ARG:%.*]] : $Error):
// CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var Error }
// CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: store [[COPY_ARG]] to [init] [[PROJ_BOX]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: [[LOAD_BOX:%.*]] = load [copy] [[PROJ_BOX]]
// CHECK: [[OPAQUE_ARG:%.*]] = open_existential_box [[LOAD_BOX]] : $Error to $*@opened({{.*}}) Error
// CHECK: [[LOAD_OPAQUE:%.*]] = load [copy] [[OPAQUE_ARG]]
// CHECK: [[ALLOC_OPEN:%.*]] = alloc_stack $@opened({{.*}}) Error
// CHECK: store [[LOAD_OPAQUE]] to [init] [[ALLOC_OPEN]]
// CHECK: [[RET_VAL:%.*]] = apply {{.*}}<@opened({{.*}}) Error>([[ALLOC_OPEN]])
// CHECK: return [[RET_VAL]] : $String
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s240_____propOfLValueSSs5Error_pF'
func s240_____propOfLValue(_ x: Error) -> String {
var x = x
return x._domain
}
// Tests Implicit Value Construction under Opaque value mode
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s250_________testBoxTyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[BOX_MTYPE:%.*]] = metatype $@thin Box<Int>.Type
// CHECK: [[MTYPE:%.*]] = metatype $@thin Int.Type
// CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.Int2048, 42
// CHECK: [[AINT:%.*]] = apply {{.*}}([[INTLIT]], [[MTYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: apply {{.*}}<Int>([[AINT]], [[BOX_MTYPE]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin Box<τ_0_0>.Type) -> @out Box<τ_0_0>
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s250_________testBoxTyyF'
func s250_________testBoxT() {
let _ = Box(t: 42)
}
// Tests Address only enums
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s260_______AOnly_enumyAA17AddressOnlyStructVF : $@convention(thin) (AddressOnlyStruct) -> () {
// CHECK: bb0([[ARG:%.*]] : $AddressOnlyStruct):
// CHECK: [[MTYPE1:%.*]] = metatype $@thin AddressOnlyEnum.Type
// CHECK: [[APPLY1:%.*]] = apply {{.*}}([[MTYPE1]]) : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_owned (@in EmptyP) -> @out AddressOnlyEnum
// CHECK: destroy_value [[APPLY1]]
// CHECK: [[MTYPE2:%.*]] = metatype $@thin AddressOnlyEnum.Type
// CHECK: [[ENUM1:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.nought!enumelt
// CHECK: [[MTYPE3:%.*]] = metatype $@thin AddressOnlyEnum.Type
// CHECK: [[INIT_OPAQUE:%.*]] = init_existential_opaque [[ARG]] : $AddressOnlyStruct, $AddressOnlyStruct, $EmptyP
// CHECK: [[ENUM2:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.mere!enumelt.1, [[INIT_OPAQUE]] : $EmptyP
// CHECK: destroy_value [[ENUM2]]
// CHECK: [[MTYPE4:%.*]] = metatype $@thin AddressOnlyEnum.Type
// CHECK: [[ENUM3:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.phantom!enumelt.1, [[ARG]] : $AddressOnlyStruct
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s260_______AOnly_enumyAA17AddressOnlyStructVF'
func s260_______AOnly_enum(_ s: AddressOnlyStruct) {
_ = AddressOnlyEnum.mere
_ = AddressOnlyEnum.nought
_ = AddressOnlyEnum.mere(s)
_ = AddressOnlyEnum.phantom(s)
}
// Tests InjectOptional for opaque value types + conversion of opaque structs
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s270_convOptAnyStructyAA0gH0VADSgcF : $@convention(thin) (@owned @callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@in Optional<AnyStruct>, @owned @callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct) -> @out Optional<AnyStruct>
// CHECK: destroy_value [[PAPPLY]] : $@callee_owned (@in Optional<AnyStruct>) -> @out Optional<AnyStruct>
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct, $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG2:%.*]] = copy_value [[BORROWED_ARG2]]
// CHECK: [[PAPPLY2:%.*]] = partial_apply %{{.*}}([[COPY_ARG2]]) : $@convention(thin) (@in Optional<AnyStruct>, @owned @callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct) -> @out Optional<AnyStruct>
// CHECK: destroy_value [[PAPPLY2]] : $@callee_owned (@in Optional<AnyStruct>) -> @out Optional<AnyStruct>
// CHECK: end_borrow [[BORROWED_ARG2]] from [[ARG]] : $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct, $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct
// CHECK: destroy_value [[ARG]] : $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s270_convOptAnyStructyAA0gH0VADSgcF'
func s270_convOptAnyStruct(_ a1: @escaping (AnyStruct?) -> AnyStruct) {
let _: (AnyStruct?) -> AnyStruct? = a1
let _: (AnyStruct!) -> AnyStruct? = a1
}
// Tests conversion between existential types
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s280_convExistTrivialyAA0G6StructVAA1P_pcF : $@convention(thin) (@owned @callee_owned (@in P) -> TrivialStruct) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned (@in P) -> TrivialStruct):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@in P2, @owned @callee_owned (@in P) -> TrivialStruct) -> @out P2
// CHECK: destroy_value [[PAPPLY]] : $@callee_owned (@in P2) -> @out P2
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_owned (@in P) -> TrivialStruct
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s280_convExistTrivialyAA0G6StructVAA1P_pcF'
func s280_convExistTrivial(_ s: @escaping (P) -> TrivialStruct) {
let _: (P2) -> P2 = s
}
// Tests conversion between existential types - optionals case
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s290_convOptExistTrivyAA13TrivialStructVAA1P_pSgcF : $@convention(thin) (@owned @callee_owned (@in Optional<P>) -> TrivialStruct) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned (@in Optional<P>) -> TrivialStruct):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}([[COPY_ARG]]) : $@convention(thin) (Optional<TrivialStruct>, @owned @callee_owned (@in Optional<P>) -> TrivialStruct) -> @out P2
// CHECK: destroy_value [[PAPPLY]] : $@callee_owned (Optional<TrivialStruct>) -> @out P2
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_owned (@in Optional<P>) -> TrivialStruct, $@callee_owned (@in Optional<P>) -> TrivialStruct
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s290_convOptExistTrivyAA13TrivialStructVAA1P_pSgcF'
func s290_convOptExistTriv(_ s: @escaping (P?) -> TrivialStruct) {
let _: (TrivialStruct?) -> P2 = s
}
// Tests corner-case: reabstraction of an empty tuple to any
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s300__convETupleToAnyyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> ()):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> @out Any
// CHECK: destroy_value [[PAPPLY]] : $@callee_owned () -> @out Any
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_owned () -> (), $@callee_owned () -> ()
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s300__convETupleToAnyyyycF'
func s300__convETupleToAny(_ t: @escaping () -> ()) {
let _: () -> Any = t
}
// Tests corner-case: reabstraction of a non-empty tuple to any
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s310__convIntTupleAnyySi_SitycF : $@convention(thin) (@owned @callee_owned () -> (Int, Int)) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> (Int, Int)):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@owned @callee_owned () -> (Int, Int)) -> @out Any
// CHECK: destroy_value [[PAPPLY]] : $@callee_owned () -> @out Any
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_owned () -> (Int, Int), $@callee_owned () -> (Int, Int)
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s310__convIntTupleAnyySi_SitycF'
func s310__convIntTupleAny(_ t: @escaping () -> (Int, Int)) {
let _: () -> Any = t
}
// Tests translating and imploding into Any under opaque value mode
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s320__transImplodeAnyyyypcF : $@convention(thin) (@owned @callee_owned (@in Any) -> ()) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned (@in Any) -> ()):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}([[COPY_ARG]]) : $@convention(thin) (Int, Int, @owned @callee_owned (@in Any) -> ()) -> ()
// CHECK: destroy_value [[PAPPLY]] : $@callee_owned (Int, Int) -> ()
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_owned (@in Any) -> (), $@callee_owned (@in Any) -> ()
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s320__transImplodeAnyyyypcF'
func s320__transImplodeAny(_ t: @escaping (Any) -> ()) {
let _: ((Int, Int)) -> () = t
}
// Tests support for address only let closures under opaque value mode - they are not by-address anymore
// ---
// CHECK-LABEL: sil private @_T020opaque_values_silgen21s330___addrLetClosurexxlFxycfU_xycfU_ : $@convention(thin) <T> (@in T) -> @out T {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] : $T
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $T
// CHECK: destroy_value [[ARG]]
// CHECK: return [[COPY_ARG]] : $T
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s330___addrLetClosurexxlFxycfU_xycfU_'
func s330___addrLetClosure<T>(_ x:T) -> T {
return { { x }() }()
}
// Tests support for capture of a mutable opaque value type
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s340_______captureBoxyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var EmptyP }, var, name "mutableAddressOnly"
// CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
// CHECK: [[APPLY_FOR_BOX:%.*]] = apply %{{.*}}(%{{.*}}) : $@convention(method) (@thin AddressOnlyStruct.Type) -> AddressOnlyStruct
// CHECK: [[INIT_OPAQUE:%.*]] = init_existential_opaque [[APPLY_FOR_BOX]] : $AddressOnlyStruct, $AddressOnlyStruct, $EmptyP
// CHECK: store [[INIT_OPAQUE]] to [init] [[PROJ_BOX]] : $*EmptyP
// CHECK: [[COPY_BOX:%.*]] = copy_value [[ALLOC_OF_BOX]] : ${ var EmptyP }
// CHECK: mark_function_escape [[PROJ_BOX]] : $*EmptyP
// CHECK: apply %{{.*}}([[COPY_BOX]]) : $@convention(thin) (@owned { var EmptyP }) -> ()
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s340_______captureBoxyyF'
func s340_______captureBox() {
var mutableAddressOnly: EmptyP = AddressOnlyStruct()
func captureEverything() {
s100_________identity((mutableAddressOnly))
}
captureEverything()
}
// Tests support for if statements for opaque value(s) under new mode
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s350_______addrOnlyIfAA6EmptyP_pSb1x_tF : $@convention(thin) (Bool) -> @out EmptyP {
// CHECK: bb0([[ARG:%.*]] : $Bool):
// CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var EmptyP }, var
// CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
// CHECK: [[APPLY_FOR_BOX:%.*]] = apply %{{.*}}(%{{.*}}) : $@convention(method) (@thin AddressOnlyStruct.Type) -> AddressOnlyStruct
// CHECK: [[INIT_OPAQUE:%.*]] = init_existential_opaque [[APPLY_FOR_BOX]] : $AddressOnlyStruct, $AddressOnlyStruct, $EmptyP
// CHECK: store [[INIT_OPAQUE]] to [init] [[PROJ_BOX]] : $*EmptyP
// CHECK: [[APPLY_FOR_BRANCH:%.*]] = apply %{{.*}}([[ARG]]) : $@convention(method) (Bool) -> Builtin.Int1
// CHECK: cond_br [[APPLY_FOR_BRANCH]], bb2, bb1
// CHECK: bb1:
// CHECK: [[RETVAL1:%.*]] = load [copy] [[PROJ_BOX]] : $*EmptyP
// CHECK: br bb3([[RETVAL1]] : $EmptyP)
// CHECK: bb2:
// CHECK: [[RETVAL2:%.*]] = load [copy] [[PROJ_BOX]] : $*EmptyP
// CHECK: br bb3([[RETVAL2]] : $EmptyP)
// CHECK: bb3([[RETVAL:%.*]] : $EmptyP):
// CHECK: destroy_value [[ALLOC_OF_BOX]]
// CHECK: return [[RETVAL]] : $EmptyP
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s350_______addrOnlyIfAA6EmptyP_pSb1x_tF'
func s350_______addrOnlyIf(x: Bool) -> EmptyP {
var a : EmptyP = AddressOnlyStruct()
return x ? a : a
}
// Tests support for guards and indirect enums for opaque values
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s360________guardEnumyAA08IndirectF0OyxGlF : $@convention(thin) <T> (@owned IndirectEnum<T>) -> () {
// CHECK: bb0([[ARG:%.*]] : $IndirectEnum<T>):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: switch_enum [[COPY__ARG]] : $IndirectEnum<T>, case #IndirectEnum.Node!enumelt.1: [[NODE_BB:bb[0-9]+]], case #IndirectEnum.Nil!enumelt: [[NIL_BB:bb[0-9]+]]
//
// CHECK: [[NIL_BB]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $IndirectEnum<T>, $IndirectEnum<T>
// CHECK: br [[NIL_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NIL_TRAMPOLINE]]:
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[NODE_BB]]([[EARG:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[PROJ_BOX:%.*]] = project_box [[EARG]]
// CHECK: [[LOAD_BOX:%.*]] = load [take] [[PROJ_BOX]] : $*T
// CHECK: [[COPY_BOX:%.*]] = copy_value [[LOAD_BOX]] : $T
// CHECK: destroy_value [[EARG]]
// CHECK: br [[CONT_BB:bb[0-9]+]]
//
// CHECK: [[CONT_BB]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $IndirectEnum<T>, $IndirectEnum<T>
// CHECK: destroy_value [[COPY_BOX]]
// CHECK: br [[EPILOG_BB]]
//
// CHECK: [[EPILOG_BB]]:
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s360________guardEnumyAA08IndirectF0OyxGlF'
func s360________guardEnum<T>(_ e: IndirectEnum<T>) {
do {
guard case .Node(let x) = e else { return }
}
}
// Tests contextual init() of opaque value types
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s370_____optToOptCastxSgSQyxGlF : $@convention(thin) <T> (@in Optional<T>) -> @out Optional<T> {
// CHECK: bb0([[ARG:%.*]] : $Optional<T>):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $Optional<T>, $Optional<T>
// CHECK: destroy_value [[ARG]]
// CHECK: return [[COPY__ARG]] : $Optional<T>
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s370_____optToOptCastxSgSQyxGlF'
func s370_____optToOptCast<T>(_ x : T!) -> T? {
return x
}
// Tests casting optional opaques to optional opaques
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s380___contextualInitySiSgF : $@convention(thin) (Optional<Int>) -> () {
// CHECK: bb0([[ARG:%.*]] : $Optional<Int>):
// CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var Optional<Int> }, var
// CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
// CHECK: store [[ARG]] to [trivial] [[PROJ_BOX]] : $*Optional<Int>
// CHECK: destroy_value [[ALLOC_OF_BOX]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s380___contextualInitySiSgF'
func s380___contextualInit(_ a : Int?) {
var x: Int! = a
}
// Tests opaque call result types
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s390___addrCallResultyxycSglF : $@convention(thin) <T> (@owned Optional<@callee_owned () -> @out T>) -> () {
// CHECK: bb0([[ARG:%.*]] : $Optional<@callee_owned () -> @out T>):
// CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[SENUM:%.*]] = select_enum [[COPY__ARG]]
// CHECK: cond_br [[SENUM]], bb3, bb1
// CHECK: bb1:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br bb2
// CHECK: bb2:
// CHECK: [[ONONE:%.*]] = enum $Optional<T>, #Optional.none!enumelt
// CHECK: br bb4([[ONONE]] : $Optional<T>)
// CHECK: bb4(%{{.*}} : $Optional<T>):
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s390___addrCallResultyxycSglF'
func s390___addrCallResult<T>(_ f: (() -> T)?) {
var x = f?()
}
// Tests reabstraction / partial apply of protocols under opaque value mode
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s400______maybeClonePyAA8Clonable_p1c_tF : $@convention(thin) (@in Clonable) -> () {
// CHECK: bb0([[ARG:%.*]] : $Clonable):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPEN_ARG:%.*]] = open_existential_opaque [[BORROWED_ARG]] : $Clonable
// CHECK: [[COPY_OPAQUE:%.*]] = copy_value [[OPEN_ARG]]
// CHECK: [[APPLY_OPAQUE:%.*]] = apply %{{.*}}<@opened({{.*}}) Clonable>([[COPY_OPAQUE]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@in τ_0_0) -> @owned @callee_owned () -> @out Optional<τ_0_0>
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}<@opened({{.*}}) Clonable>([[APPLY_OPAQUE]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: end_borrow [[BORROWED_ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s400______maybeClonePyAA8Clonable_p1c_tF'
func s400______maybeCloneP(c: Clonable) {
let _: () -> Clonable? = c.maybeClone
}
// Tests global opaque values / subscript rvalues
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s410__globalRvalueGetS2iF : $@convention(thin) (Int) -> Int {
// CHECK: bb0([[ARG:%.*]] : $Int):
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020opaque_values_silgen16subscriptableGetAA013SubscriptableE0_pv : $*SubscriptableGet
// CHECK: [[OPEN_ARG:%.*]] = open_existential_addr immutable_access [[GLOBAL_ADDR]] : $*SubscriptableGet to $*@opened
// CHECK: [[GET_OPAQUE:%.*]] = load [copy] [[OPEN_ARG]] : $*@opened
// CHECK: [[RETVAL:%.*]] = apply %{{.*}}<@opened({{.*}}) SubscriptableGet>([[ARG]], [[GET_OPAQUE]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : SubscriptableGet> (Int, @in_guaranteed τ_0_0) -> Int
// CHECK: destroy_value [[GET_OPAQUE]]
// CHECK: return [[RETVAL]] : $Int
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s410__globalRvalueGetS2iF'
func s410__globalRvalueGet(_ i : Int) -> Int {
return subscriptableGet[i]
}
// Tests global opaque values / subscript lvalues
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s420__globalLvalueGetS2iF : $@convention(thin) (Int) -> Int {
// CHECK: bb0([[ARG:%.*]] : $Int):
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020opaque_values_silgen19subscriptableGetSetAA013SubscriptableeF0_pv : $*SubscriptableGetSet
// CHECK: [[OPEN_ARG:%.*]] = open_existential_addr immutable_access [[GLOBAL_ADDR]] : $*SubscriptableGetSet to $*@opened
// CHECK: [[GET_OPAQUE:%.*]] = load [copy] [[OPEN_ARG]] : $*@opened
// CHECK: [[RETVAL:%.*]] = apply %{{.*}}<@opened({{.*}}) SubscriptableGetSet>([[ARG]], [[GET_OPAQUE]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : SubscriptableGetSet> (Int, @in_guaranteed τ_0_0) -> Int
// CHECK: destroy_value [[GET_OPAQUE]]
// CHECK: return [[RETVAL]] : $Int
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s420__globalLvalueGetS2iF'
func s420__globalLvalueGet(_ i : Int) -> Int {
return subscriptableGetSet[i]
}
// Tests tuple transformation
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s430_callUnreachableFyx1t_tlF : $@convention(thin) <T> (@in T) -> () {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[APPLY_T:%.*]] = apply %{{.*}}<((T) -> (), T)>() : $@convention(thin) <τ_0_0> () -> @out Optional<(Int, τ_0_0)>
// CHECK: switch_enum [[APPLY_T]] : $Optional<(Int, (@callee_owned (@in T) -> @out (), T))>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb2([[ENUMARG:%.*]] : $(Int, (@callee_owned (@in T) -> @out (), T))):
// CHECK: [[TELEM0:%.*]] = tuple_extract [[ENUMARG]] : $(Int, (@callee_owned (@in T) -> @out (), T)), 0
// CHECK: [[TELEM1:%.*]] = tuple_extract [[ENUMARG]] : $(Int, (@callee_owned (@in T) -> @out (), T)), 1
// CHECK: [[TELEM1P0:%.*]] = tuple_extract [[TELEM1]] : $(@callee_owned (@in T) -> @out (), T), 0
// CHECK: [[TELEM1P1:%.*]] = tuple_extract [[TELEM1]] : $(@callee_owned (@in T) -> @out (), T), 1
// CHECK: [[PAPPLY:%.*]] = partial_apply %{{.*}}<T>([[TELEM1P0]]) : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out ()) -> ()
// CHECK: [[NEWT0:%.*]] = tuple ([[PAPPLY]] : $@callee_owned (@in T) -> (), [[TELEM1P1]] : $T)
// CHECK: [[NEWT1:%.*]] = tuple ([[TELEM0]] : $Int, [[NEWT0]] : $(@callee_owned (@in T) -> (), T))
// CHECK: [[NEWENUM:%.*]] = enum $Optional<(Int, (@callee_owned (@in T) -> (), T))>, #Optional.some!enumelt.1, [[NEWT1]] : $(Int, (@callee_owned (@in T) -> (), T))
// CHECK: br bb3([[NEWENUM]] : $Optional<(Int, (@callee_owned (@in T) -> (), T))>)
// CHECK: bb3([[ENUMIN:%.*]] : $Optional<(Int, (@callee_owned (@in T) -> (), T))>):
// CHECK: destroy_value [[ENUMIN]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s430_callUnreachableFyx1t_tlF'
func s430_callUnreachableF<T>(t: T) {
let _: (Int, ((T) -> (), T))? = unreachableF()
}
// Further testing for conditional checked cast under opaque value mode - make sure we don't create a buffer for results
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s440__cleanupEmissionyxlF : $@convention(thin) <T> (@in T) -> () {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: checked_cast_value_br [[COPY_ARG]] : $T to $EmptyP, bb2, bb1
//
// CHECK: bb2([[PTYPE:%.*]] : $EmptyP):
// CHECK: [[PSOME:%.*]] = enum $Optional<EmptyP>, #Optional.some!enumelt.1, [[PTYPE]] : $EmptyP
// CHECK: br bb3([[PSOME]] : $Optional<EmptyP>)
//
// CHECK: bb3([[ENUMRES:%.*]] : $Optional<EmptyP>):
// CHECK: switch_enum [[ENUMRES]] : $Optional<EmptyP>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[NONE_BB]]:
// CHECK: end_borrow [[BORROWED_ARG]]
// CHECK: br [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[ENUMRES2:%.*]] : $EmptyP):
// CHECK: br [[CONT_BB:bb[0-9]+]]
//
// CHECK: [[CONT_BB]]:
// CHECK: end_borrow [[BORROWED_ARG]]
// CHECK: destroy_value [[ENUMRES2]]
// CHECK: br [[EPILOG_BB]]
//
// CHECK: [[EPILOG_BB]]:
// CHECK: destroy_value [[ARG]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s440__cleanupEmissionyxlF'
func s440__cleanupEmission<T>(_ x: T) {
guard let x2 = x as? EmptyP else { return }
_ = x2
}
// Tests conditional value casts and correspondingly generated reabstraction thunk, with <T> types
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s999_____condTFromAnyyyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> () {
// CHECK: bb0([[ARG0:%.*]] : $Any, [[ARG1:%.*]] : $T):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: checked_cast_value_br [[COPY__ARG]] : $Any to $@callee_owned (@in (Int, T)) -> @out (Int, T), bb2, bb1
// CHECK: bb2([[THUNK_PARAM:%.*]] : $@callee_owned (@in (Int, T)) -> @out (Int, T)):
// CHECK: [[THUNK_REF:%.*]] = function_ref @{{.*}} : $@convention(thin) <τ_0_0> (Int, @in τ_0_0, @owned @callee_owned (@in (Int, τ_0_0)) -> @out (Int, τ_0_0)) -> (Int, @out τ_0_0)
// CHECK: partial_apply [[THUNK_REF]]<T>([[THUNK_PARAM]])
// CHECK: bb6:
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s999_____condTFromAnyyyp_xtlF'
func s999_____condTFromAny<T>(_ x: Any, _ y: T) {
if let f = x as? (Int, T) -> (Int, T) {
f(42, y)
}
}
// s250_________testBoxT continued Test Implicit Value Construction under Opaque value mode
// ---
// CHECK-LABEL: sil hidden @_T020opaque_values_silgen3BoxVACyxGx1t_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T> {
// CHECK: bb0([[ARG0:%.*]] : $T, [[ARG1:%.*]] : $@thin Box<T>.Type):
// CHECK: [[RETVAL:%.*]] = struct $Box<T> ([[ARG0]] : $T)
// CHECK: return [[RETVAL]] : $Box<T>
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen3BoxVACyxGx1t_tcfC'
// s270_convOptAnyStruct continued Test: reabstraction thunk helper
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T020opaque_values_silgen9AnyStructVSgACIxir_A2DIxir_TR : $@convention(thin) (@in Optional<AnyStruct>, @owned @callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct) -> @out Optional<AnyStruct> {
// CHECK: bb0([[ARG0:%.*]] : $Optional<AnyStruct>, [[ARG1:%.*]] : $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct):
// CHECK: [[APPLYARG:%.*]] = apply [[ARG1]]([[ARG0]]) : $@callee_owned (@in Optional<AnyStruct>) -> @out AnyStruct
// CHECK: [[RETVAL:%.*]] = enum $Optional<AnyStruct>, #Optional.some!enumelt.1, [[APPLYARG]] : $AnyStruct
// CHECK: return [[RETVAL]] : $Optional<AnyStruct>
// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen9AnyStructVSgACIxir_A2DIxir_TR'
// s300__convETupleToAny continued Test: reabstraction of () to Any
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Ix_ypIxr_TR : $@convention(thin) (@owned @callee_owned () -> ()) -> @out Any {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> ()):
// CHECK: [[ASTACK:%.*]] = alloc_stack $Any
// CHECK: [[IADDR:%.*]] = init_existential_addr [[ASTACK]] : $*Any, $()
// CHECK: [[APPLYARG:%.*]] = apply [[ARG]]() : $@callee_owned () -> ()
// CHECK: [[LOAD_EXIST:%.*]] = load [trivial] [[IADDR]] : $*()
// CHECK: [[RETVAL:%.*]] = init_existential_opaque [[LOAD_EXIST]] : $(), $(), $Any
// CHECK: return [[RETVAL]] : $Any
// CHECK-LABEL: } // end sil function '_T0Ix_ypIxr_TR'
// s310_convIntTupleAny continued Test: reabstraction of non-empty tuple to Any
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIxdd_ypIxr_TR : $@convention(thin) (@owned @callee_owned () -> (Int, Int)) -> @out Any {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> (Int, Int)):
// CHECK: [[ASTACK:%.*]] = alloc_stack $Any
// CHECK: [[IADDR:%.*]] = init_existential_addr [[ASTACK]] : $*Any, $(Int, Int)
// CHECK: [[TADDR0:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 0
// CHECK: [[TADDR1:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 1
// CHECK: [[APPLYARG:%.*]] = apply [[ARG]]() : $@callee_owned () -> (Int, Int)
// CHECK: [[TEXTRACT0:%.*]] = tuple_extract [[APPLYARG]] : $(Int, Int), 0
// CHECK: [[TEXTRACT1:%.*]] = tuple_extract [[APPLYARG]] : $(Int, Int), 1
// CHECK: store [[TEXTRACT0]] to [trivial] [[TADDR0]] : $*Int
// CHECK: store [[TEXTRACT1]] to [trivial] [[TADDR1]] : $*Int
// CHECK: [[LOAD_EXIST:%.*]] = load [trivial] [[IADDR]] : $*(Int, Int)
// CHECK: [[RETVAL:%.*]] = init_existential_opaque [[LOAD_EXIST]] : $(Int, Int), $(Int, Int), $Any
// CHECK: dealloc_stack [[ASTACK]] : $*Any
// CHECK: return [[RETVAL]] : $Any
// CHECK-LABEL: } // end sil function '_T0S2iIxdd_ypIxr_TR'
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @{{.*}} : $@convention(thin) (Int, Int, Int, Int, Int, @owned @callee_owned (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)) -> (Int, Int, Int, Int, Int)
// CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $Int, [[ARG3:%.*]] : $Int, [[ARG4:%.*]] : $Int, [[ARG5:%.*]] : $@callee_owned (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)):
// CHECK: [[TUPLE_TO_APPLY0:%.*]] = tuple ([[ARG2]] : $Int, [[ARG3]] : $Int)
// CHECK: [[TUPLE_TO_APPLY1:%.*]] = tuple ([[ARG1]] : $Int, [[TUPLE_TO_APPLY0]] : $(Int, Int))
// CHECK: [[TUPLE_TO_APPLY2:%.*]] = tuple ([[ARG0]] : $Int, [[TUPLE_TO_APPLY1]] : $(Int, (Int, Int)), [[ARG4]] : $Int)
// CHECK: [[TUPLE_APPLY:%.*]] = apply [[ARG5]]([[TUPLE_TO_APPLY2]]) : $@callee_owned (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)
// CHECK: [[RET_VAL0:%.*]] = tuple_extract [[TUPLE_APPLY]] : $(Int, (Int, (Int, Int)), Int), 0
// CHECK: [[TUPLE_EXTRACT1:%.*]] = tuple_extract [[TUPLE_APPLY]] : $(Int, (Int, (Int, Int)), Int), 1
// CHECK: [[RET_VAL1:%.*]] = tuple_extract [[TUPLE_EXTRACT1]] : $(Int, (Int, Int)), 0
// CHECK: [[TUPLE_EXTRACT2:%.*]] = tuple_extract [[TUPLE_EXTRACT1]] : $(Int, (Int, Int)), 1
// CHECK: [[RET_VAL2:%.*]] = tuple_extract [[TUPLE_EXTRACT2]] : $(Int, Int), 0
// CHECK: [[RET_VAL3:%.*]] = tuple_extract [[TUPLE_EXTRACT2]] : $(Int, Int), 1
// CHECK: [[RET_VAL4:%.*]] = tuple_extract [[TUPLE_APPLY]] : $(Int, (Int, (Int, Int)), Int), 2
// CHECK: [[RET_VAL_TUPLE:%.*]] = tuple ([[RET_VAL0]] : $Int, [[RET_VAL1]] : $Int, [[RET_VAL2]] : $Int, [[RET_VAL3]] : $Int, [[RET_VAL4]] : $Int)
// CHECK: return [[RET_VAL_TUPLE]] : $(Int, Int, Int, Int, Int)
// CHECK-LABEL: } // end sil function '{{.*}}'
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @{{.*}} : $@convention(thin) <T> (Int, @in T, @owned @callee_owned (@in (Int, T)) -> @out (Int, T)) -> (Int, @out T) {
// CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $T, [[ARG2:%.*]] : $@callee_owned (@in (Int, T)) -> @out (Int, T)):
// CHECK: [[TUPLE_TO_APPLY:%.*]] = tuple ([[ARG0]] : $Int, [[ARG1]] : $T)
// CHECK: [[TUPLE_APPLY:%.*]] = apply [[ARG2]]([[TUPLE_TO_APPLY]]) : $@callee_owned (@in (Int, T)) -> @out (Int, T)
// CHECK: [[TUPLE_BORROW:%.*]] = begin_borrow [[TUPLE_APPLY]] : $(Int, T)
// CHECK: [[RET_VAL0:%.*]] = tuple_extract [[TUPLE_BORROW]] : $(Int, T), 0
// CHECK: [[TUPLE_EXTRACT:%.*]] = tuple_extract [[TUPLE_BORROW]] : $(Int, T), 1
// CHECK: [[RET_VAL1:%.*]] = copy_value [[TUPLE_EXTRACT]] : $T
// CHECK: end_borrow [[TUPLE_BORROW]] from [[TUPLE_APPLY]] : $(Int, T), $(Int, T)
// CHECK: destroy_value [[TUPLE_APPLY]] : $(Int, T)
// CHECK: [[RET_VAL_TUPLE:%.*]] = tuple ([[RET_VAL0]] : $Int, [[RET_VAL1]] : $T)
// CHECK: return [[RET_VAL_TUPLE]] : $(Int, T)
// CHECK-LABEL: } // end sil function '{{.*}}'
// Tests LogicalPathComponent's writeback for opaque value types
// ---
// CHECK-LABEL: sil @_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscriptyq_3key_tF : $@convention(method) <Key, Value where Key : Hashable> (@in Value, @inout Dictionary<Key, Value>) -> () {
// CHECK: bb0([[ARG0:%.*]] : $Value, [[ARG1:%.*]] : $*Dictionary<Key, Value>):
// CHECK: [[OPTIONAL_ALLOC:%.*]] = alloc_stack $Optional<Value>
// CHECK: switch_enum_addr [[OPTIONAL_ALLOC]] : $*Optional<Value>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb2:
// CHECK: [[OPTIONAL_LOAD:%.*]] = load [take] [[OPTIONAL_ALLOC]] : $*Optional<Value>
// CHECK: apply {{.*}}<Key, Value>([[OPTIONAL_LOAD]], {{.*}}, [[ARG1]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@in Optional<τ_0_1>, @in τ_0_1, @inout Dictionary<τ_0_0, τ_0_1>) -> ()
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscriptyq_3key_tF'
// Tests materializeForSet's createSetterCallback for opaque values
// ---
// CHECK-LABEL: sil [transparent] [serialized] @_T0s10DictionaryV20opaque_values_silgenE9subscriptq_Sgq_cfmytfU_ : $@convention(method) <Key, Value where Key : Hashable> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Key, Value>, @thick Dictionary<Key, Value>.Type) -> () {
// CHECK: bb0([[ARG0:%.*]] : $Builtin.RawPointer, [[ARG1:%.*]] : $*Builtin.UnsafeValueBuffer, [[ARG2:%.*]] : $*Dictionary<Key, Value>, [[ARG3:%.*]] : $@thick Dictionary<Key, Value>.Type):
// CHECK: [[PROJ_VAL1:%.*]] = project_value_buffer $Value in [[ARG1]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[LOAD_VAL1:%.*]] = load [take] [[PROJ_VAL1]] : $*Value
// CHECK: [[ADDR_VAL0:%.*]] = pointer_to_address [[ARG0]] : $Builtin.RawPointer to [strict] $*Optional<Value>
// CHECK: [[LOAD_VAL0:%.*]] = load [take] [[ADDR_VAL0]] : $*Optional<Value>
// CHECK: apply {{.*}}<Key, Value>([[LOAD_VAL0]], [[LOAD_VAL1]], [[ARG2]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@in Optional<τ_0_1>, @in τ_0_1, @inout Dictionary<τ_0_0, τ_0_1>) -> ()
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenE9subscriptq_Sgq_cfmytfU_'
extension Dictionary {
public subscript(key: Value) -> Value? {
@inline(__always)
get {
return key
}
set(newValue) {
}
}
public mutating func inoutAccessOfSubscript(key: Value) {
func increment(x: inout Value) { }
increment(x: &self[key]!)
}
}
// s400______maybeCloneP continued Test: reabstraction thunk
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0xSgIxr_20opaque_values_silgen8Clonable_pSgIxr_AbCRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> {
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> @out Optional<τ_0_0>):
// CHECK: [[APPLY_ARG:%.*]] = apply [[ARG]]() : $@callee_owned () -> @out Optional<τ_0_0>
// CHECK: switch_enum [[APPLY_ARG]] : $Optional<τ_0_0>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
// CHECK: bb1:
// CHECK: [[ONONE:%.*]] = enum $Optional<Clonable>, #Optional.none!enumelt
// CHECK: br bb3([[ONONE]] : $Optional<Clonable>)
// CHECK: bb2([[ENUM_SOME:%.*]] : $τ_0_0):
// CHECK: [[INIT_OPAQUE:%.*]] = init_existential_opaque [[ENUM_SOME]] : $τ_0_0, $τ_0_0, $Clonable
// CHECK: [[OSOME:%.*]] = enum $Optional<Clonable>, #Optional.some!enumelt.1, [[INIT_OPAQUE]] : $Clonable
// CHECK: br bb3([[OSOME]] : $Optional<Clonable>)
// CHECK: bb3([[RETVAL:%.*]] : $Optional<Clonable>):
// CHECK: return [[RETVAL]] : $Optional<Clonable>
// CHECK-LABEL: } // end sil function '_T0xSgIxr_20opaque_values_silgen8Clonable_pSgIxr_AbCRzlTR'
// s320__transImplodeAny continued Test: reabstraction thunk
// ---
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIxi_S2iIxyy_TR : $@convention(thin) (Int, Int, @owned @callee_owned (@in Any) -> ()) -> () {
// CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@callee_owned (@in Any) -> ()):
// CHECK: [[ASTACK:%.*]] = alloc_stack $Any
// CHECK: [[IADDR:%.*]] = init_existential_addr [[ASTACK]] : $*Any, $(Int, Int)
// CHECK: [[TADDR0:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 0
// CHECK: store [[ARG0]] to [trivial] [[TADDR0]] : $*Int
// CHECK: [[TADDR1:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 1
// CHECK: store [[ARG1]] to [trivial] [[TADDR1]] : $*Int
// CHECK: [[LOAD_EXIST:%.*]] = load [trivial] [[IADDR]] : $*(Int, Int)
// CHECK: [[INIT_OPAQUE:%.*]] = init_existential_opaque [[LOAD_EXIST]] : $(Int, Int), $(Int, Int), $Any
// CHECK: [[APPLYARG:%.*]] = apply [[ARG2]]([[INIT_OPAQUE]]) : $@callee_owned (@in Any) -> ()
// CHECK: dealloc_stack [[ASTACK]] : $*Any
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_T0ypIxi_S2iIxyy_TR'
| 57.718861 | 350 | 0.637801 |
218ee26e0b64d50a793f1206b77e7bdddad66797 | 1,944 | //
// CrewMemberShortView.swift
//
// Created on 20/04/20.
// Copyright © 2020 WildAid. All rights reserved.
//
import SwiftUI
struct CrewMemberShortView: View {
@ObservedObject var crewMember: CrewMemberViewModel
var color = Color.main
var showingLicenseNumber = true
private enum Dimensions {
static let captainLabelVerticalPadding: CGFloat = 3
static let captainLabelHorizontalPadding: CGFloat = 10
static let backgroundOpacity = 0.1
static let padding: CGFloat = 16
static let radius: CGFloat = 50.0
}
var body: some View {
HStack(alignment: .top) {
VStack(spacing: .zero) {
TextLabel(title: crewMember.name)
if showingLicenseNumber {
CaptionLabel(title: "License Number \( crewMember.license)", color: .text, font: .footnote)
}
}
if crewMember.isCaptain {
HStack {
Text("Captain".uppercased())
.font(Font.caption1.weight(.semibold))
.foregroundColor(color)
.padding(.vertical, Dimensions.captainLabelVerticalPadding)
.padding(.horizontal, Dimensions.captainLabelHorizontalPadding)
}
.background(color.opacity(Dimensions.backgroundOpacity))
.cornerRadius(Dimensions.radius)
.padding(.trailing, showingLicenseNumber ? Dimensions.padding : .zero)
}
}
}
}
struct CrewMemberShortView_Previews: PreviewProvider {
static var previews: some View {
let sampleCaptain = CrewMemberViewModel.sample
sampleCaptain.isCaptain = true
return Group {
CrewMemberShortView(crewMember: .sample)
CrewMemberShortView(crewMember: sampleCaptain, showingLicenseNumber: false)
}
}
}
| 32.4 | 111 | 0.596193 |
69b753a7c93505269b371ba24fc73aa76e045cc5 | 5,648 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public extension LayoutConstraint {
override var description: String {
var description = "<"
description += descriptionForObject(self)
if let firstItem = conditionalOptional(from: self.firstItem) {
description += " \(descriptionForObject(firstItem))"
}
if firstAttribute != .notAnAttribute {
description += ".\(descriptionForAttribute(firstAttribute))"
}
description += " \(descriptionForRelation(relation))"
if let secondItem = self.secondItem {
description += " \(descriptionForObject(secondItem))"
}
if secondAttribute != .notAnAttribute {
description += ".\(descriptionForAttribute(secondAttribute))"
}
if multiplier != 1.0 {
description += " * \(multiplier)"
}
if secondAttribute == .notAnAttribute {
description += " \(constant)"
} else {
if constant > 0.0 {
description += " + \(constant)"
} else if constant < 0.0 {
description += " - \(abs(constant))"
}
}
if priority.rawValue != 1000.0 {
description += " ^\(priority)"
}
description += ">"
return description
}
}
private func descriptionForRelation(_ relation: LayoutRelation) -> String {
switch relation {
case .equal: return "=="
case .greaterThanOrEqual: return ">="
case .lessThanOrEqual: return "<="
#if swift(>=5.0)
@unknown default: return "unknown"
#endif
}
}
private func descriptionForAttribute(_ attribute: LayoutAttribute) -> String {
#if os(iOS) || os(tvOS)
switch attribute {
case .notAnAttribute: return "notAnAttribute"
case .top: return "top"
case .left: return "left"
case .bottom: return "bottom"
case .right: return "right"
case .leading: return "leading"
case .trailing: return "trailing"
case .width: return "width"
case .height: return "height"
case .centerX: return "centerX"
case .centerY: return "centerY"
case .lastBaseline: return "lastBaseline"
case .firstBaseline: return "firstBaseline"
case .topMargin: return "topMargin"
case .leftMargin: return "leftMargin"
case .bottomMargin: return "bottomMargin"
case .rightMargin: return "rightMargin"
case .leadingMargin: return "leadingMargin"
case .trailingMargin: return "trailingMargin"
case .centerXWithinMargins: return "centerXWithinMargins"
case .centerYWithinMargins: return "centerYWithinMargins"
#if swift(>=5.0)
@unknown default: return "unknown"
#endif
}
#else
switch attribute {
case .notAnAttribute: return "notAnAttribute"
case .top: return "top"
case .left: return "left"
case .bottom: return "bottom"
case .right: return "right"
case .leading: return "leading"
case .trailing: return "trailing"
case .width: return "width"
case .height: return "height"
case .centerX: return "centerX"
case .centerY: return "centerY"
case .lastBaseline: return "lastBaseline"
case .firstBaseline: return "firstBaseline"
#if swift(>=5.0)
@unknown default: return "unknown"
#endif
}
#endif
}
private func conditionalOptional<T>(from object: T?) -> T? {
object
}
private func conditionalOptional<T>(from object: T) -> T? {
Optional.some(object)
}
private func descriptionForObject(_ object: AnyObject) -> String {
let pointerDescription = String(format: "%p", UInt(bitPattern: ObjectIdentifier(object)))
var desc = ""
desc += type(of: object).description()
if let object = object as? ConstraintView {
desc += ":\(object.snp.label() ?? pointerDescription)"
} else if let object = object as? LayoutConstraint {
desc += ":\(object.label ?? pointerDescription)"
} else {
desc += ":\(pointerDescription)"
}
if let object = object as? LayoutConstraint, let file = object.constraint?.sourceLocation.0, let line = object.constraint?.sourceLocation.1 {
desc += "@\((file as NSString).lastPathComponent)#\(line)"
}
desc += ""
return desc
}
| 33.619048 | 145 | 0.629249 |
fc0f03fbcec00a93e25d721dfad26b08604a3140 | 19,542 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import NIO
import NIOConcurrencyHelpers
import XCTest
class SelectorTest: XCTestCase {
func testDeregisterWhileProcessingEvents() throws {
try assertDeregisterWhileProcessingEvents(closeAfterDeregister: false)
}
func testDeregisterAndCloseWhileProcessingEvents() throws {
try assertDeregisterWhileProcessingEvents(closeAfterDeregister: true)
}
private func assertDeregisterWhileProcessingEvents(closeAfterDeregister: Bool) throws {
struct TestRegistration: Registration {
var interested: SelectorEventSet
let socket: Socket
}
let selector = try NIO.Selector<TestRegistration>()
defer {
XCTAssertNoThrow(try selector.close())
}
let socket1 = try Socket(protocolFamily: PF_INET, type: Posix.SOCK_STREAM)
defer {
if socket1.isOpen {
XCTAssertNoThrow(try socket1.close())
}
}
try socket1.setNonBlocking()
let socket2 = try Socket(protocolFamily: PF_INET, type: Posix.SOCK_STREAM)
defer {
if socket2.isOpen {
XCTAssertNoThrow(try socket2.close())
}
}
try socket2.setNonBlocking()
let serverSocket = try ServerSocket.bootstrap(protocolFamily: PF_INET, host: "127.0.0.1", port: 0)
defer {
XCTAssertNoThrow(try serverSocket.close())
}
_ = try socket1.connect(to: serverSocket.localAddress())
_ = try socket2.connect(to: serverSocket.localAddress())
let accepted1 = try serverSocket.accept()!
defer {
XCTAssertNoThrow(try accepted1.close())
}
let accepted2 = try serverSocket.accept()!
defer {
XCTAssertNoThrow(try accepted2.close())
}
// Register both sockets with .write. This will ensure both are ready when calling selector.whenReady.
try selector.register(selectable: socket1 , interested: [.reset, .write], makeRegistration: { ev in
TestRegistration(interested: ev, socket: socket1)
})
try selector.register(selectable: socket2 , interested: [.reset, .write], makeRegistration: { ev in
TestRegistration(interested: ev, socket: socket2)
})
var readyCount = 0
try selector.whenReady(strategy: .block) { ev in
readyCount += 1
if socket1 === ev.registration.socket {
try selector.deregister(selectable: socket2)
if closeAfterDeregister {
try socket2.close()
}
} else if socket2 === ev.registration.socket {
try selector.deregister(selectable: socket1)
if closeAfterDeregister {
try socket1.close()
}
} else {
XCTFail("ev.registration.socket was neither \(socket1) or \(socket2) but \(ev.registration.socket)")
}
}
XCTAssertEqual(1, readyCount)
}
private static let testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse = 10
func testWeDoNotDeliverEventsForPreviouslyClosedChannels() {
/// We use this class to box mutable values, generally in this test anything boxed should only be read/written
/// on the event loop `el`.
class Box<T> {
init(_ value: T) {
self._value = value
}
private var _value: T
var value: T {
get {
XCTAssertNotNil(MultiThreadedEventLoopGroup.currentEventLoop)
return self._value
}
set {
XCTAssertNotNil(MultiThreadedEventLoopGroup.currentEventLoop)
self._value = newValue
}
}
}
enum DidNotReadError: Error {
case didNotReadGotInactive
case didNotReadGotReadComplete
}
/// This handler is inserted in the `ChannelPipeline` that are re-connected. So we're closing a bunch of
/// channels and (in the same event loop tick) we then connect the same number for which I'm using the
/// terminology 're-connect' here.
/// These re-connected channels will re-use the fd numbers of the just closed channels. The interesting thing
/// is that the `Selector` will still have events buffered for the _closed fds_. Note: the re-connected ones
/// will end up using the _same_ fds and this test ensures that we're not getting the outdated events. In this
/// case the outdated events are all `.readEOF`s which manifest as `channelReadComplete`s. If we're delivering
/// outdated events, they will also happen in the _same event loop tick_ and therefore we do quite a few
/// assertions that we're either in or not in that interesting event loop tick.
class HappyWhenReadHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private let didReadPromise: EventLoopPromise<Void>
private let hasReConnectEventLoopTickFinished: Box<Bool>
private var didRead: Bool = false
init(hasReConnectEventLoopTickFinished: Box<Bool>, didReadPromise: EventLoopPromise<Void>) {
self.didReadPromise = didReadPromise
self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished
}
func channelActive(ctx: ChannelHandlerContext) {
// we expect these channels to be connected within the re-connect event loop tick
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
}
func channelInactive(ctx: ChannelHandlerContext) {
// we expect these channels to be close a while after the re-connect event loop tick
XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value)
XCTAssertTrue(self.didRead)
if !self.didRead {
self.didReadPromise.fail(error: DidNotReadError.didNotReadGotInactive)
ctx.close(promise: nil)
}
}
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
// we expect these channels to get data only a while after the re-connect event loop tick as it's
// impossible to get a read notification in the very same event loop tick that you got registered
XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value)
XCTAssertFalse(self.didRead)
var buf = self.unwrapInboundIn(data)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual("H", buf.readString(length: 1)!)
self.didRead = true
self.didReadPromise.succeed(result: ())
}
func channelReadComplete(ctx: ChannelHandlerContext) {
// we expect these channels to get data only a while after the re-connect event loop tick as it's
// impossible to get a read notification in the very same event loop tick that you got registered
XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value)
XCTAssertTrue(self.didRead)
if !self.didRead {
self.didReadPromise.fail(error: DidNotReadError.didNotReadGotReadComplete)
ctx.close(promise: nil)
}
}
}
/// This handler will wait for all client channels to have come up and for one of them to have received EOF.
/// (We will see the EOF as they're set to support half-closure). Then, it'll close half of those file
/// descriptors and open the same number of new ones. The new ones (called re-connected) will share the same
/// fd numbers as the recently closed ones. That brings us in an interesting situation: There will (very likely)
/// be `.readEOF` events enqueued for the just closed ones and because the re-connected channels share the same
/// fd numbers danger looms. The `HappyWhenReadHandler` above makes sure nothing bad happens.
class CloseEveryOtherAndOpenNewOnesHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private let allChannels: Box<[Channel]>
private let serverAddress: SocketAddress
private let everythingWasReadPromise: EventLoopPromise<Void>
private let hasReConnectEventLoopTickFinished: Box<Bool>
init(allChannels: Box<[Channel]>,
hasReConnectEventLoopTickFinished: Box<Bool>,
serverAddress: SocketAddress,
everythingWasReadPromise: EventLoopPromise<Void>) {
self.allChannels = allChannels
self.serverAddress = serverAddress
self.everythingWasReadPromise = everythingWasReadPromise
self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished
}
func channelActive(ctx: ChannelHandlerContext) {
// collect all the channels
ctx.channel.getOption(option: ChannelOptions.allowRemoteHalfClosure).whenSuccess { halfClosureAllowed in
precondition(halfClosureAllowed,
"the test configuration is bogus: half-closure is dis-allowed which breaks the setup of this test")
}
self.allChannels.value.append(ctx.channel)
}
func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) {
// this is the `.readEOF` that is triggered by the `ServerHandler`'s `close` calls because our channel
// supports half-closure
guard self.allChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse else {
return
}
// all channels are up, so let's construct the situation we want to be in:
// 1. let's close half the channels
// 2. then re-connect (must be synchronous) the same number of channels and we'll get fd number re-use
ctx.channel.eventLoop.execute {
// this will be run immediately after we processed all `Selector` events so when
// `self.hasReConnectEventLoopTickFinished.value` becomes true, we're out of the event loop
// tick that is interesting.
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
self.hasReConnectEventLoopTickFinished.value = true
}
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
let everyOtherIndex = stride(from: 0, to: SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, by: 2)
for f in everyOtherIndex {
XCTAssertTrue(self.allChannels.value[f].isActive)
// close will succeed synchronously as we're on the right event loop.
self.allChannels.value[f].close(promise: nil)
XCTAssertFalse(self.allChannels.value[f].isActive)
}
// now we have completed stage 1: we freed up a bunch of file descriptor numbers, so let's open
// some new ones
var reconnectedChannelsHaveRead: [EventLoopFuture<Void>] = []
for _ in everyOtherIndex {
var hasBeenAdded: Bool = false
let p: EventLoopPromise<Void> = ctx.channel.eventLoop.newPromise()
reconnectedChannelsHaveRead.append(p.futureResult)
let newChannel = ClientBootstrap(group: ctx.eventLoop)
.channelInitializer { channel in
channel.pipeline.add(handler: HappyWhenReadHandler(hasReConnectEventLoopTickFinished: self.hasReConnectEventLoopTickFinished,
didReadPromise: p)).map {
hasBeenAdded = true
}
}
.connect(to: self.serverAddress)
.map { (channel: Channel) -> Void in
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value,
"""
This is bad: the connect of the channels to be re-connected has not
completed synchronously.
We assumed that on all platform a UNIX Domain Socket connect is
synchronous but we must be wrong :(.
The good news is: Not everything is lost, this test should also work
if you instead open a regular file (in O_RDWR) and just use this file's
fd with `ClientBootstrap(group: group).withConnectedSocket(fileFD)`.
Sure, a file is not a socket but it's always readable and writable and
that fulfills the requirements we have here.
I still hope this change will never have to be done.
Note: if you changed anything about the pipeline's handler adding/removal
you might also have a bug there.
""")
}
// just to make sure we got `newChannel` synchronously and we could add our handler to the
// pipeline synchronously too.
XCTAssertTrue(newChannel.isFulfilled)
XCTAssertTrue(hasBeenAdded)
}
// if all the new re-connected channels have read, then we're happy here.
EventLoopFuture<Void>.andAll(reconnectedChannelsHaveRead,
eventLoop: ctx.eventLoop).cascade(promise: self.everythingWasReadPromise)
// let's also remove all the channels so this code will not be triggered again.
self.allChannels.value.removeAll()
}
}
// all of the following are boxed as we need mutable references to them, they can only be read/written on the
// event loop `el`.
let allServerChannels: Box<[Channel]> = Box([])
var allChannels: Box<[Channel]> = Box([])
let hasReConnectEventLoopTickFinished: Box<Bool> = Box(false)
let numberOfConnectedChannels: Box<Int> = Box(0)
/// This spawns a server, always send a character immediately and after the first
/// `SelectorTest.numberOfChannelsToUse` have been established, we'll close them all. That will trigger
/// an `.readEOF` in the connected client channels which will then trigger other interesting things (see above).
class ServerHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private var number: Int = 0
private let allServerChannels: Box<[Channel]>
private let numberOfConnectedChannels: Box<Int>
init(allServerChannels: Box<[Channel]>, numberOfConnectedChannels: Box<Int>) {
self.allServerChannels = allServerChannels
self.numberOfConnectedChannels = numberOfConnectedChannels
}
func channelActive(ctx: ChannelHandlerContext) {
var buf = ctx.channel.allocator.buffer(capacity: 1)
buf.write(string: "H")
ctx.channel.writeAndFlush(buf, promise: nil)
self.number += 1
self.allServerChannels.value.append(ctx.channel)
if self.allServerChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse {
// just to be sure all of the client channels have connected
XCTAssertEqual(SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, numberOfConnectedChannels.value)
self.allServerChannels.value.forEach { c in
c.close(promise: nil)
}
}
}
}
let el = MultiThreadedEventLoopGroup(numberOfThreads: 1).next()
defer {
XCTAssertNoThrow(try el.syncShutdownGracefully())
}
let tempDir = createTemporaryDirectory()
let secondServerChannel = try! ServerBootstrap(group: el)
.childChannelInitializer { channel in
channel.pipeline.add(handler: ServerHandler(allServerChannels: allServerChannels,
numberOfConnectedChannels: numberOfConnectedChannels))
}
.bind(to: SocketAddress(unixDomainSocketPath: "\(tempDir)/server-sock.uds"))
.wait()
let everythingWasReadPromise: EventLoopPromise<Void> = el.newPromise()
XCTAssertNoThrow(try el.submit { () -> [EventLoopFuture<Channel>] in
(0..<SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse).map { (_: Int) in
ClientBootstrap(group: el)
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.channelInitializer { channel in
channel.pipeline.add(handler: CloseEveryOtherAndOpenNewOnesHandler(allChannels: allChannels,
hasReConnectEventLoopTickFinished: hasReConnectEventLoopTickFinished,
serverAddress: secondServerChannel.localAddress!,
everythingWasReadPromise: everythingWasReadPromise))
}
.connect(to: secondServerChannel.localAddress!)
.map { channel in
numberOfConnectedChannels.value += 1
return channel
}
}
}.wait().forEach { XCTAssertNoThrow(try $0.wait()) } as Void)
XCTAssertNoThrow(try everythingWasReadPromise.futureResult.wait())
XCTAssertNoThrow(try FileManager.default.removeItem(at: URL(fileURLWithPath: tempDir)))
}
}
| 53.393443 | 160 | 0.587913 |
875408050ded3597adac66a2adeb7fffd8ec710e | 1,424 | //
// FSAlbumViewCell.swift
// YPImgePicker
//
// Created by Sacha Durand Saint Omer on 2015/11/14.
// Copyright © 2015 Yummypets. All rights reserved.
//
import UIKit
import Stevia
class FSAlbumViewCell: UICollectionViewCell {
var representedAssetIdentifier: String!
let imageView = UIImageView()
let durationLabel = UILabel()
let selectionOverlay = UIView()
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override init(frame: CGRect) {
super.init(frame: frame)
sv(
imageView,
durationLabel,
selectionOverlay
)
imageView.fillContainer()
selectionOverlay.fillContainer()
layout(
durationLabel-5-|,
5
)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
durationLabel.textColor = .white
durationLabel.font = .systemFont(ofSize: 12)
durationLabel.isHidden = true
selectionOverlay.backgroundColor = .black
selectionOverlay.alpha = 0
backgroundColor = UIColor(r: 247, g: 247, b: 247)
}
override var isSelected: Bool {
didSet { isHighlighted = isSelected }
}
override var isHighlighted: Bool {
didSet {
selectionOverlay.alpha = isHighlighted ? 0.5 : 0
}
}
}
| 25.428571 | 99 | 0.610955 |
20dea1060036d9a22b2f36271b1e6ad8b4610c31 | 6,115 | //
// PhotoOperation.swift
// VoteYourSpider
//
// Created by Richard Turton on 17/04/2015.
// Copyright (c) 2015 raywenderlich. All rights reserved.
//
// http://www.raywenderlich.com/76341/use-nsoperation-nsoperationqueue-swift
//
import Foundation
enum AssetRecordState
{
case new, succeed, failed
}
class AssetRecord
{
let url: String
let name: String
var type = PHAssetMediaType.image
var state = AssetRecordState.new
var item: PHAsset!
init(url:String, item:PHAsset, name:String)
{
self.url = url
self.item = item
self.name = name
self.type = item.mediaType
}
}
class PendingOperation
{
lazy var savingInProgress = [AssetSaver]()
lazy var savingQueue:OperationQueue = {
var queue = OperationQueue()
queue.name = "Saving queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
}
//--------------------------------------------------------------------------
//
// CLASS
// @NSOperation
//
//--------------------------------------------------------------------------
class AssetSaver: Foundation.Operation
{
let assetRecord: AssetRecord
let needThumbail: Bool
lazy var phManager: PHImageManager =
{
return PHImageManager.default()
}()
lazy var phOptions: PHImageRequestOptions =
{
let options = PHImageRequestOptions()
options.isSynchronous = true;
return options
}()
init(photoRecord: AssetRecord, thumbnail:Bool=true)
{
self.assetRecord = photoRecord
self.needThumbail = thumbnail
}
override func main()
{
if self.isCancelled
{
return
}
var success = false
// for video
if self.assetRecord.type == PHAssetMediaType.video
{
phManager.requestAVAsset(forVideo: self.assetRecord.item, options: nil) { (asset, audioMix, info) in
DispatchQueue.main.async(execute: {
let asset = asset as? AVURLAsset
print("File to be written at: \(self.assetRecord.url)")
if let newData:NSData = NSData(contentsOf: (asset?.url)!)
{
success = newData.write(toFile: self.assetRecord.url, atomically: true)
if !success
{
print("general error - unable to write to file", terminator: "\n")
self.assetRecord.state = .failed
}
else
{
self.saveThumbnail()
}
}
})
}
}
else if self.assetRecord.type == PHAssetMediaType.image
{
phManager.requestImageData(for: self.assetRecord.item, options: self.phOptions)
{
imageData,dataUTI,orientation,info in
// save actual phasset file
print("File to be written at: \(self.assetRecord.url)")
success = (imageData! as NSData).write(toFile: self.assetRecord.url, atomically: true)
if !success
{
print("general error - unable to write to file", terminator: "\n")
self.assetRecord.state = .failed
}
else
{
self.saveThumbnail()
}
}
}
}
func saveThumbnail()
{
if self.needThumbail
{
// save phasset's thumbnail file
let option = PHImageRequestOptions()
option.resizeMode = PHImageRequestOptionsResizeMode.exact
option.isSynchronous = true
self.phManager.requestImage(for: self.assetRecord.item, targetSize: CGSize(width: 200, height: 200), contentMode: PHImageContentMode.aspectFill, options: option, resultHandler: { (incomingImage, info) -> Void in
print("Thumb to be written at: \(ConstantsVO.thumbPath.path + "/" + self.assetRecord.name)")
do
{
var tmpName:String = self.assetRecord.name
if (self.assetRecord.type == PHAssetMediaType.video)
{
var splitItems = self.assetRecord.name.components(separatedBy: ".")
_ = splitItems.popLast()
tmpName = splitItems.joined(separator: ".") + ".jpg"
}
try UIImagePNGRepresentation(incomingImage!)!.write(to: URL(fileURLWithPath: ConstantsVO.thumbPath.path + "/" + tmpName), options: .atomic)
}
catch
{
print(error)
}
if self.isCancelled
{
return
}
self.assetRecord.state = .succeed
})
}
else
{
if self.isCancelled
{
return
}
self.assetRecord.state = .succeed
}
}
}
//--------------------------------------------------------------------------
//
// CLASS
// @NSOperation
//
//--------------------------------------------------------------------------
class ThumbGenerator: Foundation.Operation
{
let instance: GalleryInstance
var state = AssetRecordState.new
var thumb: UIImage!
init(photoRecord: GalleryInstance)
{
self.instance = photoRecord
}
override func main()
{
if self.isCancelled
{
return
}
guard let image = UIImage(contentsOfFile: ConstantsVO.thumbPath.path + "/" + self.instance.url) else
{
self.state = .failed
return
}
self.thumb = image
self.state = .succeed
}
}
| 28.981043 | 223 | 0.483892 |
46064c1bd7ce7a2f436b83dc77c74f602a85663e | 5,448 | //
// MealViewController.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/3/6.
// Copyright © 2017年 MAD. All rights reserved.
//
import UIKit
import SwipyCell
class MealViewController: UIViewController {
@IBOutlet var tableView: UITableView!
let mealItemCellIdentifier = "MealItemCell"
let mealHeaderCellIdentifier = "MealHeaderCell"
var dailyPlan = DailyPlan()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = dailyPlan.date.dateAndWeekday()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
BaseManager.shared.save(object: dailyPlan)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
if segue.identifier == "SearchFoods",
let button = sender as? UIButton {
let destinationVC = segue.destination as! FoodSearchViewController
let when = Food.When(rawValue: dailyPlan.meals[button.tag].name)
destinationVC.delegate = self
destinationVC.when = when
}
}
}
extension MealViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return dailyPlan.meals.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let meal = dailyPlan.meals[section]
return meal.mealFoods.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: mealItemCellIdentifier, for: indexPath) as! MealItemCell
let meal = dailyPlan.meals[indexPath.section]
let mealFood = meal.mealFoods[indexPath.row]
cell.foodNameLabel.text = mealFood.food?.name
let deleteImageView = UIImageView(image: #imageLiteral(resourceName: "cross"))
deleteImageView.contentMode = .center
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .exit, swipeView: deleteImageView, swipeColor: UIColor.red) { [unowned self](cell, state, mode) in
self.deleteFood(cell)
}
return cell
}
private func deleteFood(_ cell: UITableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let meal = dailyPlan.meals[indexPath.section]
BaseManager.shared.transaction {
meal.mealFoods.remove(objectAtIndex: indexPath.row)
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
extension MealViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let meal = dailyPlan.meals[section]
let cell = tableView.dequeueReusableCell(withIdentifier: mealHeaderCellIdentifier) as! MealHeaderCell
cell.mealNameLabel.text = meal.name
cell.section = section
cell.delegate = self
cell.addFoodButton.tag = section
let sectionView = UIView(frame: cell.frame)
sectionView.addSubview(cell)
return sectionView
}
}
extension MealViewController: MealHeaderCellDelegate {
func addFoodButtonTapped(section: Int) {
// performSegue(withIdentifier: "SearchFoods", sender: section)
}
func pickFoodButtonTapped(section: Int) {
let meal = dailyPlan.meals[section]
let when = Food.When(rawValue: meal.name)
let mealFood = FoodManager.shared.randomMealFood(of: when!)
BaseManager.shared.transaction {
mealFood.food?.addNeedIngredientCount()
meal.mealFoods.append(mealFood)
}
let indexPath = IndexPath(row: meal.mealFoods.count-1, section: section)
tableView.insertRows(at: [indexPath], with: .fade)
}
}
extension MealViewController: SwipyCellDelegate {
func swipyCellDidStartSwiping(_ cell: SwipyCell) {
}
func swipyCellDidFinishSwiping(_ cell: SwipyCell) {
}
func swipyCell(_ cell: SwipyCell, didSwipeWithPercentage percentage: CGFloat) {
}
}
extension MealViewController: FoodSearchViewControllerDelegate {
func didChoose(food: Food, when: Food.When) {
for meal in dailyPlan.meals {
if meal.name == when.rawValue {
BaseManager.shared.transaction {
food.addNeedIngredientCount()
let mealFood = MealFood(food: food)
meal.mealFoods.append(mealFood)
}
let indexPath = IndexPath(row: meal.mealFoods.count-1, section: dailyPlan.meals.index(of: meal)!)
tableView.insertRows(at: [indexPath], with: .fade)
}
}
}
}
| 35.607843 | 165 | 0.657489 |
794f789362535436647980519e15d0dcdd47b80c | 542 | //
// ██╗ ██╗████████╗███████╗██╗ ██╗████████╗
// ╚██╗██╔╝╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝
// ╚███╔╝ ██║ █████╗ ╚███╔╝ ██║
// ██╔██╗ ██║ ██╔══╝ ██╔██╗ ██║
// ██╔╝ ██╗ ██║ ███████╗██╔╝ ██╗ ██║
// ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝
//
// xColorExtension.swift
// xColor (https://github.com/cyanzhong/xTextHandler/)
//
// Created by cyan on 16/7/4.
// Copyright © 2016年 cyan. All rights reserved.
//
import Foundation
import XcodeKit
class xColorExtension: NSObject, XCSourceEditorExtension {
}
| 24.636364 | 58 | 0.361624 |
909e5413d09cff1063cebcc16e43e0d49079b940 | 2,733 | //
// Money.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 8/23/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
public struct Money: Hashable, Codable {
public let amount: Int64
public let decimals: Int
public private(set) var isBigAmount = false
public private(set) var isSmallAmount = false
public init(_ amount: Int64, _ decimals: Int) {
self.amount = amount
self.decimals = decimals
}
}
public extension Money {
init(value: Decimal, _ decimals: Int) {
let decimalValue = (value * pow(10, decimals)).rounded()
let isValidDecimal = Decimal(Int64.max) >= decimalValue
self.amount = isValidDecimal ? Int64(truncating: decimalValue as NSNumber) : 0
self.decimals = decimals
self.isBigAmount = self.amount == 0 && value > 0 && decimalValue > 0
self.isSmallAmount = self.amount == 0 && value > 0 && decimalValue == 0
}
}
public extension Money {
var displayText: String {
return MoneyUtil.getScaledText(amount, decimals: decimals)
}
var displayTextWithoutSpaces: String {
return displayText.replacingOccurrences(of: " ", with: "")
}
func displayTextFull(isFiat: Bool) -> String {
return MoneyUtil.getScaledFullText(amount, decimals: decimals, isFiat: isFiat)
}
var displayShortText: String {
return MoneyUtil.getScaledShortText(amount, decimals: decimals)
}
}
public extension Money {
var isZero: Bool {
return amount == 0
}
var decimalValue: Decimal {
return Decimal(amount) / pow(10, decimals)
}
var doubleValue: Double {
return decimalValue.doubleValue
}
var floatValue: Float {
return decimalValue.floatValue
}
}
public extension Money {
func add(_ value: Double) -> Money {
let additionalValue = Int64(value * pow(10, decimals).doubleValue)
return Money(amount + additionalValue, decimals)
}
func minus(_ value: Double) -> Money {
let additionalValue = Int64(value * pow(10, decimals).doubleValue)
var newAmount = amount - additionalValue
if newAmount < 0 {
newAmount = 0
}
return Money(newAmount, decimals)
}
}
//MARK: - Calculation
public extension Money {
static func price(amount: Int64, amountDecimals: Int, priceDecimals: Int) -> Money {
let precisionDiff = priceDecimals - amountDecimals + 8
let decimalValue = Decimal(amount) / pow(10, precisionDiff)
return Money((decimalValue * pow(10, priceDecimals)).int64Value, priceDecimals)
}
}
| 25.783019 | 88 | 0.629711 |
336cd6fc234361eafdc1a2b1e12cd3e441e3417d | 80,520 | //
// ————————————————————————————————————————————————————————————————————————————————————————————
// ||||||||| Swift-Big-Number-Core.swift ||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
// Created by Marcel Kröker on 30.09.16.
// Copyright (c) 2016 Blubyte. All rights reserved.
//
//
//
// ——————————————————————————————————————————— v1.0 ———————————————————————————————————————————
// - Initial Release.
//
// ——————————————————————————————————————————— v1.1 ———————————————————————————————————————————
// - Improved String conversion, now about 45x faster, uses base 10^9 instead
// of base 10.
// - bytes renamed to limbs.
// - Uses typealias for limbs and digits.
//
// ——————————————————————————————————————————— v1.2 ———————————————————————————————————————————
// - Improved String conversion, now about 10x faster, switched from base 10^9
// to 10^18 (biggest possible decimal base).
// - Implemented karatsuba multiplication algorithm, about 5x faster than the
// previous algorithm.
// - Addition is 1.3x faster.
// - Addtiton and subtraction omit trailing zeros, algorithms need less
// operations now.
// - Implemented exponentiation by squaring.
// - New storage (BStorage) for often used results.
// - Uses uint_fast64_t instead of UInt64 for Limbs and Digits.
//
// ——————————————————————————————————————————— v1.3 ———————————————————————————————————————————
// - Huge Perfomance increase by skipping padding zeros and new multiplication
// algotithms.
// - Printing is now about 10x faster, now on par with GMP.
// - Some operations now use multiple cores.
//
// ——————————————————————————————————————————— v1.4 ———————————————————————————————————————————
// - Reduced copying by using more pointers.
// - Multiplication is about 50% faster.
// - String to BInt conversion is 2x faster.
// - BInt to String also performs 50% better.
//
// ——————————————————————————————————————————— v1.5 ———————————————————————————————————————————
// - Updated for full Swift 3 compatibility.
// - Various optimizations:
// - Multiplication is about 2x faster.
// - BInt to String conversion is more than 3x faster.
// - String to BInt conversion is more than 2x faster.
//
// ——————————————————————————————————————————— v1.6 ———————————————————————————————————————————
// - Code refactored into modules.
// - Renamed the project to SMP (Swift Multiple Precision).
// - Added arbitrary base conversion.
//
// ——————————————————————————————————————————— v2.0 ———————————————————————————————————————————
// - Updated for full Swift 4 compatibility.
// - Big refactor, countless optimizations for even better performance.
// - BInt conforms to SignedNumeric and BinaryInteger, this makes it very easy to write
// generic code.
// - BDouble also conforms to SignedNumeric and has new functionalities.
//
//
//
// ————————————————————————————————————————————————————————————————————————————————————————————
// |||||||||||||||| Evolution ||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Planned features of BInt v3.0:
// - Implement some basic cryptography functions.
// - General code cleanup, better documentation.
// - More extensive tests.
// - Please contact me if you have any suggestions for new features!
//
//
//
// ————————————————————————————————————————————————————————————————————————————————————————————
// |||||||||||||||| Basic Project syntax conventions ||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
// Indentation: Tabs
//
// Align: Spaces
//
// Style: allman
// func foo(...)
// {
// ...
// }
//
// Single line if-statement:
// if condition { code }
//
// Maximum line length: 96 characters
//
// ————————————————————————————————————————————————————————————————————————————————————————————
// MARK: - Imports
// ————————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Imports |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
import Foundation
// MARK: - Typealiases
// ————————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Typealiases |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
// Limbs are basically single Digits in base 2^64. Each slot in an Limbs array stores one
// Digit of the number. The least significant digit is stored at index 0, the most significant
// digit is stored at the last index.
public typealias Limbs = [UInt64]
public typealias Limb = UInt64
// A digit is a number in base 10^18. This is the biggest possible base that
// fits into an unsigned 64 bit number while maintaining the propery that the square root of
// the base is a whole number and a power of ten . Digits are required for printing BInt
// numbers. Limbs are converted into Digits first, and then printed.
public typealias Digits = [UInt64]
public typealias Digit = UInt64
// MARK: - Imports
// ————————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Operators |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
precedencegroup ExponentiationPrecedence
{
associativity: left
higherThan: MultiplicationPrecedence
lowerThan: BitwiseShiftPrecedence
}
// Exponentiation operator
infix operator ** : ExponentiationPrecedence
// MARK: - BInt
// ————————————————————————————————————————————————————————————————————————————————————————————
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// |||||||| BInt ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
/// BInt is an arbitrary precision integer value type. It stores a number in base 2^64 notation
/// as an array. Each element of the array is called a limb, which is of type UInt64, the whole
/// array is called limbs and has the type [UInt64]. A boolean sign variable determines if the
/// number is positive or negative. If sign == true, then the number is smaller than 0,
/// otherwise it is greater or equal to 0. It stores the 64 bit digits in little endian, that
/// is, the least significant digit is stored in the array index 0:
///
/// limbs == [] := undefined, should throw an error
/// limbs == [0], sign == false := 0, defined as positive
/// limbs == [0], sign == true := undefined, should throw an error
/// limbs == [n] := n if sign == false, otherwise -n, given 0 <= n < 2^64
///
/// limbs == [l0, l1, l2, ..., ln] :=
/// (l0 * 2^(0*64)) +
/// (11 * 2^(1*64)) +
/// (12 * 2^(2*64)) +
/// ... +
/// (ln * 2^(n*64))
public struct BInt:
SignedNumeric, // Implies Numeric, Equatable, ExpressibleByIntegerLiteral
BinaryInteger, // Implies Hashable, CustomStringConvertible, Strideable, Comparable
ExpressibleByFloatLiteral
{
//
//
// MARK: - Internal data
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Internal data |||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// Stores the sign of the number represented by the BInt. "true" means that the number is
/// less than zero, "false" means it's more than or equal to zero.
internal var sign = false
/// Stores the absolute value of the number represented by the BInt. Each element represents
/// a "digit" of the number in base 2^64 in an acending order, where the first element is
/// the least significant "digit". This representations is the most efficient one for
/// computations, however it also means that the number is stored in a non-human-readable
/// fashion. To make it readable as a decimal number, BInt offers the required functions.
internal var limbs = Limbs()
// Required by the protocol "Numeric".
public typealias Magnitude = UInt64
// Required by the protocol "Numeric". It's pretty useless because the magnitude of a BInt won't
// fit into a UInt64 generally, so we just return the first limb of the BInt.
public var magnitude: UInt64
{
return self.limbs[0]
}
// Required by the protocol "BinaryInteger".
public typealias Words = [UInt]
// Required by the protocol "BinaryInteger".
public var words: BInt.Words
{
return self.limbs.map{ UInt($0) }
}
/// Returns the size of the BInt in bits.
public var size: Int
{
return 1 + (self.limbs.count * MemoryLayout<Limb>.size * 8)
}
/// Returns a formated human readable string that says how much space (in bytes, kilobytes, megabytes, or gigabytes) the BInt occupies.
public var sizeDescription: String
{
// One bit for the sign, plus the size of the limbs.
let bits = self.size
if bits < 8_000
{
return String(format: "%.1f b", Double(bits) / 8.0)
}
if bits < 8_000_000
{
return String(format: "%.1f kb", Double(bits) / 8_000.0)
}
if UInt64(bits) < UInt64(8_000_000_000.0)
{
return String(format: "%.1f mb", Double(bits) / 8_000_000.0)
}
return String(format: "%.1f gb", Double(bits) / 8_000_000_000.0)
}
//
//
// MARK: - Initializers
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Initializers ||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// Root initializer for all other initializers. Because no sign is provided, the new
/// instance is positive by definition.
internal init(limbs: Limbs)
{
precondition(limbs != [], "BInt can't be initialized with limbs == []")
self.limbs = limbs
}
/// Create an instance initialized with a sign and a limbs array.
internal init(sign: Bool, limbs: Limbs)
{
self.init(limbs: limbs)
self.sign = sign
}
/// Create an instance initialized with the value 0.
init()
{
self.init(limbs: [0])
}
/// Create an instance initialized to an integer value.
public init(_ z: Int)
{
// Since abs(Int.min) > Int.max, it is necessary to handle
// z == Int.min as a special case.
if z == Int.min
{
self.init(sign: true, limbs: [Limb(Int.max) + 1])
return
}
else
{
self.init(sign: z < 0, limbs: [Limb(abs(z))])
}
}
/// Create an instance initialized to an unsigned integer value.
public init(_ n: UInt)
{
self.init(limbs: [Limb(n)])
}
/// Create an instance initialized to a string value.
public init?(_ str: String)
{
var (str, sign, base, limbs) = (str, false, [Limb(1)], [Limb(0)])
limbs.reserveCapacity(Int(Double(str.count) / log10(pow(2.0, 64.0))))
if str.hasPrefix("-")
{
str.remove(at: str.startIndex)
sign = str != "0"
}
for chunk in String(str.reversed()).split(19).map({ String($0.reversed()) })
{
if let num = Limb(String(chunk))
{
limbs.addProductOf(multiplier: base, multiplicand: num)
base = base.multiplyingBy([10_000_000_000_000_000_000])
}
else
{
return nil
}
}
self.init(sign: sign, limbs: limbs)
}
/// Create an instance initialized to a string with the value of mathematical numerical
/// system of the specified radix (base). So for example, to get the value of hexadecimal
/// string radix value must be set to 16.
public init?(_ number: String, radix: Int)
{
if radix == 10
{
// Regular string init is faster for decimal numbers.
self.init(number)
return
}
let chars: [Character] = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
]
var (number, sign, base, limbs) = (number, false, [Limb(1)], [Limb(0)])
if number.hasPrefix("-")
{
number.remove(at: number.startIndex)
sign = number != "0"
}
for char in number.reversed()
{
if let digit = chars.index(of: char), digit < radix
{
limbs.addProductOf(multiplier: base, multiplicand: Limb(digit))
base = base.multiplyingBy([Limb(radix)])
}
else
{
return nil
}
}
self.init(sign: sign, limbs: limbs)
}
/// Create an instance initialized to a string with the value of mathematical numerical
/// system of the specified radix (base). You have to specify the base as a prefix, so for
/// example, "0b100101010101110" is a vaild input for a binary number. Currently,
/// hexadecimal (0x), octal (0o) and binary (0b) are supported.
public init?(prefixedNumber number: String)
{
if number.hasPrefix("0x")
{
self.init(String(number.dropFirst(2)), radix: 16)
}
if number.hasPrefix("0o")
{
self.init(String(number.dropFirst(2)), radix: 8)
}
if number.hasPrefix("0b")
{
self.init(String(number.dropFirst(2)), radix: 2)
}
else
{
return nil
}
}
// Requierd by protocol ExpressibleByFloatLiteral.
public init(floatLiteral value: Double)
{
self.init(sign: value < 0.0, limbs: [Limb(value)])
}
// Required by protocol ExpressibleByIntegerLiteral.
public init(integerLiteral value: Int)
{
self.init(value)
}
// Required by protocol Numeric
public init?<T>(exactly source: T) where T : BinaryInteger
{
self.init(Int(source))
}
/// Creates an integer from the given floating-point value, rounding toward zero.
public init<T>(_ source: T) where T : BinaryFloatingPoint
{
self.init(Int(source))
}
/// Creates a new instance from the given integer.
public init<T>(_ source: T) where T : BinaryInteger
{
self.init(Int(source))
}
/// Creates a new instance with the representable value that’s closest to the given integer.
public init<T>(clamping source: T) where T : BinaryInteger
{
self.init(Int(source))
}
/// Creates an integer from the given floating-point value, if it can be represented
/// exactly.
public init?<T>(exactly source: T) where T : BinaryFloatingPoint
{
self.init(source)
}
/// Creates a new instance from the bit pattern of the given instance by sign-extending or
/// truncating to fit this type.
public init<T>(truncatingIfNeeded source: T) where T : BinaryInteger
{
self.init(source)
}
//
//
// MARK: - Struct functions
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Struct functions ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Required by protocol CustomStringConvertible.
public var description: String
{
return (self.sign ? "-" : "").appending(self.limbs.decimalRepresentation)
}
/// Returns the BInt's value in the given base (radix) as a string.
public func asString(radix: Int) -> String
{
let chars: [Character] = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
]
var (limbs, res) = (self.limbs, "")
while !limbs.equalTo(0)
{
let divmod = limbs.divMod([Limb(radix)])
if let r = divmod.remainder.first, r < radix
{
res.append(chars[Int(r)])
limbs = divmod.quotient
}
else
{
fatalError("BInt.asString: Base too big, should be between 2 and 62")
}
}
if res == "" { return "0" }
return (self.sign ? "-" : "").appending(String(res.reversed()))
}
/// Returns BInt's value as an integer. Conversion only works when self has only one limb
/// that's within the range of the type "Int".
func asInt() -> Int?
{
if self.limbs.count != 1 { return nil }
let number = self.limbs[0]
if number <= Limb(Int.max)
{
return self.sign ? -Int(number) : Int(number)
}
if number == (Limb(Int.max) + 1) && self.sign
{
// This is a special case where self == Int.min
return Int.min
}
return nil
}
var rawValue: (sign: Bool, limbs: [UInt64])
{
return (self.sign, self.limbs)
}
public var hashValue: Int
{
return "\(self.sign)\(self.limbs)".hashValue
}
// Required by the protocol "BinaryInteger". A Boolean value indicating whether this type is a
// signed integer type.
public static var isSigned: Bool
{
return true
}
// Required by the protocol "BinaryInteger". The number of bits in the current binary
// representation of this value.
public var bitWidth: Int
{
return self.limbs.bitWidth
}
/// Returns -1 if this value is negative and 1 if it’s positive; otherwise, 0.
public func signum() -> BInt
{
if self.isZero() { return BInt(0) }
else if self.isPositive() { return BInt(1) }
else { return BInt(-1) }
}
func isPositive() -> Bool { return !self.sign }
func isNegative() -> Bool { return self.sign }
func isZero() -> Bool { return self.limbs[0] == 0 && self.limbs.count == 1 }
func isNotZero() -> Bool { return self.limbs[0] != 0 || self.limbs.count > 1 }
func isOdd() -> Bool { return self.limbs[0] & 1 == 1 }
func isEven() -> Bool { return self.limbs[0] & 1 == 0 }
/// The number of trailing zeros in this value’s binary representation.
public var trailingZeroBitCount: Int
{
var i = 0
while true
{
if self.limbs.getBit(at: i) { return i }
i += 1
}
}
//
//
// MARK: - BInt Shifts
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Shifts |||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func <<<T: BinaryInteger>(lhs: BInt, rhs: T) -> BInt
{
if rhs < 0 { return lhs >> rhs }
let limbs = lhs.limbs.shiftingUp(Int(rhs))
let sign = lhs.isNegative() && !limbs.equalTo(0)
return BInt(sign: sign, limbs: limbs)
}
public static func <<=<T: BinaryInteger>(lhs: inout BInt, rhs: T)
{
lhs.limbs.shiftUp(Int(rhs))
}
public static func >><T: BinaryInteger>(lhs: BInt, rhs: T) -> BInt
{
if rhs < 0 { return lhs << rhs }
return BInt(sign: lhs.sign, limbs: lhs.limbs.shiftingDown(Int(rhs)))
}
public static func >>=<T: BinaryInteger>(lhs: inout BInt, rhs: T)
{
lhs.limbs.shiftDown(Int(rhs))
}
//
//
// MARK: - BInt Bitwise AND
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt BInt Bitwise AND |||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// Returns the result of performing a bitwise AND operation on the two given values.
public static func &(lhs: BInt, rhs: BInt) -> BInt
{
var res: Limbs = [0]
for i in 0..<(64 * Swift.max(lhs.limbs.count, rhs.limbs.count))
{
let newBit = lhs.limbs.getBit(at: i) && rhs.limbs.getBit(at: i)
res.setBit(at: i, to: newBit)
}
return BInt(sign: lhs.sign && rhs.sign, limbs: res)
}
// static func &(lhs: Int, rhs: BInt) -> BInt
// static func &(lhs: BInt, rhs: Int) -> BInt
/// Stores the result of performing a bitwise AND operation on the two given values in the
/// left-hand-side variable.
public static func &=(lhs: inout BInt, rhs: BInt)
{
let res = lhs & rhs
lhs = res
}
// static func &=(inout lhs: Int, rhs: BInt)
// static func &=(inout lhs: BInt, rhs: Int)
//
//
// MARK: - BInt Bitwise OR
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Bitwise OR |||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func |(lhs: BInt, rhs: BInt) -> BInt
{
var res: Limbs = [0]
for i in 0..<(64 * Swift.max(lhs.limbs.count, rhs.limbs.count))
{
let newBit = lhs.limbs.getBit(at: i) || rhs.limbs.getBit(at: i)
res.setBit(at: i, to: newBit)
}
return BInt(sign: lhs.sign || rhs.sign, limbs: res)
}
// static func |(lhs: Int, rhs: BInt) -> BInt
// static func |(lhs: BInt, rhs: Int) -> BInt
//
public static func |=(lhs: inout BInt, rhs: BInt)
{
let res = lhs | rhs
lhs = res
}
// static func |=(inout lhs: Int, rhs: BInt)
// static func |=(inout lhs: BInt, rhs: Int)
//
//
// MARK: - BInt Bitwise OR
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Bitwise XOR ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func ^(lhs: BInt, rhs: BInt) -> BInt
{
var res: Limbs = [0]
for i in 0..<(64 * Swift.max(lhs.limbs.count, rhs.limbs.count))
{
let newBit = lhs.limbs.getBit(at: i) != rhs.limbs.getBit(at: i)
res.setBit(at: i, to: newBit)
}
return BInt(sign: lhs.sign != rhs.sign, limbs: res)
}
public static func ^=(lhs: inout BInt, rhs: BInt)
{
let res = lhs ^ rhs
lhs = res
}
//
//
// MARK: - BInt Bitwise NOT
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Bitwise NOT ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public prefix static func ~(x: BInt) -> BInt
{
var res = x.limbs
for i in 0..<(res.bitWidth)
{
res.setBit(at: i, to: !res.getBit(at: i))
}
while res.last! == 0 && res.count > 1 { res.removeLast() }
return BInt(sign: !x.sign, limbs: res)
}
//
//
// MARK: - BInt Addition
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Addition |||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public prefix static func +(x: BInt) -> BInt
{
return x
}
// Required by protocol Numeric
public static func +=(lhs: inout BInt, rhs: BInt)
{
if lhs.sign == rhs.sign
{
lhs.limbs.addLimbs(rhs.limbs)
return
}
let rhsIsMin = rhs.limbs.lessThan(lhs.limbs)
lhs.limbs.difference(rhs.limbs)
lhs.sign = (rhs.sign && !rhsIsMin) || (lhs.sign && rhsIsMin) // DNF minimization
if lhs.isZero() { lhs.sign = false }
}
// Required by protocol Numeric
public static func +(lhs: BInt, rhs: BInt) -> BInt
{
var lhs = lhs
lhs += rhs
return lhs
}
static func +(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) + rhs }
static func +(lhs: BInt, rhs: Int) -> BInt { return lhs + BInt(rhs) }
static func +=(lhs: inout Int, rhs: BInt) { lhs += (BInt(lhs) + rhs).asInt()! }
static func +=(lhs: inout BInt, rhs: Int) { lhs += BInt(rhs) }
//
//
// MARK: - BInt Negation
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Negation |||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Required by protocol SignedNumeric
public mutating func negate()
{
if self.isNotZero() { self.sign = !self.sign }
}
// Required by protocol SignedNumeric
public static prefix func -(n: BInt) -> BInt
{
var n = n
n.negate()
return n
}
//
//
// MARK: - BInt Subtraction
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Subtraction ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Required by protocol Numeric
public static func -(lhs: BInt, rhs: BInt) -> BInt
{
return lhs + -rhs
}
static func -(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) - rhs }
static func -(lhs: BInt, rhs: Int) -> BInt { return lhs - BInt(rhs) }
// Required by protocol Numeric
public static func -=(lhs: inout BInt, rhs: BInt) { lhs += -rhs }
static func -=(lhs: inout Int, rhs: BInt) { lhs = (BInt(lhs) - rhs).asInt()! }
static func -=(lhs: inout BInt, rhs: Int) { lhs -= BInt(rhs) }
//
//
// MARK: - BInt Multiplication
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Multiplication |||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Required by protocol Numeric
public static func *(lhs: BInt, rhs: BInt) -> BInt
{
let sign = !(lhs.sign == rhs.sign || lhs.isZero() || rhs.isZero())
return BInt(sign: sign, limbs: lhs.limbs.multiplyingBy(rhs.limbs))
}
static func *(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) * rhs }
static func *(lhs: BInt, rhs: Int) -> BInt { return lhs * BInt(rhs) }
// Required by protocol SignedNumeric
public static func *=(lhs: inout BInt, rhs: BInt) { lhs = lhs * rhs }
static func *=(lhs: inout Int, rhs: BInt) { lhs = (BInt(lhs) * rhs).asInt()! }
static func *=(lhs: inout BInt, rhs: Int) { lhs = lhs * BInt(rhs) }
//
//
// MARK: - BInt Exponentiation
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Exponentiation |||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
static func **(lhs: BInt, rhs: Int) -> BInt
{
precondition(rhs >= 0, "BInts can't be exponentiated with exponents < 0")
return BInt(sign: lhs.sign && (rhs % 2 != 0), limbs: lhs.limbs.exponentiating(rhs))
}
func factorial() -> BInt
{
precondition(!self.sign, "Can't calculate the factorial of an negative number")
return BInt(limbs: Limbs.recursiveMul(0, Limb(self.asInt()!)))
}
//
//
// MARK: - BInt Division
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Division |||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// Returns the quotient and remainder of this value divided by the given value.
public func quotientAndRemainder(dividingBy rhs: BInt) -> (quotient: BInt, remainder: BInt)
{
let limbRes = self.limbs.divMod(rhs.limbs)
return (BInt(limbs: limbRes.quotient), BInt(limbs: limbRes.remainder))
}
public static func /(lhs: BInt, rhs:BInt) -> BInt
{
let limbs = lhs.limbs.divMod(rhs.limbs).quotient
let sign = (lhs.sign != rhs.sign) && !limbs.equalTo(0)
return BInt(sign: sign, limbs: limbs)
}
static func /(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) / rhs }
static func /(lhs: BInt, rhs: Int) -> BInt { return lhs / BInt(rhs) }
public static func /=(lhs: inout BInt, rhs: BInt) { lhs = lhs / rhs }
static func /=(lhs: inout BInt, rhs: Int) { lhs = lhs / BInt(rhs) }
//
//
// MARK: - BInt Modulus
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Modulus ||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func %(lhs: BInt, rhs: BInt) -> BInt
{
let limbs = lhs.limbs.divMod(rhs.limbs).remainder
let sign = lhs.sign && !limbs.equalTo(0)
return BInt(sign: sign, limbs: limbs)
}
static func %(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) % rhs }
static func %(lhs: BInt, rhs: Int) -> BInt { return lhs % BInt(rhs) }
public static func %=(lhs: inout BInt, rhs: BInt) { lhs = lhs % rhs }
static func %=(lhs: inout BInt, rhs: Int) { lhs = lhs % BInt(rhs) }
//
//
// MARK: - BInt Comparing
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BInt Comparing ||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Required by protocol Equatable
public static func ==(lhs: BInt, rhs: BInt) -> Bool
{
if lhs.sign != rhs.sign { return false }
return lhs.limbs == rhs.limbs
}
static func ==<T: BinaryInteger>(lhs: BInt, rhs: T) -> Bool
{
if lhs.limbs.count != 1 { return false }
return lhs.limbs[0] == rhs
}
static func ==<T: BinaryInteger>(lhs: T, rhs: BInt) -> Bool { return rhs == lhs }
static func !=(lhs: BInt, rhs: BInt) -> Bool
{
if lhs.sign != rhs.sign { return true }
return lhs.limbs != rhs.limbs
}
static func !=<T: BinaryInteger>(lhs: BInt, rhs: T) -> Bool
{
if lhs.limbs.count != 1 { return true }
return lhs.limbs[0] != rhs
}
static func !=<T: BinaryInteger>(lhs: T, rhs: BInt) -> Bool { return rhs != lhs }
// Required by protocol Comparable
public static func <(lhs: BInt, rhs: BInt) -> Bool
{
if lhs.sign != rhs.sign { return lhs.sign }
if lhs.sign { return rhs.limbs.lessThan(lhs.limbs) }
return lhs.limbs.lessThan(rhs.limbs)
}
static func <<T: BinaryInteger>(lhs: BInt, rhs: T) -> Bool
{
if lhs.sign != (rhs < 0) { return lhs.sign }
if lhs.sign
{
if lhs.limbs.count != 1 { return true }
return rhs < lhs.limbs[0]
}
else
{
if lhs.limbs.count != 1 { return false }
return lhs.limbs[0] < rhs
}
}
static func <(lhs: Int, rhs: BInt) -> Bool { return BInt(lhs) < rhs }
static func <(lhs: BInt, rhs: Int) -> Bool { return lhs < BInt(rhs) }
// Required by protocol Comparable
public static func >(lhs: BInt, rhs: BInt) -> Bool { return rhs < lhs }
static func >(lhs: Int, rhs: BInt) -> Bool { return BInt(lhs) > rhs }
static func >(lhs: BInt, rhs: Int) -> Bool { return lhs > BInt(rhs) }
// Required by protocol Comparable
public static func <=(lhs: BInt, rhs: BInt) -> Bool { return !(rhs < lhs) }
static func <=(lhs: Int, rhs: BInt) -> Bool { return !(rhs < BInt(lhs)) }
static func <=(lhs: BInt, rhs: Int) -> Bool { return !(BInt(rhs) < lhs) }
// Required by protocol Comparable
public static func >=(lhs: BInt, rhs: BInt) -> Bool { return !(lhs < rhs) }
static func >=(lhs: Int, rhs: BInt) -> Bool { return !(BInt(lhs) < rhs) }
static func >=(lhs: BInt, rhs: Int) -> Bool { return !(lhs < BInt(rhs)) }
}
//
//
// MARK: - String operations
// ————————————————————————————————————————————————————————————————————————————————————————————
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// |||||||| String operations |||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
//
//
fileprivate extension String
{
// Splits the string into equally sized parts (exept for the last one).
func split(_ count: Int) -> [String] {
return stride(from: 0, to: self.count, by: count).map { i -> String in
let start = index(startIndex, offsetBy: i)
let end = index(start, offsetBy: count, limitedBy: endIndex) ?? endIndex
return String(self[start..<end])
}
}
}
fileprivate let DigitBase: Digit = 1_000_000_000_000_000_000
fileprivate let DigitHalfBase: Digit = 1_000_000_000
fileprivate let DigitZeros = 18
fileprivate extension Array where Element == Limb
{
var decimalRepresentation: String
{
// First, convert limbs to digits
var digits: Digits = [0]
var power: Digits = [1]
for limb in self
{
let digit = (limb >= DigitBase)
? [limb % DigitBase, limb / DigitBase]
: [limb]
digits.addProductOfDigits(digit, power)
var nextPower: Digits = [0]
nextPower.addProductOfDigits(power, [446_744_073_709_551_616, 18])
power = nextPower
}
// Then, convert digits to string
var res = String(digits.last!)
if digits.count == 1 { return res }
for i in (0..<(digits.count - 1)).reversed()
{
let str = String(digits[i])
let leadingZeros = String(repeating: "0", count: DigitZeros - str.count)
res.append(leadingZeros.appending(str))
}
return res
}
}
fileprivate extension Digit
{
mutating func addReportingOverflowDigit(_ addend: Digit) -> Bool
{
self = self &+ addend
if self >= DigitBase { self -= DigitBase; return true }
return false
}
func multipliedFullWidthDigit(by multiplicand: Digit) -> (Digit, Digit)
{
let (lLo, lHi) = (self % DigitHalfBase, self / DigitHalfBase)
let (rLo, rHi) = (multiplicand % DigitHalfBase, multiplicand / DigitHalfBase)
let K = (lHi * rLo) + (rHi * lLo)
var resLo = (lLo * rLo) + ((K % DigitHalfBase) * DigitHalfBase)
var resHi = (lHi * rHi) + (K / DigitHalfBase)
if resLo >= DigitBase
{
resLo -= DigitBase
resHi += 1
}
return (resLo, resHi)
}
}
fileprivate extension Array where Element == Digit
{
mutating func addOneDigit(
_ addend: Limb,
padding paddingZeros: Int
){
let sc = self.count
if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) }
if paddingZeros >= sc { self.append(addend); return }
// Now, i < sc
var i = paddingZeros
let ovfl = self[i].addReportingOverflowDigit(addend)
while ovfl
{
i += 1
if i == sc { self.append(1); return }
self[i] += 1
if self[i] != DigitBase { return }
self[i] = 0
}
}
mutating func addTwoDigit(
_ addendLow: Limb,
_ addendHigh: Limb,
padding paddingZeros: Int)
{
let sc = self.count
if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) }
if paddingZeros >= sc { self += [addendLow, addendHigh]; return }
// Now, i < sc
var i = paddingZeros
var newDigit: Digit
let ovfl1 = self[i].addReportingOverflowDigit(addendLow)
i += 1
if i == sc
{
newDigit = (addendHigh &+ (ovfl1 ? 1 : 0)) % DigitBase
self.append(newDigit)
if newDigit == 0 { self.append(1) }
return
}
// Still, i < sc
var ovfl2 = self[i].addReportingOverflowDigit(addendHigh)
if ovfl1
{
self[i] += 1
if self[i] == DigitBase { self[i] = 0; ovfl2 = true }
}
while ovfl2
{
i += 1
if i == sc { self.append(1); return }
self[i] += 1
if self[i] != DigitBase { return }
self[i] = 0
}
}
mutating func addProductOfDigits(_ multiplier: Digits, _ multiplicand: Digits)
{
let (mpc, mcc) = (multiplier.count, multiplicand.count)
self.reserveCapacity(mpc &+ mcc)
var l, r, resLo, resHi: Digit
for i in 0..<mpc
{
l = multiplier[i]
if l == 0 { continue }
for j in 0..<mcc
{
r = multiplicand[j]
if r == 0 { continue }
(resLo, resHi) = l.multipliedFullWidthDigit(by: r)
if resHi == 0
{
self.addOneDigit(resLo, padding: i + j)
}
else
{
self.addTwoDigit(resLo, resHi, padding: i + j)
}
}
}
}
}
//
//
// MARK: - Limbs extension
// ————————————————————————————————————————————————————————————————————————————————————————————
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// |||||||| Limbs extension |||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Extension to Limbs type
fileprivate extension Array where Element == Limb
{
//
//
// MARK: - Limbs bitlevel
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs bitlevel ||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// Returns the number of bits that contribute to the represented number, ignoring all
/// leading zeros.
var bitWidth: Int
{
var lastBits = 0
var last = self.last!
while last != 0 {
last >>= 1
lastBits += 1
}
return ((self.count - 1) * 64) + lastBits
}
/// Get bit i of limbs.
func getBit(at i: Int) -> Bool
{
let limbIndex = Int(Limb(i) >> 6)
if limbIndex >= self.count { return false }
let bitIndex = Limb(i) & 0b111_111
return (self[limbIndex] & (1 << bitIndex)) != 0
}
/// Set bit i of limbs to b. b must be 0 for false, and everything else for true.
mutating func setBit(
at i: Int,
to bit: Bool
){
let limbIndex = Int(Limb(i) >> 6)
if limbIndex >= self.count && !bit { return }
let bitIndex = Limb(i) & 0b111_111
while limbIndex >= self.count { self.append(0) }
if bit
{
self[limbIndex] |= (1 << bitIndex)
}
else
{
self[limbIndex] &= ~(1 << bitIndex)
}
}
//
//
// MARK: - Limbs Shifting
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Shifting ||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
mutating func shiftUp(_ shift: Int)
{
// No shifting is required in this case
if shift == 0 || self.equalTo(0) { return }
let limbShifts = shift >> 6
let bitShifts = Limb(shift) & 0x3f
if bitShifts != 0
{
var previousCarry = Limb(0)
var carry = Limb(0)
var ele = Limb(0) // use variable to minimize array accesses
for i in 0..<self.count
{
ele = self[i]
carry = ele >> (64 - bitShifts)
ele <<= bitShifts
ele |= previousCarry // carry from last step
previousCarry = carry
self[i] = ele
}
if previousCarry != 0 { self.append(previousCarry) }
}
if limbShifts != 0
{
self.insert(contentsOf: Limbs(repeating: 0, count: limbShifts), at: 0)
}
}
func shiftingUp(_ shift: Int) -> Limbs
{
var res = self
res.shiftUp(shift)
return res
}
mutating func shiftDown(_ shift: Int)
{
if shift == 0 || self.equalTo(0) { return }
let limbShifts = shift >> 6
let bitShifts = Limb(shift) & 0x3f
if limbShifts >= self.count
{
self = [0]
return
}
self.removeSubrange(0..<limbShifts)
if bitShifts != 0
{
var previousCarry = Limb(0)
var carry = Limb(0)
var ele = Limb(0) // use variable to minimize array accesses
var i = self.count - 1 // use while for high performance
while i >= 0
{
ele = self[i]
carry = ele << (64 - bitShifts)
ele >>= bitShifts
ele |= previousCarry
previousCarry = carry
self[i] = ele
i -= 1
}
}
if self.last! == 0 && self.count != 1 { self.removeLast() }
}
func shiftingDown(_ shift: Int) -> Limbs
{
var res = self
res.shiftDown(shift)
return res
}
//
//
// MARK: - Limbs Addition
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Addition ||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
mutating func addLimbs(_ addend: Limbs)
{
let (sc, ac) = (self.count, addend.count)
var (newLimb, ovfl) = (Limb(0), false)
let minCount = Swift.min(sc, ac)
var i = 0
while i < minCount
{
if ovfl
{
(newLimb, ovfl) = self[i].addingReportingOverflow(addend[i])
newLimb = newLimb &+ 1
ovfl = ovfl || newLimb == 0
}
else
{
(newLimb, ovfl) = self[i].addingReportingOverflow(addend[i])
}
self[i] = newLimb
i += 1
}
while ovfl
{
if i < sc
{
if i < ac
{
(newLimb, ovfl) = self[i].addingReportingOverflow(addend[i])
newLimb = newLimb &+ 1
ovfl = ovfl || newLimb == 0
}
else
{
(newLimb, ovfl) = self[i].addingReportingOverflow(1)
}
self[i] = newLimb
}
else
{
if i < ac
{
(newLimb, ovfl) = addend[i].addingReportingOverflow(1)
self.append(newLimb)
}
else
{
self.append(1)
return
}
}
i += 1
}
if self.count < ac
{
self.append(contentsOf: addend.suffix(from: i))
}
}
/// Adding Limbs and returning result
func adding(_ addend: Limbs) -> Limbs
{
var res = self
res.addLimbs(addend)
return res
}
// CURRENTLY NOT USED:
/// Add the addend to Limbs, while using a padding at the lower end.
/// Every zero is a Limb, that means one padding zero equals 64 padding bits
mutating func addLimbs(
_ addend: Limbs,
padding paddingZeros: Int
){
let sc = self.count
if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) }
if paddingZeros >= sc { self += addend; return }
// Now, i < sc
let ac = addend.count &+ paddingZeros
var (newLimb, ovfl) = (Limb(0), false)
let minCount = Swift.min(sc, ac)
var i = paddingZeros
while i < minCount
{
if ovfl
{
(newLimb, ovfl) = self[i].addingReportingOverflow(addend[i &- paddingZeros])
newLimb = newLimb &+ 1
self[i] = newLimb
ovfl = ovfl || newLimb == 0
}
else
{
(self[i], ovfl) = self[i].addingReportingOverflow(addend[i &- paddingZeros])
}
i += 1
}
while ovfl
{
if i < sc
{
let adding = i < ac ? addend[i &- paddingZeros] &+ 1 : 1
(self[i], ovfl) = self[i].addingReportingOverflow(adding)
ovfl = ovfl || adding == 0
}
else
{
if i < ac
{
(newLimb, ovfl) = addend[i &- paddingZeros].addingReportingOverflow(1)
self.append(newLimb)
}
else
{
self.append(1)
return
}
}
i += 1
}
if self.count < ac
{
self.append(contentsOf: addend.suffix(from: i &- paddingZeros))
}
}
mutating func addOneLimb(
_ addend: Limb,
padding paddingZeros: Int
){
let sc = self.count
if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) }
if paddingZeros >= sc { self.append(addend); return }
// Now, i < lhc
var i = paddingZeros
var ovfl: Bool
(self[i], ovfl) = self[i].addingReportingOverflow(addend)
while ovfl
{
i += 1
if i == sc { self.append(1); return }
(self[i], ovfl) = self[i].addingReportingOverflow(1)
}
}
/// Basically self.addOneLimb([addendLow, addendHigh], padding: paddingZeros), but faster
mutating func addTwoLimb(
_ addendLow: Limb,
_ addendHigh: Limb,
padding paddingZeros: Int)
{
let sc = self.count
if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) }
if paddingZeros >= sc { self += [addendLow, addendHigh]; return }
// Now, i < sc
var i = paddingZeros
var newLimb: Limb
var ovfl1: Bool
(self[i], ovfl1) = self[i].addingReportingOverflow(addendLow)
i += 1
if i == sc
{
newLimb = addendHigh &+ (ovfl1 ? 1 : 0)
self.append(newLimb)
if newLimb == 0 { self.append(1) }
return
}
// Still, i < sc
var ovfl2: Bool
(self[i], ovfl2) = self[i].addingReportingOverflow(addendHigh)
if ovfl1
{
self[i] = self[i] &+ 1
if self[i] == 0 { ovfl2 = true }
}
while ovfl2
{
i += 1
if i == sc { self.append(1); return }
(self[i], ovfl2) = self[i].addingReportingOverflow(1)
}
}
//
//
// MARK: - Limbs Subtraction
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Subtraction |||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// Calculates difference between Limbs in left limb
mutating func difference(_ subtrahend: Limbs)
{
var subtrahend = subtrahend
// swap to get difference
if self.lessThan(subtrahend) { swap(&self, &subtrahend) }
let rhc = subtrahend.count
var ovfl = false
var i = 0
// skip first zeros
while i < rhc && subtrahend[i] == 0 { i += 1 }
while i < rhc
{
if ovfl
{
(self[i], ovfl) = self[i].subtractingReportingOverflow(subtrahend[i])
self[i] = self[i] &- 1
ovfl = ovfl || self[i] == Limb.max
}
else
{
(self[i], ovfl) = self[i].subtractingReportingOverflow(subtrahend[i])
}
i += 1
}
while ovfl
{
if i >= self.count
{
self.append(Limb.max)
break
}
(self[i], ovfl) = self[i].subtractingReportingOverflow(1)
i += 1
}
if self.count > 1 && self.last! == 0 // cut excess zeros if required
{
var j = self.count - 2
while j >= 1 && self[j] == 0 { j -= 1 }
self.removeSubrange((j + 1)..<self.count)
}
}
func differencing(_ subtrahend: Limbs) -> Limbs
{
var res = self
res.difference(subtrahend)
return res
}
//
//
// MARK: - Limbs Multiplication
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Multiplication |||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
mutating func addProductOf(
multiplier: Limbs,
multiplicand: Limbs
){
let (mpc, mcc) = (multiplier.count, multiplicand.count)
self.reserveCapacity(mpc + mcc)
// Minimize array subscript calls
var l, r, mulHi, mulLo: Limb
for i in 0..<mpc
{
l = multiplier[i]
if l == 0 { continue }
for j in 0..<mcc
{
r = multiplicand[j]
if r == 0 { continue }
(mulHi, mulLo) = l.multipliedFullWidth(by: r)
if mulHi != 0 { self.addTwoLimb(mulLo, mulHi, padding: i + j) }
else { self.addOneLimb(mulLo, padding: i + j) }
}
}
}
// Perform res += (lhs * r)
mutating func addProductOf(
multiplier: Limbs,
multiplicand: Limb
){
if multiplicand < 2
{
if multiplicand == 1 { self.addLimbs(multiplier) }
// If r == 0 then do nothing with res
return
}
// Minimize array subscript calls
var l, mulHi, mulLo: Limb
for i in 0..<multiplier.count
{
l = multiplier[i]
if l == 0 { continue }
(mulHi, mulLo) = l.multipliedFullWidth(by: multiplicand)
if mulHi != 0 { self.addTwoLimb(mulLo, mulHi, padding: i) }
else { self.addOneLimb(mulLo, padding: i) }
}
}
func multiplyingBy(_ multiplicand: Limbs) -> Limbs
{
var res: Limbs = [0]
res.addProductOf(multiplier: self, multiplicand: multiplicand)
return res
}
func squared() -> Limbs
{
var res: Limbs = [0]
res.reserveCapacity(2 * self.count)
// Minimize array subscript calls
var l, r, mulHi, mulLo: Limb
for i in 0..<self.count
{
l = self[i]
if l == 0 { continue }
for j in 0...i
{
r = self[j]
if r == 0 { continue }
(mulHi, mulLo) = l.multipliedFullWidth(by: r)
if mulHi != 0
{
if i != j { res.addTwoLimb(mulLo, mulHi, padding: i + j) }
res.addTwoLimb(mulLo, mulHi, padding: i + j)
}
else
{
if i != j { res.addOneLimb(mulLo, padding: i + j) }
res.addOneLimb(mulLo, padding: i + j)
}
}
}
return res
}
//
//
// MARK: - Limbs Exponentiation
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Exponentiation ||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Exponentiation by squaring
func exponentiating(_ exponent: Int) -> Limbs
{
if exponent == 0 { return [1] }
if exponent == 1 { return self }
var base = self
var exponent = exponent
var y: Limbs = [1]
while exponent > 1
{
if exponent & 1 != 0 { y = y.multiplyingBy(base) }
base = base.squared()
exponent >>= 1
}
return base.multiplyingBy(y)
}
/// Calculate (n + 1) * (n + 2) * ... * (k - 1) * k
static func recursiveMul(_ n: Limb, _ k: Limb) -> Limbs
{
if n >= k - 1 { return [k] }
let m = (n + k) >> 1
return recursiveMul(n, m).multiplyingBy(recursiveMul(m, k))
}
func factorial(_ base: Int) -> BInt
{
return BInt(limbs: Limbs.recursiveMul(0, Limb(base)))
}
//
//
// MARK: - Limbs Division and Modulo
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Division and Modulo |||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/// An O(n) division algorithm that returns quotient and remainder.
func divMod(_ divisor: Limbs) -> (quotient: Limbs, remainder: Limbs)
{
precondition(!divisor.equalTo(0), "Division or Modulo by zero not allowed")
if self.equalTo(0) { return ([0], [0]) }
var (quotient, remainder): (Limbs, Limbs) = ([0], [0])
var (previousCarry, carry, ele): (Limb, Limb, Limb) = (0, 0, 0)
// bits of lhs minus one bit
var i = (64 * (self.count - 1)) + Int(log2(Double(self.last!)))
while i >= 0
{
// shift remainder by 1 to the left
for r in 0..<remainder.count
{
ele = remainder[r]
carry = ele >> 63
ele <<= 1
ele |= previousCarry // carry from last step
previousCarry = carry
remainder[r] = ele
}
if previousCarry != 0 { remainder.append(previousCarry) }
remainder.setBit(at: 0, to: self.getBit(at: i))
if !remainder.lessThan(divisor)
{
remainder.difference(divisor)
quotient.setBit(at: i, to: true)
}
i -= 1
}
return (quotient, remainder)
}
/// Division with limbs, result is floored to nearest whole number.
func dividing(_ divisor: Limbs) -> Limbs
{
return self.divMod(divisor).quotient
}
/// Modulo with limbs, result is floored to nearest whole number.
func modulus(_ divisor: Limbs) -> Limbs
{
return self.divMod(divisor).remainder
}
//
//
// MARK: - Limbs Comparing
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Limbs Comparing |||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// Note:
// a < b iff b > a
// a <= b iff b >= a
// but:
// a < b iff !(a >= b)
// a <= b iff !(a > b)
func lessThan(_ compare: Limbs) -> Bool
{
let lhsc = self.count
let rhsc = compare.count
if lhsc != rhsc
{
return lhsc < rhsc
}
var i = lhsc - 1
while i >= 0
{
if self[i] != compare[i] { return self[i] < compare[i] }
i -= 1
}
return false // lhs == rhs
}
func equalTo(_ compare: Limb) -> Bool
{
return self[0] == compare && self.count == 1
}
}
//
//
// MARK: - Useful BInt math functions
// ————————————————————————————————————————————————————————————————————————————————————————————
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// |||||||| Useful BInt math functions ||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
//
//
internal class BIntMath
{
/// Returns true iff (2 ** exp) - 1 is a mersenne prime.
static func isMersenne(_ exp: Int) -> Bool
{
var mersenne = Limbs(repeating: Limb.max, count: exp >> 6)
if (exp % 64) > 0
{
mersenne.append((Limb(1) << Limb(exp % 64)) - Limb(1))
}
var res: Limbs = [4]
for _ in 0..<(exp - 2)
{
res = res.squared().differencing([2]).divMod(mersenne).remainder
}
return res.equalTo(0)
}
fileprivate static func euclid(_ a: Limbs, _ b: Limbs) -> Limbs
{
var (a, b) = (a, b)
while !b.equalTo(0)
{
(a, b) = (b, a.divMod(b).remainder)
}
return a
}
fileprivate static func gcdFactors(_ lhs: Limbs, rhs: Limbs) -> (ax: Limbs, bx: Limbs)
{
let gcd = steinGcd(lhs, rhs)
return (lhs.divMod(gcd).quotient, rhs.divMod(gcd).quotient)
}
static func steinGcd(_ a: Limbs, _ b: Limbs) -> Limbs
{
if a == [0] { return b }
if b == [0] { return a }
// Trailing zeros
var (za, zb) = (0, 0)
while !a.getBit(at: za) { za += 1 }
while !b.getBit(at: zb) { zb += 1 }
let k = min(za, zb)
var (a, b) = (a, b)
a.shiftDown(za)
b.shiftDown(k)
repeat
{
zb = 0
while !b.getBit(at: zb) { zb += 1 }
b.shiftDown(zb)
if b.lessThan(a) { (a, b) = (b, a) }
// At this point, b >= a
b.difference(a)
}
while b != [0]
return a.shiftingUp(k)
}
static func gcd(_ a: BInt, _ b: BInt) -> BInt
{
let limbRes = steinGcd(a.limbs, b.limbs)
return BInt(sign: a.sign && !limbRes.equalTo(0), limbs: limbRes)
}
/// Do not use this, extremely slow. Only for testing purposes.
static func gcdEuclid(_ a: BInt, _ b: BInt) -> BInt
{
let limbRes = euclid(a.limbs, b.limbs)
return BInt(sign: a.sign && !limbRes.equalTo(0), limbs: limbRes)
}
fileprivate static func lcmPositive(_ a: Limbs, _ b: Limbs) -> Limbs
{
return a.divMod(steinGcd(a, b)).quotient.multiplyingBy(b)
}
static func lcm(_ a:BInt, _ b:BInt) -> BInt
{
return BInt(limbs: lcmPositive(a.limbs, b.limbs))
}
static func fib(_ n:Int) -> BInt
{
var a: Limbs = [0], b: Limbs = [1], t: Limbs
for _ in 2...n
{
t = b
b.addLimbs(a)
a = t
}
return BInt(limbs: b)
}
/// Order matters, repetition not allowed.
static func permutations(_ n: Int, _ k: Int) -> BInt
{
// n! / (n-k)!
return BInt(n).factorial() / BInt(n - k).factorial()
}
/// Order matters, repetition allowed.
static func permutationsWithRepitition(_ n: Int, _ k: Int) -> BInt
{
// n ** k
return BInt(n) ** k
}
/// Order does not matter, repetition not allowed.
static func combinations(_ n: Int, _ k: Int) -> BInt
{
// (n + k - 1)! / (k! * (n - 1)!)
return BInt(n + k - 1).factorial() / (BInt(k).factorial() * BInt(n - 1).factorial())
}
/// Order does not matter, repetition allowed.
static func combinationsWithRepitition(_ n: Int, _ k: Int) -> BInt
{
// n! / (k! * (n - k)!)
return BInt(n).factorial() / (BInt(k).factorial() * BInt(n - k).factorial())
}
static func randomBInt(bits n: Int) -> BInt
{
let limbs = n >> 6
let singleBits = n % 64
var res = Limbs(repeating: 0, count: Int(limbs))
for i in 0..<Int(limbs)
{
res[i] = Limb(arc4random_uniform(UInt32.max)) |
(Limb(arc4random_uniform(UInt32.max)) << 32)
}
if singleBits > 0
{
var last: Limb
if singleBits < 32
{
last = Limb(arc4random_uniform(UInt32(2 ** singleBits)))
}
else if singleBits == 32
{
last = Limb(arc4random_uniform(UInt32.max))
}
else
{
last = Limb(arc4random_uniform(UInt32.max)) |
(Limb(arc4random_uniform(UInt32(2.0 ** (singleBits - 32)))) << 32)
}
res.append(last)
}
return BInt(limbs: res)
}
let random = randomBInt
func isPrime(_ n: BInt) -> Bool
{
if n <= 3 { return n > 1 }
if ((n % 2) == 0) || ((n % 3) == 0) { return false }
var i = 5
while (i * i) <= n
{
if ((n % i) == 0) || ((n % (i + 2)) == 0)
{
return false
}
i += 6
}
return true
}
/// Quick exponentiation/modulo algorithm
/// FIXME: for security, this should use the constant-time Montgomery algorithm to thwart timing attacks
///
/// - Parameters:
/// - b: base
/// - p: power
/// - m: modulus
/// - Returns: pow(b, p) % m
static func mod_exp(_ b: BInt, _ p: BInt, _ m: BInt) -> BInt {
precondition(m != 0, "modulus needs to be non-zero")
precondition(p >= 0, "exponent needs to be non-negative")
var base = b % m
var exponent = p
var result = BInt(1)
while exponent > 0 {
if exponent.limbs[0] % 2 != 0 {
result = result * base % m
}
exponent.limbs.shiftDown(1)
base *= base
base %= m
}
return result
}
/// Non-negative modulo operation
///
/// - Parameters:
/// - a: left hand side of the module operation
/// - m: modulus
/// - Returns: r := a % b such that 0 <= r < abs(m)
static func nnmod(_ a: BInt, _ m: BInt) -> BInt {
let r = a % m
guard r.isNegative() else { return r }
let p = m.isNegative() ? r - m : r + m
return p
}
/// Convenience function combinding addition and non-negative modulo operations
///
/// - Parameters:
/// - a: left hand side of the modulo addition
/// - b: right hand side of the modulo addition
/// - m: modulus
/// - Returns: nnmod(a + b, m)
static func mod_add(_ a: BInt, _ b: BInt, _ m: BInt) -> BInt {
return nnmod(a + b, m)
}
}
//
//
// MARK: - BDouble
// ————————————————————————————————————————————————————————————————————————————————————————————
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// |||||||| BDouble |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public struct BDouble:
ExpressibleByIntegerLiteral,
ExpressibleByFloatLiteral,
CustomStringConvertible,
SignedNumeric,
Comparable,
Hashable
{
//
//
// MARK: - Internal data
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Internal data |||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
var sign = Bool()
var numerator = Limbs()
var denominator = Limbs()
public typealias Magnitude = Double
public var magnitude: Double = 0.0
//
//
// MARK: - Initializers
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Initializers ||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public init?<T>(exactly source: T) where T : BinaryInteger
{
self.init(0.0)
}
/**
Inits a BDouble with two Limbs as numerator and denominator
- Parameters:
- numerator: The upper part of the fraction as Limbs
- denominator: The lower part of the fraction as Limbs
Returns: A new BDouble
*/
public init(sign: Bool, numerator: Limbs, denominator: Limbs)
{
precondition(
!denominator.equalTo(0) && denominator != [] && numerator != [],
"Denominator can't be zero and limbs can't be []"
)
self.sign = sign
self.numerator = numerator
self.denominator = denominator
self.minimize()
}
public init(_ numerator: BInt, over denominator: BInt)
{
self.init(
sign: numerator.sign != denominator.sign,
numerator: numerator.limbs,
denominator: denominator.limbs
)
}
public init(_ numerator: Int, over denominator: Int)
{
self.init(
sign: (numerator < 0) != (denominator < 0),
numerator: [UInt64(abs(numerator))],
denominator: [UInt64(abs(denominator))]
)
}
public init?(_ numerator: String, over denominator: String)
{
if let n = BInt(numerator) {
if let d = BInt(denominator) {
self.init(n, over: d)
return
}
}
return nil
}
public init?(_ nStr: String)
{
if let bi = BInt(nStr) {
self.init(bi, over: 1)
} else {
if let exp = nStr.index(of: "e")?.encodedOffset
{
let beforeExp = String(Array(nStr)[..<exp].filter{ $0 != "." })
var afterExp = String(Array(nStr)[(exp + 1)...])
var sign = false
if let neg = afterExp.index(of: "-")?.encodedOffset
{
afterExp = String(Array(afterExp)[(neg + 1)...])
sign = true
}
if sign
{
if var safeAfterExp = Int(afterExp) {
if beforeExp.starts(with: "+") || beforeExp.starts(with: "-") {
safeAfterExp = safeAfterExp - beforeExp.count + 2
} else {
safeAfterExp = safeAfterExp - beforeExp.count + 1
}
let den = ["1"] + [Character](repeating: "0", count: safeAfterExp)
self.init(beforeExp, over: String(den))
return
}
return nil
}
else
{
if var safeAfterExp = Int(afterExp) {
if beforeExp.starts(with: "+") || beforeExp.starts(with: "-") {
safeAfterExp = safeAfterExp - beforeExp.count + 2
} else {
safeAfterExp = safeAfterExp - beforeExp.count + 1
}
let num = beforeExp + String([Character](repeating: "0", count: safeAfterExp))
self.init(num, over: "1")
return
}
return nil
}
}
if let io = nStr.index(of: ".")
{
let i = io.encodedOffset
let beforePoint = String(Array(nStr)[..<i])
let afterPoint = String(Array(nStr)[(i + 1)...])
if afterPoint == "0"
{
self.init(beforePoint, over: "1")
}
else
{
let den = ["1"] + [Character](repeating: "0", count: afterPoint.count)
self.init(beforePoint + afterPoint, over: String(den))
}
} else
{
return nil
}
}
}
/// Create an instance initialized to a string with the value of mathematical numerical system of the specified radix (base).
/// So for example, to get the value of hexadecimal string radix value must be set to 16.
public init?(_ nStr: String, radix: Int)
{
if radix == 10 {
// regular string init is faster
// see metrics
self.init(nStr)
return
}
var useString = nStr
if radix == 16 {
if useString.hasPrefix("0x") {
useString = String(nStr.dropFirst(2))
}
}
if radix == 8 {
if useString.hasPrefix("0o") {
useString = String(nStr.dropFirst(2))
}
}
if radix == 2 {
if useString.hasPrefix("0b") {
useString = String(nStr.dropFirst(2))
}
}
let bint16 = BDouble(radix)
var total = BDouble(0)
var exp = BDouble(1)
for c in useString.reversed() {
let int = Int(String(c), radix: radix)
if int != nil {
let value = BDouble(int!)
total = total + (value * exp)
exp = exp * bint16
} else {
return nil
}
}
self.init(String(describing:total))
}
public init(_ z: Int)
{
self.init(z, over: 1)
}
public init(_ d: Double)
{
let nStr = String(d)
self.init(nStr)!
}
public init(integerLiteral value: Int)
{
self.init(value)
}
public init(floatLiteral value: Double)
{
self.init(value)
}
//
//
// MARK: - Descriptions
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| Descriptions ||||||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/**
* returns the current value in a fraction format
*/
public var description: String
{
return self.fractionDescription
}
/**
* returns the current value in a fraction format
*/
public var fractionDescription : String
{
var res = (self.sign ? "-" : "")
res.append(self.numerator.decimalRepresentation)
if self.denominator != [1]
{
res.append("/".appending(self.denominator.decimalRepresentation))
}
return res
}
static private var _precision = 4
/**
* the global percision for all newly created values
*/
static public var precision : Int
{
get
{
return _precision
}
set
{
var nv = newValue
if nv < 0 {
nv = 0
}
_precision = nv
}
}
private var _precision : Int = BDouble.precision
/**
* the precision for the current value
*/
public var precision : Int
{
get
{
return _precision
}
set
{
var nv = newValue
if nv < 0 {
nv = 0
}
_precision = nv
}
}
/**
* returns the current value in decimal format with the current precision
*/
public var decimalDescription : String
{
return self.decimalExpansion(precisionAfterDecimalPoint: self.precision)
}
/**
Returns the current value in decimal format (always with a decimal point).
- parameter precision: the precision after the decimal point
- parameter rounded: whether or not the return value's last digit will be rounded up
*/
public func decimalExpansion(precisionAfterDecimalPoint precision: Int, rounded : Bool = true) -> String
{
var currentPrecision = precision
if(rounded && precision > 0) {
currentPrecision = currentPrecision + 1
}
let multiplier = [10].exponentiating(currentPrecision)
let limbs = self.numerator.multiplyingBy(multiplier).divMod(self.denominator).quotient
var res = BInt(limbs: limbs).description
if currentPrecision <= res.count
{
res.insert(".", at: String.Index(encodedOffset: res.count - currentPrecision))
if res.hasPrefix(".") { res = "0" + res }
else if res.hasSuffix(".") { res += "0" }
}
else
{
res = "0." + String(repeating: "0", count: currentPrecision - res.count) + res
}
var retVal = self.isNegative() && !limbs.equalTo(0) ? "-" + res : res
if(rounded && precision > 0) {
let lastDigit = Int(retVal.suffix(1))! // this should always be a number
let secondDigit = retVal.suffix(2).prefix(1) // this could be a decimal
retVal = String(retVal.prefix(retVal.count-2))
if (secondDigit != ".") {
if lastDigit >= 5 {
retVal = retVal + String(Int(secondDigit)! + 1)
} else {
retVal = retVal + String(Int(secondDigit)!)
}
} else {
retVal = retVal + "." + String(lastDigit)
}
}
return retVal
}
public var hashValue: Int
{
return "\(self.sign)\(self.numerator)\(self.denominator)".hashValue
}
/**
* Returns the size of the BDouble in bits.
*/
public var size: Int
{
return 1 + ((self.numerator.count + self.denominator.count) * MemoryLayout<Limb>.size * 8)
}
/**
* Returns a formated human readable string that says how much space
* (in bytes, kilobytes, megabytes, or gigabytes) the BDouble occupies
*/
public var sizeDescription: String
{
// One bit for the sign, plus the size of the numerator and denominator.
let bits = self.size
if bits < 8_000
{
return String(format: "%.1f b", Double(bits) / 8.0)
}
if bits < 8_000_000
{
return String(format: "%.1f kb", Double(bits) / 8_000.0)
}
if UInt64(bits) < UInt64(8_000_000_000.0)
{
return String(format: "%.1f mb", Double(bits) / 8_000_000.0)
}
return String(format: "%.1f gb", Double(bits) / 8_000_000_000.0)
}
public func rawData() -> (sign: Bool, numerator: [UInt64], denominator: [UInt64])
{
return (self.sign, self.numerator, self.denominator)
}
public func isPositive() -> Bool { return !self.sign }
public func isNegative() -> Bool { return self.sign }
public func isZero() -> Bool { return self.numerator.equalTo(0) }
public mutating func minimize()
{
if self.numerator.equalTo(0)
{
self.denominator = [1]
return
}
let gcd = BIntMath.steinGcd(self.numerator, self.denominator)
if gcd[0] > 1 || gcd.count > 1
{
self.numerator = self.numerator.divMod(gcd).quotient
self.denominator = self.denominator.divMod(gcd).quotient
}
}
/**
* If the right side of the decimal is greater than 0.5 then it will round up (ceil),
* otherwise round down (floor) to the nearest BInt
*/
public func rounded() -> BInt
{
if self.isZero() {
return BInt(0)
}
let digits = 3
let multiplier = [10].exponentiating(digits)
let rawRes = abs(self).numerator.multiplyingBy(multiplier).divMod(self.denominator).quotient
let res = BInt(limbs: rawRes).description
let offset = res.count - digits
let rhs = Double("0." + res.suffix(res.count - offset))!
let lhs = res.prefix(offset)
var retVal = BInt(String(lhs))!
if self.isNegative()
{
retVal = -retVal
if rhs > 0.5 {
retVal = retVal - BInt(1)
}
} else {
if rhs > 0.5
{
retVal = retVal + 1
}
}
return retVal
}
// public func sqrt(precision digits: Int) -> BDouble
// {
// // let self = v
// // Find x such that x*x=v <==> x = v/x
//
// }
//
//
// MARK: - BDouble Addition
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Addition ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func +(lhs: BDouble, rhs: BDouble) -> BDouble
{
// a/b + c/d = ad + bc / bd, where lhs = a/b and rhs = c/d.
let ad = lhs.numerator.multiplyingBy(rhs.denominator)
let bc = rhs.numerator.multiplyingBy(lhs.denominator)
let bd = lhs.denominator.multiplyingBy(rhs.denominator)
let resNumerator = BInt(sign: lhs.sign, limbs: ad) + BInt(sign: rhs.sign, limbs: bc)
return BDouble(
sign: resNumerator.sign && !resNumerator.limbs.equalTo(0),
numerator: resNumerator.limbs,
denominator: bd
)
}
public static func +(lhs: BDouble, rhs: Double) -> BDouble { return lhs + BDouble(rhs) }
public static func +(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) + rhs }
public static func +=(lhs: inout BDouble, rhs: BDouble) {
let res = lhs + rhs
lhs = res
}
public static func +=(lhs: inout BDouble, rhs: Double) { lhs += BDouble(rhs) }
//
//
// MARK: - BDouble Negation
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Negation ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/**
* makes the current value negative
*/
public mutating func negate()
{
if !self.isZero()
{
self.sign = !self.sign
}
}
public static prefix func -(n: BDouble) -> BDouble
{
var n = n
n.negate()
return n
}
//
//
// MARK: - BDouble Subtraction
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Subtraction |||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func -(lhs: BDouble, rhs: BDouble) -> BDouble
{
return lhs + -rhs
}
public static func -(lhs: BDouble, rhs: Double) -> BDouble { return lhs - BDouble(rhs) }
public static func -(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) - rhs }
public static func -=(lhs: inout BDouble, rhs: BDouble) {
let res = lhs - rhs
lhs = res
}
public static func -=(lhs: inout BDouble, rhs: Double) { lhs -= BDouble(rhs) }
//
//
// MARK: - BDouble Multiplication
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Multiplication ||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func *(lhs: BDouble, rhs: BDouble) -> BDouble
{
var res = BDouble(
sign: lhs.sign != rhs.sign,
numerator: lhs.numerator.multiplyingBy(rhs.numerator),
denominator: lhs.denominator.multiplyingBy(rhs.denominator)
)
if res.isZero() { res.sign = false }
return res
}
public static func *(lhs: BDouble, rhs: Double) -> BDouble { return lhs * BDouble(rhs) }
public static func *(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) * rhs }
public static func *=(lhs: inout BDouble, rhs: BDouble) {
let res = lhs * rhs
lhs = res
}
public static func *=(lhs: inout BDouble, rhs: Double) { lhs *= BDouble(rhs) }
//
//
// MARK: - BDouble Exponentiation
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Exponentiation ||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
// TODO: Exponentiation function that supports Double/BDouble in the exponent
public static func **(_ base : BDouble, _ exponent : Int) -> BDouble
{
if exponent == 0
{
return BDouble(1)
}
if exponent == 1
{
return base
}
if exponent < 0
{
return BDouble(1) / (base ** -exponent)
}
return base * (base ** (exponent - 1))
}
//
//
// MARK: - BDouble Division
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Division ||||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
public static func /(lhs: BDouble, rhs: BDouble) -> BDouble
{
var res = BDouble(
sign: lhs.sign != rhs.sign,
numerator: lhs.numerator.multiplyingBy(rhs.denominator),
denominator: lhs.denominator.multiplyingBy(rhs.numerator)
)
if res.isZero() { res.sign = false }
return res
}
public static func /(lhs: BDouble, rhs: Double) -> BDouble { return lhs / BDouble(rhs) }
public static func /(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) / rhs }
//
//
// MARK: - BDouble Comparing
// ————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble Comparing |||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/**
* An == comparison with an epsilon (fixed then a calculated "ULPs")
* Reference: http://floating-point-gui.de/errors/comparison/
* Reference: https://bitbashing.io/comparing-floats.html
*/
public static func nearlyEqual(_ lhs: BDouble, _ rhs: BDouble, epsilon: Double = 0.00001) -> Bool {
let absLhs = abs(lhs)
let absRhs = abs(rhs);
let diff = abs(lhs - rhs);
if (lhs == rhs) { // shortcut, handles infinities
return true;
} else if diff <= epsilon {
return true // shortcut
} else if (lhs == 0 || rhs == 0 || diff < Double.leastNormalMagnitude) {
// lhs or rhs is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Double.leastNormalMagnitude);
} else { // use relative error
return diff / min((absLhs + absRhs), BDouble(Double.greatestFiniteMagnitude)) < epsilon;
}
}
public static func ==(lhs: BDouble, rhs: BDouble) -> Bool
{
if lhs.sign != rhs.sign { return false }
if lhs.numerator != rhs.numerator { return false }
if lhs.denominator != rhs.denominator { return false }
return true
}
public static func ==(lhs: BDouble, rhs: Double) -> Bool { return lhs == BDouble(rhs) }
public static func ==(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) == rhs }
public static func !=(lhs: BDouble, rhs: BDouble) -> Bool
{
return !(lhs == rhs)
}
public static func !=(lhs: BDouble, rhs: Double) -> Bool { return lhs != BDouble(rhs) }
public static func !=(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) != rhs }
public static func <(lhs: BDouble, rhs: BDouble) -> Bool
{
if lhs.sign != rhs.sign { return lhs.sign }
// more efficient than lcm version
let ad = lhs.numerator.multiplyingBy(rhs.denominator)
let bc = rhs.numerator.multiplyingBy(lhs.denominator)
if lhs.sign { return bc.lessThan(ad) }
return ad.lessThan(bc)
}
public static func <(lhs: BDouble, rhs: Double) -> Bool { return lhs < BDouble(rhs) }
public static func <(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) < rhs }
public static func >(lhs: BDouble, rhs: BDouble) -> Bool { return rhs < lhs }
public static func >(lhs: BDouble, rhs: Double) -> Bool { return lhs > BDouble(rhs) }
public static func >(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) > rhs }
public static func <=(lhs: BDouble, rhs: BDouble) -> Bool { return !(rhs < lhs) }
public static func <=(lhs: BDouble, rhs: Double) -> Bool { return lhs <= BDouble(rhs) }
public static func <=(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) <= rhs }
public static func >=(lhs: BDouble, rhs: BDouble) -> Bool { return !(lhs < rhs) }
public static func >=(lhs: BDouble, rhs: Double) -> Bool { return lhs >= BDouble(rhs) }
public static func >=(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) >= rhs }
}
//
//
// MARK: - BDouble Operators
// ————————————————————————————————————————————————————————————————————————————————————————————
// |||||||| BDouble more Operators ||||||||||||||||||||||||||||||||||||||||||||||
// ————————————————————————————————————————————————————————————————————————————————————————————
//
//
//
/**
* Returns the absolute value of the given number.
* - parameter x: a big double
*/
public func abs(_ x: BDouble) -> BDouble
{
return BDouble(
sign: false,
numerator: x.numerator,
denominator: x.denominator
)
}
/**
* round to largest BInt value not greater than base
*/
public func floor(_ base: BDouble) -> BInt
{
if base.isZero()
{
return BInt(0)
}
let digits = 3
let multiplier = [10].exponentiating(digits)
let rawRes = abs(base).numerator.multiplyingBy(multiplier).divMod(base.denominator).quotient
let res = BInt(limbs: rawRes).description
let offset = res.count - digits
let lhs = res.prefix(offset).description
let rhs = Double("0." + res.suffix(res.count - offset))!
var ans = BInt(String(lhs))!
if base.isNegative() {
ans = -ans
if rhs > 0.0 {
ans = ans - BInt(1)
}
}
return ans
}
/**
* round to smallest BInt value not less than base
*/
public func ceil(_ base: BDouble) -> BInt
{
if base.isZero()
{
return BInt(0)
}
let digits = 3
let multiplier = [10].exponentiating(digits)
let rawRes = abs(base).numerator.multiplyingBy(multiplier).divMod(base.denominator).quotient
let res = BInt(limbs: rawRes).description
let offset = res.count - digits
let rhs = Double("0." + res.suffix(res.count - offset))!
let lhs = res.prefix(offset)
var retVal = BInt(String(lhs))!
if base.isNegative()
{
retVal = -retVal
} else {
if rhs > 0.0
{
retVal += 1
}
}
return retVal
}
/**
* Returns a BDouble number raised to a given power.
*/
public func pow(_ base : BDouble, _ exp : Int) -> BDouble {
return base**exp
}
/**
* Returns the BDouble that is the smallest
*/
public func min(_ lhs: BDouble, _ rhs: BDouble) -> BDouble {
if lhs <= rhs {
return lhs
}
return rhs
}
/**
* Returns the BDouble that is largest
*/
public func max(_ lhs: BDouble, _ rhs: BDouble) -> BDouble {
if lhs >= rhs {
return lhs
}
return rhs
}
| 26.59181 | 136 | 0.502819 |
e84e5725078c86e4b7157b0726eb92d0198d6cba | 1,585 | import Foundation
import Domain
import RealmSwift
protocol PokemonFavoritesBusinessLogic {
func fetchPokemons(request: PokemonFavorites.FetchPokemons.Request)
}
protocol PokemonFavoritesDataStore {
var pokemons: [Pokemon] { get }
}
class PokemonFavoritesInteractor: PokemonFavoritesDataStore {
var presenter: PokemonFavoritesPresentationLogic?
var pokemons: [Pokemon]
// MARK: - Use Cases
let fetchPokemons: FetchPokemons
init(fetchPokemons: FetchPokemons, pokemons: [Pokemon] = []) {
self.fetchPokemons = fetchPokemons
self.pokemons = pokemons
}
}
// MARK: - UnlockBusinessLogic
extension PokemonFavoritesInteractor: PokemonFavoritesBusinessLogic {
func fetchPokemons(request: PokemonFavorites.FetchPokemons.Request) {
let decoder = JSONDecoder()
var pokemon = try! decoder.decode(Pokemon.self, from: Data(ObjectHelper.object.utf8))
var pokemons : [Pokemon] = []
let realm = try! Realm()
let favorites = realm.objects(PokemonObject.self)
for fav in favorites {
pokemon.favorited = fav.favorited
pokemon.height = fav.height
pokemon.id = fav.id
pokemon.name = fav.name
pokemon.order = fav.order
pokemon.weight = fav.weight
pokemon.sprites.frontDefault = fav.frontDefault
pokemons.append(pokemon)
}
self.presenter?.presentFetchPokemons(response: PokemonFavorites.FetchPokemons.Response(pokemons: pokemons))
}
}
| 30.480769 | 115 | 0.666877 |
ff4887940d39e55e2bcbd3e94d3ef30ba5e263c4 | 325 | //
// UIColor_Extension.swift
// DouYuDemo
//
// Created by LT-MacbookPro on 17/2/23.
// Copyright © 2017年 XFX. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(r :CGFloat,g :CGFloat,b :CGFloat){
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
}
| 15.47619 | 72 | 0.615385 |
1e1ff65d3c2b196ad14fd84c8f76f395092655f0 | 4,752 | import AST
import Basic
public enum ControlEdge {
case forward, backward, bidirectional
}
public typealias ControlFlowGraph = AdjacencyList<BasicBlock.ID, ControlEdge>
/// A VIL function.
public struct VILFun {
/// An iterator that supplies pairs `(path, inst)`, where path is an instruction path and `inst`
/// the instruction at that path, for all the instructions in a function.
public struct InstEnumerator: IteratorProtocol {
fileprivate let funName: VILName
fileprivate var blocks: [(key: BasicBlock.ID, value: BasicBlock)]
fileprivate var instIndex: BasicBlock.Index?
fileprivate init(funName: VILName, blocks: [(key: BasicBlock.ID, value: BasicBlock)]) {
self.funName = funName
self.blocks = blocks
self.instIndex = blocks.last?.value.instructions.startIndex
}
public mutating func next() -> (path: InstPath, inst: Inst)? {
while let (blockID, block) = blocks.last, let i = instIndex {
if i != block.instructions.endIndex {
defer { instIndex = block.instructions.index(after: i) }
return (
path: InstPath(funName: funName, blockID: blockID, instIndex: i),
inst: block.instructions[i])
} else {
blocks.removeLast()
instIndex = blocks.last?.value.instructions.startIndex
}
}
return nil
}
}
/// The mangled name of the function.
public let name: VILName
/// An optional debug name describing the function.
public let debugName: String?
/// The VIL type of the function.
public let type: VILFunType
/// The basic blocks of the function.
///
/// Do not add or remove blocks using this property. Use `createBlock(arguments:before:)` or
/// `removeBasicBlock(_:)` instead.
public var blocks: [BasicBlock.ID: BasicBlock] = [:]
/// The identifier of the entry block.
public var entryID: BasicBlock.ID?
/// The control flow graph of the function.
///
/// This graph describes the relation between the basic blocks of the function. The direction of
/// of its edges denotes the direction of the control flow from one block to another: there an
/// edge from `A` to `B` if the former's terminator points to the latter.
///
/// The graph is represented as an adjacency list that encodes the successor and the predecessor
/// relations, enabling efficient lookup in both directions. Let `l` be the label on an edge
/// from `A` to `B`:
/// - if `l = .forward`, then `A` is a predecessor of `B`;
/// - if `l = .backward`, then `A` is a successor of `B`;
/// - if `l = .bidirectional`, then `A` is a predecessor *and* a successor of `B`.
public var cfg = ControlFlowGraph()
/// Creates a new VIL function.
///
/// - Parameters:
/// - name: The name of the function.
/// - type: The unapplied type of the function.
/// - debugName: An optional debug name describing the function.
init(name: VILName, type: VILFunType, debugName: String? = nil) {
self.name = name
self.debugName = debugName
self.type = type
}
/// A Boolean value that indicates whether the function has an entry.
public var hasEntry: Bool { entryID != nil }
/// The entry block of the function.
public var entry: BasicBlock? {
guard let entryID = self.entryID else { return nil }
return blocks[entryID]
}
/// Returns an iterator that supplies all instructions of the function.
///
/// The iterator offers no guarantee over the order in which it returns the function's
/// instructions.
public func makeInstIterator() -> JoinedIterator<StableDoublyLinkedList<Inst>.Iterator> {
return JoinedIterator(blocks.values.map({ $0.instructions.makeIterator() }))
}
/// Returns an iterator that supplies all instructions of the function, together with their path.
///
/// The iterator offers no guarantee over the order in which instructions are returned.
public func makeInstEnumerator() -> InstEnumerator {
return InstEnumerator(funName: name, blocks: Array(blocks))
}
/// Dereference an instruction path, assuming it refers into this function.
public subscript(path: InstPath) -> Inst {
assert(path.funName == name)
return blocks[path.blockID]!.instructions[path.instIndex]
}
/// Inserts a control edge from one basic block to another.
mutating func insertControlEdge(from source: BasicBlock.ID, to target: BasicBlock.ID) {
assert(blocks[source] != nil && blocks[target] != nil)
let (inserted, label) = cfg.insertEdge(from: source, to: target, labeledBy: .forward)
if inserted {
cfg[target, source] = .backward
} else if label == .backward {
cfg[source, target] = .bidirectional
cfg[target, source] = .bidirectional
}
}
}
| 34.941176 | 99 | 0.679503 |
33085952d7c6e6956f07a36eca24eaed9496d315 | 382 | //
// ItemAddCardCollectionReusableView.swift
// EstrategiaDigital
//
// Created by Charls Salazar on 04/07/17.
// Copyright © 2017 Charls Salazar. All rights reserved.
//
import UIKit
public class ItemAddCardCollectionReusableView: UICollectionReusableView {
override public func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 20.105263 | 74 | 0.712042 |
3aa12b2960128d0a621b63764133eea6014a961c | 2,336 | import XCTest
@testable import PointFreeFramework
class PointFreeFrameworkTests: SnapshotTestCase {
func testEpisodesView() {
let episodesVC = EpisodeListViewController(episodes: episodes)
assertSnapshot(matching: episodesVC)
}
}
protocol Snapshottable {
associatedtype Snapshot: Diffable
var snapshot: Snapshot { get }
}
protocol Diffable {
static func diff(old: Self, new: Self) -> [XCTAttachment]
static func from(data: Data) -> Self
var data: Data { get }
}
extension UIImage: Diffable {
var data: Data {
return self.pngData()!
}
static func from(data: Data) -> Self {
return self.init(data: data, scale: UIScreen.main.scale)!
}
static func diff(old: UIImage, new: UIImage) -> [XCTAttachment] {
guard let difference = Diff.images(old, new) else { return [] }
return [old, new, difference].map(XCTAttachment.init(image:))
}
}
extension UIImage: Snapshottable {
var snapshot: UIImage {
return self
}
}
extension CALayer: Snapshottable {
var snapshot: UIImage {
return UIGraphicsImageRenderer(size: self.bounds.size)
.image { ctx in self.render(in: ctx.cgContext) }
}
}
extension UIView: Snapshottable {
var snapshot: UIImage {
return self.layer.snapshot
}
}
extension UIViewController: Snapshottable {
var snapshot: UIImage {
return self.view.snapshot
}
}
class SnapshotTestCase: XCTestCase {
var record = false
func assertSnapshot<S: Snapshottable>(
matching value: S,
file: StaticString = #file,
function: String = #function,
line: UInt = #line) {
let snapshot = value.snapshot
let referenceUrl = snapshotUrl(file: file, function: function)
.appendingPathExtension("png")
if !self.record, let referenceData = try? Data(contentsOf: referenceUrl) {
let reference = S.Snapshot.from(data: referenceData)
let attachments = S.Snapshot.diff(old: reference, new: snapshot)
guard !attachments.isEmpty else { return }
XCTFail("Snapshot didn't match reference", file: file, line: line)
XCTContext.runActivity(named: "Attached failure diff") { activity in
attachments.forEach(activity.add)
}
} else {
try! snapshot.data.write(to: referenceUrl)
XCTFail("Recorded: …\n\"\(referenceUrl.path)\"", file: file, line: line)
}
}
}
| 22.461538 | 78 | 0.685788 |
fcaf6d5d7a8a027836a9590d75ade3bf5504b03e | 4,895 | //
// SlidableModifier.swift
// TimeThreads
//
// Created by 杨鑫 on 2020/7/22.
// Copyright © 2020 杨鑫. All rights reserved.
//
import SwiftUI
public struct SlidableModifier: ViewModifier {
public enum SlideAxis {
case left2Right
case right2Left
}
private var contentOffset: CGSize {
switch self.slideAxis {
case .left2Right:
return .init(width: self.currentSlotsWidth, height: 0)
case .right2Left:
return .init(width: -self.currentSlotsWidth, height: 0)
}
}
private var slotOffset: CGSize {
switch self.slideAxis {
case .left2Right:
return .init(width: self.currentSlotsWidth - self.totalSlotWidth, height: 0)
case .right2Left:
return .init(width: self.totalSlotWidth - self.currentSlotsWidth, height: 0)
}
}
private var zStackAlignment: Alignment {
switch self.slideAxis {
case .left2Right:
return .leading
case .right2Left:
return .trailing
}
}
/// Animated slot widths of total
@State var currentSlotsWidth: CGFloat = 0
/// To restrict the bounds of slots
private func optWidth(value: CGFloat) -> CGFloat {
return min(abs(value), totalSlotWidth)
}
var animatableData: Double {
get { Double(self.currentSlotsWidth) }
set { self.currentSlotsWidth = CGFloat(newValue) }
}
private var totalSlotWidth: CGFloat {
return slots.map { $0.style.slotWidth }.reduce(0, +) + 30
}
private var slots: [Slot]
private var slideAxis: SlideAxis
public init(slots: [Slot], slideAxis: SlideAxis) {
self.slots = slots
self.slideAxis = slideAxis
}
private func flushState() {
withAnimation {
self.currentSlotsWidth = 0
}
}
public func body(content: Content) -> some View {
ZStack(alignment: self.zStackAlignment) {
content
.offset(self.contentOffset)
.onTapGesture(perform: flushState)
Rectangle()
.opacity(0)
.overlay(
HStack(spacing: 10) {
ForEach(self.slots) { slot in
Circle()
.overlay(
VStack(spacing: 4) {
slot.image()
.resizable()
.scaledToFit()
.foregroundColor(slot.style.imageColor)
.frame(width: slot.style.slotWidth * 0.3)
slot.title()
.foregroundColor(slot.style.imageColor)
.font(.system(size: slot.style.slotWidth * 0.2))
}
)
.frame(width: slot.style.slotWidth)
.foregroundColor(slot.style.background)
.onTapGesture {
slot.action()
self.flushState()
}
}
}
)
.offset(self.slotOffset)
.frame(width: self.totalSlotWidth)
}
.gesture(
DragGesture()
.onChanged { value in
let amount = value.translation.width
if self.slideAxis == .left2Right {
if amount < 0 { return }
} else {
if amount > 0 { return }
}
self.currentSlotsWidth = self.optWidth(value: amount)
}
.onEnded { value in
withAnimation {
if self.currentSlotsWidth < (self.totalSlotWidth / 2) {
self.currentSlotsWidth = 0
} else {
self.currentSlotsWidth = self.totalSlotWidth
}
}
}
)
}
}
extension View {
func swipeLeft2Right(slots: [Slot]) -> some View {
return self.modifier(SlidableModifier(slots: slots, slideAxis: .left2Right))
}
func swipeRight2Left(slots: [Slot]) -> some View {
return self.modifier(SlidableModifier(slots: slots, slideAxis: .right2Left))
}
func embedInAnyView() -> AnyView {
return AnyView ( self )
}
}
| 30.59375 | 88 | 0.45475 |
d7dc0d8505cfdd5a6245ee3dcb9b3110078f51e8 | 3,965 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Creates an asynchronous sequence that contains, in order, the elements of
/// the base sequence that satisfy the given predicate.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `filter(_:)` method returns `true` for even
/// values and `false` for odd values, thereby filtering out the odd values:
///
/// let stream = Counter(howHigh: 10)
/// .filter { $0 % 2 == 0 }
/// for await number in stream {
/// print("\(number) ", terminator: " ")
/// }
/// // Prints: 2 4 6 8 10
///
/// - Parameter isIncluded: A closure that takes an element of the
/// asynchronous sequence as its argument and returns a Boolean value
/// that indicates whether to include the element in the filtered sequence.
/// - Returns: An asynchronous sequence that contains, in order, the elements
/// of the base sequence that satisfy the given predicate.
@inlinable
public __consuming func filter(
_ isIncluded: @escaping (Element) async -> Bool
) -> AsyncFilterSequence<Self> {
return AsyncFilterSequence(self, isIncluded: isIncluded)
}
}
/// An asynchronous sequence that contains, in order, the elements of
/// the base sequence that satisfy a given predicate.
@available(SwiftStdlib 5.1, *)
public struct AsyncFilterSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let isIncluded: (Element) async -> Bool
@usableFromInline
init(
_ base: Base,
isIncluded: @escaping (Base.Element) async -> Bool
) {
self.base = base
self.isIncluded = isIncluded
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncFilterSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The filter sequence produces whatever type of element its base
/// sequence produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the filter sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let isIncluded: (Base.Element) async -> Bool
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
isIncluded: @escaping (Base.Element) async -> Bool
) {
self.baseIterator = baseIterator
self.isIncluded = isIncluded
}
/// Produces the next element in the filter sequence.
///
/// This iterator calls `next()` on its base iterator; if this call returns
/// `nil`, `next()` returns nil. Otherwise, `next()` evaluates the
/// result with the `predicate` closure. If the closure returns `true`,
/// `next()` returns the received element; otherwise it awaits the next
/// element from the base iterator.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
while true {
guard let element = try await baseIterator.next() else {
return nil
}
if await isIncluded(element) {
return element
}
}
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), isIncluded: isIncluded)
}
}
| 34.181034 | 80 | 0.652963 |
611843f2449d66f15001a1d856d3eee48abbff20 | 631 | //
// SharedObserver.swift
// iOSCleanArchitectureTwitterSample
//
// Created by koutalou on 2016/11/15.
// Copyright © 2016年 koutalou. All rights reserved.
//
import RxSwift
class SharedObserver {
static let instance: SharedObserver = SharedObserver()
fileprivate let selectPerson: PublishSubject<Void> = PublishSubject()
}
// MARK: - Interface
public protocol SelectPersonObserver {
var selectPersonObserver: PublishSubject<Void> { get }
}
// MARK: - Implementation
extension SharedObserver: SelectPersonObserver {
var selectPersonObserver: PublishSubject<Void> {
return selectPerson
}
}
| 22.535714 | 73 | 0.735341 |
8a8d4b6a6cb97621c7a38346fd584ec012821081 | 6,127 | //
// AddressesKeysViewController.swift
// WavesWallet-iOS
//
// Created by mefilt on 25/10/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import RxFeedback
import RxSwift
import RxCocoa
final class MyAddressViewController: UIViewController {
typealias Types = MyAddressTypes
@IBOutlet private var tableView: UITableView!
private var sections: [Types.ViewModel.Section] = []
private var eventInput: PublishSubject<Types.Event> = PublishSubject<Types.Event>()
var presenter: MyAddressPresenterProtocol!
override func viewDidLoad() {
super.viewDidLoad()
createBackButton()
navigationItem.backgroundImage = UIImage()
navigationItem.shadowImage = UIImage()
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
} else {
edgesForExtendedLayout = UIRectEdge(rawValue: 0)
}
tableView.tableFooterView = UIView()
tableView.tableHeaderView = UIView()
setupSystem()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.contentInset = UIEdgeInsets(top: UIApplication.shared.statusBarFrame.height, left: 0, bottom: 0, right: 0)
}
}
//MARK: - MyAddressInfoAddressCellDelegate
extension MyAddressViewController: MyAddressInfoAddressCellDelegate {
func myAddressInfoAddressCellDidTapShareAddress(_ address: String) {
ImpactFeedbackGenerator.impactOccurred()
let activityVC = UIActivityViewController(activityItems: [address], applicationActivities: [])
present(activityVC, animated: true, completion: nil)
}
}
// MARK: RxFeedback
private extension MyAddressViewController {
func setupSystem() {
let uiFeedback: MyAddressPresenterProtocol.Feedback = bind(self) { (owner, state) -> (Bindings<Types.Event>) in
return Bindings(subscriptions: owner.subscriptions(state: state), events: owner.events())
}
let readyViewFeedback: MyAddressPresenterProtocol.Feedback = { [weak self] _ in
guard let self = self else { return Signal.empty() }
return self
.rx
.viewWillAppear
.asObservable()
.throttle(1, scheduler: MainScheduler.asyncInstance)
.asSignal(onErrorSignalWith: Signal.empty())
.map { _ in Types.Event.viewWillAppear }
}
let viewDidDisappearFeedback: MyAddressPresenterProtocol.Feedback = { [weak self] _ in
guard let self = self else { return Signal.empty() }
return self
.rx
.viewDidDisappear
.asObservable()
.throttle(1, scheduler: MainScheduler.asyncInstance)
.asSignal(onErrorSignalWith: Signal.empty())
.map { _ in Types.Event.viewDidDisappear }
}
presenter.system(feedbacks: [uiFeedback, readyViewFeedback, viewDidDisappearFeedback])
}
func events() -> [Signal<Types.Event>] {
return [eventInput.asSignal(onErrorSignalWith: Signal.empty())]
}
func subscriptions(state: Driver<Types.State>) -> [Disposable] {
let subscriptionSections = state.drive(onNext: { [weak self] state in
guard let self = self else { return }
self.updateView(with: state.displayState)
})
return [subscriptionSections]
}
func updateView(with state: Types.DisplayState) {
self.sections = state.sections
if let action = state.action {
switch action {
case .update:
tableView.reloadData()
case .none:
break
}
}
}
}
// MARK: UITableViewDataSource
extension MyAddressViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = sections[indexPath]
switch row {
case .address(let address):
let cell: MyAddressInfoAddressCell = tableView.dequeueCell()
cell.delegate = self
cell.update(with: .init(address: address))
return cell
case .aliases(let count):
let cell: MyAddressAliacesCell = tableView.dequeueCell()
cell.update(with: .init(count: count))
cell.infoButtonDidTap = { [weak self] in
guard let self = self else { return }
self.eventInput.onNext(.tapShowInfo)
}
return cell
case .qrcode(let address):
let cell: MyAddressQRCodeCell = tableView.dequeueCell()
cell.update(with: .init(address: address))
return cell
case .skeleton:
let cell: MyAddressAliacesSkeletonCell = tableView.dequeueCell()
return cell
}
}
}
// MARK: UITableViewDelegate
extension MyAddressViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = sections[indexPath]
switch row {
case .address:
return MyAddressInfoAddressCell.viewHeight()
case .aliases:
return MyAddressAliacesCell.viewHeight()
case .qrcode:
return MyAddressQRCodeCell.viewHeight()
case .skeleton:
return MyAddressAliacesSkeletonCell.viewHeight()
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let row = sections[indexPath]
switch row {
case .skeleton:
let skeleton = cell as? MyAddressAliacesSkeletonCell
skeleton?.startAnimation()
default:
break
}
}
}
| 29.315789 | 125 | 0.630488 |
1e85a05c4eb4282e99ca738b6bd0d401a7c12101 | 4,869 | //
// FlightsResultInteractor.swift
// SkyScannerChallenge
//
// Created by iOS developer on 12/11/18.
// Copyright © 2018 Sky Scanner Candidate Ltd. All rights reserved.
//
import Foundation
import RxAlamofire
import RxSwift
protocol FlightsResultBusinessLogic {
func searchFlights()
}
protocol FlightsResultDataStore: class {
var routeQuery: SearchFlightsQuery? { get set }
}
class FlightsResultInteractor: FlightsResultDataStore {
private var presenter: FlightsResultPresentationLogic?
private let apiWorker = ApiWorker()
private let errorWorker = ErrorWorker()
private var disposeBag = DisposeBag()
private var sessionId: String?
var routeQuery: SearchFlightsQuery?
init(_ resourceView: FlightsResultDisplayLogic) {
presenter = FlightsResultPresenter(resourceView)
}
deinit {
disposeBag = DisposeBag()
NSLog("Deinit: \(type(of: self))")
}
}
extension FlightsResultInteractor: FlightsResultBusinessLogic {
final func searchFlights() {
guard let wRouteQuery = routeQuery else { return }
apiWorker.requestPricingSession(FlightsRequest(originPlace: wRouteQuery.departingCity.skyCode, destinationPlace: wRouteQuery.arrivalCity.skyCode, outboundDate: wRouteQuery.departingDate, inboundDate: wRouteQuery.arrivalDate))
.asDriver(onErrorJustReturn: ApiWorker.Result.failure(ErrorWorker.ApiError.invalidResponse))
.drive(onNext: { [weak self] (result) in
guard let wSelf = self else {return}
switch result {
case .success(let response):
if let location = response.1["Location"] as? String {
wSelf.sessionId = URL(string: location)!.lastPathComponent
wSelf.pollFlights()
} else {
wSelf.presenter?.manageLiveFlightSearchFailResult(wSelf.errorWorker.process(error: ErrorWorker.ApiError.invalidLocationHeader))
}
case .failure(let error):
wSelf.presenter?.manageLiveFlightSearchFailResult(wSelf.errorWorker.process(error: error))
wSelf.sessionId = .none
}
}).disposed(by: disposeBag)
}
}
private extension FlightsResultInteractor {
final func pollFlights(_ pageIndex: Int = 0) {
apiWorker.pollFlightsResult(FlightResultsRequest(sessionId: sessionId!, pageIndex: pageIndex))
.asDriver(onErrorJustReturn: ApiWorker.Result.failure(ErrorWorker.ApiError.invalidResponse))
.drive(onNext: { [weak self] (result) in
guard let wSelf = self else {return}
switch result {
case .success(let response):
wSelf.processData(response.0, isPolling: pageIndex != -1)
case .failure(let error):
wSelf.presenter?.manageLiveFlightSearchFailResult(wSelf.errorWorker.process(error: error))
}
}).disposed(by: disposeBag)
}
final func processData(_ response: FlightResultsResponse, isPolling: Bool = true) {
NSLog("Process stating")
DispatchQueue.global().async {
var items = [Itinerary]()
response.itineraries.forEach { (itinerary) in
let outboundLeg = Leg.initLeg(response.legs, originalSegments: response.segments, places: response.places, carriers: response.carriers, wantedLegId: itinerary.outboundLegId)
let inboundLeg = Leg.initLeg(response.legs, originalSegments: response.segments, places: response.places, carriers: response.carriers, wantedLegId: itinerary.inboundLegId)
let firstPriceOption = itinerary.pricingOptions.first
var agent: Agent?
if let agentId = firstPriceOption?.agents.first {
agent = response.agents.first(where: { $0.identifier == agentId})
}
items.append(Itinerary(outboundLeg: outboundLeg, inboundLeg: inboundLeg, agent: agent, price: firstPriceOption?.price))
}
DispatchQueue.main.async { [weak self] in
guard let wSelf = self else { return }
let isComplete = response.status == "UpdatesComplete"
wSelf.presenter?.manageLiveFlightSearchResult(newData: items, complete: isComplete && !isPolling)
NSLog("Process ending")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
if !isComplete {
NSLog("Start polling again")
wSelf.pollFlights()
} else if isPolling {
NSLog("Start fetching all data")
wSelf.pollFlights(-1)
}
}
}
}
}
}
| 41.974138 | 233 | 0.625796 |
f746e038ba74ec9a72922a5b666a6fa9ac4a8174 | 1,700 | import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
return actualValue >= expectedValue
}
}
/// A Nimble matcher that succeeds when the actual value is greater than
/// or equal to the expected value.
public func beGreaterThanOrEqualTo<T: NMBComparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedAscending
return matches
}
}
public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
extension NMBObjCMatcher {
public class func beGreaterThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
let expr = actualExpression.cast { $0 as NMBComparable? }
return beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| 42.5 | 122 | 0.728235 |
0162960cbfc434654220ea086686d7cbf583b230 | 1,387 | //
// ControlPanelView.swift
// ImageMask
//
// Created by Виталий Баник on 03.07.2020.
// Copyright © 2020 Виталий Баник. All rights reserved.
//
import SwiftUI
// MARK: - ControlPanelView
struct ControlPanelView: View {
// MARK: - ViewModel
@ObservedObject var viewModel: ProcessImageViewModel
// MARK: - Body
var body: some View {
HStack(alignment: .center, spacing: 4) {
Spacer()
Button(action: {
self.viewModel.openImage()
}) {
Text("Open png image")
}.disabled(self.viewModel.processingState == .processing)
ProcessingStateText(state: self.viewModel.processingState)
.frame(minWidth: 150, minHeight: 35)
.lineLimit(nil)
.multilineTextAlignment(.center)
Button(action: {
self.viewModel.createMask()
}) {
Text("Create mask file")
}.disabled(self.viewModel.processingState == .processing || self.viewModel.image == nil)
Spacer()
}
.padding()
}
}
// MARK: - Preview
struct ControlPanelView_Previews: PreviewProvider {
static var previews: some View {
ControlPanelView(viewModel: ProcessImageViewModel(configType: .processMaskFileLocalPNG))
}
}
| 27.196078 | 100 | 0.568854 |
6a5911be20b7666dab57cc08f5f75e7baea24138 | 1,572 | import UIKit
protocol ApplicationSettingsPresentable {
func askOpenApplicationSettings(
with message: String,
title: String?,
from view: ControllerBackedProtocol?,
locale: Locale?
)
}
extension ApplicationSettingsPresentable {
func askOpenApplicationSettings(
with message: String,
title: String?,
from view: ControllerBackedProtocol?,
locale: Locale?
) {
var currentController = view?.controller
if currentController == nil {
currentController = UIApplication.shared.delegate?.window??.rootViewController
}
guard let controller = currentController else {
return
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let closeTitle = R.string.localizable.commonNotNow(preferredLanguages: locale?.rLanguages)
let closeAction = UIAlertAction(title: closeTitle, style: .cancel, handler: nil)
let settingsTitle = R.string.localizable.commonOpenSettings(preferredLanguages: locale?.rLanguages)
let settingsAction = UIAlertAction(title: settingsTitle, style: .default) { _ in
if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
alert.addAction(closeAction)
alert.addAction(settingsAction)
controller.present(alert, animated: true, completion: nil)
}
}
| 33.446809 | 113 | 0.670483 |
d6084d510d6f4774af6fa1729c0a4d2c779e2f3f | 4,935 | //
// AccelerationRecorder.swift
// GetHeart Extension
//
// Created by Admin on 5/9/18.
// Copyright © 2018 Admin. All rights reserved.
//
import Foundation
import CoreMotion
import WatchKit
class CoreMotionRecorder {
let motion = CMMotionManager()
let dataHeading = "date,x_acc,y_acc,z_acc,x_gyro,y_gyro,z_gyro,heart_rate"
var isRecordingMotion = false
var recordingFrequency : Double = 1.0/30.0 // 30 Hz
var sigFigs: Int = 8
private var motionData: String = ""
private var timer : Timer?
var view : InterfaceController
/// - parameter viewbox: the parent `InterfaceController`
init(_ viewbox : InterfaceController) {
view = viewbox
}
/**
- parameters:
- viewbox: the parent `InterfaceController`
- recordingRate: Frequency at which to record
- dataLength: Length to which data values should be clipped, as a String
*/
init(_ viewbox : InterfaceController, _ recordingRate: Double, _ dataLength: Int) {
view = viewbox
recordingFrequency = recordingRate
sigFigs = dataLength
}
/**
Starts recording acceleration and rotation rate at `recordingFrequency` Hz
Updates labels with corrosponding values during each tick, and appends values to `motionData`
*/
func startRecording() {
if(motion.isDeviceMotionAvailable) {
isRecordingMotion = true
motion.deviceMotionUpdateInterval = recordingFrequency
motion.startDeviceMotionUpdates()
timer = Timer(fire: Date(), interval: recordingFrequency, repeats: true, block: { (timer) in
// Get data.
if let data = self.motion.deviceMotion {
let x = self.formatDataPoint(data.userAcceleration.x)
let y = self.formatDataPoint(data.userAcceleration.y)
let z = self.formatDataPoint(data.userAcceleration.z)
let xr = self.formatDataPoint(data.rotationRate.x)
let yr = self.formatDataPoint(data.rotationRate.y)
let zr = self.formatDataPoint(data.rotationRate.z)
// update labels
DispatchQueue.main.async {
self.view.updateMotionLabel("x", x, true)
self.view.updateMotionLabel("y", y, true)
self.view.updateMotionLabel("z", z, true)
self.view.updateMotionLabel("x", xr, false)
self.view.updateMotionLabel("y", yr, false)
self.view.updateMotionLabel("z", zr, false)
}
let date = InterfaceController.microsecondsSince1970()
self.motionData += ("\(date),\(x),\(y),\(z),\(xr),\(yr),\(zr),\(self.view.heart.newData)\n")
}
})
// Add the timer to the current run loop.
RunLoop.current.add(self.timer!, forMode: .defaultRunLoopMode)
}
else {
isRecordingMotion = false
view.presentAlert(withTitle: "Error", message: "Device motion unavailable", preferredStyle: .alert, actions: [WKAlertAction(title: "OK", style: .default){}])
}
}
func formatDataPoint(_ num : Double) -> String {
var output = String(num.description.prefix(sigFigs))
while(output.count < sigFigs) {
output = "0" + output
}
return output
}
/**
Stops the recording of rotation rate and acceleration.
Sends the collected data as an Array of Strings to `InterfaceController.motionData`,
and updates the formatted data variable, `InterfaceController.data`
*/
func stopRecording() {
isRecordingMotion = false
timer?.invalidate()
timer = nil
motion.stopDeviceMotionUpdates()
InterfaceController.motionData = getData(false)
InterfaceController.data = view.formatData()
view.updateMotionLabel("x", "---", true)
view.updateMotionLabel("y", "---", true)
view.updateMotionLabel("z", "---", true)
view.updateMotionLabel("x", "---", false)
view.updateMotionLabel("y", "---", false)
view.updateMotionLabel("z", "---", false)
}
/**
Transforms `motionData` into an array of Strings, splitting by "\n"
- parameter saveData: determines whether or not to reset existing data, or overwrite.
- returns: An Array of Strings containing the lines of `motionData`
*/
func getData(_ saveData: Bool) -> Array<String> {
let lines = motionData.split(separator: "\n")
var data : [String] = Array()
for line in lines {
data.append(String(line))
}
if(!saveData) {
InterfaceController.data = ""
motionData = ""
}
return data
}
}
| 38.554688 | 169 | 0.591287 |
bb153f695a86e6185747532066c7f51b31df82ab | 6,540 | //
// LBXScanViewController.swift
// swiftScan
//
// Created by lbxia on 15/12/8.
// Copyright © 2015年 xialibing. All rights reserved.
//
import UIKit
import Foundation
import AVFoundation
public protocol LBXScanViewControllerDelegate: class {
func scanFinished(scanResult: LBXScanResult, error: String?)
}
public protocol QRRectDelegate {
func drawwed()
}
open class LBXScanViewController: UIViewController {
// 返回扫码结果,也可以通过继承本控制器,改写该handleCodeResult方法即可
open weak var scanResultDelegate: LBXScanViewControllerDelegate?
open var delegate: QRRectDelegate?
open var scanObj: LBXScanWrapper?
open var scanStyle: LBXScanViewStyle? = LBXScanViewStyle()
open var qRScanView: LBXScanView?
// 启动区域识别功能
open var isOpenInterestRect = false
//连续扫码
open var isSupportContinuous = false;
// 识别码的类型
public var arrayCodeType: [AVMetadataObject.ObjectType]?
// 是否需要识别后的当前图像
public var isNeedCodeImage = false
// 相机启动提示文字
public var readyString: String! = "loading"
open override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// [self.view addSubview:_qRScanView];
view.backgroundColor = UIColor.black
edgesForExtendedLayout = UIRectEdge(rawValue: 0)
}
open func setNeedCodeImage(needCodeImg: Bool) {
isNeedCodeImage = needCodeImg
}
// 设置框内识别
open func setOpenInterestRect(isOpen: Bool) {
isOpenInterestRect = isOpen
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
drawScanView()
perform(#selector(LBXScanViewController.startScan), with: nil, afterDelay: 0.3)
}
@objc open func startScan() {
if scanObj == nil {
var cropRect = CGRect.zero
if isOpenInterestRect {
cropRect = LBXScanView.getScanRectWithPreView(preView: view, style: scanStyle!)
}
// 指定识别几种码
if arrayCodeType == nil {
arrayCodeType = [AVMetadataObject.ObjectType.qr as NSString,
AVMetadataObject.ObjectType.ean13 as NSString,
AVMetadataObject.ObjectType.code128 as NSString] as [AVMetadataObject.ObjectType]
}
scanObj = LBXScanWrapper(videoPreView: view,
objType: arrayCodeType!,
isCaptureImg: isNeedCodeImage,
cropRect: cropRect,
success: { [weak self] (arrayResult) -> Void in
guard let strongSelf = self else {
return
}
if !strongSelf.isSupportContinuous {
// 停止扫描动画
strongSelf.qRScanView?.stopScanAnimation()
}
strongSelf.handleCodeResult(arrayResult: arrayResult)
})
}
scanObj?.supportContinuous = isSupportContinuous;
// 结束相机等待提示
qRScanView?.deviceStopReadying()
// 开始扫描动画
qRScanView?.startScanAnimation()
// 相机运行
scanObj?.start()
}
open func drawScanView() {
if qRScanView == nil {
qRScanView = LBXScanView(frame: view.frame, vstyle: scanStyle!)
view.addSubview(qRScanView!)
delegate?.drawwed()
}
// qRScanView?.deviceStartReadying(readyStr: readyString)
}
/**
处理扫码结果,如果是继承本控制器的,可以重写该方法,作出相应地处理,或者设置delegate作出相应处理
*/
open func handleCodeResult(arrayResult: [LBXScanResult]) {
guard let delegate = scanResultDelegate else {
fatalError("you must set scanResultDelegate or override this method without super keyword")
}
if !isSupportContinuous {
navigationController?.popViewController(animated: true)
}
if let result = arrayResult.first {
delegate.scanFinished(scanResult: result, error: nil)
} else {
let result = LBXScanResult(str: nil, img: nil, barCodeType: nil, corner: nil)
delegate.scanFinished(scanResult: result, error: "no scan result")
}
}
open override func viewWillDisappear(_ animated: Bool) {
NSObject.cancelPreviousPerformRequests(withTarget: self)
qRScanView?.stopScanAnimation()
scanObj?.stop()
}
@objc open func openPhotoAlbum() {
LBXPermissions.authorizePhotoWith { [weak self] _ in
let picker = UIImagePickerController()
picker.sourceType = UIImagePickerController.SourceType.photoLibrary
picker.delegate = self
picker.allowsEditing = true
self?.present(picker, animated: true, completion: nil)
}
}
}
//MARK: - 图片选择代理方法
extension LBXScanViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: -----相册选择图片识别二维码 (条形码没有找到系统方法)
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
picker.dismiss(animated: true, completion: nil)
let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
guard let image = editedImage ?? originalImage else {
showMsg(title: nil, message: NSLocalizedString("Identify failed", comment: "Identify failed"))
return
}
let arrayResult = LBXScanWrapper.recognizeQRImage(image: image)
if !arrayResult.isEmpty {
handleCodeResult(arrayResult: arrayResult)
}
}
}
//MARK: - 私有方法
private extension LBXScanViewController {
func showMsg(title: String?, message: String?) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let alertAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .default, handler: nil)
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
}
}
| 33.367347 | 150 | 0.607187 |
4b9f016c6180d1ea2791c7f38771f9ff6284e5f8 | 898 | import Foundation
// MARK: - HTTPRequest
struct HTTPResponse {
static let separator:[UInt8] = [0x0d, 0x0a, 0x0d, 0x0a]
var version:HTTPVersion = .Version11
var statusCode:HTTPStatusCode = .OK
var headerFields:[String: String] = [:]
var body:[UInt8] = []
}
// MARK: CustomStringConvertible
extension HTTPResponse: CustomStringConvertible {
var description:String {
return Mirror(reflecting: self).description
}
}
// MARK: BytesConvertible
extension HTTPResponse: BytesConvertible {
var bytes:[UInt8] {
get {
var lines:[String] = []
lines.append("\(version) \(statusCode)")
for (key, value) in headerFields {
lines.append("\(key): \(value)")
}
return [UInt8](lines.joinWithSeparator("\r\n").utf8) + HTTPResponse.separator + body
}
set {
}
}
}
| 24.944444 | 96 | 0.601336 |
cce3dab4f172cd420d0d616ce3d969075e8eead6 | 6,353 | import Foundation
public extension Database {
/// Prepares an `UPDATE` statement.
///
/// - Parameters:
/// - tableName: The table to update.
/// - setExpr: A SQL expression to update rows (e.g. what follows the `SET` keyword)
/// - whereExpr: A SQL `WHERE` expression that selects which rows are updated (e.g. what follows the `WHERE` keyword)
/// - parameters: Parameters to bind to the statement.
/// - Returns: The prepared `Statement`.
/// - Throws:
/// An NSError with the sqlite error code and message.
public func prepareUpdate(_ tableName: String, setExpr:String, whereExpr:String? = nil, parameters: [Bindable?] = []) throws -> Statement {
var fragments = ["UPDATE", escapeIdentifier(tableName), "SET", setExpr]
if whereExpr != nil {
fragments.append("WHERE")
fragments.append(whereExpr!)
}
let statement = try prepareStatement(fragments.joined(separator: " "))
if parameters.count > 0 {
try statement.bind(parameters)
}
return statement
}
/// Updates table rows using a dynamic SQL expression. This is useful when you would like to use SQL functions or
/// operators to update the values of particular rows.
///
/// - Parameters:
/// - tableName: The table to update.
/// - setExpr: A SQL expression to update rows (e.g. what follows the `SET` keyword)
/// - whereExpr: A SQL `WHERE` expression that selects which rows are updated (e.g. what follows the `WHERE` keyword)
/// - parameters: Parameters to bind to the statement.
/// - Returns: The number of rows updated.
/// - Throws:
/// An NSError with the sqlite error code and message.
@discardableResult
public func update(_ tableName: String, setExpr:String, whereExpr:String? = nil, parameters: [Bindable?] = []) throws -> Int {
let statement = try prepareUpdate(tableName,
setExpr:setExpr,
whereExpr:whereExpr,
parameters:parameters)
try statement.execute()
return self.numberOfChangedRows
}
/// Prepares an `UPDATE` statement to update the given columns to specific values. The returned `Statement` will
/// have one parameter for each column, in the same order.
///
/// - Parameters:
/// - tableName: The name of the table to update.
/// - columns: The columns to update.
/// - whereExpr: A SQL expression to select which rows to update. If `nil`, all rows are updated.
/// - Returns: The prepared UPDATE statement.
/// - Throws:
/// An NSError with the sqlite error code and message.
public func prepareUpdate(_ tableName: String,
columns: [String],
whereExpr: String? = nil) throws -> Statement {
let columnsToSet = columns.map { escapeIdentifier($0) + " = ?" }.joined(separator: ", ")
return try prepareUpdate(tableName, setExpr:columnsToSet, whereExpr:whereExpr)
}
/// Updates table rows with the given values. This is a helper for executing an
/// `UPDATE ... SET ... WHERE` statement when all updated values are provided.
///
/// - Parameters:
/// - tableName: The name of the table to update.
/// - columns: The columns to update.
/// - values: The column values.
/// - whereExpr: A WHERE clause to select which rows to update. If nil, all rows are updated.
/// - parameters: Parameters to the WHERE clause.
/// - Returns: The number of rows updated.
/// - Throws:
/// An NSError with the sqlite error code and message.
@discardableResult
public func update(_ tableName: String,
columns: [String],
values: [Bindable?],
whereExpr: String? = nil,
parameters: [Bindable?] = []) throws -> Int {
let statement = try prepareUpdate(tableName, columns: columns, whereExpr: whereExpr)
try statement.bind(values + parameters)
try statement.execute()
return self.numberOfChangedRows
}
/// Updates table rows with the given values. This is a helper for executing an `UPDATE ... SET ... WHERE` statement
/// when all updated values are provided.
///
/// - Parameters:
/// - tableName: The name of the table to update.
/// - set: A dictionary of column names and values to set.
/// - whereExpr: A WHERE clause to select which rows to update. If nil, all rows are updated.
/// - parameters: Parameters to the WHERE clause.
/// - Returns: The number of rows updated.
/// - Throws:
/// An NSError with the sqlite error code and message.
@discardableResult
public func update(_ tableName: String,
set: [String:Bindable?],
whereExpr: String? = nil,
parameters: [Bindable?] = []) throws -> Int {
var columns = [String]()
var values = [Bindable?]()
for (columnName, value) in set {
columns.append(columnName)
values.append(value)
}
return try update(tableName, columns:columns, values:values, whereExpr:whereExpr, parameters:parameters)
}
/// Updates table rows given a set of row IDs.
///
/// - Parameters:
/// - tableName: The name of the table to update.
/// - rowIds: The IDs of rows to update.
/// - values: A dictionary of column names and values to set on the rows.
/// - Returns: The number of rows updated.
/// - Throws:
/// An NSError with the sqlite error code and message.
@discardableResult
public func update(_ tableName: String,
rowIds: [RowId],
values: [String:Bindable?]) throws -> Int {
if rowIds.count == 0 {
return 0
}
let whereExpr = "_ROWID_ IN (" + rowIds.map { String($0) }.joined(separator: ",") + ")"
return try update(tableName, set:values, whereExpr:whereExpr)
}
}
| 43.813793 | 143 | 0.581143 |
b9f41a833a8a5521af1d9c4d2eb6433b1adb8eaa | 9,714 | //
// SecureEnclaveModule.swift
// SecureEnclaveSample
//
// Created by hanwe lee on 2021/11/24.
//
import Foundation
import Security
class SecureEnclaveModule {
// MARK: internal func
func createAccessControl(accessibility: SecureEnclaveModule.Accessibility, policy: SecureEnclaveModule.AuthenticationPolicy) -> Result<SecAccessControl, Error> {
let policy: SecAccessControlCreateFlags = SecAccessControlCreateFlags(rawValue: policy.rawValue)
var error: Unmanaged<CFError>?
guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue as CFTypeRef, SecAccessControlCreateFlags(rawValue: CFOptionFlags(policy.rawValue)), &error) else {
if let error = error?.takeUnretainedValue() {
return .failure(error)
}
return .failure(SecureEnclaveModuleError.unexpected)
}
return .success(accessControl)
}
// MARK: private func
}
extension SecureEnclaveModule {
enum Accessibility {
var rawValue: String {
switch self {
case .whenUnlocked:
return String(kSecAttrAccessibleWhenUnlocked)
case .afterFirstUnlock:
return String(kSecAttrAccessibleAfterFirstUnlock)
#if !targetEnvironment(macCatalyst)
case .always:
return String(kSecAttrAccessibleAlways)
#endif
case .whenPasscodeSetThisDeviceOnly:
if #available(OSX 10.10, *) {
return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
} else {
fatalError("'Accessibility.WhenPasscodeSetThisDeviceOnly' is not available on this version of OS.")
}
case .whenUnlockedThisDeviceOnly:
return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .afterFirstUnlockThisDeviceOnly:
return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
#if !targetEnvironment(macCatalyst)
case .alwaysThisDeviceOnly:
return String(kSecAttrAccessibleAlwaysThisDeviceOnly)
#endif
}
}
/**
Item data can only be accessed
while the device is unlocked. This is recommended for items that only
need be accesible while the application is in the foreground. Items
with this attribute will migrate to a new device when using encrypted
backups.
*/
case whenUnlocked
/**
Item data can only be
accessed once the device has been unlocked after a restart. This is
recommended for items that need to be accesible by background
applications. Items with this attribute will migrate to a new device
when using encrypted backups.
*/
case afterFirstUnlock
/**
Item data can always be accessed
regardless of the lock state of the device. This is not recommended
for anything except system use. Items with this attribute will migrate
to a new device when using encrypted backups.
*/
@available(macCatalyst, unavailable)
case always
/**
Item data can
only be accessed while the device is unlocked. This class is only
available if a passcode is set on the device. This is recommended for
items that only need to be accessible while the application is in the
foreground. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device, these items
will be missing. No items can be stored in this class on devices
without a passcode. Disabling the device passcode will cause all
items in this class to be deleted.
*/
@available(iOS 8.0, OSX 10.10, *)
case whenPasscodeSetThisDeviceOnly
/**
Item data can only
be accessed while the device is unlocked. This is recommended for items
that only need be accesible while the application is in the foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case whenUnlockedThisDeviceOnly
/**
Item data can
only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device these items will
be missing.
*/
case afterFirstUnlockThisDeviceOnly
/**
Item data can always
be accessed regardless of the lock state of the device. This option
is not recommended for anything except system use. Items with this
attribute will never migrate to a new device, so after a backup is
restored to a new device, these items will be missing.
*/
@available(macCatalyst, unavailable)
case alwaysThisDeviceOnly
}
struct AuthenticationPolicy: OptionSet {
/**
User presence policy using Touch ID or Passcode. Touch ID does not
have to be available or enrolled. Item is still accessible by Touch ID
even if fingers are added or removed.
*/
@available(iOS 8.0, OSX 10.10, watchOS 2.0, tvOS 8.0, *)
public static let userPresence = AuthenticationPolicy(rawValue: 1 << 0)
/**
Constraint: Touch ID (any finger) or Face ID. Touch ID or Face ID must be available. With Touch ID
at least one finger must be enrolled. With Face ID user has to be enrolled. Item is still accessible by Touch ID even
if fingers are added or removed. Item is still accessible by Face ID if user is re-enrolled.
*/
@available(iOS 11.3, OSX 10.13.4, watchOS 4.3, tvOS 11.3, *)
public static let biometryAny = AuthenticationPolicy(rawValue: 1 << 1)
/**
Deprecated, please use biometryAny instead.
*/
@available(iOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryAny")
@available(OSX, introduced: 10.12.1, deprecated: 10.13.4, renamed: "biometryAny")
@available(watchOS, introduced: 2.0, deprecated: 4.3, renamed: "biometryAny")
@available(tvOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryAny")
public static let touchIDAny = AuthenticationPolicy(rawValue: 1 << 1)
/**
Constraint: Touch ID from the set of currently enrolled fingers. Touch ID must be available and at least one finger must
be enrolled. When fingers are added or removed, the item is invalidated. When Face ID is re-enrolled this item is invalidated.
*/
@available(iOS 11.3, OSX 10.13, watchOS 4.3, tvOS 11.3, *)
public static let biometryCurrentSet = AuthenticationPolicy(rawValue: 1 << 3)
/**
Deprecated, please use biometryCurrentSet instead.
*/
@available(iOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryCurrentSet")
@available(OSX, introduced: 10.12.1, deprecated: 10.13.4, renamed: "biometryCurrentSet")
@available(watchOS, introduced: 2.0, deprecated: 4.3, renamed: "biometryCurrentSet")
@available(tvOS, introduced: 9.0, deprecated: 11.3, renamed: "biometryCurrentSet")
public static let touchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3)
/**
Constraint: Device passcode
*/
@available(iOS 9.0, OSX 10.11, watchOS 2.0, tvOS 9.0, *)
public static let devicePasscode = AuthenticationPolicy(rawValue: 1 << 4)
/**
Constraint: Watch
*/
@available(iOS, unavailable)
@available(OSX 10.15, *)
@available(watchOS, unavailable)
@available(tvOS, unavailable)
public static let watch = AuthenticationPolicy(rawValue: 1 << 5)
/**
Constraint logic operation: when using more than one constraint,
at least one of them must be satisfied.
*/
@available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *)
public static let or = AuthenticationPolicy(rawValue: 1 << 14)
/**
Constraint logic operation: when using more than one constraint,
all must be satisfied.
*/
@available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *)
public static let and = AuthenticationPolicy(rawValue: 1 << 15)
/**
Create access control for private key operations (i.e. sign operation)
*/
@available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *)
public static let privateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30)
/**
Security: Application provided password for data encryption key generation.
This is not a constraint but additional item encryption mechanism.
*/
@available(iOS 9.0, OSX 10.12.1, watchOS 2.0, tvOS 9.0, *)
public static let applicationPassword = AuthenticationPolicy(rawValue: 1 << 31)
#if swift(>=2.3)
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
#else
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
#endif
}
enum SecureEnclaveModuleError: Int, Error {
case unexpected = -99999
}
}
| 41.690987 | 209 | 0.637739 |
21b01683b54bcfef24aaf4f162d7003f17e9e843 | 226 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a
protocol c : A { }
func a<T, A : c
protocol A : A
| 25.111111 | 87 | 0.725664 |
03ab269df8c9d260a1fcfb13788a3945ccea7505 | 4,227 | //
// HomeGameController.swift
// Tomatos
//
// Created by Admin on 9/30/20.
//
import UIKit
import JXFoundation
private let reuseIdentifierItem = "reuseIdentifierItem"
private let reuseIdentifierHeader = "reuseIdentifierHeader"
private let reuseIdentifierFooter = "reuseIdentifierFooter"
class HomeGameController: UIViewController {
//collectionView
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout.init()
layout.sectionInset = UIEdgeInsets.init(top: 12, left: 0, bottom: 12, right: 0)
layout.minimumLineSpacing = 12
layout.minimumInteritemSpacing = 12
let width = (kScreenWidth - 84 - 12 - 12) / 2
layout.itemSize = CGSize(width: width, height: width)
// layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
// layout.estimatedItemSize = CGSize(width: width, height: width)
// layout.headerReferenceSize = CGSize(width: self.view.bounds.width, height: 48)
// layout.footerReferenceSize = CGSize(width: self.view.bounds.width, height: 62)
// layout.headerReferenceSize = UICollectionViewFlowLayoutAutomaticSize
// layout.footerReferenceSize = UICollectionViewFlowLayoutAutomaticSize
let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.clear
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "LiveHeaderReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: reuseIdentifierHeader)
collectionView.register(UINib(nibName: "HomeCommonFooterReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: reuseIdentifierFooter)
collectionView.register(UINib(nibName: "GameItemViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifierItem)
return collectionView
}()
//data array
var dataArray = [Any]()
/// 一级列表选中的行
var selectRow = 0
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.frame = self.view.bounds
self.collectionView.frame = CGRect(x: 0, y: 0, width: kScreenWidth - 84 - 12, height: kScreenHeight - (kNavStatusHeight + 10) - 44)
self.view.addSubview(self.collectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - UICollectionViewDataSource & UICollectionViewDelegate
extension HomeGameController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// if self.dataArray.count > 0 {
// let entityTwo = self.dataArray[self.selectRow]
// let entityThree = entityTwo.list[section]
// return entityThree.list.count
// }
return 6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierItem, for: indexPath) as! GameItemViewCell
// let entityOne = self.dataArray[self.selectRow]
// let entityTwo = entityOne.list[indexPath.section]
// let entityThree = entityTwo.list[indexPath.item]
//
// cell.titleView.text = entityThree.title
// cell.statusView.isHidden = true
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// let entityOne = self.dataArray[self.selectRow]
// let entityTwo = entityOne.list[indexPath.section]
// let entityThree = entityTwo.list[indexPath.item]
//
// let v = JXNoticeView.init(text: entityThree.desc ?? "")
// v.show()
}
}
| 41.851485 | 207 | 0.702153 |
640a99533c693cbdbcf4d31b17f7a92d8b0edf70 | 538 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{{class a{class B<T where g:a{class b<f{class d:b class a{class a{{}func a{class a{class where{func a{class n{{}class a{let a{{func f{enum S{class a{func f{let a{{func f{{}let a{let:{func f{class a{class n{struct B{struct S{class d{class B{let a{struct d{{}func a{func a{let a{struct B{func a{struct S{let a{{let a{{}let a
| 67.25 | 322 | 0.717472 |
3341073f22b8338b68f00503d39705a266b0756e | 779 | // Copyright © 2020, Fueled Digital Media, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
public protocol OptionalProtocol {
associatedtype Wrapped
var wrapped: Wrapped? { get }
}
extension Optional: OptionalProtocol {
public var wrapped: Wrapped? {
self
}
}
| 29.961538 | 75 | 0.745828 |
e8c800a289867cdcddfbadb6c9aa3e6a47a042be | 1,524 | import Kitura
import MongoSwift
import NIO
/// A Codable type that matches the data in our home.kittens collection.
struct Kitten: Codable {
var name: String
var color: String
}
// Create a single EventLoopGroup for Kitura and the MongoClient to share.
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4)
let mongoClient = try MongoClient(using: eventLoopGroup)
defer {
mongoClient.syncShutdown()
cleanupMongoSwift()
try? eventLoopGroup.syncShutdownGracefully()
}
let router: Router = {
let router = Router()
/// A single collection with type `Kitten`. This allows us to directly retrieve instances of
/// `Kitten` from the collection. `MongoCollection` is safe to share across threads.
let collection = mongoClient.db("home").collection("kittens", withType: Kitten.self)
router.get("kittens") { _, response, next -> Void in
let res = collection.find().flatMap { cursor in
cursor.toArray()
}
res.whenSuccess { results in
response.send(results)
next()
}
res.whenFailure { error in
response.error = error
response.send("Error: \(error)")
next()
}
}
return router
}()
let server = Kitura.addHTTPServer(onPort: 8080, with: router)
// Use the EventLoopGroup created above for the Kitura server. To call this method we must build with
// `export KITURA_NIO=1 && swift build`.
try server.setEventLoopGroup(eventLoopGroup)
Kitura.run()
| 28.754717 | 101 | 0.677165 |
09b8aa1f7f592375882626865d89d31455e62b06 | 575 |
import UIKit
class PersonsTransformer {
let personsCollection: PersonsCollection
init(personsCollection: PersonsCollection) {
self.personsCollection = personsCollection
}
func getPersonsViewModel() -> [PersonViewModel] {
var personsViewModelSet: Set<PersonViewModel> = Set()
for person in self.personsCollection.entries {
let personViewModel = PersonViewModel(person: person)
personsViewModelSet.insert(personViewModel!)
}
return Array(personsViewModelSet)
}
}
| 26.136364 | 65 | 0.664348 |
26094c5769f76251063e41ef77f73473d78128f6 | 4,301 | import Foundation
import SourceKittenFramework
public struct RedundantTypeAnnotationRule: OptInRule, SubstitutionCorrectableRule,
ConfigurationProviderRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "redundant_type_annotation",
name: "Redundant Type Annotation",
description: "Variables should not have redundant type annotation",
kind: .idiomatic,
nonTriggeringExamples: [
"var url = URL()",
"var url: CustomStringConvertible = URL()",
"@IBInspectable var color: UIColor = UIColor.white"
],
triggeringExamples: [
"var url↓:URL=URL()",
"var url↓:URL = URL(string: \"\")",
"var url↓: URL = URL()",
"let url↓: URL = URL()",
"lazy var url↓: URL = URL()",
"let alphanumerics↓: CharacterSet = CharacterSet.alphanumerics",
"""
class ViewController: UIViewController {
func someMethod() {
let myVar↓: Int = Int(5)
}
}
"""
],
corrections: [
"var url↓: URL = URL()": "var url = URL()",
"let url↓: URL = URL()": "let url = URL()",
"let alphanumerics↓: CharacterSet = CharacterSet.alphanumerics":
"let alphanumerics = CharacterSet.alphanumerics",
"""
class ViewController: UIViewController {
func someMethod() {
let myVar↓: Int = Int(5)
}
}
""":
"""
class ViewController: UIViewController {
func someMethod() {
let myVar = Int(5)
}
}
"""
]
)
public func validate(file: SwiftLintFile) -> [StyleViolation] {
return violationRanges(in: file).map { range in
StyleViolation(
ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location)
)
}
}
public func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String) {
return (violationRange, "")
}
public func violationRanges(in file: SwiftLintFile) -> [NSRange] {
let typeAnnotationPattern = ":\\s?\\w+"
let pattern = "(var|let)\\s?\\w+\(typeAnnotationPattern)\\s?=\\s?\\w+(\\(|.)"
let foundRanges = file.match(pattern: pattern, with: [.keyword, .identifier, .typeidentifier, .identifier])
return foundRanges
.filter { !isFalsePositive(in: file, range: $0) && !isIBInspectable(range: $0, file: file) }
.compactMap {
file.match(pattern: typeAnnotationPattern,
excludingSyntaxKinds: SyntaxKind.commentAndStringKinds, range: $0).first
}
}
private func isFalsePositive(in file: SwiftLintFile, range: NSRange) -> Bool {
let substring = file.contents.bridge().substring(with: range)
let components = substring.components(separatedBy: "=")
let charactersToTrimFromRhs = CharacterSet(charactersIn: ".(").union(.whitespaces)
guard
components.count == 2,
let lhsTypeName = components[0].components(separatedBy: ":").last?.trimmingCharacters(in: .whitespaces)
else {
return true
}
let rhsTypeName = components[1].trimmingCharacters(in: charactersToTrimFromRhs)
return lhsTypeName != rhsTypeName
}
private func isIBInspectable(range: NSRange, file: SwiftLintFile) -> Bool {
guard let byteRange = file.contents.bridge().NSRangeToByteRange(start: range.location, length: range.length),
let dict = file.structureDictionary.structures(forByteOffset: byteRange.location).last,
let kind = dict.declarationKind,
SwiftDeclarationKind.variableKinds.contains(kind) else {
return false
}
return dict.enclosedSwiftAttributes.contains(.ibinspectable)
}
}
| 38.747748 | 117 | 0.574285 |
3393ddba6924e710562cc63b3c29cafaa6baf7be | 526 | //
// BodyLabel.swift
// Codeforces Watcher
//
// Created by Den Matyash on 4/13/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
class BodyLabel: UILabel {
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
textColor = Palette.gray
font = Font.textBody
}
}
| 18.785714 | 52 | 0.61597 |
def6ae905a99c4722a394429afa5dcc65a3e8502 | 8,531 |
enum CSVTableParserEntry {
case Header
case HeaderExit
case Row
case RowExit
case Column
case ColumnQuoted
}
// Unicode data.
//
// The file format is like this:
//
// * The first row includes the serial number only. It is a sequencial number
// starting from 0 that helps to make the rows unique for updating and deleting.
//
// * The second row is the header row that helps to give a label to each column.
// The very first column is already labeled by default with "id".
//
// * From the third row onwards we find the actual data rows. They all start
// with the id column.
//
// * All rows should end with just the newline character(\n or 10).
//
// * All rows should include the same number of columns.
//
// * Data is in general represented in string format only. It simplifies it
// a lot and may match the use-case of users when they already have strings to
// compare the data with.
//
// * The column data follows the convention specified on this Wikipedia entry:
// https://en.wikipedia.org/wiki/Comma-separated_values
// Where columns can start with a double quote which can include within it:
//
// ** A data comma. E.g. "Hey, ho"
//
// ** A data newline character. E.g. "So \n it begins."
//
// ** And even a data double quote if it is escaped with another double
// quote. E.g. "Let's "" go"
//
public struct CSVTable {
var _path: String
public var serialId = 0
var stream = ByteStream()
var entryParser = CSVTableParserEntry.Header
var _header = [String]()
var columnGroup = CSVTableParserEntry.Header
var recordExit = CSVTableParserEntry.HeaderExit
var columnValue = ""
var _rows = [[String]]()
var _row = [String]()
var unescapedColumnValue = ""
public init(path: String) throws {
_path = path
try load()
}
mutating public func load() throws {
var f = try File(path: _path)
defer { f.close() }
stream.bytes = try f.readAllBytes()
if stream.eatWhileDigit() {
serialId = Int(stream.collectTokenString()!)!
if stream.eatOne(10) { // Newline
entryParser = .Column
_header = []
columnGroup = .Header
recordExit = .HeaderExit
while !stream.isEol {
try next()
}
// Be nice and check for a last row without a trailing new line
// following it. Sometimes when manually editing a file, the last line
// could lose its new line.
if !_row.isEmpty {
try inRowExit()
}
} else {
throw CSVTableError.NewLine
}
} else {
throw CSVTableError.SerialId
}
}
mutating func next() throws {
switch entryParser {
case .Header:
try inHeader()
case .HeaderExit:
try inHeaderExit()
case .Row:
try inRow()
case .RowExit:
try inRowExit()
case .Column:
try inColumn()
case .ColumnQuoted:
try inColumnQuoted()
}
}
mutating func inHeader() throws {
_header.append(columnValue)
entryParser = .Column
}
mutating func inHeaderExit() throws {
if header.isEmpty {
throw CSVTableError.Header
}
entryParser = .Column
columnGroup = .Row
recordExit = .RowExit
_row = []
}
mutating func inRow() throws {
_row.append(columnValue)
entryParser = .Column
}
mutating func inRowExit() throws {
if _row.count != _header.count {
throw CSVTableError.Row
}
entryParser = .Column
_rows.append(_row)
_row = []
}
func matchCommaOrNewLine(c: UInt8) -> Bool {
return c == 44 || c == 10
}
mutating func inColumn() throws {
stream.startIndex = stream.currentIndex
if stream.eatDoubleQuote() {
unescapedColumnValue = ""
entryParser = .ColumnQuoted
stream.startIndex = stream.currentIndex
} else if stream.eatComma() {
columnValue = ""
entryParser = columnGroup
} else if stream.eatUntil(matchCommaOrNewLine) {
columnValue = stream.collectTokenString()!
stream.eatComma()
entryParser = columnGroup
} else if stream.eatOne(10) {
entryParser = recordExit
} else {
throw CSVTableError.Unreachable
}
}
mutating func inColumnQuoted() throws {
if stream.skipTo(34) >= 0 { // "
if let s = stream.collectTokenString() {
unescapedColumnValue += s
}
stream.eatDoubleQuote()
stream.startIndex = stream.currentIndex
if !stream.eatDoubleQuote() { // Ends if not an escaped quote sequence: ""
if let s = stream.collectTokenString() {
unescapedColumnValue += s
}
columnValue = unescapedColumnValue
stream.eatComma()
entryParser = columnGroup
}
} else {
throw CSVTableError.Column
}
}
public var path: String { return _path }
public var header: [String] { return _header }
public var rows: [[String]] { return _rows }
// Don't include the id, since it will be automatically generated based on the
// next number on the sequence.
mutating public func insert(row: [String]) throws -> Int {
if row.count + 1 != header.count {
throw CSVTableError.Insert
}
var a = [String]()
let sid = serialId
a.append("\(sid)")
for s in row {
a.append(s)
}
_rows.append(a)
serialId += 1
return sid
}
// Alias for insert.
mutating public func append(row: [String]) throws -> Int {
return try insert(row)
}
// This will insert it if it does not exist, and it will keep whatever index
// id it was called with. This can help with data migration. The serialId
// can be adjusted accordingly afterwards.
mutating public func update(index: String, row: [String]) throws {
if row.count + 1 != header.count {
throw CSVTableError.Update
}
let n = findIndex(index)
if n >= 0 {
for i in 0..<row.count {
_rows[n][i + 1] = row[i]
}
} else {
var a = [String]()
a.append(index)
for s in row {
a.append(s)
}
_rows.append(a)
}
}
func findIndex(index: String) -> Int {
for i in 0..<_rows.count {
if _rows[i][0] == index {
return i
}
}
return -1
}
// If the record pointed at by index does not exist, simply ignore it.
mutating public func delete(index: String) {
let n = findIndex(index)
if n >= 0 {
_rows.removeAtIndex(n)
}
}
mutating public func updateColumn(index: String, columnIndex: Int,
value: String) {
let n = findIndex(index)
if n >= 0 {
_rows[n][columnIndex] = value
}
}
mutating public func select(index: String) -> [String]? {
let n = findIndex(index)
if n >= 0 {
return _rows[n]
}
return nil
}
public var data: String {
var s = "\(serialId)\n"
var comma = false
for c in _header {
if comma { s += "," }
s += CSVTable.escape(c)
comma = true
}
s += "\n"
if !_rows.isEmpty {
for row in _rows {
var comma = false
for c in row {
if comma { s += "," }
s += CSVTable.escape(c)
comma = true
}
s += "\n"
}
s += "\n"
}
return s
}
public func save() throws {
try IO.write(path, string: data)
}
// This makes sure the data is escaped for double quote, comma and new line.
public static func escape(string: String) -> String {
let len = string.utf16.count
var i = 0
while i < len {
let c = string.utf16.codeUnitAt(i)
if c == 34 || c == 44 || c == 10 { // " , newline
i += 1
var s = "\""
s += string.utf16.substring(0, endIndex: i) ?? ""
if c == 34 {
s += "\""
}
var si = i
while i < len {
if string.utf16.codeUnitAt(i) == 34 {
s += string.utf16.substring(si, endIndex: i + 1) ?? ""
s += "\""
si = i + 1
}
i += 1
}
s += string.utf16.substring(si, endIndex: i) ?? ""
s += "\""
return s
}
i += 1
}
return string
}
public static func create(path: String, header: [String]) throws -> CSVTable {
var s = "0\nid"
for c in header {
s += ","
s += escape(c)
}
s += "\n"
try IO.write(path, string: s)
return try CSVTable(path: path)
}
}
enum CSVTableError: ErrorType {
case SerialId
case NewLine
case Header
case Row
case Column
case Insert
case Update
case Unreachable
}
| 24.444126 | 80 | 0.589614 |
039fc060cbc157a39361ead6ce5e97cbf2011fcb | 3,593 | //
// ScimV2CreateUser.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Defines the creation of a SCIM user. */
public class ScimV2CreateUser: Codable {
/** The list of supported schemas. */
public var schemas: [String]?
/** Indicates whether the user's administrative status is active. */
public var active: Bool?
/** The user's Genesys Cloud email address. Must be unique. */
public var userName: String?
/** The display name of the user. */
public var displayName: String?
/** The new password for the Genesys Cloud user. Does not return an existing password. When creating a user, if a password is not supplied, then a password will be randomly generated that is 40 characters in length and contains five characters from each of the password policy groups. */
public var password: String?
/** The user's title. */
public var title: String?
/** The list of the user's phone numbers. */
public var phoneNumbers: [ScimPhoneNumber]?
/** The list of the user's email addresses. */
public var emails: [ScimEmail]?
/** The external ID of the user. Set by the provisioning client. \"caseExact\" is set to \"true\". \"mutability\" is set to \"readWrite\". */
public var externalId: String?
/** The list of groups that the user is a member of. */
public var groups: [ScimV2GroupReference]?
/** The list of roles assigned to the user. */
public var roles: [ScimUserRole]?
/** The URI of the schema for the enterprise user. */
public var urnietfparamsscimschemasextensionenterprise20User: ScimV2EnterpriseUser?
/** The URI of the schema for the Genesys Cloud user. */
public var urnietfparamsscimschemasextensiongenesyspurecloud20User: ScimUserExtensions?
public init(schemas: [String]?, active: Bool?, userName: String?, displayName: String?, password: String?, title: String?, phoneNumbers: [ScimPhoneNumber]?, emails: [ScimEmail]?, externalId: String?, groups: [ScimV2GroupReference]?, roles: [ScimUserRole]?, urnietfparamsscimschemasextensionenterprise20User: ScimV2EnterpriseUser?, urnietfparamsscimschemasextensiongenesyspurecloud20User: ScimUserExtensions?) {
self.schemas = schemas
self.active = active
self.userName = userName
self.displayName = displayName
self.password = password
self.title = title
self.phoneNumbers = phoneNumbers
self.emails = emails
self.externalId = externalId
self.groups = groups
self.roles = roles
self.urnietfparamsscimschemasextensionenterprise20User = urnietfparamsscimschemasextensionenterprise20User
self.urnietfparamsscimschemasextensiongenesyspurecloud20User = urnietfparamsscimschemasextensiongenesyspurecloud20User
}
public enum CodingKeys: String, CodingKey {
case schemas
case active
case userName
case displayName
case password
case title
case phoneNumbers
case emails
case externalId
case groups
case roles
case urnietfparamsscimschemasextensionenterprise20User = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
case urnietfparamsscimschemasextensiongenesyspurecloud20User = "urn:ietf:params:scim:schemas:extension:genesys:purecloud:2.0:User"
}
}
| 39.483516 | 414 | 0.686335 |
e8df13871df2f2b919acf0f2beca76db6f26fdca | 684 | //
// main.swift
// Lab2_Junghwan Park_c0661374
//
// Created by macadmin on 2016-05-20.
// Copyright © 2016 Lambton College. All rights reserved.
//
import Foundation
class Program {
func DoMain() {
print(" -------------------------")
let square1 = Square()
let square2 = Square(length : 7)
let rect1 = Rectangle()
let rect2 = Rectangle(length : 10, width: 5)
print("squre1 : \(square1.description())")
print("squre1 : \(square2.description())")
print("rect1 : \(rect1.description())")
print("rect2 : \(rect2.description())")
}
}
Program().DoMain() | 20.727273 | 58 | 0.524854 |
213277f6f9c1cc625ac172fa96f04ab6b72f046b | 468 | //
// Reward.swift
// Rewards
//
// Created by Anthonio Ez on 07/06/2018.
// Copyright © 2018 Nairalance. All rights reserved.
//
import UIKit
class Reward: NSObject
{
public static let PAGE_SIZE = 40;
public static let EVENT_LIST = "rewards_list";
public static let EVENT_ACTIONS = "rewards_actions";
public static let EVENT_REQUEST = "rewards_request";
public static let EVENT_RESPONSE = "rewards_response";
}
| 24.631579 | 61 | 0.66453 |
0e7a03b572125ffa4f2bd844658e1280cc6c1e0d | 1,714 | //
// MPNowPlayingInfoCenter+AudioItem.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 27/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import MediaPlayer
extension MPNowPlayingInfoCenter {
/// Updates the MPNowPlayingInfoCenter with the latest information on a `AudioItem`.
///
/// - Parameters:
/// - item: The item that is currently played.
/// - duration: The item's duration.
/// - progression: The current progression.
/// - playbackRate: The current playback rate.
func ap_update(with item: AudioItem, duration: TimeInterval?, progression: TimeInterval?, playbackRate: Float) {
var info = [String: Any]()
if let title = item.title {
info[MPMediaItemPropertyTitle] = title
}
if let artist = item.artist {
info[MPMediaItemPropertyArtist] = artist
}
if let album = item.album {
info[MPMediaItemPropertyAlbumTitle] = album
}
// if let trackCount = item.trackCount {
// info[MPMediaItemPropertyAlbumTrackCount] = trackCount
// }
// if let trackNumber = item.trackNumber {
// info[MPMediaItemPropertyAlbumTrackNumber] = trackNumber
// }
if let artwork = item.artwork {
info[MPMediaItemPropertyArtwork] = artwork
}
if let duration = duration {
info[MPMediaItemPropertyPlaybackDuration] = duration
}
if let progression = progression {
info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = progression
}
info[MPNowPlayingInfoPropertyPlaybackRate] = playbackRate
nowPlayingInfo = info
}
}
| 34.28 | 116 | 0.630105 |
26fff3367d0cdb825eb0a362b3d8cf21f61ee3d7 | 894 | //
// TransactionManager.swift
// Chat Bot
//
// Created by Adarsh on 05/01/19.
// Copyright © 2019 Pallav Trivedi. All rights reserved.
//
import Foundation
class TransactionManager: NSObject {
static let sharedInstance: TransactionManager = {
let instance = TransactionManager()
// setup code
return instance
}()
func getListOfCarDetailsWithBuyerDetails(details: BuyerDetails, completion : @ escaping (_ result: [ListedCarDetails], _ error: Error?) -> Void) {
NetworkManager.sharedInstance.getListOfCarAvailableWithDetails(withBuyerDetails: details, completion: completion);
}
func postSellerDetails(details: SellerDetails, completion : @ escaping (_ error: Error?) -> Void) {
NetworkManager.sharedInstance.postSellerDetails(witDetails: details, completion: completion);
}
}
| 27.090909 | 151 | 0.681208 |
ab91f62193caffff2e8247a0746d2c216250eb4d | 890 | import Foundation
class YearField: Field, FieldCheckerInterface {
func isSatisfiedBy(_ date: Date, value: String) -> Bool {
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: date)
guard let year = components.year else { return false }
return self.isSatisfied(String(format: "%d", year), value: value)
}
func increment(_ date: Date, toMatchValue: String) -> Date {
if let nextDate = date.nextDate(matchingUnit: .year, value: toMatchValue) {
return nextDate
}
let calendar = Calendar.current
let midnightComponents = calendar.dateComponents([.day, .month, .year], from: date)
var components = DateComponents()
components.year = 1
return calendar.date(byAdding: components, to: calendar.date(from: midnightComponents)!)!
}
func validate(_ value: String) -> Bool {
return StringValidator.isNumber(value)
}
}
| 27.8125 | 91 | 0.719101 |
0ed8d649ec7cca4113691d07fd3037b4f4d73fd5 | 1,947 | //
// WeatherManager.swift
// Sights
//
// Created by Lina Alkhodair on 02/04/2020.
// Copyright © 2020 Lina Alkhodair. All rights reserved.
//
import Foundation
protocol WeatherManagerDelegate {
func didUpdateWeather(_ weatherManager: WeatherManager, weather: WeatherModel)
func didFailWithError(error: Error)
}
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=e72ca729af228beabd5d20e3b7749713&units=metric"
var delegate: WeatherManagerDelegate?
func fetchWeather(cityName: String) {
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(with: urlString)
}
func performRequest(with urlString: String) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}
if let safeData = data {
if let weather = self.parseJSON(safeData) {
self.delegate?.didUpdateWeather(self, weather: weather)
}
}
}
task.resume()
}
}
func parseJSON(_ weatherData: Data) -> WeatherModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
let id = decodedData.weather[0].id
let temp = decodedData.main.temp
let name = decodedData.name
let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
return weather
} catch {
delegate?.didFailWithError(error: error)
return nil
}
}
}
| 29.5 | 122 | 0.57319 |
26a442c733ca9f9a77047b776722ff2f1ec8e7d0 | 39,369 | //
// MatrixTests.swift
// LASwift
//
// Created by Alexander Taraymovich on 28/02/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Darwin
import Quick
import Nimble
import LASwift
class MatrixSpec: QuickSpec {
override func spec() {
describe("Matrix construction tests") {
let count = 10
let m1 = ones(count, count+1)
it("ones matrix has correct dimensions") {
expect(m1.rows) == count
expect(m1.cols) == count+1
}
it("ones matrix all ones") {
for i in 0..<count {
for j in 0..<count+1 {
expect(m1[i, j]).to(beCloseTo(1.0))
}
}
}
let m2 = zeros(count, count+1)
it("zeros matrix has correct dimensions") {
expect(m2.rows) == count
expect(m2.cols) == count+1
}
it("zeros matrix all zeros") {
for i in 0..<count {
for j in 0..<count+1 {
expect(m2[i, j]).to(beCloseTo(0.0))
}
}
}
let m3 = zeros(count, count+1)
it("zeros vectors are equal") {
expect(m3) == m2
}
it("zeros and ones vectors are not equal") {
expect(m2) != m1
}
let ones_like_m3 = ones(like: m3) // input is zeros(count, count+1)
it("ones like are equal") {
expect(ones_like_m3) == m1 // test against ones(count, count+1)
}
let zeros_like_m1 = zeros(like: m1) // input is ones(count, count+1)
it("zeros like are equal") {
expect(zeros_like_m1) == m3 // test against zeros(count, count+1)
}
let m4 = eye(count, count)
it("identity matrix has correct dimensions") {
expect(m4.rows) == count
expect(m4.cols) == count
}
it("identity matrix ones on diag") {
for i in 0..<count {
for j in 0..<count {
if i == j {
expect(m4[i, j]).to(beCloseTo(1.0))
} else {
expect(m4[i, j]).to(beCloseTo(0.0))
}
}
}
}
let v1 = [1.0, 2.0, 3.0, 4.0, 5.0]
let v2 = Matrix(v1)
let m5 = diag(v1)
let m6 = diag(v2)
let m7 = diag(v1.count + 2, v1.count, v2)
it("diag matrix has correct dimensions") {
expect(m5.rows) == v1.count
expect(m5.cols) == v1.count
expect(m6.rows) == v1.count
expect(m6.cols) == v1.count
expect(m7.rows) == v1.count + 2
expect(m7.cols) == v1.count
}
it("diag matrix correct") {
for i in 0..<v1.count {
for j in 0..<v1.count {
if i == j {
expect(m5[i, j]).to(beCloseTo(v1[i]))
expect(m6[i, j]).to(beCloseTo(v1[i]))
expect(m7[i, j]).to(beCloseTo(v1[i]))
} else {
expect(m5[i, j]).to(beCloseTo(0.0))
expect(m6[i, j]).to(beCloseTo(0.0))
expect(m7[i, j]).to(beCloseTo(0.0))
}
}
}
}
it("rand") {
let size = 100
let m8 = rand(size, size)
expect(m8.rows) == size
expect(m8.cols) == size
for i in 0..<size {
for j in 0..<size {
expect(m8[i, j]).to(beLessThan(1.0))
expect(m8[i, j]).to(beGreaterThanOrEqualTo(0.0))
}
}
}
it("randn") {
let m8 = randn(1000, 1000)
expect(m8.rows) == 1000
expect(m8.cols) == 1000
let m = mean(m8)
let s = std(m8)
_ = (0..<1000).map { (i) in
expect(m[i]).to(beCloseTo(0.0, within: 0.2))
expect(s[i]).to(beCloseTo(1.0, within: 0.2))
}
}
}
describe("Matrix arithmetic tests") {
it("addition") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0], [7.0, 8.0]])
let res = Matrix([[6.0, 8.0], [10.0, 12.0]])
expect(m1 + m2) == res
}
it("substraction") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0], [7.0, 8.0]])
let res = Matrix([[-4.0, -4.0], [-4.0, -4.0]])
expect(m1 - m2) == res
}
it("multiplication") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0], [7.0, 8.0]])
let res = Matrix([[5.0, 12.0], [21.0, 32.0]])
expect(m1 .* m2) == res
}
it("right division") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0], [7.0, 8.0]])
let res = Matrix([[1.0 / 5.0, 2.0 / 6.0], [3.0 / 7.0, 4.0 / 8.0]])
expect(m1 ./ m2) == res
}
it("left division") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0], [7.0, 8.0]])
let res = Matrix([[5.0 / 1.0, 6.0 / 2.0], [7.0 / 3.0, 8.0 / 4.0]])
expect(m1 ./. m2) == res
}
it("vector addition") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let v = [5.0, 6.0]
let res = Matrix([[6.0, 8.0], [8.0, 10.0]])
expect(m1 + v) == res
expect(v + m1) == res
}
it("vector substraction") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let v = [5.0, 6.0]
let res1 = Matrix([[-4.0, -4.0], [-2.0, -2.0]])
let res2 = Matrix([[4.0, 4.0], [2.0, 2.0]])
expect(m1 - v) == res1
expect(v - m1) == res2
}
it("vector multiplication") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let v = [5.0, 6.0]
let res = Matrix([[5.0, 12.0], [15.0, 24.0]])
expect(m1 .* v) == res
expect(v .* m1) == res
}
it("vector right division") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let v = [5.0, 6.0]
let res1 = Matrix([[1.0 / 5.0, 2.0 / 6.0], [3.0 / 5.0, 4.0 / 6.0]])
let res2 = Matrix([[5.0 / 1.0, 6.0 / 2.0], [5.0 / 3.0, 6.0 / 4.0]])
expect(m1 ./ v) == res1
expect(v ./ m1) == res2
}
it("vector left division") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let v = [5.0, 6.0]
let res1 = Matrix([[5.0 / 1.0, 6.0 / 2.0], [5.0 / 3.0, 6.0 / 4.0]])
let res2 = Matrix([[1.0 / 5.0, 2.0 / 6.0], [3.0 / 5.0, 4.0 / 6.0]])
expect(m1 ./. v) == res1
expect(v ./. m1) == res2
}
it("scalar addition") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let s = 5.0
let res = Matrix([[6.0, 7.0], [8.0, 9.0]])
expect(m1 + s) == res
expect(s + m1) == res
}
it("scalar substraction") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let s = 5.0
let res1 = Matrix([[-4.0, -3.0], [-2.0, -1.0]])
let res2 = Matrix([[4.0, 3.0], [2.0, 1.0]])
expect(m1 - s) == res1
expect(s - m1) == res2
}
it("scalar multiplication") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let s = 5.0
let res = Matrix([[5.0, 10.0], [15.0, 20.0]])
expect(m1 .* s) == res
expect(s .* m1) == res
}
it("scalar right division") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let s = 5.0
let res1 = Matrix([[1.0 / 5.0, 2.0 / 5.0], [3.0 / 5.0, 4.0 / 5.0]])
let res2 = Matrix([[5.0 / 1.0, 5.0 / 2.0], [5.0 / 3.0, 5.0 / 4.0]])
expect(m1 ./ s) == res1
expect(s ./ m1) == res2
}
it("scalar left division") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let s = 5.0
let res1 = Matrix([[5.0 / 1.0, 5.0 / 2.0], [5.0 / 3.0, 5.0 / 4.0]])
let res2 = Matrix([[1.0 / 5.0, 2.0 / 5.0], [3.0 / 5.0, 4.0 / 5.0]])
expect(m1 ./. s) == res1
expect(s ./. m1) == res2
}
it("negation") {
let m1 = Matrix([[1.0, -2.0], [-3.0, 4.0]])
let res = Matrix([[-1.0, 2.0], [3.0, -4.0]])
expect(-m1) == res
}
it("absolute") {
let m1 = Matrix([[1.0, -2.0], [-3.0, 4.0]])
let res = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(abs(m1)) == res
}
it("threshold") {
let m1 = Matrix([[1.0, -2.0], [-3.0, 4.0]])
let res = Matrix([[1.0, 0.0], [0.0, 4.0]])
expect(thr(m1, 0.0)) == res
}
}
describe("Matrix comparison") {
it("equal") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1 == m2) == true
}
it("not equal") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m2 = Matrix([[1.0, 4.0], [3.0, 2.0]])
expect(m1 != m2) == true
}
it("greater/less than") {
let m1 = Matrix([[11.0, 12.0], [13.0, 14.0]])
let m2 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1) > m2
expect(m2) < m1
}
it("greater/less than or equal") {
let m1 = Matrix([[11.0, 12.0], [13.0, 14.0]])
let m2 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let m3 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1) >= m2
expect(m2) <= m1
expect(m2) >= m3
expect(m2) <= m3
}
}
describe("Matrix subscript") {
it("[i,j]") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1[1, 1]) == 4.0
m1[1, 0] = 10.0
expect(m1[1, 0]) == 10.0
}
it("index") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1[3]) == 4.0
m1[2] = 10.0
expect(m1[2]) == 10.0
expect(m1[1, 0]) == 10.0
}
it("row") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1[row: 1]) == [3.0, 4.0]
m1[row: 0] = [10.0, 20.0]
expect(m1[row: 0]) == [10.0, 20.0]
expect(m1[0, 0]) == 10.0
expect(m1[0, 1]) == 20.0
}
it("column") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
expect(m1[col: 1]) == [2.0, 4.0]
m1[col: 0] = [10.0, 30.0]
expect(m1[col: 0]) == [10.0, 30.0]
expect(m1[0, 0]) == 10.0
expect(m1[1, 0]) == 30.0
}
}
describe("Matrix range-based subscript") {
it("[i,j] -> Matrix") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
let m2 = Matrix([[10.0, 11.0],
[12.0, 13.0]])
expect(m1[0, 1].flat) == [2.0, 3.0, 5.0, 6.0, 8.0, 9.0]
m1[1, 0] = m2
expect(m1[1..<3, 0...1].flat) == [10.0, 11.0, 12.0, 13.0]
}
it("closed") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
let m2 = Matrix([[10.0, 11.0],
[12.0, 13.0]])
expect(m1[1...2, 0...1].flat) == [4.0, 5.0, 7.0, 8.0]
m1[0...1, 1...2] = m2
expect(m1.flat) == [1.0, 10.0, 11.0, 4.0, 12.0, 13.0, 7.0, 8.0, 9.0]
}
it("open") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
let m2 = Matrix([[10.0, 11.0],
[12.0, 13.0]])
expect(m1[1..<3, 0..<2].flat) == [4.0, 5.0, 7.0, 8.0]
m1[0..<2, 1..<3] = m2
expect(m1.flat) == [1.0, 10.0, 11.0, 4.0, 12.0, 13.0, 7.0, 8.0, 9.0]
}
it("partial") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
let m2 = Matrix([[10.0, 11.0],
[12.0, 13.0]])
expect(m1[1..., ..<2].flat) == [4.0, 5.0, 7.0, 8.0]
m1[1..., 1...] = m2
expect(m1.flat) == [1.0, 2.0, 3.0, 4.0, 10.0, 11.0, 7.0, 12.0, 13.0]
}
it("unbounded") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
let m2 = Matrix([[10.0, 11.0, 12.0]])
expect(m1[..., 2...2].flat) == [3.0, 6.0, 9.0]
m1[1...1, ...] = m2
expect(m1.flat) == [1.0, 2.0, 3.0, 10.0, 11.0, 12.0, 7.0, 8.0, 9.0]
}
}
describe("Matrix map/reduce") {
it("map") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[1.0, 4.0], [9.0, 16.0]])
expect(map(m1, { $0 * $0 })) == res
}
it("map vec") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[1.0, 4.0], [9.0, 16.0]])
expect(map(m1, square)) == res
}
it("reduce rows") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = [3.0, 7.0]
expect(reduce(m1, sum)) == res
expect(reduce(m1, sum, .Row)) == res
}
it("reduce cols") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = [4.0, 6.0]
expect(reduce(m1, sum, .Column)) == res
}
}
describe("Matrix power and exponential tests") {
it("power") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let p = 3.0
let res = Matrix([[1.0, 8.0], [27.0, 64.0]])
expect(m1 .^ p) == res
}
it("square") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[1.0, 4.0], [9.0, 16.0]])
expect(square(m1)) == res
expect(m1 .^ 2.0) == res
}
it("sqrt") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[sqrt(1.0), sqrt(2.0)], [sqrt(3.0), sqrt(4.0)]])
expect(sqrt(m1)) == res
expect(m1 .^ 0.5) == res
}
it("exp") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[exp(1.0), exp(2.0)], [exp(3.0), exp(4.0)]])
expect(exp(m1)) == res
}
it("log") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[log(1.0), log(2.0)], [log(3.0), log(4.0)]])
expect(log(m1)) == res
}
it("log10") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[log10(1.0), log10(2.0)], [log10(3.0), log10(4.0)]])
expect(log10(m1)) == res
}
it("log2") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[log2(1.0), log2(2.0)], [log2(3.0), log2(4.0)]])
expect(log2(m1)) == res
}
}
describe("Matrix trigonometric tests") {
it("sin") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[sin(1.0), sin(2.0)], [sin(3.0), sin(4.0)]])
expect(sin(m1)) == res
}
it("cos") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[cos(1.0), cos(2.0)], [cos(3.0), cos(4.0)]])
expect(cos(m1)) == res
}
it("tan") {
let m1 = Matrix([[1.0, 2.0], [3.0, 4.0]])
let res = Matrix([[tan(1.0), tan(2.0)], [tan(3.0), tan(4.0)]])
expect(tan(m1)) == res
}
}
describe("Matrix statistics tests") {
it("max") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [4.0, 3.0]
let res2 = [3.0, 4.0]
expect(max(m1)).to(beCloseTo(res1))
expect(max(m1, .Row)).to(beCloseTo(res1))
expect(max(m1, .Column)).to(beCloseTo(res2))
}
it("maxi") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [1, 0]
let res2 = [1, 0]
expect(maxi(m1)) == res1
expect(maxi(m1, .Row)) == res1
expect(maxi(m1, .Column)) == res2
}
it("min") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [1.0, 2.0]
let res2 = [1.0, 2.0]
expect(min(m1)).to(beCloseTo(res1))
expect(min(m1, .Row)).to(beCloseTo(res1))
expect(min(m1, .Column)).to(beCloseTo(res2))
}
it("mini") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [0, 1]
let res2 = [0, 1]
expect(mini(m1)) == res1
expect(mini(m1, .Row)) == res1
expect(mini(m1, .Column)) == res2
}
it("mean") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [2.5, 2.5]
let res2 = [2.0, 3.0]
expect(mean(m1)).to(beCloseTo(res1))
expect(mean(m1, .Row)).to(beCloseTo(res1))
expect(mean(m1, .Column)).to(beCloseTo(res2))
}
it("std") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [sqrt(4.5 / 2.0), sqrt(0.5 / 2.0)]
let res2 = [sqrt(2.0 / 2.0), sqrt(2.0 / 2.0)]
expect(std(m1)).to(beCloseTo(res1))
expect(std(m1, .Row)).to(beCloseTo(res1))
expect(std(m1, .Column)).to(beCloseTo(res2))
}
it("normalize") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let mr = mean(m1)
let sr = std(m1)
let mc = mean(m1, .Column)
let sc = std(m1, .Column)
let res1 = transpose((transpose(m1) - mr) ./ sr)
let res2 = (m1 - mc) ./ sc
expect(normalize(m1)) == res1
expect(normalize(m1, .Row)) == res1
expect(normalize(m1, .Column)) == res2
}
it("sum") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [5.0, 5.0]
let res2 = [4.0, 6.0]
expect(sum(m1)).to(beCloseTo(res1))
expect(sum(m1, .Row)).to(beCloseTo(res1))
expect(sum(m1, .Column)).to(beCloseTo(res2))
}
it("sumsq") {
let m1 = Matrix([[1.0, 4.0], [3.0, 2.0]])
let res1 = [17.0, 13.0]
let res2 = [10.0, 20.0]
expect(sumsq(m1)).to(beCloseTo(res1))
expect(sumsq(m1, .Row)).to(beCloseTo(res1))
expect(sumsq(m1, .Column)).to(beCloseTo(res2))
}
}
describe("Matrix linear algebra tests") {
it("trace") {
let m1 = Matrix([[1.0, 0.0, 2.0],
[-1.0, 5.0, 0.0],
[0.0, 3.0, -9.0]])
let res = -3.0
expect(trace(m1)) == res
}
it("transpose") {
let m1 = Matrix([[1.0, 4.0],
[3.0, 2.0]])
let res = Matrix([[1.0, 3.0],
[4.0, 2.0]])
expect(transpose(m1)) == res
expect(m1′) == res
expect(m1.T) == res
}
it("mtimes") {
let m1 = Matrix([[1.0, 3.0, 5.0],
[2.0, 4.0, 7.0]])
let m2 = Matrix([[-5.0, 8.0, 11.0],
[3.0, 9.0, 21.0],
[4.0, 0.0, 8.0]])
let res = Matrix([[24.0, 35.0, 114.0],
[30.0, 52.0, 162.0]])
expect(m1 * m2) == res
expect(mtimes(m1, m2)) == res
}
it("mpower") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let res1 = Matrix([[7.0, 10.0],
[15.0, 22.0]])
let res2 = inv(m1 * m1)
let eye = Matrix([[1.0, 0.0],
[0.0, 1.0]])
expect(m1 ^ 1) == m1
expect(m1 ^ 2) == res1
expect(m1 ^ -2) == res2
expect(m1 ^ 0) == eye
}
it("inverse") {
let m1 = Matrix([[1.0, 0.0, 2.0],
[-1.0, 5.0, 0.0],
[0.0, 3.0, -9.0]])
let res = Matrix([[0.88235294117647067, -0.11764705882352944, 0.19607843137254904],
[0.17647058823529416, 0.17647058823529413, 0.03921568627450981],
[0.058823529411764663, 0.058823529411764719, -0.098039215686274522]])
expect(inv(m1)) == res
expect(mpower(m1, -1)) == res
expect(m1 ^ -1) == res
let m2 = Matrix([[1.0, 0.0, 2.0], [-1.0, 5.0, 0.0]])
#if !SWIFT_PACKAGE
expect { () -> Void in _ = inv(m2) }.to(throwAssertion())
expect { () -> Void in _ = inv(ones(3, 3)) }.to(throwAssertion())
#endif
expect(inv(m1) * m1) == eye(3, 3)
}
it("eigen") {
let m1 = Matrix([[1.0000, 0.5000, 0.3333, 0.2500],
[0.5000, 1.0000, 0.6667, 0.5000],
[0.3333, 0.6667, 1.0000, 0.7500],
[0.2500, 0.5000, 0.7500, 1.0000]])
let e1 = eig(m1)
expect(m1 * e1.V) == e1.V * e1.D
let m2 = Matrix([[1.0, 0.0, 2.0],
[-1.0, 5.0, 0.0]])
#if !SWIFT_PACKAGE
expect { () -> Void in _ = eig(m2) }.to(throwAssertion())
#endif
let m3 = Matrix([[0, 1],
[-2, -3]])
let e2 = eig(m3)
expect(m3 * e2.V) == e2.V * e2.D
let v3 = Matrix([[-1.0, 0.0],
[0.0, -2.0]])
expect(e2.D) == v3
}
it("svd") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0],
[7.0, 8.0]])
let usv = svd(m1)
expect(usv.U * usv.S * usv.V′) == m1
}
it("gsvd") {
let m1 = Matrix([[1.0, 6.0, 11.0],
[2.0, 7.0, 12.0],
[3.0, 8.0, 13.0],
[4.0, 9.0, 14.0],
[5.0, 10.0, 15.0]])
let m2 = Matrix([[8.0, 1.0, 6.0],
[3.0, 5.0, 7.0],
[4.0, 9.0, 2.0]])
let m3 = Matrix([[0.5700, -0.6457, -0.4279],
[-0.7455, -0.3296, -0.4375],
[-0.1702, -0.0135, -0.4470],
[0.2966, 0.3026, -0.4566],
[0.0490, 0.6187, -0.4661]])
let (U, _, _, _, _, _) = gsvd(m1, m2)
expect(U == m3)
}
it("chol") {
let m1 = Matrix([[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]])
let u = chol(m1)
expect(u′ * u) == m1
let l = chol(m1, .Lower)
expect(l * l′) == m1
}
it("det") {
let m = Matrix([[1.44, -7.84, -4.39, 4.53],
[-9.96, -0.28, -3.24, 3.83],
[-7.55, 3.24, 6.27, -6.64],
[8.34, 8.09, 5.28, 2.06]])
let d = det(m)
expect(d).to(beCloseTo(-4044.7754))
}
it("lstsq") {
// Setup
let a1 = Matrix([[1.44, -7.84, -4.39, 4.53],
[-9.96, -0.28, -3.24, 3.83],
[-7.55, 3.24, 6.27, -6.64],
[8.34, 8.09, 5.28, 2.06],
[7.08, 2.52, 0.74, -2.47],
[-5.45, -5.70, -1.19, 4.70]])
let b1 = Matrix([[8.58, 9.35],
[8.26, -4.43],
[8.48, -0.70],
[-5.28, -0.26],
[5.72, -7.36],
[8.93, -2.52]])
let c2 = Matrix([[-0.4506, 0.2497],
[-0.8491, -0.9020],
[0.7066, 0.6323],
[0.1288, 0.1351]])
let d2 = Matrix([[195.3616, 107.05746]])
// Run function
let (c1, d1) = lstsqr(a1, b1)
// Check solution matrix
expect(c1.rows) == c2.rows
expect(c1.cols) == c2.cols
for i in 0..<c1.rows {
for j in 0..<c1.cols {
let e1: Double = c1[i, j]
let e2: Double = c2[i, j]
expect(e1).to(beCloseTo(e2, within:0.001))
}
}
// Check residue matrix
expect(d1.rows) == d2.rows
expect(d1.cols) == d2.cols
for i in 0..<d1.rows {
for j in 0..<d1.cols {
let e1: Double = d1[i, j]
let e2: Double = d2[i, j]
expect(e1).to(beCloseTo(e2, within:0.001))
}
}
}
}
describe("Matrix concatenation") {
it("horizontal scalar append") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = 5.0
let res = Matrix([[1.0, 2.0],
[3.0, 4.0],
[5.0, 5.0]])
expect(m1 === v) == res
}
it("horizontal scalar prepend") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = 5.0
let res = Matrix([[5.0, 5.0],
[1.0, 2.0],
[3.0, 4.0]])
expect(v === m1) == res
}
it("horizontal vector append") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = [5.0, 6.0]
let res = Matrix([[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0]])
expect(m1 === v) == res
expect(append(m1, rows: [v])) == res
expect(append(m1, rows: Matrix([v]))) == res
}
it("horizontal vector prepend") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = [5.0, 6.0]
let res = Matrix([[5.0, 6.0],
[1.0, 2.0],
[3.0, 4.0]])
expect(v === m1) == res
expect(prepend(m1, rows: [v])) == res
expect(prepend(m1, rows: Matrix([v]))) == res
}
it("horizontal matrix append") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0],
[7.0, 8.0]])
let res = Matrix([[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0],
[7.0, 8.0]])
expect(m1 === m2) == res
}
it("horizontal matrix prepend") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0],
[7.0, 8.0]])
let res = Matrix([[5.0, 6.0],
[7.0, 8.0],
[1.0, 2.0],
[3.0, 4.0]])
expect(m2 === m1) == res
}
it("horizontal matrix insert") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0],
[7.0, 8.0]])
let res = Matrix([[1.0, 2.0],
[5.0, 6.0],
[7.0, 8.0],
[3.0, 4.0]])
expect(insert(m1, rows: m2, at: 1)) == res
}
it("vertical scalar append") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = 5.0
let res = Matrix([[1.0, 2.0, 5.0],
[3.0, 4.0, 5.0]])
expect(m1 ||| v) == res
}
it("vertical scalar prepend") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = 5.0
let res = Matrix([[5.0, 1.0, 2.0],
[5.0, 3.0, 4.0]])
expect(v ||| m1) == res
}
it("vertical vector append") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = [5.0, 6.0]
let res = Matrix([[1.0, 2.0, 5.0],
[3.0, 4.0, 6.0]])
expect(m1 ||| v) == res
expect(append(m1, cols: [v])) == res
expect(append(m1, cols: Matrix(v))) == res
}
it("vertical vector prepend") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let v = [5.0, 6.0]
let res = Matrix([[5.0, 1.0, 2.0],
[6.0, 3.0, 4.0]])
expect(v ||| m1) == res
expect(prepend(m1, cols: [v])) == res
expect(prepend(m1, cols: Matrix(v))) == res
}
it("vertical matrix append") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0],
[7.0, 8.0]])
let res = Matrix([[1.0, 2.0, 5.0, 6.0],
[3.0, 4.0, 7.0, 8.0]])
expect(m1 ||| m2) == res
}
it("vertical matrix prepend") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0],
[7.0, 8.0]])
let res = Matrix([[5.0, 6.0, 1.0, 2.0],
[7.0, 8.0, 3.0, 4.0]])
expect(m2 ||| m1) == res
}
it("vertical matrix insert") {
let m1 = Matrix([[1.0, 2.0],
[3.0, 4.0]])
let m2 = Matrix([[5.0, 6.0],
[7.0, 8.0]])
let res = Matrix([[1.0, 5.0, 6.0, 2.0],
[3.0, 7.0, 8.0, 4.0]])
expect(insert(m1, cols: m2, at: 1)) == res
}
it("vstack") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
let m2 = Matrix([[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]])
let res = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]])
expect(vstack([m1, m2])) == res
}
it("hstack") {
let m1 = Matrix([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
let m2 = Matrix([[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]])
let res = Matrix([[1.0, 2.0, 3.0, 7.0, 8.0, 9.0],
[4.0, 5.0, 6.0, 10.0, 11.0, 12.0]])
expect(hstack([m1, m2])) == res
}
}
describe("matrix slicing") {
it("basic tests") {
let m1 = Matrix([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
let res1 = Matrix([[0, 1, 2],
[5, 6, 7],
[10, 11, 12]])
let res2 = Matrix([[12, 13, 14],
[17, 18, 19]])
let res3 = Matrix([[10, 11, 12, 13, 14],
[5, 6, 7, 8, 9 ]])
let res4 = Matrix([[2, 1],
[7, 6],
[12, 11],
[17, 16]])
let res5 = Matrix([[9, 7, 5],
[4, 2, 0]])
let res6 = Matrix([[18, 15],
[8, 5]])
expect(m1 ?? (.All, .All)) == m1
expect(m1[(.All, .All)]) == m1
expect(m1 ?? (.Take(3), .DropLast(2))) == res1
expect(m1 ?? (.DropLast(1), .Take(3))) == res1
expect(m1 ?? (.TakeLast(2), .TakeLast(3))) == res2
expect(m1 ?? (.Drop(2), .Drop(2))) == res2
expect(m1 ?? (.Pos([2, 1]), .All)) == res3
expect(m1 ?? (.All, .Pos([2, 1]))) == res4
expect(m1 ?? (.PosCyc([-7, 80]), .Range(4, -2, 0))) == res5
expect(m1 ?? (.Range(3, -2, 0), .PosCyc([-7, 80]))) == res6
#if !SWIFT_PACKAGE
expect { () -> Void in _ = m1 ?? (.Range(4, -2, 0), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Range(3, -2, -1), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Range(5, -2, 0)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Range(3, -2, -1)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Range(0, -2, 4), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Range(-1, -2, 3), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Range(0, -2, 5)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Range(-1, -2, 3)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Take(5), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Take(-1), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Take(6)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Take(-1)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Drop(5), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.Drop(-1), .All) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Drop(6)) }.to(throwAssertion())
expect { () -> Void in _ = m1 ?? (.All, .Drop(-1)) }.to(throwAssertion())
#endif
}
}
}
}
| 41.397476 | 103 | 0.311286 |
33ff6038e7c64a478d7af75f27c2040132dec1bc | 1,921 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import XCTest
@testable import Datadog
class URLSessionAutoInstrumentationTests: XCTestCase {
override func setUp() {
super.setUp()
XCTAssertNil(URLSessionAutoInstrumentation.instance)
}
override func tearDown() {
XCTAssertNil(URLSessionAutoInstrumentation.instance)
super.tearDown()
}
func testWhenURLSessionAutoInstrumentationIsEnabled_thenSharedInterceptorIsAvailable() {
XCTAssertNil(URLSessionInterceptor.shared)
// When
URLSessionAutoInstrumentation.instance = URLSessionAutoInstrumentation(
configuration: .mockAny(),
commonDependencies: .mockAny()
)
defer {
URLSessionAutoInstrumentation.instance?.deinitialize()
}
// Then
XCTAssertNotNil(URLSessionInterceptor.shared)
}
func testGivenURLSessionAutoInstrumentationEnabled_whenRUMMonitorIsRegistered_itSubscribesAsResourcesHandler() throws {
// Given
RUMFeature.instance = .mockNoOp()
defer { RUMFeature.instance?.deinitialize() }
URLSessionAutoInstrumentation.instance = URLSessionAutoInstrumentation(
configuration: .mockAny(),
commonDependencies: .mockAny()
)
defer {
URLSessionAutoInstrumentation.instance?.deinitialize()
}
// When
Global.rum = RUMMonitor.initialize()
defer { Global.rum = DDNoopRUMMonitor() }
// Then
let resourcesHandler = URLSessionAutoInstrumentation.instance?.interceptor.handler as? URLSessionRUMResourcesHandler
XCTAssertTrue(resourcesHandler?.subscriber === Global.rum)
}
}
| 32.559322 | 124 | 0.691827 |
3a0484ed9e0fad8a903c9cdb3e4f2bf2f89ea536 | 1,823 | //
// MerchantAttributeView.swift
// DropBit
//
// Created by Mitchell Malleo on 11/12/19.
// Copyright © 2019 Coin Ninja, LLC. All rights reserved.
//
import Foundation
import UIKit
protocol MerchantAttributeViewDelegate: AnyObject {
func attributeViewWasTouched(with url: URL)
}
class MerchantAttributeView: UIView {
@IBOutlet var imageView: UIImageView!
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var linkButton: UIButton!
weak var delegate: MerchantAttributeViewDelegate?
var viewModel: MerchantAttributeResponse?
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func initialize() {
xibSetup()
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = .lightGrayBackground
}
func load(with model: MerchantAttributeResponse) {
imageView.image = model.image
viewModel = model
if model.link != nil {
let normalString = NSMutableAttributedString.regular(model.description,
size: 14, color: .darkBlueText)
normalString.underlineText()
linkButton.setAttributedTitle(normalString, for: .normal)
linkButton.isHidden = false
descriptionLabel.isHidden = true
} else {
descriptionLabel.attributedText = NSMutableAttributedString.regular(model.description,
size: 14, color: .darkBlueText)
linkButton.isHidden = true
descriptionLabel.isHidden = false
}
}
@IBAction func linkButtonWasTapped() {
guard let link = viewModel?.link, let url = URL(string: link) else { return }
delegate?.attributeViewWasTouched(with: url)
}
}
| 25.676056 | 104 | 0.667581 |
116faee1eb75ff3693bcf1d0aaae0ed14627ae48 | 274 |
let variable = "string"
var variable: Int? = nil
func test(){}
private func funcTest(){}
override func afunc (){}
self.method()
var strongSelf = self
numbers.map { 3 * $0.value }
protocol Nameable {}
var nextPage = (stateValue.lastPage ?? 0) + 1
fileprivate var number = 3
| 21.076923 | 45 | 0.693431 |
b90061be50519284ce79ad11ac84fcd66aef8a01 | 3,346 | //
// BrickAppearBehaviorTests.swift
// BrickKit
//
// Created by Ruben Cagnie on 10/11/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import XCTest
@testable import BrickKit
class BrickAppearBehaviorTests: XCTestCase {
var attributes: UICollectionViewLayoutAttributes!
var brickCollectionView: BrickCollectionView!
override func setUp() {
super.setUp()
attributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attributes.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
brickCollectionView = BrickCollectionView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
brickCollectionView.contentSize = brickCollectionView.frame.size
}
func testShouldInitializeWithoutAppearBehavior() {
let brickLayout = BrickFlowLayout()
XCTAssertNil(brickLayout.appearBehavior)
}
// Mark: - Top
func testTopAppear() {
let topAppear = BrickAppearTopBehavior()
topAppear.configureAttributesForAppearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.frame, CGRect(x: 0, y: -200, width: 320, height: 200))
}
func testTopDisappear() {
let topAppear = BrickAppearTopBehavior()
topAppear.configureAttributesForDisappearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.frame, CGRect(x: 0, y: -200, width: 320, height: 200))
}
// Mark: - Bottom
func testBottomAppear() {
let bottomAppear = BrickAppearBottomBehavior()
bottomAppear.configureAttributesForAppearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 480, width: 320, height: 200))
}
func testBottomDisappear() {
let bottomAppear = BrickAppearBottomBehavior()
bottomAppear.configureAttributesForDisappearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 480, width: 320, height: 200))
}
func testBottomAppearWithSmallContentHeight() {
brickCollectionView.contentSize.height = 10
let bottomAppear = BrickAppearBottomBehavior()
bottomAppear.configureAttributesForAppearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 480, width: 320, height: 200))
}
func testBottomAppearWithLargeContentHeight() {
brickCollectionView.contentSize.height = 1000
let bottomAppear = BrickAppearBottomBehavior()
bottomAppear.configureAttributesForAppearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 1000, width: 320, height: 200))
}
// Mark: - Fade
func testScaleAppear() {
let scaleAppear = BrickAppearScaleBehavior()
scaleAppear.configureAttributesForAppearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.alpha, 0)
XCTAssertEqual(attributes.transform, CGAffineTransform(scaleX: 0.1, y: 0.1))
}
func testScaleDisappear() {
let scaleAppear = BrickAppearScaleBehavior()
scaleAppear.configureAttributesForDisappearing(attributes, in: brickCollectionView)
XCTAssertEqual(attributes.alpha, 0)
XCTAssertEqual(attributes.transform, CGAffineTransform(scaleX: 0.1, y: 0.1))
}
}
| 37.595506 | 101 | 0.711297 |
79027267100e13ad3b70f27106199baec382d1ea | 284 | //
// MockNetworkActivityIndicator.swift
// Tests
//
// Copyright © 2017 Bottle Rocket Studios. All rights reserved.
//
import Foundation
import Hyperspace
class MockNetworkActivityIndicator: NetworkActivityIndicatable {
var isNetworkActivityIndicatorVisible: Bool = false
}
| 20.285714 | 64 | 0.785211 |
697086fe37d021604867152ad07515ec33eee72d | 912 | //
// ItemSelectionView.swift
// PrivateVault
//
// Created by Emilio Peláez on 1/3/21.
//
import SwiftUI
struct ItemSelectionView: View {
let selected: Bool
var body: some View {
ZStack {
Circle()
.fill(Color(.systemBackground))
.shadow(color: Color(white: 0, opacity: 0.4), radius: 2, x: 0, y: 1)
.opacity(0.5)
Circle()
.fill(Color(.systemBlue))
.padding(2)
.scaleEffect(selected ? 1 : .ulpOfOne)
Image(systemName: "checkmark")
.font(.system(size: 10, weight: .bold))
.foregroundColor(Color(.systemBackground))
.scaleEffect(selected ? 1 : .ulpOfOne)
}
.frame(width: 25, height: 25)
}
}
struct ItemSelectionView_Previews: PreviewProvider {
static var previews: some View {
ItemSelectionView(selected: true)
.padding()
.previewLayout(.sizeThatFits)
ItemSelectionView(selected: false)
.padding()
.previewLayout(.sizeThatFits)
}
}
| 21.209302 | 72 | 0.667763 |
d57969a6bf0ab461405eb8763878c31102af02c5 | 91 | import XCTest
@testable import SauceTests
XCTMain([
testCase(SauceTests.allTests),
])
| 13 | 34 | 0.758242 |
fe198bd60f389688279527b6649a82c83f38e018 | 853 | //
// ShepardPhotoFrameBorderView.swift
// MEGameTracker
//
// Created by Emily Ivie on 1/19/20.
// Copyright © 2020 Emily Ivie. All rights reserved.
//
import UIKit
@IBDesignable
class ShepardPhotoFrameBorderView: UIView {
@IBInspectable var cornerRadius: CGFloat = 10
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
let maskLayer = CAShapeLayer()
let maskPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: [.topLeft, .topRight, .bottomLeft],
cornerRadii: CGSize(width: cornerRadius, height: 0.0))
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
}
}
| 25.848485 | 90 | 0.603751 |
1eaf218419a150e52b2033fc59f2fac89863cb57 | 1,886 | import ThemeKit
import RxSwift
import RxCocoa
class WalletConnectScanQrViewController: ScanQrViewController {
private let baseViewModel: WalletConnectViewModel
private let viewModel: WalletConnectScanQrViewModel
private weak var sourceViewController: UIViewController?
private let disposeBag = DisposeBag()
init(baseViewModel: WalletConnectViewModel, sourceViewController: UIViewController?) {
self.baseViewModel = baseViewModel
viewModel = baseViewModel.scanQrViewModel
self.sourceViewController = sourceViewController
super.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel.openMainSignal
.emit(onNext: { [weak self] in
self?.openMain()
})
.disposed(by: disposeBag)
viewModel.openErrorSignal
.emit(onNext: { [weak self] error in
self?.openError(error: error)
})
.disposed(by: disposeBag)
}
override func onScan(string: String) {
viewModel.handleScanned(string: string)
}
private func openMain() {
let viewController = WalletConnectMainViewController(baseViewModel: baseViewModel, sourceViewController: sourceViewController)
dismiss(animated: true) { [weak self] in
self?.sourceViewController?.present(ThemeNavigationController(rootViewController: viewController), animated: true)
}
}
private func openError(error: Error) {
let viewController = WalletConnectErrorViewController(error: error, sourceViewController: sourceViewController)
present(ThemeNavigationController(rootViewController: viewController), animated: true)
}
}
| 33.087719 | 134 | 0.678685 |
f42edb01c7a9d5fce4b6c099a60293e27add82b6 | 892 | //: [トップ](Top) | [前のページ](@previous)
import Foundation
//: # Optionalってどんなもの?
// まずは、普通の文字列です
var normalMessage: String = "hello!"
// Swiftの世界では、普通の文字列にはnilを入れる (= 空っぽにする) ことができません
//: - callout(Error): `var normalMessage: String = nil`
// -> Nil cannot initialize specified type 'String'
// -> nilはString型を初期化できません
// 型の末尾に「?」がついたものが「Optional (オプショナル)」です
var optionalMessage: String? = "hi!"
// Optionalな変数には、nilを入れることができます
// 試しに入れてみてもエラーが出ませんね
optionalMessage = nil
// つまり、Optionalとは
// 値が入っているかもしれない、入っていないかもしれない…そんな曖昧なものなのです
//: ## Optionalの型
// よい機会なので、それぞれがどんな型になっているのか、 type(of:) で見てみましょう
type(of: normalMessage)
// -> String.Type
type(of: optionalMessage)
// -> Optional<String>.Type
// 「?」がついているほうは、 Optional<String> という型であることがわかります
// つまり、こう書いても同じ意味になります
var optionalMessage2: Optional<String> = nil
// Optionalの簡単な書きかたをSwiftが用意してくれている、というわけですね
//: [次のページ](@next)
| 19.391304 | 55 | 0.724215 |
18c1f98f5cbd8c101d0b7dd87f42929fed0155d6 | 1,365 | //
// AppDelegate.swift
// DiplomaDigitalHabbits
//
// Created by Роман Ковайкин on 16.09.2021.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.891892 | 179 | 0.748718 |
5011c5f12ccc33552bbceb693537c99c1ff769d4 | 2,449 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for AmplifyBackend
public struct AmplifyBackendErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case gatewayTimeoutException = "GatewayTimeoutException"
case notFoundException = "NotFoundException"
case tooManyRequestsException = "TooManyRequestsException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize AmplifyBackend
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// An error returned if a request is not formed properly.
public static var badRequestException: Self { .init(.badRequestException) }
/// An error returned if there's a temporary issue with the service.
public static var gatewayTimeoutException: Self { .init(.gatewayTimeoutException) }
/// An error returned when a specific resource type is not found.
public static var notFoundException: Self { .init(.notFoundException) }
/// An error that is returned when a limit of a specific type has been exceeded.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
}
extension AmplifyBackendErrorType: Equatable {
public static func == (lhs: AmplifyBackendErrorType, rhs: AmplifyBackendErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension AmplifyBackendErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 36.552239 | 117 | 0.664761 |
d79ba119546e59a7191804b77f79237cc328b67e | 750 | //
// UITextFieldExtension.swift
// thecareprtal
//
// Created by Anil Kukadeja on 03/05/18.
// Copyright © 2018 Jiniguru. All rights reserved.
//
import Foundation
import UIKit
extension UITextField{
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
}
}
func setPlaceHolderColor(placeHolderText : String,color : UIColor){
self.attributedPlaceholder = NSAttributedString(string: placeHolderText, attributes: [NSAttributedString.Key.foregroundColor : color])
}
}
| 26.785714 | 157 | 0.686667 |
387b81f0411d6ebca2820d3b6e3c0f615e20de18 | 5,145 | //
// FC_SQLiteManager.swift
// JKB_EquipmentManage
//
// Created by 方存 on 2019/6/11.
// Copyright © 2019年 JKB. All rights reserved.
//
import Foundation
import SQLite
/// 表字段
let id = Expression<Int64>("rowid")
let token = Expression<String>("token")
let name = Expression<String?>("name")
let phone = Expression<String?>("phone")
let company = Expression<String?>("company")
let headerImg = Expression<String?>("headerImg")
class FC_SQLiteManager: NSObject {
/// 数据库管理者(单例)
static let manager = FC_SQLiteManager()
// 数据库链接
private var db: Connection?
/// 用户信息 表
private var table: Table?
/// 连接数据库
func getDB() -> Connection {
if db == nil {
// 沙盒存放路径
let path = NSHomeDirectory() + "/Documents/userInfo.sqlite3"
db = try! Connection(path)
// 连接尝试重试语句的秒数
db?.busyTimeout = 5.0
DLog("与数据库建立连接 成功")
}
return db!
}
/// 获取表
func getTable() -> Table {
if table == nil {
table = Table("user_info")
try! getDB().run(
table!.create(temporary: false, ifNotExists: true, withoutRowid: false, block: { (builder) in
builder.column(id, primaryKey: true) // 设置为主键
builder.column(token)
builder.column(name)
builder.column(phone)
builder.column(company)
builder.column(headerImg)
})
)
}
return table!
}
// 增加一条数据(一条数据包含模型中所有字段)
func insert(_ info: FC_UserInfo) {
let insert = getTable().insert(token <- info.token, name <- info.name, phone <- info.phone, company <- info.company, headerImg <- info.headerImg)
if let rowId = try? getDB().run(insert) {
DLog("插入成功:数据id=\(rowId)")
} else {
DLog("插入失败")
}
}
/// 查询所有数据
func selectAll() -> [FC_UserInfo] {
var infoArr = [FC_UserInfo]()
for user in try! getDB().prepare(getTable()) {
let newInfo = FC_UserInfo(token: user[token], name: user[name] ?? "", phone: user[phone] ?? "", company: user[company] ?? "", headerImg: user[headerImg] ?? "")
// 添加到数组中
infoArr.append(newInfo)
}
return infoArr
}
/// 根据插入数据的id(目前只存一个用户信息,所以id传1即可) 及 关键字 更新本条数据
func update(id: Int64, keyWord: String, newsInfo: FC_UserInfo) {
// 更新 哪条数据
let update = getTable().filter(rowid == id)
if keyWord == "token" {
// 修改token
if let count = try? getDB().run(update.update(token <- newsInfo.token)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败")}
}else if keyWord == "name" {
// 修改名字
if let count = try? getDB().run(update.update(name <- newsInfo.name)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败")}
}else if keyWord == "phone" {
// 修改手机
if let count = try? getDB().run(update.update(phone <- newsInfo.phone)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败")}
}else if keyWord == "company" {
// 修改公司
if let count = try? getDB().run(update.update(company <- newsInfo.company)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败")}
}else if keyWord == "headerImg" {
// 修改头像
if let count = try? getDB().run(update.update(headerImg <- newsInfo.headerImg)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败")}
}else if keyWord == "n_p_c" {
// 修改名字、手机、公司
if let count = try? getDB().run(update.update(name <- newsInfo.name, phone <- newsInfo.phone, company <- newsInfo.company)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败") }
}else{
// 修改所有字段值
if let count = try? getDB().run(update.update(token <- newsInfo.token, name <- newsInfo.name, phone <- newsInfo.phone, company <- newsInfo.company, headerImg <- newsInfo.headerImg)) {
DLog("修改的结果为:\(count == 1)")
} else { DLog("修改失败") }
}
}
/// 根据id 删除
func delete(id: Int64) {
filter_delete(filter: rowid < id)
}
/// 根据条件删除(参数可以不传,如果传则如: rowid == id 或 name == "xiaoMing")
func filter_delete(filter: Expression<Bool>? = nil) {
var query = getTable()
if let f = filter {
query = query.filter(f)
}
if let count = try? getDB().run(query.delete()) {
DLog("删除的条数为:\(count)")
} else {
DLog("删除失败")
}
}
/// 清空本地数据库
func clearTableData() {
do {
if try getDB().run(table!.delete()) > 0 {
DLog("清空成功")
}else {
DLog("清空失败")
}
} catch {
DLog("清空错误:\(error)")
}
}
}
| 31.564417 | 195 | 0.495627 |
de4e5bd5961bc803e68706290af7098dc93b252a | 2,262 | //
// Battleship.swift
// swift-functional
//
// Created by CMVIOS1 on 2017/7/20.
// Copyright © 2017年 CMV. All rights reserved.
//
import UIKit
class swift_functional_1_1: NSObject {
}
typealias Distance = Double
struct Position {
var x : Double
var y : Double
}
extension Position {
func inRange(range: Distance) -> Bool {
//sqrt 平方根函数
return sqrt(x * x + y * y) <= range
}
}
struct Ship {
var position: Position
var firingRange: Distance
var unsafeRange: Distance
}
extension Ship {
func canEngageShip(target: Ship) -> Bool {
let dx = target.position.x - position.x
let dy = target.position.y - position.y
let targetDistance = sqrt(dx * dx + dy * dy)
return targetDistance <= firingRange
}
func canSafelyEngageShip(target: Ship) -> Bool {
let dx = target.position.x - position.x
let dy = target.position.y - position.y
let targetDistance = sqrt(dx * dx + dy * dy)
return targetDistance <= firingRange && targetDistance > unsafeRange
}
func canSafelyEngageShip1(target: Ship,friendly: Ship) -> Bool {
let dx = target.position.x - position.x
let dy = target.position.y - position.y
let targetDistance = sqrt(dx * dx + dy * dy)
let friendlyDx = friendly.position.x - target.position.x
let friendlyDy = friendly.position.y - target.position.y
let friendlyDistance = sqrt(friendlyDx * friendlyDx + friendlyDy * friendlyDy)
return targetDistance <= firingRange
&& targetDistance > unsafeRange
&& (friendlyDistance > unsafeRange)
}
}
extension Position {
func minus(p: Position) -> Position {
return Position(x: x - p.x, y: y - p.y)
}
var length : Double {
return sqrt(x * x + y * y)
}
}
extension Ship {
func canSafelyEngageShip2(target: Ship,friendly: Ship) -> Bool {
let targetDistance = sqrt(target.position.minus(p: position).length)
let friendlyDistance = sqrt(friendly.position.minus(p: target.position).length)
return targetDistance <= firingRange
&& targetDistance > unsafeRange
&& (friendlyDistance > unsafeRange)
}
}
| 24.857143 | 87 | 0.623784 |
7a4044b394eb80cafd1abcfc6d686e85cea6ad2d | 795 | //
// ClousersViewController.swift
// Demos
//
// Created by Kritika Middha on 08/02/19.
// Copyright © 2019 ranosys. All rights reserved.
//
import UIKit
class ClousersViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
doSomething()
}
func getSumOf(array:[Int], handler: @escaping ((Int)->Void)) {
print("step 2")
var sum: Int = 0
for value in array {
sum += value
}
print("step 3")
handler(sum)
print("end of function")
}
func doSomething() {
print("setp 1")
self.getSumOf(array: [16,756,442,6,23]) { sum in
print(sum)
print("step 4, finishing the execution")
}
}
}
| 19.390244 | 66 | 0.532075 |
1e8ae1113f73f14618c69dd84dfc7ac10aadb606 | 943 | extension FluentBenchmarker {
public func testNonstandardIDKey() throws {
try self.runTest(#function, [
FooMigration()
]) {
let foo = Foo(baz: "qux")
try foo.save(on: self.database).wait()
XCTAssertNotNil(foo.id)
}
}
}
private final class Foo: Model {
static let schema = "foos"
@ID(key: "bar")
var id: Int?
@Field(key: "baz")
var baz: String
init() { }
init(id: Int? = nil, baz: String) {
self.id = id
self.baz = baz
}
}
private struct FooMigration: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("foos")
.field("bar", .int, .identifier(auto: true))
.field("baz", .string, .required)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("foos").delete()
}
}
| 22.452381 | 66 | 0.544008 |
5b97397c3f00c2695e53a899d7dfe2f2d38be8ac | 1,259 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 3.0.1.11917
// 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 set codes that define the functional status of an implanted device.
URL: http://hl7.org/fhir/implant-status
ValueSet: http://hl7.org/fhir/ValueSet/implant-status
*/
public enum ImplantStatus: String, FHIRPrimitiveType {
/// The implanted device is working normally
case functional = "functional"
/// The implanted device is not working
case nonFunctional = "non-functional"
/// The implanted device has been turned off
case disabled = "disabled"
/// the functional status of the implant has not been determined
case unknown = "unknown"
}
| 29.97619 | 76 | 0.731533 |
18e9dba6c446cefaef8129f63caae281db2388e9 | 250 | //
// RendererType.swift
// AGFaceTrackingApp
//
// Created by Alexey Gross on 2020-04-29.
// Copyright © 2020 Alexey Gross. All rights reserved.
//
import Foundation
/// Renderer types
enum RendererType {
case sceneKit
case metalKit
}
| 15.625 | 55 | 0.696 |
896f4f6fa494cb95f31c8905d21f42d22fa5981b | 16,993 | import Foundation
import UIKit
public class Finder: MacApp{
public var desktopIcon: UIImage?
lazy public var uniqueIdentifier: String = {
return UUID().uuidString
}()
public var identifier: String? = "finder"
public var shouldDragApplication: Bool = false
public var contentMode: ContentStyle = .light
public lazy var container: UIView? = FinderView()
public var menuActions: [MenuAction]?
public var windowTitle: String? = ""
var window: OSWindow?
init() {
menuActions = [MenuAction]()
var fileMenuList = [MenuAction]()
fileMenuList.append(MenuAction(title: "Open", action: nil, subMenus: nil, enabled: false))
fileMenuList.append(MenuAction(title: "Duplicate", action: nil, subMenus: nil, enabled: false))
fileMenuList.append(MenuAction(title: "Get Info", action: nil, subMenus: nil, enabled: false))
fileMenuList.append(MenuAction(title: "Put Back", action: nil, subMenus: nil, enabled: false))
fileMenuList.append(MenuAction(type: .seperator))
fileMenuList.append(MenuAction(title: "Close", action: {
if let app = self.window!.activeApplications.last {
self.window?.close(app: app)
}
},runtimeClosure: {
if (self.window?.activeApplications.count ?? 0) > 0{
return true
}
return false
}))
fileMenuList.append(MenuAction(title: "Close All", action: {
for app in self.window!.activeApplications{
self.window?.close(app: app)
}
},runtimeClosure: {
if (self.window?.activeApplications.count ?? 0) > 0{
return true
}
return false
}))
fileMenuList.append(MenuAction(title: "Print", action: {
let topApp = self.window?.activeApplications.last
if topApp is NotePad{
let notepad = topApp as! NotePad
let i = (notepad.container as! NotePadView).currentPage
let currentText = notepad.currentText[i]
NotePad.printCurrentPage(text: currentText.replacingOccurrences(of: "\n", with: "\r\n") + "\r\n")
}else{
print("Top app is not NotePad!")
}
}, runtimeClosure: {
let topApp = self.window?.activeApplications.last
if topApp is NotePad{
return true
}
return false
}))
fileMenuList.append(MenuAction(title: "", action: nil, subMenus: nil,type: .seperator))
fileMenuList.append(MenuAction(title: "Eject ⌘E ", action: nil, subMenus: nil))
menuActions?.append(MenuAction(title: "File", action: { (Void) in
}, subMenus: fileMenuList))
var editMenuList = [MenuAction]()
editMenuList.append(MenuAction(title: "Undo",action: {
let topApp = self.window?.activeApplications.last
if topApp is Picasso{
(topApp as! Picasso).undo()
}
},runtimeClosure: {
let topApp = self.window?.activeApplications.last
if topApp is Picasso{
return (topApp?.container as? PaintView)?.canvas.canUndo ?? false
}
return false
}))
editMenuList.append(MenuAction(type: .seperator))
editMenuList.append(MenuAction(title: "Cut"))
editMenuList.append(MenuAction(title: "Copy"))
editMenuList.append(MenuAction(title: "Paste"))
editMenuList.append(MenuAction(title: "Clear",action: {(Void) in
let topApp = self.window?.activeApplications.last
if topApp is NotePad{
if !(topApp is AboutMe) && !(topApp is HelpNotePad){
let notepad = topApp as! NotePad
let i = (notepad.container as! NotePadView).currentPage
notepad.currentText[i] = ""
notepad.reloadData()
}
}
if topApp is Picasso{
(topApp as! Picasso).clear()
}
},runtimeClosure: {
let topApp = self.window?.activeApplications.last
if topApp is NotePad{
if !(topApp is AboutMe) && !(topApp is HelpNotePad){
return true
}
}
if topApp is Picasso{
return true
}
return false
}))
editMenuList.append(MenuAction(title: "Select All"))
editMenuList.append(MenuAction(type: .seperator))
editMenuList.append(MenuAction(title: "Show Clipboard"))
menuActions?.append(MenuAction(title: "Edit", action: { (Void) in
}, subMenus: editMenuList))
var viewMenuList = [MenuAction]()
viewMenuList.append(MenuAction(title: "By Icon ",enabled: false))
viewMenuList.append(MenuAction(title: "By Name ",enabled: false))
viewMenuList.append(MenuAction(title: "By Date ",enabled: false))
viewMenuList.append(MenuAction(title: "By Size ",enabled: false))
viewMenuList.append(MenuAction(title: "By Kind ",enabled: false))
menuActions?.append(MenuAction(title: "View", action: { (Void) in
}, subMenus: viewMenuList))
var specialMenuList = [MenuAction]()
specialMenuList.append(MenuAction(title: "Clean Up",enabled: false))
specialMenuList.append(MenuAction(title: "Empty Trash ",enabled: false))
specialMenuList.append(MenuAction(title: "Erase Disk",enabled: false))
specialMenuList.append(MenuAction(title: "Set Startup",enabled: false))
menuActions?.append(MenuAction(title: "Special", action: { (Void) in
}, subMenus: specialMenuList))
}
public func willLaunchApplication(in view: OSWindow, withApplicationWindow appWindow: OSApplicationWindow) {
}
public func willTerminateApplication(){
}
public func sizeForWindow() -> CGSize {
return CGSize(width: 364, height: 205)
}
}
public class FinderView: UIView{
override public func draw(_ rect: CGRect) {
UIColor.white.setFill()
UIBezierPath(rect: rect).fill()
//draw upper part
//draw forground rect
UIColor.black.setFill()
let upperRect = CGRect(x: 0, y: 0, width: rect.width, height: rect.height * 0.25)
let upperForground = UIBezierPath(rect: upperRect)
upperForground.fill()
//draw lines
UIColor.white.setFill()
getUpperLines(upperRect).forEach { $0.fill()}
//draw sun
let sunRect = CGRect(x: rect.width * 0.59, y: rect.height * 0.10, width: rect.height * 0.25, height: rect.height * 0.25)
UIBezierPath(roundedRect: sunRect, cornerRadius: sunRect.height / 2).fill()
//draw upper mountains
//draw line
UIColor.black.set()
UIColor.black.setFill()
pathForUpperMountains(rect).stroke()
//draw objects (shadows)
getMountainShadows(rect).forEach {$0.fill()}
//draw lower mountains
pathForLowerMountains(rect).fill()
//draw text
var attributes: [String : Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: SystemSettings.normalSizeFont]
let title = NSAttributedString(string: "The Macintosh™ Finder", attributes: attributes)
title.draw(at: CGPoint(x: rect.width * 0.02, y: rect.height * 0.03))
attributes = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: SystemSettings.notePadFont]
let versionLabel = NSAttributedString(string: "Version 1.1 \nCreated By Antonio Zaitoun", attributes: attributes)
versionLabel.draw(at: CGPoint(x: rect.width * 0.02, y: rect.height * 0.85))
}
func getMountainShadows(_ rect: CGRect)->[UIBezierPath]{
let object1 = UIBezierPath()
object1.move(to: CGPoint(x: rect.width * 0.15, y: rect.height * 0.32))
object1.addLine(to: CGPoint(x: rect.width * 0.13, y: rect.height * 0.36))
object1.addLine(to: CGPoint(x: rect.width * 0.15, y: rect.height * 0.40))
object1.addLine(to: CGPoint(x: rect.width * 0.13, y: rect.height * 0.43))
object1.addLine(to: CGPoint(x: rect.width * 0.15, y: rect.height * 0.46))
object1.addLine(to: CGPoint(x: rect.width * 0.18, y: rect.height * 0.46))
object1.addLine(to: CGPoint(x: rect.width * 0.20, y: rect.height * 0.51))
object1.addLine(to: CGPoint(x: rect.width * 0.25, y: rect.height * 0.51))
object1.addLine(to: CGPoint(x: rect.width * 0.28, y: rect.height * 0.47))
object1.addLine(to: CGPoint(x: rect.width * 0.26, y: rect.height * 0.42))
object1.addLine(to: CGPoint(x: rect.width * 0.22, y: rect.height * 0.42))
object1.addLine(to: CGPoint(x: rect.width * 0.22, y: rect.height * 0.38))
object1.addLine(to: CGPoint(x: rect.width * 0.24, y: rect.height * 0.36))
object1.close()
let object2 = UIBezierPath()
object2.move(to: CGPoint(x: rect.width * 0.29, y: rect.height * 0.55))
object2.addLine(to: CGPoint(x: rect.width * 0.24, y: rect.height * 0.59))
object2.addLine(to: CGPoint(x: rect.width * 0.29, y: rect.height * 0.62))
object2.addLine(to: CGPoint(x: rect.width * 0.37, y: rect.height * 0.59))
object2.addLine(to: CGPoint(x: rect.width * 0.35, y: rect.height * 0.55))
object2.close()
let object3 = UIBezierPath()
object3.move(to: CGPoint(x: rect.width * 0.33, y: rect.height * 0.40))
object3.addLine(to: CGPoint(x: rect.width * 0.35, y: rect.height * 0.42))
object3.addLine(to: CGPoint(x: rect.width * 0.35, y: rect.height * 0.47))
object3.addLine(to: CGPoint(x: rect.width * 0.40, y: rect.height * 0.47))
object3.addLine(to: CGPoint(x: rect.width * 0.42, y: rect.height * 0.43))
object3.addLine(to: CGPoint(x: rect.width * 0.40, y: rect.height * 0.37))
object3.close()
let object4 = UIBezierPath()
object4.move(to: CGPoint(x: rect.width * 0.50, y: rect.height * 0.32))
object4.addLine(to: CGPoint(x: rect.width * 0.44, y: rect.height * 0.43))
object4.addLine(to: CGPoint(x: rect.width * 0.46, y: rect.height * 0.47))
object4.addLine(to: CGPoint(x: rect.width * 0.44, y: rect.height * 0.55))
object4.addLine(to: CGPoint(x: rect.width * 0.42, y: rect.height * 0.59))
object4.addLine(to: CGPoint(x: rect.width * 0.44, y: rect.height * 0.66))
object4.addLine(to: CGPoint(x: rect.width * 0.42, y: rect.height * 0.63))
object4.addLine(to: CGPoint(x: rect.width * 0.46, y: rect.height * 0.78))
object4.addLine(to: CGPoint(x: rect.width * 0.50, y: rect.height * 0.78))
object4.addLine(to: CGPoint(x: rect.width * 0.48, y: rect.height * 0.71))
object4.addLine(to: CGPoint(x: rect.width * 0.46, y: rect.height * 0.71))
object4.addLine(to: CGPoint(x: rect.width * 0.46, y: rect.height * 0.66))
object4.addLine(to: CGPoint(x: rect.width * 0.51, y: rect.height * 0.66))
object4.addLine(to: CGPoint(x: rect.width * 0.55, y: rect.height * 0.59))
object4.addLine(to: CGPoint(x: rect.width * 0.61, y: rect.height * 0.66))
object4.addLine(to: CGPoint(x: rect.width * 0.61, y: rect.height * 0.59))
object4.addLine(to: CGPoint(x: rect.width * 0.64, y: rect.height * 0.59))
object4.addLine(to: CGPoint(x: rect.width * 0.66, y: rect.height * 0.55))
object4.addLine(to: CGPoint(x: rect.width * 0.64, y: rect.height * 0.51))
object4.addLine(to: CGPoint(x: rect.width * 0.59, y: rect.height * 0.51))
object4.addLine(to: CGPoint(x: rect.width * 0.59, y: rect.height * 0.47))
object4.addLine(to: CGPoint(x: rect.width * 0.63, y: rect.height * 0.39))
object4.close()
let object5 = UIBezierPath()
object5.move(to: CGPoint(x: rect.width * 0.71, y: rect.height * 0.43))
object5.addLine(to: CGPoint(x: rect.width * 0.76, y: rect.height * 0.57))
object5.addLine(to: CGPoint(x: rect.width * 0.80, y: rect.height * 0.55))
object5.addLine(to: CGPoint(x: rect.width * 0.82, y: rect.height * 0.44))
object5.addLine(to: CGPoint(x: rect.width * 0.77, y: rect.height * 0.43))
object5.addLine(to: CGPoint(x: rect.width * 0.80, y: rect.height * 0.40))
object5.addLine(to: CGPoint(x: rect.width * 0.77, y: rect.height * 0.38))
object5.close()
let object6 = UIBezierPath()
object6.move(to: CGPoint(x: rect.width * 1.00, y: rect.height * 0.32))
object6.addLine(to: CGPoint(x: rect.width * 0.92, y: rect.height * 0.38))
object6.addLine(to: CGPoint(x: rect.width * 0.95, y: rect.height * 0.47))
object6.addLine(to: CGPoint(x: rect.width * 0.93, y: rect.height * 0.55))
object6.addLine(to: CGPoint(x: rect.width * 0.95, y: rect.height * 0.62))
object6.addLine(to: CGPoint(x: rect.width * 1.00, y: rect.height * 0.62))
object6.close()
return [object1,object2,object3,object4,object5,object6]
}
func pathForLowerMountains(_ rect: CGRect)->UIBezierPath{
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: rect.height * 0.59))
path.addLine(to: CGPoint(x: rect.width * 0.06, y: rect.height * 0.62))
path.addLine(to: CGPoint(x: rect.width * 0.11, y: rect.height * 0.70))
path.addLine(to: CGPoint(x: rect.width * 0.13, y: rect.height * 0.70))
path.addLine(to: CGPoint(x: rect.width * 0.18, y: rect.height * 0.78))
path.addLine(to: CGPoint(x: rect.width * 0.22, y: rect.height * 0.75))
path.addLine(to: CGPoint(x: rect.width * 0.29, y: rect.height * 0.87))
path.addLine(to: CGPoint(x: rect.width * 0.33, y: rect.height * 0.82))
path.addLine(to: CGPoint(x: rect.width * 0.37, y: rect.height * 0.87))
path.addLine(to: CGPoint(x: rect.width * 0.42, y: rect.height * 0.79))
path.addLine(to: CGPoint(x: rect.width * 0.46, y: rect.height * 0.82))
path.addLine(to: CGPoint(x: rect.width * 0.60, y: rect.height * 0.83))
path.addLine(to: CGPoint(x: rect.width * 0.64, y: rect.height * 0.78))
path.addLine(to: CGPoint(x: rect.width * 0.70, y: rect.height * 0.82))
path.addLine(to: CGPoint(x: rect.width * 0.77, y: rect.height * 0.79))
path.addLine(to: CGPoint(x: rect.width * 0.88, y: rect.height * 0.82))
path.addLine(to: CGPoint(x: rect.width * 0.92, y: rect.height * 0.86))
path.addLine(to: CGPoint(x: rect.width * 1.00, y: rect.height * 0.80))
path.addLine(to: CGPoint(x: rect.width, y: rect.height))
path.addLine(to: CGPoint(x: 0, y: rect.height))
path.close()
return path
}
func pathForUpperMountains(_ rect: CGRect)->UIBezierPath{
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: rect.height * 0.36))
path.addLine(to: CGPoint(x: rect.width * 0.15, y: rect.height * 0.32))
path.addLine(to: CGPoint(x: rect.width * 0.33, y: rect.height * 0.40))
path.addLine(to: CGPoint(x: rect.width * 0.50, y: rect.height * 0.32))
path.addLine(to: CGPoint(x: rect.width * 0.71, y: rect.height * 0.43))
path.addLine(to: CGPoint(x: rect.width * 0.79, y: rect.height * 0.36))
path.addLine(to: CGPoint(x: rect.width * 0.86, y: rect.height * 0.43))
path.addLine(to: CGPoint(x: rect.width * 1.00, y: rect.height * 0.32))
path.lineWidth = rect.height * 0.005
return path
}
func getUpperLines(_ rect: CGRect)->[UIBezierPath]{
let h = rect.height
let startingPoint = rect.height / 2
let line1 = UIBezierPath(rect: CGRect(x: 0, y: startingPoint, width: rect.width, height: h * 0.02))
let line2 = UIBezierPath(rect: CGRect(x: 0, y: startingPoint + h * 0.14, width: rect.width, height: h * 0.02))
let line3 = UIBezierPath(rect: CGRect(x: 0, y: startingPoint + 2 * h * 0.14, width: rect.width, height: h * 0.02))
let line4 = UIBezierPath(rect: CGRect(x: 0, y: startingPoint + h * (2 * 0.14 + 0.08), width: rect.width, height: h * 0.04))
let line5 = UIBezierPath(rect: CGRect(x: 0, y: startingPoint + h * (2 * 0.14 + 0.16), width: rect.width, height: h * 0.02))
return [line1,line2,line3,line4,line5]
}
}
| 47.072022 | 131 | 0.583417 |
26326c1e43f2886e3486e960a7bd518f56147049 | 1,877 | //
// UITableViewHeaderFooterView.swift
// Cacao
//
// Created by Alsey Coleman Miller on 11/17/17.
//
import Foundation
#if os(iOS)
import UIKit
import CoreGraphics
#else
import Silica
#endif
/// A reusable view that can be placed at the top or bottom of a table section
/// to display additional information for that section.
///
/// You can use this class as-is without subclassing in most cases.
/// If you have custom content to display, create the subviews for
/// your content and add them to the view in the `contentView` property.
open class UITableViewHeaderFooterView: UIView {
// MARK: - Initializing the View
/// Initializes a header/footer view with the specified reuse identifier.
public required init(reuseIdentifier: String?) {
self.reuseIdentifier = reuseIdentifier
super.init(frame: .zero)
}
#if os(iOS)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#endif
// MARK: - Accessing the Content Views
/// The content view of the header or footer.
public var contentView: UIView = UIView(frame: .zero)
/// The background view of the header or footer.
public var backgroundView: UIView?
// MARK: - Managing View Reuse
/// A string used to identify a reusable header or footer.
public let reuseIdentifier: String?
/// Prepares a reusable header or footer view for reuse by the table.
open func prepareForReuse() { } // override
// MARK: - Accessing the Default View Content
/// A primary text label for the view.
open var textLabel: UILabel?
/// A detail text label for the view.
open var detailTextLabel: UILabel?
}
// MARK: - ReusableView Protocol
extension UITableViewHeaderFooterView: ReusableView { }
| 26.814286 | 78 | 0.674481 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.