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
|
---|---|---|---|---|---|
6a1badfd8a9ab37d2fdbcd9d594001dc2091149c | 2,320 | import Cocoa
public class KeyResponder: NSView {
@IBOutlet var eventQueue: EventQueue!
override public func draw(_: NSRect) {
NSGraphicsContext.saveGraphicsState()
//
// Draw area
//
let lineWidth = bounds.size.width / 40.0
NSColor.white.withAlphaComponent(0.8).set()
NSBezierPath(roundedRect: bounds, xRadius: 10.0, yRadius: 10.0).fill()
NSColor.black.withAlphaComponent(0.6).set()
let path = NSBezierPath(roundedRect: bounds, xRadius: 10, yRadius: 10)
path.lineWidth = lineWidth
path.stroke()
//
// Draw texts
//
let textRect = NSMakeRect(lineWidth * 2,
lineWidth * 2,
bounds.size.width - lineWidth * 4,
bounds.size.height - lineWidth * 4)
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: NSFont.boldSystemFont(ofSize: textRect.size.width / 10),
NSAttributedString.Key.foregroundColor: NSColor.black.withAlphaComponent(0.6),
]
NSString("Mouse Area").draw(in: textRect, withAttributes: attributes)
NSGraphicsContext.restoreGraphicsState()
}
//
// Key event handlers
//
override public func keyDown(with _: NSEvent) {}
override public func keyUp(with _: NSEvent) {}
override public func flagsChanged(with _: NSEvent) {}
override public func mouseDown(with _: NSEvent) {}
override public func mouseUp(with _: NSEvent) {}
override public func mouseDragged(with event: NSEvent) {
eventQueue.pushMouseEvent(event)
}
override public func rightMouseDown(with _: NSEvent) {}
override public func rightMouseUp(with _: NSEvent) {}
override public func rightMouseDragged(with event: NSEvent) {
eventQueue.pushMouseEvent(event)
}
override public func otherMouseDown(with _: NSEvent) {}
override public func otherMouseUp(with _: NSEvent) {}
override public func otherMouseDragged(with event: NSEvent) {
eventQueue.pushMouseEvent(event)
}
override public func scrollWheel(with event: NSEvent) {
eventQueue.pushMouseEvent(event)
}
override public func swipe(with _: NSEvent) {}
}
| 28.292683 | 97 | 0.634052 |
084b05fdae70dafdfcbc4c848745f53eb70f562c | 5,850 | //
// FileHeader.swift
// FitDataProtocol
//
// Created by Kevin Hoogheem on 1/27/18.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import DataDecoder
/// Protocol Major Version
public let kProtocolVersionMajor: UInt8 = 21
/// Protocol Minor Version
public let kProtocolVersionMinor: UInt8 = 16
internal func ProtocolVersionMajor(_ value: UInt8) -> UInt8 {
return (value >> 4)
}
internal var protocolVersion20: UInt8 {
// 4 is the major version shift
return (2 << 4) | 0
}
/// FIT File Header
internal struct FileHeader {
/// Header Size
private static var kHeaderSize: UInt8 = 14
/// Size of Header
private(set) public var headerSize: UInt8
/// Protocol version number as provided in SDK
private(set) public var protocolVersion: UInt8
/// Profile version number as provided in SDK
private(set) public var profileVersion: UInt16
/// Data Size
private(set) public var dataSize: UInt32
/// CRC Value
private(set) public var crc: UInt16?
internal init(dataSize: UInt32) {
self.headerSize = FileHeader.kHeaderSize
self.protocolVersion = protocolVersion20
self.profileVersion = (UInt16(kProtocolVersionMajor) * 100) + UInt16(kProtocolVersionMinor)
self.dataSize = dataSize
self.crc = 0
}
private init(headerSize: UInt8, protocolVersion: UInt8, profileVersion: UInt16, dataSize: UInt32, crc: UInt16?) {
self.headerSize = headerSize
self.protocolVersion = protocolVersion
self.profileVersion = profileVersion
self.dataSize = dataSize
self.crc = crc
}
}
extension FileHeader: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
internal static func == (lhs: FileHeader, rhs: FileHeader) -> Bool {
return (lhs.headerSize == rhs.headerSize) &&
(lhs.protocolVersion == rhs.protocolVersion) &&
(lhs.profileVersion == rhs.profileVersion) &&
(lhs.dataSize == rhs.dataSize) &&
(lhs.crc == rhs.crc)
}
}
internal extension FileHeader {
var encodedData: Data {
var encode = Data()
encode.append(headerSize)
encode.append(protocolVersion)
encode.append(Data(from: profileVersion.littleEndian))
encode.append(Data(from: dataSize.littleEndian))
_ = String([ ".", "F", "I", "T"]).utf8.map{ encode.append(UInt8($0)) }
if headerSize == FileHeader.kHeaderSize {
let crcCheck = CRC16(data: encode).crc
encode.append(Data(from:crcCheck.littleEndian))
}
return encode
}
}
internal extension FileHeader {
static func decode(data: Data, validateCrc: Bool = true) -> Result<FileHeader, FitDecodingError> {
var decoder = DecodeData()
let headerSize = decoder.decodeUInt8(data)
/// Just call this not a Fit file if the header size doesn't match the data size
guard headerSize <= data.count else { return.failure(FitDecodingError.nonFitFile) }
let protocolVersion = decoder.decodeUInt8(data)
/// we will check the protocolVersion later.
let profileVersion = decoder.decodeUInt16(data)
let dataSize = decoder.decodeUInt32(data)
let fitCheckData = decoder.decodeData(data, length: 4)
let fitString = String(bytes: fitCheckData, encoding: .ascii)
guard fitString == ".FIT" else { return.failure(FitDecodingError.nonFitFile) }
guard ProtocolVersionMajor(protocolVersion) <= ProtocolVersionMajor(protocolVersion20) else {
return.failure(FitDecodingError.protocolVersionNotSupported)
}
// If we have a size of 14 in Header check CRC
var crc: UInt16?
if headerSize == FileHeader.kHeaderSize {
let crcValue = decoder.decodeUInt16(data)
if crcValue != 0 {
crc = crcValue
if validateCrc == true {
let crcData = data[0...11]
let value = CRC16(data: crcData).crc
guard value == crc else { return.failure(FitDecodingError.invalidHeaderCrc) }
}
}
}
let fileHeader = FileHeader(headerSize: headerSize,
protocolVersion: protocolVersion,
profileVersion: profileVersion,
dataSize: dataSize,
crc: crc)
return.success(fileHeader)
}
}
| 34.210526 | 117 | 0.644957 |
1a95a7688f60d10cddff026e1d5cafe4826b423b | 221 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
extension NSData {
func f: T
{
class
case c,
case
| 18.416667 | 87 | 0.751131 |
64ceb4a8927250d9b8293dcee3b3c89dedd73346 | 442 | // MIT license. Copyright (c) 2019 SwiftyFORM. All rights reserved.
import UIKit
extension UIView {
/// Find the first UITableView among all the superviews.
///
/// - returns: the found tableview otherwise nil.
func form_tableView() -> UITableView? {
var viewOrNil: UIView? = self
while let view = viewOrNil {
if let tableView = view as? UITableView {
return tableView
}
viewOrNil = view.superview
}
return nil
}
}
| 23.263158 | 67 | 0.692308 |
72baf03dbfd8f2a6c0d3c17dfa14b88973c4b43e | 843 | //
// CFDiaryModel.swift
// CareFree
//
// Created by 张驰 on 2019/12/5.
// Copyright © 2019 张驰. All rights reserved.
//
import Foundation
struct CFAlbumMouthModel {
var time = ""
var data = [CFDiaryModel]()
var celldata = [AlbumCellModel]()
}
struct CFDiaryModel {
var id = 0
var mode = 0
var user_id = ""
var day_id = ""
var dayDiary = DayDiaryModel()
var nowDiary = [NowDiaryModel]()
}
struct CFDiaryDayModel {
var id = 0
var user_id = ""
var day_id = ""
var title = ""
var content = ""
var weather = ""
var images = ""
var date = Date()
var mode = 0
}
struct CFDiaryNowModel {
var id = 0
var user_id = ""
var day_id = ""
var title = ""
var content = ""
var weather = ""
var images = ""
var date = Date()
var mode = 0
}
| 17.204082 | 45 | 0.557533 |
5b4bdda7d5f389375a14e014de4d499a66b7f57a | 1,677 | //
// UISectionedViewType+RxAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UITableView {
@available(*, deprecated=0.7, renamed="rx_itemsWithDataSource", message="You can just use normal `rx_itemsWithDataSource` extension.")
public func rx_itemsAnimatedWithDataSource<
DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>,
S: SequenceType,
O: ObservableType
where
DataSource.Element == S,
O.E == S,
S.Generator.Element: AnimatableSectionModelType
>
(dataSource: DataSource)
-> (source: O)
-> Disposable {
return { source in
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
}
}
extension UICollectionView {
@available(*, deprecated=0.7, renamed="rx_itemsWithDataSource", message="You can just use normal `rx_itemsWithDataSource` extension.")
public func rx_itemsAnimatedWithDataSource<
DataSource: protocol<RxCollectionViewDataSourceType, UICollectionViewDataSource>,
S: SequenceType,
O: ObservableType
where
DataSource.Element == S,
O.E == S,
S.Generator.Element: AnimatableSectionModelType
>
(dataSource: DataSource)
-> (source: O)
-> Disposable {
return { source in
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
}
} | 31.055556 | 138 | 0.644603 |
fb76f3bccb29b373c695f4ba220dbdf571cdae3d | 511 | //
// UIView+Extension.swift
// DeDaoSwift
//
// Created by niuting on 2017/3/7.
// Copyright © 2017年 niuNaruto. All rights reserved.
//
import Foundation
extension UIView {
/// The screen size
class var size: CGSize {
return UIScreen.main.bounds.size
}
/// The screen's width
class var screenWidth: CGFloat {
return UIView.size.width
}
/// The screen's height
class var screenHeight: CGFloat {
return UIView.size.height
}
}
| 17.62069 | 53 | 0.608611 |
0910a91870fa87a90381c234bd5661d986b99847 | 351 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// rdar://16726530
// REQUIRES: objc_interop
import Foundation
// Test overlain variadic methods.
let s = NSPredicate(format: "(lastName like[cd] %@) AND (birthday > %@)", "LLLL", "BBBB")
print(s.predicateFormat)
// CHECK: lastName LIKE[cd] "LLLL" AND birthday > "BBBB"
| 25.071429 | 89 | 0.695157 |
03419aea2444b1946ea78935f4af756febc00961 | 76 |
import PackageDescription
let package = Package(
name: "Fractional"
)
| 10.857143 | 25 | 0.723684 |
abf475cdd391ee6bafad0f72fcce082b07432c9a | 953 | //
// Created by Nityananda on 28.01.21.
//
import Apodini
/// A `Configuration` for the protocol buffer coding strategy of `FixedWidthInteger`s that depend on
/// the target architecture.
///
/// - **Example:**
/// Using `IntegerWidthConfiguration.thirtyTwo` on a 64-bit architecture limits the
/// encoding and decoding of `Int`s and `UInts` to `Int32` and `UInt32`, respectively.
/// Disregarding their `.bitWidth` of 64.
///
/// The `.proto` file of the web service will only contain `int32` and `uint32` as well.
///
/// We assume only the most common architectures, 32 and 64-bit.
public enum IntegerWidthConfiguration: Int {
case thirtyTwo = 32
case sixtyFour = 64
/// `.native` is derived from the target's underlying architecture.
public static let native: Self = {
if MemoryLayout<Int>.size == 4 {
return .thirtyTwo
} else {
return .sixtyFour
}
}()
}
| 30.741935 | 100 | 0.64638 |
29f093f548a6151ae885d11b87b6bad81f2c06dc | 592 | //
// UserDefaults+Extension.swift
// RVNav
//
// Created by Jake Connerly on 12/18/19.
// Copyright © 2019 RVNav. All rights reserved.
//
import Foundation
extension UserDefaults {
static func isFirstLaunch() -> Bool {
let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
if (isFirstLaunch) {
UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
UserDefaults.standard.synchronize()
}
return isFirstLaunch
}
}
| 26.909091 | 90 | 0.685811 |
0828eed8d35474e0df4cfa56323f2ff287a98c38 | 1,674 | //
// MakeCustomTextToSend.swift
// FanapPodAsyncSDK
//
// Created by Mahyar Zhiani on 3/22/1398 AP.
// Copyright © 1398 Mahyar Zhiani. All rights reserved.
//
import Foundation
import SwiftyJSON
open class MakeCustomTextToSend {
let textMessage: String
public init(message: String) {
self.textMessage = message
}
/*
it's all about this 3 characters: 'space' , '\n', '\t'
this function will put some freak characters instead of these 3 characters (inside the Message text content)
because later on, the Async will eliminate from all these kind of characters to reduce size of the message that goes through socket,
on there, we will replace them with the original one;
so now we don't miss any of these 3 characters on the Test Message, but also can eliminate all extra characters...
*/
public func replaceSpaceEnterWithSpecificCharecters() -> String {
var returnStr = ""
for c in textMessage {
if (c == " ") {
returnStr.append("Ⓢ")
} else {
returnStr.append(c)
}
}
return returnStr
}
public func removeSpecificCharectersWithSpace() -> String {
let compressedStr = String(textMessage.filter { !" ".contains($0) })
let strWithSpace = compressedStr.replacingOccurrences(of: "Ⓢ", with: " ")
return strWithSpace
}
}
extension JSON {
public func toString() -> String? {
return self.rawString()?.replacingOccurrences(of: "\\s", with: "", options: String.CompareOptions.regularExpression, range: nil)
}
}
| 26.571429 | 137 | 0.623656 |
16891e81d180e75fd41c752f67acf9fb3151ce9c | 6,682 | //
// ImportMnemonicController.swift
// AelfApp
//
// Created by 晋先森 on 2019/5/31.
// Copyright © 2019 AELF. All rights reserved.
//
import UIKit
import Hero
import JXSegmentedView
/// 通过 助记词 导入钱包
class ImportPrivateKeyController: BaseController {
@IBOutlet weak var menmonicTextView: UITextView!
@IBOutlet weak var pwdField: UITextField!
@IBOutlet weak var confirmPwdField: UITextField!
@IBOutlet weak var hintField: UITextField!
@IBOutlet weak var agreeButton: UIButton!
@IBOutlet weak var serverProtocolButton: UIButton!
@IBOutlet weak var importButton: UIButton!
@IBOutlet weak var pwdInfoLabel: UILabel!
var parentVC: ImportContentController?
let viewModel = ImportMnemonicViewModel()
override func viewDidLoad() {
super.viewDidLoad()
#if DEBUG
// menmonicTextView.text = "main case speed hint similar maze fish benefit oppose adapt hollow subway"
menmonicTextView.text = "4c02c6f538d68a77f3f0e7ef980fbe5548ec50836e81fb4891b67ba38c76069a"
pwdField.text = "111111111aA!"
confirmPwdField.text = "111111111aA!"
hintField.text = "auto"
#endif
menmonicTextView.placeholder = "Input privatekey".localized()
importButton.hero.id = "importID"
bindImportViewModel()
}
override func languageChanged() {
pwdField.placeholder = "%d-%d characters password".localizedFormat(pwdLengthMin,pwdLengthMax)
confirmPwdField.placeholder = "Please confirm your password".localized()
hintField.placeholder = "Password hints (Optional)".localized()
pwdInfoLabel.text = "please enter %d-%d characters password rule".localizedFormat(pwdLengthMin,pwdLengthMax)
}
func bindImportViewModel() {
menmonicTextView.rx.text.orEmpty//.map{ $0.setMnemonicFormatter() }
.bind(to: menmonicTextView.rx.text).disposed(by: rx.disposeBag)
pwdField.rx.text.orEmpty.map({ $0[0..<pwdLengthMax]})
.bind(to: pwdField.rx.text).disposed(by: rx.disposeBag)
confirmPwdField.rx.text.orEmpty.map({ $0[0..<pwdLengthMax]})
.bind(to: confirmPwdField.rx.text).disposed(by: rx.disposeBag)
hintField.rx.text.orEmpty.map({ $0[0..<WalletInputLimit.hintRange.upperBound - 1]})
.bind(to: hintField.rx.text).disposed(by: rx.disposeBag)
let input = ImportMnemonicViewModel.Input(pwd: pwdField.asDriver(),
confirmPwd: confirmPwdField.asDriver(),
importTrigger: importButton.rx.tap.asDriver())
let output = viewModel.transform(input: input)
output.result.asObservable().subscribe(onNext: { (v) in
SVProgressHUD.showInfo(withStatus: v.message)
}).disposed(by: rx.disposeBag)
output.verifyOK.subscribe(onNext: { [weak self] v in
self?.importWalletHandler()
}).disposed(by: rx.disposeBag)
}
func transitionEyeButton(_ button: UIButton) {
UIView.transition(with: button,
duration: 0.5,
options: .transitionCrossDissolve,
animations: { button.isSelected = !button.isSelected },
completion: nil)
}
@IBAction func eyeButton2Tapped(_ sender: UIButton) {
pwdField.isSecureTextEntry = !pwdField.isSecureTextEntry
transitionEyeButton(sender)
}
// 隐私模式
@IBAction func eyeButtonTapped(_ sender: UIButton) {
confirmPwdField.isSecureTextEntry = !confirmPwdField.isSecureTextEntry
transitionEyeButton(sender)
}
// 查看用户服务协议
@IBAction func serverButtonTapped(_ sender: UIButton) {
parentVC?.push(controller: WebViewController.termsOfService())
}
// 同意协议
@IBAction func agreeButtonTapped(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
func importWalletHandler() {
view.endEditing(true)
if !agreeButton.isSelected {
SVProgressHUD.showInfo(withStatus: "Please read and agree".localized())
return
}
let privateKey = menmonicTextView.text.setMnemonicFormatter()
let pwd = pwdField.text ?? ""
let hint = hintField.text ?? ""
if privateKey.count == 0 {
} else {
let loadingView = WalletLoadingView.loadView(type: .importWallet)
loadingView.show()
AElfWallet.createPrivateKeyWallet(privateKey: privateKey,
pwd: pwd,
hint: hint,
name: Define.defaultChainID,
callback: { [weak self] (created, wallet) in
if created {
App.isPrivateKeyImport = true;
self?.importedHandler(address: wallet?.address,loadingView: loadingView)
} else {
SVProgressHUD.showInfo(withStatus: "Import failed".localized())
loadingView.dismiss()
}
})
}
}
func importedHandler(address: String?,loadingView: WalletLoadingView) {
guard let address = address else { return }
AElfWallet.isBackup = true
let deviceId = UserDefaults.standard.string(forKey: "deviceId") ?? ""
if (deviceId.length > 0) {
viewModel.uploadDeviceInfo(address: address,
deviceId: deviceId).subscribe(onNext: { result in
logDebug("updateDeviceToken:\(result)")
}).disposed(by: rx.disposeBag)
}
viewModel.bindDefaultAsset(address: address).subscribe(onNext: { result in
// 返回结果不影响进入首页
}).disposed(by: rx.disposeBag)
asyncMainDelay(duration: 1, block: {
loadingView.dismiss() //
BaseTableBarController.resetRootController() // 重置 TabBar
})
}
}
extension ImportPrivateKeyController: JXSegmentedListContainerViewListDelegate {
func listView() -> UIView {
return view
}
}
| 38.182857 | 124 | 0.569141 |
464686cd4f5e8285bb24e30f977a95de49b5000e | 1,693 | //
// ChannelInfoUserCell.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 10/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
struct ChannelInfoUserCellData: ChannelInfoCellDataProtocol {
let cellType = ChannelInfoUserCell.self
var user: User?
}
class ChannelInfoUserCell: UITableViewCell, ChannelInfoCellProtocol {
typealias DataType = ChannelInfoUserCellData
static let identifier = "kChannelInfoCellUser"
static let defaultHeight: Float = 292
var data: DataType? {
didSet {
// labelTitle.text = data?.user?.username
// labelSubtitle.text = data?.user?.name
avatarView.user = data?.user
}
}
@IBOutlet weak var avatarViewContainer: UIView! {
didSet {
if let avatarView = AvatarView.instantiateFromNib() {
avatarView.frame = avatarViewContainer.bounds
avatarViewContainer.layer.cornerRadius = 4
avatarViewContainer.layer.masksToBounds = true
avatarViewContainer.layer.borderWidth = 5
avatarViewContainer.layer.borderColor = UIColor.white.cgColor
avatarViewContainer.addSubview(avatarView)
self.avatarView = avatarView
}
}
}
weak var avatarView: AvatarView! {
didSet {
avatarView.layer.cornerRadius = 4
// avatarView.layer.masksToBounds = true
avatarView.layer.borderWidth = 5
avatarView.layer.borderColor = UIColor.white.cgColor
}
}
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelSubtitle: UILabel!
}
| 30.781818 | 77 | 0.643828 |
7afe1e770d7582ee5dfa4061b14234798f753322 | 5,091 | //
// ViewController.swift
// MahJongCalculator
//
// Created by Fuke Masaki on 2020/02/13.
// Copyright © 2020 Fuke Masaki. All rights reserved.
//
import UIKit
final class ViewController: UIViewController {
private var fuCalculator: FuCalculator = .default {
didSet { calc.fu = fuCalculator.score }
}
private var calc = PaymentCalculator(han: 1, fu: FuCalculator.default.score, role: .parent, counters: 0) {
didSet { updateScore() }
}
@IBOutlet weak var countersLabel: UILabel!
@IBOutlet weak var countersStepper: UIStepper!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var winningTypeControl: UISegmentedControl!
@IBOutlet var segmentedControls: [UISegmentedControl]!
@IBOutlet var switchControls: [UISwitch]!
@IBOutlet weak var hanStepper: UIStepper!
@IBOutlet weak var hanLabel: UILabel!
@IBOutlet weak var mentsuStackView: UIStackView!
private var isMentsuEditable: Bool = true {
didSet {
mentsuStackView.isUserInteractionEnabled = isMentsuEditable
mentsuStackView.alpha = isMentsuEditable ? 1 : 0.5
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateScore()
applyDarkForNonDarkModeOS()
}
@IBAction private func reset(_ sender: Any) {
calc.counters = 0
countersStepper.value = 0
calc.han = 1
hanStepper.value = 1
calc.role = .parent
fuCalculator = .default
segmentedControls.forEach({ $0.selectedSegmentIndex = 0 })
switchControls.forEach({ $0.isOn = false })
updateControlState()
}
@IBAction private func countersChanged(_ sender: UIStepper) {
calc.counters = Int(sender.value)
}
@IBAction private func roleChanged(_ sender: UISegmentedControl) {
calc.role = sender.selectedSegmentIndex == 0 ? .parent : .child
}
@IBAction func exceptionTypeChanged(_ sender: UISegmentedControl) {
fuCalculator.exceptionType = FuCalculator.ExceptionType.allCases[sender.selectedSegmentIndex]
updateControlState()
}
@IBAction private func winningTypeChanged(_ sender: UISegmentedControl) {
fuCalculator.winningType = FuCalculator.WinningType.allCases[sender.selectedSegmentIndex]
}
@IBAction private func hanChanged(_ sender: UIStepper) {
calc.han = Int(sender.value)
}
@IBAction private func headTypeChanged(_ sender: UISegmentedControl) {
fuCalculator.headType = sender.selectedSegmentIndex == 0 ? .numbers : .charactors
}
@IBAction private func waitingChanged(_ sender: UISegmentedControl) {
fuCalculator.waitingType = FuCalculator.WaitingType.allCases[sender.selectedSegmentIndex]
}
@IBAction private func setsTypeChaged(_ sender: UISegmentedControl) {
let index = sender.tag
fuCalculator.sets[index].type = FuCalculator.JongSet.SetType.allCases[sender.selectedSegmentIndex]
}
@IBAction private func secretChanged(_ sender: UISwitch) {
let index = sender.tag
fuCalculator.sets[index].isSecret = !sender.isOn
}
@IBAction private func edgeOrCharactorsChanged(_ sender: UISwitch) {
let index = sender.tag
fuCalculator.sets[index].isEdgeOrCharactors = sender.isOn
}
private func updateScore() {
let payment = fuCalculator.winningType == .tsumo ? calc.paymentForTsumo : calc.paymentForRon
scoreLabel.text = "\(calc.fu)符\(calc.han)飜 \(payment)"
hanLabel.text = "\(calc.han)飜:"
countersLabel.text = "\(calc.counters)本場"
}
private func updateControlState() {
if fuCalculator.exceptionType == .none {
isMentsuEditable = true
hanStepper.minimumValue = 1
}
else {
calc.han = max(2, calc.han)
hanStepper.minimumValue = 2
isMentsuEditable = false
}
hanStepper.value = Double(calc.han)
if fuCalculator.exceptionType == .pinfuTsumo {
fuCalculator.winningType = .tsumo
winningTypeControl.selectedSegmentIndex = 0
(0..<winningTypeControl.numberOfSegments).forEach {
winningTypeControl.setEnabled($0 == 0, forSegmentAt: $0)
}
}
else {
(0..<winningTypeControl.numberOfSegments).forEach {
winningTypeControl.setEnabled(true, forSegmentAt: $0)
}
}
}
private func applyDarkForNonDarkModeOS() {
if #available(iOS 13, *) { return }
navigationController?.navigationBar.barStyle = .black
view.backgroundColor = .black
view.tintColor = .white
view.allViews(of: UILabel.self).forEach({ $0.textColor = .white })
}
}
extension UIView {
func allViews<T: UIView>(of type: T.Type) -> [T] {
if let view = self as? T {
return [view]
}
else {
return subviews.flatMap({ $0.allViews(of: type) })
}
}
}
| 33.493421 | 110 | 0.638185 |
39c0fa7440f84bb0e346dca1c37b7e6e9c39197a | 2,166 | //
// MainTabBarController.swift
// QueuedMusic
//
// Created by Micky on 2/7/17.
// Copyright © 2017 Red Shepard LLC. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
var lastSelect: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
let checkInViewController = storyboard?.instantiateViewController(withIdentifier: "CheckInViewController") as! CheckInViewController
let navController = UINavigationController(rootViewController: checkInViewController)
present(navController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MainTabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let rootViewController = (viewController as! UINavigationController).viewControllers.first
if UserDataModel.shared.currentUser() == nil && !(rootViewController is HomeViewController) {
let alertView = AlertView(title: "Warning", message: "You must sign in to view this content", okButtonTitle: "Login", cancelButtonTitle: "Cancel")
alertView.delegate = self
present(customModalViewController: alertView, centerYOffset: 0)
return false
}
return true
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let rootViewController = (viewController as! UINavigationController).viewControllers.first
if rootViewController is HomeViewController && rootViewController == lastSelect {
NotificationCenter.default.post(name: .homeReselectedNotification, object: nil)
}
lastSelect = rootViewController
}
}
extension MainTabBarController: AlertViewDelegate {
func onOkButtonClicked() {
_ = navigationController?.popToRootViewController(animated: true)
}
}
| 37.344828 | 158 | 0.717452 |
69b140a71e603db0bd9809a80edcd4bb7ea2dd9d | 1,100 | //
// RxSwiftReachabilityBackgroundColorDemoTests.swift
// RxSwiftReachabilityBackgroundColorDemoTests
//
// Created by Pepas Personal on 11/22/15.
// Copyright © 2015 Pepas Labs. All rights reserved.
//
import XCTest
@testable import RxSwiftReachabilityBackgroundColorDemo
class RxSwiftReachabilityBackgroundColorDemoTests: 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 29.72973 | 111 | 0.675455 |
9c30e67889ac25474c7618d811f255dcef9cd204 | 1,341 |
//
// StyleDictionary.swift
//
// Do not edit directly
// Generated on Thu, 14 May 2020 19:51:53 GMT
//
import UIKit
public class StyleDictionary {
public static let colorSolidDark = UIColor(red: 0.298, green: 0.294, blue: 0.369, alpha:1)
public static let colorSolidError = UIColor(red: 0.851, green: 0.341, blue: 0.341, alpha:1)
public static let colorSolidExtraLight = UIColor(red: 0.949, green: 0.949, blue: 0.976, alpha:1)
public static let colorSolidLight = UIColor(red: 0.780, green: 0.780, blue: 0.831, alpha:1)
public static let colorSolidMedium = UIColor(red: 0.624, green: 0.624, blue: 0.686, alpha:1)
public static let colorSolidPrimary = UIColor(red: 0.000, green: 0.639, blue: 0.878, alpha:1)
public static let colorSolidSecondary = UIColor(red: 0.200, green: 0.247, blue: 0.282, alpha:1)
public static let colorSolidSuccess = UIColor(red: 0.502, green: 0.863, blue: 0.561, alpha:1)
public static let colorSolidWarning = UIColor(red: 1.000, green: 0.820, blue: 0.439, alpha:1)
public static let colorSolidWhite = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha:1)
public static let sizeFontBase = CGFloat(16.00)
public static let sizeFontLarge = CGFloat(32.00)
public static let sizeFontMedium = CGFloat(16.00)
public static let sizeFontSmall = CGFloat(12.00)
}
| 47.892857 | 100 | 0.706189 |
d6c83855715a2b30b70edcba43be031f2b67f7ea | 43 | import Foundation
protocol Presenter {
}
| 7.166667 | 20 | 0.767442 |
1e5798d324eb47a7a970b214f5c05673f0a574e0 | 3,862 | //
// Board.swift
// Sudoku
//
// Created by Cameron Francis on 2017-09-14.
// Copyright © 2017 Cameron Francis. All rights reserved.
//
// This data model represents a 9x9 Sudoku board.
// It implements methods for interfacing with the board,
// like getting different rows, columns, and regions.
import UIKit
import Foundation
struct PropertyKey{
static let boardArray = "boardArray"
static let permanents = "permanents"
}
final class Board : NSObject, NSCoding {
let width = 9
var totalItems : Int {
return (width * width)
}
var boardArray : [Int?]
var permanents : [Int : Int] // Index, Value
required init?(coder aDecoder: NSCoder) {
guard let boardArray = aDecoder.decodeObject(forKey: PropertyKey.boardArray) as? [Int?],
let permanents = aDecoder.decodeObject(forKey: PropertyKey.permanents) as? [Int : Int] else {
print("Failed to resture board state from save.")
return nil
}
self.boardArray = boardArray
self.permanents = permanents
}
override init() {
boardArray = [Int?]()
permanents = [Int : Int]()
super.init()
for _ in 0..<totalItems {
boardArray.append(nil)
}
}
init(initArray : [Int?]) {
boardArray = [Int?]()
permanents = [Int : Int]()
super.init()
if(initArray.count > totalItems) {
assert(false, "Can't pass \(initArray.count) items to board with total size \(totalItems)")
}
boardArray.append(contentsOf: initArray)
for _ in 0..<(totalItems - initArray.count) {
boardArray.append(nil)
}
// Automatically set board permanents when any board is generated.
BoardMethods.setBoardPermanents(self)
}
}
// NSCoding
extension Board {
func encode(with aCoder: NSCoder) {
aCoder.encode(boardArray, forKey: PropertyKey.boardArray)
aCoder.encode(permanents, forKey: PropertyKey.permanents)
}
}
// Board model methods
extension Board {
private func at(_ x : Int, _ y : Int) -> Int? {
guard x < boardArray.count
&& x >= 0
&& y < boardArray.count
&& y >= 0 else {
return nil
}
return boardArray[x * (y + 1)]
}
subscript(_ x: Int, _ y: Int) -> Int?{
return self.at(x, y)
}
func row(_ at : Int) -> [Int?] {
let indices = (at * width)..<((at + 1) * width)
return Array(boardArray[indices])
}
func column(_ at : Int) -> [Int?] {
var out = [Int?]()
for row in 0..<width {
out.append(boardArray[row * width + at])
}
return out
}
func region(_ at : Int) -> [Int?] {
assert(width == 9, "Only implemented for normal-sized boards.")
let baseX = (at % 3) * 3
let baseY = Int(floor(Double(at) / 3)) * 3
var out = [Int?]()
for y in 0..<3 {
for x in 0..<3 {
let index = (baseY + y) * width + baseX + x
out.append(boardArray[index])
}
}
return out
}
func getRowColRegion(from index : Int) -> (row : Int, column : Int, region : Int) {
return (
row : index % 9,
column : index / 9,
region : ((index / 9) / 3) * 3 + ((index % 9) / 3)
)
}
func boardDescription() -> String {
var out = ""
for index in 0..<totalItems {
if let x = boardArray[index] {
out.append(String(describing : x) + ",")
} else {
out.append(" ")
}
if(index % width == width - 1) {
out.append("\n")
}
}
return out
}
}
| 27.197183 | 105 | 0.521491 |
3929fe331d3e5c85891fb8e48d2d2919f35994db | 9,353 | // Generated using Sourcery 1.0.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
extension AssociatedValuesEnum {
internal init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let enumCase = try container.decode(String.self, forKey: .enumCaseKey)
switch enumCase {
case CodingKeys.someCase.rawValue:
let id = try container.decode(Int.self, forKey: .id)
let name = try container.decode(String.self, forKey: .name)
self = .someCase(id: id, name: name)
case CodingKeys.unnamedCase.rawValue:
// Enum cases with unnamed associated values can't be decoded
throw DecodingError.dataCorruptedError(forKey: .enumCaseKey, in: container, debugDescription: "Can't decode '\(enumCase)'")
case CodingKeys.mixCase.rawValue:
// Enum cases with mixed named and unnamed associated values can't be decoded
throw DecodingError.dataCorruptedError(forKey: .enumCaseKey, in: container, debugDescription: "Can't decode '\(enumCase)'")
case CodingKeys.anotherCase.rawValue:
self = .anotherCase
default:
throw DecodingError.dataCorruptedError(forKey: .enumCaseKey, in: container, debugDescription: "Unknown enum case '\(enumCase)'")
}
}
internal func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .someCase(id, name):
try container.encode(CodingKeys.someCase.rawValue, forKey: .enumCaseKey)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
case .unnamedCase:
// Enum cases with unnamed associated values can't be encoded
throw EncodingError.invalidValue(self, .init(codingPath: encoder.codingPath, debugDescription: "Can't encode '\(self)'"))
case .mixCase:
// Enum cases with mixed named and unnamed associated values can't be encoded
throw EncodingError.invalidValue(self, .init(codingPath: encoder.codingPath, debugDescription: "Can't encode '\(self)'"))
case .anotherCase:
try container.encode(CodingKeys.anotherCase.rawValue, forKey: .enumCaseKey)
}
}
}
extension AssociatedValuesEnumNoCaseKey {
enum CodingKeys: String, CodingKey {
case someCase
case unnamedCase
case mixCase
case anotherCase
case id
case name
}
internal init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.allKeys.contains(.someCase), try container.decodeNil(forKey: .someCase) == false {
let associatedValues = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .someCase)
let id = try associatedValues.decode(Int.self, forKey: .id)
let name = try associatedValues.decode(String.self, forKey: .name)
self = .someCase(id: id, name: name)
return
}
if container.allKeys.contains(.unnamedCase), try container.decodeNil(forKey: .unnamedCase) == false {
var associatedValues = try container.nestedUnkeyedContainer(forKey: .unnamedCase)
let associatedValue0 = try associatedValues.decode(Int.self)
let associatedValue1 = try associatedValues.decode(String.self)
self = .unnamedCase(associatedValue0, associatedValue1)
return
}
if container.allKeys.contains(.mixCase), try container.decodeNil(forKey: .mixCase) == false {
// Enum cases with mixed named and unnamed associated values can't be decoded
throw DecodingError.dataCorruptedError(forKey: .mixCase, in: container, debugDescription: "Can't decode `.mixCase`")
}
if container.allKeys.contains(.anotherCase), try container.decodeNil(forKey: .anotherCase) == false {
self = .anotherCase
return
}
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Unknown enum case"))
}
internal func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .someCase(id, name):
var associatedValues = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .someCase)
try associatedValues.encode(id, forKey: .id)
try associatedValues.encode(name, forKey: .name)
case let .unnamedCase(associatedValue0, associatedValue1):
var associatedValues = container.nestedUnkeyedContainer(forKey: .unnamedCase)
try associatedValues.encode(associatedValue0)
try associatedValues.encode(associatedValue1)
case .mixCase:
// Enum cases with mixed named and unnamed associated values can't be encoded
throw EncodingError.invalidValue(self, .init(codingPath: encoder.codingPath, debugDescription: "Can't encode '\(self)'"))
case .anotherCase:
_ = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .anotherCase)
}
}
}
extension CustomCodingWithNotAllDefinedKeys {
internal init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = try container.decode(Int.self, forKey: .value)
}
internal func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
encodeComputedValue(to: &container)
}
}
extension CustomContainerCodable {
public init(from decoder: Decoder) throws {
let container = try CustomContainerCodable.decodingContainer(decoder)
value = try container.decode(Int.self, forKey: .value)
}
public func encode(to encoder: Encoder) throws {
var container = encodingContainer(encoder)
try container.encode(value, forKey: .value)
}
}
extension CustomMethodsCodable {
enum CodingKeys: String, CodingKey {
case boolValue
case intValue
case optionalString
case requiredString
case requiredStringWithDefault
case computedPropertyToEncode
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
boolValue = try CustomMethodsCodable.decodeBoolValue(from: decoder)
intValue = CustomMethodsCodable.decodeIntValue(from: container) ?? CustomMethodsCodable.defaultIntValue
optionalString = try container.decodeIfPresent(String.self, forKey: .optionalString)
requiredString = try container.decode(String.self, forKey: .requiredString)
requiredStringWithDefault = (try? container.decode(String.self, forKey: .requiredStringWithDefault)) ?? CustomMethodsCodable.defaultRequiredStringWithDefault
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try encodeBoolValue(to: encoder)
encodeIntValue(to: &container)
try container.encodeIfPresent(optionalString, forKey: .optionalString)
try container.encode(requiredString, forKey: .requiredString)
try container.encode(requiredStringWithDefault, forKey: .requiredStringWithDefault)
encodeComputedPropertyToEncode(to: &container)
try encodeAdditionalValues(to: encoder)
}
}
extension SimpleEnum {
enum CodingKeys: String, CodingKey {
case someCase
case anotherCase
}
internal init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let enumCase = try container.decode(String.self)
switch enumCase {
case CodingKeys.someCase.rawValue: self = .someCase
case CodingKeys.anotherCase.rawValue: self = .anotherCase
default: throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Unknown enum case '\(enumCase)'"))
}
}
internal func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .someCase: try container.encode(CodingKeys.someCase.rawValue)
case .anotherCase: try container.encode(CodingKeys.anotherCase.rawValue)
}
}
}
extension SkipDecodingWithDefaultValueOrComputedProperty {
internal init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = try container.decode(Int.self, forKey: .value)
}
internal func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
try container.encode(computedValue, forKey: .computedValue)
}
}
extension SkipEncodingKeys {
enum CodingKeys: String, CodingKey {
case value
case skipValue
}
internal func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
}
}
| 38.489712 | 165 | 0.680744 |
7189310e6d32f87ceb1f2962a8c166275f71a310 | 37,633 | //
// LineChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class LineChartRenderer: LineRadarRenderer
{
// TODO: Currently, this nesting isn't necessary for LineCharts. However, it will make it much easier to add a custom rotor
// that navigates between datasets.
// NOTE: Unlike the other renderers, LineChartRenderer populates accessibleChartElements in drawCircles due to the nature of its drawing options.
/// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver.
private lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements()
@objc open weak var dataProvider: LineChartDataProvider?
@objc public init(dataProvider: LineChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let lineData = dataProvider?.lineData else { return }
let sets = lineData.dataSets as? [LineChartDataSet]
assert(sets != nil, "Datasets for LineChartRenderer must conform to ILineChartDataSet")
let drawDataSet = { self.drawDataSet(context: context, dataSet: $0) }
sets!.lazy
.filter(\.isVisible)
.forEach(drawDataSet)
}
@objc open func drawDataSet(context: CGContext, dataSet: LineChartDataSetProtocol)
{
if dataSet.entryCount < 1
{
return
}
context.saveGState()
context.setLineWidth(dataSet.lineWidth)
if dataSet.lineDashLengths != nil
{
context.setLineDash(phase: dataSet.lineDashPhase, lengths: dataSet.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setLineCap(dataSet.lineCapType)
// if drawing cubic lines is enabled
switch dataSet.mode
{
case .linear: fallthrough
case .stepped:
drawLinear(context: context, dataSet: dataSet)
case .cubicBezier:
drawCubicBezier(context: context, dataSet: dataSet)
case .horizontalBezier:
drawHorizontalBezier(context: context, dataSet: dataSet)
}
context.restoreGState()
}
private func drawLine(
context: CGContext,
spline: CGMutablePath,
drawingColor: NSUIColor)
{
context.beginPath()
context.addPath(spline)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()
}
@objc open func drawCubicBezier(context: CGContext, dataSet: LineChartDataSetProtocol)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
let intensity = dataSet.cubicIntensity
// the path for the cubic-spline
let cubicPath = CGMutablePath()
let valueToPixelMatrix = trans.valueToPixelMatrix
if _xBounds.range >= 1
{
var prevDx: CGFloat = 0.0
var prevDy: CGFloat = 0.0
var curDx: CGFloat = 0.0
var curDy: CGFloat = 0.0
// Take an extra point from the left, and an extra from the right.
// That's because we need 4 points for a cubic bezier (cubic=4), otherwise we get lines moving and doing weird stuff on the edges of the chart.
// So in the starting `prev` and `cur`, go -2, -1
let firstIndex = _xBounds.min + 1
var prevPrev: ChartDataEntry! = nil
var prev: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 2, 0))
var cur: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 1, 0))
var next: ChartDataEntry! = cur
var nextIndex: Int = -1
if cur == nil { return }
// let the spline start
cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix)
for j in _xBounds.dropFirst() // same as firstIndex
{
prevPrev = prev
prev = cur
cur = nextIndex == j ? next : dataSet.entryForIndex(j)
nextIndex = j + 1 < dataSet.entryCount ? j + 1 : j
next = dataSet.entryForIndex(nextIndex)
if next == nil { break }
prevDx = CGFloat(cur.x - prevPrev.x) * intensity
prevDy = CGFloat(cur.y - prevPrev.y) * intensity
curDx = CGFloat(next.x - prev.x) * intensity
curDy = CGFloat(next.y - prev.y) * intensity
cubicPath.addCurve(
to: CGPoint(
x: CGFloat(cur.x),
y: CGFloat(cur.y) * CGFloat(phaseY)),
control1: CGPoint(
x: CGFloat(prev.x) + prevDx,
y: (CGFloat(prev.y) + prevDy) * CGFloat(phaseY)),
control2: CGPoint(
x: CGFloat(cur.x) - curDx,
y: (CGFloat(cur.y) - curDy) * CGFloat(phaseY)),
transform: valueToPixelMatrix)
}
}
context.saveGState()
defer { context.restoreGState() }
if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()
drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}
if dataSet.isDrawLineWithGradientEnabled
{
drawGradientLine(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix)
}
else
{
drawLine(context: context, spline: cubicPath, drawingColor: drawingColor)
}
}
@objc open func drawHorizontalBezier(context: CGContext, dataSet: LineChartDataSetProtocol)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
// the path for the cubic-spline
let cubicPath = CGMutablePath()
let valueToPixelMatrix = trans.valueToPixelMatrix
if _xBounds.range >= 1
{
var prev: ChartDataEntry! = dataSet.entryForIndex(_xBounds.min)
var cur: ChartDataEntry! = prev
if cur == nil { return }
// let the spline start
cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix)
for j in _xBounds.dropFirst()
{
prev = cur
cur = dataSet.entryForIndex(j)
let cpx = CGFloat(prev.x + (cur.x - prev.x) / 2.0)
cubicPath.addCurve(
to: CGPoint(
x: CGFloat(cur.x),
y: CGFloat(cur.y * phaseY)),
control1: CGPoint(
x: cpx,
y: CGFloat(prev.y * phaseY)),
control2: CGPoint(
x: cpx,
y: CGFloat(cur.y * phaseY)),
transform: valueToPixelMatrix)
}
}
context.saveGState()
defer { context.restoreGState() }
if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()
drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}
if dataSet.isDrawLineWithGradientEnabled
{
drawGradientLine(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix)
}
else
{
drawLine(context: context, spline: cubicPath, drawingColor: drawingColor)
}
}
open func drawCubicFill(
context: CGContext,
dataSet: LineChartDataSetProtocol,
spline: CGMutablePath,
matrix: CGAffineTransform,
bounds: XBounds)
{
guard
let dataProvider = dataProvider
else { return }
if bounds.range <= 0
{
return
}
let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0
var pt1 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min + bounds.range)?.x ?? 0.0), y: fillMin)
var pt2 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min)?.x ?? 0.0), y: fillMin)
pt1 = pt1.applying(matrix)
pt2 = pt2.applying(matrix)
spline.addLine(to: pt1)
spline.addLine(to: pt2)
spline.closeSubpath()
if dataSet.fill != nil
{
drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawLinear(context: CGContext, dataSet: LineChartDataSetProtocol)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let entryCount = dataSet.entryCount
let isDrawSteppedEnabled = dataSet.mode == .stepped
let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// if drawing filled is enabled
if dataSet.isDrawFilledEnabled && entryCount > 0
{
drawLinearFill(context: context, dataSet: dataSet, trans: trans, bounds: _xBounds)
}
context.saveGState()
defer { context.restoreGState() }
// more than 1 color
if dataSet.colors.count > 1, !dataSet.isDrawLineWithGradientEnabled
{
if _lineSegments.count != pointsPerEntryPair
{
// Allocate once in correct size
_lineSegments = [CGPoint](repeating: CGPoint(), count: pointsPerEntryPair)
}
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
var e: ChartDataEntry! = dataSet.entryForIndex(j)
if e == nil { continue }
_lineSegments[0].x = CGFloat(e.x)
_lineSegments[0].y = CGFloat(e.y * phaseY)
if j < _xBounds.max
{
// TODO: remove the check.
// With the new XBounds iterator, j is always smaller than _xBounds.max
// Keeping this check for a while, if xBounds have no further breaking changes, it should be safe to remove the check
e = dataSet.entryForIndex(j + 1)
if e == nil { break }
if isDrawSteppedEnabled
{
_lineSegments[1] = CGPoint(x: CGFloat(e.x), y: _lineSegments[0].y)
_lineSegments[2] = _lineSegments[1]
_lineSegments[3] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY))
}
else
{
_lineSegments[1] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY))
}
}
else
{
_lineSegments[1] = _lineSegments[0]
}
_lineSegments = _lineSegments.map { $0.applying(valueToPixelMatrix) }
if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x))
{
break
}
// Determine the start and end coordinates of the line, and make sure they differ.
guard
let firstCoordinate = _lineSegments.first,
let lastCoordinate = _lineSegments.last,
firstCoordinate != lastCoordinate else { continue }
// make sure the lines don't do shitty things outside bounds
if !viewPortHandler.isInBoundsLeft(lastCoordinate.x) ||
!viewPortHandler.isInBoundsTop(max(firstCoordinate.y, lastCoordinate.y)) ||
!viewPortHandler.isInBoundsBottom(min(firstCoordinate.y, lastCoordinate.y))
{
continue
}
// get the color that is set for this line-segment
context.setStrokeColor(dataSet.color(atIndex: j).cgColor)
context.strokeLineSegments(between: _lineSegments)
}
}
else
{ // only one color per dataset
var e1: ChartDataEntry!
var e2: ChartDataEntry!
e1 = dataSet.entryForIndex(_xBounds.min)
if e1 != nil
{
context.beginPath()
var firstPoint = true
var closePath = false
let path = CGMutablePath()
for x in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1))
e2 = dataSet.entryForIndex(x)
if e1 == nil || e2 == nil { continue }
let pt = CGPoint(
x: CGFloat(e1.x),
y: CGFloat(e1.y * phaseY)
).applying(valueToPixelMatrix)
if firstPoint
{
if e1.visible {
path.move(to: pt)
firstPoint = false
}else if e2.visible {
path.move(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e2.y * phaseY)
).applying(valueToPixelMatrix))
}
}
else if e1.visible
{
if closePath {
continue
}else {
path.addLine(to: pt)
}
}
if isDrawSteppedEnabled
{
path.addLine(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e1.y * phaseY)
).applying(valueToPixelMatrix))
}
if e2.visible {
if closePath {
path.move(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e2.y * phaseY)
).applying(valueToPixelMatrix))
closePath = false
}else{
path.addLine(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e2.y * phaseY)
).applying(valueToPixelMatrix))
}
}else {
closePath = true
}
}
if !firstPoint
{
if dataSet.isDrawLineWithGradientEnabled {
drawGradientLine(context: context, dataSet: dataSet, spline: path, matrix: valueToPixelMatrix)
} else {
context.beginPath()
context.addPath(path)
context.setStrokeColor(dataSet.color(atIndex: 0).cgColor)
context.strokePath()
}
}
}
}
}
open func drawLinearFill(context: CGContext, dataSet: LineChartDataSetProtocol, trans: Transformer, bounds: XBounds)
{
guard let dataProvider = dataProvider else { return }
let filled = generateFilledPath(
dataSet: dataSet,
fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0,
bounds: bounds,
matrix: trans.valueToPixelMatrix)
if dataSet.fill != nil
{
drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
/// Generates the path that is used for filled drawing.
private func generateFilledPath(dataSet: LineChartDataSetProtocol, fillMin: CGFloat, bounds: XBounds, matrix: CGAffineTransform) -> CGPath
{
let phaseY = animator.phaseY
let isDrawSteppedEnabled = dataSet.mode == .stepped
let matrix = matrix
var e: ChartDataEntry!
let filled = CGMutablePath()
var drawFirst = false
e = dataSet.entryForIndex(bounds.min)
if e != nil && e.visible
{
drawFirst = true
filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}
var currentEntry :ChartDataEntry!
var previousEntry :ChartDataEntry!
previousEntry = e
var closed = false
// create a new path
for x in stride(from: (bounds.min + 1), through: bounds.range + bounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(x) else { continue }
currentEntry = e
if(!currentEntry.visible) {
if(closed || !drawFirst){continue}
filled.addLine(to: CGPoint(x: CGFloat(previousEntry.x), y: fillMin), transform: matrix)
filled.closeSubpath()
closed = true
continue
}
else if(closed) {
closed = false
filled.move(to: CGPoint(x: CGFloat(currentEntry.x), y: fillMin), transform: matrix)
}
if isDrawSteppedEnabled
{
guard let ePrev = dataSet.entryForIndex(x-1) else { continue }
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(ePrev.y * phaseY)), transform: matrix)
}
if drawFirst {
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}else{
drawFirst = true
filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}
previousEntry = currentEntry
}
// close up
e = dataSet.entryForIndex(bounds.range + bounds.min)
if e != nil && e.visible
{
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
}
if drawFirst {
filled.closeSubpath()
}
return filled
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
let phaseY = animator.phaseY
var pt = CGPoint()
for i in lineData.indices
{
guard let
dataSet = lineData[i] as? LineChartDataSetProtocol,
shouldDrawValues(forDataSet: dataSet)
else { continue }
let valueFont = dataSet.valueFont
let formatter = dataSet.valueFormatter
let angleRadians = dataSet.valueLabelAngle.DEG2RAD
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75)
if !dataSet.isDrawCirclesEnabled
{
valOffset = valOffset / 2
}
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
for j in _xBounds
{
guard let e = dataSet.entryForIndex(j) else { break }
if !e.visible { continue }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
if dataSet.isDrawValuesEnabled
{
context.drawText(formatter.stringForValue(e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
at: CGPoint(x: pt.x,
y: pt.y - CGFloat(valOffset) - valueFont.lineHeight),
align: .center,
angleRadians: angleRadians,
attributes: [.font: valueFont,
.foregroundColor: dataSet.valueTextColorAt(j)])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
context.drawImage(icon,
atCenter: CGPoint(x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y),
size: icon.size)
}
}
}
}
}
open override func drawExtras(context: CGContext)
{
drawCircles(context: context)
}
private func drawCircles(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
let phaseY = animator.phaseY
var pt = CGPoint()
var rect = CGRect()
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements()
// Make the chart header the first element in the accessible elements array
if let chart = dataProvider as? LineChartView {
let element = createAccessibleHeader(usingChart: chart,
andData: lineData,
withDefaultDescription: "Line Chart")
accessibleChartElements.append(element)
}
context.saveGState()
for i in lineData.indices
{
guard let dataSet = lineData[i] as? LineChartDataSetProtocol else { continue }
// Skip Circles and Accessibility if not enabled,
// reduces CPU significantly if not needed
if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0
{
continue
}
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let circleRadius = dataSet.circleRadius
let circleDiameter = circleRadius * 2.0
let circleHoleRadius = dataSet.circleHoleRadius
let circleHoleDiameter = circleHoleRadius * 2.0
let drawCircleHole = dataSet.isDrawCircleHoleEnabled &&
circleHoleRadius < circleRadius &&
circleHoleRadius > 0.0
let drawTransparentCircleHole = drawCircleHole &&
(dataSet.circleHoleColor == nil ||
dataSet.circleHoleColor == NSUIColor.clear)
for j in _xBounds
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the circles don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
// Accessibility element geometry
let scaleFactor: CGFloat = 3
let accessibilityRect = CGRect(x: pt.x - (scaleFactor * circleRadius),
y: pt.y - (scaleFactor * circleRadius),
width: scaleFactor * circleDiameter,
height: scaleFactor * circleDiameter)
// Create and append the corresponding accessibility element to accessibilityOrderedElements
if let chart = dataProvider as? LineChartView
{
let element = createAccessibleElement(withIndex: j,
container: chart,
dataSet: dataSet,
dataSetIndex: i)
{ (element) in
element.accessibilityFrame = accessibilityRect
}
accessibilityOrderedElements[i].append(element)
}
context.setFillColor(dataSet.getCircleColor(atIndex: j)!.cgColor)
rect.origin.x = pt.x - circleRadius
rect.origin.y = pt.y - circleRadius
rect.size.width = circleDiameter
rect.size.height = circleDiameter
if drawTransparentCircleHole
{
// Begin path for circle with hole
context.beginPath()
context.addEllipse(in: rect)
// Cut hole in path
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
context.addEllipse(in: rect)
// Fill in-between
context.fillPath(using: .evenOdd)
}
else
{
context.fillEllipse(in: rect)
if drawCircleHole
{
context.setFillColor(dataSet.circleHoleColor!.cgColor)
// The hole rect
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
context.fillEllipse(in: rect)
}
}
}
}
context.restoreGState()
// Merge nested ordered arrays into the single accessibleChartElements.
accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 } )
accessibilityPostLayoutChangedNotification()
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
let chartXMax = dataProvider.chartXMax
context.saveGState()
for high in indices
{
guard let set = lineData[high.dataSetIndex] as? LineChartDataSetProtocol,
set.isHighlightEnabled
else { continue }
guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let x = e.x // get the x-position
let y = e.y * Double(animator.phaseY)
if x > chartXMax * animator.phaseX
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
let pt = trans.pixelForValues(x: x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
func drawGradientLine(context: CGContext, dataSet: LineChartDataSetProtocol, spline: CGPath, matrix: CGAffineTransform)
{
guard let gradientPositions = dataSet.gradientPositions else
{
assertionFailure("Must set `gradientPositions if `dataSet.isDrawLineWithGradientEnabled` is true")
return
}
// `insetBy` is applied since bounding box
// doesn't take into account line width
// so that peaks are trimmed since
// gradient start and gradient end calculated wrong
let boundingBox = spline.boundingBox
.insetBy(dx: -dataSet.lineWidth / 2, dy: -dataSet.lineWidth / 2)
guard !boundingBox.isNull, !boundingBox.isInfinite, !boundingBox.isEmpty else {
return
}
let gradientStart = CGPoint(x: 0, y: boundingBox.minY)
let gradientEnd = CGPoint(x: 0, y: boundingBox.maxY)
let gradientColorComponents: [CGFloat] = dataSet.colors
.reversed()
.reduce(into: []) { (components, color) in
guard let (r, g, b, a) = color.nsuirgba else {
return
}
components += [r, g, b, a]
}
let gradientLocations: [CGFloat] = gradientPositions.reversed()
.map { (position) in
let location = CGPoint(x: boundingBox.minX, y: position)
.applying(matrix)
let normalizedLocation = (location.y - boundingBox.minY)
/ (boundingBox.maxY - boundingBox.minY)
return normalizedLocation.clamped(to: 0...1)
}
let baseColorSpace = CGColorSpaceCreateDeviceRGB()
guard let gradient = CGGradient(
colorSpace: baseColorSpace,
colorComponents: gradientColorComponents,
locations: gradientLocations,
count: gradientLocations.count) else {
return
}
context.saveGState()
defer { context.restoreGState() }
context.beginPath()
context.addPath(spline)
context.replacePathWithStrokedPath()
context.clip()
context.drawLinearGradient(gradient, start: gradientStart, end: gradientEnd, options: [])
}
/// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements.
/// This is marked internal to support HorizontalBarChartRenderer as well.
private func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]]
{
guard let chart = dataProvider as? LineChartView else { return [] }
let dataSetCount = chart.lineData?.dataSetCount ?? 0
return Array(repeating: [NSUIAccessibilityElement](),
count: dataSetCount)
}
/// Creates an NSUIAccessibleElement representing the smallest meaningful bar of the chart
/// i.e. in case of a stacked chart, this returns each stack, not the combined bar.
/// Note that it is marked internal to support subclass modification in the HorizontalBarChart.
private func createAccessibleElement(withIndex idx: Int,
container: LineChartView,
dataSet: LineChartDataSetProtocol,
dataSetIndex: Int,
modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement
{
let element = NSUIAccessibilityElement(accessibilityContainer: container)
let xAxis = container.xAxis
guard let e = dataSet.entryForIndex(idx) else { return element }
guard let dataProvider = dataProvider else { return element }
// NOTE: The formatter can cause issues when the x-axis labels are consecutive ints.
// i.e. due to the Double conversion, if there are more than one data set that are grouped,
// there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution.
let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)"
let elementValueText = dataSet.valueFormatter.stringForValue(e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler)
let dataSetCount = dataProvider.lineData?.dataSetCount ?? -1
let doesContainMultipleDataSets = dataSetCount > 1
element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText)"
modifier(element)
return element
}
}
| 39.241919 | 155 | 0.510935 |
291f0f835e5644ffdb9d02bc0fceb382c2d936ae | 3,992 | //
// TwitterClient.swift
// TwitterDemo
//
// Created by Chris Wren on 6/1/16.
// Copyright © 2016 Chris Wren. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class TwitterClient: BDBOAuth1SessionManager {
static let sharedInstance = TwitterClient(baseURL: NSURL(string: "https://api.twitter.com"), consumerKey: "zy9jaX31Ri1gpBCv3atFFenYC", consumerSecret: "vDwW7tRaW9cWcyRITLGyNSa0Gy7QGFjhAaV8Y65jVLO3tOEHVr")
var loginFailure: ((NSError) -> ())?
var loginSuccess: (() -> ())?
func homeTimeline(success: ([Tweet]) -> (), failure: ((NSError) -> ())?) {
GET("1.1/statuses/home_timeline.json", parameters: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) in
let tweets = response as! [NSDictionary]
success(Tweet.tweetsWithArray(tweets))
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
if let failure = failure {
failure(error)
}
})
}
func mentions(success: ([Tweet]) -> (), failure: ((NSError) -> ())?) {
GET("1.1/statuses/mentions_timeline.json", parameters: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) in
let tweets = response as! [NSDictionary]
success(Tweet.tweetsWithArray(tweets))
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
if let failure = failure {
failure(error)
}
})
}
func tweet(status: String, success: (AnyObject?) -> (), failure: ((NSError) -> ())?) {
POST("1.1/statuses/update.json", parameters: ["status": status], success: { (task:NSURLSessionDataTask, response:AnyObject?) in
success(response)
}) { (task: NSURLSessionDataTask?, error: NSError) in
failure!(error)
}
}
func retweet(id: String, success: (AnyObject?) -> (), failure: ((NSError) -> ())?) {
POST("1.1/statuses/retweet/\(id).json", parameters: [], success: { (task:NSURLSessionDataTask, response:AnyObject?) in
success(response)
}) { (task: NSURLSessionDataTask?, error: NSError) in
failure!(error)
}
}
func unretweet(id: String, success: (AnyObject?) -> (), failure: ((NSError) -> ())?) {
POST("1.1/statuses/unretweet/\(id).json", parameters: [], success: { (task:NSURLSessionDataTask, response:AnyObject?) in
success(response)
}) { (task: NSURLSessionDataTask?, error: NSError) in
failure!(error)
}
}
func login (success: () -> (), error: (NSError) -> ()) {
self.loginSuccess = success
TwitterClient.sharedInstance.deauthorize()
TwitterClient.sharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "twitterdemo://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in
let url = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)")
UIApplication.sharedApplication().openURL(url!)
}, failure: { (error: (NSError!)) in
self.loginFailure?(error)
})
}
func handleOpenUrl(url: NSURL) {
let requestToken = BDBOAuth1Credential(queryString: url.query)
fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: requestToken, success: { (requestToken: BDBOAuth1Credential!) -> Void in
self.currentAccount({ (user :User) in
User.currentUser = user
self.loginSuccess?()
}, failure: { (error: NSError) in
self.loginFailure?(error)
})
self.loginSuccess?()
}, failure: { (error: (NSError!)) in
self.loginFailure?(error)
})
}
func currentAccount(success: (User) -> (), failure: (NSError) -> ()) {
GET("1.1/account/verify_credentials.json", parameters: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) in
let user = User(dictionary: response as! NSDictionary)
success(user)
}, failure: { (task: NSURLSessionDataTask?, error: NSError) in
failure(error)
})
}
}
| 38.019048 | 218 | 0.646042 |
e685398b62855cd19cd1ad0997c6328c353f675b | 2,724 | //
// SwiftUIView.swift
// Backfire
//
// Created by David Jensenius on 2021-04-18.
//
import SwiftUI
struct SettingsView: View {
@Environment(\.managedObjectContext) private var viewContext
@State private var useHealthKit = false
@State private var useBackfire = false
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Config.timestamp, ascending: false)],
animation: .default)
private var config: FetchedResults<Config>
var body: some View {
VStack {
Text("If you enable HealthKit this app will track your ride as a skating activity.")
List {
Toggle("HealthKit", isOn: $useHealthKit)
.onAppear(perform: {
configureHealthKit()
})
.onChange(of: useHealthKit, perform: { value in
updateHealth(use: value)
})
Toggle("Backfire Board", isOn: $useBackfire
)
.onAppear(perform: {
configureBackfire()
})
.onChange(of: useBackfire, perform: { value in
updateBackfire(use: value)
})
}
}.padding()
}
func updateHealth(use: Bool) {
if config.count == 0 {
let newConfig = Config(context: self.viewContext)
newConfig.useHealthKit = use
} else {
config[0].useHealthKit = use
}
do {
try self.viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved saving HealthKit \(nsError), \(nsError.userInfo)")
}
}
func configureHealthKit() {
if config.count > 0 && config[0].useHealthKit == true {
useHealthKit = true
} else {
useHealthKit = false
}
}
func updateBackfire(use: Bool) {
if config.count == 0 {
let newConfig = Config(context: self.viewContext)
newConfig.useBackfire = use
} else {
config[0].useBackfire = use
}
do {
try self.viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved saving HealthKit \(nsError), \(nsError.userInfo)")
}
}
func configureBackfire() {
if config.count > 0 && config[0].useBackfire == true {
useBackfire = true
} else {
useBackfire = false
}
}
}
/*
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
*/
| 28.082474 | 96 | 0.520558 |
7139f76a859751ca188bdb19743119adf357c47c | 1,856 | //
// ObservationDefinitionTests.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.1-9346c8cc45 on 2019-11-19.
// 2019, SMART Health IT.
//
import XCTest
#if !NO_MODEL_IMPORT
import Models
typealias SwiftFHIRObservationDefinition = Models.ObservationDefinition
#else
import SwiftFHIR
typealias SwiftFHIRObservationDefinition = SwiftFHIR.ObservationDefinition
#endif
class ObservationDefinitionTests: XCTestCase {
func instantiateFrom(filename: String) throws -> SwiftFHIRObservationDefinition {
return try instantiateFrom(json: try readJSONFile(filename))
}
func instantiateFrom(json: FHIRJSON) throws -> SwiftFHIRObservationDefinition {
return try SwiftFHIRObservationDefinition(json: json)
}
func testObservationDefinition1() {
do {
let instance = try runObservationDefinition1()
try runObservationDefinition1(instance.asJSON())
}
catch let error {
XCTAssertTrue(false, "Must instantiate and test ObservationDefinition successfully, but threw:\n---\n\(error)\n---")
}
}
@discardableResult
func runObservationDefinition1(_ json: FHIRJSON? = nil) throws -> SwiftFHIRObservationDefinition {
let inst = (nil != json) ? try instantiateFrom(json: json!) : try instantiateFrom(filename: "observationdefinition-example.json")
XCTAssertEqual(inst.code?.coding?[0].code, "15074-8")
XCTAssertEqual(inst.code?.coding?[0].display, "Glucose [Moles/volume] in Blood")
XCTAssertEqual(inst.code?.coding?[0].system?.absoluteString, "http://loinc.org")
XCTAssertEqual(inst.id, "example")
XCTAssertEqual(inst.meta?.tag?[0].code, "HTEST")
XCTAssertEqual(inst.meta?.tag?[0].display, "test health data")
XCTAssertEqual(inst.meta?.tag?[0].system?.absoluteString, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
XCTAssertEqual(inst.text?.status, NarrativeStatus(rawValue: "generated")!)
return inst
}
}
| 33.745455 | 131 | 0.760237 |
280deec7323a792ef41529616d3375c5601e1dbb | 15,846 |
//
// MedianCut.swift
// MedianCut_Example
//
// Created by 이준석 on 2017. 12. 1..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
public class MedianCut {
/**
Data pointer of given image.
*/
private var data: UnsafePointer<UInt8>!
private var componentLayout: ComponentLayout!
/**
colorDepth of MedianCut.
*/
private var colorDepth: Int = 8
private var resizeTargetSize: CGSize = CGSize(width: 256, height: 256)
/**
Inits MedianCut with specified colorDepth and target image size.
- Parameter colorDepth: `colorDepth` of MedianCut. Must provide a value more than 4. The result of extracting colors gives at most 2^(`colorDepth`) colors. Setting a value of 4 means you can get at most 16 colors from the image. The number of colors could be less then 2^(`colorDepth`) since MedianCut removes similar colors from the result array. Default value is 8.
- Parameter resizeTargetSize: Size to apply when resizing image to get colors from image. Providing larger size increases time to get results. If resized image's number of pixels is smaller than 2^(`colorDepth`), result array may only contains a single color. Default value is 256 * 256.
*/
public convenience init(colorDepth: Int = 8, resizeTargetSize: CGSize = CGSize(width: 256, height: 256)) {
self.init()
self.colorDepth = max(colorDepth, 4)
self.resizeTargetSize = resizeTargetSize
}
/**
Extract colors from given image.
- Parameter image: The image to extract colors.
- Parameter completion: Completion Block.
- Parameter succeed: If color extraction is done successfully.
- Parameter colors: Extraced colors from image.
*/
public func getColors(image: UIImage, completion: @escaping (_ succeed: Bool, _ colors: [UIColor]) -> Void) {
DispatchQueue.global(qos: .background).async {
// Resize image to improve performance and get dominant colors
let _resizedImage: UIImage? = self.resizeImage(image: image, targetSize: self.resizeTargetSize)
// Get color data from image
let _bmp: CFData? = _resizedImage?.cgImage?.dataProvider?.data
guard let bmp = _bmp, let resizedImage = _resizedImage else {
// Failed to get color data
completion(false, [])
return
}
// Get rgba array pointer
self.componentLayout = resizedImage.cgImage?.bitmapInfo.componentLayout ?? .rgba
self.data = CFDataGetBytePtr(bmp)
// Pointers array saving 'blue' value index in image rgba data array
var pointers: [Int] = []
// Data array has (number of pixels * 4) elements since each pixel is represented with 4 values (r,g,b,a)
// To get all 'initial' value index, simply loop through 0 to pixel numbers and multiply by 4.
for i in 0..<Int(resizedImage.size.width * resizedImage.scale * resizedImage.size.height * resizedImage.scale) {
pointers.append(i*4)
}
// Result color tables
var colorTables: [UIColor] = []
// Get colors from image
self.getColorTables(pointers: pointers, colorTable: &colorTables, depth: 0)
// Filter out similar colors
colorTables = colorTables.uniqueColors
// colorTables = colorTables.sorted(by: { (a, b) -> Bool in
// if a.hueValue == b.hueValue {
// if a.brightnessValue == b.brightnessValue {
// return a.saturationValue > b.saturationValue
// } else {
// return a.brightnessValue > b.brightnessValue
// }
// } else {
// return a.hueValue > b.hueValue
// }
// })
completion(true, colorTables)
}
}
/**
A recursive function to get colors from color pointers
- Parameter pointers: The image color pointers to extract colors.
- Parameter colorTable: Array to insert result colors.
- Parameter depth: Depth of current median cut loop.
*/
private func getColorTables(pointers: [Int], colorTable: inout [UIColor], depth: Int) {
// If it's the last depth of the algorithm, get average color of colors and insert to result array.
if depth == colorDepth {
if pointers.count != 0 {
colorTable.append(getAverageColor(pointers: pointers))
}
return
}
// Sort pointers by dominant color values
let sortedPointers = getDominantSorted(pointers: pointers)
// Median cut pointers
let separatorIndex: Int = sortedPointers.count / 2
let front: [Int] = Array(sortedPointers[..<separatorIndex])
let rear: [Int] = Array(sortedPointers[separatorIndex...])
// Run algorithm recursively
getColorTables(pointers: front, colorTable: &colorTable, depth: depth + 1)
getColorTables(pointers: rear, colorTable: &colorTable, depth: depth + 1)
}
/**
Sort given array by dominant color element. Dominant color element means one of red, green, blue element of a pixel which has the greatest range in pointers array.
- Parameter pointers: The pointer array to sort.
- Returns: Dominant sorted array.
*/
private func getDominantSorted(pointers: [Int]) -> [Int]{
// Copy of pointers
var pointers = pointers
// Each RGB value range, represented by (min, max) tuple.
var rRange = (255,0)
var gRange = (255,0)
var bRange = (255,0)
// Get RGB min, max values in data within given pointer range.
for pointer in pointers {
let red = Int(data[pointer + componentLayout.getRedIndex()])
let green = Int(data[pointer + componentLayout.getGreenIndex()])
let blue = Int(data[pointer + componentLayout.getBlueIndex()])
rRange = (min(rRange.0, red),max(rRange.1, red))
gRange = (min(gRange.0, green),max(gRange.1, green))
bRange = (min(bRange.0, blue),max(bRange.1, blue))
}
// Get one between red, green and blue value that has the greatest range.
let rangeTable = [(rRange.1 - rRange.0), (gRange.1 - gRange.0), (bRange.1 - bRange.0)]
var dominantIndex: Int {
let dominantRange = rangeTable.firstIndex(of: max(rangeTable[0], max(rangeTable[1], rangeTable[2])))!
switch dominantRange {
case 0:
return componentLayout.getRedIndex()
case 1:
return componentLayout.getGreenIndex()
default:
return componentLayout.getBlueIndex()
}
}
// Sort pointers by dominant color element.
pointers = countSort(pointers: pointers, dominantIndex: dominantIndex)
return pointers
}
/**
Counting sort given pointers by dominant color element.
- Parameter pointers: The pointer array to sort.
- Parameter dominantIndex: DominantIndex 0 means blue value, 1 means green value and 2 means red value.
- Returns: Sorted pointer array.
*/
private func countSort(pointers: [Int], dominantIndex: Int) -> [Int] {
// Arry to count numbers of value exist in pointer array
var sumArray = Array<Int>.init(repeating: 0, count: 256)
// Result Array
var sortedArray = Array<Int>.init(repeating: 0, count: pointers.count)
// Count numbers of value in pointer array
for pointer in pointers {
let value = Int(data[pointer + dominantIndex])
sumArray[value] = sumArray[value] + 1
}
// Sum up counted values to represent index to start fill up with.
for i in 1..<sumArray.count {
sumArray[i] = sumArray[i-1] + sumArray[i]
}
// Fill up sorted array with proper values
for pointer in pointers {
let value = Int(data[pointer + dominantIndex])
sortedArray[sumArray[value] - 1] = pointer
sumArray[value] = sumArray[value] - 1
}
return sortedArray
}
/**
Get average color of given pointers. Simply calculates arithmetic mean of each rgb values.
- Parameter pointers: The pointer array to extract average color.
- Returns: The average color of pointer array.
*/
private func getAverageColor(pointers: [Int]) -> UIColor {
// RGB values
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
// Sum up each RGB values
for pointer in pointers {
r += CGFloat(data[pointer + componentLayout.getRedIndex()])
g += CGFloat(data[pointer + componentLayout.getGreenIndex()])
b += CGFloat(data[pointer + componentLayout.getBlueIndex()])
}
// Get average of each RGB values
r = r/CGFloat(pointers.count)/255
g = g/CGFloat(pointers.count)/255
b = b/CGFloat(pointers.count)/255
return UIColor(red: r, green: g, blue: b, alpha: 1)
}
/**
Resizes the given `image` to fit in `targetSize`
- Parameter image: The image to resize.
- Parameter targetSize: Size to fit resized image in.
- Returns: Resized UIImage, the result is optional.
*/
private func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
// Resize ratio of width/height to figure out which side to fit.
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Original image ratio
let ratio = size.height / size.width
// Figure out resized image size.
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: floor(targetSize.height / ratio), height: floor(targetSize.height))
} else {
newSize = CGSize(width: floor(targetSize.width), height: floor(targetSize.width * ratio))
}
// Make a rect to use to draw resized image on.
let rect = CGRect(x: 0, y:0, width: newSize.width, height: newSize.height)
// Resize the image and draw on given rect.
UIGraphicsBeginImageContextWithOptions(newSize, false, 1)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
extension UIColor {
// RGBA Helpers
var redValue: CGFloat{ return CIColor(color: self).red }
var greenValue: CGFloat{ return CIColor(color: self).green }
var blueValue: CGFloat{ return CIColor(color: self).blue }
var alphaValue: CGFloat{ return CIColor(color: self).alpha }
// HSB Helpers
var hueValue: CGFloat{
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return h
}
var saturationValue: CGFloat{
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return s
}
var brightnessValue: CGFloat{
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return b
}
/**
Determine if two colors are similar. If differences between two colors' each rgb values are all less than 0.2, it is considered to be similar.
- Parameter to: The color to compare with.
- Returns: If two colors are similar, returns true. Vise versa
*/
func isSimilar(to: UIColor) -> Bool {
// Check red value
if abs(self.redValue - to.redValue) > 0.2 {
return false
}
// Check blue value
if abs(self.blueValue - to.blueValue) > 0.2 {
return false
}
// Check green value
if abs(self.greenValue - to.greenValue) > 0.2 {
return false
}
return true
}
}
extension Array where Element:UIColor {
/**
Get unique colors (filter out similar colors) in UIColor array but keep original order.
- Returns: UIColor array which similar colors are filtered out.
*/
var uniqueColors: [UIColor] {
// The unique list kept in a Set for fast retrieval
var set = Set<UIColor>()
// Keeping the unique list of elements but ordered
var arrayOrdered = [UIColor]()
// Loop through array to filter out similar colors.
for value in self {
if !set.contains(where: { (color) -> Bool in
if value.isSimilar(to: color) {
return true
} else {
return false
}
}) {
set.insert(value)
arrayOrdered.append(value)
}
}
return arrayOrdered
}
}
fileprivate extension CGBitmapInfo {
var componentLayout: ComponentLayout? {
guard let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue) else { return nil }
let isLittleEndian = contains(.byteOrder32Little)
if alphaInfo == .none {
return isLittleEndian ? .bgr : .rgb
}
let alphaIsFirst = alphaInfo == .premultipliedFirst || alphaInfo == .first || alphaInfo == .noneSkipFirst
if isLittleEndian {
return alphaIsFirst ? .bgra : .abgr
} else {
return alphaIsFirst ? .argb : .rgba
}
}
}
fileprivate enum ComponentLayout {
case bgra
case abgr
case argb
case rgba
case bgr
case rgb
var count: Int {
switch self {
case .bgr, .rgb: return 3
default: return 4
}
}
func getRedIndex() -> Int {
switch self {
case .bgra:
return 2
case .abgr:
return 3
case .argb:
return 1
case .rgba:
return 0
case .bgr:
return 2
case .rgb:
return 0
}
}
func getGreenIndex() -> Int {
switch self {
case .bgra:
return 1
case .abgr:
return 2
case .argb:
return 3
case .rgba:
return 1
case .bgr:
return 1
case .rgb:
return 1
}
}
func getBlueIndex() -> Int {
switch self {
case .bgra:
return 0
case .abgr:
return 1
case .argb:
return 3
case .rgba:
return 2
case .bgr:
return 0
case .rgb:
return 2
}
}
}
| 33.36 | 372 | 0.560772 |
1e6a1795fa9474da13d52e8220f9b41a7b5039ad | 375 | //
// UIAlertController+Comet.swift
// Comet
//
// Created by Harley on 2016/11/8.
//
//
import UIKit
public extension UIAlertController {
func addAction(title: String?, style: UIAlertAction.Style, handler: ((UIAlertAction)->())? = nil) {
let action = UIAlertAction(title: title, style: style, handler: handler)
self.addAction(action)
}
}
| 18.75 | 103 | 0.650667 |
67cda0f779cec942da716faa9995d0490581f39b | 2,503 | //
// VirtualObject.swift
// HomeDesign
//
// Created by Maximiliano on 2/24/18.
// Copyright © 2018 Maximiliano. All rights reserved.
//
import Foundation
import SceneKit
import ARKit
class VirtualObject: SCNNode {
static let ROOT_NAME = "Virtual object root node"
var fileExtension: String = ""
var thumbImage: UIImage!
var title: String = ""
var modelName: String = ""
var modelLoaded: Bool = false
var id: Int!
var viewController: MainViewController?
override init() {
super.init()
self.name = VirtualObject.ROOT_NAME
}
init(modelName: String, fileExtension: String, thumbImageFilename: String, title: String) {
super.init()
self.id = VirtualObjectsManager.shared.generateUid()
self.name = VirtualObject.ROOT_NAME
self.modelName = modelName
self.fileExtension = fileExtension
self.thumbImage = UIImage(named: thumbImageFilename)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadModel() {
guard let virtualObjectScene = SCNScene(named: "\(modelName).\(fileExtension)",
inDirectory: "Models.scnassets/\(modelName)") else {
return
}
let wrapperNode = SCNNode()
for child in virtualObjectScene.rootNode.childNodes {
child.geometry?.firstMaterial?.lightingModel = .physicallyBased
child.movabilityHint = .movable
wrapperNode.addChildNode(child)
}
self.addChildNode(wrapperNode)
modelLoaded = true
}
func unloadModel() {
for child in self.childNodes {
child.removeFromParentNode()
}
modelLoaded = false
}
func translateBasedOnScreenPos(_ pos: CGPoint, instantly: Bool, infinitePlane: Bool) {
guard let controller = viewController else {
return
}
let result = controller.worldPositionFromScreenPosition(pos, objectPos: self.position, infinitePlane: infinitePlane)
controller.moveVirtualObjectToPosition(result.position, instantly, !result.hitAPlane)
}
}
extension VirtualObject {
static func isNodePartOfVirtualObject(_ node: SCNNode) -> Bool {
if node.name == VirtualObject.ROOT_NAME {
return true
}
if node.parent != nil {
return isNodePartOfVirtualObject(node.parent!)
}
return false
}
}
// MARK: - Protocols for Virtual Objects
protocol ReactsToScale {
func reactToScale()
}
extension SCNNode {
func reactsToScale() -> ReactsToScale? {
if let canReact = self as? ReactsToScale {
return canReact
}
if parent != nil {
return parent!.reactsToScale()
}
return nil
}
}
| 22.348214 | 118 | 0.726728 |
29eb3594fed6c8c6a9c866d12e970a2768748f68 | 3,111 | //
// ValidWordAbbreviationTests.swift
// CodingChallengesTests
//
// Created by William Boles on 23/12/2021.
// Copyright © 2021 Boles. All rights reserved.
//
import XCTest
@testable import LeetCode
class ValidWordAbbreviationTests: XCTestCase {
// MARK: - Tests
func test_A() {
let word = "internationalization"
let abbr = "i12iz4n"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertTrue(isValid)
}
func test_B() {
let word = "apple"
let abbr = "a2e"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
func test_C() {
let word = "substitution"
let abbr = "s10n"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertTrue(isValid)
}
func test_D() {
let word = "substitution"
let abbr = "sub4u4"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertTrue(isValid)
}
func test_E() {
let word = "substitution"
let abbr = "12"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertTrue(isValid)
}
func test_F() {
let word = "substitution"
let abbr = "su3i1u2on"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertTrue(isValid)
}
func test_G() {
let word = "substitution"
let abbr = "substitution"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertTrue(isValid)
}
func test_H() {
let word = "substitution"
let abbr = "s55n"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
func test_I() {
let word = "substitution"
let abbr = "s010n"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
func test_J() {
let word = "substitution"
let abbr = "s0ubstitution"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
func test_K() {
let word = "word"
let abbr = "3e"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
func test_L() {
let word = "hi"
let abbr = "2i"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
func test_M() {
let word = "hi"
let abbr = "1"
let isValid = ValidWordAbbreviation.validWordAbbreviation(word, abbr)
XCTAssertFalse(isValid)
}
}
| 23.216418 | 77 | 0.565734 |
bf432fe224fbcef0b211f820c8feaa2b3b84d85f | 1,628 | //
// JLExtensionSwift.swift
// JLExtension-Swift
//
// Created by JasonLiu on 2017/5/19.
// Copyright © 2017年 JasonLiu. All rights reserved.
//
import UIKit
// 设备屏幕宽
let screenWidth: CGFloat = UIScreen.main.bounds.size.width
// 设备屏幕高
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
// iPhone X 刘海系列
let isIPhoneXAll: Bool = ((Int)((screenHeight/screenWidth)*100) == 216)
// iPhone X
let isIPhoneX: Bool = (screenWidth == 375 && screenHeight == 812)
// iPhone XS
let isIPhoneXS: Bool = (screenWidth == 375 && screenHeight == 812)
// iPhone XR
let isIPhoneXR: Bool = (screenWidth == 414 && screenHeight == 896)
// iPhone XS Max
let isIPhoneXSMax: Bool = (screenWidth == 414 && screenHeight == 896)
// 时间戳
var timeStampInt: Int = Int(Date().timeIntervalSince1970)
// 时间戳
let timeStampString: String = timeStampInt.toString
func rgb(r: Float, g: Float, b: Float) -> UIColor {
return rgba(r: r, g: g, b: b, a: 1.0)
}
func rgba(r: Float, g: Float, b: Float, a: Float) -> UIColor {
if #available(iOS 10.0, *) {
return UIColor(displayP3Red: CGFloat(r/255.0), green: CGFloat(g/255.0), blue: CGFloat(b/255.0), alpha: CGFloat(a))
} else {
// Fallback on earlier versions
return UIColor.init(red: CGFloat(r/255.0), green: CGFloat(g/255.0), blue: CGFloat(b/255.0), alpha: CGFloat(a))
}
}
func log(_ items: Any..., separator: String = " ", terminator: String = "\n", line: Int = #line, file: String = #file, functoin: String = #function) {
print("\n在源文件\(String(file.components(separatedBy: "/").last!)) 第\(line)行 \(functoin)函数中: \(items)", separator, terminator)
}
| 30.148148 | 150 | 0.661548 |
2692ddde5f129ff63649360124e2614a5a43d2b3 | 587 | //
// ChartAxisValueString.swift
// SwiftCharts
//
// Created by ischuetz on 29/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartAxisValueString: ChartAxisValue {
open let string: String
public init(_ string: String = "", order: Int, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
self.string = string
super.init(scalar: Double(order), labelSettings: labelSettings)
}
// MARK: CustomStringConvertible
override open var description: String {
return string
}
}
| 22.576923 | 110 | 0.672913 |
ebac6c7792109f391de35621d3b548e5d498c118 | 16,707 | // RUN: %target-swift-frontend -Xllvm -sil-disable-pass="Function Signature Optimization" -emit-sil -o - -O %s | FileCheck %s
//////////////////
// Declarations //
//////////////////
public class C {}
public class D : C {}
public class E {}
var b : UInt8 = 0
var c = C()
var d = D()
var e = E()
var f : UInt64 = 0
var o : AnyObject = c
////////////////////////////
// Archetype To Archetype //
////////////////////////////
@inline(never)
public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 {
return t as! T2
}
ArchetypeToArchetype(t: b, t2: b)
ArchetypeToArchetype(t: c, t2: c)
ArchetypeToArchetype(t: b, t2: c)
ArchetypeToArchetype(t: c, t2: b)
ArchetypeToArchetype(t: c, t2: d)
ArchetypeToArchetype(t: d, t2: c)
ArchetypeToArchetype(t: c, t2: e)
ArchetypeToArchetype(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_S____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, UInt8) -> UInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_S0____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast_addr
// y -> x where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_Vs5UInt8___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1D___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $C
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK: unconditional_checked_cast_addr take_always C in [[STACK]] : $*C to D in
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D_CS_1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: upcast {{%[0-9]+}} : $D to $C
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1E___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated non classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_Vs6UInt64___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, UInt64) -> UInt64 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
///////////////////////////
// Archetype To Concrete //
///////////////////////////
@inline(never)
public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> UInt8 {
return t as! UInt8
}
ArchetypeToConcreteConvertUInt8(t: b)
ArchetypeToConcreteConvertUInt8(t: c)
ArchetypeToConcreteConvertUInt8(t: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{.*}} : $@convention(thin) (UInt8) -> UInt8 {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where y is a class but x is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@owned C) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are classes and x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@owned D) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: [[UC:%[0-9]+]] = upcast %0
// CHECK-NEXT: return [[UC]]
// x -> y where x,y are classes, but x is unrelated to y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ArchetypeToConcreteConvertC<T>(t t: T) -> C {
return t as! C
}
ArchetypeToConcreteConvertC(t: c)
ArchetypeToConcreteConvertC(t: b)
ArchetypeToConcreteConvertC(t: d)
ArchetypeToConcreteConvertC(t: e)
@inline(never)
public func ArchetypeToConcreteConvertD<T>(t t: T) -> D {
return t as! D
}
ArchetypeToConcreteConvertD(t: c)
// x -> y where x,y are classes and x is a sub class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{.*}} : $@convention(thin) (@owned C) -> @owned D {
// CHECK: bb0(%0 : $C):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func ArchetypeToConcreteConvertE<T>(t t: T) -> E {
return t as! E
}
ArchetypeToConcreteConvertE(t: c)
// x -> y where x,y are classes, but y is unrelated to x. The idea is
// to make sure that the fact that y is concrete does not affect the
// result.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
///////////////////////////
// Concrete to Archetype //
///////////////////////////
@inline(never)
public func ConcreteToArchetypeConvertUInt8<T>(t t: UInt8, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertUInt8(t: b, t2: b)
ConcreteToArchetypeConvertUInt8(t: b, t2: c)
ConcreteToArchetypeConvertUInt8(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, UInt8) -> UInt8 {
// CHECK: bb0(%0 : $UInt8, %1 : $UInt8):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where x is not a class but y is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, @owned C) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are different non class types.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, UInt64) -> UInt64 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertC(t: c, t2: c)
ConcreteToArchetypeConvertC(t: c, t2: b)
ConcreteToArchetypeConvertC(t: c, t2: d)
ConcreteToArchetypeConvertC(t: c, t2: e)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0(%0 : $C, %1 : $D):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: strong_release %1
// CHECK-DAG: strong_release %0
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK: bb0(%0 : $C, %1 : $E):
// CHECK-NEXT: builtin "int_trap"
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertD(t: d, t2: c)
// x -> y where x is a subclass of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK: bb0(%0 : $D, %1 : $C):
// CHECK-DAG: [[UC:%[0-9]+]] = upcast %0
// CHECK-DAG: strong_release %1
// CHECK: return [[UC]]
////////////////////////
// Super To Archetype //
////////////////////////
@inline(never)
public func SuperToArchetypeC<T>(c c : C, t : T) -> T {
return c as! T
}
SuperToArchetypeC(c: c, t: c)
SuperToArchetypeC(c: c, t: d)
SuperToArchetypeC(c: c, t: b)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0
// CHECK: unconditional_checked_cast_addr take_always C in
// x -> y where x is a class and y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func SuperToArchetypeD<T>(d d : D, t : T) -> T {
return d as! T
}
SuperToArchetypeD(d: d, t: c)
SuperToArchetypeD(d: d, t: d)
// *NOTE* The frontend is smart enough to turn this into an upcast. When this
// test is converted to SIL, this should be fixed appropriately.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK: upcast
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@owned D, @owned D) -> @owned D {
// CHECK: bb0(%0 : $D, %1 : $D):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
@inline(never)
public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T {
return o as! T
}
// AnyObject -> Class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, @owned C) -> @owned C {
// CHECK: unconditional_checked_cast_addr take_always AnyObject in {{%.*}} : $*AnyObject to C
// AnyObject -> Non Class (should always fail)
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, UInt8) -> UInt8 {
// CHECK: builtin "int_trap"()
// CHECK: unreachable
// CHECK-NEXT: }
// AnyObject -> AnyObject
// CHECK-LABEL: sil shared [noinline] @_TTSg5Ps9AnyObject____TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, @owned AnyObject) -> @owned AnyObject {
// CHECK: bb0(%0 : $AnyObject, %1 : $AnyObject):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
ExistentialToArchetype(o: o, t: c)
ExistentialToArchetype(o: o, t: b)
ExistentialToArchetype(o: o, t: o)
// Ensure that a downcast from an Optional source is not promoted to a
// value cast. We could do the promotion, but the optimizer would need
// to insert the Optional unwrapping logic before the cast.
//
// CHECK-LABEL: sil shared [noinline] @_TTSg5GSqC37specialize_unconditional_checked_cast1C__CS_1D___TF37specialize_unconditional_checked_cast15genericDownCastu0_rFTxMq__q_ : $@convention(thin) (@owned Optional<C>, @thick D.Type) -> @owned D {
// CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type):
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C>
// CHECK-DAG: store %0 to [[STACK_C]]
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always Optional<C> in [[STACK_C]] : $*Optional<C> to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func genericDownCast<T, U>(_ a: T, _ : U.Type) -> U {
return a as! U
}
public func callGenericDownCast(_ c: C?) -> D {
return genericDownCast(c, D.self)
}
| 43.735602 | 242 | 0.723469 |
f787b899ea27e3cfff18f59e148cc209d5422938 | 3,035 | //
// ForecastTests.swift
// weatherTests
//
import Quick
import Nimble
@testable import weather
class ForecastTests: QuickSpec {
override func spec() {
describe("Forecast Tests") {
describe("Decodable.init(from:)") {
let decoder = JSONDecoder()
var forecast: Forecast?
var parseError: Error?
context("when provided valid data") {
let data = HereWeatherResponseDataFixture.ForecastData()
beforeEach {
forecast = nil
parseError = nil
do {
forecast = try decoder.decode(Forecast.self, from: data)
} catch let error {
parseError = error
}
}
it("parses successfully") {
expect(parseError).to(beNil())
}
it("initializes correctly") {
expect(forecast).toNot(beNil())
}
}
context("when provided empty data") {
let data = HereWeatherResponseDataFixture.EmptyData()
beforeEach {
forecast = nil
parseError = nil
do {
forecast = try decoder.decode(Forecast.self, from: data)
} catch let error {
parseError = error
}
}
it("does not parse correctly") {
expect(parseError).toNot(beNil())
}
it("does not initializes") {
expect(forecast).to(beNil())
}
}
context("when provided invalid data") {
let data = HereWeatherResponseDataFixture.InvalidForecastData()
beforeEach {
forecast = nil
parseError = nil
do {
forecast = try decoder.decode(Forecast.self, from: data)
} catch let error {
parseError = error
}
}
it("does not parse correctly") {
expect(parseError).toNot(beNil())
}
it("does not initializes") {
expect(forecast).to(beNil())
}
}
}
}
}
}
| 33.351648 | 84 | 0.346293 |
11a701905f7349680151bbdff16cc722971b636b | 7,788 | //
// Copyright (c) 2018 Related Code - http://relatedcode.com
//
// 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.
//-------------------------------------------------------------------------------------------------------------------------------------------------
class GroupsView: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!
private var dbgroups: RLMResults = DBGroup.objects(with: NSPredicate(value: false))
//---------------------------------------------------------------------------------------------------------------------------------------------
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
tabBarItem.image = UIImage(named: "tab_groups")
tabBarItem.title = "Groups"
NotificationCenterX.addObserver(target: self, selector: #selector(loadGroups), name: NOTIFICATION_USER_LOGGED_IN)
NotificationCenterX.addObserver(target: self, selector: #selector(actionCleanup), name: NOTIFICATION_USER_LOGGED_OUT)
NotificationCenterX.addObserver(target: self, selector: #selector(refreshTableView), name: NOTIFICATION_REFRESH_GROUPS)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
title = "Groups"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(actionNew))
tableView.register(UINib(nibName: "GroupsCell", bundle: nil), forCellReuseIdentifier: "GroupsCell")
tableView.tableFooterView = UIView()
if (FUser.currentId() != "") {
loadGroups()
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (FUser.currentId() != "") {
if (FUser.isOnboardOk()) {
AdvertCustom(target: self);
} else {
OnboardUser(target: self)
}
} else {
LoginUser(target: self)
}
}
// MARK: - Realm methods
//---------------------------------------------------------------------------------------------------------------------------------------------
@objc func loadGroups() {
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func deleteGroup(dbgroup: DBGroup) {
}
// MARK: - Refresh methods
//---------------------------------------------------------------------------------------------------------------------------------------------
@objc func refreshTableView() {
tableView.reloadData()
}
// MARK: - User actions
//---------------------------------------------------------------------------------------------------------------------------------------------
@objc func actionNewGroup() {
}
//---------------------------------------------------------------------------------------------------------------------------------------------
@objc func actionNew() {
}
// MARK: - Cleanup methods
//---------------------------------------------------------------------------------------------------------------------------------------------
@objc func actionCleanup() {
refreshTableView()
}
// MARK: - UIScrollViewDelegate
//---------------------------------------------------------------------------------------------------------------------------------------------
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
view.endEditing(true)
}
// MARK: - Table view data source
//---------------------------------------------------------------------------------------------------------------------------------------------
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(dbgroups.count)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GroupsCell", for: indexPath) as! GroupsCell
let dbgroup = dbgroups[UInt(indexPath.row)] as! DBGroup
cell.bindData(dbgroup: dbgroup)
cell.loadImage(dbgroup: dbgroup, tableView: tableView, indexPath: indexPath)
return cell
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
let dbgroup = dbgroups[UInt(indexPath.row)] as! DBGroup
return (dbgroup.userId == FUser.currentId())
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
// MARK: - Table view delegate
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
// MARK: - UISearchBarDelegate
//---------------------------------------------------------------------------------------------------------------------------------------------
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
loadGroups()
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func searchBarTextDidBeginEditing(_ searchBar_: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func searchBarTextDidEndEditing(_ searchBar_: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func searchBarCancelButtonClicked(_ searchBar_: UISearchBar) {
searchBar.text = ""
searchBar.resignFirstResponder()
loadGroups()
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func searchBarSearchButtonClicked(_ searchBar_: UISearchBar) {
searchBar.resignFirstResponder()
}
}
| 40.352332 | 147 | 0.425398 |
897955729c1981c30cf7d63032f634e5831c31b9 | 147 | import XCTest
#if !os(macOS)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(SlackPostTests.allTests),
]
}
#endif
| 14.7 | 45 | 0.646259 |
c121fdc49af6c3fa7edc3482a8b7d626756c1703 | 304 | import PackageDescription
let package = Package(
name: "Jay-C7",
dependencies: [
.Package(url: "https://github.com/czechboy0/Jay.git", versions: Version(0,14,0)..<Version(1,0,0)),
.Package(url: "https://github.com/open-swift/C7.git", versions: Version(0,8,0)..<Version(1,0,0))
]
)
| 30.4 | 103 | 0.644737 |
33d942d7a9b34a76b8d49dd832f68d5df6d14f32 | 889 | //
// ViewController.swift
// Example
//
// Created by 王垒 on 2017/4/27.
// Copyright © 2017年 王垒. 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.
view.backgroundColor = UIColor.yellow
let textField = UITextField(frame: CGRect(x: 15, y: 120, width: JMTWindowWidth - 30, height: 35))
textField.borderStyle = .roundedRect
view.addSubview(textField)
WLCardKeyBoard.defaule.addKeyBoard(view, field: textField)
textField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 24.027027 | 105 | 0.626547 |
21c71216349c014d1fb3ac3d89b44e1144a44c14 | 1,182 | //
// ExSwiftFloatTests.swift
// ExSwift
//
// Created by pNre on 04/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import XCTest
class ExSwiftFloatTests: XCTestCase {
func testAbs() {
XCTAssertGreaterThan((-1.0).abs(), 0)
}
func testSqrt() {
XCTAssertEqual(2, (4.0).sqrt())
}
func testDigits () {
let first = 10.214.digits()
XCTAssertEqualObjects(first.integerPart, [1, 0])
XCTAssertEqualObjects(first.fractionalPart[0...1], [2, 1])
let second = 0.123.digits()
XCTAssertEqualObjects(second.integerPart, [0])
XCTAssertEqualObjects(second.fractionalPart[0...1], [1, 2])
let third = 10.0.digits()
XCTAssertEqualObjects(third.integerPart, [1, 0])
XCTAssertEqualObjects(third.fractionalPart, [0])
}
func testFloor () {
XCTAssertEqual(2, (2.9).floor())
}
func testCeil () {
XCTAssertEqual(3, (2.9).ceil())
}
func testRound () {
XCTAssertEqual(3, (2.5).round())
XCTAssertEqual(2, (2.4).round())
}
func testRandom() {
}
}
| 21.490909 | 67 | 0.553299 |
5bc48b5cb476149ad1721dc07f86a83f53283e54 | 816 | //
// BaseCollectionIdentifierCell.swift
// SharedCore
//
// Created by Pawel Klapuch on 2/9/21.
//
import UIKit
open class BaseCollectionIdentifierCell: UICollectionViewCell, CellReusableIdentifier {
public static func registerWithCollectionViewNoNib(_ collectionView: UICollectionView) {
let className = NSStringFromClass(self).components(separatedBy: ".").last!
collectionView.register(self, forCellWithReuseIdentifier: className)
}
public static func registerWithCollectionView(_ collectionView: UICollectionView) {
let className = NSStringFromClass(self).components(separatedBy: ".").last!
let nib = UINib.init(nibName: className, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: reuseIdentifier)
}
}
| 32.64 | 92 | 0.727941 |
8778e6f5252c89b2f7f9cda23523b4c2df047b4e | 263 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
[ {
{
{
}
if true {
enum e {
let d{
if true {
if true {
if true {
struct d{
class
case c,
{
| 13.15 | 87 | 0.688213 |
469143729f9b4e38a28db965dc6a8716e2c423bc | 3,739 | // MIT License
//
// Copyright (c) 2015-present Vladimir Kazantsev
//
// 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 canImport(UIKit)
import UIKit
public final class SeparatorView: UIView {
public enum Side {
case top, left, bottom, right
}
@discardableResult
public static func create(
in view: UIView,
attachedTo side: Side,
color: UIColor = UIColor( white: 0, alpha: 0.2 ),
insets: UIEdgeInsets = .zero,
length: CGFloat = 1 / UIScreen.main.scale
) -> SeparatorView {
let axis: NSLayoutConstraint.Axis = side.isIn( .top, .bottom ) ? .horizontal : .vertical
let separator = SeparatorView( axis: axis, color: color, length: length )
view.addSubview( separator )
separator.attach( to: side, insets: insets )
return separator
}
public func attach(
to side: Side,
insets: UIEdgeInsets = .zero
) {
switch side {
case .top, .bottom:
pin( .left, constant: insets.left )
pin( .right, constant: -insets.right )
pin( side == .top ? .top : .bottom,
constant: side == .top ? insets.top : -insets.bottom )
case .left, .right:
pin( .top, constant: insets.top )
pin( .bottom, constant: -insets.bottom )
pin( side == .left ? .left : .right,
constant: side == .left ? insets.left : -insets.right )
}
}
public init(
axis: NSLayoutConstraint.Axis = .horizontal,
color: UIColor = UIColor( white: 0, alpha: 0.2 ),
length: CGFloat = 1 / UIScreen.main.scale
) {
super.init( frame: .zero )
backgroundColor = color
translatesAutoresizingMaskIntoConstraints = false
switch axis {
case .horizontal: constrainTo( height: length )
case .vertical: constrainTo( width: length )
@unknown default: fatalError()
}
}
required public init?( coder aDecoder: NSCoder ) {
super.init( coder: aDecoder )
}
// For convenience, if you need one pixel height/width separator in Xib or Storyboard
// add UIView, assign `SeparatorView` as its class name, add position constraints
// and add height or width (depending on type of the separator you need ) constraint
// with constant value of one. After initialization this constraint will change to
// one pixel heght or width.
override public func awakeFromNib() {
super.awakeFromNib()
// Looking for height constraint and setting it to exactly one pixel.
for constraint in constraints where constraint.firstItem === self && constraint.firstAttribute == .height {
constraint.constant = 1 / UIScreen.main.scale
return
}
// Looking for width constraint and setting it to exactly one pixel.
for constraint in constraints where constraint.firstItem === self && constraint.firstAttribute == .width {
constraint.constant = 1 / UIScreen.main.scale
break
}
}
}
#endif
| 34.302752 | 109 | 0.717304 |
e6bfb15b8b1b5b7d8a5249a11b03d3481fa9c234 | 3,624 | //
// NSURLRequest+cURL.swift
// Yep
//
// Created by nixzhu on 15/9/8.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import Foundation
// ref https://github.com/dduan/cURLLook
// modify for Yep
extension URLRequest {
var cURLCommandLine: String {
get {
return cURLCommandLineWithSession(nil)
}
}
func cURLCommandLineWithSession(_ session: URLSession?, credential: URLCredential? = nil) -> String {
var components = ["\ncurl -i"]
if let HTTPMethod = httpMethod, HTTPMethod != "GET" {
components.append("-X \(HTTPMethod)")
}
if let URLString = url?.absoluteString {
components.append("\"\(URLString)\"")
}
if let credentialStorage = session?.configuration.urlCredentialStorage {
if let host = url?.host, let scheme = url?.scheme {
let port = (url as NSURL?)?.port?.intValue ?? 0
let protectionSpace = URLProtectionSpace(
host: host,
port: port,
protocol: scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
if let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
} else {
if let user = credential?.user, let password = credential?.password {
components.append("-u \(user):\(password)")
}
}
}
}
if let session = session, let URL = url {
if session.configuration.httpShouldSetCookies {
if let
cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: URL), !cookies.isEmpty {
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
components.append("-b \"\(string[string.startIndex..<string.index(before: string.endIndex)])\"")
}
}
}
if let headerFields = allHTTPHeaderFields {
for (field, value) in headerFields {
switch field {
case "Cookie":
continue
default:
let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(field): \(escapedValue)\"")
}
}
}
if let additionalHeaders = session?.configuration.httpAdditionalHeaders as? [String: String] {
for (field, value) in additionalHeaders {
switch field {
case "Cookie":
continue
default:
let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(field): \(escapedValue)\"")
}
}
}
if let HTTPBody = httpBody, let HTTPBodyString = String(data: HTTPBody, encoding: .utf8) {
let escapedString = HTTPBodyString.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedString)\"")
}
return components.joined(separator: " ") + "\n"
}
}
| 33.247706 | 116 | 0.504415 |
508ae2883883c486724c21897cedfe96dfa35e0c | 1,270 | //
// Copyright (c) 2020 Related Code - http://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
//-------------------------------------------------------------------------------------------------------------------------------------------------
class GroupsCell: UITableViewCell {
@IBOutlet var imageGroup: UIImageView!
@IBOutlet var labelInitials: UILabel!
@IBOutlet var labelName: UILabel!
@IBOutlet var labelMembers: UILabel!
//---------------------------------------------------------------------------------------------------------------------------------------------
func bindData(group: Group) {
labelInitials.text = String(group.name.prefix(1))
labelName.text = group.name
let userIds = Members.userIds(chatId: group.chatId)
labelMembers.text = "\(userIds.count) members"
}
}
| 38.484848 | 147 | 0.57874 |
0eca9c1db25e92f1c70c3b7720857416ce378021 | 3,037 | //
// Statio
// Varun Santhanam
//
import Analytics
import Foundation
import MonitorKit
import ShortRibs
import SnapKit
import UIKit
/// @CreateMock
protocol BatteryViewControllable: ViewControllable {}
/// @CreateMock
protocol BatteryPresentableListener: AnyObject {
func didTapBack()
}
final class BatteryViewController: ScopeViewController, BatteryPresentable, BatteryViewControllable, UICollectionViewDelegate {
// MARK: - Initializers
init(analyticsManager: AnalyticsManaging,
collectionView: BatteryCollectionViewable,
dataSource: BatteryDataSource) {
self.analyticsManager = analyticsManager
self.collectionView = collectionView
self.dataSource = dataSource
super.init()
}
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
title = "Battery"
let leadingItem = UIBarButtonItem(barButtonSystemItem: .close,
target: self,
action: #selector(didTapBack))
navigationItem.leftBarButtonItem = leadingItem
specializedView.backgroundColor = .systemBackground
collectionView.delegate = self
specializedView.addSubview(collectionView.uiview)
collectionView.uiview.snp.makeConstraints { make in
make
.edges
.equalToSuperview()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
analyticsManager.send(event: AnalyticsEvent.battery_vc_impression)
}
// MARK: - BatteryPresentable
weak var listener: BatteryPresentableListener?
func update(level: Battery.Level) {
self.level = level
reload()
}
func update(state: Battery.State) {
self.state = state
reload()
}
// MARK: - Private
private let analyticsManager: AnalyticsManaging
private let collectionView: BatteryCollectionViewable
private let dataSource: BatteryDataSource
private var level: Battery.Level?
private var state: Battery.State?
private func reload() {
var snapshot = NSDiffableDataSourceSnapshot<Int, BatteryRow>()
snapshot.appendSections([0])
snapshot.appendItems([.init(title: "Level", value: level.map(\.description) ?? "Unknown"),
.init(title: "State", value: state.map(\.userDescription) ?? "Unknown")],
toSection: 0)
dataSource.apply(snapshot)
}
@objc
private func didTapBack() {
analyticsManager.send(event: AnalyticsEvent.battery_vc_dismiss)
listener?.didTapBack()
}
}
private extension Battery.State {
var userDescription: String {
switch self {
case .charging:
return "Charging"
case .discharging:
return "Discharging"
case .full:
return "Full"
case .unknown:
return "Unknown"
}
}
}
| 27.116071 | 127 | 0.634178 |
dbe2c6b687ccaa4d69591da03ca348b3f1fd6c1d | 1,970 | /*
* 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
extension UIViewControllerSwizzler {
func unswizzle() {
viewWillAppear.unswizzle()
viewWillDisappear.unswizzle()
}
}
class UIViewControllerSwizzlerTests: XCTestCase {
private let handler = UIKitRUMViewsHandlerMock()
private lazy var swizzler = try! UIViewControllerSwizzler(handler: handler)
override func setUp() {
super.setUp()
swizzler.swizzle()
}
override func tearDown() {
swizzler.unswizzle()
super.tearDown()
}
func testWhenViewWillAppearIsCalled_itNotifiesTheHandler() {
let expectation = self.expectation(description: "Notify handler")
let viewController = createMockView()
let animated = Bool.random()
handler.onViewWillAppear = { receivedViewController, receivedAnimated in
XCTAssertTrue(receivedViewController === viewController)
XCTAssertEqual(receivedAnimated, animated)
expectation.fulfill()
}
viewController.viewWillAppear(animated)
waitForExpectations(timeout: 0.5, handler: nil)
}
func testWhenViewWillDisappearIsCalled_itNotifiesTheHandler() {
let expectation = self.expectation(description: "Notify handler")
let viewController = createMockView()
let animated = Bool.random()
handler.onViewWillDisappear = { receivedViewController, receivedAnimated in
XCTAssertTrue(receivedViewController === viewController)
XCTAssertEqual(receivedAnimated, animated)
expectation.fulfill()
}
viewController.viewWillDisappear(animated)
waitForExpectations(timeout: 0.5, handler: nil)
}
}
| 31.269841 | 117 | 0.694924 |
09b0431778370112c68cf604b0a5129f34795288 | 312 | //
// UIScreen+Extension.swift
// IDSwiftExtensions
//
// Created by Island on 17/2/21.
//
//
import UIKit
public extension UIScreen {
/// 屏幕宽度
static var width: CGFloat {
return main.bounds.width
}
/// 屏幕高度
static var height: CGFloat {
return main.bounds.height
}
}
| 14.857143 | 33 | 0.605769 |
efef732074cdf76456f4de2e4caa419b14356c1a | 474 | //
//
// LinkMemoBuilder.swift
// ViewerScene
//
// Created by sudo.park on 2021/10/24.
//
// ViewerScene
//
// Created sudo.park on 2021/10/24.
// Copyright © 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
import Domain
import CommonPresenting
// MARK: - Builder + DependencyInjector Extension
public protocol LinkMemoSceneBuilable {
func makeLinkMemoScene(memo: ReadLinkMemo, listener: LinkMemoSceneListenable?) -> LinkMemoScene
}
| 18.230769 | 99 | 0.727848 |
d5ea4ee9aac6a6ef2751dcf9010be8981d20546d | 919 | //
// MessageViewModel.swift
// Chat
//
// Created by 차수연 on 2020/05/11.
// Copyright © 2020 차수연. All rights reserved.
//
import UIKit
struct MessageViewModel {
private let message: Message
var messageBackgroundColor: UIColor {
return message.isFromCurrentUser ? #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) : .systemPurple
}
var messsageTextColor: UIColor {
return message.isFromCurrentUser ? .black : .white
}
var rightAnchorActive: Bool {
return message.isFromCurrentUser
}
var leftAnchorActive: Bool {
return !message.isFromCurrentUser
}
var shouldHideProfileImage: Bool {
return message.isFromCurrentUser
}
var profileImageUrl: URL? {
guard let user = message.user else { return nil }
return URL(string: user.profileImageUrl)
}
init(message: Message) {
self.message = message
}
}
| 20.422222 | 138 | 0.68988 |
265bc0f120ecb79cdc18eee62172d896d75f6135 | 8,986 | //
// WelcomeViewController.swift
// BeerboardBWWFramework
//
// Created by Srinivasulu Budharapu on 10/04/18.
// Copyright © 2018 Srinivasulu Budharapu. All rights reserved.
//
import UIKit
public class WelcomeViewController: UIViewController {
@IBOutlet weak var beerchiptableContainerView: UIView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var beerMenuTableView: UITableView!
@IBOutlet weak var currentBalancedisplayLbl: UILabel!
@IBOutlet weak var redeemBtn: UIButton!
@IBOutlet weak var beerMenuSegmentedControl: UISegmentedControl!
@IBOutlet weak var locationIndicatorBtn: UIButton!
@IBOutlet weak var myBalanceDisplayLable: UILabel!
@IBOutlet weak var cashOutBtn: UIButton!
@IBOutlet weak var cashOutBtnView: UIView!
@IBOutlet weak var locationTableView: UITableView!
@IBOutlet weak var locationTableContainerView: UIView!
@IBOutlet weak var alphaView: UIView!
var titleArr = [String]()
var subTitleArr = [String]()
var abvValueArr = [String]()
var locationArr = [String]()
var locationAddreddArr = [String]()
var beerMenuImagesArr = [String]()
var beerchipTableVC = BeerChipTableViewController()
var isBeerchipTableVCAdding = false
var isBeerchipTableVCRemoving = false
var usedefaults = UserDefaults.standard
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "BEERCHIPS"
beerMenuTableView.estimatedRowHeight = 100.0
beerMenuTableView.rowHeight = UITableViewAutomaticDimension
beerMenuTableView.tableFooterView = UIView()
titleArr = ["AUGUST SHELL FORT ROAD HELLES " , "BLUE POINT TOASTED LAGER " ,"SAMUEL ADAMS BOSTON LAGAR"]
subTitleArr = ["German Style Helles/August Schell brewing Company/New Utm,MN","Vienna Lager/Blue point Brewery/Patchogue,NY","Vienna Lager/Samuel Adams/Boston,MA"]
beerMenuImagesArr = ["beer-logo-bud-light","beer-logo-bud-light-lime" ,"beer-logo-budweiser","beer-logo-bud-light"]
abvValueArr = ["5.8%","6%","5%"]
locationArr = ["Cahokia","Canton","Camillus","Columbus","Dalton","Douglas","East Hartford","East Haven","Enfield","Fairfield","Farmington","Greenwich","Groton"]
cashOutBtnView.backgroundColor = UIColor.black
cashOutBtn.layer.cornerRadius = 8.0
redeemBtn.layer.cornerRadius = 8.0
locationIndicatorBtn.layer.cornerRadius = 8.0
alphaView.isHidden = true
locationTableContainerView.isHidden = true
let beerboardBWWStoryboard = UIStoryboard(name: "BeerboardBWWFrameworkStoryboard", bundle: Bundle(for: BeerboardBWWViewController.self))
beerchipTableVC = beerboardBWWStoryboard.instantiateViewController(withIdentifier: "BeerChipTableViewController") as! BeerChipTableViewController
let index = NSIndexPath(row: 3, section: 0)
self.locationTableView.selectRow(at: index as IndexPath, animated: true, scrollPosition: UITableViewScrollPosition.middle)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var userdefaultsLocation = UserDefaults.standard.string(forKey: "location")
if userdefaultsLocation == nil {
userdefaultsLocation = "CAMILLUS"
}
locationIndicatorBtn.setTitle(userdefaultsLocation, for: .normal)
}
@IBAction func cashOutBtnAction(_ sender: Any) {
}
@IBAction func beerMenuSegmentedControlAction(_ sender: Any) {
if beerMenuSegmentedControl.selectedSegmentIndex == 0 {
print("called segmnet 0")
currentBalancedisplayLbl.text = "$7.50"
myBalanceDisplayLable.text = "$7.50"
cashOutBtnView.isHidden = false
cashOutBtnView.backgroundColor = UIColor.black
isBeerchipTableVCRemoving = true
beerChipTableVCAddingAndRemoving()
}else{
print("called segment 1")
currentBalancedisplayLbl.text = "$20.50"
myBalanceDisplayLable.text = "$20.50"
cashOutBtnView.isHidden = true
isBeerchipTableVCAdding = true
beerChipTableVCAddingAndRemoving()
}
}
@IBAction func redeemButtonAction(_ sender: Any) {
performSegue(withIdentifier: "RedeemBeerchipVCSegue", sender: self)
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "RedeemBeerchipVCSegue"
{
let destinationVC = segue.destination as! RedeemBeerchipViewController
destinationVC.redeemBeerchipVCDelegate = self
}
}
@IBAction func locationIndicatorBtnAction(_ sender: Any) {
alphaView.isHidden = false
locationTableContainerView.isHidden = false
}
func beerChipTableVCAddingAndRemoving() {
if isBeerchipTableVCAdding {
self.addChildViewController(beerchipTableVC)
beerchipTableVC.view.frame = CGRect(x: 0, y: 232, width: UIScreen.main.bounds.width, height: (beerchiptableContainerView.bounds.height))
contentView.addSubview(beerchipTableVC.view)
beerchipTableVC.didMove(toParentViewController: self)
isBeerchipTableVCAdding = false
}
if isBeerchipTableVCRemoving{
beerchipTableVC.willMove(toParentViewController: nil)
beerchipTableVC.view.removeFromSuperview()
beerchipTableVC.removeFromParentViewController()
isBeerchipTableVCRemoving = false
}
}
}
extension WelcomeViewController:redeemBeerchipVCProtocol{
func customBackButtonAction() {
beerMenuSegmentedControl.selectedSegmentIndex = 1
currentBalancedisplayLbl.text = "$20.50"
myBalanceDisplayLable.text = "$20.50"
cashOutBtnView.isHidden = true
isBeerchipTableVCAdding = true
beerChipTableVCAddingAndRemoving()
}
}
extension WelcomeViewController:UITableViewDelegate,UITableViewDataSource{
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == beerMenuTableView {
return titleArr.count+1
}else{
return locationArr.count
}
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == beerMenuTableView {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "titleCell") as!RedeemViewBeerchipTableTitleTableViewCell
cell.beerchipsLbl.text = "BEERCHIPS"
cell.abvLabel.text = "ABV"
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "subTitleCell") as! RedeemviewBeerchipTableSubTitlesTableViewCell
cell.abvValueLbl.text = abvValueArr[indexPath.row-1]
cell.beerTitleLable.text = titleArr[indexPath.row-1]
let imgName = beerMenuImagesArr[indexPath.row-1]
cell.beerDisplayImageView.image = UIImage(named: imgName)
if indexPath.row == 2{
cell.beerchipsImageView.image = nil
}
cell.beerSubTitleLbl.text = subTitleArr[indexPath.row-1]
return cell
}
}
else{
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "locationTitleCell") as! LocationTableViewCell
let label = cell.viewWithTag(99) as! UILabel
label.text = "LOCATIONS"
label.font = UIFont .systemFont(ofSize: 25.0)
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell") as! LocationTableViewCell
cell.locationNameLbl.text = locationArr[indexPath.row-1]
let backgroundView = UIView()
backgroundView.backgroundColor = #colorLiteral(red: 1, green: 0.8, blue: 0, alpha: 1)
cell.selectedBackgroundView = backgroundView
return cell
}
}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == locationTableView {
let locationName = locationArr[indexPath.row-1]
locationIndicatorBtn.setTitle(locationName, for: .normal)
alphaView.isHidden = true
locationTableContainerView.isHidden = true
usedefaults.set(locationName, forKey: "location")
}
}
}
| 37.598326 | 171 | 0.645115 |
bf945077500f69bc0ba9247c405ae27c0fd10de5 | 2,168 | // Copyright (c) 2016, RED When Excited
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import OysterKit
/// A parser for [STLR](https://github.com/SwiftStudies/OysterKit/blob/master/STLR.md) source files
public class STLRParser : Parser{
public var ast : STLRScope
/**
Creates a new instance of the parser and parses the source
- Parameter source: The STLR source
*/
public init(source:String){
ast = STLRScope(building: source)
super.init(grammar: STLR.generatedLanguage.grammar)
ast.optimize()
}
/// The errors encountered during parsing
var errors : [Error] {
return ast.errors
}
/// `true` if the STLR was succesfully compiled
public var compiled : Bool {
return ast.rules.count > 0
}
}
| 38.714286 | 99 | 0.704336 |
67dc4a74f58ad518f6acd878ddbe336df199de78 | 2,768 | //
// SupportViewController.swift
// Odysseia
//
// Created by lcr on 03/12/2020.
//
import UIKit
protocol SupportView: AnyObject {
var presenter: SupportPresentation! { get }
// View -> Presenter
func viewDidLoad()
// Presenter -> View
func error(error: Error)
func success()
func allredyPurchased()
}
class SupportViewController: UIViewController, StoryboardInstantiatable {
static var instantiateType: StoryboardInstantiateType { .initial }
var presenter: SupportPresentation!
@IBOutlet weak var purchaseButton: UIButton!
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
let navItem = UIBarButtonItem(title: L10n.Localizable.restoreButtonTitle,
style: .plain,
target: self,
action: #selector(restoreButtonTouched(_:)))
navigationItem.rightBarButtonItems = [navItem]
}
@IBAction func purchaseButtonTouched(_ sender: Any) {
presenter.purchaseButtonTouched()
}
@objc func restoreButtonTouched(_ sender: UIBarButtonItem) {
presenter.restoreButtonTouched()
}
@IBAction private func deleteKeychainButtonTouched(_ sender: Any) {
// debug only
presenter.deleteKeychainButtonTouched()
}
}
extension SupportViewController: SupportView {
func error(error: Error) {
DispatchQueue.main.async {
let alert = UIAlertController(title: L10n.Localizable.failedPurchasedTitle,
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: L10n.Localizable.ok,
style: .default,
handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func success() {
DispatchQueue.main.async {
let alert = UIAlertController(title: L10n.Localizable.successPurchasedTitle,
message: nil,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: L10n.Localizable.ok,
style: .default,
handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func allredyPurchased() {
DispatchQueue.main.async {
self.purchaseButton.setTitle(L10n.Localizable.alredyPurchasedMsg, for: .normal)
self.purchaseButton.isEnabled = false
}
}
}
| 33.349398 | 91 | 0.572616 |
282ffce0aff608cb1840a037106c010c0015f84e | 2,705 | //
// FeedbackNoteCell.swift
// SWHub
//
// Created by 杨建祥 on 2021/5/29.
//
import UIKit
class FeedbackNoteCell: BaseCollectionCell, ReactorKit.View {
let issuesSubject = PublishSubject<Void>()
lazy var label: SWFLabel = {
let label = SWFLabel.init(frame: .zero)
label.delegate = self
label.numberOfLines = 0
label.verticalAlignment = .top
let author = "\(Author.username)/\(Author.reponame)"
let text = R.string.localizable.tipsFeedback(author)
label.setText(text.styled(with: .color(.footer), .font(.normal(13))))
let range = text.range(of: author)!
let link = SWFLabelLink.init(
attributes: [
NSAttributedString.Key.foregroundColor: UIColor.primary,
NSAttributedString.Key.font: UIFont.normal(13)
],
activeAttributes: [
NSAttributedString.Key.foregroundColor: UIColor.red
],
inactiveAttributes: [
NSAttributedString.Key.foregroundColor: UIColor.gray
],
textCheckingResult:
.spellCheckingResult(
range: .init(
location: text.nsRange(from: range).location,
length: author.count)
)
)
label.addLink(link)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.addSubview(self.label)
themeService.rx
.bind({ $0.brightColor }, to: self.contentView.rx.backgroundColor)
.disposed(by: self.rx.disposeBag)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
}
override func layoutSubviews() {
super.layoutSubviews()
self.label.sizeToFit()
self.label.width = self.contentView.width - 20 * 2
self.label.height = self.contentView.height
self.label.left = self.label.leftWhenCenter
self.label.top = self.label.topWhenCenter
}
func bind(reactor: FeedbackNoteItem) {
super.bind(item: reactor)
reactor.state.map { _ in }
.bind(to: self.rx.setNeedsLayout)
.disposed(by: self.disposeBag)
}
override class func size(width: CGFloat, item: BaseCollectionItem) -> CGSize {
.init(width: width, height: 40)
}
}
extension FeedbackNoteCell: SWFLabelDelegate {
func attributedLabel(_ label: SWFLabel!, didSelectLinkWith result: NSTextCheckingResult!) {
self.issuesSubject.onNext(())
}
}
| 30.055556 | 95 | 0.594824 |
56be49251933f985fe848d629cfd4d8a516e6d82 | 1,802 | //
// AppDelegate.swift
// FirstBaseline
//
// Created by Keith Harrison https://useyourloaf.com
// Copyright (c) 2017 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| 43.95122 | 79 | 0.764151 |
114fb8bb63d832fc32d155771c80c8a34c997840 | 14,460 | //
// Logger.swift
// log4swift
//
// Created by Jérôme Duquennoy on 14/06/2015.
// Copyright © 2015 Jérôme Duquennoy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
A logger is identified by a UTI identifier, it defines a threshold level and a destination appender
*/
@objc public final class Logger: NSObject {
public enum DictionaryKey: String {
case ThresholdLevel = "ThresholdLevel"
case AppenderIds = "AppenderIds"
case Asynchronous = "Asynchronous"
}
private static let loggingQueue:DispatchQueue = {
let createdQueue: DispatchQueue
if #available(OSX 10.10, *) {
createdQueue = DispatchQueue(label: "log4swift.dispatchLoggingQueue", qos: .background, attributes: []) //(label: "log4swift.dispatchLoggingQueue", attributes: [.serial, .background])
} else {
let backgroundQueue = DispatchQueue.global(priority: .background)
createdQueue = DispatchQueue(label: "log4swift.dispatchLoggingQueue", attributes: [], target: backgroundQueue)
}
return createdQueue
}()
/// The UTI string that identifies the logger. Example : product.module.feature
public let identifier: String
internal var parent: Logger?
private var thresholdLevelStorage: LogLevel
private var appendersStorage: [Appender]
private var asynchronousStorage = false
private var timeProviderStorage: () -> Date = Date.init
/// If asynchronous is true, only the minimum of work will be done on the main thread, the rest will be deffered to a low priority background thread.
/// The order of the messages will be preserved in async mode.
@objc
public var asynchronous: Bool {
get {
if let parent = self.parent {
return parent.asynchronous
} else {
return self.asynchronousStorage
}
}
set {
self.breakDependencyWithParent()
self.asynchronousStorage = newValue
}
}
/// The threshold under which log messages will be ignored.
/// For example, if the threshold is Warning:
/// * logs issued with a Debug or Info will be ignored
/// * logs issued wiht a Warning, Error or Fatal level will be processed
@objc
public var thresholdLevel: LogLevel {
get {
if let parent = self.parent {
return parent.thresholdLevel
} else {
return self.thresholdLevelStorage
}
}
set {
self.breakDependencyWithParent()
self.thresholdLevelStorage = newValue
}
}
/// The list of destination appenders for the log messages.
@objc
public var appenders: [Appender] {
get {
if let parent = self.parent {
return parent.appenders
} else {
return self.appendersStorage
}
}
set {
self.breakDependencyWithParent()
self.appendersStorage = newValue
}
}
/// Gets/sets external time provider for log messages.
/// Default behavior is just `Date()`.
///
/// Allows to "mock" the time - could be useful in unit tests
/// which may run on some "virtual" time instead of real one.
///
/// Child loggers inherit this value so it's possible to set it only once
/// (on the `rootLogger` for example) - entire sub-hierarchy of loggers will have it.
///
@objc
public var timeProvider: () -> Date {
get {
if let parent = self.parent {
return parent.timeProvider
} else {
return self.timeProviderStorage
}
}
set {
self.breakDependencyWithParent()
self.timeProviderStorage = newValue
}
}
/// Creates a new logger with the given identifier, log level and appenders.
/// The identifier will not be modifiable, and should not be an empty string.
@objc
public init(identifier: String, level: LogLevel = LogLevel.Debug, appenders: [Appender] = []) {
self.identifier = identifier
self.thresholdLevelStorage = level
self.appendersStorage = appenders
}
@objc
convenience override init() {
self.init(identifier: "", appenders: Logger.createDefaultAppenders())
}
/// Create a logger that is a child of the given logger.
/// The created logger will follow the parent logger's configuration until it is manually modified.
@objc
public convenience init(parentLogger: Logger, identifier: String) {
self.init(identifier: identifier, level: parentLogger.thresholdLevel, appenders: [Appender]() + parentLogger.appenders)
self.parent = parentLogger
}
/// Updates the logger with the content of the configuration dictionary.
internal func update(withDictionary dictionary: Dictionary<String, Any>, availableAppenders: Array<Appender>) throws {
breakDependencyWithParent()
if let safeLevelString = dictionary[DictionaryKey.ThresholdLevel.rawValue] as? String {
if let safeLevel = LogLevel(safeLevelString) {
self.thresholdLevel = safeLevel
} else {
throw NSError.Log4swiftError(description: "Invalid '\(DictionaryKey.ThresholdLevel.rawValue)' value for logger '\(self.identifier)'")
}
}
if let appenderIds = dictionary[DictionaryKey.AppenderIds.rawValue] as? Array<String> {
appendersStorage.removeAll()
for currentAppenderId in appenderIds {
if let foundAppender = availableAppenders.find(filter: {$0.identifier == currentAppenderId}) {
appendersStorage.append(foundAppender)
} else {
throw NSError.Log4swiftError(description: "No such appender '\(currentAppenderId)' for logger \(self.identifier)")
}
}
}
if let asynchronous = dictionary[DictionaryKey.Asynchronous.rawValue] as? Bool {
self.asynchronous = asynchronous
}
}
func resetConfiguration() {
self.thresholdLevel = .Debug
self.appenders = Logger.createDefaultAppenders()
self.asynchronousStorage = false
}
// MARK: Logging methods
/// Logs the provided message with a trace level.
@nonobjc public func trace(_ format: String, _ args: CVarArg..., file: String = #file, line: Int = #line, function: String = #function) {
let formattedMessage = format.format(args: args)
self.log(message: formattedMessage, level: LogLevel.Trace, file: file, line: line, function: function)
}
/// Logs the provided message with a debug level.
@nonobjc public func debug(_ format: String, _ args: CVarArg..., file: String = #file, line: Int = #line, function: String = #function) {
let formattedMessage = format.format(args: args)
self.log(message: formattedMessage, level: LogLevel.Debug, file: file, line: line, function: function)
}
/// Logs the provided message with an info level
@nonobjc public func info(_ format: String, _ args: CVarArg..., file: String = #file, line: Int = #line, function: String = #function) {
let formattedMessage = format.format(args: args)
self.log(message: formattedMessage, level: LogLevel.Info, file: file, line: line, function: function)
}
/// Logs the provided message with a warning level
@nonobjc public func warning(_ format: String, _ args: CVarArg..., file: String = #file, line: Int = #line, function: String = #function) {
let formattedMessage = format.format(args: args)
self.log(message: formattedMessage, level: LogLevel.Warning, file: file, line: line, function: function)
}
/// Logs the provided message with an error level
@nonobjc public func error(_ format: String, _ args: CVarArg..., file: String = #file, line: Int = #line, function: String = #function) {
let formattedMessage = format.format(args: args)
self.log(message: formattedMessage, level: LogLevel.Error, file: file, line: line, function: function)
}
/// Logs the provided message with a fatal level
@nonobjc public func fatal(_ format: String, _ args: CVarArg..., file: String = #file, line: Int = #line, function: String = #function) {
let formattedMessage = format.format(args: args)
self.log(message: formattedMessage, level: LogLevel.Fatal, file: file, line: line, function: function)
}
/// Logs a the message returned by the closure with a debug level
/// If the logger's or appender's configuration prevents the message to be issued, the closure will not be called.
@nonobjc public func trace(file: String = #file, line: Int = #line, function: String = #function, closure: @escaping () -> String) {
self.log(closure: closure, level: LogLevel.Trace, file: file, line: line, function: function)
}
/// Logs a the message returned by the closure with a debug level
/// If the logger's or appender's configuration prevents the message to be issued, the closure will not be called.
@nonobjc public func debug(file: String = #file, line: Int = #line, function: String = #function, closure: @escaping () -> String) {
self.log(closure: closure, level: LogLevel.Debug, file: file, line: line, function: function)
}
/// Logs a the message returned by the closure with an info level
/// If the logger's or appender's configuration prevents the message to be issued, the closure will not be called.
@nonobjc public func info(file: String = #file, line: Int = #line, function: String = #function, closure: @escaping () -> String) {
self.log(closure: closure, level: LogLevel.Info, file: file, line: line, function: function)
}
/// Logs a the message returned by the closure with a warning level
/// If the logger's or appender's configuration prevents the message to be issued, the closure will not be called.
@nonobjc public func warning(file: String = #file, line: Int = #line, function: String = #function, closure: @escaping () -> String) {
self.log(closure: closure, level: LogLevel.Warning, file: file, line: line, function: function)
}
/// Logs a the message returned by the closure with an error level
/// If the logger's or appender's configuration prevents the message to be issued, the closure will not be called.
@nonobjc public func error(file: String = #file, line: Int = #line, function: String = #function, closure: @escaping () -> String) {
self.log(closure: closure, level: LogLevel.Error, file: file, line: line, function: function)
}
/// Logs a the message returned by the closure with a fatal level
/// If the logger's or appender's configuration prevents the message to be issued, the closure will not be called.
@nonobjc public func fatal(file: String = #file, line: Int = #line, function: String = #function, closure: @escaping () -> String) {
self.log(closure: closure, level: LogLevel.Fatal, file: file, line: line, function: function)
}
/// Returns true if a message sent with the given level will be issued by at least one appender.
public func willIssueLogForLevel(_ level: LogLevel) -> Bool {
return level.rawValue >= self.thresholdLevel.rawValue && self.appenders.reduce(false) { (shouldLog, currentAppender) in
shouldLog || level.rawValue >= currentAppender.thresholdLevel.rawValue
}
}
@nonobjc internal func log(message: String, level: LogLevel, file: String? = nil, line: Int? = nil, function: String? = nil) {
if(self.willIssueLogForLevel(level)) {
var info: LogInfoDictionary = [
.LoggerName: self.identifier,
.LogLevel: level,
.Timestamp: self.timeProvider().timeIntervalSince1970,
.ThreadId: currentThreadId(),
.ThreadName: currentThreadName()
]
if let file = file {
info[.FileName] = file
}
if let line = line {
info[.FileLine] = line
}
if let function = function {
info[.Function] = function
}
let logClosure = {
for currentAppender in self.appenders {
currentAppender.log(message, level:level, info: info)
}
}
self.executeLogClosure(logClosure)
}
}
@nonobjc internal func log(closure: @escaping () -> (String), level: LogLevel, file: String? = nil, line: Int? = nil, function: String? = nil) {
if(self.willIssueLogForLevel(level)) {
var info: LogInfoDictionary = [
.LoggerName: self.identifier,
.LogLevel: level,
.Timestamp: self.timeProvider().timeIntervalSince1970,
.ThreadId: currentThreadId(),
.ThreadName: currentThreadName()
]
if let file = file {
info[.FileName] = file
}
if let line = line {
info[.FileLine] = line
}
if let function = function {
info[.Function] = function
}
let logClosure = {
let logMessage = closure()
for currentAppender in self.appenders {
currentAppender.log(logMessage, level:level, info: info)
}
}
self.executeLogClosure(logClosure)
}
}
// MARK: Private methods
private func executeLogClosure(_ logClosure: @escaping () -> ()) {
if(self.asynchronous) {
Logger.loggingQueue.async(execute: logClosure)
} else {
logClosure()
}
}
private func breakDependencyWithParent() {
guard let parent = self.parent else {
return
}
self.thresholdLevelStorage = parent.thresholdLevel
self.appendersStorage = parent.appenders
self.timeProviderStorage = parent.timeProvider
self.parent = nil
}
private final class func createDefaultAppenders() -> [Appender] {
return [StdOutAppender("defaultAppender")]
}
}
/// returns the current thread name
private func currentThreadName() -> String {
if Thread.isMainThread {
return "main"
} else {
var name: String = Thread.current.name ?? ""
if name.isEmpty {
let queueNameBytes = __dispatch_queue_get_label(nil)
if let queuName = String(validatingUTF8: queueNameBytes) {
name = queuName
}
}
if name.isEmpty {
name = String(format: "%p", Thread.current)
}
return name
}
}
internal func currentThreadId() -> UInt64 {
var threadId: UInt64 = 0
if (pthread_threadid_np(nil, &threadId) != 0) {
threadId = UInt64(pthread_mach_thread_np(pthread_self()));
}
return threadId
}
| 39.400545 | 189 | 0.683541 |
deac9b532591b7bceddc1149379bda5a1a258649 | 2,247 | // --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
/// User-configurable options for the `PutByteValid` operation.
public struct PutByteValidOptions: RequestOptions {
/// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// Highly recommended for correlating client-side activites with requests received by the server.
public let clientRequestId: String?
/// A token used to make a best-effort attempt at canceling a request.
public let cancellationToken: CancellationToken?
/// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
public var dispatchQueue: DispatchQueue?
/// A `PipelineContext` object to associate with the request.
public var context: PipelineContext?
/// Initialize a `PutByteValidOptions` structure.
/// - Parameters:
/// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// - cancellationToken: A token used to make a best-effort attempt at canceling a request.
/// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
/// - context: A `PipelineContext` object to associate with the request.
public init(
clientRequestId: String? = nil,
cancellationToken: CancellationToken? = nil,
dispatchQueue: DispatchQueue? = nil,
context: PipelineContext? = nil
) {
self.clientRequestId = clientRequestId
self.cancellationToken = cancellationToken
self.dispatchQueue = dispatchQueue
self.context = context
}
}
| 44.058824 | 122 | 0.681353 |
72bd8581f0072a4e2deef933d63d178a6129263f | 281 | //
// PhraseSearchedUseCase.swift
// ChuckNorrisDomain
//
// Created by Fernando Cruz on 19/07/18.
// Copyright © 2018 Fernando Cruz. All rights reserved.
//
import Foundation
import RxSwift
protocol PhraseSearchedUseCase {
func phrasesSerached() -> Observable<[Joke]>
}
| 18.733333 | 56 | 0.729537 |
39020fa465db1bcafeb2c0d87c263f6010c1e871 | 358 | // 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 : BooleanType, A {
protocol A {
typealias e : b
func a<T : BooleanType, A {
let i() -> U))"[1)
let t: C {
}
}
func g: e == [Void{
return "
typealias e : c,
func a
class b: e : e
| 19.888889 | 87 | 0.673184 |
e9500d3ec15122a01a5974a0ae82f4a4d3493be9 | 515 | //
// NotificationExtension.swift
// MorseCodeApp
//
// Created by Mariusz Sut on 16/04/2019.
// Copyright © 2019 Mariusz Sut. All rights reserved.
//
import Foundation
import UIKit
extension Notification {
func getKeyboardHeight() -> CGFloat? {
return (self.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height
}
func getKeyboardDuration() -> Double? {
return self.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
}
}
| 24.52381 | 104 | 0.712621 |
e56a4eb3070efb7d5946dc272bbe8484f73761e6 | 2,172 | //
// Signal+KeyValueObserving.swift
// Flow
//
// Created by Måns Bernhardt on 2016-01-08.
// Copyright © 2016 iZettle. All rights reserved.
//
import Foundation
// https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/NSObject.swift
public extension _KeyValueCodingAndObserving {
/// Returns a signal observing the property at `keyPath` of `self` using key value observing (KVO).
func signal<T>(for keyPath: KeyPath<Self, T>) -> ReadSignal<T> {
return ReadSignal(object: self, keyPath: keyPath)
}
/// Returns a signal observing the property at `keyPath` of `self` using key value observing (KVO).
func signal<T>(for keyPath: WritableKeyPath<Self, T>) -> ReadWriteSignal<T> {
return ReadWriteSignal(object: self, keyPath: keyPath)
}
}
public extension CoreSignal where Kind == Read {
/// Creates a new instance observing the property at `keyPath` of `object` using key value observing (KVO).
convenience init<O: _KeyValueCodingAndObserving>(object: O, keyPath: KeyPath<O, Value>) {
self.init(getValue: { object[keyPath: keyPath] }, options: .shared, onInternalEvent: { callback in
let token = object.observe(keyPath, options: .new) { _, _ in
callback(.value(object[keyPath: keyPath]))
}
return Disposer { _ = token } // Hold on to reference
})
}
}
public extension CoreSignal where Kind == ReadWrite {
/// Creates a new instance observing the property at `keyPath` of `object` using key value observing (KVO).
convenience init<O: _KeyValueCodingAndObserving>(object: O, keyPath: WritableKeyPath<O, Value>) {
var object = object
self.init(getValue: { object[keyPath: keyPath] },
setValue: { object[keyPath: keyPath] = $0 },
options: .shared,
onInternalEvent: { callback in
let token = object.observe(keyPath, options: .new) { newObject, _ in
callback(.value(newObject[keyPath: keyPath]))
}
return Disposer { _ = token } // Hold on to reference
})
}
}
| 42.588235 | 111 | 0.63674 |
eb2360e09c6fdf8da80e94dc5539a313e2fe511f | 2,052 | //
// AppDelegate.swift
// Character Tracker
//
// Created by Isaac Lyons on 10/30/19.
// Copyright © 2019 Isaac Lyons. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
preloadData()
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.
}
private func preloadData() {
let preloadedDataKey = "preloadedDataVersion"
let userDefaults = UserDefaults.standard
let loadedVersion = userDefaults.string(forKey: preloadedDataKey)
if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
(loadedVersion ?? "0").compare(appVersion, options: .numeric) == .orderedAscending {
print("Preloading data...")
PortController.shared.preloadData()
userDefaults.set(appVersion, forKey: preloadedDataKey)
}
}
}
| 40.235294 | 179 | 0.717836 |
c1dd4c4abf979e0089316b6afa523ad5d30c1eec | 3,595 | //
// FactorStrategy.swift
// PFactors
//
// Created by Stephan Jancar on 18.10.17.
//
import Foundation
import BigInt
public class PrimeFactorStrategy {
var verbose = true
private let first : [UInt64] = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,5359,61,71,73,79,83,89,97]
private var rho : PrimeFaktorRho!
private var shanks : PrimeFactorShanks!
private var lehman : PrimeFactorLehman!
public init() {
self.rho = PrimeFaktorRho()
self.shanks = PrimeFactorShanks()
self.lehman = PrimeFactorLehman()
}
private func QuickTrial(ninput: BigUInt) -> (rest : BigUInt, factors : [BigUInt]) {
if verbose { print ("QuickTrial") }
var factors : [BigUInt] = []
var nn = ninput
for p in first {
let bigp = BigUInt(p)
if bigp * bigp > nn { break }
while nn % bigp == 0 {
nn = nn / bigp
factors.append(bigp)
if verbose { print("Factor:",bigp) }
}
}
return (rest: nn, factors: factors)
}
public func Factorize(ninput: BigUInt) -> [BigUInt] {
//1. Probedivision fuer sehr kleine Faktoren
var (nn,factors) = QuickTrial(ninput: ninput)
if nn == 1 { return factors }
//2. Pollards-Rho Methode fuer kleine Zahlen zur Abspaltung von Faktoren bis zur vierten Wurzel
let rhoupto = ninput.squareRoot().squareRoot()
while nn > rhoupto { //Heuristik
if verbose { print ("Rho") }
//Rest schon prim, dann fertig
if nn.isPrime() {
factors.append(nn)
if verbose { print("Factor:",nn) }
return factors
}
//Suche mit Pollards-Methode
let factor = rho.GetFactor(n: nn)
//Nichts gefunden, dann weiter mit der nächsten Methode
if factor == 0 { break }
//Ist der gefunden Faktor prim
if !factor.isPrime() {
//Der gefundene Faktor war nicht prim, dann zerlegen
let subfactors = self.Factorize(ninput: factor)
for s in subfactors {
factors.append(s);
if verbose { print("Factor:",s) }
nn = nn / s }
} else {
//Primfaktor abspalten
factors.append(factor)
if verbose { print("Factor:",factor) }
nn = nn / factor
}
}
//Wechsle zu Shanks
while nn > 1 {
if verbose { print("Shanks") }
//Rest schon prim, dann fertig
if nn.isPrime() {
factors.append(nn)
if verbose { print("Factor:",nn) }
return factors
}
//Shanks anwenden
let factor = shanks.GetFactor(n: nn)
if factor == 0 { break }
//Ist der gefunden Faktor prim
if !factor.isPrime() {
//Der gefundene Faktor war nicht prim, dann zerlegen (unwahrscheinlich)
let subfactors = self.Factorize(ninput: factor)
for s in subfactors {
factors.append(s);
if verbose { print("Factor:",s) }
nn = nn / s }
} else {
//Primfaktor abspalten
factors.append(factor)
if verbose { print("Factor:",factor) }
nn = nn / factor
}
}
//3. Letzte Retturn Fermattest
while nn > 1 {
if verbose { print("Fermat") }
if nn.isPrime() {
factors.append(nn)
if verbose { print("Factor:",nn) }
return factors
}
let factor = lehman.GetFactor(n: nn)
if factor.isPrime() {
factors.append(factor)
}
else {
let subfactors = Factorize(ninput: factor)
for s in subfactors {
factors.append(s)
if verbose { print("Factor:",s) }
}
}
nn = nn / factor
}
return factors
}
public func Factorize(s: String) -> String {
var ans = ""
guard let n = BigUInt(s) else { return "" }
let factors = Factorize(ninput: n)
var start = true
for f in factors {
if !start { ans = ans + "*" }
ans.append(String(f))
start = false
}
return ans
}
}
| 24.127517 | 100 | 0.622531 |
292fb1dfbd0b86798f209f7dc8d67f03e6e36e35 | 3,530 | import Foundation
import TSCBasic
import TuistSupport
enum SetupLoaderError: FatalError {
case setupNotFound(AbsolutePath)
var description: String {
switch self {
case let .setupNotFound(path):
return "We couldn't find a Setup.swift traversing up the directory hierarchy from the path \(path.pathString)."
}
}
var type: ErrorType {
switch self {
case .setupNotFound: return .abort
}
}
}
/// Protocol that represents an entity that knows how to get the environment status
/// for a given project and configure it.
public protocol SetupLoading {
/// It runs meet on each command if it is not met.
///
/// - Parameter path: Path to the project.
/// - Throws: An error if any of the commands exit unsuccessfully.
func meet(at path: AbsolutePath) throws
}
public class SetupLoader: SetupLoading {
/// Linter for up commands.
private let upLinter: UpLinting
/// Manifest loader instance to load the setup.
private let manifestLoader: ManifestLoading
/// Locator for `Setup.swift` file
private let manifestFilesLocator: ManifestFilesLocating
/// Default constructor.
public convenience init() {
let upLinter = UpLinter()
let manifestLoader = ManifestLoader()
let manifestFilesLocator = ManifestFilesLocator()
self.init(upLinter: upLinter, manifestLoader: manifestLoader, manifestFilesLocator: manifestFilesLocator)
}
/// Initializes the command with its arguments.
///
/// - Parameters:
/// - upLinter: Linter for up commands.
/// - manifestLoader: Manifest loader instance to load the setup.
/// - manifestFilesLocator: Locator for `Setup.swift` file
init(upLinter: UpLinting,
manifestLoader: ManifestLoading,
manifestFilesLocator: ManifestFilesLocating)
{
self.upLinter = upLinter
self.manifestLoader = manifestLoader
self.manifestFilesLocator = manifestFilesLocator
}
/// It runs meet on each command if it is not met.
///
/// - Parameter path: Path to the project.
/// - Throws: An error if any of the commands exit unsuccessfully
/// or if there isn't a `Setup.swift` file within the project path.
public func meet(at path: AbsolutePath) throws {
guard let setupPath = manifestFilesLocator.locateSetup(at: path) else { throw SetupLoaderError.setupNotFound(path) }
logger.info("Setting up the environment defined in \(setupPath.pathString)")
let setupParentPath = setupPath.parentDirectory
let setup = try manifestLoader.loadSetup(at: setupParentPath)
try setup.requires.map { command in upLinter.lint(up: command) }
.flatMap { $0 }
.printAndThrowIfNeeded()
try setup.requires.forEach { command in
if try !command.isMet(projectPath: setupParentPath) {
logger.notice("Validating \(command.name)", metadata: .subsection)
try command.meet(projectPath: setupParentPath)
}
}
try setup.actions.map { command in upLinter.lint(up: command) }
.flatMap { $0 }
.printAndThrowIfNeeded()
try setup.actions.forEach { command in
if try !command.isMet(projectPath: setupParentPath) {
logger.notice("Configuring \(command.name)", metadata: .subsection)
try command.meet(projectPath: setupParentPath)
}
}
}
}
| 36.391753 | 124 | 0.656091 |
bb3e854e05de296fd0c76273c8e00b5578903e80 | 51 | namespace "http://foo/"
namespace ns "http://bar/"
| 17 | 26 | 0.666667 |
f75f9e5a1ba7a3fc2bcf598a7f6c516e49452e27 | 2,890 | //
// EventListRow.swift
// Toast Pusher
//
// Created by Eric Lambrecht on 12.02.21.
//
import SwiftUI
struct EventListRow: View {
var event: ToastPusherNotificationEvent
var new: Bool
var highlighted: Bool
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
Spacer()
HStack(alignment: .bottom) {
Text(event.title)
.font(.headline)
.lineLimit(1)
.truncationMode(.tail)
if event.date != nil {
Text(event.date!.timeAgoDisplay())
.foregroundColor(.gray)
.font(.caption)
.padding(.bottom, 1)
}
}
Text(event.body)
.font(.subheadline)
.lineLimit(getBodyLineLimit())
.truncationMode(.tail)
Spacer()
}
.padding(.leading, getLeadingPadding())
Spacer()
if event.url != nil {
Link("Open", destination: event.url!)
.padding()
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
}
}
.frame(height: getRowHeight())
.frame(minWidth: 200)
.overlay(
new ?
getNewMarker()
: nil
, alignment: .topLeading)
.overlay(
highlighted ? Rectangle()
.foregroundColor(.clear)
.border(Color.blue, width: 2) : nil
)
}
func getLeadingPadding() -> CGFloat {
#if os(iOS)
return 16
#else
return 4.5
#endif
}
func getRowHeight() -> CGFloat {
#if os(iOS)
return 87
#else
return 50
#endif
}
func getBodyLineLimit() -> Int {
#if os(iOS)
return 2
#else
return 1
#endif
}
func getNewMarker() -> some View {
#if os(iOS)
return Rectangle()
.frame(width: 4, height: getRowHeight() - 8)
.padding(4)
.foregroundColor(.green)
#else
return Rectangle()
.frame(width: 2, height: getRowHeight() - 8)
.padding(.vertical, 4)
.foregroundColor(.green)
#endif
}
}
struct EventListRow_Previews: PreviewProvider {
static var previews: some View {
EventListRow(event: ToastPusherNotificationEvent(publishId: "id", body: "Message Body that is extremely long and I dont know", title: "eBay Kleinanzeigen", url: URL(string: "https://google.de"), date: Date()), new: true, highlighted: false)
.previewLayout(.sizeThatFits)
}
}
| 28.058252 | 248 | 0.47474 |
284b7178d5fb971cfa53d6708f14cdcc4be87225 | 7,279 | //
// GameEnemies.swift
// ForestInvasion
//
// Created by Vincent Van Wynendaele on 13/05/2021.
//
import SpriteKit
import GameplayKit
extension GameScene {
func giveMeSpawnPoint() -> CGPoint {
let randomSide=GKRandomSource.sharedRandom().nextInt(upperBound: 4)
var spawnPoint: CGPoint
switch randomSide {
case 0:
let randomHeightPosition:CGFloat = CGFloat(GKRandomSource.sharedRandom().nextInt(upperBound: 5))
spawnPoint = CGPoint(x: (self.size.width), y: (2+randomHeightPosition)*self.size.height/10)
case 1:
let randomWidthPosition:CGFloat = CGFloat(GKRandomSource.sharedRandom().nextInt(upperBound: 10))
spawnPoint = CGPoint(x: randomWidthPosition*self.size.width/10, y: 9*self.size.height/10)
case 2:
let randomWidthPosition:CGFloat = CGFloat(GKRandomSource.sharedRandom().nextInt(upperBound: 10))
spawnPoint = CGPoint(x: randomWidthPosition*self.size.width/10, y: 2*self.size.height/10)
case 3:
let randomHeightPosition:CGFloat = CGFloat(GKRandomSource.sharedRandom().nextInt(upperBound: 5))
spawnPoint = CGPoint(x: 0, y: (2+randomHeightPosition)*self.size.height/10 )
default:
spawnPoint = CGPoint(x: self.size.width, y: 9*self.size.height/10)
}
return spawnPoint
}
func spawnAnEnemy(position: CGPoint, enemyType: Enemy.EnemyType) {
let enemy = Enemy(type: enemyType)
var timeBeforeSpawning:TimeInterval
enemy.position = position
enemy.size = self.setRealSize(width: enemy.size.width , height: enemy.size.height)
if enemyType == .mole {
timeBeforeSpawning = TimeInterval(0)
} else {
timeBeforeSpawning = TimeInterval(GKRandomSource.sharedRandom().nextInt(upperBound:2))
self.stage?.enemiesSpawned += 1
}
self.run(SKAction.sequence([SKAction.wait(forDuration: timeBeforeSpawning),SKAction.run {
self.addChild(enemy)
guard let player = self.player else {return}
self.run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
if enemy.feared {
enemy.runAndSetDirection(from: player.position, to: enemy.position)
} else {
enemy.runAndSetDirection(from: enemy.position, to: player.position)
}
},SKAction.wait(forDuration: 0.8)])))
}]))
}
func spawnABatchOfEnemies() {
let amountAtTheSameSpot = GKRandomSource.sharedRandom().nextInt(upperBound: 5)
var spawnPoint = self.giveMeSpawnPoint()
for i in 0..<amountAtTheSameSpot {
spawnPoint.x = spawnPoint.x + CGFloat(i)
let randomEnemy = (self.stage?.enemyPool.randomElement()!)!
self.spawnAnEnemy(position: spawnPoint, enemyType: randomEnemy)
}
}
func startSpawning() {
if map?.actualTileType == .monster {
self.run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
self.spawnABatchOfEnemies()
}, SKAction.wait(forDuration: self.stage!.timeBetweenBatch )])),withKey: "Spawning")
}
}
func playAnimation(animation: String, position: CGPoint) {
if animation == "death" {
let texture = SKSpriteNode(imageNamed: "enemyDeath1")
texture.size = self.setRealSize(width: (texture.texture?.size().width)! , height: (texture.texture?.size().height)!)
texture.position = position
texture.zPosition = 3
self.addChild(texture)
texture.run(SKAction.sequence([SKAction.animate(with: [SKTexture(imageNamed: "enemyDeath1"),SKTexture(imageNamed: "enemyDeath2"),SKTexture(imageNamed: "enemyDeath3"),SKTexture(imageNamed: "enemyDeath4"),SKTexture(imageNamed: "enemyDeath5"),SKTexture(imageNamed: "enemyDeath6")], timePerFrame: 0.1), SKAction.run {
texture.removeFromParent()
}]))
} else if animation == "smoke" {
let texture = SKSpriteNode(imageNamed: "smoke1")
texture.size = self.setRealSize(width: (texture.texture?.size().width)! , height: (texture.texture?.size().height)!)
texture.position = position
texture.zPosition = 3
self.addChild(texture)
texture.run(SKAction.sequence([SKAction.animate(with: [SKTexture(imageNamed: "smoke1"),SKTexture(imageNamed: "smoke2"),SKTexture(imageNamed: "smoke3"),SKTexture(imageNamed: "smoke4"),SKTexture(imageNamed: "smoke5"),SKTexture(imageNamed: "smoke6"),SKTexture(imageNamed: "smoke7"),SKTexture(imageNamed: "smoke8"),SKTexture(imageNamed: "smoke9"),SKTexture(imageNamed: "smoke10"),SKTexture(imageNamed: "smoke11"),SKTexture(imageNamed: "smoke12"),SKTexture(imageNamed: "smoke13"),SKTexture(imageNamed: "smoke14"),SKTexture(imageNamed: "smoke15"),SKTexture(imageNamed: "smoke16"),SKTexture(imageNamed: "smoke17")], timePerFrame: 0.05), SKAction.run {
texture.removeFromParent()
}]))
} else if animation == "wisp" {
let texture = SKSpriteNode(imageNamed: "wisp1")
texture.size = self.setRealSize(width: 2*(texture.texture?.size().width)! , height: 2*(texture.texture?.size().height)!)
texture.position = position
texture.zPosition = 3
self.addChild(texture)
texture.run(SKAction.sequence([SKAction.animate(with: [SKTexture(imageNamed: "wisp1"),SKTexture(imageNamed: "wisp2"),SKTexture(imageNamed: "wisp3"),SKTexture(imageNamed: "wisp4"),SKTexture(imageNamed: "wisp5"),SKTexture(imageNamed: "wisp6"),SKTexture(imageNamed: "wisp7"),SKTexture(imageNamed: "wisp8"),SKTexture(imageNamed: "wisp9"),SKTexture(imageNamed: "wisp10"),SKTexture(imageNamed: "wisp11"),SKTexture(imageNamed: "wisp12"),SKTexture(imageNamed: "wisp13"),SKTexture(imageNamed: "wisp14"),SKTexture(imageNamed: "wisp15"),SKTexture(imageNamed: "wisp16"),SKTexture(imageNamed: "wisp17"),SKTexture(imageNamed: "wisp18"),SKTexture(imageNamed: "wisp19"),SKTexture(imageNamed: "wisp20"),SKTexture(imageNamed: "wisp21"),SKTexture(imageNamed: "wisp22"),SKTexture(imageNamed: "wisp23"),SKTexture(imageNamed: "wisp24")], timePerFrame: 0.05), SKAction.run {
texture.removeFromParent()
}]))
} else if animation == "ground" {
let texture = SKSpriteNode(imageNamed: "ground1")
texture.size = self.setRealSize(width: (texture.texture?.size().width)! , height: (texture.texture?.size().height)!)
texture.position = position
texture.zPosition = 3
self.addChild(texture)
texture.run(SKAction.sequence([SKAction.animate(with: [SKTexture(imageNamed: "ground1"),SKTexture(imageNamed: "ground2"),SKTexture(imageNamed: "ground3"),SKTexture(imageNamed: "ground4"),SKTexture(imageNamed: "ground5"),SKTexture(imageNamed: "ground6"),SKTexture(imageNamed: "ground7"),SKTexture(imageNamed: "ground8"),SKTexture(imageNamed: "ground9"),SKTexture(imageNamed: "ground10")], timePerFrame: 0.05), SKAction.run {
texture.removeFromParent()
}]))
}
}
}
| 59.178862 | 863 | 0.653799 |
d92fe437306319d97458ef24ab32314899f30942 | 989 | //
// SignInViewController.swift
// Dropbox
//
// Created by Zach Cole on 2/4/16.
// Copyright © 2016 Zach Cole. All rights reserved.
//
import UIKit
class SignInViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButton(sender: UIButton) {
navigationController!.popViewControllerAnimated(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 25.358974 | 106 | 0.679474 |
eddfe6de7681a53dde65e272df4acb7f307511b1 | 2,613 | //
// WalletOverlayView.swift
// auroracoin
//
// Created by Yoshi Jäger on 04.08.18.
// Copyright © 2018 breadwallet LLC. All rights reserved.
//
import UIKit
/* shadow and shape overlay for wallet transaction card */
class WalletOverlayView: UIView {
private let shape: CAShapeLayer
override init(frame: CGRect) {
shape = CAShapeLayer()
super.init(frame: frame)
layer.addSublayer(shape)
style()
}
private func style() {
shape.lineWidth = 1
// #191A29
shape.fillColor = UIColor(red: 0x01 / 255, green: 0x69 / 255, blue: 0x59 / 255, alpha: 1).cgColor //0x191a29 //016959
shape.strokeColor = UIColor.clear.cgColor
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.13;
layer.shadowOffset = CGSize(width: 0, height: -7.0);
layer.shadowRadius = 5.0;
layer.masksToBounds = false;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func recalc() {
let cutStart: CGFloat = shape.frame.height * 1 / 3
let curveStart: CGFloat = shape.frame.width * 1 / 6
let middle: CGFloat = shape.frame.width / 2
let curveStrengthBottom: CGFloat = 0.6
let curveStrength: CGFloat = 0.2
let curveEnd: CGFloat = shape.frame.width - curveStart
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: shape.frame.height))
path.addLine(to: CGPoint(x: 0, y: cutStart))
path.addLine(to: CGPoint(x: curveStart, y: cutStart))
path.addCurve(
to: CGPoint(x: middle, y: 0),
controlPoint1: CGPoint(x: middle * (1 - curveStrength), y: cutStart),
controlPoint2: CGPoint(x: curveStart * (1 + curveStrengthBottom), y: 0)
)
path.addCurve(
to: CGPoint(x: curveEnd, y: cutStart),
controlPoint1: CGPoint(x: shape.frame.width - curveStart * (1 + curveStrengthBottom), y: 0),
controlPoint2: CGPoint(x: shape.frame.width - middle * (1 - curveStrength), y: cutStart)
)
path.addLine(to: CGPoint(x: shape.frame.width, y: cutStart))
path.addLine(to: CGPoint(x: shape.frame.width, y: shape.frame.height))
path.close()
path.fill()
shape.path = path.cgPath
shape.shadowPath = path.cgPath
}
override func layoutSubviews() {
super.layoutSubviews()
shape.frame = self.layer.bounds
recalc()
}
}
| 32.6625 | 125 | 0.591657 |
ccbf3a6dc677c20a9c33d31ef10f507616120118 | 309 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
ject, ]
[]
class a<T where h : C {
let f {
let a {
ext
}
if true {
}
{
var f f = c< where S< H.c
if true {
class B<b: a {
import Foundation
| 16.263158 | 87 | 0.679612 |
2264d3155fab060ce5491dee8af8522719a8dd6c | 3,191 | //
// HttpClientTest.swift
// MochaUtilities
//
// Created by Gregory Sholl e Santos on 09/06/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
@testable import MochaUtilities
class HttpClientTest: XCTestCase {
private var mainUrl = "https://httpbin.org"
override func setUp() {
super.setUp()
}
func testRequestWithoutUrl() {
let expect = expectation(description: "HttpHelper returns data through closure.")
var response : Result<Data>!
let handler = { (result: Result<Data>) in
response = result
expect.fulfill()
}
let httpHelper = HttpClient.Builder(build: {
$0.handler = handler
}).build()
httpHelper.get()
waitForExpectations(timeout: 60) { error in
if error != nil {
XCTAssert(false)
}
switch response! {
case .failure(let error):
switch error {
case .descriptive(_):
XCTAssert(true)
default:
XCTAssert(false)
}
case .success(_):
XCTAssert(false)
}
}
}
func testGet() {
let expect = expectation(description: "HttpHelper returns data through closure.")
var response : Result<Data>!
let handler = { (result: Result<Data>) in
response = result
expect.fulfill()
}
let httpHelper = getDefaultBuilder(url: "/get", handler: handler).build()
httpHelper.get()
}
func testPost() {
let expect = expectation(description: "HttpHelper returns data through closure.")
var response : Result<Data>!
let handler = { (result: Result<Data>) in
response = result
expect.fulfill()
}
let builder = getDefaultBuilder(url: "/post", handler: handler)
builder.parameters = ["obj1": "content1", "obj2": "content2"]
builder.contentType = .json
builder.build().post()
waitForExpectations(timeout: 5) { error in
switch response! {
case .failure(let error):
XCTAssert(false, error.localizedDescription)
case .success(let data):
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
guard let jsonDict = json as? [String: Any] else {
XCTAssert(false, "'json' is not a dictionary")
return
}
print("\(jsonDict)")
XCTAssert(true)
} catch let jsonError {
XCTAssert(false, jsonError.localizedDescription)
}
}
}
}
private func getDefaultBuilder(url: String, handler: @escaping HttpClient.Handler) -> HttpClient.Builder {
return HttpClient.Builder(build: {
$0.url = mainUrl + url
$0.handler = handler
})
}
}
| 29.275229 | 110 | 0.517393 |
bf17ed83c5dc265d001968c6100d23beebc3b0e7 | 1,183 | //
// ClearNumberPad.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-03-16.
// Copyright © 2017 breadwallet LLC. All rights reserved.
//
import UIKit
class ClearNumberPad: GenericPinPadCell {
override func setAppearance() {
if text == "0" {
topLabel.isHidden = true
centerLabel.isHidden = false
} else {
topLabel.isHidden = false
centerLabel.isHidden = true
}
topLabel.textColor = .white
centerLabel.textColor = .white
sublabel.textColor = .white
if isHighlighted {
backgroundColor = .transparentBlack
} else {
if text == "" || text == deleteKeyIdentifier {
backgroundColor = .clear
imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .white
} else {
backgroundColor = .transparentWhite
}
}
}
override func setSublabel() {
guard let text = self.text else { return }
if sublabels[text] != nil {
sublabel.text = sublabels[text]
}
}
}
| 25.170213 | 85 | 0.558749 |
0a0bc28698af4d837ac515a77cb1e7403ab333df | 206 | //
// FF_ComputerCommand.swift
// Command-ex
//
// Created by ffwang on 2017/6/14.
// Copyright © 2017年 ffwang. All rights reserved.
//
import Cocoa
protocol FF_ComputerCommand {
func execute()
}
| 14.714286 | 50 | 0.684466 |
280e6b55b0644569bc084f17eea93393a94eba71 | 1,549 | // ArrayLoader
// Written in 2015 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
@testable import ArrayLoader
import XCTest
class InfoLoadRequestTests: XCTestCase
{
func testNext()
{
let request = InfoLoadRequest<Int, Int>.Next(current: [], info: 0)
XCTAssertTrue(request.isNext)
XCTAssertFalse(request.isPrevious)
}
func testPrevious()
{
let request = InfoLoadRequest<Int, Int>.Previous(current: [], info: 0)
XCTAssertTrue(request.isPrevious)
XCTAssertFalse(request.isNext)
}
func testCurrent()
{
let previous = InfoLoadRequest<Int, Int>.Previous(current: [0, 1, 2, 3], info: 0)
XCTAssertEqual(previous.current, [0, 1, 2, 3])
let next = InfoLoadRequest<Int, Int>.Previous(current: [0, 1, 2, 3], info: 0)
XCTAssertEqual(next.current, [0, 1, 2, 3])
}
func testInfo()
{
let previous = InfoLoadRequest<Int, Int>.Next(current: [], info: 10)
XCTAssertEqual(previous.info, 10)
let next = InfoLoadRequest<Int, Int>.Next(current: [], info: 10)
XCTAssertEqual(next.info, 10)
}
}
| 32.270833 | 89 | 0.652034 |
56d9e3f72f4ca8f313074540da79c4fc33221f8f | 13,277 | import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import NVActivityIndicatorView
import Contacts
protocol EmptyFeedPostCellDelegate {
func didTapUser(user: User)
func handleShowNewGroup()
func didTapImportContacts()
func requestImportContactsIfAuth()
func didFollowFirstUser()
}
class EmptyFeedPostCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, EmptyFeedUserCellDelegate, ImportContactsCellDelegate {
let padding: CGFloat = 12
var fetchedAllGroups: Bool? {
didSet {
setLoadingVisibility(fetchedAllGroups: fetchedAllGroups!)
}
}
var delegate: EmptyFeedPostCellDelegate?
var recommendedUsers: [User]? {
didSet {
}
}
var collectionView: UICollectionView!
let endLabel: UILabel = {
let label = UILabel()
label.isHidden = true
label.textColor = UIColor.black
label.attributedText = NSMutableAttributedString(string: "You're All Caught Up!", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)])
label.numberOfLines = 0
label.size(22)
label.textAlignment = .center
return label
}()
let endLabelNoRecommended: UILabel = {
let label = UILabel()
label.isHidden = true
label.textColor = UIColor.black
label.attributedText = NSMutableAttributedString(string: "You're All Caught Up!", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)])
label.numberOfLines = 0
label.size(22)
label.textAlignment = .center
return label
}()
let recommendedLabel: UILabel = {
let label = UILabel()
label.isHidden = true
label.textColor = UIColor.black
let attributedText = NSMutableAttributedString(string: "Follow suggested users\n", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)])
attributedText.append(NSMutableAttributedString(string: "to have their public groups in your feed", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14)]))
label.attributedText = attributedText
label.numberOfLines = 0
label.size(22)
label.textAlignment = .center
return label
}()
private lazy var newGroupButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(didTapNewGroup), for: .touchUpInside)
button.layer.zPosition = 4;
button.isHidden = true
button.backgroundColor = UIColor(white: 0.9, alpha: 1)
button.setTitleColor(.black, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.setTitle("Create a new Group", for: .normal)
return button
}()
let logoImageView: UIImageView = {
let img = UIImageView()
img.image = #imageLiteral(resourceName: "icon_login_4")
img.isHidden = true
return img
}()
let activityIndicatorView = NVActivityIndicatorView(frame: CGRect(x: UIScreen.main.bounds.width/2 - 35, y: UIScreen.main.bounds.height/2 - 35, width: 70, height: 70), type: NVActivityIndicatorType.circleStrokeSpin)
var activityIndicator = UIActivityIndicatorView()
static var cellId = "emptyFeedPostCellId"
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
override func prepareForReuse() {
super.prepareForReuse()
endLabel.isHidden = true
endLabelNoRecommended.isHidden = true
activityIndicatorView.isHidden = false
recommendedLabel.isHidden = true
newGroupButton.isHidden = true
collectionView.isHidden = true
logoImageView.isHidden = true
}
private func sharedInit() {
addSubview(endLabel)
endLabel.anchor(top: topAnchor, left: leftAnchor, right: rightAnchor, paddingTop: UIScreen.main.bounds.height/8 - 40)
addSubview(endLabelNoRecommended)
endLabelNoRecommended.anchor(top: topAnchor, left: leftAnchor, right: rightAnchor, paddingTop: UIScreen.main.bounds.height/2.2 - 60)
// insertSubview(activityIndicatorView, at: 20)
// activityIndicatorView.isHidden = true
// activityIndicatorView.color = .black
// activityIndicatorView.startAnimating()
addSubview(newGroupButton)
newGroupButton.frame = CGRect(x: UIScreen.main.bounds.width/2-150, y: UIScreen.main.bounds.height/4 * 3 + 30 - 60, width: 300, height: 50)
newGroupButton.layer.cornerRadius = 14
addSubview(recommendedLabel)
recommendedLabel.frame = CGRect(x: UIScreen.main.bounds.width/2-150, y: UIScreen.main.bounds.height/3 - 40 - 60, width: 300, height: 60)
addSubview(logoImageView)
logoImageView.frame = CGRect(x: frame.width/2 - 100, y: 80 - 60, width: 200, height: 200)
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionView.ScrollDirection.horizontal
layout.itemSize = CGSize(width: 140, height: 190)
layout.minimumLineSpacing = CGFloat(15)
collectionView = UICollectionView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height/3 + 20 - 60, width: UIScreen.main.bounds.width, height: 210), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView.register(EmptyFeedUserCell.self, forCellWithReuseIdentifier: EmptyFeedUserCell.cellId)
collectionView.register(ImportContactsCell.self, forCellWithReuseIdentifier: ImportContactsCell.cellId)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isUserInteractionEnabled = true
// collectionView.allowsSelection = true
collectionView.backgroundColor = UIColor.clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.isHidden = true
insertSubview(collectionView, at: 10)
fetchRecommendedUsers()
// set the shadow of the view's layer
collectionView.layer.backgroundColor = UIColor.clear.cgColor
collectionView.layer.shadowColor = UIColor.black.cgColor
collectionView.layer.shadowOffset = CGSize(width: 0, height: 1.0)
collectionView.layer.shadowOpacity = 0.2
collectionView.layer.shadowRadius = 3.0
}
func fetchRecommendedUsers(){
guard let currentLoggedInUserId = Auth.auth().currentUser?.uid else { return }
Database.database().fetchFollowRecommendations(withUID: currentLoggedInUserId, completion: { (recommended_users) in
self.recommendedUsers = recommended_users
self.setRecommendedVisibility()
self.collectionView?.reloadData()
self.requestImportContacts()
}) { (err) in
}
}
func requestImportContacts(){
guard recommendedUsers != nil else { return }
guard let fetchedAllGroups = fetchedAllGroups else { return }
if fetchedAllGroups {
print("sending request")
self.delegate?.requestImportContactsIfAuth()
}
}
func setRecommendedVisibility() {
guard let recommendedUsers = recommendedUsers else { return }
guard let fetchedAllGroups = fetchedAllGroups else { return }
if recommendedUsers.count == 0 && (CNContactStore.authorizationStatus(for: .contacts) == .authorized || CNContactStore.authorizationStatus(for: .contacts) == .denied) && fetchedAllGroups {
collectionView.isHidden = true
recommendedLabel.isHidden = true
endLabel.isHidden = true
endLabelNoRecommended.isHidden = false
logoImageView.isHidden = false
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if CNContactStore.authorizationStatus(for: .contacts) != .authorized && CNContactStore.authorizationStatus(for: .contacts) != .denied {
return (recommendedUsers?.count ?? 0) + 1
}
return recommendedUsers?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if CNContactStore.authorizationStatus(for: .contacts) != .authorized && CNContactStore.authorizationStatus(for: .contacts) != .denied && indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImportContactsCell.cellId, for: indexPath) as! ImportContactsCell
cell.layer.cornerRadius = 7
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.clear.cgColor
cell.layer.masksToBounds = true
cell.delegate = self
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmptyFeedUserCell.cellId, for: indexPath) as! EmptyFeedUserCell
if recommendedUsers != nil && recommendedUsers!.count > 0 {
if CNContactStore.authorizationStatus(for: .contacts) != .authorized && CNContactStore.authorizationStatus(for: .contacts) != .denied {
// need to do minus 1 here because first cell is taken up by the import contact cell
// so all are shifted right by 1
cell.user = recommendedUsers![indexPath.row - 1]
}
else {
cell.user = recommendedUsers![indexPath.row]
}
}
cell.layer.cornerRadius = 7
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.clear.cgColor
cell.layer.masksToBounds = true
cell.delegate = self
return cell
}
}
func didTapUser(user: User) {
self.delegate?.didTapUser(user: user)
}
// Follow the user, and remove from the collectionview
// Don't need to set 1000 as that happens in cloud function
func didFollowUser(user: User) {
Database.database().followUser(withUID: user.uid) { (err) in
if err != nil {
return
}
// remove from recommendedUsers and refresh the collectionview
if self.recommendedUsers != nil && self.recommendedUsers!.count > 0 {
self.recommendedUsers!.removeAll(where: { $0.uid == user.uid })
}
self.collectionView.reloadData()
// check if this is the first time the user has followed someone and if so, show the popup
Database.database().hasFollowedSomeone(completion: { (hasFollowed) in
if !hasFollowed {
// add them to followed someone
// send notification to show popup
Database.database().followedSomeone() { (err) in }
self.delegate?.didFollowFirstUser()
}
})
Database.database().createNotification(to: user, notificationType: NotificationType.newFollow) { (err) in
if err != nil {
return
}
}
}
}
func didRemoveUser(user: User) {
// set to 1000 and remove from collectionview
Database.database().removeFromFollowRecommendation(withUID: user.uid) { (err) in
if err != nil {
return
}
if self.recommendedUsers != nil && self.recommendedUsers!.count > 0 {
self.recommendedUsers!.removeAll(where: { $0.uid == user.uid })
}
self.collectionView.reloadData()
}
}
@objc func didTapNewGroup(){
self.delegate?.handleShowNewGroup()
}
func setLoadingVisibility(fetchedAllGroups: Bool){
if fetchedAllGroups {
activityIndicatorView.isHidden = true
endLabel.isHidden = false
newGroupButton.isHidden = false
recommendedLabel.isHidden = false
collectionView.isHidden = false
self.setRecommendedVisibility()
self.requestImportContacts()
}
}
func didTapImportContacts() {
self.delegate?.didTapImportContacts()
}
}
extension EmptyFeedPostCell: UICollectionViewDelegateFlowLayout {
private func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlowLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 140, height: 190)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
}
}
| 41.883281 | 218 | 0.645854 |
18f307d47454476fadaaa3e2f481ffb5b8c306bc | 3,624 | //
// FileUtility.swift
// Universe Docs Brain
//
// Created by Kumar Muthaiah on 24/07/19.
//
//Copyright 2020 Kumar Muthaiah
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import Cocoa
#if targetEnvironment(macCatalyst)
import AppKit
#endif
public class FileUtility {
public func writeFile(fileName: String, contents: String)
{
#if targetEnvironment(macCatalyst)
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(fileName)
//writing
do {
try contents.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {
print("FileUtility: \(error)")
}
}
#endif
}
public func getFileLines(fileUrl: String) -> [String] {
var lines = [String]()
// make sure the file exists
guard FileManager.default.fileExists(atPath: fileUrl) else {
preconditionFailure("file expected at \(fileUrl) is missing")
}
// open the file for reading
// note: user should be prompted the first time to allow reading from this location
guard let filePointer:UnsafeMutablePointer<FILE> = fopen(fileUrl,"r") else {
preconditionFailure("Could not open file at \(fileUrl)")
}
// a pointer to a null-terminated, UTF-8 encoded sequence of bytes
var lineByteArrayPointer: UnsafeMutablePointer<CChar>? = nil
// the smallest multiple of 16 that will fit the byte array for this line
var lineCap: Int = 0
// initial iteration
var bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
defer {
// remember to close the file when done
fclose(filePointer)
}
while (bytesRead > 0) {
// note: this translates the sequence of bytes to a string using UTF-8 interpretation
let lineAsString = String.init(cString:lineByteArrayPointer!)
// do whatever you need to do with this single line of text`
// for debugging, can print it
lines.append(lineAsString)
// updates number of bytes read, for the next iteration
bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
}
return lines
}
/**
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
*/
}
| 37.75 | 462 | 0.653422 |
147514bb438ee32a08b302224b02c02c504537d2 | 545 | protocol SimpleIdentificationModuleInput: class {
}
protocol SimpleIdentificationModuleOutput: class {
func identificationDidFinishSuccess()
func identificationDidClose()
}
struct SimpleIdentificationInputData {
let merchantToken: String
let language: String?
let isLoggingEnabled: Bool
init(merchantToken: String,
language: String? = nil,
isLoggingEnabled: Bool) {
self.merchantToken = merchantToken
self.language = language
self.isLoggingEnabled = isLoggingEnabled
}
}
| 23.695652 | 50 | 0.719266 |
4b5825bcb0edbfd4d6061964fc5ed2b37c80338e | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let b = compose ( [ {
{
}
}
Void{
class
case ,
| 18 | 87 | 0.717593 |
2fffacb0a9d6d659a8a6a46ce3742e89c8fdfd6f | 3,368 | import XCTest
@testable import IO
@testable import Core
@testable import Venice
public class TCPTests: XCTestCase {
func testConnectionRefused() throws {
let deadline = 1.minute.fromNow()
let connection = try TCPStream(host: "127.0.0.1", port: 8001, deadline: deadline)
XCTAssertThrowsError(try connection.open(deadline: deadline))
}
func testReadWriteClosedSocket() throws {
let deadline = 1.minute.fromNow()
let port = 8002
let channel = try Channel<Void>()
let buffer = UnsafeMutableRawBufferPointer.allocate(count: 1)
defer {
buffer.deallocate()
}
let coroutine = try Coroutine {
do {
let host = try TCPHost(port: port)
let stream = try host.accept(deadline: deadline)
try channel.receive(deadline: deadline)
try stream.close(deadline: deadline)
XCTAssertThrowsError(try stream.write("123", deadline: deadline))
XCTAssertThrowsError(try stream.read(buffer, deadline: deadline))
try channel.receive(deadline: deadline)
} catch {
XCTFail("\(error)")
}
}
let stream = try TCPStream(host: "127.0.0.1", port: port, deadline: deadline)
try stream.open(deadline: deadline)
try channel.send(deadline: deadline)
try stream.close(deadline: deadline)
XCTAssertThrowsError(try stream.close(deadline: deadline))
XCTAssertThrowsError(try stream.write("123", deadline: deadline))
XCTAssertThrowsError(try stream.read(buffer, deadline: deadline))
try channel.send(deadline: deadline)
coroutine.cancel()
}
func testClientServer() throws {
let deadline = 1.minute.fromNow()
let port = 8004
let channel = try Channel<Void>()
let buffer = UnsafeMutableRawBufferPointer.allocate(count: 10)
defer {
buffer.deallocate()
}
let coroutine = try Coroutine {
do {
let host = try TCPHost(port: port)
let stream = try host.accept(deadline: deadline)
try stream.write("Yo client!", deadline: deadline)
let read: String = try stream.read(buffer, deadline: deadline)
XCTAssertEqual(read, "Yo server!")
try stream.close(deadline: deadline)
try channel.send(deadline: deadline)
} catch {
XCTFail("\(error)")
}
}
let stream = try TCPStream(host: "127.0.0.1", port: port, deadline: deadline)
try stream.open(deadline: deadline)
let read: String = try stream.read(buffer, deadline: deadline)
XCTAssertEqual(read, "Yo client!")
try stream.write("Yo server!", deadline: deadline)
try stream.close(deadline: deadline)
try channel.receive(deadline: deadline)
coroutine.cancel()
}
}
extension TCPTests {
public static var allTests: [(String, (TCPTests) -> () throws -> Void)] {
return [
("testConnectionRefused", testConnectionRefused),
("testReadWriteClosedSocket", testReadWriteClosedSocket),
("testClientServer", testClientServer),
]
}
}
| 36.608696 | 89 | 0.592043 |
ac447d68c2e5941bb9c8ef201c391ebe8c7c06ad | 1,692 | /*
*
* Copyright 2018 APPNEXUS 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 UIKit
import AppNexusSDK
class ViewController: UIViewController, ANBannerAdViewDelegate {
@IBOutlet weak var banner = ANBannerAdView()
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.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
banner?.adSize = CGSize(width: 300, height: 250)
banner?.placementId = "13844648"
banner?.gender = .female
banner?.age = "18 - 24"
banner?.rootViewController = self;
banner?.delegate = self
banner?.loadAd()
}
//delegate methods
func adDidReceiveAd(_ ad: Any!) {
print("adDidReceiveAd");
}
func ad(_ ad: Any!, requestFailedWithError error: Error!) {
print("Ad requestFailedWithError");
}
}
| 29.684211 | 80 | 0.648345 |
fc0e064ac617085e56dbd04c780eb9119fdb0650 | 462 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct c<d where h: e
protocol P {
func c> {
return ")
}
if c {
| 30.8 | 79 | 0.733766 |
e80aac90467e16956c45adaa5f60ebd149260c54 | 1,320 | //
// MovieListViewStateTests.swift
// ReduxMovieDBTests
//
// Created by Matheus Cardoso on 12/27/18.
// Copyright © 2018 Matheus Cardoso. All rights reserved.
//
import ReSwift
import XCTest
@testable import ReduxMovieDB
class MovieListViewStateTests: XCTestCase {
func testInitWithSearchStateCanceled() {
var state = MainState()
state.search = .canceled
let viewState = MovieListViewState(state)
XCTAssertEqual(viewState.searchBarText, "")
XCTAssertEqual(viewState.searchBarShowsCancel, false)
XCTAssertEqual(viewState.searchBarFirstResponder, false)
}
func testInitWithSearchStateReady() {
var state = MainState()
state.search = .ready
let viewState = MovieListViewState(state)
XCTAssertEqual(viewState.searchBarText, "")
XCTAssertEqual(viewState.searchBarShowsCancel, true)
XCTAssertEqual(viewState.searchBarFirstResponder, true)
}
func testInitWithSearchStateSearching() {
var state = MainState()
state.search = .searching("test")
let viewState = MovieListViewState(state)
XCTAssertEqual(viewState.searchBarText, "test")
XCTAssertEqual(viewState.searchBarShowsCancel, true)
XCTAssertEqual(viewState.searchBarFirstResponder, true)
}
}
| 29.333333 | 64 | 0.706061 |
9b455aa49904279cdef243a26be956d87978f508 | 1,404 | //
// CoreDataRootTest.swift
// HMRequestFrameworkTests
//
// Created by Hai Pham on 10/8/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import RxBlocking
import RxTest
import SwiftUtilities
import SwiftUtilitiesTests
import XCTest
@testable import HMRequestFramework
public class CoreDataRootTest: RootTest {
public typealias Req = HMCDRequestProcessor.Req
var dummyCount: Int!
var manager: HMCDManager!
var dbProcessor: HMCDRequestProcessor!
override public func setUp() {
super.setUp()
dummyCount = 100
manager = Singleton.coreDataManager(.background, .InMemory)
dbProcessor = Singleton.dbProcessor(manager!)
}
}
extension CoreDataRootTest {
func dummy1FetchRequest() -> Req {
return Req.builder()
.with(poType: Dummy1.self)
.with(operation: .fetch)
.with(predicate: NSPredicate(value: true))
.with(sortDescriptors: NSSortDescriptor(key: "id", ascending: true))
.build()
}
}
extension CoreDataRootTest {
func dummy2FetchRequest() -> Req {
return Req.builder()
.with(cdType: CDDummy2.self)
.with(operation: .fetch)
.with(predicate: NSPredicate(value: true))
.with(sortDescriptors: NSSortDescriptor(key: "id", ascending: true))
.build()
}
}
| 26.490566 | 80 | 0.655271 |
1d0cb2ad87bff95ada3e6df2f409c02276f5fa35 | 320 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import EssentialFeed
class FeedLoaderStub: FeedLoader {
private let result: FeedLoader.Result
init(result: FeedLoader.Result) {
self.result = result
}
func load(completion: @escaping (FeedLoader.Result) -> Void) {
completion(result)
}
}
| 17.777778 | 63 | 0.725 |
dd5e9e31cbb16aa2c88778b3543c4aad0108a107 | 3,050 | //
// EmojiMemoryGameView.swift
// Memorize
//
// Created by Luciano Nunes de Siqueira on 13/05/21.
//
//VIEW
import SwiftUI
struct EmojiMemoryGameView: View {
@ObservedObject var viewModel: EmojiMemoryGame
var body: some View {
VStack {
Grid(viewModel.cards) { card in
CardView(card: card).onTapGesture {
withAnimation(.linear(duration: 0.75)){
viewModel.choose(card: card)
}
}
.padding(5)
}
.padding()
.foregroundColor(Color.orange)
Button(action: {
withAnimation(.easeInOut)
{
viewModel.resetGame()
}
}, label: { Text ("New Game" )})
}
}
}
struct CardView: View{
var card: MemoryGame<String>.Card
var body : some View {
GeometryReader { geometry in
self.body(for: geometry.size)
}
}
@State private var animatedBonusRemaining: Double = 0
private func startBonusTimeAnumation() {
animatedBonusRemaining = card.bonusRemaining
withAnimation(.linear(duration: card.bonusTimeRemaining)) {
animatedBonusRemaining = 0
}
}
@ViewBuilder
private func body(for size: CGSize) -> some View {
if card.isFaceUp || !card.isMatched {
ZStack {
Group {
if card.isConsumingBonusTime{
Pie(startAngle: Angle.degrees(0-90), endAngle: Angle.degrees(-animatedBonusRemaining*360-90), clockwise: true)
.onAppear{
startBonusTimeAnumation()
}
} else {
Pie(startAngle: Angle.degrees(0-90), endAngle: Angle.degrees(-card.bonusRemaining*360-90), clockwise: true)
}
}
.padding(5).opacity(0.4)
.transition(.identity)
Text(card.content)
.font(Font.system(size: fontSize(for: size)))
.rotationEffect(Angle.degrees(card.isMatched ? 360 : 0))
.animation(card.isMatched ? Animation.linear(duration: 1).repeatForever(autoreverses: false) : .default)
}
.cardify (isFaceUp: card.isFaceUp)
.transition(AnyTransition.scale)
}
}
//MARK: - Drawing Constants
private let cornerRadius: CGFloat = 10.0
private let edgeLineWidth: CGFloat = 3
private let fontScaleFactor: CGFloat = 0.75
private func fontSize(for size: CGSize) -> CGFloat {
min(size.width,size.height) * 0.7
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let game = EmojiMemoryGame()
game.choose(card: game.cards[0])
return EmojiMemoryGameView(viewModel: game )
}
}
| 28.504673 | 134 | 0.525574 |
293b640b192706271d4537f742f745ea0bfe2876 | 1,835 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections 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
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import CollectionsBenchmark
final class BinarySearchTests: XCTestCase {
func testBinarySearch() {
for count in [0, 1, 2, 100] {
for dupes in 0 ..< 10 {
for offset in 0 ..< count {
var items: [Int] = []
items.append(contentsOf: 0 ..< offset)
items.append(contentsOf: Array(repeating: offset, count: dupes))
items.append(contentsOf: offset + 1 ..< count)
let (found, start) = items._binarySearchStart(offset)
let end = items._binarySearchEnd(offset)
XCTAssertEqual(found, dupes > 0)
XCTAssertEqual(start, offset)
XCTAssertEqual(end, offset + dupes)
}
}
}
}
func testBinarySearch_Extract() {
for count in [0, 1, 2, 100] {
for dupes in 0 ..< 10 {
for offset in 0 ..< count {
var items: [Int] = []
items.append(contentsOf: 0 ..< offset)
items.append(contentsOf: Array(repeating: offset, count: dupes))
items.append(contentsOf: offset + 1 ..< count)
let (found, start) = items._binarySearchStart(UInt64(offset), by: { UInt64($0) })
let end = items._binarySearchEnd(UInt64(offset), by: { UInt64($0) })
XCTAssertEqual(found, dupes > 0)
XCTAssertEqual(start, offset)
XCTAssertEqual(end, offset + dupes)
}
}
}
}
}
| 32.767857 | 91 | 0.552044 |
3a6479984ee3ecc730fcc283a8f233c79d544112 | 80,251 | //
// CoreDrawing.swift
// CoreLib
//
// Created by Minhnd on 4/16/17.
// Copyright © 2017 LGKKTeam. All rights reserved.
//
//
import UIKit
// swiftlint:disable type_body_length line_length object_literal function_body_length file_length
public class CoreDrawing : NSObject {
//// Cache
private struct Cache {
static let colorBlack: UIColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
static var imageOfNext: UIImage?
static var nextTargets: [AnyObject]?
static var imageOfVolume: UIImage?
static var volumeTargets: [AnyObject]?
static var imageOfPlayRevert: UIImage?
static var playRevertTargets: [AnyObject]?
static var imageOfPlayBack: UIImage?
static var playBackTargets: [AnyObject]?
static var imageOfVolumeMax: UIImage?
static var volumeMaxTargets: [AnyObject]?
static var imageOfPause: UIImage?
static var pauseTargets: [AnyObject]?
static var imageOfFastBackward: UIImage?
static var fastBackwardTargets: [AnyObject]?
static var imageOfFoward: UIImage?
static var fowardTargets: [AnyObject]?
static var imageOfVolumeMin: UIImage?
static var volumeMinTargets: [AnyObject]?
static var imageOfBackward: UIImage?
static var backwardTargets: [AnyObject]?
static var imageOfPlayNext: UIImage?
static var playNextTargets: [AnyObject]?
static var imageOfFastFoward: UIImage?
static var fastFowardTargets: [AnyObject]?
static var imageOfBack: UIImage?
static var backTargets: [AnyObject]?
static var imageOfPlay: UIImage?
static var playTargets: [AnyObject]?
static var imageOfFullScreen: UIImage?
static var fullScreenTargets: [AnyObject]?
static var imageOfExitFullScreen: UIImage?
static var exitFullScreenTargets: [AnyObject]?
static var imageOfDefaultView: UIImage?
static var defaultViewTargets: [AnyObject]?
static var imageOfCheckmark: UIImage?
static var checkmarkTargets: [AnyObject]?
static var imageOfSettingsFilled: UIImage?
static var settingsFilledTargets: [AnyObject]?
static var imageOfSettings: UIImage?
static var settingsTargets: [AnyObject]?
static var imageOfTheaterMode: UIImage?
static var theaterModeTargets: [AnyObject]?
static var imageOfSoundMuted: UIImage?
static var soundMutedTargets: [AnyObject]?
}
//// Colors
public dynamic class var colorBlack: UIColor { return Cache.colorBlack }
//// Drawing Methods
public dynamic class func drawNext(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 180),
resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame = resizing.apply(rect: CGRect(x: 0, y: 0, width: 100, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 180)
//// raw Drawing
let rawPath = UIBezierPath()
rawPath.move(to: CGPoint(x: 100, y: 90))
rawPath.addLine(to: CGPoint(x: 10.89, y: 0))
rawPath.addLine(to: CGPoint(x: 0, y: 10.9))
rawPath.addLine(to: CGPoint(x: 78.99, y: 90))
rawPath.addLine(to: CGPoint(x: 0, y: 169.1))
rawPath.addLine(to: CGPoint(x: 10.89, y: 180))
rawPath.addLine(to: CGPoint(x: 100, y: 90))
rawPath.close()
CoreDrawing.colorBlack.setFill()
rawPath.fill()
context.restoreGState()
}
public dynamic class func drawVolume(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 71, height: 128), resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 71, height: 128), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 71, y: resizedFrame.height / 128)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 42.21))
bezierPath.addCurve(to: CGPoint(x: 29.08, y: 42.21), controlPoint1: CGPoint(x: 27.39, y: 42.21), controlPoint2: CGPoint(x: 29.08, y: 42.21))
bezierPath.addLine(to: CGPoint(x: 71, y: 0))
bezierPath.addLine(to: CGPoint(x: 71, y: 128))
bezierPath.addLine(to: CGPoint(x: 29.08, y: 85.79))
bezierPath.addLine(to: CGPoint(x: 0, y: 85.79))
bezierPath.addLine(to: CGPoint(x: 0, y: 42.21))
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
context.restoreGState()
}
public dynamic class func drawPlayRevert(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 90, height: 180), resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 90, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 90, y: resizedFrame.height / 180)
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 90, y: 0))
bezier2Path.addCurve(to: CGPoint(x: 90, y: 180), controlPoint1: CGPoint(x: 90, y: 180.02), controlPoint2: CGPoint(x: 90, y: 180))
bezier2Path.addLine(to: CGPoint(x: 0, y: 87))
bezier2Path.addLine(to: CGPoint(x: 90, y: 0))
CoreDrawing.colorBlack.setFill()
bezier2Path.fill()
context.restoreGState()
}
public dynamic class func drawPlayBack(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 115, height: 180), resizing: ResizingBehavior = .aspectFit) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 115, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 115, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 180))
bezierPath.addLine(to: CGPoint(x: 15, y: 180))
bezierPath.addLine(to: CGPoint(x: 15, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 180))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 115, y: 0))
bezierPath.addCurve(to: CGPoint(x: 115, y: 180), controlPoint1: CGPoint(x: 115, y: 180.02), controlPoint2: CGPoint(x: 115, y: 180))
bezierPath.addLine(to: CGPoint(x: 25, y: 87))
bezierPath.addLine(to: CGPoint(x: 115, y: 0))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
context.restoreGState()
}
public dynamic class func drawVolumeMax(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 128, height: 128), resizing: ResizingBehavior = .aspectFit) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 128, height: 128), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 128, y: resizedFrame.height / 128)
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 0, y: 42.21))
bezier4Path.addCurve(to: CGPoint(x: 29.27, y: 42.21), controlPoint1: CGPoint(x: 27.57, y: 42.21), controlPoint2: CGPoint(x: 29.27, y: 42.21))
bezier4Path.addLine(to: CGPoint(x: 71.47, y: 0))
bezier4Path.addLine(to: CGPoint(x: 71.47, y: 128))
bezier4Path.addLine(to: CGPoint(x: 29.27, y: 85.79))
bezier4Path.addLine(to: CGPoint(x: 0, y: 85.79))
bezier4Path.addLine(to: CGPoint(x: 0, y: 42.21))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 85.12, y: 13.47))
bezier4Path.addCurve(to: CGPoint(x: 128, y: 63.15), controlPoint1: CGPoint(x: 109.38, y: 17.01), controlPoint2: CGPoint(x: 128, y: 37.9))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 112.83), controlPoint1: CGPoint(x: 128, y: 88.39), controlPoint2: CGPoint(x: 109.38, y: 109.29))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 99.74), controlPoint1: CGPoint(x: 85.12, y: 108.82), controlPoint2: CGPoint(x: 85.12, y: 104.41))
bezier4Path.addCurve(to: CGPoint(x: 115.07, y: 63.32), controlPoint1: CGPoint(x: 102.19, y: 96.41), controlPoint2: CGPoint(x: 115.07, y: 81.37))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 26.9), controlPoint1: CGPoint(x: 115.07, y: 45.27), controlPoint2: CGPoint(x: 102.19, y: 30.23))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 13.47), controlPoint1: CGPoint(x: 85.12, y: 22.1), controlPoint2: CGPoint(x: 85.12, y: 17.58))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 85.12, y: 42.15))
bezier4Path.addCurve(to: CGPoint(x: 99.75, y: 62.98), controlPoint1: CGPoint(x: 93.65, y: 45.22), controlPoint2: CGPoint(x: 99.75, y: 53.39))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 83.81), controlPoint1: CGPoint(x: 99.75, y: 72.57), controlPoint2: CGPoint(x: 93.65, y: 80.74))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 42.15), controlPoint1: CGPoint(x: 85.12, y: 72.23), controlPoint2: CGPoint(x: 85.12, y: 53.72))
bezier4Path.close()
CoreDrawing.colorBlack.setFill()
bezier4Path.fill()
context.restoreGState()
}
public dynamic class func drawSoundMuted(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 128, height: 128), resizing: ResizingBehavior = .aspectFit) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 128, height: 128), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 128, y: resizedFrame.height / 128)
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 120.51, y: 113))
bezier4Path.addLine(to: CGPoint(x: 127.58, y: 105.93))
bezier4Path.addLine(to: CGPoint(x: 37.07, y: 15.42))
bezier4Path.addLine(to: CGPoint(x: 30, y: 22.49))
bezier4Path.addLine(to: CGPoint(x: 120.51, y: 113))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 99.75, y: 62.98))
bezier4Path.addCurve(to: CGPoint(x: 97.12, y: 73.47), controlPoint1: CGPoint(x: 99.75, y: 66.77), controlPoint2: CGPoint(x: 98.8, y: 70.34))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 61.47), controlPoint1: CGPoint(x: 93.24, y: 69.59), controlPoint2: CGPoint(x: 89.19, y: 65.54))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 54.35), controlPoint1: CGPoint(x: 85.12, y: 59.07), controlPoint2: CGPoint(x: 85.12, y: 56.67))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 42.15), controlPoint1: CGPoint(x: 85.12, y: 49.9), controlPoint2: CGPoint(x: 85.12, y: 45.7))
bezier4Path.addCurve(to: CGPoint(x: 99.75, y: 62.98), controlPoint1: CGPoint(x: 93.65, y: 45.22), controlPoint2: CGPoint(x: 99.75, y: 53.39))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 85.12, y: 79.61))
bezier4Path.addCurve(to: CGPoint(x: 88.03, y: 82.52), controlPoint1: CGPoint(x: 86.1, y: 80.59), controlPoint2: CGPoint(x: 87.07, y: 81.56))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 83.81), controlPoint1: CGPoint(x: 87.1, y: 83.01), controlPoint2: CGPoint(x: 86.12, y: 83.45))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 79.61), controlPoint1: CGPoint(x: 85.12, y: 82.49), controlPoint2: CGPoint(x: 85.12, y: 81.09))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 71.47, y: 0))
bezier4Path.addCurve(to: CGPoint(x: 71.47, y: 47.81), controlPoint1: CGPoint(x: 71.47, y: -0), controlPoint2: CGPoint(x: 71.47, y: 22.03))
bezier4Path.addCurve(to: CGPoint(x: 47.56, y: 23.91), controlPoint1: CGPoint(x: 62.33, y: 38.68), controlPoint2: CGPoint(x: 53.83, y: 30.18))
bezier4Path.addCurve(to: CGPoint(x: 71.46, y: 0.01), controlPoint1: CGPoint(x: 58.83, y: 12.64), controlPoint2: CGPoint(x: 71.18, y: 0.29))
bezier4Path.addLine(to: CGPoint(x: 71.47, y: 0))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 71.47, y: 65.96))
bezier4Path.addCurve(to: CGPoint(x: 71.47, y: 128), controlPoint1: CGPoint(x: 71.47, y: 97.29), controlPoint2: CGPoint(x: 71.47, y: 128))
bezier4Path.addLine(to: CGPoint(x: 29.27, y: 85.79))
bezier4Path.addLine(to: CGPoint(x: 0, y: 85.79))
bezier4Path.addLine(to: CGPoint(x: 0, y: 42.21))
bezier4Path.addLine(to: CGPoint(x: 29.27, y: 42.21))
bezier4Path.addCurve(to: CGPoint(x: 38.49, y: 32.98), controlPoint1: CGPoint(x: 29.27, y: 42.21), controlPoint2: CGPoint(x: 33.12, y: 38.36))
bezier4Path.addCurve(to: CGPoint(x: 71.47, y: 65.96), controlPoint1: CGPoint(x: 46.35, y: 40.84), controlPoint2: CGPoint(x: 58.7, y: 53.19))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 128, y: 63.15))
bezier4Path.addCurve(to: CGPoint(x: 117.52, y: 93.86), controlPoint1: CGPoint(x: 128, y: 74.72), controlPoint2: CGPoint(x: 124.09, y: 85.37))
bezier4Path.addCurve(to: CGPoint(x: 108.32, y: 84.67), controlPoint1: CGPoint(x: 114.84, y: 91.18), controlPoint2: CGPoint(x: 111.73, y: 88.07))
bezier4Path.addCurve(to: CGPoint(x: 115.07, y: 63.32), controlPoint1: CGPoint(x: 112.57, y: 78.63), controlPoint2: CGPoint(x: 115.07, y: 71.27))
bezier4Path.addCurve(to: CGPoint(x: 114.62, y: 57.52), controlPoint1: CGPoint(x: 115.07, y: 61.35), controlPoint2: CGPoint(x: 114.91, y: 59.41))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 26.9), controlPoint1: CGPoint(x: 112.2, y: 42.12), controlPoint2: CGPoint(x: 100.32, y: 29.87))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 13.47), controlPoint1: CGPoint(x: 85.12, y: 22.1), controlPoint2: CGPoint(x: 85.12, y: 17.58))
bezier4Path.addCurve(to: CGPoint(x: 128, y: 63.15), controlPoint1: CGPoint(x: 109.38, y: 17.01), controlPoint2: CGPoint(x: 128, y: 37.9))
bezier4Path.close()
bezier4Path.move(to: CGPoint(x: 108.44, y: 102.93))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 112.83), controlPoint1: CGPoint(x: 101.79, y: 108.06), controlPoint2: CGPoint(x: 93.82, y: 111.56))
bezier4Path.addCurve(to: CGPoint(x: 85.12, y: 99.74), controlPoint1: CGPoint(x: 85.12, y: 108.82), controlPoint2: CGPoint(x: 85.12, y: 104.41))
bezier4Path.addCurve(to: CGPoint(x: 99.24, y: 93.73), controlPoint1: CGPoint(x: 90.29, y: 98.73), controlPoint2: CGPoint(x: 95.08, y: 96.64))
bezier4Path.addCurve(to: CGPoint(x: 108.44, y: 102.93), controlPoint1: CGPoint(x: 102.59, y: 97.08), controlPoint2: CGPoint(x: 105.69, y: 100.18))
bezier4Path.close()
UIColor.black.setFill()
bezier4Path.fill()
context.restoreGState()
}
public dynamic class func drawPause(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 90, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 90, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 90, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 180))
bezierPath.addLine(to: CGPoint(x: 30, y: 180))
bezierPath.addLine(to: CGPoint(x: 30, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 180))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 60, y: 180))
bezierPath.addLine(to: CGPoint(x: 90, y: 180))
bezierPath.addLine(to: CGPoint(x: 90, y: 0))
bezierPath.addLine(to: CGPoint(x: 60, y: 0))
bezierPath.addLine(to: CGPoint(x: 60, y: 180))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawFastBackward(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 200, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 200, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 200, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 90))
bezierPath.addLine(to: CGPoint(x: 89.11, y: 0))
bezierPath.addLine(to: CGPoint(x: 100, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 21.01, y: 90))
bezierPath.addLine(to: CGPoint(x: 100, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 89.11, y: 180))
bezierPath.addLine(to: CGPoint(x: 0, y: 90))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 50, y: 90))
bezierPath.addLine(to: CGPoint(x: 139.11, y: 0))
bezierPath.addLine(to: CGPoint(x: 150, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 71.01, y: 90))
bezierPath.addLine(to: CGPoint(x: 150, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 139.11, y: 180))
bezierPath.addLine(to: CGPoint(x: 50, y: 90))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 100, y: 90))
bezierPath.addLine(to: CGPoint(x: 189.11, y: 0))
bezierPath.addLine(to: CGPoint(x: 200, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 121.01, y: 90))
bezierPath.addLine(to: CGPoint(x: 200, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 189.11, y: 180))
bezierPath.addLine(to: CGPoint(x: 100, y: 90))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawFoward(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 150, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 150, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 150, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 100, y: 90))
bezierPath.addLine(to: CGPoint(x: 10.89, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 78.99, y: 90))
bezierPath.addLine(to: CGPoint(x: 0, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 10.89, y: 180))
bezierPath.addLine(to: CGPoint(x: 100, y: 90))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 150, y: 90))
bezierPath.addLine(to: CGPoint(x: 60.89, y: 0))
bezierPath.addLine(to: CGPoint(x: 50, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 128.99, y: 90))
bezierPath.addLine(to: CGPoint(x: 50, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 60.89, y: 180))
bezierPath.addLine(to: CGPoint(x: 150, y: 90))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawVolumeMin(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 102, height: 128), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 102, height: 128), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 102, y: resizedFrame.height / 128)
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 0, y: 42.21))
bezier3Path.addCurve(to: CGPoint(x: 29.34, y: 42.21), controlPoint1: CGPoint(x: 27.63, y: 42.21), controlPoint2: CGPoint(x: 29.34, y: 42.21))
bezier3Path.addLine(to: CGPoint(x: 71.64, y: 0))
bezier3Path.addLine(to: CGPoint(x: 71.64, y: 128))
bezier3Path.addLine(to: CGPoint(x: 29.34, y: 85.79))
bezier3Path.addLine(to: CGPoint(x: 0, y: 85.79))
bezier3Path.addLine(to: CGPoint(x: 0, y: 42.21))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: 87.33, y: 42.15))
bezier3Path.addCurve(to: CGPoint(x: 102, y: 62.98), controlPoint1: CGPoint(x: 95.88, y: 45.22), controlPoint2: CGPoint(x: 102, y: 53.39))
bezier3Path.addCurve(to: CGPoint(x: 87.33, y: 83.81), controlPoint1: CGPoint(x: 102, y: 72.57), controlPoint2: CGPoint(x: 95.88, y: 80.74))
bezier3Path.addCurve(to: CGPoint(x: 87.33, y: 42.15), controlPoint1: CGPoint(x: 87.33, y: 72.23), controlPoint2: CGPoint(x: 87.33, y: 53.72))
bezier3Path.close()
CoreDrawing.colorBlack.setFill()
bezier3Path.fill()
////
context.restoreGState()
}
public dynamic class func drawBackward(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 150, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 150, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 150, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 50, y: 90))
bezierPath.addLine(to: CGPoint(x: 139.11, y: 0))
bezierPath.addLine(to: CGPoint(x: 150, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 71.01, y: 90))
bezierPath.addLine(to: CGPoint(x: 150, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 139.11, y: 180))
bezierPath.addLine(to: CGPoint(x: 50, y: 90))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 0, y: 90))
bezierPath.addLine(to: CGPoint(x: 89.11, y: 0))
bezierPath.addLine(to: CGPoint(x: 100, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 21.01, y: 90))
bezierPath.addLine(to: CGPoint(x: 100, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 89.11, y: 180))
bezierPath.addLine(to: CGPoint(x: 0, y: 90))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawPlayNext(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 115, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 115, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 115, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0.99))
bezierPath.addCurve(to: CGPoint(x: 0, y: 180), controlPoint1: CGPoint(x: 0, y: 180.02), controlPoint2: CGPoint(x: 0, y: 180))
bezierPath.addLine(to: CGPoint(x: 90, y: 91.23))
bezierPath.addLine(to: CGPoint(x: 0, y: 2.46))
bezierPath.addLine(to: CGPoint(x: 0, y: 0.99))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 100, y: 180))
bezierPath.addLine(to: CGPoint(x: 115, y: 180))
bezierPath.addLine(to: CGPoint(x: 115, y: 0))
bezierPath.addLine(to: CGPoint(x: 100, y: 0))
bezierPath.addLine(to: CGPoint(x: 100, y: 180))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawFastFoward(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 200, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 200, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 200, y: resizedFrame.height / 180)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 100, y: 90))
bezierPath.addLine(to: CGPoint(x: 10.89, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 78.99, y: 90))
bezierPath.addLine(to: CGPoint(x: 0, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 10.89, y: 180))
bezierPath.addLine(to: CGPoint(x: 100, y: 90))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 200, y: 90))
bezierPath.addLine(to: CGPoint(x: 110.89, y: 0))
bezierPath.addLine(to: CGPoint(x: 100, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 178.99, y: 90))
bezierPath.addLine(to: CGPoint(x: 100, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 110.89, y: 180))
bezierPath.addLine(to: CGPoint(x: 200, y: 90))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 150, y: 90))
bezierPath.addLine(to: CGPoint(x: 60.89, y: 0))
bezierPath.addLine(to: CGPoint(x: 50, y: 10.9))
bezierPath.addLine(to: CGPoint(x: 128.99, y: 90))
bezierPath.addLine(to: CGPoint(x: 50, y: 169.1))
bezierPath.addLine(to: CGPoint(x: 60.89, y: 180))
bezierPath.addLine(to: CGPoint(x: 150, y: 90))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawBack(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 100, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 180)
//// raw Drawing
let rawPath = UIBezierPath()
rawPath.move(to: CGPoint(x: 0, y: 90))
rawPath.addLine(to: CGPoint(x: 89.11, y: 0))
rawPath.addLine(to: CGPoint(x: 100, y: 10.9))
rawPath.addLine(to: CGPoint(x: 21.01, y: 90))
rawPath.addLine(to: CGPoint(x: 100, y: 169.1))
rawPath.addLine(to: CGPoint(x: 89.11, y: 180))
rawPath.addLine(to: CGPoint(x: 0, y: 90))
rawPath.close()
CoreDrawing.colorBlack.setFill()
rawPath.fill()
////
context.restoreGState()
}
public dynamic class func drawPlay(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 90, height: 180), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 90, height: 180), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 90, y: resizedFrame.height / 180)
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 0, y: 1))
bezier2Path.addCurve(to: CGPoint(x: 0, y: 181), controlPoint1: CGPoint(x: 0, y: 181.02), controlPoint2: CGPoint(x: 0, y: 181))
bezier2Path.addLine(to: CGPoint(x: 90, y: 91.74))
bezier2Path.addLine(to: CGPoint(x: 0, y: 2.48))
CoreDrawing.colorBlack.setFill()
bezier2Path.fill()
////
context.restoreGState()
}
public dynamic class func drawFullScreen(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 128, height: 128), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 128, height: 128), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 128, y: resizedFrame.height / 128)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 127.7, y: 0.3))
bezierPath.addLine(to: CGPoint(x: 67.65, y: 0))
bezierPath.addLine(to: CGPoint(x: 67.66, y: 7.31))
bezierPath.addLine(to: CGPoint(x: 120.66, y: 7.34))
bezierPath.addLine(to: CGPoint(x: 120.69, y: 60.34))
bezierPath.addLine(to: CGPoint(x: 128, y: 60.35))
bezierPath.addLine(to: CGPoint(x: 127.7, y: 0.3))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 127.7, y: 127.7))
bezierPath.addLine(to: CGPoint(x: 128, y: 67.65))
bezierPath.addLine(to: CGPoint(x: 120.69, y: 67.66))
bezierPath.addLine(to: CGPoint(x: 120.66, y: 120.66))
bezierPath.addLine(to: CGPoint(x: 67.66, y: 120.69))
bezierPath.addLine(to: CGPoint(x: 67.65, y: 128))
bezierPath.addLine(to: CGPoint(x: 127.7, y: 127.7))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 0.3, y: 0.3))
bezierPath.addLine(to: CGPoint(x: 0, y: 60.35))
bezierPath.addLine(to: CGPoint(x: 7.31, y: 60.34))
bezierPath.addLine(to: CGPoint(x: 7.34, y: 7.34))
bezierPath.addLine(to: CGPoint(x: 60.34, y: 7.31))
bezierPath.addLine(to: CGPoint(x: 60.35, y: 0))
bezierPath.addLine(to: CGPoint(x: 0.3, y: 0.3))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 0.3, y: 127.7))
bezierPath.addLine(to: CGPoint(x: 60.35, y: 128))
bezierPath.addLine(to: CGPoint(x: 60.34, y: 120.69))
bezierPath.addLine(to: CGPoint(x: 7.34, y: 120.66))
bezierPath.addLine(to: CGPoint(x: 7.31, y: 67.66))
bezierPath.addLine(to: CGPoint(x: 0, y: 67.65))
bezierPath.addLine(to: CGPoint(x: 0.3, y: 127.7))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawExitFullScreen(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 128, height: 128), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 128, height: 128), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 128, y: resizedFrame.height / 128)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 71.43, y: 55.6))
bezierPath.addLine(to: CGPoint(x: 71.15, y: 0))
bezierPath.addLine(to: CGPoint(x: 78.04, y: 0))
bezierPath.addLine(to: CGPoint(x: 78.07, y: 49.07))
bezierPath.addLine(to: CGPoint(x: 128, y: 49.11))
bezierPath.addLine(to: CGPoint(x: 128, y: 55.87))
bezierPath.addLine(to: CGPoint(x: 71.43, y: 55.6))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 56.57, y: 55.6))
bezierPath.addLine(to: CGPoint(x: 0, y: 55.87))
bezierPath.addLine(to: CGPoint(x: 0, y: 49.11))
bezierPath.addLine(to: CGPoint(x: 49.93, y: 49.07))
bezierPath.addLine(to: CGPoint(x: 49.96, y: 0))
bezierPath.addLine(to: CGPoint(x: 56.85, y: 0))
bezierPath.addLine(to: CGPoint(x: 56.57, y: 55.6))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 71.43, y: 72.4))
bezierPath.addLine(to: CGPoint(x: 128, y: 72.13))
bezierPath.addLine(to: CGPoint(x: 128, y: 78.89))
bezierPath.addLine(to: CGPoint(x: 78.07, y: 78.93))
bezierPath.addLine(to: CGPoint(x: 78.04, y: 128))
bezierPath.addLine(to: CGPoint(x: 71.15, y: 128))
bezierPath.addLine(to: CGPoint(x: 71.43, y: 72.4))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 56.57, y: 72.4))
bezierPath.addLine(to: CGPoint(x: 56.85, y: 128))
bezierPath.addLine(to: CGPoint(x: 49.96, y: 128))
bezierPath.addLine(to: CGPoint(x: 49.93, y: 78.93))
bezierPath.addLine(to: CGPoint(x: 0, y: 78.89))
bezierPath.addLine(to: CGPoint(x: 0, y: 72.13))
bezierPath.addLine(to: CGPoint(x: 56.57, y: 72.4))
bezierPath.close()
CoreDrawing.colorBlack.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawDefaultView(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 128, height: 73), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 128, height: 73), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 128, y: resizedFrame.height / 73)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 100.63, y: 4.22))
bezierPath.addLine(to: CGPoint(x: 4.21, y: 4.22))
bezierPath.addLine(to: CGPoint(x: 4.21, y: 53.59))
bezierPath.addLine(to: CGPoint(x: 100.63, y: 53.59))
bezierPath.addLine(to: CGPoint(x: 100.63, y: 4.22))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 128, y: 0))
bezierPath.addLine(to: CGPoint(x: 128, y: 73))
bezierPath.addLine(to: CGPoint(x: 0, y: 73))
bezierPath.addLine(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: 128, y: 0))
bezierPath.addLine(to: CGPoint(x: 128, y: 0))
bezierPath.close()
UIColor.black.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawTheaterMode(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 128, height: 73), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 128, height: 73), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 128, y: resizedFrame.height / 73)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 123, y: 5))
bezierPath.addLine(to: CGPoint(x: 5, y: 5))
bezierPath.addLine(to: CGPoint(x: 5, y: 68))
bezierPath.addLine(to: CGPoint(x: 123, y: 68))
bezierPath.addLine(to: CGPoint(x: 123, y: 5))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 128, y: 0))
bezierPath.addCurve(to: CGPoint(x: 128, y: 73), controlPoint1: CGPoint(x: 128, y: 0), controlPoint2: CGPoint(x: 128, y: 73))
bezierPath.addLine(to: CGPoint(x: 0, y: 73))
bezierPath.addLine(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: 128, y: 0))
bezierPath.addLine(to: CGPoint(x: 128, y: 0))
bezierPath.close()
UIColor.black.setFill()
bezierPath.fill()
////
context.restoreGState()
}
public dynamic class func drawCheckmark(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 64, height: 64), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 64, height: 64), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 64, y: resizedFrame.height / 64)
//// raw Drawing
let rawPath = UIBezierPath()
rawPath.move(to: CGPoint(x: 1.16, y: 41.19))
rawPath.addCurve(to: CGPoint(x: 0.14, y: 36.69), controlPoint1: CGPoint(x: 0.12, y: 39.82), controlPoint2: CGPoint(x: -0.22, y: 38.32))
rawPath.addCurve(to: CGPoint(x: 2.93, y: 32.77), controlPoint1: CGPoint(x: 0.5, y: 35.06), controlPoint2: CGPoint(x: 1.43, y: 33.75))
rawPath.addCurve(to: CGPoint(x: 7.96, y: 31.79), controlPoint1: CGPoint(x: 4.49, y: 31.79), controlPoint2: CGPoint(x: 6.17, y: 31.47))
rawPath.addCurve(to: CGPoint(x: 12.22, y: 34.44), controlPoint1: CGPoint(x: 9.76, y: 32.12), controlPoint2: CGPoint(x: 11.18, y: 33))
rawPath.addLine(to: CGPoint(x: 23.08, y: 48.14))
rawPath.addLine(to: CGPoint(x: 52.13, y: 3.02))
rawPath.addCurve(to: CGPoint(x: 55.95, y: 0.19), controlPoint1: CGPoint(x: 53.11, y: 1.52), controlPoint2: CGPoint(x: 54.38, y: 0.58))
rawPath.addCurve(to: CGPoint(x: 60.74, y: 0.87), controlPoint1: CGPoint(x: 57.51, y: -0.21), controlPoint2: CGPoint(x: 59.11, y: 0.02))
rawPath.addCurve(to: CGPoint(x: 63.77, y: 4.59), controlPoint1: CGPoint(x: 62.3, y: 1.72), controlPoint2: CGPoint(x: 63.32, y: 2.96))
rawPath.addCurve(to: CGPoint(x: 63.09, y: 9.19), controlPoint1: CGPoint(x: 64.23, y: 6.22), controlPoint2: CGPoint(x: 64, y: 7.75))
rawPath.addLine(to: CGPoint(x: 29.34, y: 60.95))
rawPath.addCurve(to: CGPoint(x: 27.04, y: 63.11), controlPoint1: CGPoint(x: 28.82, y: 61.87), controlPoint2: CGPoint(x: 28.05, y: 62.59))
rawPath.addCurve(to: CGPoint(x: 23.86, y: 63.99), controlPoint1: CGPoint(x: 26.03, y: 63.63), controlPoint2: CGPoint(x: 24.97, y: 63.92))
rawPath.addCurve(to: CGPoint(x: 20.68, y: 63.35), controlPoint1: CGPoint(x: 22.69, y: 64.05), controlPoint2: CGPoint(x: 21.63, y: 63.84))
rawPath.addCurve(to: CGPoint(x: 18.19, y: 61.35), controlPoint1: CGPoint(x: 19.73, y: 62.86), controlPoint2: CGPoint(x: 18.9, y: 62.19))
rawPath.addLine(to: CGPoint(x: 1.16, y: 41.19))
rawPath.close()
UIColor.black.setFill()
rawPath.fill()
////
context.restoreGState()
}
public dynamic class func drawSettingsFilled(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 500, height: 500), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 500, height: 500), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 500, y: resizedFrame.height / 500)
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 288, y: 0))
bezier2Path.addCurve(to: CGPoint(x: 300.65, y: 73.98), controlPoint1: CGPoint(x: 288, y: 0), controlPoint2: CGPoint(x: 298.59, y: 61.92))
bezier2Path.addCurve(to: CGPoint(x: 339, y: 89.86), controlPoint1: CGPoint(x: 314.14, y: 77.82), controlPoint2: CGPoint(x: 326.98, y: 83.18))
bezier2Path.addCurve(to: CGPoint(x: 355.79, y: 77.64), controlPoint1: CGPoint(x: 341.4, y: 88.11), controlPoint2: CGPoint(x: 347.89, y: 83.39))
bezier2Path.addCurve(to: CGPoint(x: 400.21, y: 45.34), controlPoint1: CGPoint(x: 373.94, y: 64.44), controlPoint2: CGPoint(x: 399.56, y: 45.81))
bezier2Path.addCurve(to: CGPoint(x: 453.97, y: 99.07), controlPoint1: CGPoint(x: 400.23, y: 45.33), controlPoint2: CGPoint(x: 453.97, y: 99.07))
bezier2Path.addCurve(to: CGPoint(x: 410.14, y: 160.99), controlPoint1: CGPoint(x: 453.97, y: 99.07), controlPoint2: CGPoint(x: 415.86, y: 152.89))
bezier2Path.addCurve(to: CGPoint(x: 426.02, y: 199.35), controlPoint1: CGPoint(x: 416.81, y: 173), controlPoint2: CGPoint(x: 422.17, y: 185.86))
bezier2Path.addCurve(to: CGPoint(x: 500, y: 212), controlPoint1: CGPoint(x: 438.08, y: 201.41), controlPoint2: CGPoint(x: 500, y: 212))
bezier2Path.addLine(to: CGPoint(x: 500, y: 288))
bezier2Path.addCurve(to: CGPoint(x: 426.01, y: 299.68), controlPoint1: CGPoint(x: 500, y: 288), controlPoint2: CGPoint(x: 438.05, y: 297.78))
bezier2Path.addCurve(to: CGPoint(x: 410.51, y: 337.34), controlPoint1: CGPoint(x: 422.24, y: 312.91), controlPoint2: CGPoint(x: 417.01, y: 325.52))
bezier2Path.addCurve(to: CGPoint(x: 454.67, y: 398.07), controlPoint1: CGPoint(x: 417.4, y: 346.82), controlPoint2: CGPoint(x: 454.67, y: 398.07))
bezier2Path.addLine(to: CGPoint(x: 400.93, y: 451.81))
bezier2Path.addCurve(to: CGPoint(x: 339.93, y: 408.62), controlPoint1: CGPoint(x: 400.93, y: 451.81), controlPoint2: CGPoint(x: 350.5, y: 416.1))
bezier2Path.addCurve(to: CGPoint(x: 300.83, y: 424.97), controlPoint1: CGPoint(x: 327.7, y: 415.51), controlPoint2: CGPoint(x: 314.6, y: 421.03))
bezier2Path.addCurve(to: CGPoint(x: 288, y: 500), controlPoint1: CGPoint(x: 299.32, y: 433.8), controlPoint2: CGPoint(x: 288, y: 500))
bezier2Path.addLine(to: CGPoint(x: 212, y: 500))
bezier2Path.addCurve(to: CGPoint(x: 200.15, y: 424.97), controlPoint1: CGPoint(x: 212, y: 500), controlPoint2: CGPoint(x: 201.55, y: 433.79))
bezier2Path.addCurve(to: CGPoint(x: 160.63, y: 408.37), controlPoint1: CGPoint(x: 186.22, y: 420.98), controlPoint2: CGPoint(x: 172.98, y: 415.37))
bezier2Path.addCurve(to: CGPoint(x: 99.93, y: 452.51), controlPoint1: CGPoint(x: 151.06, y: 415.33), controlPoint2: CGPoint(x: 99.93, y: 452.51))
bezier2Path.addLine(to: CGPoint(x: 46.19, y: 398.77))
bezier2Path.addCurve(to: CGPoint(x: 90.14, y: 336.69), controlPoint1: CGPoint(x: 46.19, y: 398.77), controlPoint2: CGPoint(x: 84.83, y: 344.2))
bezier2Path.addCurve(to: CGPoint(x: 75.03, y: 299.85), controlPoint1: CGPoint(x: 83.83, y: 325.11), controlPoint2: CGPoint(x: 78.74, y: 312.77))
bezier2Path.addCurve(to: CGPoint(x: 0, y: 288), controlPoint1: CGPoint(x: 66.21, y: 298.45), controlPoint2: CGPoint(x: 0, y: 288))
bezier2Path.addLine(to: CGPoint(x: 0, y: 212))
bezier2Path.addCurve(to: CGPoint(x: 75.03, y: 199.17), controlPoint1: CGPoint(x: 0, y: 212), controlPoint2: CGPoint(x: 66.19, y: 200.68))
bezier2Path.addCurve(to: CGPoint(x: 90.49, y: 161.66), controlPoint1: CGPoint(x: 78.8, y: 185.99), controlPoint2: CGPoint(x: 84.02, y: 173.43))
bezier2Path.addCurve(to: CGPoint(x: 45.49, y: 99.77), controlPoint1: CGPoint(x: 86.9, y: 156.72), controlPoint2: CGPoint(x: 45.49, y: 99.77))
bezier2Path.addCurve(to: CGPoint(x: 85.33, y: 59.93), controlPoint1: CGPoint(x: 45.49, y: 99.77), controlPoint2: CGPoint(x: 69.41, y: 75.85))
bezier2Path.addCurve(to: CGPoint(x: 99.23, y: 46.03), controlPoint1: CGPoint(x: 93.27, y: 51.99), controlPoint2: CGPoint(x: 99.23, y: 46.03))
bezier2Path.addCurve(to: CGPoint(x: 161.51, y: 90.13), controlPoint1: CGPoint(x: 99.23, y: 46.03), controlPoint2: CGPoint(x: 154.88, y: 85.43))
bezier2Path.addCurve(to: CGPoint(x: 200.32, y: 73.99), controlPoint1: CGPoint(x: 173.66, y: 83.33), controlPoint2: CGPoint(x: 186.66, y: 77.88))
bezier2Path.addCurve(to: CGPoint(x: 212, y: 0), controlPoint1: CGPoint(x: 202.22, y: 61.95), controlPoint2: CGPoint(x: 212, y: 0))
bezier2Path.addLine(to: CGPoint(x: 288, y: 0))
bezier2Path.addLine(to: CGPoint(x: 288, y: 0))
bezier2Path.close()
bezier2Path.move(to: CGPoint(x: 250.5, y: 175))
bezier2Path.addCurve(to: CGPoint(x: 230.57, y: 177.7), controlPoint1: CGPoint(x: 243.6, y: 175), controlPoint2: CGPoint(x: 236.92, y: 175.94))
bezier2Path.addCurve(to: CGPoint(x: 176, y: 249.5), controlPoint1: CGPoint(x: 199.1, y: 186.41), controlPoint2: CGPoint(x: 176, y: 215.26))
bezier2Path.addCurve(to: CGPoint(x: 250.5, y: 324), controlPoint1: CGPoint(x: 176, y: 290.65), controlPoint2: CGPoint(x: 209.35, y: 324))
bezier2Path.addCurve(to: CGPoint(x: 325, y: 249.5), controlPoint1: CGPoint(x: 291.65, y: 324), controlPoint2: CGPoint(x: 325, y: 290.65))
bezier2Path.addCurve(to: CGPoint(x: 250.5, y: 175), controlPoint1: CGPoint(x: 325, y: 208.35), controlPoint2: CGPoint(x: 291.65, y: 175))
bezier2Path.close()
UIColor.black.setFill()
bezier2Path.fill()
////
context.restoreGState()
}
public dynamic class func drawSettings(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 500, height: 500), resizing: ResizingBehavior = .aspectFit) {
////
guard let context = UIGraphicsGetCurrentContext() else {
return
}
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 500, height: 500), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 500, y: resizedFrame.height / 500)
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 251.5, y: 175))
bezier3Path.addCurve(to: CGPoint(x: 231.36, y: 177.75), controlPoint1: CGPoint(x: 244.52, y: 175), controlPoint2: CGPoint(x: 237.77, y: 175.96))
bezier3Path.addCurve(to: CGPoint(x: 177, y: 249.5), controlPoint1: CGPoint(x: 200, y: 186.54), controlPoint2: CGPoint(x: 177, y: 215.33))
bezier3Path.addCurve(to: CGPoint(x: 251.5, y: 324), controlPoint1: CGPoint(x: 177, y: 290.65), controlPoint2: CGPoint(x: 210.35, y: 324))
bezier3Path.addCurve(to: CGPoint(x: 326, y: 249.5), controlPoint1: CGPoint(x: 292.65, y: 324), controlPoint2: CGPoint(x: 326, y: 290.65))
bezier3Path.addCurve(to: CGPoint(x: 251.5, y: 175), controlPoint1: CGPoint(x: 326, y: 208.35), controlPoint2: CGPoint(x: 292.65, y: 175))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: 331, y: 250))
bezier3Path.addCurve(to: CGPoint(x: 251, y: 330), controlPoint1: CGPoint(x: 331, y: 294.18), controlPoint2: CGPoint(x: 295.18, y: 330))
bezier3Path.addCurve(to: CGPoint(x: 171, y: 250), controlPoint1: CGPoint(x: 206.82, y: 330), controlPoint2: CGPoint(x: 171, y: 294.18))
bezier3Path.addCurve(to: CGPoint(x: 228.41, y: 173.23), controlPoint1: CGPoint(x: 171, y: 213.66), controlPoint2: CGPoint(x: 195.23, y: 182.98))
bezier3Path.addCurve(to: CGPoint(x: 251, y: 170), controlPoint1: CGPoint(x: 235.58, y: 171.13), controlPoint2: CGPoint(x: 243.16, y: 170))
bezier3Path.addCurve(to: CGPoint(x: 331, y: 250), controlPoint1: CGPoint(x: 295.18, y: 170), controlPoint2: CGPoint(x: 331, y: 205.82))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: 212.02, y: 0))
bezier3Path.addCurve(to: CGPoint(x: 288, y: 0), controlPoint1: CGPoint(x: 212, y: 0), controlPoint2: CGPoint(x: 288, y: 0))
bezier3Path.addCurve(to: CGPoint(x: 300.65, y: 73.98), controlPoint1: CGPoint(x: 288, y: 0), controlPoint2: CGPoint(x: 298.59, y: 61.92))
bezier3Path.addCurve(to: CGPoint(x: 339, y: 89.86), controlPoint1: CGPoint(x: 314.14, y: 77.82), controlPoint2: CGPoint(x: 326.98, y: 83.18))
bezier3Path.addCurve(to: CGPoint(x: 400.23, y: 45.33), controlPoint1: CGPoint(x: 346.99, y: 84.05), controlPoint2: CGPoint(x: 400.23, y: 45.33))
bezier3Path.addLine(to: CGPoint(x: 453.97, y: 99.07))
bezier3Path.addCurve(to: CGPoint(x: 410.14, y: 160.99), controlPoint1: CGPoint(x: 453.97, y: 99.07), controlPoint2: CGPoint(x: 415.86, y: 152.89))
bezier3Path.addCurve(to: CGPoint(x: 426.01, y: 199.32), controlPoint1: CGPoint(x: 416.81, y: 173), controlPoint2: CGPoint(x: 422.17, y: 185.84))
bezier3Path.addCurve(to: CGPoint(x: 500, y: 211), controlPoint1: CGPoint(x: 438.05, y: 201.22), controlPoint2: CGPoint(x: 500, y: 211))
bezier3Path.addLine(to: CGPoint(x: 500, y: 287))
bezier3Path.addCurve(to: CGPoint(x: 426.02, y: 299.65), controlPoint1: CGPoint(x: 500, y: 287), controlPoint2: CGPoint(x: 438.08, y: 297.59))
bezier3Path.addCurve(to: CGPoint(x: 410.5, y: 337.36), controlPoint1: CGPoint(x: 422.24, y: 312.9), controlPoint2: CGPoint(x: 417.01, y: 325.53))
bezier3Path.addCurve(to: CGPoint(x: 453.96, y: 398.77), controlPoint1: CGPoint(x: 417.29, y: 346.97), controlPoint2: CGPoint(x: 453.97, y: 398.77))
bezier3Path.addCurve(to: CGPoint(x: 400.23, y: 452.51), controlPoint1: CGPoint(x: 453.97, y: 398.77), controlPoint2: CGPoint(x: 400.23, y: 452.51))
bezier3Path.addCurve(to: CGPoint(x: 339.9, y: 408.64), controlPoint1: CGPoint(x: 400.23, y: 452.51), controlPoint2: CGPoint(x: 350.33, y: 416.23))
bezier3Path.addCurve(to: CGPoint(x: 300.83, y: 424.97), controlPoint1: CGPoint(x: 327.68, y: 415.52), controlPoint2: CGPoint(x: 314.59, y: 421.03))
bezier3Path.addCurve(to: CGPoint(x: 288, y: 500), controlPoint1: CGPoint(x: 299.32, y: 433.8), controlPoint2: CGPoint(x: 288, y: 500))
bezier3Path.addLine(to: CGPoint(x: 212, y: 500))
bezier3Path.addCurve(to: CGPoint(x: 200.15, y: 424.97), controlPoint1: CGPoint(x: 212, y: 500), controlPoint2: CGPoint(x: 201.55, y: 433.79))
bezier3Path.addCurve(to: CGPoint(x: 160.63, y: 408.37), controlPoint1: CGPoint(x: 186.22, y: 420.98), controlPoint2: CGPoint(x: 172.98, y: 415.37))
bezier3Path.addCurve(to: CGPoint(x: 99.93, y: 452.51), controlPoint1: CGPoint(x: 151.06, y: 415.33), controlPoint2: CGPoint(x: 99.93, y: 452.51))
bezier3Path.addLine(to: CGPoint(x: 46.19, y: 398.77))
bezier3Path.addCurve(to: CGPoint(x: 90.14, y: 336.69), controlPoint1: CGPoint(x: 46.19, y: 398.77), controlPoint2: CGPoint(x: 84.83, y: 344.2))
bezier3Path.addCurve(to: CGPoint(x: 75.03, y: 299.83), controlPoint1: CGPoint(x: 83.83, y: 325.11), controlPoint2: CGPoint(x: 78.73, y: 312.77))
bezier3Path.addCurve(to: CGPoint(x: 0, y: 287), controlPoint1: CGPoint(x: 66.2, y: 298.32), controlPoint2: CGPoint(x: 0, y: 287))
bezier3Path.addCurve(to: CGPoint(x: 0, y: 211), controlPoint1: CGPoint(x: 0, y: 287), controlPoint2: CGPoint(x: 0, y: 211))
bezier3Path.addCurve(to: CGPoint(x: 71.47, y: 199.72), controlPoint1: CGPoint(x: 0, y: 211), controlPoint2: CGPoint(x: 55.1, y: 202.3))
bezier3Path.addCurve(to: CGPoint(x: 75.03, y: 199.15), controlPoint1: CGPoint(x: 73.04, y: 199.47), controlPoint2: CGPoint(x: 74.26, y: 199.27))
bezier3Path.addCurve(to: CGPoint(x: 90.49, y: 161.65), controlPoint1: CGPoint(x: 78.81, y: 185.98), controlPoint2: CGPoint(x: 84.02, y: 173.42))
bezier3Path.addCurve(to: CGPoint(x: 46.19, y: 99.07), controlPoint1: CGPoint(x: 86.95, y: 156.65), controlPoint2: CGPoint(x: 46.19, y: 99.07))
bezier3Path.addCurve(to: CGPoint(x: 91.48, y: 53.78), controlPoint1: CGPoint(x: 46.19, y: 99.07), controlPoint2: CGPoint(x: 76.35, y: 68.91))
bezier3Path.addCurve(to: CGPoint(x: 96.09, y: 49.17), controlPoint1: CGPoint(x: 93.25, y: 52.01), controlPoint2: CGPoint(x: 94.8, y: 50.46))
bezier3Path.addCurve(to: CGPoint(x: 99.93, y: 45.33), controlPoint1: CGPoint(x: 98.49, y: 46.77), controlPoint2: CGPoint(x: 99.93, y: 45.33))
bezier3Path.addCurve(to: CGPoint(x: 135.8, y: 71.41), controlPoint1: CGPoint(x: 99.93, y: 45.33), controlPoint2: CGPoint(x: 118.83, y: 59.07))
bezier3Path.addCurve(to: CGPoint(x: 161.52, y: 90.12), controlPoint1: CGPoint(x: 147.79, y: 80.13), controlPoint2: CGPoint(x: 158.81, y: 88.15))
bezier3Path.addCurve(to: CGPoint(x: 200.32, y: 73.99), controlPoint1: CGPoint(x: 173.67, y: 83.33), controlPoint2: CGPoint(x: 186.67, y: 77.88))
bezier3Path.addCurve(to: CGPoint(x: 200.71, y: 71.47), controlPoint1: CGPoint(x: 200.43, y: 73.3), controlPoint2: CGPoint(x: 200.56, y: 72.46))
bezier3Path.addCurve(to: CGPoint(x: 211.23, y: 4.9), controlPoint1: CGPoint(x: 202.83, y: 58.09), controlPoint2: CGPoint(x: 209.04, y: 18.75))
bezier3Path.addCurve(to: CGPoint(x: 212, y: 0), controlPoint1: CGPoint(x: 211.7, y: 1.89), controlPoint2: CGPoint(x: 211.99, y: 0.08))
bezier3Path.addLine(to: CGPoint(x: 212.02, y: 0))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: 284.29, y: 5))
bezier3Path.addLine(to: CGPoint(x: 215.81, y: 5))
bezier3Path.addCurve(to: CGPoint(x: 213.14, y: 21.77), controlPoint1: CGPoint(x: 215.81, y: 5), controlPoint2: CGPoint(x: 214.68, y: 12.13))
bezier3Path.addCurve(to: CGPoint(x: 203.53, y: 78.28), controlPoint1: CGPoint(x: 210.45, y: 37.58), controlPoint2: CGPoint(x: 206.42, y: 61.3))
bezier3Path.addCurve(to: CGPoint(x: 162.58, y: 95.27), controlPoint1: CGPoint(x: 189.06, y: 82.24), controlPoint2: CGPoint(x: 175.32, y: 87.99))
bezier3Path.addCurve(to: CGPoint(x: 126.99, y: 70.58), controlPoint1: CGPoint(x: 152.3, y: 88.14), controlPoint2: CGPoint(x: 138.79, y: 78.77))
bezier3Path.addCurve(to: CGPoint(x: 100.77, y: 51.56), controlPoint1: CGPoint(x: 113.63, y: 60.89), controlPoint2: CGPoint(x: 100.77, y: 51.56))
bezier3Path.addLine(to: CGPoint(x: 52.35, y: 99.98))
bezier3Path.addCurve(to: CGPoint(x: 52.44, y: 100.1), controlPoint1: CGPoint(x: 52.35, y: 99.98), controlPoint2: CGPoint(x: 52.38, y: 100.02))
bezier3Path.addCurve(to: CGPoint(x: 52.31, y: 100.22), controlPoint1: CGPoint(x: 52.36, y: 100.18), controlPoint2: CGPoint(x: 52.31, y: 100.22))
bezier3Path.addCurve(to: CGPoint(x: 96.07, y: 161.93), controlPoint1: CGPoint(x: 52.31, y: 100.22), controlPoint2: CGPoint(x: 79.92, y: 139.15))
bezier3Path.addCurve(to: CGPoint(x: 79.27, y: 202.57), controlPoint1: CGPoint(x: 88.88, y: 174.59), controlPoint2: CGPoint(x: 83.2, y: 188.21))
bezier3Path.addCurve(to: CGPoint(x: 59.37, y: 206.17), controlPoint1: CGPoint(x: 73.31, y: 203.65), controlPoint2: CGPoint(x: 66.45, y: 204.89))
bezier3Path.addCurve(to: CGPoint(x: 5, y: 214.81), controlPoint1: CGPoint(x: 39.52, y: 209.32), controlPoint2: CGPoint(x: 5, y: 214.81))
bezier3Path.addCurve(to: CGPoint(x: 5, y: 216), controlPoint1: CGPoint(x: 5, y: 214.81), controlPoint2: CGPoint(x: 5, y: 215.23))
bezier3Path.addCurve(to: CGPoint(x: 5, y: 283.29), controlPoint1: CGPoint(x: 5, y: 225.09), controlPoint2: CGPoint(x: 5, y: 283.29))
bezier3Path.addCurve(to: CGPoint(x: 5, y: 284), controlPoint1: CGPoint(x: 5, y: 283.75), controlPoint2: CGPoint(x: 5, y: 284))
bezier3Path.addCurve(to: CGPoint(x: 79.33, y: 296.65), controlPoint1: CGPoint(x: 5, y: 284), controlPoint2: CGPoint(x: 51.77, y: 291.96))
bezier3Path.addCurve(to: CGPoint(x: 95.46, y: 335.99), controlPoint1: CGPoint(x: 83.14, y: 310.52), controlPoint2: CGPoint(x: 88.59, y: 323.7))
bezier3Path.addCurve(to: CGPoint(x: 62.57, y: 383.4), controlPoint1: CGPoint(x: 85.86, y: 349.82), controlPoint2: CGPoint(x: 72.03, y: 369.76))
bezier3Path.addCurve(to: CGPoint(x: 52.35, y: 397.86), controlPoint1: CGPoint(x: 56.72, y: 391.67), controlPoint2: CGPoint(x: 52.35, y: 397.86))
bezier3Path.addCurve(to: CGPoint(x: 52.46, y: 397.97), controlPoint1: CGPoint(x: 52.35, y: 397.86), controlPoint2: CGPoint(x: 52.39, y: 397.9))
bezier3Path.addCurve(to: CGPoint(x: 52.02, y: 398.6), controlPoint1: CGPoint(x: 52.17, y: 398.38), controlPoint2: CGPoint(x: 52.02, y: 398.6))
bezier3Path.addLine(to: CGPoint(x: 100.1, y: 446.69))
bezier3Path.addCurve(to: CGPoint(x: 100.73, y: 446.24), controlPoint1: CGPoint(x: 100.1, y: 446.69), controlPoint2: CGPoint(x: 100.32, y: 446.53))
bezier3Path.addCurve(to: CGPoint(x: 105.1, y: 443.14), controlPoint1: CGPoint(x: 100.77, y: 446.28), controlPoint2: CGPoint(x: 102.4, y: 445.1))
bezier3Path.addCurve(to: CGPoint(x: 161.53, y: 403.13), controlPoint1: CGPoint(x: 116.28, y: 435.22), controlPoint2: CGPoint(x: 143.72, y: 415.76))
bezier3Path.addCurve(to: CGPoint(x: 203.35, y: 420.67), controlPoint1: CGPoint(x: 174.52, y: 410.66), controlPoint2: CGPoint(x: 188.55, y: 416.6))
bezier3Path.addCurve(to: CGPoint(x: 213.14, y: 478.23), controlPoint1: CGPoint(x: 206.25, y: 437.71), controlPoint2: CGPoint(x: 210.4, y: 462.09))
bezier3Path.addCurve(to: CGPoint(x: 215.81, y: 495), controlPoint1: CGPoint(x: 214.68, y: 487.87), controlPoint2: CGPoint(x: 215.81, y: 495))
bezier3Path.addLine(to: CGPoint(x: 284.29, y: 495))
bezier3Path.addCurve(to: CGPoint(x: 290.04, y: 461.62), controlPoint1: CGPoint(x: 284.29, y: 495), controlPoint2: CGPoint(x: 287.14, y: 478.41))
bezier3Path.addCurve(to: CGPoint(x: 297.43, y: 420.73), controlPoint1: CGPoint(x: 292.51, y: 447.94), controlPoint2: CGPoint(x: 295.29, y: 432.57))
bezier3Path.addCurve(to: CGPoint(x: 338.51, y: 403.68), controlPoint1: CGPoint(x: 311.95, y: 416.76), controlPoint2: CGPoint(x: 325.73, y: 410.99))
bezier3Path.addCurve(to: CGPoint(x: 388.68, y: 438.48), controlPoint1: CGPoint(x: 353.88, y: 414.34), controlPoint2: CGPoint(x: 375.74, y: 429.5))
bezier3Path.addCurve(to: CGPoint(x: 399.39, y: 446.28), controlPoint1: CGPoint(x: 395.03, y: 443.11), controlPoint2: CGPoint(x: 399.39, y: 446.28))
bezier3Path.addLine(to: CGPoint(x: 447.8, y: 397.86))
bezier3Path.addLine(to: CGPoint(x: 405, y: 337))
bezier3Path.addCurve(to: CGPoint(x: 404.91, y: 337.11), controlPoint1: CGPoint(x: 405, y: 337), controlPoint2: CGPoint(x: 404.97, y: 337.04))
bezier3Path.addLine(to: CGPoint(x: 404.98, y: 336.99))
bezier3Path.addCurve(to: CGPoint(x: 421.78, y: 296.24), controlPoint1: CGPoint(x: 412.18, y: 324.3), controlPoint2: CGPoint(x: 417.86, y: 310.63))
bezier3Path.addCurve(to: CGPoint(x: 461.62, y: 289.04), controlPoint1: CGPoint(x: 433.47, y: 294.13), controlPoint2: CGPoint(x: 448.34, y: 291.44))
bezier3Path.addCurve(to: CGPoint(x: 495, y: 283.29), controlPoint1: CGPoint(x: 478.41, y: 286.14), controlPoint2: CGPoint(x: 495, y: 283.29))
bezier3Path.addCurve(to: CGPoint(x: 495, y: 283), controlPoint1: CGPoint(x: 495, y: 283.29), controlPoint2: CGPoint(x: 495, y: 283.19))
bezier3Path.addCurve(to: CGPoint(x: 495, y: 215), controlPoint1: CGPoint(x: 495, y: 278.35), controlPoint2: CGPoint(x: 495, y: 218.78))
bezier3Path.addCurve(to: CGPoint(x: 495, y: 214.81), controlPoint1: CGPoint(x: 495, y: 214.88), controlPoint2: CGPoint(x: 495, y: 214.81))
bezier3Path.addCurve(to: CGPoint(x: 478.23, y: 212.14), controlPoint1: CGPoint(x: 495, y: 214.81), controlPoint2: CGPoint(x: 487.87, y: 213.68))
bezier3Path.addCurve(to: CGPoint(x: 421.72, y: 202.53), controlPoint1: CGPoint(x: 462.42, y: 209.45), controlPoint2: CGPoint(x: 438.7, y: 205.42))
bezier3Path.addCurve(to: CGPoint(x: 404.77, y: 161.64), controlPoint1: CGPoint(x: 417.76, y: 188.08), controlPoint2: CGPoint(x: 412.03, y: 174.37))
bezier3Path.addCurve(to: CGPoint(x: 432.85, y: 121.15), controlPoint1: CGPoint(x: 412.91, y: 149.9), controlPoint2: CGPoint(x: 423.98, y: 133.95))
bezier3Path.addCurve(to: CGPoint(x: 447.8, y: 99.98), controlPoint1: CGPoint(x: 440.91, y: 109.75), controlPoint2: CGPoint(x: 447.8, y: 99.98))
bezier3Path.addCurve(to: CGPoint(x: 447.65, y: 99.82), controlPoint1: CGPoint(x: 447.8, y: 99.98), controlPoint2: CGPoint(x: 447.75, y: 99.92))
bezier3Path.addCurve(to: CGPoint(x: 447.87, y: 99.51), controlPoint1: CGPoint(x: 447.79, y: 99.62), controlPoint2: CGPoint(x: 447.87, y: 99.51))
bezier3Path.addLine(to: CGPoint(x: 399.78, y: 51.43))
bezier3Path.addCurve(to: CGPoint(x: 399.47, y: 51.65), controlPoint1: CGPoint(x: 399.78, y: 51.43), controlPoint2: CGPoint(x: 399.68, y: 51.5))
bezier3Path.addCurve(to: CGPoint(x: 399.39, y: 51.56), controlPoint1: CGPoint(x: 399.42, y: 51.59), controlPoint2: CGPoint(x: 399.39, y: 51.56))
bezier3Path.addCurve(to: CGPoint(x: 390.27, y: 58.17), controlPoint1: CGPoint(x: 399.39, y: 51.56), controlPoint2: CGPoint(x: 395.72, y: 54.22))
bezier3Path.addCurve(to: CGPoint(x: 359.62, y: 79.9), controlPoint1: CGPoint(x: 382.51, y: 63.68), controlPoint2: CGPoint(x: 370.99, y: 71.84))
bezier3Path.addCurve(to: CGPoint(x: 345.06, y: 90.23), controlPoint1: CGPoint(x: 354.63, y: 83.44), controlPoint2: CGPoint(x: 349.67, y: 86.96))
bezier3Path.addCurve(to: CGPoint(x: 338.16, y: 95.12), controlPoint1: CGPoint(x: 342.65, y: 91.94), controlPoint2: CGPoint(x: 340.33, y: 93.58))
bezier3Path.addCurve(to: CGPoint(x: 297.24, y: 78.22), controlPoint1: CGPoint(x: 325.42, y: 87.87), controlPoint2: CGPoint(x: 311.7, y: 82.16))
bezier3Path.addCurve(to: CGPoint(x: 290.04, y: 38.38), controlPoint1: CGPoint(x: 295.13, y: 66.53), controlPoint2: CGPoint(x: 292.44, y: 51.66))
bezier3Path.addCurve(to: CGPoint(x: 284.29, y: 5), controlPoint1: CGPoint(x: 287.14, y: 21.59), controlPoint2: CGPoint(x: 284.29, y: 5))
bezier3Path.close()
bezier3Path.move(to: CGPoint(x: 404.89, y: 337.12))
bezier3Path.addCurve(to: CGPoint(x: 404.8, y: 337.58), controlPoint1: CGPoint(x: 404.9, y: 337.12), controlPoint2: CGPoint(x: 404.86, y: 337.28))
bezier3Path.addLine(to: CGPoint(x: 404.67, y: 337.39))
bezier3Path.addCurve(to: CGPoint(x: 404.89, y: 337.12), controlPoint1: CGPoint(x: 404.76, y: 337.28), controlPoint2: CGPoint(x: 404.84, y: 337.19))
bezier3Path.close()
UIColor.black.setFill()
bezier3Path.fill()
////
context.restoreGState()
}
// MARK: - Generated Images
public dynamic class var imageOfNext: UIImage {
if Cache.imageOfNext == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 100, height: 180), false, 0)
CoreDrawing.drawNext()
Cache.imageOfNext = UIGraphicsGetImageFromCurrentImageContext()?.withRenderingMode(.alwaysTemplate)
UIGraphicsEndImageContext()
}
if let imageOfNext = Cache.imageOfNext {
return imageOfNext
} else {
fatalError("imageOfNext is nil")
}
}
public dynamic class var imageOfVolume: UIImage {
if Cache.imageOfVolume == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 71, height: 128), false, 0)
CoreDrawing.drawVolume()
Cache.imageOfVolume = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfVolume = Cache.imageOfVolume {
return imageOfVolume
} else {
fatalError("imageOfVolume is nil")
}
}
public dynamic class var imageOfPlayRevert: UIImage {
if Cache.imageOfPlayRevert == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 90, height: 180), false, 0)
CoreDrawing.drawPlayRevert()
Cache.imageOfPlayRevert = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfPlayRevert = Cache.imageOfPlayRevert {
return imageOfPlayRevert
} else {
fatalError("imageOfPlayRevert is nil")
}
}
public dynamic class var imageOfPlayBack: UIImage {
if Cache.imageOfPlayBack == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 115, height: 180), false, 0)
CoreDrawing.drawPlayBack()
Cache.imageOfPlayBack = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfPlayBack = Cache.imageOfPlayBack {
return imageOfPlayBack
} else {
fatalError("imageOfPlayBack is nil")
}
}
public dynamic class var imageOfVolumeMax: UIImage {
if Cache.imageOfVolumeMax == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 128, height: 128), false, 0)
CoreDrawing.drawVolumeMax()
Cache.imageOfVolumeMax = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfVolumeMax = Cache.imageOfVolumeMax {
return imageOfVolumeMax
} else {
fatalError("imageOfVolumeMax is nil")
}
}
public dynamic class var imageOfPause: UIImage {
if Cache.imageOfPause == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 90, height: 180), false, 0)
CoreDrawing.drawPause()
Cache.imageOfPause = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfPause = Cache.imageOfPause {
return imageOfPause
} else {
fatalError("imageOfPause is nil")
}
}
public dynamic class var imageOfFastBackward: UIImage {
if Cache.imageOfFastBackward == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 200, height: 180), false, 0)
CoreDrawing.drawFastBackward()
Cache.imageOfFastBackward = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfFastBackward = Cache.imageOfFastBackward {
return imageOfFastBackward
} else {
fatalError("imageOfFastBackward is nil")
}
}
public dynamic class var imageOfFoward: UIImage {
if Cache.imageOfFoward == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 150, height: 180), false, 0)
CoreDrawing.drawFoward()
Cache.imageOfFoward = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfFoward = Cache.imageOfFoward {
return imageOfFoward
} else {
fatalError("imageOfFoward is nil")
}
}
public dynamic class var imageOfVolumeMin: UIImage {
if Cache.imageOfVolumeMin == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 102, height: 128), false, 0)
CoreDrawing.drawVolumeMin()
Cache.imageOfVolumeMin = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfVolumeMin = Cache.imageOfVolumeMin {
return imageOfVolumeMin
} else {
fatalError("imageOfVolumeMin is nil")
}
}
public dynamic class var imageOfBackward: UIImage {
if Cache.imageOfBackward == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 150, height: 180), false, 0)
CoreDrawing.drawBackward()
Cache.imageOfBackward = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfBackward = Cache.imageOfBackward {
return imageOfBackward
} else {
fatalError("imageOfBackward is nil")
}
}
public dynamic class var imageOfPlayNext: UIImage {
if Cache.imageOfPlayNext == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 115, height: 180), false, 0)
CoreDrawing.drawPlayNext()
Cache.imageOfPlayNext = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfPlayNext = Cache.imageOfPlayNext {
return imageOfPlayNext
} else {
fatalError("imageOfPlayNext is nil")
}
}
public dynamic class var imageOfFastFoward: UIImage {
if Cache.imageOfFastFoward == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 200, height: 180), false, 0)
CoreDrawing.drawFastFoward()
Cache.imageOfFastFoward = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfFastFoward = Cache.imageOfFastFoward {
return imageOfFastFoward
} else {
fatalError("imageOfFastFoward is nil")
}
}
public dynamic class var imageOfBack: UIImage {
if Cache.imageOfBack == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 100, height: 180), false, 0)
CoreDrawing.drawBack()
Cache.imageOfBack = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfBack = Cache.imageOfBack {
return imageOfBack
} else {
fatalError("imageOfBack is nil")
}
}
public dynamic class var imageOfPlay: UIImage {
if Cache.imageOfPlay == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 90, height: 180), false, 0)
CoreDrawing.drawPlay()
Cache.imageOfPlay = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfPlay = Cache.imageOfPlay {
return imageOfPlay
} else {
fatalError("imageOfPlay is nil")
}
}
public dynamic class var imageOfFullScreen: UIImage {
if Cache.imageOfFullScreen == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 128, height: 128), false, 0)
CoreDrawing.drawFullScreen()
Cache.imageOfFullScreen = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfFullScreen = Cache.imageOfFullScreen {
return imageOfFullScreen
} else {
fatalError("imageOfFullScreen is nil")
}
}
public dynamic class var imageOfExitFullScreen: UIImage {
if Cache.imageOfExitFullScreen == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 128, height: 128), false, 0)
CoreDrawing.drawExitFullScreen()
Cache.imageOfExitFullScreen = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfExitFullScreen = Cache.imageOfExitFullScreen {
return imageOfExitFullScreen
} else {
fatalError("imageOfExitFullScreen is nil")
}
}
public dynamic class var imageOfDefaultView: UIImage {
if Cache.imageOfDefaultView == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 128, height: 73), false, 0)
CoreDrawing.drawDefaultView()
Cache.imageOfDefaultView = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfDefaultView = Cache.imageOfDefaultView {
return imageOfDefaultView
} else {
fatalError("imageOfDefaultView is nil")
}
}
public dynamic class var imageOfCheckmark: UIImage {
if Cache.imageOfCheckmark == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 64, height: 64), false, 0)
CoreDrawing.drawCheckmark()
Cache.imageOfCheckmark = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfCheckmark = Cache.imageOfCheckmark {
return imageOfCheckmark
} else {
fatalError("imageOfCheckmark is nil")
}
}
public dynamic class var imageOfSettingsFilled: UIImage {
if Cache.imageOfSettingsFilled == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 500, height: 500), false, 0)
CoreDrawing.drawSettingsFilled()
Cache.imageOfSettingsFilled = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfSettingsFilled = Cache.imageOfSettingsFilled {
return imageOfSettingsFilled
} else {
fatalError("imageOfSettingsFilled is nil")
}
}
public dynamic class var imageOfSettings: UIImage {
if Cache.imageOfSettings == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 500, height: 500), false, 0)
CoreDrawing.drawSettings()
Cache.imageOfSettings = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfSettings = Cache.imageOfSettings {
return imageOfSettings
} else {
fatalError("imageOfSettings is nil")
}
}
public dynamic class var imageOfTheaterMode: UIImage {
if Cache.imageOfTheaterMode == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 128, height: 73), false, 0)
CoreDrawing.drawTheaterMode()
Cache.imageOfTheaterMode = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfTheaterMode = Cache.imageOfTheaterMode {
return imageOfTheaterMode
} else {
fatalError("imageOfTheaterMode is nil")
}
}
public dynamic class var imageOfSoundMuted: UIImage {
if Cache.imageOfSoundMuted == nil {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 128, height: 128), false, 0)
CoreDrawing.drawSoundMuted()
Cache.imageOfSoundMuted = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
if let imageOfSoundMuted = Cache.imageOfSoundMuted {
return imageOfSoundMuted
} else {
fatalError("imageOfSoundMuted is nil")
}
}
// MARK: - Customization Infrastructure
@IBOutlet fileprivate dynamic var nextTargets: [AnyObject]! {
get { return Cache.nextTargets }
set {
Cache.nextTargets = newValue
for target: AnyObject in newValue {
_ = target.perform(NSSelectorFromString("setImage:"), with: CoreDrawing.imageOfNext)
}
}
}
@IBOutlet fileprivate dynamic var volumeTargets: [AnyObject]! {
get { return Cache.volumeTargets }
set {
Cache.volumeTargets = newValue
for target: AnyObject in newValue {
_ = target.perform(NSSelectorFromString("setImage:"), with: CoreDrawing.imageOfVolume)
}
}
}
@IBOutlet fileprivate dynamic var playRevertTargets: [AnyObject]! {
get { return Cache.playRevertTargets }
set {
Cache.playRevertTargets = newValue
for target: AnyObject in newValue {
_ = target.perform(NSSelectorFromString("setImage:"), with: CoreDrawing.imageOfPlayRevert)
}
}
}
@objc(CoreDrawingResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
| 55.96304 | 164 | 0.624403 |
912d897555beae40b3ebe15458e4b756f5246c4d | 508 | //
// Worksheets.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct Worksheets: Codable {
public var link: Link?
public var worksheetList: [LinkElement]?
public enum CodingKeys: String, CodingKey {
case link = "link"
case worksheetList = "WorksheetList"
}
public init(link: Link?, worksheetList: [LinkElement]?) {
self.link = link
self.worksheetList = worksheetList
}
}
| 16.933333 | 61 | 0.65748 |
082d3b98ed7125c9d2be8268bd3190b88eee52db | 889 | //
// CategoryCollectionViewCell.swift
// Klozet
//
// Created by Huy Vo on 8/3/19.
//
import UIKit
class CategoryCollectionViewCell: UICollectionViewCell {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var descriptionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// backgroundColor = UIColor.white
addShadowOnCell()
addCornerRadiusOnContentView()
}
private func addShadowOnCell() {
backgroundColor = .clear // very important
layer.masksToBounds = false
layer.shadowOpacity = 0.14
layer.shadowRadius = 4
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowColor = UIColor.black.cgColor
}
private func addCornerRadiusOnContentView() {
contentView.backgroundColor = .white
contentView.layer.cornerRadius = 8
}
}
| 23.394737 | 56 | 0.654668 |
f7eb67c51dc3e0c2067146d442230bce4e494d37 | 1,420 | //
// ArgsParser.swift
// Swiftline
//
// Created by Omar Abdelhafith on 27/11/2015.
// Copyright © 2015 Omar Abdelhafith. All rights reserved.
//
class ArgsParser {
static func parseFlags(_ args: [String]) -> ([Option], [String]) {
var options = [Option]()
var others = [String]()
var previousArgument: Argument?
var argsTerminated = false
for argumentString in args {
let argument = Argument(argumentString)
defer { previousArgument = argument }
if argsTerminated {
others += [argumentString]
continue
}
if argument.isFlagTerminator {
argsTerminated = true
continue
}
if argument.isFlag {
options += [Option(argument: argument)]
continue
}
if let previousArgument = previousArgument , previousArgument.isFlag {
updatelastOption(forArray: &options, withValue: argumentString)
} else {
others += [argument.name]
}
}
return (options, others)
}
static func updatelastOption(forArray array: inout [Option], withValue value: String) {
var previousOption = array.last!
previousOption.value = value
array.removeLast()
array += [previousOption]
}
}
| 26.296296 | 91 | 0.551408 |
1d20613ce8a724b50082d930bb11ab0305fd2947 | 1,295 | //
// CharacterSetExtension.swift
// ParsecMock
//
// Created by Keith on 2018/7/2.
// Copyright © 2018 Keith. All rights reserved.
//
import Foundation
extension CharacterSet {
public func contains(_ c: Character) -> Bool {
let cs = CharacterSet.init(charactersIn: "\(c)")
return self.isSuperset(of: cs)
}
}
extension NSCharacterSet {
public var lazyCharacters:
LazyCollection<FlattenCollection<LazyMapCollection<LazyFilterCollection<(ClosedRange<UInt8>)>, [Character]>>> {
return ((0...16) as ClosedRange<UInt8>)
.lazy
.filter(self.hasMemberInPlane)
.flatMap { (plane) in
let p0 = UInt32(plane) << 16
let p1 = (UInt32(plane) + 1) << 16
return ((p0 ..< p1) as Range<UTF32Char>)
.lazy
.filter(self.longCharacterIsMember)
.compactMap(UnicodeScalar.init)
.map(Character.init)}
}
public var characters:[Character] {
return Array(self.lazyCharacters)
}
}
extension CharacterSet {
public var lazyCharacters:
LazyCollection<FlattenCollection<LazyMapCollection<LazyFilterCollection<(ClosedRange<UInt8>)>, [Character]>>> {
return (self as NSCharacterSet).lazyCharacters
}
public var characters: [Character] {
return (self as NSCharacterSet).characters
}
}
| 26.979167 | 115 | 0.671815 |
22b8fe85a81e067ee2d3c90d5570cf97afebf209 | 1,817 | import RxSwift
import CoreLocation
import RxAppState
class SingleLocationRequestRegionDetector: RegionDetector {
private let locationUpdater: LocationUpdater
var allowedAppStates: [AppState]
init(locationUpdater: LocationUpdater, allowedAppStates: [AppState]) {
self.locationUpdater = locationUpdater
self.allowedAppStates = allowedAppStates
}
func isInsideRegion(center: CLLocationCoordinate2D, radius: CLLocationDistance) -> Observable<Bool> {
UIApplication.shared.rx.currentAndChangedAppState
.flatMapLatest { appState -> Observable<Bool> in
if self.allowedAppStates.contains(appState) {
return self.performCheck(center: center, radius: radius)
}
return Observable.empty()
}
}
private func performCheck(center: CLLocationCoordinate2D, radius: CLLocationDistance) -> Observable<Bool> {
locationUpdater.locationChanges
.do(onSubscribe: { self.locationUpdater.requestCurrentLocation() })
.compactMap { (positions: [CLLocation]) -> CLLocation? in
positions
// Take only last 5 minutes positions
.filter { Date().timeIntervalSince1970 - $0.timestamp.timeIntervalSince1970 < 60.0 * 5.0 }
.sorted { $0.timestamp > $1.timestamp }
// Take only the newest position
.first
}
.map { (position: CLLocation) in
// Check if the position is inside of the region (given the accuracy)
position.distance(from: CLLocation(latitude: center.latitude, longitude: center.longitude)) < position.horizontalAccuracy + radius
}
.distinctUntilChanged()
}
}
| 37.854167 | 146 | 0.63126 |
5bfa78dc209c108b596297313bdcd8ed8ce35ab2 | 1,187 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
extension AmplifyAPICategory: APICategoryGraphQLBehavior {
// MARK: - Request-based GraphQL operations
@discardableResult
public func query<R: Decodable>(request: GraphQLRequest<R>,
listener: GraphQLOperation<R>.ResultListener?) -> GraphQLOperation<R> {
plugin.query(request: request, listener: listener)
}
@discardableResult
public func mutate<R: Decodable>(request: GraphQLRequest<R>,
listener: GraphQLOperation<R>.ResultListener?) -> GraphQLOperation<R> {
plugin.mutate(request: request, listener: listener)
}
public func subscribe<R>(request: GraphQLRequest<R>,
valueListener: GraphQLSubscriptionOperation<R>.InProcessListener?,
completionListener: GraphQLSubscriptionOperation<R>.ResultListener?)
-> GraphQLSubscriptionOperation<R> {
plugin.subscribe(request: request, valueListener: valueListener, completionListener: completionListener)
}
}
| 38.290323 | 116 | 0.658804 |
141217a0363b4eac36074b71012aafd030f9cc43 | 905 | //
// PaddingLabel.swift
// SwiftUtils
//
// Created by DaoNV on 10/5/15.
// Copyright © 2015 Astraler Technology. All rights reserved.
//
import UIKit
public class EdgeInsetsLabel: UILabel {
public var edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
override public func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect = edgeInsets.inset(bounds)
rect = super.textRectForBounds(rect, limitedToNumberOfLines: numberOfLines)
return edgeInsets.inverse.inset(rect)
}
override public func drawTextInRect(rect: CGRect) {
super.drawTextInRect(edgeInsets.inset(rect))
}
public override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
size.width += (edgeInsets.left + edgeInsets.right)
size.height += (edgeInsets.top + edgeInsets.bottom)
return size
}
} | 30.166667 | 111 | 0.720442 |
d6f123848079dcd74bc7e43be807fa285558517b | 16,487 | fileprivate func callCLibApiFunctionWithStringReturn(
_ cLibApiFunction: (
_ pString: UnsafeMutablePointer<CChar>?,
_ stringSize: Int,
_ pCharsWritten: UnsafeMutablePointer<Int>?) -> DszCLibErrorNum,
_ stringResult: inout String) -> DszCLibErrorNum
{
let stringSize: Int = 128
let pString = UnsafeMutablePointer<CChar>.allocate(capacity: stringSize)
pString.assign(repeating: ("\0".utf8CString[0]), count: stringSize)
let cLibErrorNum = cLibApiFunction(
pString,
stringSize,
nil)
stringResult = String(cString: pString)
pString.deallocate()
return cLibErrorNum
}
public struct LibraryError : Error {
private(set) var message: String
internal init(errorNum: Int) {
self.message = ""
_ = callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibErrorNumGetMessage(errorNum, pString, stringSize, pCharsWritten)
return (0)
},
&self.message)
}
internal init(message: String) {
self.message = message
}
}
extension LibraryError : CustomStringConvertible {
public var description: String {
return message
}
}
fileprivate func callCLibApiAndCheckErrorNum(_ cLibApiFunction: () -> DszCLibErrorNum) throws {
let cLibErrorNum = cLibApiFunction()
if (cLibErrorNum != 0) {
// swift doesn't unwind stack during exception throwing so no information is lost
throw (LibraryError(errorNum: cLibErrorNum))
}
}
public struct Library {
private init() {
}
public static func initialize() throws {
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in DszCLibLibraryInitialize()
})
}
public static func uninitialize() {
DszCLibLibraryUninitialize()
}
public static func getVersionString() throws -> String {
var versionString = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibLibraryGetVersionString(pString, stringSize, pCharsWritten)
}, &versionString)
})
return versionString
}
public static var versionString: String {
return (try? getVersionString()) ?? String()
}
}
public final class Address {
// https://stackoverflow.com/a/44894681
private var pImpl: UnsafeMutablePointer<DszCLibAddress?>?
public init(
streetNum: Int,
street: String,
city: String,
province: String,
zipCode: String,
country: String) throws {
self.pImpl = UnsafeMutablePointer<DszCLibAddress?>.allocate(capacity: 1)
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibAddressCreate(
CInt(truncatingIfNeeded: streetNum),
street,
city,
province,
zipCode,
country,
self.pImpl) // ?? how does this work?
})
}
internal init(addressImpl: DszCLibAddress?) {
self.pImpl = UnsafeMutablePointer<DszCLibAddress?>.allocate(capacity: 1)
self.pImpl!.pointee = addressImpl
}
deinit {
if (self.pImpl != nil) {
let pAddressImpl = self.pImpl!
DszCLibAddressDestroy(pAddressImpl.pointee)
pAddressImpl.deallocate()
self.pImpl = nil
}
}
internal func getAddressImpl() throws -> DszCLibAddress? {
assert(self.pImpl != nil)
let pAddressImpl = self.pImpl!
return pAddressImpl.pointee
}
public func getStreetNum() throws -> Int {
let addressImpl = try getAddressImpl()
let pStreetNum = UnsafeMutablePointer<CInt>.allocate(capacity: 1)
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibAddressGetStreetNum(addressImpl, pStreetNum)
})
let streetNum = pStreetNum.pointee
pStreetNum.deallocate()
return Int(streetNum)
}
public func getStreet() throws -> String {
let addressImpl = try getAddressImpl()
var street = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibAddressGetStreet(addressImpl, pString, stringSize, pCharsWritten)
}, &street)
})
return street
}
public func getCity() throws -> String {
let addressImpl = try getAddressImpl()
var city = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibAddressGetCity(addressImpl, pString, stringSize, pCharsWritten)
}, &city)
})
return city
}
public func getProvince() throws -> String {
let addressImpl = try getAddressImpl()
var province = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibAddressGetProvince(addressImpl, pString, stringSize, pCharsWritten)
}, &province)
})
return province
}
public func getZipCode() throws -> String {
let addressImpl = try getAddressImpl()
var zipCode = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibAddressGetZipCode(addressImpl, pString, stringSize, pCharsWritten)
}, &zipCode)
})
return zipCode
}
public func getCountry() throws -> String {
let addressImpl = try getAddressImpl()
var country = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibAddressGetCountry(addressImpl, pString, stringSize, pCharsWritten)
}, &country)
})
return country
}
public var streetNum: Int {
return (try? getStreetNum()) ?? Int()
}
public var street: String {
return (try? getStreet()) ?? String()
}
public var city: String {
return (try? getCity()) ?? String()
}
public var province: String {
return (try? getProvince()) ?? String()
}
public var zipCode: String {
return (try? getZipCode()) ?? String()
}
public var country: String {
return (try? getCountry()) ?? String()
}
public func toString() throws -> String {
let addressImpl = try getAddressImpl()
var addressString = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibAddressToString(addressImpl, pString, stringSize, pCharsWritten)
}, &addressString)
})
return addressString
}
}
extension Address : CustomStringConvertible {
public var description: String {
return (try? toString()) ?? String()
}
}
public final class Person {
private var pImpl: UnsafeMutablePointer<DszCLibPerson?>?
public init(
lastName: String,
firstName: String,
age: Int,
address: Address) throws {
self.pImpl = UnsafeMutablePointer<DszCLibPerson?>.allocate(capacity: 1)
let addressImpl = try address.getAddressImpl()
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibPersonCreate(
lastName,
firstName,
CInt(truncatingIfNeeded: age),
addressImpl,
self.pImpl) // ?? how does this work?
})
}
internal init(personImpl: DszCLibPerson?) {
self.pImpl = UnsafeMutablePointer<DszCLibPerson?>.allocate(capacity: 1)
self.pImpl!.pointee = personImpl
}
deinit {
if (self.pImpl != nil) {
let pPersonImpl = self.pImpl!
DszCLibPersonDestroy(pPersonImpl.pointee)
pPersonImpl.deallocate()
self.pImpl = nil
}
}
internal func getPersonImpl() throws -> DszCLibPerson? {
assert(self.pImpl != nil)
let pPersonImpl = self.pImpl!
return pPersonImpl.pointee
}
public func getLastName() throws -> String {
let personImpl = try getPersonImpl()
var lastName = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibPersonGetLastName(personImpl, pString, stringSize, pCharsWritten)
}, &lastName)
})
return lastName
}
public func getFirstName() throws -> String {
let personImpl = try getPersonImpl()
var firstName = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibPersonGetFirstName(personImpl, pString, stringSize, pCharsWritten)
}, &firstName)
})
return firstName
}
public func getAge() throws -> Int {
let personImpl = try getPersonImpl()
let pAge = UnsafeMutablePointer<CInt>.allocate(capacity: 1)
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibPersonGetAge(personImpl, pAge)
})
let age = pAge.pointee
pAge.deallocate()
return Int(age)
}
public func getAddress() throws -> Address? {
let personImpl = try getPersonImpl()
let pAddressImpl = UnsafeMutablePointer<DszCLibAddress?>.allocate(capacity: 1)
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibPersonGetAddress(personImpl, pAddressImpl)
})
let addressImpl = pAddressImpl.pointee
if (addressImpl == nil) {
return nil
}
let address = Address(addressImpl: addressImpl)
pAddressImpl.deallocate()
return address
}
public var lastName: String {
return (try? getLastName()) ?? String()
}
public var firstName: String {
return (try? getFirstName()) ?? String()
}
public var age: Int {
return (try? getAge()) ?? Int()
}
public var address: Address? {
return try? getAddress()
}
public func toString() throws -> String {
let personImpl = try getPersonImpl()
var personString = String();
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
callCLibApiFunctionWithStringReturn({
(pString, stringSize, pCharsWritten) -> DszCLibErrorNum in
DszCLibPersonToString(personImpl, pString, stringSize, pCharsWritten)
}, &personString)
})
return personString
}
}
extension Person : CustomStringConvertible {
public var description: String {
return (try? toString()) ?? String()
}
}
public protocol Generator {
func generateInt(data: Int) -> Int
func generateString(data: Int) -> String
}
fileprivate func generateIntRedirect(
_ data: CInt,
_ pInt: UnsafeMutablePointer<CInt>?,
_ pUserData: UnsafeMutableRawPointer?) -> DszCLibErrorNum {
if (pInt == nil) {
return DszCLibErrorNum(-2)
}
if (pUserData == nil) {
return DszCLibErrorNum(-2)
}
let generator = pUserData!.load(as: Generator.self)
let generatedInt = generator.generateInt(data: Int(data))
pInt!.pointee = CInt(truncatingIfNeeded: generatedInt)
return DszCLibErrorNum(0)
}
fileprivate func generateStringRedirect(
_ data: CInt,
_ pString: UnsafeMutablePointer<CChar>?,
_ stringSize: Int,
_ pCharsWritten: UnsafeMutablePointer<Int>?,
_ pUserData: UnsafeMutableRawPointer?) -> DszCLibErrorNum {
if (pUserData == nil) {
return DszCLibErrorNum(-2)
}
let generator = pUserData!.load(as: Generator.self)
let generatedString = generator.generateString(data: Int(data))
var numChars = generatedString.utf8.count;
if ((pString != nil) && (stringSize > 0)) {
numChars = numChars < stringSize ? numChars : stringSize
let utf8Array = Array(generatedString.utf8)
for i in 1...numChars {
pString![i - 1] = CChar(utf8Array[i - 1])
}
}
if (pCharsWritten != nil) {
pCharsWritten!.pointee = numChars
}
return DszCLibErrorNum(0)
}
public final class Printer {
private var pImpl: UnsafeMutablePointer<DszCLibPrinter?>?
private var generator: Generator
// needed to keep the closures alive as long as Printer is allive
private var fnGenerateInt: DszCLibGenerateIntFunction?
private var fnGenerateString: DszCLibGenerateStringFunction?
public init(generator: Generator) throws {
self.pImpl = UnsafeMutablePointer<DszCLibPerson?>.allocate(capacity: 1)
self.generator = generator
fnGenerateInt = {
(data, pInt, pUserData) -> DszCLibErrorNum in
generateIntRedirect(data, pInt, pUserData)
}
fnGenerateString = {
(data, pString, stringSize, pCharsWritten, pUserData) -> DszCLibErrorNum in
generateStringRedirect(data, pString, stringSize, pCharsWritten, pUserData)
}
let pGeneratorImpl = try createGeneratorImpl()
if (pGeneratorImpl == nil) {
throw LibraryError(message: "Failed to create generator")
}
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibPrinterCreate(
pGeneratorImpl!.pointee,
self.pImpl)
})
pGeneratorImpl!.deallocate()
}
deinit {
if (self.pImpl != nil) {
let pPrinterImpl = self.pImpl!
DszCLibPrinterDestroy(pPrinterImpl.pointee)
pPrinterImpl.deallocate()
self.pImpl = nil
}
}
internal func getPrinterImpl() throws -> DszCLibPrinter? {
assert(self.pImpl != nil)
let pPrinterImpl = self.pImpl!
return pPrinterImpl.pointee
}
private func createGeneratorImpl() throws -> UnsafeMutablePointer<DszCLibGenerator?>? {
let pGeneratorImpl = UnsafeMutablePointer<DszCLibGenerator?>.allocate(capacity: 1)
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibGeneratorCreate(
fnGenerateInt,
fnGenerateString,
pGeneratorImpl)
})
return pGeneratorImpl
}
public func printInt() throws {
let printerImpl = try getPrinterImpl()
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibPrinterPrintIntWithUserData(
printerImpl,
&self.generator)
})
}
public func printString() throws {
let printerImpl = try getPrinterImpl()
try callCLibApiAndCheckErrorNum({
() -> DszCLibErrorNum in
DszCLibPrinterPrintStringWithUserData(
printerImpl,
&self.generator)
})
}
}
| 29.336299 | 98 | 0.595924 |
6910758b797edb1d13adbfe1db1ea0ed4c5a8cf9 | 7,718 | //
// Valet.swift
// PHP Monitor
//
// Created by Nico Verbruggen on 29/11/2021.
// Copyright © 2021 Nico Verbruggen. All rights reserved.
//
import Foundation
class Valet {
static let shared = Valet()
/// The version of Valet that was detected.
var version: String
/// The Valet configuration file.
var config: Valet.Configuration
/// A cached list of sites that were detected after analyzing the paths set up for Valet.
var sites: [Site] = []
init() {
version = VersionExtractor.from(Actions.valet("--version"))
?? "UNKNOWN"
let file = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".config/valet/config.json")
config = try! JSONDecoder().decode(
Valet.Configuration.self,
from: try! String(contentsOf: file, encoding: .utf8).data(using: .utf8)!
)
self.sites = []
}
public func startPreloadingSites() {
let maximumPreload = 10
let foundSites = self.countPaths()
if foundSites <= maximumPreload {
// Preload the sites and their drivers
print("Fewer than or \(maximumPreload) sites found, preloading list of sites...")
self.reloadSites()
} else {
print("\(foundSites) sites found, exceeds \(maximumPreload) for preload at launch!")
}
}
public func reloadSites() {
resolvePaths(tld: config.tld)
}
public func validateVersion() -> Void {
if version == "UNKNOWN" {
return print("The Valet version could not be extracted... that does not bode well.")
}
if version.versionCompare(Constants.MinimumRecommendedValetVersion) == .orderedAscending {
let version = version
print("Valet version \(version) is too old! (recommended: \(Constants.MinimumRecommendedValetVersion))")
DispatchQueue.main.async {
Alert.notify(message: "alert.min_valet_version.title".localized, info: "alert.min_valet_version.info".localized(version, Constants.MinimumRecommendedValetVersion))
}
} else {
print("Valet version \(version) is recent enough, OK (recommended: \(Constants.MinimumRecommendedValetVersion))")
}
}
/**
Returns a count of how many sites are linked and parked.
*/
private func countPaths() -> Int {
var count = 0
for path in config.paths {
let entries = try! FileManager.default.contentsOfDirectory(atPath: path)
for entry in entries {
if resolveSite(entry, forPath: path) {
count += 1
}
}
}
return count
}
/**
Resolves all paths and creates linked or parked site instances that can be referenced later.
*/
private func resolvePaths(tld: String) {
sites = []
for path in config.paths {
let entries = try! FileManager.default.contentsOfDirectory(atPath: path)
for entry in entries {
resolvePath(entry, forPath: path, tld: tld)
}
}
}
/**
Determines whether the site can be resolved as a symbolic link or as a directory.
Regular files are ignored. Returns true if the path can be parsed.
*/
private func resolveSite(_ entry: String, forPath path: String) -> Bool {
let siteDir = path + "/" + entry
let attrs = try! FileManager.default.attributesOfItem(atPath: siteDir)
let type = attrs[FileAttributeKey.type] as! FileAttributeType
if type == FileAttributeType.typeSymbolicLink || type == FileAttributeType.typeDirectory {
return true
}
return false
}
/**
Determines whether the site can be resolved as a symbolic link or as a directory.
Regular files are ignored, and the site is added to Valet's list of sites.
*/
private func resolvePath(_ entry: String, forPath path: String, tld: String) {
let siteDir = path + "/" + entry
// See if the file is a symlink, if so, resolve it
let attrs = try! FileManager.default.attributesOfItem(atPath: siteDir)
// We can also determine whether the thing at the path is a directory, too
let type = attrs[FileAttributeKey.type] as! FileAttributeType
// We should also check that we can interpret the path correctly
if URL(fileURLWithPath: siteDir).lastPathComponent == "" {
print("Warning: could not parse the site: \(siteDir), skipping!")
return
}
if type == FileAttributeType.typeSymbolicLink {
sites.append(Site(aliasPath: siteDir, tld: tld))
} else if type == FileAttributeType.typeDirectory {
sites.append(Site(absolutePath: siteDir, tld: tld))
}
}
// MARK: - Structs
class Site {
/// Name of the site. Does not include the TLD.
var name: String!
/// The absolute path to the directory that is served.
var absolutePath: String!
/// Location of the alias. If set, this is a linked domain.
var aliasPath: String?
/// Whether the site has been secured.
var secured: Bool!
/// What driver is currently in use. If not detected, defaults to nil.
var driver: String? = nil
init() {}
convenience init(absolutePath: String, tld: String) {
self.init()
self.absolutePath = absolutePath
self.name = URL(fileURLWithPath: absolutePath).lastPathComponent
self.aliasPath = nil
determineSecured(tld)
determineDriver()
}
convenience init(aliasPath: String, tld: String) {
self.init()
self.absolutePath = try! FileManager.default.destinationOfSymbolicLink(atPath: aliasPath)
self.name = URL(fileURLWithPath: aliasPath).lastPathComponent
self.aliasPath = aliasPath
determineSecured(tld)
determineDriver()
}
public func determineSecured(_ tld: String) {
secured = Shell.fileExists("~/.config/valet/Certificates/\(self.name!).\(tld).key")
}
public func determineDriver() {
let driver = Shell.pipe("cd '\(absolutePath!)' && valet which", requiresPath: true)
if driver.contains("This site is served by") {
self.driver = driver
// TODO: Use a regular expression to retrieve the driver instead?
.replacingOccurrences(of: "This site is served by [", with: "")
.replacingOccurrences(of: "ValetDriver].\n", with: "")
} else {
self.driver = nil
}
}
}
struct Configuration: Decodable {
/// Top level domain suffix. Usually "test" but can be set to something else.
/// - Important: Does not include the actual dot. ("test", not ".test"!)
let tld: String
/// The paths that need to be checked.
let paths: [String]
/// The loopback address.
let loopback: String
/// The default site that is served if the domain is not found. Optional.
let defaultSite: String?
private enum CodingKeys: String, CodingKey {
case tld, paths, loopback, defaultSite = "default"
}
}
}
| 35.081818 | 179 | 0.580591 |
8f07abc0d9120a8c2477f24b7e7a871ecb04a001 | 935 | //
// PracticeProjectTests.swift
// PracticeProjectTests
//
// Created by Nghia Nguyen on 2/29/20.
// Copyright © 2020 Nghia Nguyen. All rights reserved.
//
import XCTest
@testable import PracticeProject
class PracticeProjectTests: XCTestCase {
override func 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.
}
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.714286 | 111 | 0.665241 |
dee98e6a3d3ba075734a4b91bc5de109d4812f16 | 9,432 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2018 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// The description for an individual target.
public final class Target {
/// The type of this target.
public enum TargetType: String, Encodable {
case regular
case test
case system
}
/// Represents a target's dependency on another entity.
public enum Dependency {
#if PACKAGE_DESCRIPTION_4
case targetItem(name: String)
case productItem(name: String, package: String?)
case byNameItem(name: String)
#else
case _targetItem(name: String)
case _productItem(name: String, package: String?)
case _byNameItem(name: String)
#endif
}
/// The name of the target.
public var name: String
/// The path of the target, relative to the package root.
///
/// If nil, package manager will search the predefined paths to look
/// for this target.
public var path: String?
/// The source files in this target.
///
/// If nil, all valid source files found in the target's path will be included.
///
/// This can contain directories and individual source files. Directories
/// will be searched recursively for valid source files.
///
/// Paths specified are relative to the target path.
public var sources: [String]?
/// List of paths to be excluded from source inference.
///
/// Exclude paths are relative to the target path.
/// This property has more precedence than sources property.
public var exclude: [String]
/// If this is a test target.
public var isTest: Bool {
return type == .test
}
/// Dependencies on other entities inside or outside the package.
public var dependencies: [Dependency]
/// The path to the directory containing public headers of a C language target.
///
/// If a value is not provided, the directory will be set to "include".
public var publicHeadersPath: String?
/// The type of target.
public let type: TargetType
/// `pkgconfig` name to use for system library target. If present, swiftpm will try to
/// search for <name>.pc file to get the additional flags needed for the
/// system target.
public let pkgConfig: String?
/// Providers array for the System library target.
public let providers: [SystemPackageProvider]?
/// C build settings.
public var cSettings: [CSetting]?
/// C++ build settings.
public var cxxSettings: [CXXSetting]?
/// Swift build settings.
public var swiftSettings: [SwiftSetting]?
/// Linker build settings.
public var linkerSettings: [LinkerSetting]?
/// Construct a target.
private init(
name: String,
dependencies: [Dependency],
path: String?,
exclude: [String],
sources: [String]?,
publicHeadersPath: String?,
type: TargetType,
pkgConfig: String? = nil,
providers: [SystemPackageProvider]? = nil,
cSettings: [CSetting]? = nil,
cxxSettings: [CXXSetting]? = nil,
swiftSettings: [SwiftSetting]? = nil,
linkerSettings: [LinkerSetting]? = nil
) {
self.name = name
self.dependencies = dependencies
self.path = path
self.publicHeadersPath = publicHeadersPath
self.sources = sources
self.exclude = exclude
self.type = type
self.pkgConfig = pkgConfig
self.providers = providers
self.cSettings = cSettings
self.cxxSettings = cxxSettings
self.swiftSettings = swiftSettings
self.linkerSettings = linkerSettings
switch type {
case .regular, .test:
precondition(pkgConfig == nil && providers == nil)
case .system: break
}
}
public static func target(
name: String,
dependencies: [Dependency] = [],
path: String? = nil,
exclude: [String] = [],
sources: [String]? = nil,
publicHeadersPath: String? = nil,
cSettings: [CSetting]? = nil,
cxxSettings: [CXXSetting]? = nil,
swiftSettings: [SwiftSetting]? = nil,
linkerSettings: [LinkerSetting]? = nil
) -> Target {
return Target(
name: name,
dependencies: dependencies,
path: path,
exclude: exclude,
sources: sources,
publicHeadersPath: publicHeadersPath,
type: .regular,
cSettings: cSettings,
cxxSettings: cxxSettings,
swiftSettings: swiftSettings,
linkerSettings: linkerSettings
)
}
public static func testTarget(
name: String,
dependencies: [Dependency] = [],
path: String? = nil,
exclude: [String] = [],
sources: [String]? = nil,
cSettings: [CSetting]? = nil,
cxxSettings: [CXXSetting]? = nil,
swiftSettings: [SwiftSetting]? = nil,
linkerSettings: [LinkerSetting]? = nil
) -> Target {
return Target(
name: name,
dependencies: dependencies,
path: path,
exclude: exclude,
sources: sources,
publicHeadersPath: nil,
type: .test,
cSettings: cSettings,
cxxSettings: cxxSettings,
swiftSettings: swiftSettings,
linkerSettings: linkerSettings
)
}
#if !PACKAGE_DESCRIPTION_4
public static func systemLibrary(
name: String,
path: String? = nil,
pkgConfig: String? = nil,
providers: [SystemPackageProvider]? = nil
) -> Target {
return Target(
name: name,
dependencies: [],
path: path,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .system,
pkgConfig: pkgConfig,
providers: providers)
}
#endif
}
extension Target: Encodable {
private enum CodingKeys: CodingKey {
case name
case path
case sources
case exclude
case dependencies
case publicHeadersPath
case type
case pkgConfig
case providers
case cSettings
case cxxSettings
case swiftSettings
case linkerSettings
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(path, forKey: .path)
try container.encode(sources, forKey: .sources)
try container.encode(exclude, forKey: .exclude)
try container.encode(dependencies, forKey: .dependencies)
try container.encode(publicHeadersPath, forKey: .publicHeadersPath)
try container.encode(type, forKey: .type)
try container.encode(pkgConfig, forKey: .pkgConfig)
try container.encode(providers, forKey: .providers)
if let cSettings = self.cSettings {
let cSettings = VersionedValue(cSettings, api: "cSettings", versions: [.v5])
try container.encode(cSettings, forKey: .cSettings)
}
if let cxxSettings = self.cxxSettings {
let cxxSettings = VersionedValue(cxxSettings, api: "cxxSettings", versions: [.v5])
try container.encode(cxxSettings, forKey: .cxxSettings)
}
if let swiftSettings = self.swiftSettings {
let swiftSettings = VersionedValue(swiftSettings, api: "swiftSettings", versions: [.v5])
try container.encode(swiftSettings, forKey: .swiftSettings)
}
if let linkerSettings = self.linkerSettings {
let linkerSettings = VersionedValue(linkerSettings, api: "linkerSettings", versions: [.v5])
try container.encode(linkerSettings, forKey: .linkerSettings)
}
}
}
extension Target.Dependency {
/// A dependency on a target in the same package.
public static func target(name: String) -> Target.Dependency {
#if PACKAGE_DESCRIPTION_4
return .targetItem(name: name)
#else
return ._targetItem(name: name)
#endif
}
/// A dependency on a product from a package dependency.
public static func product(name: String, package: String? = nil) -> Target.Dependency {
#if PACKAGE_DESCRIPTION_4
return .productItem(name: name, package: package)
#else
return ._productItem(name: name, package: package)
#endif
}
// A by-name dependency that resolves to either a target or a product,
// as above, after the package graph has been loaded.
public static func byName(name: String) -> Target.Dependency {
#if PACKAGE_DESCRIPTION_4
return .byNameItem(name: name)
#else
return ._byNameItem(name: name)
#endif
}
}
// MARK: ExpressibleByStringLiteral
extension Target.Dependency: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
#if PACKAGE_DESCRIPTION_4
self = .byNameItem(name: value)
#else
self = ._byNameItem(name: value)
#endif
}
}
| 31.545151 | 103 | 0.61726 |
6919bf865f0d27e28c45186d6259e357989963c0 | 5,978 | /**
* 企业信息控制器
*/
import UIKit
class THJGProCompanyController: THJGBaseController {
//MARK: - UI Elements
@IBOutlet weak var tabView: UIView!
@IBOutlet weak var baseBtn: UIButton!
@IBOutlet weak var financeBtn: UIButton!
@IBOutlet weak var riskBtn: UIButton!
@IBOutlet weak var markView: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var baseInfoView: THJGProCompanyBaseInfoView!
@IBOutlet weak var financeInfoView: THJGProCompanyFinanceInfoView!
@IBOutlet weak var riskInfoView: THJGProCompanyRiskInfoView!
//MARK: - Properties
var param: (comId: String, comType: String, index: Int)!
var companyVM = THJGProCompanyViewModel()
var bean: THJGProCompanyBean! {
didSet {
//设置标题
navigationItem.title = bean.baseInfo.companyName
//设定当前tab
curSelectedIndex = param.index
}
}
//tab相关
var curSelectedTab: UIButton!
var curSelectedIndex: Int = 0 {
didSet {
switch curSelectedIndex {
case 0://公司信息
tabBtnDidClicked(baseBtn)
case 1://财务信息
tabBtnDidClicked(financeBtn)
case 2://风险信息
tabBtnDidClicked(riskBtn)
default:
break
}
}
}
//MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
//初始化
setup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
/* 注册请求成功通知 */
NotificationCenter.default.addObserver(self, selector: #selector(requestSuccess(_:)), name: NSNotification.Name(THJG_NOTIFICATION_PROCOMPANY_SUCCESS), object: nil)
}
}
//MARK: - METHODS
extension THJGProCompanyController {
//初始化
func setup() {
//屏蔽全屏返回手势
fd_interactivePopDisabled = true
//add guesture to the view
let guesture_left = UISwipeGestureRecognizer(target: self, action: #selector(swapSubViews))
guesture_left.direction = .left
view.addGestureRecognizer(guesture_left)
let guesture_right = UISwipeGestureRecognizer(target: self, action: #selector(swapSubViews))
guesture_right.direction = .right
view.addGestureRecognizer(guesture_right)
//发送请求
requestForData()
}
//MARK: - switch the tab
@objc func swapSubViews(_ guestureRecognizer: UISwipeGestureRecognizer) {
switch guestureRecognizer.direction {
case .left:
if curSelectedIndex != 2 {
curSelectedIndex += 1
} else {
curSelectedIndex = 0
}
case .right:
if curSelectedIndex != 0 {
curSelectedIndex -= 1
} else {
curSelectedIndex = 2
}
default:
break
}
}
//请求数据
func requestForData() {
//校验参数
if DQSUtils.isBlank(param.comId)
|| DQSUtils.isBlank(param.comType) {
DispatchQueue.main.async {
self.bean = THJGProCompanyBean(baseInfo: ProCompanyBaseInfoBean(companyName: "企业信息", legalName: "", registerAmount: "", actualAmount: "", authCode: "", companyDes: "", leaderInfo: [ProCompanyPdfBean]()), financeInfo: [ProCompanyPdfBean](), riskInfo: [ProCompanyPdfBean]())
}
return
}
//请求数据
DQSUtils.showLoading(view)
companyVM.requestForProCompanyData(param: ["companyId": param.comId, "companyType": param.comType])
}
override func requestSuccess(_ notification: Notification) {
super.requestSuccess(notification)
let specBean = notification.object as! THJGSuccessBean
bean = (specBean.bean as! THJGProCompanyBean)
}
//MARK: - tab切换事件监听
@IBAction func tabBtnDidClicked(_ sender: UIButton) {
guard sender != curSelectedTab else {
return
}
if curSelectedTab != nil {
curSelectedTab.isSelected = false
}
sender.isSelected = true
curSelectedTab = sender
switch sender.tag {
case 1000:
containerView.bringSubviewToFront(baseInfoView)
baseInfoView.reloadData(bean: bean) {[unowned self] (pdfUrl, _) in
let request = URLRequest(url: URL(string: pdfUrl)!)
let webVC = THJGWebController()
webVC.request = request
self.navigationController?.pushViewController(webVC, animated: true)
}
//调整底部红色浮标
var center = markView.center
center.x = baseBtn.center.x
markView.center = center
case 1001:
containerView.bringSubviewToFront(financeInfoView)
financeInfoView.reloadData(bean: bean) {[unowned self] (pdfUrl, _) in
let request = URLRequest(url: URL(string: pdfUrl)!)
let webVC = THJGWebController()
webVC.request = request
self.navigationController?.pushViewController(webVC, animated: true)
}
//调整底部红色浮标
var center = markView.center
center.x = financeBtn.center.x
markView.center = center
case 1002:
containerView.bringSubviewToFront(riskInfoView)
riskInfoView.reloadData(bean: bean) {[unowned self] (pdfUrl, _) in
let request = URLRequest(url: URL(string: pdfUrl)!)
let webVC = THJGWebController()
webVC.request = request
self.navigationController?.pushViewController(webVC, animated: true)
}
//调整底部红色浮标
var center = markView.center
center.x = riskBtn.center.x
markView.center = center
default:
break
}
}
}
| 32.846154 | 288 | 0.585815 |
015a15ee27108f6fd9f42c6d39374d4e079da800 | 3,331 | //
// KRActivityIndicatorAnimationBallBeat.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
class KRActivityIndicatorAnimationBallBeat: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - circleSize) / 2
let duration: CFTimeInterval = 0.7
let beginTime = CACurrentMediaTime()
let beginTimes = [0.35, 0, 0.35]
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.75, 1]
scaleAnimation.duration = duration
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 0.5, 1]
opacityAnimation.values = [1, 0.2, 1]
opacityAnimation.duration = duration
// Aniamtion
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circles
for i in 0 ..< 3 {
let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
| 41.6375 | 133 | 0.661963 |
ff803921fdfad9ba035493ad64f44c16c0a5bb02 | 2,754 | //
// ViewController.swift
// InTouchApp
//
// Created by Никита Казанцев on 25.10.2020.
//
import UIKit
import MessageUI
class ViewController: UIViewController, MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func sendEmail(sender: AnyObject) {
if MFMailComposeViewController.canSendMail() {
let mailVC = MFMailComposeViewController()
mailVC.setSubject("MySubject")
mailVC.setToRecipients(["[email protected]"])
mailVC.setMessageBody("<p>Hello!</p>", isHTML: true)
mailVC.mailComposeDelegate = self;
self.present(mailVC, animated: true, completion: nil) } else {
print("This device is currently unable to send email") }
}
@IBAction func sendText(sender: AnyObject) {
if MFMessageComposeViewController.canSendText() {
let smsVC : MFMessageComposeViewController = MFMessageComposeViewController()
smsVC.messageComposeDelegate = self
smsVC.recipients = ["1234500000"]
smsVC.body = "Please call me back."
self.present(smsVC, animated: true, completion: nil) } else {
print("This device is currently unable to send text messages") }
}
@IBAction func openWebsite(sender: AnyObject) {
UIApplication.shared.open(URL(string: "http://hse.ru")!, options: [:], completionHandler: nil) }
func mailComposeController(_ didFinishWithcontroller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: NSError?) {
switch result {
case MFMailComposeResult.sent:
print("Result: Email Sent!")
case MFMailComposeResult.cancelled:
print("Result: Email Cancelled.") case MFMailComposeResult.failed:
print("Result: Error, Unable to Send Email.") case MFMailComposeResult.saved:
print("Result: Mail Saved as Draft.") }
self.dismiss(animated: true, completion: nil) }
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
switch result {
case MessageComposeResult.sent:
print("Result: Text Message Sent!") case MessageComposeResult.cancelled:
print("Result: Text Message Cancelled.") case MessageComposeResult.failed:
print("Result: Error, Unable to Send Text Message.") }
self.dismiss(animated:true, completion: nil) }
}
| 43.03125 | 148 | 0.650327 |
ac8412daeb4e779a91b1a4d5173df60cb2fb411c | 12,711 | // The SwiftUI Lab
// Website: https://swiftui-lab.com
// Article: https://swiftui-lab.com/alignment-guides
import SwiftUI
class Model: ObservableObject {
@Published var minimumContainer = true
@Published var extendedTouchBar = false
@Published var twoPhases = true
@Published var addImplicitView = false
@Published var showImplicit = false
@Published var algn: [AlignmentEnum] = [.center, .center, .center]
@Published var delayedAlgn: [AlignmentEnum] = [.center, .center, .center]
@Published var frameAlignment: Alignment = .center
@Published var stackAlignment: HorizontalAlignment = .leading
func nextAlignment() -> Alignment {
if self.frameAlignment == .leading {
return .center
} else if self.frameAlignment == .center {
return .trailing
} else {
return .leading
}
}
}
extension Alignment {
var asString: String {
switch self {
case .leading:
return ".leading"
case .center:
return ".center"
case .trailing:
return ".trailing"
default:
return "unknown"
}
}
}
extension HorizontalAlignment {
var asString: String {
switch self {
case .leading:
return ".leading"
case .trailing:
return ".trailing"
case .center:
return ".center"
default:
return "unknown"
}
}
}
extension HorizontalAlignment: Hashable {
public func hash(into hasher: inout Hasher) {
switch self {
case .leading:
hasher.combine(0)
case .center:
hasher.combine(1)
case .trailing:
hasher.combine(2)
default:
hasher.combine(3)
}
}
}
extension Alignment: Hashable {
public func hash(into hasher: inout Hasher) {
switch self {
case .leading:
hasher.combine(0)
case .center:
hasher.combine(1)
case .trailing:
hasher.combine(2)
default:
hasher.combine(3)
}
}
}
struct ContentView: View {
var body: some View {
Group {
if UIDevice.current.userInterfaceIdiom == .pad
{
GeometryReader { proxy in
VStack(spacing: 0) {
HStack(spacing: 0) {
ControlsView().frame(width: 380).layoutPriority(1).background(Color(UIColor.secondarySystemBackground))
DisplayView(width: proxy.size.width - 380).frame(maxWidth: proxy.size.width - 380).clipShape(Rectangle())//.border(Color.green, width: 3)
}.frame(height: (proxy.size.height - 300))
VStack {
CodeView().frame(height: 300)
}.frame(width: proxy.size.width, alignment: .center).background(Color(UIColor.secondarySystemBackground))
}.environmentObject(Model())
}
} else {
VStack(spacing: 30) {
Text("I need an iPad to run!")
Text("😟").scaleEffect(2)
}.font(.largeTitle)
}
}
}
}
struct ControlsView: View {
@EnvironmentObject var model: Model
var body: some View {
return Form {
HStack { Spacer(); Text("Settings").font(.title); Spacer() }
Toggle(isOn: self.$model.minimumContainer, label: { Text("Narrow Container") })
Toggle(isOn: self.$model.extendedTouchBar, label: { Text("Extended Bar") })
Toggle(isOn: self.$model.twoPhases, label: { Text("Show in Two Phases") })
Toggle(isOn: self.$model.addImplicitView, label: { Text("Include Implicitly View") })
if self.model.addImplicitView {
Toggle(isOn: self.$model.showImplicit, label: { Text("Show Implicit Guides") })//.disabled(!self.model.addImplicitView)
}
HStack {
Text("Frame Alignment")
Picker(selection: self.$model.frameAlignment.animation(), label: EmptyView()) {
Text(".leading").tag(Alignment.leading)
Text(".center").tag(Alignment.center)
Text(".trailing").tag(Alignment.trailing)
}.pickerStyle(SegmentedPickerStyle())
}
HStack {
Text("Stack Alignment")
Picker(selection: self.$model.stackAlignment.animation(), label: EmptyView()) {
Text(".leading").tag(HorizontalAlignment.leading)
Text(".center").tag(HorizontalAlignment.center)
Text(".trailing").tag(HorizontalAlignment.trailing)
}.pickerStyle(SegmentedPickerStyle())
}
}.padding(10).background(Color(UIColor.secondarySystemBackground))
}
}
struct CodeView: View {
@EnvironmentObject var model: Model
var body: some View {
VStack(alignment: .leading) {
Text("VStack(alignment: \(self.model.stackAlignment.asString) {")
CodeFragment(idx: 0)
CodeFragment(idx: 1)
if model.addImplicitView {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 0) {
Text(" SomeView()").foregroundColor(.primary)
Text(".alignmentGuide(\(self.model.stackAlignment.asString), computedValue { d in ")
Text("d[\(self.model.stackAlignment.asString)]").padding(5)
Text(" }")
}.foregroundColor(self.model.showImplicit ? .secondary : .clear)//.transition(AnyTransition.opacity.animation())
}
}
CodeFragment(idx: 2)
HStack(spacing: 0) {
Text("}.frame(alignment: ")
Text("\(self.model.frameAlignment.asString)").padding(5)
Text(")")
}
}
.font(Font.custom("Menlo", size: 16))
.padding(20)
}
}
struct CodeFragment: View {
@EnvironmentObject var model: Model
var idx: Int
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 0) {
Text(" SomeView()")
Text(".alignmentGuide(\(self.model.stackAlignment.asString), computedValue { d in ")
Text("\(self.model.algn[idx].asString)").padding(5).background(self.model.algn[idx] != self.model.delayedAlgn[idx] ? Color.yellow : Color.clear)
Text(" }")
}
}
}
}
struct DisplayView: View {
@EnvironmentObject var model: Model
let width: CGFloat
var body: some View {
VStack(alignment: self.model.stackAlignment, spacing: 20) {
Block(algn: binding(0)).frame(width: 250)
.alignmentGuide(self.model.stackAlignment, computeValue: { d in self.model.delayedAlgn[0].computedValue(d) })
Block(algn: binding(1)).frame(width: 200)
.alignmentGuide(self.model.stackAlignment, computeValue: { d in self.model.delayedAlgn[1].computedValue(d) })
if model.addImplicitView {
RoundedRectangle(cornerRadius: 8).fill(Color.gray).frame(width: 250, height: 50)
.overlay(Text("Implicitly Aligned").foregroundColor(.white))
.overlay(Marker(algn: AlignmentEnum.fromHorizontalAlignment(self.model.stackAlignment)).opacity(0.5))
}
Block(algn: binding(2)).frame(width: 300)
.alignmentGuide(self.model.stackAlignment, computeValue: { d in self.model.delayedAlgn[2].computedValue(d) })
}.frame(width: self.model.minimumContainer ? nil : width, alignment: self.model.frameAlignment).border(Color.red)
}
func binding(_ idx: Int) -> Binding<AlignmentEnum> {
return Binding<AlignmentEnum>(get: {
self.model.algn[idx]
}, set: { v in
self.model.algn[idx] = v
let delay = self.model.twoPhases ? 500 : 0
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay)) {
withAnimation(.easeInOut(duration: 0.5)
) {
self.model.delayedAlgn[idx] = v
}
}
})
}
}
struct Block: View {
@Binding var algn: AlignmentEnum
let a = Animation.easeInOut(duration: 0.5)
var body: some View {
let gesture = DragGesture(minimumDistance: 0, coordinateSpace: .local)
.onEnded({v in
withAnimation(self.a) {
self.algn = .value(v.startLocation.x)
}
})
return VStack(spacing: 0) {
HStack {
AlignButton(label: "L", action: { withAnimation(self.a) { self.algn = .leading } })
Spacer()
AlignButton(label: "C", action: { withAnimation(self.a) { self.algn = .center } })
Spacer()
AlignButton(label: "T", action: { withAnimation(self.a) { self.algn = .trailing } })
}.padding(5)
.padding(.bottom, 20)
}
.background(RoundedRectangle(cornerRadius: 8).foregroundColor(.gray))
.overlay(TouchBar().gesture(gesture))
.overlay(Marker(algn: algn).opacity(0.5))
}
}
struct TouchBar: View {
@EnvironmentObject var model: Model
@State private var flag = false
var body: some View {
GeometryReader { proxy in
RoundedRectangle(cornerRadius: 8)
.foregroundColor(.yellow)
.frame(width: proxy.size.width + (self.model.extendedTouchBar ? 100 : 0), height: 20)
.offset(x: 0, y: proxy.size.height / 2.0 - 10)
}
}
}
struct AlignButton: View {
let label: String
let action: () -> ()
var body: some View {
Button(action: {
self.action()
}, label: {
Text(label)
.foregroundColor(.black)
.padding(10)
.background(RoundedRectangle(cornerRadius: 8).foregroundColor(.green))
})
}
}
struct Marker: View {
let algn: AlignmentEnum
var body: some View {
GeometryReader { proxy in
MarkerLine().offset(x: self.algn.asNumber(width: proxy.size.width))
}
}
}
struct MarkerLine: Shape {
func path(in rect: CGRect) -> Path {
var p = Path()
p.move(to: CGPoint(x: 0, y: 0))
p.addLine(to: CGPoint(x: 0, y: rect.maxY))
p = p.strokedPath(.init(lineWidth: 4, lineCap: .round, lineJoin: .bevel, miterLimit: 1, dash: [6, 6], dashPhase: 3))
return p
}
}
enum AlignmentEnum: Equatable {
case leading
case center
case trailing
case value(CGFloat)
var asString: String {
switch self {
case .leading:
return "d[.leading]"
case .center:
return "d[.center]"
case .trailing:
return "d[.trailing]"
case .value(let v):
return "\(v)"
}
}
func asNumber(width: CGFloat) -> CGFloat {
switch self {
case .leading:
return 0
case .center:
return width / 2.0
case .trailing:
return width
case .value(let v):
return v
}
}
func computedValue(_ d: ViewDimensions) -> CGFloat {
switch self {
case .leading:
return d[.leading]
case .center:
return d.width / 2.0
case .trailing:
return d[.trailing]
case .value(let v):
return v
}
}
static func fromHorizontalAlignment(_ a: HorizontalAlignment) -> AlignmentEnum {
switch a {
case .leading:
return .leading
case .center:
return .center
case .trailing:
return .trailing
default:
return .value(0)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 31.154412 | 165 | 0.524192 |
Subsets and Splits