text
stringlengths
8
1.32M
import Foundation import TimKit import Combine public protocol StringIdentifiable { var id: String { get } } public protocol ArtMetadata { var title: String { get } var artist: String { get } } public protocol RemoteImage{ var imageURL: URL { get } } public protocol Art: StringIdentifiable, ArtMetadata, RemoteImage {}
// // Created by Kerim Deveci on 10.04.2020. // Copyright (c) 2020 Kerim Deveci. All rights reserved. // import UIKit import RxCocoa import RxSwift class TrendingRepoCell: UITableViewCell { @IBOutlet weak var repoName: UILabel! @IBOutlet weak var repoDescription: UILabel! @IBOutlet weak var repoImage: UIImageView! @IBOutlet weak var downloadCount: UILabel! @IBOutlet weak var languageLabel: UILabel! @IBOutlet weak var contributionCount: UILabel! @IBOutlet weak var backView: UIView! @IBOutlet weak var viewReadmeButton: UIButton! var repoUrl: String? let disposeBag = DisposeBag() override func awakeFromNib() { super.awakeFromNib() } override func layoutSubviews() { super.layoutSubviews() backView.layer.cornerRadius = 15 backView.layer.shadowColor = UIColor(red:0.188, green:0.188, blue:0.188, alpha: 1.000).cgColor backView.layer.shadowOpacity = 0.5 backView.layer.shadowOffset = CGSize(width: 0, height: 0) backView.layer.shadowRadius = 6 } func configure(with repo: Repo){ viewReadmeButton.rx.tap.subscribe(onNext: { [weak self] in guard let self = self else { return } self.window?.rootViewController?.presentSafariWebViewFor(url: self.repoUrl!) }).disposed(by: disposeBag) repoImage.image = repo.image repoDescription.text = repo.description repoName.text = repo.name downloadCount.text = String(repo.numberOfForks) contributionCount.text = String(repo.numberOfContributors) languageLabel.text = repo.language repoUrl = repo.repoUrl } }
// // PromoCell.swift // Promos // // Created by Imad Ajallal on 12/23/16. // Copyright © 2016 Imad Ajallal. All rights reserved. // import UIKit class PromoCell: UITableViewCell { @IBOutlet weak var promocellImageView: UIImageView! @IBOutlet weak var promoOperateurCellLabel: UILabel! @IBOutlet weak var promoValableCellLabel: UILabel! @IBOutlet weak var promoTypeCellLabel: UILabel! @IBOutlet weak var promoPriceCellLabel: UILabel! }
import XCTest @testable import Buildkite_Anka_Demo class Buildkite_Anka_DemoTests: XCTestCase { func testExample() { XCTAssert(1 == 1) } func testPerformanceExample() { self.measure { 1 == 1 } } }
// // MenuItemCollectionViewCell.swift // Pay-hub // // Created by RSTI E-Services on 18/04/17. // Copyright © 2017 RSTI E-Services. All rights reserved. // import UIKit import GMStepper class MenuItemCollectionViewCell: UICollectionViewCell { @IBOutlet weak var itemImageView: UIImageView! @IBOutlet weak var itemtName: UILabel! @IBOutlet weak var itemdescripion: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var itemGMStepper: GMStepper! let gradientLayer: CAGradientLayer = CAGradientLayer() required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func awakeFromNib() { self.contentView.autoresizingMask.insert(.flexibleHeight) self.contentView.autoresizingMask.insert(.flexibleWidth) let topColor = UIColor.clear let bottomColor = UIColor.black let gradientColors: [CGColor] = [topColor.cgColor, bottomColor.cgColor] let gradientLoactions: [Float] = [0.6, 0.9] gradientLayer.colors = gradientColors gradientLayer.locations = gradientLoactions as [NSNumber] gradientLayer.frame = self.itemImageView.bounds // gradientLayer.masksToBounds = true self.itemImageView.layer.insertSublayer(gradientLayer, at: 0) } override func layoutSubviews() { gradientLayer.frame = self.itemImageView.bounds } override func prepareForReuse() { super.prepareForReuse() // self.itemtName.text = "" // self.itemImageView.image = UIImage.init(named: "") // self.itemGMStepper.value = 0 // self.itemdescripion.text = "" } }
// // UICollectionViewLayout.swift // CMoney // // Created by 黃仕杰 on 2021/7/24. // import Foundation import UIKit class UICollectionViewLayout: UICollectionViewFlowLayout { let numberOfColumns: CGFloat = 4 let padding: CGFloat = 1 override init() { super.init() self.minimumInteritemSpacing = self.padding self.minimumLineSpacing = self.padding let itemSizeW = (UIScreen.main.bounds.size.width - ((self.numberOfColumns - 1) * self.padding)) / numberOfColumns self.itemSize = CGSize(width: itemSizeW, height: itemSizeW) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // NetworkManager.swift // ExchangeRates // // Created by Ekaterina on 4.07.21. // import Foundation import Alamofire class NetworkManager { var rates: [Rate] = [] let baseUrl = URL(string: "https://alpha.as50464.net:29870/moby-pre-44/core?r=BEYkZbmV&d=563B4852-6D4B-49D6-A86E-B273DD520FD2&t=ExchangeRates&v=44") let headers: HTTPHeaders = ["User-Agent":"Test GeekBrains iOS 3.0.0.182 (iPhone 11; iOS 14.4.1; Scale/2.00; Private)", "Content-Type":"application/json", "Accept":"application/json"] let parameters: [String: Any] = [ "uid" : "563B4852-6D4B-49D6-A86E-B273DD520FD2", "type" : "ExchangeRates", "rid" : "BEYkZbmV", ] func getRates(completion: @escaping (([Rate]) -> Void)) { if let url = baseUrl { AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseData { response in switch response.result { case.success(let data): do { let rates = try JSONDecoder().decode(ExchangeModel.self, from: data).rates completion(rates!) } catch let error as NSError { debugPrint(error.localizedDescription) } case .failure(let error): debugPrint(error.localizedDescription) } } } } }
// // ThemeManager.swift // Brizeo // // Created by Roman Bayik on 1/28/17. // Copyright © 2017 Kogi Mobile. All rights reserved. // import UIKit import ChameleonFramework import SVProgressHUD class ThemeManager: NSObject { // MARK: - Types struct Constants { static let navigationBarColor = UIColor.white static let navigationBarButtonItemColor = HexColor("1f4ba5")! static let navigationBarButtonItemFontSize: CGFloat = 17.0 static let navigationBarButtonItemFontName = "SourceSansPro-Semibold" } // MARK: - Class methods class func applyGlobalTheme() { // navigation bar UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName : Constants.navigationBarButtonItemColor, NSFontAttributeName: UIFont(name: Constants.navigationBarButtonItemFontName, size: Constants.navigationBarButtonItemFontSize)!] UINavigationBar.appearance().barTintColor = Constants.navigationBarColor // navigation bar item UIBarButtonItem.appearance().setTitleTextAttributes([ NSForegroundColorAttributeName : Constants.navigationBarButtonItemColor, NSFontAttributeName: UIFont(name: Constants.navigationBarButtonItemFontName, size: Constants.navigationBarButtonItemFontSize)!], for: .normal) // tabbar UITabBar.appearance().backgroundColor = UIColor.white UITabBar.appearance().barTintColor = .clear UITabBar.appearance().backgroundImage = UIImage() UITabBar.appearance().shadowImage = UIImage() // loading HUD SVProgressHUD.setDefaultMaskType(.gradient) } class func placeLogo(on navigationItem: UINavigationItem) { let imageView = UIImageView(image: #imageLiteral(resourceName: "ic_nav_logo")) imageView.contentMode = .scaleAspectFit let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 44)) imageView.frame = titleView.bounds titleView.addSubview(imageView) navigationItem.titleView = titleView } class func tabbarHeight() -> CGFloat { return 49.0 /* standart height for tab bar */ } }
// // MyLine.swift // CoordinateCalculator // // Created by BLU on 2019. 5. 14.. // Copyright © 2019년 Codesquad Inc. All rights reserved. // import Foundation struct MyLine: Shape, Measurable, Equatable { private let pointA: MyPoint private let pointB: MyPoint private(set) var points: [MyPoint] private(set) var area: Double init?(pointA: MyPoint, pointB: MyPoint) { guard pointA != pointB else { return nil } self.pointA = pointA self.pointB = pointB self.points = [pointA, pointB] self.area = sqrt(pow(Double(pointA.x - pointB.x), 2) + pow(Double(pointA.y - pointB.y), 2)) } func areaDescription() -> String { return "두 점 사이 거리는" } public static func ==(lhs: MyLine, rhs: MyLine) -> Bool { return (lhs.pointA == rhs.pointA && lhs.pointB == rhs.pointB) || (lhs.pointA == rhs.pointB && lhs.pointB == rhs.pointA) } }
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: Jub_Bitcoin.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } enum JUB_Proto_Bitcoin_ENUM_COIN_TYPE_BTC: SwiftProtobuf.Enum { typealias RawValue = Int case coinbtc // = 0 case coinbch // = 1 case coinltc // = 2 case coinusdt // = 3 case coindash // = 4 case coinqtum // = 5 case UNRECOGNIZED(Int) init() { self = .coinbtc } init?(rawValue: Int) { switch rawValue { case 0: self = .coinbtc case 1: self = .coinbch case 2: self = .coinltc case 3: self = .coinusdt case 4: self = .coindash case 5: self = .coinqtum default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .coinbtc: return 0 case .coinbch: return 1 case .coinltc: return 2 case .coinusdt: return 3 case .coindash: return 4 case .coinqtum: return 5 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Bitcoin_ENUM_COIN_TYPE_BTC: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Bitcoin_ENUM_COIN_TYPE_BTC] = [ .coinbtc, .coinbch, .coinltc, .coinusdt, .coindash, .coinqtum, ] } #endif // swift(>=4.2) enum JUB_Proto_Bitcoin_ENUM_TRAN_STYPE_BTC: SwiftProtobuf.Enum { typealias RawValue = Int case p2Pkh // = 0 case p2ShP2Wpkh // = 1 case p2ShMultisig // = 2 case p2Pk // = 3 case UNRECOGNIZED(Int) init() { self = .p2Pkh } init?(rawValue: Int) { switch rawValue { case 0: self = .p2Pkh case 1: self = .p2ShP2Wpkh case 2: self = .p2ShMultisig case 3: self = .p2Pk default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .p2Pkh: return 0 case .p2ShP2Wpkh: return 1 case .p2ShMultisig: return 2 case .p2Pk: return 3 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Bitcoin_ENUM_TRAN_STYPE_BTC: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Bitcoin_ENUM_TRAN_STYPE_BTC] = [ .p2Pkh, .p2ShP2Wpkh, .p2ShMultisig, .p2Pk, ] } #endif // swift(>=4.2) enum JUB_Proto_Bitcoin_BTC_UNIT_TYPE: SwiftProtobuf.Enum { typealias RawValue = Int case btc // = 0 case cBtc // = 1 case mBtc // = 2 case uBtc // = 3 case satoshi // = 4 case UNRECOGNIZED(Int) init() { self = .btc } init?(rawValue: Int) { switch rawValue { case 0: self = .btc case 1: self = .cBtc case 2: self = .mBtc case 3: self = .uBtc case 4: self = .satoshi default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .btc: return 0 case .cBtc: return 1 case .mBtc: return 2 case .uBtc: return 3 case .satoshi: return 4 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Bitcoin_BTC_UNIT_TYPE: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Bitcoin_BTC_UNIT_TYPE] = [ .btc, .cBtc, .mBtc, .uBtc, .satoshi, ] } #endif // swift(>=4.2) enum JUB_Proto_Bitcoin_ENUM_SCRIPT_TYPE_BTC: SwiftProtobuf.Enum { typealias RawValue = Int case scP2Pkh // = 0 case scReturn0 // = 1 case scQrc20 // = 3 case UNRECOGNIZED(Int) init() { self = .scP2Pkh } init?(rawValue: Int) { switch rawValue { case 0: self = .scP2Pkh case 1: self = .scReturn0 case 3: self = .scQrc20 default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .scP2Pkh: return 0 case .scReturn0: return 1 case .scQrc20: return 3 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Bitcoin_ENUM_SCRIPT_TYPE_BTC: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Bitcoin_ENUM_SCRIPT_TYPE_BTC] = [ .scP2Pkh, .scReturn0, .scQrc20, ] } #endif // swift(>=4.2) struct JUB_Proto_Bitcoin_ContextCfgBTC { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var mainPath: String = String() var coinType: JUB_Proto_Bitcoin_ENUM_COIN_TYPE_BTC = .coinbtc var transType: JUB_Proto_Bitcoin_ENUM_TRAN_STYPE_BTC = .p2Pkh var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct JUB_Proto_Bitcoin_InputBTC { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var preHash: String { get {return _storage._preHash} set {_uniqueStorage()._preHash = newValue} } var preIndex: UInt32 { get {return _storage._preIndex} set {_uniqueStorage()._preIndex = newValue} } var amount: UInt64 { get {return _storage._amount} set {_uniqueStorage()._amount = newValue} } var path: JUB_Proto_Common_Bip44Path { get {return _storage._path ?? JUB_Proto_Common_Bip44Path()} set {_uniqueStorage()._path = newValue} } /// Returns true if `path` has been explicitly set. var hasPath: Bool {return _storage._path != nil} /// Clears the value of `path`. Subsequent reads from it will return its default value. mutating func clearPath() {_uniqueStorage()._path = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _storage = _StorageClass.defaultInstance } struct JUB_Proto_Bitcoin_StandardOutput { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var address: String { get {return _storage._address} set {_uniqueStorage()._address = newValue} } var amount: UInt64 { get {return _storage._amount} set {_uniqueStorage()._amount = newValue} } var changeAddress: Bool { get {return _storage._changeAddress} set {_uniqueStorage()._changeAddress = newValue} } var path: JUB_Proto_Common_Bip44Path { get {return _storage._path ?? JUB_Proto_Common_Bip44Path()} set {_uniqueStorage()._path = newValue} } /// Returns true if `path` has been explicitly set. var hasPath: Bool {return _storage._path != nil} /// Clears the value of `path`. Subsequent reads from it will return its default value. mutating func clearPath() {_uniqueStorage()._path = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _storage = _StorageClass.defaultInstance } struct JUB_Proto_Bitcoin_Return0Output { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var amount: UInt64 = 0 var data: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct JUB_Proto_Bitcoin_QRC20Output { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var data: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct JUB_Proto_Bitcoin_OutputBTC { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var type: JUB_Proto_Bitcoin_ENUM_SCRIPT_TYPE_BTC { get {return _storage._type} set {_uniqueStorage()._type = newValue} } var output: OneOf_Output? { get {return _storage._output} set {_uniqueStorage()._output = newValue} } var stdOutput: JUB_Proto_Bitcoin_StandardOutput { get { if case .stdOutput(let v)? = _storage._output {return v} return JUB_Proto_Bitcoin_StandardOutput() } set {_uniqueStorage()._output = .stdOutput(newValue)} } var return0Output: JUB_Proto_Bitcoin_Return0Output { get { if case .return0Output(let v)? = _storage._output {return v} return JUB_Proto_Bitcoin_Return0Output() } set {_uniqueStorage()._output = .return0Output(newValue)} } var qrc20Output: JUB_Proto_Bitcoin_QRC20Output { get { if case .qrc20Output(let v)? = _storage._output {return v} return JUB_Proto_Bitcoin_QRC20Output() } set {_uniqueStorage()._output = .qrc20Output(newValue)} } var unknownFields = SwiftProtobuf.UnknownStorage() enum OneOf_Output: Equatable { case stdOutput(JUB_Proto_Bitcoin_StandardOutput) case return0Output(JUB_Proto_Bitcoin_Return0Output) case qrc20Output(JUB_Proto_Bitcoin_QRC20Output) #if !swift(>=4.1) static func ==(lhs: JUB_Proto_Bitcoin_OutputBTC.OneOf_Output, rhs: JUB_Proto_Bitcoin_OutputBTC.OneOf_Output) -> Bool { switch (lhs, rhs) { case (.stdOutput(let l), .stdOutput(let r)): return l == r case (.return0Output(let l), .return0Output(let r)): return l == r case (.qrc20Output(let l), .qrc20Output(let r)): return l == r default: return false } } #endif } init() {} fileprivate var _storage = _StorageClass.defaultInstance } struct JUB_Proto_Bitcoin_TransactionBTC { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var version: UInt32 = 0 var locktime: UInt32 = 0 var inputs: [JUB_Proto_Bitcoin_InputBTC] = [] var outputs: [JUB_Proto_Bitcoin_OutputBTC] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "JUB.Proto.Bitcoin" extension JUB_Proto_Bitcoin_ENUM_COIN_TYPE_BTC: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "COINBTC"), 1: .same(proto: "COINBCH"), 2: .same(proto: "COINLTC"), 3: .same(proto: "COINUSDT"), 4: .same(proto: "COINDASH"), 5: .same(proto: "COINQTUM"), ] } extension JUB_Proto_Bitcoin_ENUM_TRAN_STYPE_BTC: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "P2PKH"), 1: .same(proto: "P2SH_P2WPKH"), 2: .same(proto: "P2SH_MULTISIG"), 3: .same(proto: "P2PK"), ] } extension JUB_Proto_Bitcoin_BTC_UNIT_TYPE: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "BTC"), 1: .same(proto: "cBTC"), 2: .same(proto: "mBTC"), 3: .same(proto: "uBTC"), 4: .same(proto: "Satoshi"), ] } extension JUB_Proto_Bitcoin_ENUM_SCRIPT_TYPE_BTC: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "SC_P2PKH"), 1: .same(proto: "SC_RETURN0"), 3: .same(proto: "SC_QRC20"), ] } extension JUB_Proto_Bitcoin_ContextCfgBTC: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ContextCfgBTC" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "main_path"), 2: .standard(proto: "coin_type"), 3: .standard(proto: "trans_type"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.mainPath) case 2: try decoder.decodeSingularEnumField(value: &self.coinType) case 3: try decoder.decodeSingularEnumField(value: &self.transType) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.mainPath.isEmpty { try visitor.visitSingularStringField(value: self.mainPath, fieldNumber: 1) } if self.coinType != .coinbtc { try visitor.visitSingularEnumField(value: self.coinType, fieldNumber: 2) } if self.transType != .p2Pkh { try visitor.visitSingularEnumField(value: self.transType, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_ContextCfgBTC, rhs: JUB_Proto_Bitcoin_ContextCfgBTC) -> Bool { if lhs.mainPath != rhs.mainPath {return false} if lhs.coinType != rhs.coinType {return false} if lhs.transType != rhs.transType {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Bitcoin_InputBTC: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".InputBTC" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "pre_hash"), 2: .standard(proto: "pre_index"), 3: .same(proto: "amount"), 4: .same(proto: "path"), ] fileprivate class _StorageClass { var _preHash: String = String() var _preIndex: UInt32 = 0 var _amount: UInt64 = 0 var _path: JUB_Proto_Common_Bip44Path? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _preHash = source._preHash _preIndex = source._preIndex _amount = source._amount _path = source._path } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &_storage._preHash) case 2: try decoder.decodeSingularUInt32Field(value: &_storage._preIndex) case 3: try decoder.decodeSingularUInt64Field(value: &_storage._amount) case 4: try decoder.decodeSingularMessageField(value: &_storage._path) default: break } } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if !_storage._preHash.isEmpty { try visitor.visitSingularStringField(value: _storage._preHash, fieldNumber: 1) } if _storage._preIndex != 0 { try visitor.visitSingularUInt32Field(value: _storage._preIndex, fieldNumber: 2) } if _storage._amount != 0 { try visitor.visitSingularUInt64Field(value: _storage._amount, fieldNumber: 3) } if let v = _storage._path { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_InputBTC, rhs: JUB_Proto_Bitcoin_InputBTC) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._preHash != rhs_storage._preHash {return false} if _storage._preIndex != rhs_storage._preIndex {return false} if _storage._amount != rhs_storage._amount {return false} if _storage._path != rhs_storage._path {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Bitcoin_StandardOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".StandardOutput" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "address"), 2: .same(proto: "amount"), 3: .standard(proto: "change_address"), 4: .same(proto: "path"), ] fileprivate class _StorageClass { var _address: String = String() var _amount: UInt64 = 0 var _changeAddress: Bool = false var _path: JUB_Proto_Common_Bip44Path? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _address = source._address _amount = source._amount _changeAddress = source._changeAddress _path = source._path } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &_storage._address) case 2: try decoder.decodeSingularUInt64Field(value: &_storage._amount) case 3: try decoder.decodeSingularBoolField(value: &_storage._changeAddress) case 4: try decoder.decodeSingularMessageField(value: &_storage._path) default: break } } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if !_storage._address.isEmpty { try visitor.visitSingularStringField(value: _storage._address, fieldNumber: 1) } if _storage._amount != 0 { try visitor.visitSingularUInt64Field(value: _storage._amount, fieldNumber: 2) } if _storage._changeAddress != false { try visitor.visitSingularBoolField(value: _storage._changeAddress, fieldNumber: 3) } if let v = _storage._path { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_StandardOutput, rhs: JUB_Proto_Bitcoin_StandardOutput) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._address != rhs_storage._address {return false} if _storage._amount != rhs_storage._amount {return false} if _storage._changeAddress != rhs_storage._changeAddress {return false} if _storage._path != rhs_storage._path {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Bitcoin_Return0Output: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Return0Output" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "amount"), 2: .same(proto: "data"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt64Field(value: &self.amount) case 2: try decoder.decodeSingularStringField(value: &self.data) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.amount != 0 { try visitor.visitSingularUInt64Field(value: self.amount, fieldNumber: 1) } if !self.data.isEmpty { try visitor.visitSingularStringField(value: self.data, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_Return0Output, rhs: JUB_Proto_Bitcoin_Return0Output) -> Bool { if lhs.amount != rhs.amount {return false} if lhs.data != rhs.data {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Bitcoin_QRC20Output: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".QRC20Output" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "data"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.data) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.data.isEmpty { try visitor.visitSingularStringField(value: self.data, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_QRC20Output, rhs: JUB_Proto_Bitcoin_QRC20Output) -> Bool { if lhs.data != rhs.data {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Bitcoin_OutputBTC: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".OutputBTC" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "type"), 2: .standard(proto: "std_output"), 3: .standard(proto: "return0_output"), 4: .standard(proto: "qrc20_output"), ] fileprivate class _StorageClass { var _type: JUB_Proto_Bitcoin_ENUM_SCRIPT_TYPE_BTC = .scP2Pkh var _output: JUB_Proto_Bitcoin_OutputBTC.OneOf_Output? static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _type = source._type _output = source._output } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularEnumField(value: &_storage._type) case 2: var v: JUB_Proto_Bitcoin_StandardOutput? if let current = _storage._output { try decoder.handleConflictingOneOf() if case .stdOutput(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {_storage._output = .stdOutput(v)} case 3: var v: JUB_Proto_Bitcoin_Return0Output? if let current = _storage._output { try decoder.handleConflictingOneOf() if case .return0Output(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {_storage._output = .return0Output(v)} case 4: var v: JUB_Proto_Bitcoin_QRC20Output? if let current = _storage._output { try decoder.handleConflictingOneOf() if case .qrc20Output(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {_storage._output = .qrc20Output(v)} default: break } } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if _storage._type != .scP2Pkh { try visitor.visitSingularEnumField(value: _storage._type, fieldNumber: 1) } switch _storage._output { case .stdOutput(let v)?: try visitor.visitSingularMessageField(value: v, fieldNumber: 2) case .return0Output(let v)?: try visitor.visitSingularMessageField(value: v, fieldNumber: 3) case .qrc20Output(let v)?: try visitor.visitSingularMessageField(value: v, fieldNumber: 4) case nil: break } } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_OutputBTC, rhs: JUB_Proto_Bitcoin_OutputBTC) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._type != rhs_storage._type {return false} if _storage._output != rhs_storage._output {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Bitcoin_TransactionBTC: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".TransactionBTC" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "version"), 2: .same(proto: "locktime"), 3: .same(proto: "inputs"), 4: .same(proto: "outputs"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt32Field(value: &self.version) case 2: try decoder.decodeSingularUInt32Field(value: &self.locktime) case 3: try decoder.decodeRepeatedMessageField(value: &self.inputs) case 4: try decoder.decodeRepeatedMessageField(value: &self.outputs) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.version != 0 { try visitor.visitSingularUInt32Field(value: self.version, fieldNumber: 1) } if self.locktime != 0 { try visitor.visitSingularUInt32Field(value: self.locktime, fieldNumber: 2) } if !self.inputs.isEmpty { try visitor.visitRepeatedMessageField(value: self.inputs, fieldNumber: 3) } if !self.outputs.isEmpty { try visitor.visitRepeatedMessageField(value: self.outputs, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Bitcoin_TransactionBTC, rhs: JUB_Proto_Bitcoin_TransactionBTC) -> Bool { if lhs.version != rhs.version {return false} if lhs.locktime != rhs.locktime {return false} if lhs.inputs != rhs.inputs {return false} if lhs.outputs != rhs.outputs {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
// // DailyWeatherView.swift // ForecastApp // // Created by Julio Collado on 3/7/21. // import SwiftUI struct DailyWeatherView: View { @ObservedObject var cityViewModel: CityViewModel var body: some View { ForEach(cityViewModel.weather.daily) { weather in LazyVStack { dailyCell(weather: weather) } } } private func dailyCell(weather: DailyWeather) -> some View { HStack(spacing: 10) { Text(cityViewModel.getDayFor(timestamp: weather.date).uppercased()) .bold() .frame(width: 50) .padding(.leading, 20) Spacer() Text("max: \(cityViewModel.getTemperatureFor(temp: weather.temperature.max)) | min: \(cityViewModel.getTemperatureFor(temp: weather.temperature.min)) ℃") .font(.body) Spacer() LottieAnimationUtil.getWeatherIconFor(icon: weather.weather.first?.icon ?? "") .renderingMode(.original) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 30, height: 30) .padding(.horizontal, 20) } .foregroundColor(.white) .padding(.vertical, 15) .clearDaySkyBackgroundStyle() .padding(.horizontal, 10) } } struct DailyWeatherView_Previews: PreviewProvider { static var previews: some View { DailyWeatherView(cityViewModel: CityViewModel()) } }
// // OverlayView.swift // PassportOCR // // Created by Михаил on 03.09.16. // Copyright © 2016 empatika. All rights reserved. // import UIKit public class CameraOverlayView: UIView { @IBOutlet weak var codeBorder: UIView! var scanner: DocumentScanner! @IBAction func cancelButtonClicked(sender: UIButton) { scanner.viewController.dismissViewControllerAnimated(true, completion: nil) } @IBAction func scanButtonClicked(sender: UIButton) { scanner.imagePicker.takePicture() } override init(frame: CGRect) { super.init(frame: frame) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.opaque = false } }
// // ViewController.swift // LayoutPractice1 // // Created by MM on 5/15/20. // Copyright © 2020 MM. All rights reserved. // import UIKit class ViewController: UIViewController { let itemsForTopRight = ["First", "Second", "Third"] let vwTop = UIView() let lblTopLeft = UILabel() let dropDown = UIButton() let tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = self tableView.dataSource = self tableView.register(BigTableViewCell.self, forCellReuseIdentifier: "BigTableViewCell") setupUI() } func setupUI() { vwTop.backgroundColor = UIColor(red: 60.0/255, green: 71.0/255, blue: 82.0/255, alpha: 1) view.addSubview(vwTop) vwTop.translatesAutoresizingMaskIntoConstraints = false vwTop.topAnchor.constraint(equalTo: view.topAnchor).isActive = true vwTop.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true vwTop.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true vwTop.heightAnchor.constraint(equalToConstant: 100).isActive = true vwTop.addSubview(lblTopLeft) vwTop.addSubview(dropDown) lblTopLeft.text = "Top Left" lblTopLeft.font = UIFont(name: "Helvetica-Bold", size: 16) lblTopLeft.textColor = .white lblTopLeft.translatesAutoresizingMaskIntoConstraints = false //lblTopLeft.topAnchor.constraint(equalTo: vwTop.topAnchor, constant: 10).isActive = true lblTopLeft.leftAnchor.constraint(equalTo: vwTop.leftAnchor, constant: 12).isActive = true lblTopLeft.bottomAnchor.constraint(equalTo: vwTop.bottomAnchor, constant: -12).isActive = true dropDown.setTitle("\(itemsForTopRight[0]) ", for: .normal) dropDown.setImage(UIImage(systemName: "chevron.down"), for: .normal) dropDown.semanticContentAttribute = .forceRightToLeft dropDown.tintColor = .white dropDown.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 16) dropDown.addTarget(self, action: #selector(topRightDropDownClicked), for: .touchUpInside) dropDown.translatesAutoresizingMaskIntoConstraints = false dropDown.rightAnchor.constraint(equalTo: vwTop.rightAnchor, constant: -12).isActive = true //dropDown.leftAnchor.constraint(equalTo: vwTop.leftAnchor, constant: 12).isActive = true dropDown.bottomAnchor.constraint(equalTo: vwTop.bottomAnchor, constant: -8).isActive = true view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.separatorStyle = .none tableView.backgroundColor = UIColor(red: 245/255, green: 248/255, blue: 251/255, alpha: 1) tableView.topAnchor.constraint(equalTo: vwTop.bottomAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true } // @objc func topRightDropDownClicked() { // let popupVC = PopupViewController() // popupVC.isRight = true // popupVC.data = itemsForTopRight // popupVC.delegate = self // popupVC.modalPresentationStyle = .popover // popupVC.view.backgroundColor = .clear // popupVC.preferredContentSize = CGSize(width: 200, height: 300) // self.present(popupVC, animated: true, completion: nil) // // // // //popupVC.configView(rect: CGRect(x: 0, y: 0, width: 200, height: 300)) // // let controller = popupVC.popoverPresentationController // controller?.delegate = self // controller?.sourceView = self.dropDown // controller?.permittedArrowDirections = UIPopoverArrowDirection.left // controller?.sourceRect = self.dropDown.bounds //// //// //// self.present(popupVC, animated: true, completion: nil) // } @objc func topRightDropDownClicked() { let popupTestVC = PopupTestVC(nibName: "PopupTestVC", bundle: nil); popupTestVC.modalPresentationStyle = .popover if let popover = popupTestVC.popoverPresentationController { popover.sourceView = self.dropDown popover.sourceRect = self.dropDown.bounds popover.delegate = self } popupTestVC.preferredContentSize = CGSize(width: 242, height: 152) self.present(popupTestVC, animated: true) } } extension ViewController: PopupViewControllerDelegate { func sendDataBack(choice: String) { dropDown.setTitle("\(choice) ", for: .normal) } } extension ViewController: UIPopoverPresentationControllerDelegate, UIPopoverControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { // popoverPresentationController.sourceView = self.view // popoverPresentationController.sourceRect = CGRect(x: 30, y: 30, width: 200, height: 230) // popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0) } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BigTableViewCell", for: indexPath) as! BigTableViewCell cell.selectionStyle = .none if indexPath.row == 0 { cell.configWithImage(img: UIImage(named: "img")!) } return cell } }
/* * Copyright (c) 2012-2020 MIRACL UK Ltd. * * This file is part of MIRACL Core * (see https://github.com/miracl/core). * * 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. */ // // pair4.swift // // Created by Michael Scott on 07/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // /* CORE BLS Curve Pairing functions */ public struct PAIR4 { // Point doubling for pairings static private func dbl(_ A: inout ECP4,_ AA: inout FP4,_ BB: inout FP4,_ CC: inout FP4) { CC.copy(A.getx()) //X var YY=FP4(A.gety()) //Y BB.copy(A.getz()) //Z AA.copy(YY) //Y AA.mul(BB) //YZ CC.sqr() //X^2 YY.sqr() //Y^2 BB.sqr() //Z^2 AA.add(AA) AA.neg(); AA.norm() //-2AA AA.times_i() let sb=3*ROM.CURVE_B_I BB.imul(sb) CC.imul(3) if CONFIG_CURVE.SEXTIC_TWIST==CONFIG_CURVE.D_TYPE { YY.times_i() CC.times_i() } if CONFIG_CURVE.SEXTIC_TWIST==CONFIG_CURVE.M_TYPE { BB.times_i() } BB.sub(YY) BB.norm() A.dbl() } // Point addition for pairings static private func add(_ A: inout ECP4,_ B:ECP4,_ AA: inout FP4,_ BB: inout FP4,_ CC: inout FP4) { AA.copy(A.getx()) // X1 CC.copy(A.gety()) // Y1 var T1=FP4(A.getz()) // Z1 BB.copy(A.getz()) // Z1 T1.mul(B.gety()) // T1=Z1.Y2 BB.mul(B.getx()) // T2=Z1.X2 AA.sub(BB); AA.norm() // X1=X1-Z1.X2 CC.sub(T1); CC.norm() // Y1=Y1-Z1.Y2 T1.copy(AA) // T1=X1-Z1.X2 if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.M_TYPE { AA.times_i() AA.norm() } T1.mul(B.gety()) // T1=(X1-Z1.X2).Y2 BB.copy(CC) // T2=Y1-Z1.Y2 BB.mul(B.getx()) // T2=(Y1-Z1.Y2).X2 BB.sub(T1); BB.norm() // T2=(Y1-Z1.Y2).X2 - (X1-Z1.X2).Y2 CC.neg(); CC.norm() // Y1=-(Y1-Z1.Y2).Xs A.add(B) } // Line functions static private func linedbl(_ A: inout ECP4,_ Qx:FP,_ Qy:FP) -> FP24 { var a:FP8 var b:FP8 var c:FP8 var AA=FP4() //X var BB=FP4() //Y var CC=FP4() //Z dbl(&A,&AA,&BB,&CC) CC.qmul(Qx) AA.qmul(Qy) a=FP8(AA,BB) // -2YZ.Ys | 3b.Z^2-Y^2 | 3X^2.Xs if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.D_TYPE { b=FP8(CC) // L(0,1) | L(0,0) | L(1,0) c=FP8() } else { b=FP8() c=FP8(CC); c.times_i() } var res=FP24(a,b,c) res.settype(FP24.SPARSER) return res } static private func lineadd(_ A: inout ECP4,_ B: ECP4,_ Qx:FP,_ Qy:FP) -> FP24 { var a:FP8 var b:FP8 var c:FP8 var AA=FP4() //X var BB=FP4() //Y var CC=FP4() //Z add(&A,B,&AA,&BB,&CC) CC.qmul(Qx) AA.qmul(Qy) a=FP8(AA,BB) // -2YZ.Ys | 3b.Z^2-Y^2 | 3X^2.Xs if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.D_TYPE { b=FP8(CC) // L(0,1) | L(0,0) | L(1,0) c=FP8() } else { b=FP8(0) c=FP8(CC); c.times_i() } var res=FP24(a,b,c) res.settype(FP24.SPARSER) return res } static private func lbits(_ n3:inout BIG,_ n:inout BIG) -> Int { n.copy(BIG(ROM.CURVE_Bnx)) n3.copy(n) n3.pmul(3) n3.norm() return n3.nbits() } static public func initmp() -> [FP24] { var r=[FP24](); for _ in (0...CONFIG_CURVE.ATE_BITS-1).reversed() { r.append(FP24(1)) } return r } /* basic Miller loop */ static public func miller(_ r: inout [FP24]) -> FP24 { var res=FP24(1) for i in (1...CONFIG_CURVE.ATE_BITS-1).reversed() { res.sqr() res.ssmul(r[i]) r[i].zero() } if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { res.conj(); } res.ssmul(r[0]) r[0].zero() return res } static private func pack(_ AA: FP4,_ BB: FP4,_ CC: FP4) -> FP8 { var i=FP4(CC) let pNIL:FP?=nil i.inverse(pNIL) var a=FP4(AA) var b=FP4(BB) a.mul(i) b.mul(i) return FP8(a,b) } static private func unpack(_ T: FP8,_ Qx: FP,_ Qy: FP) -> FP24 { var b:FP8 var c:FP8 let W=FP4(Qx) var AA=T.geta() let BB=T.getb() AA.qmul(Qy) let a=FP8(AA,BB) if CONFIG_CURVE.SEXTIC_TWIST == CONFIG_CURVE.D_TYPE { b=FP8(W) // L(0,1) | L(0,0) | L(1,0) c=FP8() } else { b=FP8() c=FP8(W); c.times_i() } var v=FP24(a,b,c) v.settype(FP24.SPARSEST) return v } static public func precomp(_ GV: ECP4) -> [FP8] { var n = BIG() var n3 = BIG() var AA=FP4() var BB=FP4() var CC=FP4() let nb=lbits(&n3,&n) var P=ECP4(); P.copy(GV); var A=ECP4(); A.copy(P) var NP=ECP4(); NP.copy(P); NP.neg() var T=[FP8]() for i in (1...nb-2).reversed() { dbl(&A,&AA,&BB,&CC) T.append(pack(AA,BB,CC)) let bt=n3.bit(UInt(i))-n.bit(UInt(i)) if bt == 1 { add(&A,P,&AA,&BB,&CC) T.append(pack(AA,BB,CC)) } if bt == -1 { add(&A,NP,&AA,&BB,&CC) T.append(pack(AA,BB,CC)) } } return T } static public func another_pc(_ r: inout [FP24],_ T: [FP8],_ QV: ECP) { var n = BIG() var n3 = BIG() if QV.is_infinity() { return } let nb=lbits(&n3,&n) var Q=ECP(); Q.copy(QV); Q.affine() let Qx=FP(Q.getx()) let Qy=FP(Q.gety()) var j=0 for i in (1...nb-2).reversed() { var lv=unpack(T[j],Qx,Qy); j+=1 let bt=n3.bit(UInt(i))-n.bit(UInt(i)) if bt == 1 { let lv2=unpack(T[j],Qx,Qy); j+=1 lv.smul(lv2) } if bt == -1 { let lv2=unpack(T[j],Qx,Qy); j+=1 lv.smul(lv2) } r[i].ssmul(lv) } } /* Accumulate another set of line functions for n-pairing */ static public func another(_ r: inout [FP24],_ P1: ECP4,_ Q1: ECP) { var n = BIG(); var n3 = BIG(); if Q1.is_infinity() { return } // P is needed in affine form for line function, Q for (Qx,Qy) extraction var P=ECP4(); P.copy(P1); P.affine() var Q=ECP(); Q.copy(Q1); Q.affine() let Qx=FP(Q.getx()) let Qy=FP(Q.gety()) var A=ECP4() A.copy(P) var NP=ECP4() NP.copy(P) NP.neg() let nb=lbits(&n3,&n) for i in (1...nb-2).reversed() { var lv=linedbl(&A,Qx,Qy) let bt=n3.bit(UInt(i))-n.bit(UInt(i)) if bt == 1 { let lv2=lineadd(&A,P,Qx,Qy) lv.smul(lv2) } if bt == -1 { let lv2=lineadd(&A,NP,Qx,Qy) lv.smul(lv2) } r[i].ssmul(lv) } } // Optimal R-ate pairing static public func ate(_ P1:ECP4,_ Q1:ECP) -> FP24 { var n = BIG(); var n3 = BIG(); if Q1.is_infinity() { return FP24(1) } var lv:FP24 var P=ECP4(); P.copy(P1); P.affine() var Q=ECP(); Q.copy(Q1); Q.affine() let Qx=FP(Q.getx()) let Qy=FP(Q.gety()) var A=ECP4() var r=FP24(1) A.copy(P) var NP=ECP4() NP.copy(P) NP.neg() let nb=lbits(&n3,&n) for i in (1...nb-2).reversed() { r.sqr() lv=linedbl(&A,Qx,Qy) let bt=n3.bit(UInt(i))-n.bit(UInt(i)) if bt == 1 { let lv2=lineadd(&A,P,Qx,Qy) lv.smul(lv2) } if bt == -1 { let lv2=lineadd(&A,NP,Qx,Qy) lv.smul(lv2) } r.ssmul(lv) } if CONFIG_CURVE.SIGN_OF_X == CONFIG_CURVE.NEGATIVEX { r.conj() } return r } // Optimal R-ate double pairing e(P,Q).e(R,S) static public func ate2(_ P1:ECP4,_ Q1:ECP,_ R1:ECP4,_ S1:ECP) -> FP24 { var n = BIG(); var n3 = BIG(); var lv:FP24 if Q1.is_infinity() { return PAIR4.ate(R1,S1); } if S1.is_infinity() { return PAIR4.ate(P1,Q1); } var P=ECP4(); P.copy(P1); P.affine() var Q=ECP(); Q.copy(Q1); Q.affine() var R=ECP4(); R.copy(R1); R.affine() var S=ECP(); S.copy(S1); S.affine() let Qx=FP(Q.getx()) let Qy=FP(Q.gety()) let Sx=FP(S.getx()) let Sy=FP(S.gety()) var A=ECP4() var B=ECP4() var r=FP24(1) A.copy(P) B.copy(R) var NP=ECP4() NP.copy(P) NP.neg() var NR=ECP4() NR.copy(R) NR.neg() let nb=lbits(&n3,&n) for i in (1...nb-2).reversed() { r.sqr() lv=linedbl(&A,Qx,Qy) var lv2=linedbl(&B,Sx,Sy) lv.smul(lv2) r.ssmul(lv) let bt=n3.bit(UInt(i))-n.bit(UInt(i)) if bt == 1 { lv=lineadd(&A,P,Qx,Qy) lv2=lineadd(&B,R,Sx,Sy) lv.smul(lv2) r.ssmul(lv) } if bt == -1 { lv=lineadd(&A,NP,Qx,Qy) lv2=lineadd(&B,NR,Sx,Sy) lv.smul(lv2) r.ssmul(lv) } } if CONFIG_CURVE.SIGN_OF_X == CONFIG_CURVE.NEGATIVEX { r.conj() } return r } // final exponentiation - keep separate for multi-pairings and to avoid thrashing stack static public func fexp(_ m:FP24) -> FP24 { let f=FP2(BIG(ROM.Fra),BIG(ROM.Frb)); let x=BIG(ROM.CURVE_Bnx) var r=FP24(m) // Easy part of final exp var lv=FP24(r) lv.inverse() r.conj() r.mul(lv) lv.copy(r) r.frob(f,4) r.mul(lv) // Hard part of final exp // See https://eprint.iacr.org/2020/875.pdf var y1=FP24(r) y1.usqr() y1.mul(r) // y1=r^3 var y0=FP24(r.pow(x)) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { y0.conj() } var t0=FP24(r); t0.conj() r.copy(y0) r.mul(t0) y0.copy(r.pow(x)) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { y0.conj() } t0.copy(r); t0.conj() r.copy(y0) r.mul(t0) // ^(x+p) y0.copy(r.pow(x)) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { y0.conj() } t0.copy(r) t0.frob(f,1) r.copy(y0) r.mul(t0) // ^(x^2+p^2) y0.copy(r.pow(x)) y0.copy(y0.pow(x)) t0.copy(r) t0.frob(f,2) r.copy(y0) r.mul(t0) // ^(x^4+p^4-1) y0.copy(r.pow(x)) y0.copy(y0.pow(x)) y0.copy(y0.pow(x)) y0.copy(y0.pow(x)) t0.copy(r) t0.frob(f,4) y0.mul(t0) t0.copy(r); t0.conj() r.copy(y0) r.mul(t0) r.mul(y1) r.reduce() /* var t7=FP24(r); t7.usqr() var t1=t7.pow(x) x.fshr(1) var t2=t1.pow(x) x.fshl(1) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { t1.conj() } var t3=FP24(t1); t3.conj() t2.mul(t3) t2.mul(r) t3.copy(t2.pow(x)) var t4=t3.pow(x) var t5=t4.pow(x) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { t3.conj(); t5.conj() } t3.frob(f,6); t4.frob(f,5) t3.mul(t4); var t6=t5.pow(x) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { t6.conj() } t5.frob(f,4) t3.mul(t5) var t0=FP24(t2); t0.conj() t6.mul(t0) t5.copy(t6) t5.frob(f,3) t3.mul(t5) t5.copy(t6.pow(x)) t6.copy(t5.pow(x)) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { t5.conj() } t0.copy(t5) t0.frob(f,2) t3.mul(t0) t0.copy(t6) t0.frob(f,1) t3.mul(t0) t5.copy(t6.pow(x)) if CONFIG_CURVE.SIGN_OF_X==CONFIG_CURVE.NEGATIVEX { t5.conj() } t2.frob(f,7) t5.mul(t7) t3.mul(t2) t3.mul(t5) r.mul(t3) r.reduce() */ return r } // GLV method static func glv(_ ee:BIG) -> [BIG] { var u=[BIG](); let q=BIG(ROM.CURVE_Order) var x=BIG(ROM.CURVE_Bnx) let x2=BIG.smul(x,x) x.copy(BIG.smul(x2,x2)) let bd=UInt(q.nbits()-x.nbits()) u.append(BIG(ee)) u[0].ctmod(x,bd) u.append(BIG(ee)) u[1].ctdiv(x,bd) u[1].rsub(q) return u } // Galbraith & Scott Method static func gs(_ ee:BIG) -> [BIG] { var u=[BIG](); let q=BIG(ROM.CURVE_Order) let x=BIG(ROM.CURVE_Bnx) let bd=UInt(q.nbits()-x.nbits()) var w=BIG(ee) for i in 0 ..< 7 { u.append(BIG(w)) u[i].ctmod(x,bd) w.ctdiv(x,bd) } u.append(BIG(w)) if CONFIG_CURVE.SIGN_OF_X == CONFIG_CURVE.NEGATIVEX { u[1].copy(BIG.modneg(u[1],q)) u[3].copy(BIG.modneg(u[3],q)) u[5].copy(BIG.modneg(u[5],q)) u[7].copy(BIG.modneg(u[7],q)) } return u } // Multiply P by e in group G1 static public func G1mul(_ P:ECP,_ e:BIG) -> ECP { var R:ECP let q=BIG(ROM.CURVE_Order) var ee=BIG(e); ee.mod(q) if (CONFIG_CURVE.USE_GLV) { R=ECP() R.copy(P) var Q=ECP() Q.copy(P); Q.affine() let cru=FP(BIG(ROM.CRu)) var t=BIG(0) var u=PAIR4.glv(ee) Q.mulx(cru); var np=u[0].nbits() t.copy(BIG.modneg(u[0],q)) var nn=t.nbits() if (nn<np) { u[0].copy(t) R.neg() } np=u[1].nbits() t.copy(BIG.modneg(u[1],q)) nn=t.nbits() if (nn<np) { u[1].copy(t) Q.neg() } u[0].norm() u[1].norm() R=R.mul2(u[0],Q,u[1]) } else { R=P.clmul(ee,q) } return R } // Multiply P by e in group G2 static public func G2mul(_ P:ECP4,_ e:BIG) -> ECP4 { var R:ECP4 let q=BIG(ROM.CURVE_Order) var ee=BIG(e); ee.mod(q) if (CONFIG_CURVE.USE_GS_G2) { var Q=[ECP4]() let F=ECP4.frob_constants() var u=PAIR4.gs(ee); var t=BIG(0) Q.append(ECP4()) Q[0].copy(P); for i in 1 ..< 8 { Q.append(ECP4()); Q[i].copy(Q[i-1]); Q[i].frob(F,1); } for i in 0 ..< 8 { let np=u[i].nbits() t.copy(BIG.modneg(u[i],q)) let nn=t.nbits() if (nn<np) { u[i].copy(t) Q[i].neg() } u[i].norm() } R=ECP4.mul8(Q,u) } else { R=P.mul(ee) } return R; } // f=f^e // Note that this method requires a lot of RAM! Better to use compressed XTR method, see FP8.swift static public func GTpow(_ d:FP24,_ e:BIG) -> FP24 { var r:FP24 let q=BIG(ROM.CURVE_Order) var ee=BIG(e); ee.mod(q) if (CONFIG_CURVE.USE_GS_GT) { var g=[FP24]() let f=FP2(BIG(ROM.Fra),BIG(ROM.Frb)) var t=BIG(0) var u=gs(ee) g.append(FP24()) g[0].copy(d); for i in 1 ..< 8 { g.append(FP24()); g[i].copy(g[i-1]) g[i].frob(f,1) } for i in 0 ..< 8 { let np=u[i].nbits() t.copy(BIG.modneg(u[i],q)) let nn=t.nbits() if (nn<np) { u[i].copy(t) g[i].conj() } u[i].norm() } r=FP24.pow8(g,u) } else { r=d.pow(ee) } return r } // test G1 group membership */ static public func G1member(_ P:ECP) -> Bool { //let q=BIG(ROM.CURVE_Order) if P.is_infinity() {return false} let x=BIG(ROM.CURVE_Bnx) let cru=FP(BIG(ROM.CRu)) var W=ECP(); W.copy(P); W.mulx(cru) var T=P.mul(x); if P.equals(T) {return false} // P is of low order T=T.mul(x); T=T.mul(x); T=T.mul(x); T.neg() if !W.equals(T) {return false} // W.add(P); T.mulx(cru); W.add(T) // if !W.is_infinity() {return false} /* let W=P.mul(q) if !W.is_infinity() {return false} */ return true } // test G2 group membership */ static public func G2member(_ P:ECP4) -> Bool { if P.is_infinity() {return false} let F=ECP4.frob_constants() let x=BIG(ROM.CURVE_Bnx) var W=ECP4(); W.copy(P); W.frob(F,1) var T=P.mul(x) if CONFIG_CURVE.SIGN_OF_X == CONFIG_CURVE.NEGATIVEX { T.neg() } /* var R=ECP4(); R.copy(W) R.frob(F,1) W.sub(R) R.copy(T) R.frob(F,1) W.add(R) */ if !W.equals(T) {return false} /* let q=BIG(ROM.CURVE_Order) if P.is_infinity() {return false} let W=P.mul(q) if !W.is_infinity() {return false} */ return true } // Check that m is in cyclotomic sub-group // Check that m!=1, conj(m)*m==1, and m.m^{p^8}=m^{p^4} static public func GTcyclotomic(_ m:FP24) -> Bool { if m.isunity() {return false} var r=FP24(m) r.conj() r.mul(m) if !r.isunity() {return false} let f=FP2(BIG(ROM.Fra),BIG(ROM.Frb)) r.copy(m); r.frob(f,4) var w=FP24(r); w.frob(f,4) w.mul(m) if !w.equals(r) {return false} return true } // test for full GT group membership static public func GTmember(_ m:FP24) -> Bool { if !GTcyclotomic(m) {return false} let f=FP2(BIG(ROM.Fra),BIG(ROM.Frb)); let x=BIG(ROM.CURVE_Bnx) var r=FP24(m); r.frob(f,1) var t=m.pow(x) if CONFIG_CURVE.SIGN_OF_X == CONFIG_CURVE.NEGATIVEX { t.conj() } if !r.equals(t) { return false} /* let q=BIG(ROM.CURVE_Order) let r=m.pow(q) if !r.isunity() {return false} */ return true } }
/* * RocksDB.swift * Copyright (c) 2016 Ben Gollmer. * * 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 CRocksDB public enum DBError: Error, CustomStringConvertible { case backupFailed(String) case openFailed(String) case readFailed(String) case restoreFailed(String) case writeFailed(String) public var description: String { switch self { case let .backupFailed(s): return "Backup failed: \(s)" case let .openFailed(s): return "Open failed: \(s)" case let .readFailed(s): return "Read failed: \(s)" case let .restoreFailed(s): return "Restore failed: \(s)" case let .writeFailed(s): return "Write failed: \(s)" } } } public enum RocksDBVersions { case version48 case version49 } /** * The Database class provides an interface to RocksDB, a high-performance, persistent * key-value store. */ public class Database { internal var db: OpaquePointer public let options: DBOptions public let path: String public let readOnly: Bool public lazy var readOptions = DBReadOptions() public lazy var writeOptions = DBWriteOptions() public init(path: String, readOnly: Bool = false, options: DBOptions? = nil) throws { self.options = options ?? DBOptions() self.path = path self.readOnly = readOnly var err: UnsafeMutablePointer<Int8>? = nil var dbx = readOnly ? rocksdb_open_for_read_only(self.options.opts, path, 0, &err) : rocksdb_open(self.options.opts, path, &err) guard err == nil else { defer { rocksdb_free(err) } throw DBError.openFailed(String(cString: err!)) } /* Need this rigamarole to avoid an IUO error because rocksdb_open is * typed to return an OpaquePointer! */ guard dbx != nil else { throw DBError.openFailed("Unknown error") } db = dbx! } deinit { rocksdb_close(db) } public func put<K: DBSlice, V: DBSlice>(_ key: K, value: V, options: DBWriteOptions? = nil) throws { let opts = options ?? writeOptions let k = key.dbValue let v = value.dbValue var err: UnsafeMutablePointer<Int8>? = nil rocksdb_put(db, opts.opts, k, k.count, v, v.count, &err) guard err == nil else { defer { rocksdb_free(err) } throw DBError.writeFailed(String(cString: err!)) } } public func write(_ batch: DBBatch, options: DBWriteOptions? = nil) throws { let opts = options ?? writeOptions var err: UnsafeMutablePointer<Int8>? = nil rocksdb_write(db, opts.opts, batch.batch, &err) guard err == nil else { defer { rocksdb_free(err) } throw DBError.writeFailed(String(cString: err!)) } } public func delete<K: DBSlice>(_ key: K, options: DBWriteOptions? = nil) throws { let opts = options ?? writeOptions let k = key.dbValue var err: UnsafeMutablePointer<Int8>? = nil rocksdb_delete(db, opts.opts, k, k.count, &err) guard err == nil else { defer { rocksdb_free(err) } throw DBError.writeFailed(String(cString: err!)) } } public func get<K: DBSlice, V: DBSlice>(_ key: K, options: DBReadOptions? = nil) throws -> V? { let opts = options ?? readOptions let k = key.dbValue var valLength: Int = 0 var err: UnsafeMutablePointer<Int8>? = nil let value = rocksdb_get(db, opts.opts, k, k.count, &valLength, &err) guard err == nil else { defer { rocksdb_free(err) } throw DBError.readFailed(String(cString: err!)) } guard let val = value else { return nil } defer { rocksdb_free(val) } let valPointer = UnsafeBufferPointer(start: val, count: valLength) return V(dbValue: [Int8](valPointer)) } }
// // LangValue.swift // LangValue // // Created by Timothy J. Wood on 9/24/15. // Copyright © 2015 The Omni Group. All rights reserved. // import Foundation /// One of the language values enum LangValue { enum Error : ErrorType { case BadCoercion } /// LangValue support for Int case IntValue(value:Int) init(_ v:Int) { self = LangValue.IntValue(value:v) } func integerValue() throws -> Int { switch self { case .IntValue(let value): return value case .StringValue(let value): return (value as NSString).integerValue default: throw Error.BadCoercion } } /// LangValue support for String case StringValue(value:String) init(_ v:String) { self = LangValue.StringValue(value:v) } func stringValue() throws -> String { switch self { case .IntValue(let value): return "\(value)" case .StringValue(let value): return value default: throw Error.BadCoercion } } /// LangValue support for tables case Table(value:[String:LangValue]) init(_ v:[String:LangValue]) { self = LangValue.Table(value:v) } func keys() throws -> [String] { guard case .Table(let table) = self else { throw Error.BadCoercion } return table.keys.map { $0 } // Other way to flatten the lazy bits to array? } func objectForKey(key:String) throws -> LangValue? { guard case .Table(let table) = self else { throw Error.BadCoercion } return table[key] } // subscript can't be marked mutating or throws, it seems mutating func setObject(object:LangValue?, forKey key:String) throws { guard case .Table(let table) = self else { throw Error.BadCoercion } var updated = table updated[key] = object self = LangValue(updated) } mutating func removeObjectForKey(key: String) throws { try setObject(nil, forKey:key) } } func +(lhs:LangValue, rhs:LangValue) throws -> LangValue { switch (lhs, rhs) { // Same type case (.IntValue(let leftValue), .IntValue(let rightValue)): return LangValue(leftValue + rightValue) case (.StringValue(let leftValue), .StringValue(let rightValue)): return LangValue(leftValue + rightValue) // Different types case (.IntValue, .StringValue(let rightValue)): return try LangValue(lhs.stringValue() + rightValue) case (.StringValue(let leftValue), .IntValue): return try LangValue(leftValue + rhs.stringValue()) // Wrong types default: throw LangValue.Error.BadCoercion } } func addIntegerValues(values:[LangValue]) -> LangValue { let total = values.reduce(0, combine: { (sum:Int, v:LangValue) in return sum + ((try? v.integerValue()) ?? 0) }) return LangValue(total) } func addStringValues(values:[LangValue]) -> LangValue { let total = values.reduce("", combine: { (sum:String, v:LangValue) in return sum + ((try? v.stringValue()) ?? "") }) return LangValue(total) } extension LangValue: Equatable {} func ==(lhs:LangValue, rhs:LangValue) -> Bool { switch (lhs, rhs) { case (.IntValue(let leftValue), .IntValue(let rightValue)): return leftValue == rightValue case (.StringValue(let leftValue), .StringValue(let rightValue)): return leftValue == rightValue case (.Table(let leftValue), .Table(let rightValue)): // == isn't inferred by the dictionary... guard leftValue.count == rightValue.count else { return false } for (lk, lv) in leftValue { guard let rv = rightValue[lk] where lv == rv else { return false } } return true default: return false } } extension LangValue: Hashable { var hashValue: Int { switch self { case .IntValue(let v): return v.hashValue case .StringValue(let v): return v.hashValue case .Table(let t): // reduce() on a dictionary seems to pass (T, V) instead of (T, (K,V))... // Using xor here should be stable over random key orderings. var h = 0; for (k, v) in t { h = h ^ k.hashValue ^ v.hashValue } return h } } } func recursiveSetOfStringsInTable(v:LangValue) -> Set<LangValue> { var strings = Set<LangValue>() func add(v:LangValue) { switch (v) { case .StringValue: strings.insert(v) case .Table(let t): for (_, v) in t { add(v) } default: break } } add(v) return strings }
// // JuBiterWallet.swift // JubSDKProtobuf // // Created by Pan Min on 2019/12/13. // Copyright © 2019 JuBiter. All rights reserved. // import Foundation import SwiftProtobuf import JubSDKCore class JuBiterWallet { internal func inlineDeviceInfoToPb(deviceInfo: JUB_DEVICE_INFO) -> JUB_Proto_Common_DeviceInfo { var pb = JUB_Proto_Common_DeviceInfo() pb.label = withUnsafePointer(to: deviceInfo.label) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: deviceInfo.label)) { String(cString: $0) } } pb.sn = withUnsafePointer(to: deviceInfo.sn) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: deviceInfo.sn)) { String(cString: $0) } } pb.pinRetry = UInt32(deviceInfo.pinRetry) pb.pinMaxRetry = UInt32(deviceInfo.pinMaxRetry) pb.bleVersion = withUnsafePointer(to: deviceInfo.bleVersion) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: deviceInfo.bleVersion)) { String(cString: $0) } } pb.firmwareVersion = withUnsafePointer(to: deviceInfo.firmwareVersion) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: deviceInfo.firmwareVersion)) { String(cString: $0) } } return pb; } func getDeviceInfo(contextID: UInt) -> JUB_Proto_Common_ResultAny { do { var devInfo: JUB_DEVICE_INFO = JUB_DEVICE_INFO.init() let rv = JUB_GetDeviceInfo(JUB_UINT16(contextID), &devInfo) let deviceInfo = try Google_Protobuf_Any(message: inlineDeviceInfoToPb(deviceInfo: devInfo)) return inlineResultAnyToPb(stateCode: UInt64(rv), value: [deviceInfo]) } catch { return JUB_Proto_Common_ResultAny() } } func getDeviceCert(contextID: UInt) throws -> JUB_Proto_Common_ResultString { do { let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_GetDeviceCert(JUB_UINT16(contextID), buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let cert = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: cert) } } func sendOneApdu(deviceID: UInt, apdu: String) throws -> JUB_Proto_Common_ResultString { do { let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_SendOneApdu(JUB_UINT16(deviceID), apdu, buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let raw = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: raw) } } func isInitialize(contextID: UInt) -> Bool { do { return inlineEnumBoolToBool(enumBool: JUB_IsInitialize(JUB_UINT16(contextID))) } } func isBootLoader(contextID: UInt) -> Bool { do { return inlineEnumBoolToBool(enumBool: JUB_IsBootLoader(JUB_UINT16(contextID))) } } func setTimeOut(contextID: UInt, timeout: UInt) -> UInt { do { JUB_SetTimeOut(JUB_UINT16(contextID), JUB_UINT16(timeout)) return UInt(JUBR_OK) } } func enumApplets(contextID: UInt) throws -> JUB_Proto_Common_ResultString { do { let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_EnumApplets(JUB_UINT16(contextID), buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let appList = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: appList) } } func enumSupportCoins(contextID: UInt) throws -> JUB_Proto_Common_ResultString { do { let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = Jub_EnumSupportCoins(JUB_UINT16(contextID), buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let coinsList = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: coinsList) } } func getAppletVersion(deviceID: UInt, appID: String) throws -> JUB_Proto_Common_ResultString { do { let buffer = JUB_CHAR_PTR_PTR.allocate(capacity: 1) let rv = JUB_GetAppletVersion(JUB_UINT16(deviceID), appID, buffer) guard let ptr = buffer.pointee else { throw JUB.JUBError.invalidValue } defer { JUB_FreeMemory(ptr) } let raw = String(cString: ptr) return inlineResultStringToPb(stateCode: UInt64(rv), value: raw) } } func clearContext(contextID: UInt) -> UInt { do { return JUB_ClearContext(JUB_UINT16(contextID)) } } func showVirtualPwd(contextID: UInt) -> UInt { do { return JUB_ShowVirtualPwd(JUB_UINT16(contextID)) } } func cancelVirtualPwd(contextID: UInt) -> UInt { do { return JUB_CancelVirtualPwd(JUB_UINT16(contextID)) } } func verifyPIN(contextID: UInt, pinMin: String) -> JUB_Proto_Common_ResultInt { do { var retry = 0 as JUB_ULONG let rv = JUB_VerifyPIN(JUB_UINT16(contextID), pinMin, &retry) return inlineResultIntToPb(stateCode: UInt64(rv), value: UInt32(retry)) } } func queryBattery(contextID: UInt) -> JUB_Proto_Common_ResultInt{ do { var battry = 0 as UInt8 let rv = JUB_QueryBattery(JUB_UINT16(contextID), &battry) return inlineResultIntToPb(stateCode: UInt64(rv), value: UInt32(battry)) } } } // class JuBiterWallet end
// // MapVC.swift // OpenSooqTask // // Created by Qais Alnammari on 7/6/19. // Copyright © 2019 Qais Alnammari. All rights reserved. // import UIKit import GoogleMaps import Toast_Swift class MapVC: UIViewController { //Outlets:- @IBOutlet weak var mapView: GMSMapView! //Variables:- private var locationManger = CLLocationManager() weak var infoWindow : CustomWindowsView! var locationMarker = [GMSMarker]() var viewModel = MainViewModel() private var currentLocation = CLLocationCoordinate2D() private var isLocationDetected = false override func viewDidLoad() { super.viewDidLoad() configuerUI() } override func viewWillAppear(_ animated: Bool) { moveMapToSelectedMarker() } func configuerUI() { setUpLocationManger() handlingOfflineView() } func configuerData() { viewModel.longLat = "\(currentLocation.latitude),\(currentLocation.longitude)" _ = SKPreloadingView.show() viewModel.getVenues(success: { [weak self] in guard let self = self else {return} SKPreloadingView.hide() self.setupMarker() self.setupMap() }) { [weak self] (error) in guard let self = self else {return} SKPreloadingView.hide() self.view.makeToast(error.localizedDescription) } } func setUpLocationManger() { locationManger.delegate = self locationManger.requestWhenInUseAuthorization() locationManger.desiredAccuracy = kCLLocationAccuracyBest switch CLLocationManager.authorizationStatus() { case .notDetermined,.restricted,.denied: locationManger.requestWhenInUseAuthorization() break default: break } locationManger.startUpdatingLocation() locationManger.distanceFilter = 200 // will call didUpdateLocation after 200 meter to improve efficiency API Calls locationManger.startMonitoringSignificantLocationChanges() } func setupMarker() { let venues = viewModel.getVenues() for (index,venueOjc) in venues.enumerated() { let lat = venueOjc.venue?.location?.lat ?? 0 let long = venueOjc.venue?.location?.lng ?? 0 locationMarker.append(GMSMarker()) locationMarker[index].position = CLLocationCoordinate2D(latitude: lat, longitude: long) locationMarker[index].title = venueOjc.venue?.name locationMarker[index].snippet = "\(venueOjc.venue?.location?.distance ?? 0) \(localized(localizeKey: .metersAway))" locationMarker[index].map = mapView } } func setupMap() { let camera = GMSCameraPosition.camera(withLatitude: currentLocation.latitude, longitude: currentLocation.longitude, zoom: 17) mapView.camera = camera mapView.delegate = self mapView.isMyLocationEnabled = true } func moveMapToSelectedMarker() { if let selectedMarkerIndex = viewModel.selectedMarkerIndex { let marker = locationMarker[selectedMarkerIndex] mapView.selectedMarker = marker mapView.animate(toLocation: marker.position) } } func handlingOfflineView() { if viewModel.checkForInternetConnection() { //Online mapView.isHidden = false } else { //OffLine mapView.isHidden = true } self.view.handelOfflineView(isConnected: viewModel.checkForInternetConnection()) } } extension MapVC:GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { mapView.animate(toZoom: 20) return false } func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { let nib = UINib(nibName: "CustomWindowsView", bundle: nil) // register nib infoWindow = (nib.instantiate(withOwner: "CustomWindowsView", options: nil).first as! CustomWindowsView) infoWindow.autoresizingMask = [.flexibleWidth, .flexibleHeight] let selectedMareker = mapView.selectedMarker infoWindow.nameLbl.text = selectedMareker?.title infoWindow.distanceLbl.text = selectedMareker?.snippet let point = selectedMareker?.position let view = UIView(frame: CGRect(x: point?.latitude ?? 0, y: point?.longitude ?? 0, width: 200, height: 120)) infoWindow.frame = view.bounds view.addSubview(infoWindow) return view } } extension MapVC:CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = manager.location?.coordinate { currentLocation = location if viewModel.checkForInternetConnection() { //Check for internet connection first configuerData() } } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { var alert = UIAlertController() if let clErr = error as? CLError { switch clErr.code { case .locationUnknown: alert = UIAlertController(title: localized(localizeKey: .locationUnknown), message: localized(localizeKey: .pleaseTryAgainLater), preferredStyle: .alert) case .denied: alert = UIAlertController(title: localized(localizeKey: .locationAccessDenied), message: localized(localizeKey: .requiredAccessMsg), preferredStyle: .alert) alert.addAction(UIAlertAction(title: localized(localizeKey: .openSettings), style: .default, handler: { (action) in self.dismiss(animated: true, completion: nil) if let url = URL.init(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } })) alert.addAction(UIAlertAction(title: localized(localizeKey: .cancel), style: .default, handler: { (action) in self.dismiss(animated: true, completion: nil) })) case .network : alert = UIAlertController(title: localized(localizeKey: .connectionError), message: localized(localizeKey: .connectionErrorMsg), preferredStyle: .alert) default: print(error.localizedDescription) } self.present(alert, animated: true, completion: nil) } } }
import XCTest import Base85Tests var tests = [XCTestCaseEntry]() tests += Base85Tests.allTests() XCTMain(tests)
// // TextFields+Extensions.swift // testUI // // Created by Nikesh Shakya on 11/8/19. // Copyright © 2019 Nikesh Shakya. All rights reserved. // import Foundation import UIKit extension UIStackView { open override func awakeFromNib() { if self.axis == .horizontal { self.spacing = self.spacing.relativeToIphone8Width() } else { self.spacing = self.spacing.relativeToIphone8Height() } self.layoutIfNeeded() } } extension UILabel { open override func awakeFromNib() { self.font = self.font.withSize(self.font.pointSize.relativeToIphone8Width()) } } extension UITextView { open override func awakeFromNib() { self.font = self.font?.withSize((self.font?.pointSize.relativeToIphone8Width())!) } } extension UITextField { open override func awakeFromNib() { self.font = self.font?.withSize((self.font?.pointSize.relativeToIphone8Width())!) } } extension UIButton { open override func awakeFromNib() { self.titleLabel?.font = self.titleLabel?.font.withSize((self.titleLabel?.font.pointSize.relativeToIphone8Width())!) } func setBackgroundColor(color: UIColor, forState: UIControl.State) { UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor) UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, for: forState) self.clipsToBounds = true } }
// // SecretsArray.swift // Just Maps // // Created by Robert Blundell on 11/12/2017. // Copyright © 2017 Robert Blundell. All rights reserved. // import Foundation var Secrets: [Place] = [camleyStreet, platform934, sherlockHolmesRoom, broadgateIceSkatingRing, theMonument, museumOfBrands] private var camleyStreet = Place(latitude: 51.535446, longitude: -0.127705, title: "Camley Street Natural Park", placeDescription: "Concealed Garden", longPlaceDescription: """ Only a few years ago, King's Cross was one of the most squalid patches of London. Since then, real estate developers have transformed King's Cross into an uninspiring urban centre of offices, appartments and restaurants chains. This peaceful park is a hidden jungle where dragonflies and frogs cohabitate with tourists. Sit down at the community-run café and watch the canal where boats, kingfishers and swans bathe calmly. """, placeType: .secret, placeImage: #imageLiteral(resourceName: "placeholder") ) private var platform934 = Place(latitude: 51.532138, longitude: -0.124019, title: "Platform 9 3/4", placeDescription: "Recreation of Harry Potter's famous departure point to hogwarts", longPlaceDescription: """ Platform 9 3/4 at King’s Cross station in London is extremely important to young wizards, as that’s where one departs for Hogwarts via the Hogwarts Express. The Harry Potter Shop at Platform 9 3/4 is an experience that has something for everyone and a great opportunity for gift-shopping. """, placeType: .secret, placeImage: #imageLiteral(resourceName: "placeholder")) private var sherlockHolmesRoom = Place(latitude: 51.523784, longitude: -0.158465, title: "Sherlock Holmes Room", placeDescription: "221 Baker Street is the home of fictional detective Sherlock Holmes", longPlaceDescription: """ 221B Baker Street is the London address of the fictional detective Sherlock Holmes, created by author Sir Arthur Conan Doyle. Baker Street in the late 19th century was a high-class residential district, and Holmes' apartment would have been part of a Georgian terrace. For many years, Abbey National had to employ a full-time secretary to answer mail addressed to Sherlock Holmes. In 1990, the Sherlock Holmes museum (situated on the same block) installed a blue plaque marking 221B Baker Street, which led to a 15-year dispute between Abbey National and the Holmes Museum for the right to receive Sherlock Holm's mail. The Sherlock Holmes Museum is located between 237 and 241 Baker Street. It displays exhibits in period rooms, wax figures and Holmes memorabilia, with the famous study overlooking Baker Street the highlight of the museum. The description of the house can be found throughout the stories, including the 17 steps leading from the ground-floor hallway to the first-floor study. The Sherlock Holmes Pub nearby also displays tourist memorabilia. """, placeType: .secret, placeImage: #imageLiteral(resourceName: "placeholder")) private var broadgateIceSkatingRing = Place(latitude: 51.519849, longitude: -0.081198, title: "Broadgate Ice Skating Rink", placeDescription: "Hidden Ice Skating Ring in The City of London", longPlaceDescription: """ Despite being in the heart of London's financial centre, this homely ice ring is one of the cheapest in London. Few people know of it's existence, other than the investment Bankers that stare longingly at skaters from the top of their high-rise offices. The ring only fills up on Tuesdays evenings, at 7pm when broomball matches are held. 12 players will face off in this animalistic version of hockey where players substitute their sticks with brooms. """, placeType: .secret, placeImage: #imageLiteral(resourceName: "placeholder")) private var theMonument = Place(latitude: 51.510139, longitude: -0.085943, title: "The Monument", placeDescription: "Stone tower that offers an alternative view of the London Landscape", longPlaceDescription: """ This 61-metre tall tower built in pure stone (the tallest of it's kind) was built to commemorate the Great Fire of London of 1677. The city of London has outgrown the Tower, but it offers an alternative landscape view to the one most tourists take. It will take you 311 steps to walk up the damn thing, but every brave soul that makes it to the top will recieve a certificate for their fortitude. """, placeType: .secret, placeImage: #imageLiteral(resourceName: "placeholder")) private var museumOfBrands = Place(latitude: 51.516433, longitude: -0.211127, title: "Museum of Brands", placeDescription: "A hommage to consumerism", longPlaceDescription: """ Outside the centre of London is this strange museum that catalogues the conumption habits of the British population druing the past two decades. Organized artfully by theme or decade, these everyday products and packaging deconstruct the social history of Britain. The museum boasts over half a million unremarkable objects, ranging from the "Servants' Friend" stove polish to "The Win the War Cookery Book". """, placeType: .secret, placeImage: #imageLiteral(resourceName: "placeholder")) // Little Venice?? //Camden passage?? // Move leadenhall to secrets?? // Add St. Catherin's Docks to the secrets array. // add brick lane market? // add less touristy markets?
// // ConfirmPurchaseRouter.swift // OrgTech // // Created by Maksym Balukhtin on 29.04.2020. // Copyright © 2020 Maksym Balukhtin. All rights reserved. // import UIKit protocol ConfirmPurchaseRoute { func close() } extension ConfirmPurchaseRoute where Self: BaseRouter { func close() { close(completion: nil) } } final class ConfirmPurchaseRouter: BaseRouter, ConfirmPurchaseRouter.Routes { typealias Routes = ConfirmPurchaseRoute }
// // ViewController.swift // We The People // // Created by Hector Delgado on 5/15/20. // Copyright © 2020 Hector Delgado. All rights reserved. // import UIKit class HomeViewController: UIViewController { let reachability = Reachability.shared override func viewDidLoad() { super.viewDidLoad() } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { let connectionAvailable = reachability.connectionIsAvailable if !connectionAvailable { let alert = UIAlertController(title: "Oops", message: "No Internet connection detected!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true) } return connectionAvailable } }
// // MovieController.swift // ImdbMovies // // Created by Boaz Froog on 07/11/2019. // Copyright © 2019 Boaz Froog. All rights reserved. import UIKit class MovieController: UIViewController { let basePosterUrl = "https://image.tmdb.org/t/p/w300/" var movie: Movie? { didSet { titleLabel.text = movie?.title popularityLabel.text = "rating: \(movie?.popularity ?? 0)" let posterUrl = basePosterUrl + (movie?.poster_path ?? "") guard let url = URL(string: posterUrl) else { return } URLSession.shared.dataTask(with: url) { (data, _, _) in guard let data = data else { return } DispatchQueue.main.async { self.posterImageView.image = UIImage(data: data) } }.resume() } } let titleLabel: UILabel = { let label = UILabel() label.font = .boldSystemFont(ofSize: 28) return label }() let popularityLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 20) return label }() let posterImageView: UIImageView = { let iv = UIImageView(image: #imageLiteral(resourceName: "star")) iv.contentMode = .scaleAspectFill iv.clipsToBounds = true return iv }() override func viewDidLoad() { super.viewDidLoad() setupLayout() } fileprivate func setupLayout() { view.backgroundColor = .white let stackView = UIStackView(arrangedSubviews: [ titleLabel, popularityLabel, posterImageView ]) stackView.axis = .vertical stackView.spacing = 4 stackView.distribution = .fillProportionally view.addSubview(stackView) stackView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: nil, padding: .init(top: 50, left: 50, bottom: 0, right: 0)) stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } }
// // AppDelegate.swift // Metsterios // // Created by Chelsea Green on 3/27/16. // Copyright © 2016 Chelsea Green. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit import Quickblox import AWSCognito import AWSS3 let kQBApplicationID:UInt = 40697 let kQBAuthKey = "ftAZNMG9LAkGWO2" let kQBAuthSecret = "bNSdHdxPn4ZOJEt" let kQBAccountKey = "dzsiQx1v2tK5hwfTPsqk" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. QBSettings.setApplicationID(kQBApplicationID) QBSettings.setAuthKey(kQBAuthKey) QBSettings.setAuthSecret(kQBAuthSecret) QBSettings.setAccountKey(kQBAccountKey) //amazon cognito setting let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast1, identityPoolId:"us-east-1:87c5424e-123c-439b-a2ca-cd8761ba2980") let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration return FBSDKApplicationDelegate.sharedInstance() .application(application, didFinishLaunchingWithOptions: launchOptions) } func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { NSLog("[%@ %@]", NSStringFromClass(self.dynamicType), #function) /* Store the completion handler. */ AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler) } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let deviceIdentifier: String = UIDevice.currentDevice().identifierForVendor!.UUIDString let subscription: QBMSubscription! = QBMSubscription() subscription.notificationChannel = QBMNotificationChannelAPNS subscription.deviceUDID = deviceIdentifier subscription.deviceToken = deviceToken QBRequest.createSubscription(subscription, successBlock: { (response: QBResponse!, objects: [QBMSubscription]?) -> Void in // }) { (response: QBResponse!) -> Void in // } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { NSLog("Push failed to register with error: %@", error) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { NSLog("my push is: %@", userInfo) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. FBSDKAppEvents.activateApp() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance() .application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } }
// // ResourceOperation.swift // LoadIt // // Created by Luciano Marisi on 02/07/2016. // Copyright © 2016 Luciano Marisi. All rights reserved. // import Foundation public final class ResourceOperation<ResourceService: ResourceServiceType>: BaseOperation, ResourceOperationType { public typealias Resource = ResourceService.Resource public typealias DidFinishFetchingResourceCallback = (ResourceOperation<ResourceService>, Result<Resource.Model>) -> Void private let resource: Resource private let service: ResourceService private let didFinishFetchingResourceCallback: DidFinishFetchingResourceCallback public init(resource: ResourceService.Resource, service: ResourceService = ResourceService(), didFinishFetchingResourceCallback: DidFinishFetchingResourceCallback) { self.resource = resource self.service = service self.didFinishFetchingResourceCallback = didFinishFetchingResourceCallback super.init() } override public func execute() { fetch(resource: resource, usingService: service) } public func didFinishFetchingResource(result result: Result<Resource.Model>) { didFinishFetchingResourceCallback(self, result) } }
// // SettingsViewController.swift // math-exercise // // Created by Furkan Kaan Ugsuz on 13/12/2020. // import UIKit import QuickTableViewController var selectedNumberofQuestion = 10 var selectedTime = 15 var soundOn = true var vibration = true var checkSound = true var checkVibration = true var defaultSound = UserDefaults.standard var defaultVibration = UserDefaults.standard var defaultNumber = UserDefaults.standard var defaultTime = UserDefaults.standard class SettingsViewController: QuickTableViewController { override func viewDidLoad() { super.viewDidLoad() print(defaultSound.bool(forKey:"Sound")) soundOn = defaultSound.bool(forKey: "Sound") vibration = defaultVibration.bool(forKey: "Vibration") selectedTime = defaultTime.integer(forKey: "Time") selectedNumberofQuestion = defaultNumber.integer(forKey: "Number") tableContents = [ Section(title: "Switch", rows: [ SwitchRow(text: "Sound effects", switchValue: soundOn, action: soundFunc() ), SwitchRow(text: "Vibration", switchValue: vibration, action: vibrationFunc()) ]), RadioSection(title: "Number of questions in Quiz", options: [ OptionRow(text: "10", isSelected: isSelectedForQuestion10(), action: didToggleSelectionForNumber()), OptionRow(text: "15", isSelected: isSelectedForQuestion15(), action: didToggleSelectionForNumber()), OptionRow(text: "20", isSelected: isSelectedForQuestion20(), action: didToggleSelectionForNumber()) ]), RadioSection(title: "Time for questions", options: [ OptionRow(text: "10", isSelected: isSelectedForTime10(), action: didToggleSelectionForTime()), OptionRow(text: "15", isSelected: isSelectedForTime15(), action: didToggleSelectionForTime()), OptionRow(text: "20", isSelected: isSelectedForTime20(), action: didToggleSelectionForTime()) ]), Section(title: "Rate the app", rows: [ TapActionRow(text: "Rate!", action: toAppStore()) ]), ] // Do any additional setup after loading the view. } private func showAlert() -> (Row) -> Void { return { [weak self] _ in let alert = UIAlertController(title: "Action Triggered", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel) { [weak self] _ in self?.dismiss(animated: true, completion: nil) }) self?.present(alert, animated: true, completion: nil) } } private func didToggleSelectionForNumber() -> (Row) -> Void { return { row in selectedNumberofQuestion = Int(row.text)! defaultNumber.set(selectedNumberofQuestion, forKey: "Number") } } private func didToggleSelectionForTime() -> (Row) -> Void { return { row in selectedTime = Int(row.text)! defaultTime.set(selectedTime, forKey: "Time") } } private func soundFunc() -> (Row) -> Void { return{ row in if (checkSound){ soundOn = false checkSound = false defaultSound.set(soundOn,forKey: "Sound") } else{ soundOn = true checkSound = true defaultSound.set(soundOn,forKey: "Sound") } } } private func vibrationFunc() -> (Row) -> Void { return{ row in if (checkVibration ){ vibration = false checkVibration = false defaultVibration.set(vibration, forKey: "Vibration") } else{ vibration = true checkVibration = true defaultVibration.set(vibration, forKey: "Vibration") } } } func switchValueDidChange(_ sender: UISwitch) { print("wow") } func toAppStore() -> (Row) -> Void{ return {row in if let url = URL(string: "itms-apps://apple.com/app/id839686104") { UIApplication.shared.open(url) } }; } func isSelectedForTime10() -> Bool { if selectedTime == 10 { return true } return false } func isSelectedForTime15() -> Bool { if selectedTime == 15 || defaultTime.integer(forKey: "Time") == 0{ return true } return false } func isSelectedForTime20() -> Bool { if selectedTime == 20 { return true } return false } func isSelectedForQuestion10() -> Bool { if selectedNumberofQuestion == 10 { return true } return false } func isSelectedForQuestion15() -> Bool { if selectedNumberofQuestion == 15 || defaultTime.integer(forKey: "Number") == 0 { return true } return false } func isSelectedForQuestion20() -> Bool { if selectedNumberofQuestion == 20 { return true } return false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // main.swift // 数学函数 // // Created by yunna on 2020/4/9. // Copyright © 2020 yunna. All rights reserved. /* public func modff(_: Float, _: UnsafeMutablePointer<Float>!) -> Float public func modf(_: Double, _: UnsafeMutablePointer<Double>!) -> Double public func modfl(_: Float80, _: UnsafeMutablePointer<Float80>!) -> Float80 public func ldexpf(_: Float, _: Int32) -> Float public func ldexp(_: Double, _: Int32) -> Double public func ldexpl(_: Float80, _: Int32) -> Float80 public func frexpf(_: Float, _: UnsafeMutablePointer<Int32>!) -> Float public func frexp(_: Double, _: UnsafeMutablePointer<Int32>!) -> Double public func frexpl(_: Float80, _: UnsafeMutablePointer<Int32>!) -> Float80 public func ilogbf(_: Float) -> Int32 public func ilogb(_: Double) -> Int32 public func ilogbl(_: Float80) -> Int32 public func scalbnf(_: Float, _: Int32) -> Float public func scalbn(_: Double, _: Int32) -> Double public func scalbnl(_: Float80, _: Int32) -> Float80 public func scalblnf(_: Float, _: Int) -> Float public func scalbln(_: Double, _: Int) -> Double public func scalblnl(_: Float80, _: Int) -> Float80 public func fabsf(_: Float) -> Float public func fabs(_: Double) -> Double public func fabsl(_: Float80) -> Float80 public func cbrtf(_: Float) -> Float public func cbrt(_: Double) -> Double public func cbrtl(_: Float80) -> Float80 public func hypotf(_: Float, _: Float) -> Float public func hypot(_: Double, _: Double) -> Double public func hypotl(_: Float80, _: Float80) -> Float80 public func powf(_: Float, _: Float) -> Float public func pow(_: Double, _: Double) -> Double public func powl(_: Float80, _: Float80) -> Float80 public func sqrtf(_: Float) -> Float public func sqrt(_: Double) -> Double public func sqrtl(_: Float80) -> Float80 public func erff(_: Float) -> Float public func erf(_: Double) -> Double public func erfl(_: Float80) -> Float80 public func erfcf(_: Float) -> Float public func erfc(_: Double) -> Double public func erfcl(_: Float80) -> Float80 */ import Foundation
// // FormEntryField.swift // diverCity // // Created by Lauren Shultz on 3/6/19. // Copyright © 2019 Lauren Shultz. All rights reserved. // import Foundation import UIKit public class FormEntryField: UITextField { var label: UILabel! //var textField: UITextField init(frame: CGRect, withHint hint: String) { label = UILabel(frame: CGRect(x: 0, y: -30, width: 200, height: 30)) //textField = UITextField(frame: CGRect(x: frame.minX, y: label.frame.maxY, width: frame.width, height: frame.height - 30)) super.init(frame: CGRect(x: frame.minX, y: frame.minY + 30, width: frame.width, height: frame.height)) setupLabel(withText: hint) setupTextField(withHint: hint) self.addSubview(label) //self.addSubview(textField) //self.bringSubview(toFront: textField) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func setupTextField(withHint hint: String) { //self.bounds = CGRect(x: frame.minX, y: frame.minY, width: 300, height: 40) self.placeholder = "Enter text here" self.font = UIFont.systemFont(ofSize: 15) self.borderStyle = UITextField.BorderStyle.roundedRect self.autocorrectionType = UITextAutocorrectionType.no self.keyboardType = UIKeyboardType.default self.returnKeyType = UIReturnKeyType.done self.clearButtonMode = UITextField.ViewMode.whileEditing self.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center self.placeholder = hint self.isEnabled = true } // func setupTextField(withHint hint: String) { // //self.bounds = CGRect(x: frame.minX, y: frame.minY, width: 300, height: 40) // textField.placeholder = "Enter text here" // textField.font = UIFont.systemFont(ofSize: 15) // textField.borderStyle = UITextField.BorderStyle.roundedRect // textField.autocorrectionType = UITextAutocorrectionType.no // textField.keyboardType = UIKeyboardType.default // textField.returnKeyType = UIReturnKeyType.done // textField.clearButtonMode = UITextField.ViewMode.whileEditing // textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center // textField.placeholder = hint // // textField.isEnabled = true // } func setupLabel(withText text: String) { label.text = text } }
// // File.swift // PageShare // // Created by Q.S Wang on 28/02/2016. // Copyright © 2016 OnePlus All rights reserved. // import Foundation struct Path : Glossy{ let path:[Point] // let paths: [Point]? init?(path:[Point]) { self.path = path } init?(json: JSON) { self.path = ("path" <~~ json)! } func toJSON() -> JSON? { return jsonify([ "path" ~~> self.path // Encoder.encodeArray("path")(self.path) ]); } }
// // ZGestureAndKeyRecognizer.swift // Seriously // // Created by Jonathan Sand on 6/11/17. // Copyright © 2017 Jonathan Sand. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif class ZPanGestureRecognizer : NSPanGestureRecognizer { var modifiers: ZEventFlags? override var isShiftDown: Bool { return modifiers?.contains(.shift) ?? false } override var isOptionDown: Bool { return modifiers?.contains(.option) ?? false } override var isCommandDown: Bool { return modifiers?.contains(.command) ?? false } override var isControlDown: Bool { return modifiers?.contains(.control) ?? false } override open func reset() { modifiers = nil super.reset() } override open func mouseDown (with event: ZEvent) { modifiers = event.modifierFlags super.mouseDown (with: event) } } class ZKeyClickGestureRecognizer: ZClickGestureRecognizer { var modifiers: ZEventFlags? override var isShiftDown: Bool { return modifiers?.contains(.shift) ?? false } override var isOptionDown: Bool { return modifiers?.contains(.option) ?? false } override var isCommandDown: Bool { return modifiers?.contains(.command) ?? false } override var isControlDown: Bool { return modifiers?.contains(.control) ?? false } override open func reset() { modifiers = nil super.reset() } override open func mouseDown (with event: ZEvent) { modifiers = event.modifierFlags super.mouseDown (with: event) } }
// // FileDownloader.swift // CloudStorage // // Created by James Robinson on 2/5/20. // import Foundation #if canImport(Combine) import Combine #endif #if canImport(CryptoKit) import CryptoKit #endif #if canImport(Combine) /// A publisher which defines a method for downloading a file referenced by a given `Downloadable`. public protocol FileDownloader: Publisher where Output == DownloadProgress, Failure == DownloadError { associatedtype DownloadableType: Downloadable associatedtype DeleterType: FileDeleter #if canImport(CryptoKit) /// Prepares to download data for a `Downloadable` from an external service. /// /// - Parameters: /// - file: The `Downloadable` which identifies the data to fetch. /// - outputDirectory: The location of a directory or file destination to put the downloaded (and /// optionally decrypted) file. The downloader should download the relevant data into a temporary folder before /// moving that data into the `outputDirectory` and finishing. /// - decryptionKey: The symmetric key used to encrypt the data when it was uploaded. Pass `nil` to /// return the data as it is received from the server. /// /// - Throws: `DownloadError.notAuthenticated` if the user is not presently authenticated. /// - Returns: A publisher of the result of the download operation. Subscribe to this publisher to begin the download. static func downloadFile( _ file: DownloadableType, to outputDirectory: URL, decryptingUsing decryptionKey: SymmetricKey? ) throws -> Self #endif /// Prepares to delete a file from an external service. /// /// - Parameters: /// - file: The `Downloadable` which identifies the data to delete. /// - Throws: `DownloadError.notAuthenticated` if the user is not presently authenticated. /// - Returns: A publisher that completes when the deletion finishes. Subscribe to this publisher to begin the deletion. static func deleteFile(_ file: DownloadableType) throws -> DeleterType } /// A publisher which completes successfully at the end of a successful deletion operation. public protocol FileDeleter: Publisher where Output == Never, Failure == DownloadError { associatedtype Deletable: Downloadable } #endif public struct DownloadProgress { public init(completedBytes: Int, totalBytes: Int? = nil) { self.completedBytes = completedBytes self.totalBytes = totalBytes } public var completedBytes: Int public var totalBytes: Int? public var fractionCompleted: Double? { guard let total = totalBytes else { return nil } return Double(completedBytes) / Double(total) } } /// A type that conforms to this protocol may be used by objects that conform to the `FileDownloader` protocol. public protocol Downloadable: Identifiable where ID == UUID { associatedtype PayloadType: Uploadable var recordIdentifier: UUID { get } var fileExtension: String? { get } /// Local storage for the uploadable type. var storage: PayloadType? { get set } } extension Downloadable { public var localData: Data? { return storage?.payload } } public enum DownloadError: Swift.Error { /// The download was cancelled. case cancelled #if canImport(CryptoKit) /// An error occurred while decrypting downloaded data. case decryption(CryptoKitError) #endif /// An error occurred during a disk operation. case disk(CocoaError) /// The requested item was not found on the server. case itemNotFound /// Multiple errors occurred. These are mapped by their file ID. indirect case multiple([UUID: DownloadError]) /// The network is temporarily unavailable. case networkUnavailable /// The storage service is temporarily unavailable. case serviceUnavailable /// The user is not signed in. case notAuthenticated /// The signed-in user does not have permission to access the file. case unauthorized /// An error which should only come up under development and pre-launch circumstances. case development(String) /// An unknown error has occurred. If this error was derrived from a /// specific service's error codes, you may need to handle that error specially. case unknown } extension DownloadError: CustomStringConvertible { public var description: String { switch self { case .cancelled: return "Cancelled" #if canImport(CryptoKit) case .decryption(let error): return error.localizedDescription #endif case .development(let reason): return reason case .disk(let error): return error.localizedDescription case .itemNotFound: return "Item not found" case .multiple(let errors): return "\(errors.count) error\(errors.count == 1 ? "" : "s")" case .networkUnavailable: return "Network unavailable" case .notAuthenticated: return "Sign-in required" case .serviceUnavailable: return "Service unavailable. Try again later" case .unauthorized: return "No permission" case .unknown: return "Unknown error" } } }
// // ContainerVC.swift // TaxiApp // // Created by Hundily Cerqueira on 20/04/20. // Copyright © 2020 Hundily Cerqueira. All rights reserved. // import UIKit class ContainerVC: UIViewController { // MARK: - Propetis var menuVC: UIViewController! var centerVC: UIViewController! var isExpanded = false // MARK: - Init override func viewDidLoad() { super.viewDidLoad() configureHomeVC() } override func viewWillAppear(_ animated: Bool) { navigationItem.title = " " navigationController?.navigationBar.isHidden = true } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } override var prefersStatusBarHidden: Bool { return false // return isExpanded } // MARK: - Handlers func configureHomeVC() { let homeVC = HomeVC() homeVC.delegate = self centerVC = UINavigationController(rootViewController: homeVC) view.addSubview(centerVC.view) addChild(centerVC) centerVC.didMove(toParent: self) } override var preferredStatusBarStyle: UIStatusBarStyle { return .darkContent } func configureMenuVC() { if menuVC == nil { menuVC = MenuVC() view.insertSubview(menuVC.view, at: 0) addChild(menuVC) menuVC.didMove(toParent: self) } } func showMenuVC(shouldExpand: Bool) { if shouldExpand { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { self.centerVC.view.frame.origin.x = self.centerVC.view.frame.width - 80 // if let home = self.centerVC.children.first { // home.view.backgroundColor = .black // home.view.alpha = 0.5 // } }, completion: nil) } else { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { self.centerVC.view.frame.origin.x = 0 self.setNeedsStatusBarAppearanceUpdate() // if let home = self.centerVC.children.first { // home.view.backgroundColor = .black // home.view.alpha = 1 // } }, completion: nil) } animateStatusBar() } func animateStatusBar() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { self.setNeedsStatusBarAppearanceUpdate() }, completion: nil) } } extension ContainerVC: HomeVCDelegate { func handleMenuToggle() { if !isExpanded { configureMenuVC() } isExpanded = !isExpanded showMenuVC(shouldExpand: isExpanded) } }
// // Contacts+CoreDataProperties.swift // CoreDataDemo // // Created by mac on 2017. 4. 20.. // Copyright © 2017년 StudioKJ. All rights reserved. // import Foundation import CoreData extension Contacts { @nonobjc public class func fetchRequest() -> NSFetchRequest<Contacts> { return NSFetchRequest<Contacts>(entityName: "Contacts") } @NSManaged public var name: String? @NSManaged public var phone: String? @NSManaged public var address: String? }
/* CLASSES Objects and Instances A class is a blueprint or template for an instance of that class. The term object is often used to refer to an instance of a class. In Swift, however, classes and structures are very similar and it's therefore easier and less confusing to use the term instance for both classes and structures. Methods and Functions Earlier in this series, we worked with functions. In the context of classes and structures, we usually refer to functions as methods. In other words, methods are functions that belong to a particular class or structure. In the context of classes and structures, you can use both terms interchangeably since every method is a function. References: http://img05.deviantart.net/b12a/i/2012/366/0/7/sora_s_segway_by_yoi_kun-d5pxaq3.png */ // SYNTAX class Person { // Enter code here to define class Person } // PROPERTIES = attributes, variables/constants can be stored or computed properties class Person { //NOTE: Stored properties need to have a value after initialization //or be defined as an optional type var firstName: String? var lastName: String? // Constant property can possibly change its value during the //initialization of an instance. Once instance has been initialized, //the property can no longer be modified let gender = "female" } // Methods - Add behaviour or functionality (looks like a function) class Person { var firstName: String? var lastName: String? let gender = "female" func fullName() -> String { var parts: [String] = [] if let firstName = self.firstName { parts += [firstName] } if let lastName = self.lastName { parts += [lastName] } return " ".join(parts) } } /* INSTANTIATION - Instantiating an instance of a class is very similar to invoking a function. To create an instance, the name of the class is followed by a pair of parentheses, the return value is assigned to a constant or variable. */ let john = Person() // We can access the properties of an instance using the convenience of the dot syntax. john.firstName = "John" john.lastName = "Doe" john.gender = "male" // Assigning "male" to the gender property, however, results in an error. /* INITIALIZATION - Initialization is a step in the lifetime of an instance of a class or structure. During initialization, we prepare the instance for use by populating its properties with initial values. The initialization of an instance can be customized by implementing an initializer, a special type of method. */ class Person { var firstName: String? var lastName: String? let gender = "female" init() { self.gender = "male" // self refers to the instance that's being initialized. //This means that self.gender refers to the gender property of the instance. } } // *********************** MY OWN NOTES **************************************** import Foundation import SpriteKit /* CLASSES OBJECT & INSTANCES PROPERTIES & METHODS */ // SYNTAX class SomeClass { // some properties &/or methods go here } // PROPERTIES => attributes, variables/constants can be stored or computed properties class Shape { var name: String = "Square" var width: Int var color: NSColor // Change this to an optional var x: Int = 0 var y: Int = 0 /* INITIALIZATION - Initialization is a step in the lifetime of an instance of a class or structure. During initialization, we prepare the instance for use by populating its properties with initial values. The initialization of an instance can be customized by implementing an initializer, a special type of method. */ init (width:Int, color: NSColor) { self.width = width self.color = color // self refers to the instance that's being initialized. //This means that self.color refers to the color property of the instance. } // Computed propety read and write ability, getter & a setter var area: Int { get { return width * width } set { self.width = newValue / 2 // newValue is a default convention provided by Swift //if you didn't specify a name for the value coming in } } // Computed properties - read-only with just a get, must use var to declare computed properties var point: String { get { return "(\(x), \(y))" } } /* METHODS - Add behaviour or functionality (looks like a function)*/ func calculatePerimeter() -> Int { return 4 * width } } /* INSTANTIATION - Instantiating an instance of a class is very similar to invoking a function. To create an instance, the name of the class is followed by a pair of parentheses, the return value is assigned to a co nstant or variable. */ var greenSquare = Shape(width: 200, color: NSColor.greenColor()) //Access the properties of an instance using the convenience of the dot syntax. greenSquare.name = "Green Square" // Let draw a shape using our new square var greenSquareStructure = CGRect(x: greenSqua.x, y: greenSquare.y, width: greenSquare.width, height: greenSquare.width) var greenSquareVisible = SKShapeNode(rect: greenSquareStructure) greenSquareVisible.fillColor = greenSquare.color // SUBCLASSES - Act of basing a new off of an existing class, inheritance // Subclass syntax /* class SomeSubclass: SomeBaseClass { // some properties, method... } */ class Circle: Shape { // A new variable - to use later /* LAZY: lazy stored property is a property whose initial value is not calculated until the first time it is used */ lazy var radius: CGFloat = self.width / 2 // OVERRIDING - MUST always state both the name and type of the property you are overriding, enables // compiler to check that your override matches a superclass property with the same name and type. // Override a computed property override var area: CGFloat { get { return CGFloat(M_2_PI) * (radius * radius) } set { self.radius = sqrt(newValue / CGFloat(M_2_PI)) // newValue is a default convention provided by Swift //if you didn't specify a name for the value coming in } } // Override a method override func calculatePerimeter() -> CGFloat return 2 * CGFloat(M_2_PI) * radius } // Extending subclass with custom methods: func createShape () -> SKShapeNode { return SKShapeNode(circleOfRadius: self.radius) } func addFillColor () -> NSColor { return self.color } } // Create instance of circle class var redCircle = Circle(name: "Red Circle", width: 200, color: NSColor.redColor()) redCircle.addFillColor() var redCircleDisplay = redCircle.createShape() redCircleDisplay.fillColor = redCircle.addFillColor()
// // NetworkServiceSpy.swift // MarvelCharactersTests // // Created by Alexander Gurzhiev on 10.04.2021. // @testable import MarvelCharacters final class NetworkServiceSpy: NetworkService { var successResponse: MarvelResponse.DataContainer? var errorResponse: Error? var searchText: String? var didReset: Bool = false func load(search: String?, completion: @escaping RequestCompletion) { searchText = search if let successResponse = successResponse { completion(.success(successResponse)) } else if let errorResponse = errorResponse { completion(.failure(errorResponse)) } } func reset() { didReset = true } }
// // searchViewController.swift // Assignment5 // // Created by Zihan Zhang on 2017/10/29. // Copyright © 2017年 Zihan Zhang. All rights reserved. // import UIKit class searchViewController: UIViewController { @IBOutlet weak var searchTextView: UITextView! @IBOutlet weak var stextField: UITextField! @IBAction func SearchItem(_ sender: UIBarButtonItem) { let name = stextField?.text print(name) var have = false var result: String = "" for i in store.items { if i.itemName == name { have = true result = result + "Item Name: " + i.itemName + "\n" result = result + "Item Price: " + String(i.itemPrice) + "\n" result = result + "Item Description: " + i.itemDescription + "\n" result = result + "Item Category: " + i.itemType.name + "\n" searchTextView?.text = result } } if have { let alert = UIAlertView() alert.title = "Alert" alert.message = "Search Succeed" alert.addButton(withTitle: "Understood") alert.show() } else { let alert = UIAlertView() alert.title = "Alert" alert.message = "No Item" alert.addButton(withTitle: "Understood") alert.show() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Notification+Extensions.swift // RedditMe // // Created by Andrey Krit on 16.11.2020. // import Foundation extension Notification.Name { static let authNotification = Self.init("authNotification") static let didRecieveToken = Self.init("didRecieveToken") }
// // Copyright © 2021 Tasuku Tozawa. All rights reserved. // import UIKit protocol AppRootSideBarControllerDelegate: AnyObject { func appRootSideBarController(_ controller: AppRootSideBarController, didSelect item: AppRootSideBarController.Item) } class AppRootSideBarController: UIViewController { typealias Factory = ViewControllerFactory enum Section: Int { case main } typealias Item = AppRoot.SideBarItem // MARK: - Properties var currentItem: AppRoot.SideBarItem { guard isViewLoaded else { return initialItem } guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let item = dataSource.itemIdentifier(for: indexPath) else { return .top } return item } private var collectionView: UICollectionView! private var dataSource: UICollectionViewDiffableDataSource<Section, Item>! weak var delegate: AppRootSideBarControllerDelegate? private var initialItem: AppRoot.SideBarItem = .top private var isAppliedInitialValues: Bool = false // MARK: - Lifecycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "LikePics" navigationController?.navigationBar.prefersLargeTitles = true configureHierarchy() configureDataSource() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() applyInitialValuesIfNeeded() } func select(_ item: AppRoot.SideBarItem) { guard isViewLoaded else { initialItem = item return } collectionView.selectItem(at: IndexPath(row: item.rawValue, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition.centeredVertically) } private func applyInitialValuesIfNeeded() { guard !isAppliedInitialValues else { return } var snapshot = NSDiffableDataSourceSnapshot<Section, Item>() snapshot.appendSections([.main]) snapshot.appendItems(Item.allCases) dataSource.apply(snapshot) collectionView.selectItem(at: IndexPath(row: initialItem.rawValue, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition.centeredVertically) isAppliedInitialValues = true } } // MARK: - Layout extension AppRootSideBarController { private func createLayout() -> UICollectionViewLayout { return UICollectionViewCompositionalLayout { _, environment -> NSCollectionLayoutSection? in var configuration = UICollectionLayoutListConfiguration(appearance: .sidebar) configuration.backgroundColor = Asset.Color.backgroundClient.color return NSCollectionLayoutSection.list(using: configuration, layoutEnvironment: environment) } } } extension AppRootSideBarController { private func configureHierarchy() { collectionView = UICollectionView(frame: view.frame, collectionViewLayout: createLayout()) collectionView.backgroundColor = Asset.Color.backgroundClient.color collectionView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(collectionView) NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor), collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) collectionView.delegate = self } private func configureDataSource() { let registration: UICollectionView.CellRegistration<UICollectionViewListCell, Item> = .init { cell, _, item in var contentConfiguration = UIListContentConfiguration.sidebarCell() contentConfiguration.image = item.image contentConfiguration.text = item.title cell.contentConfiguration = contentConfiguration } dataSource = .init(collectionView: collectionView) { collectionView, indexPath, item in return collectionView.dequeueConfiguredReusableCell(using: registration, for: indexPath, item: item) } collectionView.dataSource = dataSource } } extension AppRootSideBarController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let item = dataSource.itemIdentifier(for: indexPath) else { return } self.delegate?.appRootSideBarController(self, didSelect: item) } }
// // ViewController.swift // RateMySnack // // Created by Ho, Derrick on 7/10/15. // Copyright (c) 2015 Ho, Derrick. All rights reserved. // import UIKit class SnackObject : FormObject { var snackName : String init(name:String ) { snackName = name } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var kindBar : SnackObject = SnackObject(name: "PopCorn") BackEndServer.submit(kindBar, completionHandler:{ (err:NSError?) -> Void in print("Just submitted Snack") }); } }
// // CRCommon.swift // CRSwiftWB // // Created by Apple on 16/9/5. // Copyright © 2016年 Apple. All rights reserved. //https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00f_zbVDWgVUTCe973002308EshvfE import Foundation ///屏宽 // MARK:- 授权的常量 let app_key = "2268051048" let app_secret = "1ebe2c75f55bc98a93c992f6357123f3" let redirect_uri = "http://www.baidu.com" let code = "35191dcfd02c898eb7aebefa996e76dc" //MARK:-- url ///string : 首页微博请求url let statusUrl = "https://api.weibo.com/2/statuses/home_timeline.json" ///string : 个人账户信息请求url let accountUrl = "https://api.weibo.com/2/users/show.json" ///string : accessToken url 2.00f_zbVDWgVUTCe973002308EshvfE let accessTokenUrl = "https://api.weibo.com/oauth2/access_token"
// // Linear_Intro.swift // 100Views // // Created by Mark Moeykens on 7/13/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Linear_Intro : View { let gradientColors = Gradient(colors: [Color.pink, Color.purple]) var body: some View { ZStack { LinearGradient(gradient: gradientColors, startPoint: .top, endPoint: .bottom) .edgesIgnoringSafeArea(.vertical) VStack(spacing: 20) { Text("LinearGradient") .font(.largeTitle) Text("Introduction") .foregroundColor(.white) Text("When creating a gradient, you can specify an array of colors and start and end points to establish the direction of the gradient.") .frame(maxWidth: .infinity) .padding() .background(Color.pink.shadow(radius: 10)) }.font(.title) } } } #if DEBUG struct Linear_Intro_Previews : PreviewProvider { static var previews: some View { Linear_Intro() } } #endif
// // HistoryViewController.swift // Tip Calculator // // Created by Kirill on 8/5/17. // Copyright © 2017 KG. All rights reserved. // import UIKit import Foundation import CoreData var records: [NSManagedObject] = [] class HistoryViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() title = "Transactions" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100)) tableView.tableFooterView = UIView(frame: rect) } // MARK: - Fetch Data override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Records") do { records = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } } } // MARK: - UITableViewDataSource extension HistoryViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records.count } // MARK: Delete data from Core Data and Table View. func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let noteEntity = "Records" let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let note = records[indexPath.row] if editingStyle == .delete { managedContext.delete(note) do { try managedContext.save() } catch let error as NSError { print("Error While Deleting Note: \(error.userInfo)") } } // MARK: Code to Fetch New Data From The DB and Reload Table. let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: noteEntity) do { records = try managedContext.fetch(fetchRequest) as! [Records] } catch let error as NSError { print("Error While Fetching Data From DB: \(error.userInfo)") } tableView.reloadData() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let person = records[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.font = UIFont(name: "Avenir", size: 16) cell.textLabel?.textColor = UIColor.red // set to any colour cell.layer.backgroundColor = UIColor.clear.cgColor cell.contentView.backgroundColor = UIColor.clear cell.textLabel?.text = person.value(forKeyPath: "name") as? String return cell } }
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. func userActionInitiated(hasTime: Bool, shouldPlay: Bool, isNotFinished: Bool) -> Player.Properties.PlaybackItem.Video.ActionInitiated { guard hasTime else { return .unknown } guard isNotFinished else { return .unknown } guard shouldPlay else { return .pause } return .play }
// // ProtocolNewsBarViewViewAccessStrategy.swift // f26View // // Created by David on 24/11/2017. // Copyright © 2017 com.smartfoundation. All rights reserved. // import UIKit /// Defines a class which provides a strategy for accessing the NewsBarView view public protocol ProtocolNewsBarViewViewAccessStrategy { // MARK: - Methods }
// // SettingsKeys.swift // Shopping List // // Created by Alex Shillingford on 7/25/19. // Copyright © 2019 Lambda School. All rights reserved. // import Foundation extension String { static var initShoppingListKey = "ShouldInitializeShoppingList" }
// // Address.swift // // // Created by Liu Pengpeng on 2020/12/16. // import Foundation import Crypto101 import CryptoSwift import secp256k1 public struct Address: CustomStringConvertible { public enum Error: Swift.Error { case invalidAddress case invalidPublicKey case invalidPrivateKey case invalidSignature case invalidRecoveryID case internalError } var bytes: [UInt8] public init(_ content: String) throws { guard content.range(of: #"^0x[a-fA-F0-9]{64}$"#, options: .regularExpression) != nil else { throw Error.invalidAddress } bytes = Array(hex: content) } public init(_ pubkey: [UInt8]) throws { var uncompressedPubkey = pubkey if (pubkey.count != 64) { uncompressedPubkey = try Address.decompressPublicKey(pubkey) } bytes = uncompressedPubkey.sha3(.keccak256).suffix(20) } // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md public var description: String { let address = bytes.toHexString() let hash = address.data(using: .ascii)!.sha3(.keccak256).toHexString() return "0x" + zip(address, hash) .map { a, h -> String in switch (a, h) { case ("0", _), ("1", _), ("2", _), ("3", _), ("4", _), ("5", _), ("6", _), ("7", _), ("8", _), ("9", _): return String(a) case (_, "8"), (_, "9"), (_, "a"), (_, "b"), (_, "c"), (_, "d"), (_, "e"), (_, "f"): return String(a).uppercased() default: return String(a).lowercased() } } .joined() } static func decompressPublicKey(_ pubkey: [UInt8]) throws -> [UInt8] { let ctx = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))! defer { secp256k1_context_destroy(ctx) } var cPubkey = secp256k1_pubkey() var uncompressedKeyLen = 65 var uncompressedPubkey = [UInt8](repeating: 0, count: uncompressedKeyLen) guard secp256k1_ec_pubkey_parse(ctx, &cPubkey, pubkey, pubkey.count) == 1, secp256k1_ec_pubkey_serialize(ctx, &uncompressedPubkey, &uncompressedKeyLen, &cPubkey, UInt32(SECP256K1_EC_UNCOMPRESSED)) == 1 else { throw Error.internalError } uncompressedPubkey.remove(at: 0) return uncompressedPubkey } } extension Address: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.bytes == rhs.bytes } }
// // NavigationBar.swift // MarketKulry // // Created by 신민희 on 2021/06/25. // import UIKit class NavigationBar: UINavigationItem { let markBackbarbutton = UIBarButtonItem(image: (UIImage(systemName: "bookmark")?.withTintColor(.lightGray, renderingMode: .alwaysOriginal)), style: UIBarButtonItem.Style.plain, target: self, action: #selector(handleBarButton(_:))) let cartBackbarbutton = UIBarButtonItem(image: (UIImage(systemName: "cart")?.withTintColor(.lightGray, renderingMode: .alwaysOriginal)), style: UIBarButtonItem.Style.plain, target: self, action: #selector(handleBarButton(_:))) } extension NavigationBar { @objc func handleBarButton(_ sender: UIBarButtonItem) { } }
import UIKit class VectorImage: UIView { //frame ref incase the UI is resized, the asset can maintain its size var imageCGRectRef: CGRect? = nil; let keyId: String = UUID().uuidString override init(frame: CGRect) { super.init(frame: frame); //init references imageCGRectRef = frame; } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func reactSetFrame(frame: CGRect) { /* everytime content size changes, you will get its frame here. */ super.reactSetFrame(frame) self.frame = frame; } //RN prop native binding, pulls the asset and sets the UIImage and UIImageVIew frames //params array is an ordered string tuple @objc var params: [String] = [] { didSet { autoreleasepool{ #if targetEnvironment(simulator) let start = DispatchTime.now() #endif let name = params[0] if Bundle.main.url(forResource: name, withExtension: "svg") != nil { if let newImage = SVGKImage.init(named: name + ".svg", withCacheKey: keyId.replacingOccurrences(of: "-", with: "")) { let size = Double(params[1]) ?? 400 //make the default an abviously wrong value for quick diagnosis on the UI let color = params[2] let aspectW = Double(params[3]) ?? 1 //if this is missing make the aspect something that is obviously wrong on the UI let aspectH = Double(params[4]) ?? 8 //if this is missing make the aspect something that is obviously wrong on the UI let outerFrame = CGRect(x: 0, y: 0, width: size, height: size) let svgFrame = getSVGAspectCGRect(size: size, aspW: aspectW, aspH: aspectH) self.subviews.forEach { $0.removeFromSuperview() } if let vectorBox = SVGKFastImageView.init(svgkImage: newImage) { if(color.count > 0) {vectorBox.setTintColor(color: hexToUIColor(hex: color))} vectorBox.frame = svgFrame self.addSubview(vectorBox) self.frame = outerFrame #if targetEnvironment(simulator) let end = DispatchTime.now() let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds let timeInterval = "Render time: " + String(Double(nanoTime) / 1_000_000) + "ms" print("------------------>>>>> VectorImage Params: ", name, size, color, aspectW, aspectH, timeInterval) #endif } } else { #if targetEnvironment(simulator) print("--------->>>>> Found SVG, failed to init:", params[0], params[1], params[2], params[3], params[4]) #endif } } else { #if targetEnvironment(simulator) //It is a programming error to call for an SVG that has not been added to Xcode fatalError("This SVG Icon was not found in Xcode: " + name) #endif } } } } private func getSVGAspectCGRect(size: Double, aspW: Double, aspH: Double) -> CGRect { let aspectRatio = aspW / aspH return aspW > aspH ? CGRect(x: 0, y: (size - size / aspectRatio) / 2, width: size, height: size / aspectRatio) : CGRect(x: (size - size * aspectRatio) / 2, y: 0, width: size * aspectRatio, height: size) } private func hexToUIColor(hex: String) -> UIColor { let rgb = buildCGFloatRGB(hex: hex) return UIColor(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: CGFloat(1)) } private func buildCGFloatRGB(hex: String) -> [CGFloat] { let nHex = hex.replacingOccurrences(of: "#", with: "") if(nHex.count == 3) {return [hexToCGFloat(hexPart: nHex[0 ..< 1]), hexToCGFloat(hexPart: nHex[1 ..< 2]), hexToCGFloat(hexPart: nHex[2 ..< 3])]} return [hexToCGFloat(hexPart: nHex[0 ..< 2]), hexToCGFloat(hexPart: nHex[2 ..< 4]), hexToCGFloat(hexPart: nHex[4 ..< 6])] } private func hexToCGFloat(hexPart: String) -> CGFloat { if let hexInt = Int(hexPart.count == 1 ? hexPart + "" + hexPart : hexPart, radix: 16) { return CGFloat(Float(hexInt) / 255.0) } else { return CGFloat(0); } } } extension SVGKImageView { func setTintColor(color: UIColor) { if self.image != nil && self.image.caLayerTree != nil { changeFillColorRecursively(sublayers: self.image.caLayerTree.sublayers, color: color) } } private func changeFillColorRecursively(sublayers: [AnyObject]?, color: UIColor) { if let sublayers = sublayers { for layer in sublayers { if let l = layer as? CAShapeLayer { if l.strokeColor != nil { l.strokeColor = color.cgColor } if l.fillColor != nil { l.fillColor = color.cgColor } } if let l = layer as? CALayer, let sub = l.sublayers { changeFillColorRecursively(sublayers: sub, color: color) } } } } }
// // ViewController.swift // TrueFalseStarter // // Created by Pasan Premaratne on 3/9/16. // Copyright © 2016 Treehouse. All rights reserved. // import UIKit import GameKit import AudioToolbox import AVFoundation class ViewController: UIViewController { @IBOutlet weak var playAgainButton: UIButton! @IBOutlet weak var questionField: UILabel! @IBOutlet weak var choice1: UIButton! @IBOutlet weak var choice2: UIButton! @IBOutlet weak var choice3: UIButton! @IBOutlet weak var choice4: UIButton! @IBOutlet weak var timer: UILabel! let correctSoundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("correct", ofType: "wav")!) let wrongSoundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("wrong", ofType: "wav")!) var audioPlayer = AVAudioPlayer() var audioPlayer2 = AVAudioPlayer() var indexOfSelectedQuestion: Int = 0 var choices: [UIButton] = [] var usedQuestions: [Int] = [] var usedOptions: [Int] = [] var settings = GameSettingsModel() let questionSet = triviaQuestions var gameTimer = NSTimer() var timerCounter = 15 override func viewDidLoad() { super.viewDidLoad() choices = [choice1,choice2, choice3, choice4] loadGameStartSound() // Start game playGameStartSound() displayQuestion() displayAnswerOptions() startTimer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func startTimer(){ //Starts the timer sets the decrement count to 1 and sets the text of the timer label gameTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) timer.text = String ("Timer: \(timerCounter)") } func updateTimer(){ //Decrements timer by count by 1 timerCounter = timerCounter - 1 timer.text = String("Timer: \(timerCounter)") //If timer runs out stop the timer and display the right answer if timerCounter == 0{ stopTimer() setGameScreen(sound: audioPlayer2, setQuetionFieldText: "Sorry! You ran out of time the correct answer was ", setDelayTime: 3, isWrongAnswer: true) settings.questionsAsked += 1 } } func stopTimer(){ //Stops and resets timer ot 15 seconds gameTimer.invalidate() timerCounter = 15 timer.text = String("Timer: \(timerCounter)") } func generateRandomNumber(upperBound upperBound:Int)->Int{ //Creates and returns a random number let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(upperBound) return randomNumber } func displayQuestion() { //Generates a random number to select a question that has not been used yet. If a question that has been //used is selected it will generate a new one until that is not the case indexOfSelectedQuestion = generateRandomNumber(upperBound: questionSet.count) while usedQuestions.contains(indexOfSelectedQuestion){ indexOfSelectedQuestion = generateRandomNumber(upperBound: questionSet.count) } usedQuestions.append(indexOfSelectedQuestion) let questionDictionary = questionSet[indexOfSelectedQuestion] questionField.text = questionDictionary.question playAgainButton.hidden = true } func displayAnswerOptions(){ let selectedQuestionDict = questionSet[indexOfSelectedQuestion] let options: [String] = ["answer","choice2","choice3","choice4"] var randomNumber = generateRandomNumber(upperBound: options.count) usedOptions.append(randomNumber) //Cycles through the number of choices in the choices array and randomly orders the choice options //on the choice buttons so that they are dynamically placed and not in the same spot every time for i in 0..<choices.count{ choices[i].setTitle(selectedQuestionDict.getRandomChoice(randomNumber), forState: UIControlState.Normal) randomNumber = generateRandomNumber(upperBound: options.count) //If an randomly selected option is already displayed on a choice button select a different one until //that is not the case or until all the choices have been used while usedOptions.contains(randomNumber)&&usedOptions.count != choices.count{ randomNumber = generateRandomNumber(upperBound: options.count) } //Add used choices to the array usedOptions.append(randomNumber) } //Clear the used choices array for the next question usedOptions = [] } func displayScore() { // Hide the answer buttons for choice in choices{ choice.hidden = true } // Display play again button playAgainButton.hidden = false questionField.text = "Way to go!\nYou got \(settings.correctQuestions) out of \(settings.questionsPerRound) correct!" } @IBAction func checkAnswer(sender: UIButton) { // Increment the questions asked counter settings.questionsAsked += 1 //If selected choice button text matches the correct answer text then display correct game screen if not display //the incorrect selection game screen if (sender.titleLabel!.text == getCorrectAnswer()) { stopTimer() setGameScreen(sound: audioPlayer, setQuetionFieldText: "Correct!", setDelayTime: 2, isWrongAnswer: false) settings.correctQuestions += 1 } else { stopTimer() setGameScreen(sound: audioPlayer2, setQuetionFieldText: "Sorry! The correct answer was actually: ", setDelayTime: 3, isWrongAnswer: true) } } func nextRound() { if settings.questionsAsked == settings.questionsPerRound { // Game is over displayScore() timer.hidden = false timer.text = " " } else { // Continue game startTimer() displayQuestion() displayAnswerOptions() } } func setGameScreen(sound sound:AVAudioPlayer, setQuetionFieldText:String, setDelayTime:Int, isWrongAnswer: Bool){ //Sets the game sound and text labels based on whether or not the correct or wrong answer was selected sound.play() if(isWrongAnswer == false){ questionField.text = "\(setQuetionFieldText)" }else { questionField.text = "\(setQuetionFieldText) \(getCorrectAnswer())" } loadNextRoundWithDelay(seconds: setDelayTime) } func getCorrectAnswer()->String{ //Gets the correct answer for selected question and returns it let selectedQuestionDict = questionSet[indexOfSelectedQuestion] let correctAnswer = selectedQuestionDict.answer return correctAnswer } @IBAction func playAgain() { // Show the answer buttons for choice in choices{ choice.hidden = false } //Resets these fields settings.questionsAsked = 0 settings.correctQuestions = 0 nextRound() } // MARK: Helper Methods func loadNextRoundWithDelay(seconds seconds: Int) { // Converts a delay in seconds to nanoseconds as signed 64 bit integer let delay = Int64(NSEC_PER_SEC * UInt64(seconds)) // Calculates a time value to execute the method given current time and delay let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, delay) // Executes the nextRound method at the dispatch time on the main queue dispatch_after(dispatchTime, dispatch_get_main_queue()) { self.nextRound() } } func loadGameStartSound() { let pathToSoundFile = NSBundle.mainBundle().pathForResource("GameSound", ofType: "wav") let soundURL = NSURL(fileURLWithPath: pathToSoundFile!) AudioServicesCreateSystemSoundID(soundURL, &settings.gameSound) do{ try audioPlayer = AVAudioPlayer(contentsOfURL: correctSoundURL, fileTypeHint: nil) try audioPlayer2 = AVAudioPlayer(contentsOfURL: wrongSoundURL, fileTypeHint: nil) }catch{ print("SOUND ERROR") } audioPlayer.prepareToPlay() audioPlayer2.prepareToPlay() } func playGameStartSound() { AudioServicesPlaySystemSound(settings.gameSound) } }
// // TransactionCardGeneralCell.swift // WavesWallet-iOS // // Created by rprokofev on 06/03/2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import UIKit import Extensions final class TransactionCardGeneralCell: UITableViewCell, Reusable { struct Model { enum Info { case balance(BalanceLabel.Model) case descriptionLabel(String) case status(_ percent: String, status: String?) } let image: UIImage let title: String let info: Info } @IBOutlet private var balanceLabel: BalanceLabel! @IBOutlet private var titleLabel: UILabel! @IBOutlet private var descriptionLabel: UILabel! @IBOutlet private var stackViewLabel: UIStackView! @IBOutlet private var transactionImageView: TransactionImageView! override func awakeFromNib() { super.awakeFromNib() } private func showInfo(_ info: Model.Info) { switch info { case .balance(let balance): balanceLabel.update(with: balance) balanceLabel.isHidden = false descriptionLabel.isHidden = true case .descriptionLabel(let text): let attrString = NSMutableAttributedString(string: text, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 22, weight: .bold)]) descriptionLabel.attributedText = attrString balanceLabel.isHidden = true descriptionLabel.isHidden = false case .status(let percent, let status): let attrString = NSMutableAttributedString(string: percent, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 22, weight: .bold)]) if let status = status { attrString.append(NSMutableAttributedString(string: status, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 22, weight: .regular)])) } descriptionLabel.attributedText = attrString balanceLabel.isHidden = true descriptionLabel.isHidden = false } } } // MARK: ViewConfiguration extension TransactionCardGeneralCell: ViewConfiguration { func update(with model: TransactionCardGeneralCell.Model) { titleLabel.text = model.title transactionImageView.update(with: model.image) showInfo(model.info) } }
import Foundation protocol SignUpRepositoryDependencyProviding { func provideDataTaskBuilder() -> SessionDataTaskBuilding func provideDatabase() -> ManagedObjectProviding func provideAuthService() -> AuthServiceProtocol }
// // LoadingBarView.swift // 08-anims // // Created by Angel Miranda on 08/07/20. // Copyright © 2020 Angel Miranda. All rights reserved. // import SwiftUI struct LoadingBarView: View { @State private var isLoading = false var body: some View { ZStack{ Text("CARGANDO") .font(.system(.headline, design: .rounded)) .bold() .offset(x:0, y: -30) RoundedRectangle(cornerRadius: 4) .stroke(Color(.systemGray6), lineWidth: 5) .frame(width: 300, height: 4) RoundedRectangle(cornerRadius: 4) .stroke(Color(.systemGreen), lineWidth: 5) .frame(width: 50, height: 4) .offset(x: isLoading ? 125 : -125, y: 0) .animation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) .onAppear(){ self.isLoading = true } } /* ZStack{ Path{ path in path.move(to: CGPoint(x: 50, y: 400)) path.addLine(to: CGPoint(x: 350, y: 400)) } .stroke(Color(.systemGray5), style: StrokeStyle(lineWidth: 10.0, lineCap: .round, lineJoin: .round)) Path{ path in path.move(to: CGPoint(x: 50, y: 400)) path.addLine(to: CGPoint(x: 100, y: 400)) } .stroke(Color(.systemGreen), style: StrokeStyle(lineWidth: 10.0, lineCap: .round, lineJoin: .round)) .offset(x: isLoading ? 250 : 0, y:0) .animation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) .onAppear(){ self.isLoading = true } } */ } } struct LoadingBarView_Previews: PreviewProvider { static var previews: some View { LoadingBarView() } }
// // ViewController.swift // imageUpload // // Created by Mohammed Altoobi on 9/13/18. // Copyright © 2018 Mohammed Altoobi. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController{ var imagePicker:UIImagePickerController! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var ageField: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func takeImage(_ sender: Any) { imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.isEditing = true imagePicker.setEditing(true, animated: true) imagePicker.sourceType = .photoLibrary //imagePicker.sourceType = .camera present(imagePicker, animated: true, completion: nil) } @IBAction func uploadImage(_ sender: Any) { self.showActivityIndicator() //Post URL let url = "http://localhost:8888/swift/image-upload/upload.php" //Getting text from textFiled! let name = nameField.text! let age = ageField.text! //Call Parameters let params: Parameters = ["name": name,"age": age] //Checking image place holder let image = #imageLiteral(resourceName: "placeholder-image") //Checking if empty name or age fileds if name.isEmpty || age.isEmpty{ self.hideActivityIndicator() myAlert(title: "Error", msg: "Make sure you enter all the required information!") } //Checking if image is not selected!! else if imageView.image == image { self.hideActivityIndicator() myAlert(title: "Error", msg: "Make sure you choose an image!") }else{ let imageToUpload = self.imageView.image! Alamofire.upload(multipartFormData: { (multipartFormData) in multipartFormData.append(UIImageJPEGRepresentation(imageToUpload, 0.8)!, withName: "image", fileName: self.generateBoundaryString(), mimeType: "image/jpeg") for (key, value) in params { multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) } }, to:url,headers:nil) { (result) in switch result { case .success(let upload,_,_ ): upload.uploadProgress(closure: { (progress) in //Print progress self.showActivityIndicator() }) upload.responseJSON { response in //print response.result if let result = response.result.value { //Calling response from API let message = (result as AnyObject).value(forKey: "message") as! String let status = (result as AnyObject).value(forKey: "status") as! String //Case Success if status == "1" { self.hideActivityIndicator() print("Your Results are ====> ",result) self.myAlert(title: "Data Upload", msg: message) self.imageView.image = #imageLiteral(resourceName: "placeholder-image") self.nameField.text = "" self.ageField.text = "" }else{ self.hideActivityIndicator() self.myAlert(title: "Error Uploading", msg: message) } } } case .failure(let encodingError): print(encodingError) break } } } } } //image Picker Extension extension ViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{ func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { //picker.showsCameraControls = true imageView.image = info[UIImagePickerControllerEditedImage] as? UIImage picker.dismiss(animated:true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } } //Another Extension extension ViewController{ func myAlert(title:String, msg:String) { let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert) let okayAction = UIAlertAction(title: "Close", style: .default, handler: nil) alertController.addAction(okayAction) present(alertController, animated: true, completion: nil) } func generateBoundaryString() -> String { return "Boundary-\(NSUUID().uuidString).jpeg" } } //Call ActivityIndicator extension UIViewController { func showActivityIndicator() { let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) activityIndicator.backgroundColor = UIColor(red:0.16, green:0.17, blue:0.21, alpha:1) activityIndicator.layer.cornerRadius = 6 activityIndicator.center = view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = .whiteLarge activityIndicator.startAnimating() //UIApplication.shared.beginIgnoringInteractionEvents() activityIndicator.tag = 100 // 100 for example // before adding it, you need to check if it is already has been added: for subview in view.subviews { if subview.tag == 100 { print("already added") return } } view.addSubview(activityIndicator) } func hideActivityIndicator() { let activityIndicator = view.viewWithTag(100) as? UIActivityIndicatorView activityIndicator?.stopAnimating() // I think you forgot to remove it? activityIndicator?.removeFromSuperview() //UIApplication.shared.endIgnoringInteractionEvents() } }
// // Updater.swift // MuseumApp // // Created by James Payne on 12/12/15. // Copyright © 2015 James Payne. All rights reserved. // import Foundation import RealmSwift import ObjectMapper import Alamofire struct BaseURLs { static let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] static let baseURL = getBaseURL() } func getBaseURL() -> String { if let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] { return dict["com.payne.ios.baseurl"] as! String } return "" // Put a better error indicator here? Throw exception. } func initUpdateRealm() { // Set up the realm /* Purge the realm file for testing purposes do { print(Realm.Configuration.defaultConfiguration.path!) try NSFileManager.defaultManager().removeItemAtPath(Realm.Configuration.defaultConfiguration.path!) } catch { // Pass } // */ let realm: Realm! // Get a new Realm instance do { realm = try Realm() } catch { // If the realm cannot be created, delete the realm file print("Could not load the realm, so old realm was removed and data will be recreated.") print("App should be removed to clear any old existing files.") do { print(Realm.Configuration.defaultConfiguration.path!) try NSFileManager.defaultManager().removeItemAtPath(Realm.Configuration.defaultConfiguration.path!) } catch { // Pass } // Retry getting the realm realm = try! Realm() } // Create a new metadata instance it none exists if (realm.objectForPrimaryKey(Metadata.self, key: 0) == nil) { try! realm.write { realm.create(Metadata.self, value: ["revision": 0], update: true) } } let metadata = realm.objectForPrimaryKey(Metadata.self, key: 0) //* Alamofire code for updating the app let URL = "\(BaseURLs.baseURL)update?revision=\(metadata!.revision)" print(URL) Alamofire.request(.GET, URL).responseJSON() { response in switch response.result { case .Success(let data): let json = data as! NSDictionary handleUpdateJSON(json) case .Failure(let error): print("Request failed with error: \(error)") } } } func handleUpdateJSON(json: NSDictionary) { // New realm as this is called asyncronously in an Alamofire response handling closure let realm = try! Realm() print("UPDATING FROM JSON: \(json)") // Arrays of new model objects to up added or updated var information = [GeneralInformation]() var viewControllers = [ViewControllerData]() var exhibitSections = [ExhibitSection]() var resources = [Resource]() var events = [Event]() var exhibits = [Exhibit]() // Array of tasks that control resources that will be downloaded in the background var resourceDownloadTasks = [NSURLSessionTask]() let networkHandler = DownloadSessionDelegate.sharedInstance let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(SessionProperties.identifier) let backgroundSession = NSURLSession(configuration: configuration, delegate: networkHandler, delegateQueue: nil) // Create new models for non-dependate objects if let jsonInformations = json["information"] as? [NSDictionary] { for jsonInformation in jsonInformations { information.append(Mapper<GeneralInformation>().map(jsonInformation)!) } } if let jsonViewControllers = json["view_controllers"] as? [NSDictionary] { for jsonViewController in jsonViewControllers { viewControllers.append(Mapper<ViewControllerData>().map(jsonViewController)!) } } if let jsonExhibitSections = json["exhibit_sections"] as? [NSDictionary] { for jsonExhibitSection in jsonExhibitSections { exhibitSections.append(Mapper<ExhibitSection>().map(jsonExhibitSection)!) } } if let jsonResources = json["resources"] as? [NSDictionary] { for jsonResource in jsonResources { let resource = Mapper<Resource>().map(jsonResource)! resources.append(resource) if !(resource.url.isEmpty) { let url = NSMutableURLRequest(URL: NSURL(string: "\(BaseURLs.baseURL)resources/\(resource.url)")!) let downloadTask = backgroundSession.downloadTaskWithRequest(url) resource.taskIdentifier = downloadTask.taskIdentifier // Set taskIdentifier in Realm to match task when complete resourceDownloadTasks.append(downloadTask) } } } // Write non-dependant objects to the realm try! realm.write { for info in information { realm.add(info) } for viewController in viewControllers { realm.add(viewController) } for exhibitSection in exhibitSections { realm.add(exhibitSection) } for resource in resources { realm.add(resource) } } // Start all resource downloads for sessionTask in resourceDownloadTasks { sessionTask.resume() } // Create new models for dependant objects if let jsonEvents = json["events"] as? [NSDictionary] { for jsonEvent in jsonEvents { let event = Mapper<Event>().map(jsonEvent)! // Add the Resource object event.resource = realm.objectForPrimaryKey(Resource.self, key: event.resourceID) events.append(event) } } if let jsonExhibits = json["exhibits"] as? [NSDictionary] { for jsonExhibit in jsonExhibits { let exhibit = Mapper<Exhibit>().map(jsonExhibit)! // Add the ExhibitSection object exhibit.exhibitSection = realm.objectForPrimaryKey(ExhibitSection.self, key: exhibit.exhibitSectionID) // Add the ViewControllerData object exhibit.viewController = realm.objectForPrimaryKey(ViewControllerData.self, key: exhibit.viewControllerID) // Add the Resource object exhibit.resource = realm.objectForPrimaryKey(Resource.self, key: exhibit.resourceID) exhibits.append(exhibit) } } // Write dependant objects to the realm try! realm.write { for event in events { realm.add(event) } for exhibit in exhibits { realm.add(exhibit) } // Update revision value after update is complete realm.objectForPrimaryKey(Metadata.self, key: 0)?.revision = json["revision"] as! Int } } func uniqueFilename(custom: String) -> NSURL { // Guarentees uniqueness for the filename in the default document directory let uuid: CFUUIDRef = CFUUIDCreate(nil) let uuidString = CFUUIDCreateString(nil, uuid) return BaseURLs.directoryURL.URLByAppendingPathComponent("\(uuidString).\(custom)") } // Saves a temporary file that was downloaded in a background session to the local device func saveDownloadedFile(downloadTask: NSURLSessionDownloadTask, location: NSURL) { // New realm as this is called asyncronously in an Alamofire response handling closure let realm = try! Realm() let resources = realm.objects(Resource).filter("taskIdentifier = %@", downloadTask.taskIdentifier) if (resources.count > 0) { let resource = resources[0] let localPath = uniqueFilename(resource.url) // Move the temporary file to the permanant location try! NSFileManager.defaultManager().copyItemAtURL(location, toURL: localPath) // Update the realm to indicate that the was properly saved try! realm.write { resource.localPath = localPath.path! resource.taskIdentifier = 0 } } else { print("Faild to find matching resource for: \(downloadTask)") } }
// // CriticalMaps import CoreLocation import Foundation struct Ride: Hashable, Codable { let id: Int let slug: String? let title: String let description: String? let dateTime: Date let location: String? let latitude: Double let longitude: Double let estimatedParticipants: Int? let estimatedDistance: Double? let estimatedDuration: Double? let disabledReason: String? let disabledReasonMessage: String? } extension Ride { var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } var titleAndTime: String { let titleWithoutDate = title.removedDatePattern() return """ \(titleWithoutDate) \(dateTime.humanReadableDate) - \(dateTime.humanReadableTime) """ } var shareMessage: String { guard let location = location else { return titleAndTime } return """ \(titleAndTime) \(location) """ } } import MapKit extension Ride { func openInMaps(_ options: [String: Any] = [ MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDefault ]) { let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) mapItem.name = location mapItem.openInMaps(launchOptions: options) } }
// // HomeView.swift // TodoAll // // Created by Franklin Cruz on 28-10-20. // Copyright © 2020 S.Y.Soft. All rights reserved. // import SwiftUI struct HomeView: View { @ObservedObject var viewModel: TaskListViewModel @State var showCreateSheet = false var body: some View { NavigationView { TaskListView(viewModel: self.viewModel) .navigationBarTitle("My TODO", displayMode: .inline) .navigationBarItems( trailing: Button(action: {}) { Image(systemName: "plus.circle") .font(.title) .foregroundColor(Color(.systemTeal)) .onTapGesture { self.showCreateSheet.toggle() } } ) }.sheet(isPresented: self.$showCreateSheet, onDismiss: { self.viewModel.refresh() }, content: { CreateTaskView(viewModel: self.viewModel.getCreateViewModel(), presented: self.$showCreateSheet) }) } } struct HomeView_Previews: PreviewProvider { static var previews: some View { let mock = MockTaskService() let vm = TaskListViewModel(service: mock, userId: 1) HomeView(viewModel: vm) } }
// // PlayViewController.swift // PitchPerfect // // Created by Rafi Khan on 2017/05/31. // Copyright © 2017 Rafi Khan. All rights reserved. // import UIKit import AVFoundation class PlayViewController: UIViewController, AVAudioPlayerDelegate { @IBOutlet weak var stopButton: UIButton! var audioURL:URL! var audioPlayer:AVAudioPlayer! var audioEngine:AVAudioEngine! // Will need for special effects. var audioFile:AVAudioFile! // Will need for special effects. override func viewDidLoad() { super.viewDidLoad() do { try audioPlayer = AVAudioPlayer(contentsOf: audioURL) // try audioFile = AVAudioFile(forReading: audioURL) // audioEngine = AVAudioEngine() audioPlayer.delegate = self audioPlayer.numberOfLoops = 3 } catch let error as NSError { print("AudioPlayer error: \(error.localizedDescription)") } } override func viewDidAppear(_ animated:Bool) { enableStoppedVisuals() } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print("Stopped") if flag { enableStoppedVisuals() } } // MARK: Actions @IBAction func playFast(_ sender: UIButton) { // playWithSpeed(3.0) playAudio() } @IBAction func playSlow(_ sender: UIButton) { playWithSpeed(0.5) } @IBAction func goBack(_ sender: UIButton) { performSegue(withIdentifier: "backToRecording", sender: sender) } @IBAction func stopAudio(_ sender: UIButton) { audioPlayer.stop() enableStoppedVisuals() } // MARK: Helpers func playWithSpeed(_ speed: Float) { audioPlayer.stop() audioPlayer.enableRate = true audioPlayer.rate = speed playAudio() } func playAudio() { audioPlayer.volume = 1.0 audioPlayer.currentTime = 0.0 audioPlayer.prepareToPlay() audioPlayer.play() print("Playing...") stopButton.isEnabled = true } func enableStoppedVisuals() { stopButton.isEnabled = false } }
// // PhotoCollectionCellViewModel.swift // Flickr Digger // // Created by Ikjot Singh on 8/31/19. // . // import Foundation import UIKit class PhotoCollectionCellViewModel { var thumbnailImage : UIImage? let thumbnailImageUrl : String let originalImageUrl : String let name : String // Dependency Injection init(photoModel : PhotoModel) { let urlString = String(format: "https://farm%d.staticflickr.com/%@/%@_%@", photoModel.farm,photoModel.serverId,photoModel.photoId,photoModel.secretId) thumbnailImageUrl = urlString + "_t.jpg" originalImageUrl = urlString + ".jpg" name = photoModel.title } } class HomescreenViewModel { let service : APIServiceProtocol //MARK:- Weakely called property on view var reloadCollectionViewClosure : (()->())? var updateLoadingStatus : (()->())? var showAlertMessage : (()->())? var pushNewViewController : (()->())? var setNavigationDelegate : (()->())? var getImageView : (() -> UIImageView?)? var getImageViewFrameInTransitioningView : (() -> CGRect?)? //MARK:- Variables var fetchedDetailModel : Photos? var latestPage : Double = 1 var currentSearchTerm : String? var selectedIndexPath : IndexPath? private var cellViewModels : [PhotoCollectionCellViewModel] = [PhotoCollectionCellViewModel]() { didSet { self.reloadCollectionViewClosure?() } } var itemsInRow : Int { get { if let val = UserDefaults.standard.value(forKey: "itemsInRow") as? Int{ return val }else{ return 3 } } set(val) { UserDefaults.standard.setValue(val, forKey: "itemsInRow") self.reloadCollectionViewClosure?() } } var numberOfItems : Int { return cellViewModels.count } var islastPage : Bool = false { didSet { self.reloadCollectionViewClosure?() } } var pushViewController : PhotoDetailViewController? { didSet{ self.pushNewViewController?() } } var isCVLoadingMoreItems : Bool = false var viewIsLoading : Bool = false { didSet { self.updateLoadingStatus?() } } var alertMessage : String? { didSet { self.showAlertMessage?() } } var navigationDelegate : ExpandTransitionController? { didSet { self.setNavigationDelegate?() } } //MARK:- Methods init(apiService : APIServiceProtocol = APIService() ) { self.service = apiService } func getPhotoViewModelAtIndexPath(indexPath : IndexPath) -> PhotoCollectionCellViewModel? { if cellViewModels.count > indexPath.row{ return cellViewModels[indexPath.row] }else{ return nil } } func loadNextPage() { guard let searchStr = currentSearchTerm else{ return } if latestPage != fetchedDetailModel?.pages { self.isCVLoadingMoreItems = true fetchPhotosForKeyword(keyword: searchStr, forPage: latestPage+1) }else{ islastPage = true } } func pushDetailViewControllerForIndex(index:IndexPath){ selectedIndexPath = index let detailVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "photoDetail") as! PhotoDetailViewController if cellViewModels.count > index.row { detailVC.photoModel = cellViewModels[index.row] } detailVC.viewModel.transitionController.sourceDelegate = self detailVC.viewModel.transitionController.destinationDelegate = detailVC.viewModel self.navigationDelegate = detailVC.viewModel.transitionController self.pushViewController = detailVC } func fetchPhotosForKeyword(keyword:String){ self.viewIsLoading = true islastPage = false cellViewModels.removeAll() fetchPhotosForKeyword(keyword: keyword, forPage:1) } func fetchPhotosForKeyword(keyword:String, forPage page: Double){ currentSearchTerm = keyword latestPage = page service.fetchPhotosForSearchKeyword(keyword: keyword, forPage: page) { [weak self] (success, photos, error) in self?.isCVLoadingMoreItems = false if let error = error { self?.islastPage = true self?.alertMessage = error.rawValue } else { if photos?.pages == self?.latestPage { self?.islastPage = true } if photos?.pages == 0 { self?.islastPage = true self?.alertMessage = "No results found" } self?.fetchedDetailModel = photos if let array = photos?.photo { self?.processFetchedPhotos(arrPhotos:array) }else{ self?.islastPage = true self?.alertMessage = "Some unexpected error Occured" } } self?.viewIsLoading = false } } func processFetchedPhotos(arrPhotos: [PhotoModel]) { let newPhotoArray = arrPhotos.map({ (photo) -> PhotoCollectionCellViewModel in return PhotoCollectionCellViewModel(photoModel: photo) }) self.cellViewModels += newPhotoArray } } // MARK:- Animator Delegate Methods extension HomescreenViewModel : ExpandAnimatorDelegate { func transitionWillBeginWith(ExpandAnimator: ExpandAnimator) { } func referenceImageViewForAnimation(for zoomAnimator: ExpandAnimator) -> UIImageView? { return self.getImageView?() } func transitionDidFinishWith(ExpandAnimator: ExpandAnimator) { } func referenceImageViewFrameInTransitioningView(for ExpandAnimator: ExpandAnimator) -> CGRect? { return self.getImageViewFrameInTransitioningView?() } }
// // NoteDetailViewController.swift // RxNotes // // Created by Dennis Örnberg on 2018-02-25. // Copyright © 2018 Dennis Örnberg. All rights reserved. // import RxSwift import RxCocoa import UIKit class NoteDetailViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var doneButton: UIBarButtonItem! var index: Int? let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .never navigationController?.navigationBar.barTintColor = UIColor(red: 112/255, green: 130/255, blue: 56/255, alpha: 1) navigationController?.navigationBar.tintColor = UIColor.white textView.becomeFirstResponder() // A binding from the model to the textview is unnecessary, just set the text once. if let index = index { textView.text = Model.shared.dataSource.value[index] } textView.rx.text.orEmpty .subscribe { event in if let index = self.index { Model.shared.dataSource.value[index] = event.element ?? "" } else { Model.shared.dataSource.value.append(event.element ?? "") self.index = Model.shared.dataSource.value.count - 1 } } .disposed(by: disposeBag) doneButton.rx.tap .subscribe { event in self.textView.resignFirstResponder() self.dismiss(animated: true) } .disposed(by: disposeBag) } }
// // FavoriteViewController.swift // PersistenceLabProj // // Created by Kevin Natera on 10/1/19. // Copyright © 2019 Kevin Natera. All rights reserved. // import UIKit class FavoriteViewController: UIViewController { @IBOutlet weak var favoritesCollectionOutlet: UICollectionView! var favorites = [Photo]() { didSet { favoritesCollectionOutlet.reloadData() } } private func loadData(){ do { favorites = try FavoritesPersistenceHelper.manager.getFavorites() } catch { print(error) } } override func viewDidLoad() { super.viewDidLoad() setUpProtocols() loadData() } override func viewWillAppear(_ animated: Bool) { loadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let detailVC = segue.destination as? FavoriteDetailViewController else { fatalError() } if let cell = sender as? PhotoCollectionViewCell, let indexPath = self.favoritesCollectionOutlet.indexPath(for: cell) { detailVC.favPic = favorites[indexPath.row] } } private func setUpProtocols() { favoritesCollectionOutlet.dataSource = self favoritesCollectionOutlet.delegate = self } } extension FavoriteViewController : UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return favorites.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let favPhoto = favorites[indexPath.row] let cell = favoritesCollectionOutlet.dequeueReusableCell(withReuseIdentifier: "favPhoto", for: indexPath) as! PhotoCollectionViewCell cell.configureCell(photo: favPhoto) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 150, height: 150) } }
public protocol SnapOnboardingDelegate: class { func onboardingWillAppear() func termsAndConditionsTapped() func privacyPolicyTapped() func enableLocationServicesTapped() func locationServicesInstructionsTapped() func facebookSignupTapped() func instagramSignupTapped() func continueAsLoggedInUserTapped() func skipLoginTapped() func logoutFromCurrentAccountTapped() }
// // NewButtonAnimate.swift // UikitAnimation // // Created by Andrei Cojocaru on 26.05.2021. // import Foundation import UIKit class NewButtonAnimate: UIButton { var widtH : NSLayoutConstraint! var height: NSLayoutConstraint! override init(frame: CGRect) { super.init(frame: frame) } init(title:String) { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false widtH = widthAnchor.constraint(equalToConstant: 100) height = heightAnchor.constraint(equalToConstant: 30) widtH.isActive = true height.isActive = true setupButon(title: title) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupButon(title:String) { titleLabel?.text = title titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .light) backgroundColor = .red layer.cornerRadius = 5 addTarget(self, action: #selector(touchUp), for: .touchDown) addTarget(self, action: #selector(touchIn), for: .touchUpInside) } @objc func touchUp() { widtH.isActive = false widtH.constant = 50 layer.cornerRadius = 10 alpha = 0.2 widtH.isActive = true height.isActive = false height.constant = 50 height.isActive = true UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: .curveEaseInOut) { self.superview?.layoutIfNeeded() } } @objc func touchIn() { widtH.isActive = false widtH.constant = 100 widtH.isActive = true layer.cornerRadius = 5 alpha = 1 height.isActive = false height.constant = 30 height.isActive = true UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: .curveEaseInOut) { self.superview?.layoutIfNeeded() } } }
// // UtilAlgorithm.swift // KLineView // // Created by 程守斌 on 2019/3/1. // import Foundation // 各指标算法 public class UtilAlgorithm: NSObject { /// 计算结果并赋值到model的计算属性 /// /// - Parameter models: 数据集 static public func calculationResults(models:[KLineModel]){ guard models.count > 0 else { return } /// 分时均线 let aveLineArray = calculateAvePrice(datas: models) for i in 0 ..< models.count { models[i].avePrice = aveLineArray[i] } /// SMA let smaLine1Array = calculateSMA(dayCount: KLineConst.kSMALine1Days, datas: models) let smaLine2Array = calculateSMA(dayCount: KLineConst.kSMALine2Days, datas: models) for i in 0 ..< models.count { models[i].smaLine1 = smaLine1Array[i] models[i].smaLine2 = smaLine2Array[i] } /// EMA let emaLine1Array = calculateEMA(dayCount: KLineConst.kEMALine1Days, datas: models) let emaLine2Array = calculateEMA(dayCount: KLineConst.kEMALine2Days, datas: models) for i in 0 ..< models.count { models[i].emaLine1 = emaLine1Array[i] models[i].emaLine2 = emaLine2Array[i] } /// BOLL let bollSet = calculateBOLL(dayCount: KLineConst.kBOLLDayCount, k: KLineConst.kBOLL_KValue, datas: models) let bollArray = bollSet.0 let ubArray = bollSet.1 let lbArray = bollSet.2 for i in 0 ..< models.count { models[i].boll = bollArray[i] models[i].ub = ubArray[i] models[i].lb = lbArray[i] } /// MACD let macdSet = calculateMACD(p1: KLineConst.kMACD_P1, p2: KLineConst.kMACD_P2, p3: KLineConst.kMACD_P3, datas: models) let difArray = macdSet.0 let deaArray = macdSet.1 let barArray = macdSet.2 for i in 0 ..< models.count { models[i].dif = difArray[i] models[i].dea = deaArray[i] models[i].bar = barArray[i] } /// KDJ let kdjSet = calculateKDJ(p1: KLineConst.kKDJ_P1, p2: KLineConst.kKDJ_P2, p3: KLineConst.kKDJ_p3, datas: models) let kArray = kdjSet.0 let dArray = kdjSet.1 let jArray = kdjSet.2 for i in 0 ..< models.count { models[i].k = kArray[i] models[i].d = dArray[i] models[i].j = jArray[i] } /// RSI let line1Array = calculateRSI(dayCount: KLineConst.kRSILine1DayCount, datas: models) let line2Array = calculateRSI(dayCount: KLineConst.kRSILine2DayCount, datas: models) let line3Array = calculateRSI(dayCount: KLineConst.kRSILine3DayCount, datas: models) for i in 0 ..< models.count { models[i].rsiLine1 = line1Array[i] models[i].rsiLine2 = line2Array[i] models[i].rsiLine3 = line3Array[i] } } } //MARK: - 算法 (fileprivate) extension UtilAlgorithm { /// 分时均线 /// /// - Parameter datas: 数据集 /// - Returns: 均值数据 fileprivate static func calculateAvePrice(datas:[KLineModel]) -> [Double] { var result = [Double]() var totalAmount = 0.0 var totalVolume = 0.0 for i in 0 ..< datas.count { let model = datas[i] totalVolume += model.volume totalAmount += model.close * model.volume let avePrice = totalAmount / totalVolume result.append(avePrice) } return result } /// SMA(简单均线) /// /// - Parameters: /// - dayCount: 天数 /// - data: 数据集 /// - Returns: 均值数据 fileprivate static func calculateSMA(dayCount: Int, datas: [KLineModel]) -> [Double] { let dayCount = dayCount - 1 var result = [Double]() for i in 0 ..< datas.count { if (i < dayCount) { result.append(Double.nan) continue } var sum: Double = 0.0 for j in 0 ..< dayCount { sum = sum + datas[i - j].close } result.append(abs(sum / Double(dayCount))) } return result } /// EMA(指数移动平均数) /// EMA(N)=2/(N+1)*(close-昨日EMA)+昨日EMA /// /// - Parameters: /// - dayCount: 天数 /// - datas: 数据集 /// - Returns: 均值数据 fileprivate static func calculateEMA(dayCount: Int, datas: [KLineModel]) -> [Double] { var yValues = [Double]() var prevEma:Double = 0.0 //前一个ema for (index, model) in datas.enumerated() { let close = model.close var ema: Double = 0.0 if index > 0 { ema = prevEma + (close - prevEma) * 2 / (Double(dayCount) + 1) } else { ema = close } yValues.append(ema) prevEma = ema } return yValues } /// BOLL(布林轨道算法) /// 计算公式 /// 中轨线=N日的移动平均线 /// 上轨线=中轨线+两倍的标准差 /// 下轨线=中轨线-两倍的标准差 /// 计算过程 /// (1)计算MA /// MA=N日内的收盘价之和÷N /// (2)计算标准差MD /// MD=平方根(N)日的(C-MA)的两次方之和除以N /// (3)计算MB、UP、DN线 /// MB=(N)日的MA /// UP=MB+k×MD /// DN=MB-k×MD /// (K为参数,可根据股票的特性来做相应的调整,一般默认为2) /// - Parameters: /// - dayCount: 天数 /// - k: 参数值 /// - datas: 数据集 /// - Returns: (BOLL,UB,LB) fileprivate static func calculateBOLL(dayCount:Int, k:Int=2 ,datas:[KLineModel]) -> ([Double],[Double],[Double]) { var bollValues = [Double]() var ubValues = [Double]() var lbValues = [Double]() // n天标准差 var mdArray = calculateBOLLSTD(dayCount: dayCount, datas: datas) // n天均值 var mbArray = calculateSMA(dayCount: dayCount, datas: datas) for i in 0 ..< datas.count { let md = mdArray[i] let mb = mbArray[i] let ub = mb + Double(k) * md let lb = mb - Double(k) * md bollValues.append(mbArray[i]) ubValues.append(ub) lbValues.append(lb) } return (bollValues,ubValues,lbValues) } /// 计算布林线中的MA平方差 /// /// - Parameters: /// - dayCount: 天数 /// - datas: 数据集 /// - Returns: 结果 fileprivate static func calculateBOLLSTD(dayCount:Int, datas:[KLineModel]) -> [Double] { var mdArray = [Double]() // n天均值 var maArray = calculateSMA(dayCount: dayCount, datas: datas) for index in 0 ..< datas.count { if index + 1 >= dayCount { var dx:Double = 0.0 for i in stride(from: index, through: index + 1 - dayCount, by: -1) { dx += pow(datas[i].close - maArray[i], 2) } var md = dx / Double(dayCount) md = pow(md, 0.5) mdArray.append(md) }else{ var dx:Double = 0.0 for i in stride(from: index, through: 0, by: -1) { dx += pow(datas[i].close - maArray[i], 2) } var md = dx / Double(dayCount) md = pow(md, 0.5) mdArray.append(md) } } return mdArray } /// MACD(平滑异同移动平均线) /// /// - Parameters: /// - p1: 天数1 (12) /// - p2: 天数2 (26) /// - p3: 天数3 (9) /// - datas: 数据集 /// - Returns: ([DIF],[DEA],[BAR]) fileprivate static func calculateMACD(p1:Int, p2:Int, p3:Int, datas:[KLineModel]) -> ([Double],[Double],[Double]){ var difArray = [Double]() var deaArray = [Double]() var barArray = [Double]() //EMA(p1)=2/(p1+1)*(C-昨日EMA)+昨日EMA; let p1EmaArray = calculateEMA(dayCount: p1, datas: datas) //EMA(p2)=2/(p2+1)*(C-昨日EMA)+昨日EMA; let p2EmaArray = calculateEMA(dayCount: p2, datas: datas) //昨日dea var prevDea:Double = 0.0 for i in 0 ..< datas.count { //DIF=今日EMA(p1)- 今日EMA(p2) let dif = p1EmaArray[i] - p2EmaArray[i] //dea(p3)=2/(p3+1)*(dif-昨日dea)+昨日dea; let dea = prevDea + (dif - prevDea) * 2 / (Double(p3) + 1) //BAR=2×(DIF-DEA) let bar = 2 * (dif - dea) prevDea = dea difArray.append(dif) deaArray.append(dea) barArray.append(bar) } return (difArray,deaArray,barArray) } /// MDJ() /// /// - Parameters: /// - p1: k指标周期(9) /// - p2: d指标周期(3) /// - p3: j指标周期(3) /// - datas: 数据集 /// - Returns: ([K],[D],[J]) fileprivate static func calculateKDJ(p1:Int, p2:Int, p3:Int, datas:[KLineModel]) -> ([Double],[Double],[Double]) { var kArray = [Double]() var dArray = [Double]() var jArray = [Double]() var prevK:Double = 50.0 var prevD:Double = 50.0 let rsvArray = calculateRSV(dayCount: p1, datas: datas) for i in 0 ..< datas.count { let rsv = rsvArray[i] let k = (2 * prevK + rsv) / 3 let d = (2 * prevD + k) / 3 let j = 3 * k - 2 * d prevK = k prevD = d kArray.append(k) dArray.append(d) jArray.append(j) } return (kArray,dArray,jArray) } /// RSV(未成熟随机值) /// /// - Parameters: /// - dayCount: 计算天数范围 /// - index: 当前的索引位 /// - datas: 数据集 /// - Returns: RSV集 fileprivate static func calculateRSV(dayCount:Int, datas:[KLineModel]) -> [Double] { var rsvArray = [Double]() for i in (0 ..< datas.count) { var rsv = 0.0 let close = datas[i].close var high = datas[i].high var low = datas[i].low let startIndex = i < dayCount ? 0 : i - dayCount + 1 //计算dayCount天内最高价最低价 for j in (startIndex ..< i){ high = datas[j].high > high ? datas[j].high : high low = datas[j].low < low ? datas[j].low : low } if high != low { rsv = (close - low) / (high - low) * 100 } rsvArray.append(rsv) } return rsvArray } /// RSI(相对强弱指标) /// 算法:N日RSI =N日内收盘涨幅的平均值/(N日内收盘涨幅均值+N日内收盘跌幅均值) ×100 /// /// - Parameters: /// - dayCount: 周期天数 /// - datas: 数据源 /// - Returns: 结果集 fileprivate static func calculateRSI(dayCount:Int, datas:[KLineModel]) -> [Double]{ var rsiArray = [Double]() //rsi值 var ratioArray = [Double]() //涨跌幅 for model in datas { if model.open == 0 { ratioArray.append(0) } else { let ratio = (model.close - model.open)/model.open ratioArray.append(ratio) } } for i in 0 ..< ratioArray.count { let startIndex = i <= dayCount ? 0 : i-dayCount var upSum:Double = 0.0 var downSum:Double = 0.0 for j in startIndex ... i { if ratioArray[j] >= 0 { upSum += ratioArray[j] //n日收盘涨幅总和 }else{ downSum += ratioArray[j] //n日收盘跌幅总和 } } let upAve = upSum / Double(dayCount) let downAve = downSum / Double(dayCount) let rsi = upAve / (upAve - downAve) * 100 rsiArray.append(rsi) } return rsiArray } }
// Copyright 2019 Algorand, 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. // // QRScannerViewController.swift import UIKit import AVFoundation class QRScannerViewController: BaseViewController { private let layout = Layout<LayoutConstants>() override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var shouldShowNavigationBar: Bool { return false } override var hidesCloseBarButtonItem: Bool { return true } weak var delegate: QRScannerViewControllerDelegate? private(set) lazy var overlayView = QRScannerOverlayView() private lazy var cancelButton: UIButton = { UIButton(type: .custom) .withBackgroundImage(img("button-bg-scan-qr")) .withTitle("title-cancel".localized) .withTitleColor(Colors.Main.white) .withFont(UIFont.font(withWeight: .semiBold(size: 16.0))) }() private var captureSession: AVCaptureSession? private let captureSessionQueue = DispatchQueue(label: AVCaptureSession.self.description(), attributes: [], target: nil) private var previewLayer: AVCaptureVideoPreviewLayer? private lazy var cameraResetHandler: EmptyHandler = { if self.captureSession?.isRunning == false { self.captureSessionQueue.async { self.captureSession?.startRunning() } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if captureSession?.isRunning == false { captureSessionQueue.async { self.captureSession?.startRunning() } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if captureSession?.isRunning == true { captureSessionQueue.async { self.captureSession?.stopRunning() } } } override func setListeners() { cancelButton.addTarget(self, action: #selector(closeScreenFromButton), for: .touchUpInside) } override func prepareLayout() { super.prepareLayout() configureScannerView() } } extension QRScannerViewController { private func configureScannerView() { if AVCaptureDevice.authorizationStatus(for: .video) == .authorized { setupCaptureSession() setupPreviewLayer() setupOverlayViewLayout() setupCancelButtonLayout() } else { AVCaptureDevice.requestAccess(for: .video) { granted in if granted { DispatchQueue.main.async { self.setupCaptureSession() self.setupPreviewLayer() self.setupOverlayViewLayout() self.setupCancelButtonLayout() } } else { DispatchQueue.main.async { self.presentDisabledCameraAlert() self.setupOverlayViewLayout() self.setupCancelButtonLayout() } } } } } private func setupCancelButtonLayout() { view.addSubview(cancelButton) cancelButton.snp.makeConstraints { make in make.bottom.equalToSuperview().inset(layout.current.buttonVerticalInset + view.safeAreaBottom) make.centerX.equalToSuperview() make.leading.trailing.equalToSuperview().inset(layout.current.buttonHorizontalInset) } } } extension QRScannerViewController { private func setupCaptureSession() { captureSession = AVCaptureSession() guard let captureSession = captureSession, let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if captureSession.canAddInput(videoInput) { captureSession.addInput(videoInput) } else { handleFailedState() return } let metadataOutput = AVCaptureMetadataOutput() if captureSession.canAddOutput(metadataOutput) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [.qr] } else { handleFailedState() return } } private func presentDisabledCameraAlert() { let alertController = UIAlertController( title: "qr-scan-go-settings-title".localized, message: "qr-scan-go-settings-message".localized, preferredStyle: .alert ) let settingsAction = UIAlertAction(title: "title-go-to-settings".localized, style: .default) { _ in UIApplication.shared.openAppSettings() } let cancelAction = UIAlertAction(title: "title-cancel".localized, style: .cancel, handler: nil) alertController.addAction(settingsAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } private func handleFailedState() { captureSession = nil displaySimpleAlertWith(title: "qr-scan-error-title".localized, message: "qr-scan-error-message".localized) } private func setupPreviewLayer() { guard let captureSession = captureSession else { return } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) guard let previewLayer = previewLayer else { return } previewLayer.frame = view.frame previewLayer.videoGravity = .resizeAspectFill view.layer.addSublayer(previewLayer) captureSessionQueue.async { captureSession.startRunning() } } private func setupOverlayViewLayout() { view.addSubview(overlayView) overlayView.frame = view.frame } } extension QRScannerViewController { @objc private func closeScreenFromButton() { closeScreen(by: .pop) } } extension QRScannerViewController: AVCaptureMetadataOutputObjectsDelegate { func metadataOutput( _ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection ) { captureSessionQueue.async { self.captureSession?.stopRunning() } if let metadataObject = metadataObjects.first { guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject, let qrString = readableObject.stringValue, let qrStringData = qrString.data(using: .utf8) else { captureSession = nil closeScreen(by: .pop) delegate?.qrScannerViewController(self, didFail: .invalidData, completionHandler: nil) return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) if let qrText = try? JSONDecoder().decode(QRText.self, from: qrStringData) { captureSession = nil closeScreen(by: .pop) delegate?.qrScannerViewController(self, didRead: qrText, completionHandler: nil) } else if let url = URL(string: qrString), qrString.hasPrefix("algorand://") { guard let qrText = url.buildQRText() else { delegate?.qrScannerViewController(self, didFail: .jsonSerialization, completionHandler: cameraResetHandler) return } captureSession = nil closeScreen(by: .pop) delegate?.qrScannerViewController(self, didRead: qrText, completionHandler: nil) } else if AlgorandSDK().isValidAddress(qrString) { let qrText = QRText(mode: .address, address: qrString) captureSession = nil closeScreen(by: .pop) delegate?.qrScannerViewController(self, didRead: qrText, completionHandler: nil) } else { delegate?.qrScannerViewController(self, didFail: .jsonSerialization, completionHandler: cameraResetHandler) return } } } } extension QRScannerViewController { private struct LayoutConstants: AdaptiveLayoutConstants { let buttonHorizontalInset: CGFloat = 20.0 let buttonVerticalInset: CGFloat = 16.0 } } protocol QRScannerViewControllerDelegate: class { func qrScannerViewController(_ controller: QRScannerViewController, didRead qrText: QRText, completionHandler: EmptyHandler?) func qrScannerViewController(_ controller: QRScannerViewController, didFail error: QRScannerError, completionHandler: EmptyHandler?) } enum QRScannerError: Error { case jsonSerialization case invalidData }
import Combine import Foundation final class EventFacade: EventFacadeProtocol { private let apiClient: ApiClientProtocol init(apiClient: ApiClientProtocol = ApiClient.shared) { self.apiClient = apiClient } func getEvents() -> AnyPublisher<[Event], RequestError> { Future { completion in self.performGetEvents(callback: completion) }.eraseToAnyPublisher() } private func performGetEvents(callback: @escaping ((Result<[Event], RequestError>) -> Void)) { apiClient.request(.getEvents) { (response: Result<[Event], RequestError>) in switch response { case let .success(events): callback(.success(events)) case let .failure(error): callback(.failure(error)) } } } func getEventDetails(id: String) -> AnyPublisher<EventDetails, RequestError> { Future { completion in self.performGetEventDetails(id: id, callback: completion) }.eraseToAnyPublisher() } private func performGetEventDetails(id: String, callback: @escaping ((Result<EventDetails, RequestError>) -> Void)) { apiClient.request(.getEventDetails(id)) { (response: Result<EventDetails, RequestError>) in switch response { case let .success(events): callback(.success(events)) case let .failure(error): callback(.failure(error)) } } } func getImageData(url: String) -> AnyPublisher<Data, RequestError> { Future { completion in self.performGetImageData(url: url, callback: completion) }.eraseToAnyPublisher() } private func performGetImageData(url: String, callback: @escaping ((Result<Data, RequestError>) -> Void)) { apiClient.request(.getImageData(url)) { (response: Result<Data, RequestError>) in switch response { case let .success(data): callback(.success(data)) case let .failure(error): callback(.failure(error)) } } } func postCheckin(eventId: String, name: String, email: String) -> AnyPublisher<[String : String], RequestError> { Future { completion in self.performPostCheckin(eventId: eventId, name: name, email: email, callback: completion) }.eraseToAnyPublisher() } private func performPostCheckin(eventId: String, name: String, email: String, callback: @escaping ((Result<[String:String], RequestError>) -> Void)) { apiClient.request(.postCheckin(eventId, name, email)) { (response: Result<[String:String], RequestError>) in switch response { case let .success(result): callback(.success(result)) case let .failure(error): callback(.failure(error)) } } } }
// // SettingsViewController.swift // Spotted // // Created by Joanne Lee on 8/25/18. // Copyright © 2018 Spotted. All rights reserved. // import UIKit import FirebaseFirestore class SettingsViewController : UIViewController { @IBOutlet weak var usernameField: UITextField! @IBAction func saveSettingsAction(_ sender: Any) { logInUser(username: usernameField.text!) self.navigationController?.popToRootViewController(animated: true) } func logInUser(username : String) { UserInfo.userName = username //UIApplication.topViewController()?.present(navStart, animated: true, completion: nil) let db = Firestore.firestore() let docRef = db.collection("users").document(username) docRef.getDocument { (document, error) in if let document = document, document.exists { UserInfo.friendos = (document.data()!["friends"] as! [String]).map({ Friend(id:0,name:$0) }) UserInfo.notifications = (document.data()!["notifications"] as! [[String:Any?]]).map({ SpottedNotification($0) }) print(UserInfo.notifications) } else { docRef.setData([ "friends" : [], "notifications" : [], ]) } } } }
// // ProxyScheduler.swift // imageFX // // Created by Serge-Olivier Amega on 2/17/16. // Copyright © 2016 Nexiosoft. All rights reserved. // import UIKit private let blockingQueue = dispatch_queue_create("com.nexiosoft.imageFXBlock.sync", DISPATCH_QUEUE_SERIAL) private let processingQueue = dispatch_queue_create("com.nexiosoft.imageFXProcess.sync", DISPATCH_QUEUE_SERIAL) class ProxyScheduler: NSObject { var functions : [()->Void] var isRunning : Bool static var instance: ProxyScheduler? = nil class func getInstance() -> ProxyScheduler { if instance == nil { instance = ProxyScheduler() } return instance! } override init() { functions = [] isRunning = false super.init() } func runTask(proxy proxy: ()->Void, actual: ()->Void) { dispatch_async(blockingQueue) { if self.functions.count > 1 { self.functions.removeRange(1..<self.functions.count) } self.functions.append(proxy) self.functions.append(actual) /* if (!isRunning) { self.isRunning = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { while !self.functions.isEmpty { if let f : (()->Void) = self.functions.removeFirst() { f() } } self.isRunning = false }) } */ func runFunctions() { dispatch_async(blockingQueue) { if let f : (()->Void) = self.functions.removeFirst() { dispatch_async(processingQueue) { f(); } } if !self.functions.isEmpty { runFunctions(); } else { self.isRunning = false; } } } if !self.isRunning { self.isRunning = true; runFunctions(); } } } }
// // ViewController.swift // BilevelCVLayout // // Created by Doug Mead on 6/21/16. // Copyright © 2016 Doug Mead. All rights reserved. // import UIKit class BiLevelNavigationController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, BiLevelFolderRowDelegate { var collectionView: UICollectionView! //var collectionViewLayout: BiLevelNavFlowLayout! var folderRow: BiLevelFolderRow? // MARK: init/deinit view lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let collectionViewLayout = BiLevelNavFlowLayout() self.collectionView = UICollectionView(frame: CGRect(x: 30.0, y: 30.0, width: self.view.bounds.width - 30.0 * 2.0, height: self.view.bounds.height - 30.0 * 2.0), collectionViewLayout: collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = StyleKit.biLevelGrey.color //UIColor.blueColor() collectionView.registerClass(TempClass.self, forCellWithReuseIdentifier: TempClass.reuseIdentifier) collectionView.registerClass(BiLevelFolderRow.CollectionViewCell.self, forCellWithReuseIdentifier: BiLevelFolderRow.reuseIdentifier) collectionView.registerClass(BiLevelLabelCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: BiLevelLabelCell.reuseIdentifier) collectionView.registerNib(UINib(nibName: TempFileCollectionViewCell.nibName, bundle: nil), forCellWithReuseIdentifier: TempFileCollectionViewCell.reuseIdentifier) let refreshControlView = UIRefreshControl() refreshControlView.addTarget(self, action: #selector(test(_:)), forControlEvents: .ValueChanged) collectionView.addSubview(refreshControlView) self.view.addSubview(collectionView) self.view.addConstraints([ NSLayoutConstraint(item: collectionView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: collectionView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: collectionView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: collectionView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0) ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func test(refreshControl: UIRefreshControl? = nil) { refreshControl?.endRefreshing() print("REFRESH!!!") } // MARK: - UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 2 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 50 default: return 50 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { switch (section: indexPath.section, item: indexPath.item) { case (section: 0, item: 0): guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(BiLevelFolderRow.reuseIdentifier, forIndexPath: indexPath) as? BiLevelFolderRow.CollectionViewCell else { print("Error casting") return UICollectionViewCell() } cell.folderRowView.delegate = self cell.backgroundColor = UIColor.whiteColor()//cyanColor().colorWithAlphaComponent(0.8) return cell default: guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TempFileCollectionViewCell.reuseIdentifier, forIndexPath: indexPath) as? TempFileCollectionViewCell else { print("Error casting") return UICollectionViewCell() } cell.backgroundColor = UIColor.orangeColor() cell.label.text = "\(indexPath.item)" cell.label.sizeToFit() return cell } } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { guard let supView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: BiLevelLabelCell.reuseIdentifier, forIndexPath: indexPath) as? BiLevelLabelCell where kind == UICollectionElementKindSectionHeader else { print("ERROR: BiLevelNav supplementary view nil or cannot cast -or- not a section header") return UICollectionReusableView() } if indexPath.section == 0 { supView.backgroundColor = UIColor.whiteColor() //greenColor().colorWithAlphaComponent(0.8) supView.setupCell(.BiLevelNavFolders, number: 12) } else { supView.backgroundColor = StyleKit.biLevelGrey.color//.greenColor().colorWithAlphaComponent(0.8) supView.setupCell(.BiLevelNavFiles, number: 14) } return supView } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? TempFileCollectionViewCell { let size = cell.label.frame.size let pointSize = cell.label.font.pointSize cell.label.font = cell.label.font.fontWithSize(pointSize + 1.0) cell.label.numberOfLines = 1000 cell.label.text = "\(cell.label.text ?? "") blah" let newSize = cell.label.sizeThatFits(CGSize(width: size.width, height: CGFloat.max)) print("Diff: \(newSize.height - size.height)") BiLevelNavFlowLayout.Constants.FileItemSize.height += newSize.height - size.height collectionView.collectionViewLayout.invalidateLayout() } } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { switch (section: indexPath.section, item: indexPath.item) { case (section: 0,item: 0): return CGSize(width: collectionView.frame.width, height: BiLevelFolderRow.Constants.FolderRowHeight) default: return BiLevelNavFlowLayout.Constants.FileItemSize //(collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize ?? CGSizeZero } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { switch section { case 0: return 0.0 case 1: return (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumInteritemSpacing ?? 0.0 default: return (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumInteritemSpacing ?? 0.0 } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { switch section { case 0: return 0.0 case 1: return (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumLineSpacing ?? 0.0 default: return (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumLineSpacing ?? 0.0 } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { switch section { case 0: return UIEdgeInsetsZero case 1: return (collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset ?? UIEdgeInsetsZero default: return (collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset ?? UIEdgeInsetsZero } } // MARK: - BiLevelFolderRowDelegate func biLevelFolderRow(biLevelFolderRow: BiLevelFolderRow, didSelectFolder folder: IMFolder, folderCell: BiLevelFolderCell) { let biLevelVC = BiLevelNavigationController() self.navigationController?.pushViewController(biLevelVC, animated: true) } // MARK: - Device orientation / size override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { print("Trait change") super.traitCollectionDidChange(previousTraitCollection) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { print("Transition to size: \(size)") self.collectionView?.reloadData() super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) } class TempClass: UICollectionViewCell { static var reuseIdentifier: String = "Cell" var label: UILabel! override init(frame: CGRect) { super.init(frame: frame) self.label = UILabel() label.text = "default" self.addSubview(label) self.translatesAutoresizingMaskIntoConstraints = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
// // JSONManager.swift // RxMovie // // Created by Hüseyin Metin on 23.01.2020. // Copyright © 2020 HüseyinMetin. All rights reserved. // import Foundation class JSONManager { let encoder: JSONEncoder = JSONEncoder() let decoder: JSONDecoder = JSONDecoder() private var formatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter } init() { encoder.dateEncodingStrategy = .formatted(formatter) decoder.dateDecodingStrategy = .formatted(formatter) } }
// // MypageViewController.swift // SmartOrder // // Created by Jeong on 05/05/2019. // Copyright © 2019 하영. All rights reserved. // import UIKit import Firebase import GoogleSignIn class MypageViewController: UIViewController, GIDSignInUIDelegate { var imagepicked = UIImage(named:"coffeebottlefilled") @IBOutlet weak var loginIcon: UIImageView! @IBOutlet var addButton: UIButton! @IBOutlet weak var mainImage: UIImageView! @IBOutlet weak var loginButtonLabel: UILabel! @IBOutlet weak var logoutIcon: UIImageView! let alertController = UIAlertController(title: "로그인이 필요한 항목입니다.", message: "", preferredStyle: .alert) let logoutalertController = UIAlertController(title: "로그아웃 하시겠습니까?", message: "", preferredStyle: .alert) @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var joinAddress: UILabel! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var orderInfoButton: UIButton! @IBAction func addButtonPressed(_ sender: Any) { let alert = UIAlertController(title: "사진 선택", message: "원하는 저장소를 선택해주세요.", preferredStyle: .alert) let library = UIAlertAction(title: "사진앨범", style: .default) { (action) in self.openLibrary() } let camera = UIAlertAction(title: "카메라", style: .default) { (action) in self.openCamera() } let defaultimage = UIAlertAction(title: "기본이미지", style: .default) { (action) in self.mainImage.image = UIImage(named: "coffeebottlefilled") self.mainImage.contentMode = .scaleAspectFit } let cancel = UIAlertAction(title: "취소", style: .cancel, handler: nil) alert.addAction(library) alert.addAction(camera) alert.addAction(defaultimage) alert.addAction(cancel) present(alert, animated: true, completion: nil) } // 로그아웃 버튼 눌렀을때 동작 처리. @IBAction func pressLogout(_ sender: Any) { self.present(logoutalertController, animated: true, completion: {}) authenticationUser() } // 주문내역 버튼 눌렀을때 동작 처리. @IBAction func pressOrderButton(_ sender: Any) { // 로그인 되어있지 않으면 guard let currentUser = Auth.auth().currentUser else{ //alert 발생 (취소, login) self.present(alertController, animated: true, completion: {}) return } // 로그인 되어있으면 (NeedOrderSegue를 통해 테이블뷰로 이동) if (currentUserInfo.orderList.count == 0){ self.performSegue(withIdentifier: "NoOrderedSegue", sender: nil) } else { self.performSegue(withIdentifier: "NeedOrderedSegue", sender: nil) } } override func viewDidLoad() { super.viewDidLoad() // 주문내역 alert처리. alertController.addAction(UIAlertAction(title: "취소", style: .cancel)) alertController.addAction(UIAlertAction(title: "로그인", style: .default) {UIAlertAction in self.performSegue(withIdentifier: "LoginVCSegue", sender: nil) }) self.mainImage.layer.cornerRadius = self.mainImage.frame.size.height / 2 // 로그아웃 alert처리 logoutalertController.addAction(UIAlertAction(title: "취소", style: .cancel)) logoutalertController.addAction(UIAlertAction(title: "확인", style: .default){ UIAlertAction in do{ try Auth.auth().signOut() self.authenticationUser() } catch let error { print("fail to signout") } }) setDefault() } override func viewDidAppear(_ animated: Bool) { print ("viewDidAppear") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) print ("ViewWillAppear") authenticationUser() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } /// - Returns: AppDelegate func getAppDelegate() -> AppDelegate!{ return UIApplication.shared.delegate as! AppDelegate } // 인증 조건에 맞춰서 뷰 변화주기 func authenticationUser(){ guard let currentUser = Auth.auth().currentUser else{ loginButton.isHidden = false logoutIcon.isHidden = true loginButtonLabel.text = "로그인" loginIcon.isHidden = false; logoutButton.isHidden = true label2.isHidden = false addButton.isHidden = true userNameLabel.text = "회원서비스 이용을 위해 로그인해주세요." joinAddress.text = "안녕하세요!" mainImage.image = UIImage(named: "coffeebottle2") return } loginButton.isHidden = true logoutIcon.isHidden = false loginButtonLabel.text = "로그아웃" loginIcon.isHidden = true; logoutButton.isHidden = false label2.isHidden = true userNameLabel.text = "님 안녕하세요!" joinAddress.text = Auth.auth().currentUser?.email addButton.isHidden = false mainImage.image = imagepicked } // 처음에 보여줄 뷰 결정하기 func setDefault(){ // 처음에 로그인 전에 이름값 숨겨주기 userNameLabel.text = "회원서비스 이용을 위해 로그인해주세요." joinAddress.text = "안녕하세요!" //버튼 디자인 요소 추가 loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 25) loginButton.setTitleColor(UIColor.white, for: .normal) logoutButton.titleLabel?.font = UIFont.systemFont(ofSize: 25) logoutButton.setTitleColor(UIColor.white, for: .normal) authenticationUser() } } extension MypageViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate{ private func presentImagePickerController(withSourceType sourceType: UIImagePickerController.SourceType){ let picker = UIImagePickerController() picker.delegate = self picker.sourceType = sourceType present(picker, animated:true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { imagepicked = image mainImage.image = image mainImage.contentMode = .scaleAspectFill print(info) } dismiss(animated: true, completion: nil) } func openLibrary(){ presentImagePickerController(withSourceType: .photoLibrary) } func openCamera(){ if(UIImagePickerController .isSourceTypeAvailable(.camera)){ presentImagePickerController(withSourceType: .camera) } else{ print("Camera not available") } } }
// // BaseTabBar.swift // LucrezCeva // // Created by Suciu Radu on 27/12/2018. // Copyright © 2018 LucrezCeva. All rights reserved. // import UIKit class BaseTabBarController: UITabBarController { override func viewDidLoad() { setupUI() } private func setupUI() { self.tabBar.barTintColor = UIColor.white self.tabBar.tintColor = Colors.colorPrimary self.tabBar.unselectedItemTintColor = UIColor.lightGray } }
// // View+frame.swift // // // Created by Carmelo Ruymán Quintana Santana on 28/12/20. // import SwiftUI public extension View { func frame(_ vale: CGFloat) -> some View { self.frame(width: vale, height: vale, alignment: .center) } func infinityAll(alignment: Alignment = .center) -> some View { self.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: alignment) } func infinityWidth(alignment: Alignment = .center) -> some View { self.frame(minWidth: 0, maxWidth: .infinity, alignment: alignment) } func infinityHeight(alignment: Alignment = .center) -> some View { self.frame(minHeight: 0, maxHeight: .infinity, alignment: alignment) } func height(_ value: CGFloat, alignment: Alignment = .center) -> some View { self.frame(height: value, alignment: alignment) } func width(_ value: CGFloat, alignment: Alignment = .center) -> some View { self.frame(width: value, alignment: alignment) } }
// // AppDelegate.swift // IntroducingFunctions-Swift // // Created by Joshua Howland on 8/14/14. // Copyright (c) 2014 DevMountain. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Insert code here... let myName = "Chad" countDownTillIntroduction(4) printIntroductions(myName) return true } // Define new functions here... func printIntroductions(name:String) { let name:String = "Chad" let introduction:String = "My name is " + name let japaneseIntroduction:String = name + " to moushimasu" println(introduction) println(japaneseIntroduction) } func countDownTillIntroduction(numberOfDays:Int) { if (numberOfDays == 0) { println("The time has come.") } else { println("\(numberOfDays) days left until introductions.") var oneLessDay:Int = numberOfDays - 1 countDownTillIntroduction(oneLessDay) } } }
// // CustomCell.swift // rtuJOY // // Created by Максим Палёхин on 08.07.2020. // Copyright © 2020 Максим Палёхин. All rights reserved. // import UIKit class CustomCell: UITableViewCell { @IBOutlet weak var timeStart: UILabel! @IBOutlet weak var timeEnd: UILabel! @IBOutlet weak var typeLesson: UILabel! @IBOutlet weak var nameLesson: UILabel! @IBOutlet weak var numberAudince: UILabel! @IBOutlet weak var nameTeacher: UILabel! }
// // SubOrder.swift // DakkenApp // // Created by Sayed Abdo on 10/31/18. // Copyright © 2018 sayedAbdo. All rights reserved. // import Foundation class SubOrder{ var itemname : String var itemimg : String var itemprice : Int var trader : String var qty : Int var price : Double var status : String var created_at : String init(itemname : String , itemimg : String , itemprice : Int , trader : String , qty : Int , price : Double , status : String , created_at : String ) { self.itemname = itemname self.itemimg = itemimg self.itemprice = itemprice self.trader = trader self.qty = qty self.price = price self.status = status self.created_at = created_at } }
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ import CoreData // Throwable types must be in global scope // otherwise linker spills cryptic errors in random object files public struct InvalidStoreURLError: Error { } public extension BrowserStateCoreData { func fetch<T: NSManagedObject>(_ predicate: NSPredicate? = nil) -> [T]? { let request = NSFetchRequest<T>(entityName: NSStringFromClass(T.self)) request.predicate = predicate return resultsOfFetchWithErrorAlert(request) } func createObject<T: NSManagedObject>() -> T? { return insertNewObject(forEntityClass: T.self) as? T } /* WARNING: Swift 2.2 (Xcode 7.3) refuses to create bridging header for function with optional return value. A function with nonoptional retval will be bridged but translated as _Nullable !!! (may be a compiler bug even) */ @objc public func metadataIfMigrationNeeded(_ sourceStoreURL: URL, destinationModel: NSManagedObjectModel) throws -> [String: Any] { let options: [AnyHashable: Any] = [ NSInferMappingModelAutomaticallyOption: true, NSMigratePersistentStoresAutomaticallyOption: true] // Load store metadata (this will contain information about the versions of the models this store was created with) let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: sourceStoreURL, options: options) let isCompatible = destinationModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata) // Metadata not needed if the persistent store is compatible with destination model // Must return empty dict instead of nil - see warning above return isCompatible ? [:] as [String: Any] : metadata } @objc public func migrate(_ storeURL: URL, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel) throws { // Compute the mapping between old model and new model let mapping = try NSMappingModel.inferredMappingModel(forSourceModel: sourceModel, destinationModel: destinationModel) // Backup old store let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss" let storeBackupURL = storeURL.appendingPathExtension("\(dateFormatter.string(from: Date()))") try FileManager.default.moveItem(at: storeURL, to: storeBackupURL) // Apply the mapping to the backed up store, replace the current store let migrationMgr = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel) try migrationMgr.migrateStore( from: storeBackupURL, sourceType: NSSQLiteStoreType, options: nil, with: mapping, toDestinationURL: storeURL, destinationType: NSSQLiteStoreType, destinationOptions: nil) } @objc public func createContext(forStoreURL storeURL: URL, withModel model: NSManagedObjectModel, wasMigrated: Bool) throws -> NSManagedObjectContext { // Since iOS7 the default sqlite journaling mode is Write-Ahead-Log. // The mode must be turned off when adding a migrated (backed up) store // https://developer.apple.com/library/ios/qa/qa1809/_index.html let options: [AnyHashable: Any] = [ NSInferMappingModelAutomaticallyOption: true, NSMigratePersistentStoresAutomaticallyOption: !wasMigrated, NSSQLitePragmasOption: ["journal_mode": wasMigrated ? "DELETE" : "WAL"] ] let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) let context = NSManagedObjectContext() context.persistentStoreCoordinator = coordinator // Browser state doesn't need to be undone, don’t waste effort recording undo actions context.undoManager = nil return context } // the following functions needed to be rewritten from Objc so they can be used in Swift3 func fetchRequest<T: NSFetchRequestResult> (with predicate: NSPredicate?) -> NSFetchRequest<T> { assert(Thread.isMainThread, "CoreData fetch not called on main thread") let request = NSFetchRequest<T>(entityName: NSStringFromClass(T.self)) if let predicate = predicate { request.predicate = predicate } return request } func resultsOfFetchWithErrorAlert<T>(_ request: NSFetchRequest<T>) -> [T]? { do { return try context.fetch(request) } catch let error { let alert = Utils.alertViewWithError(error, title: "Core Data Fetch", delegate: nil) alert?.show() } return nil } func fetchController<T>(for request: NSFetchRequest<T>, withCacheName cacheName: String?) -> NSFetchedResultsController<T> { return NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: cacheName) } func fetchController<T>(for request: NSFetchRequest<T>, sectionNameKeyPath: String, cacheName name: String?) -> NSFetchedResultsController<T> { return NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: name) } func deleteObjectsResulting<T: NSManagedObject> (fromFetch request: NSFetchRequest<T>) { let results = self.resultsOfFetchWithErrorAlert(request) if results?.count != 0 { self.deleteManagedObjects(results) } } }
// // ViewController.swift // Selfume // // Created by Samir imac4 on 01/12/20. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lblText: UILabel! override func viewDidLoad() { super.viewDidLoad() Utils.updateLanguage(str : kEnglish, view: view) self.lblText.text = "Hello World".localized() // Do any additional setup after loading the view. } @IBAction func changeLanguageClick(_ sender: Any) { if Utils.fetchString(forKey: kLanguage) == kEnglish { Utils.updateLanguage(str : kItalian, view: view) Localize.setCurrentLanguage("it") } else if Utils.fetchString(forKey: kLanguage) == kItalian { Utils.updateLanguage(str : kEnglish, view: view) Localize.setCurrentLanguage("en") } self.lblText.text = "Hello World".localized() } }
// // CRMContactDependent.swift // SweepBright // // Created by Kaio Henrique on 5/19/16. // Copyright © 2016 madewithlove. All rights reserved. // import Foundation protocol CRMContactDependent { var contact: CRMContact! {get set} }
// // detialKegiatanViewController.swift // vovy // // Created by Alfon on 26/05/20. // Copyright © 2020 Alfon. All rights reserved. // import UIKit class detialKegiatanViewController: UIViewController { var volunteerData: dataStructure? @IBOutlet weak var judulVolunteer: UILabel! @IBOutlet weak var imageVolunteer: UIImageView! @IBOutlet weak var kriteriaVolunteer: UILabel! @IBOutlet weak var deskripsiVolunteer: UILabel! @IBOutlet weak var tanggalMulai: UILabel! @IBOutlet weak var pelajariLebih: UIButton! override func viewDidLoad() { super.viewDidLoad() imageVolunteer.layer.cornerRadius = 20 imageVolunteer.layer.masksToBounds = true pelajariLebih.layer.cornerRadius = 10 pelajariLebih.layer.masksToBounds = true let url = URL(string: volunteerData!.image) DispatchQueue.global().async { let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch DispatchQueue.main.async { self.imageVolunteer.image = UIImage(data: data!) } } self.title = volunteerData?.source judulVolunteer.text = volunteerData?.title kriteriaVolunteer.text = volunteerData?.additional_information[0] deskripsiVolunteer.text = volunteerData?.description tanggalMulai.text = volunteerData?.start_date } @IBAction func keWebsite(_ sender: Any) { if let url = URL(string: volunteerData!.website_link) { UIApplication.shared.open(url) } } }
// // WeatherAPI.swift // SimpleWeatherApp // // Created by Marina Butovich on 11/2/17. // Copyright © 2017 Marinochka. All rights reserved. // import Foundation import CoreLocation public enum Result<T> { case success(T) case error(Error) } public protocol WeatherAPI { func queryWeather(for coordinate: CLLocationCoordinate2D, completion: @escaping (Result<WeatherResponse>)->Void) }
// // DetailTableViewCell.swift // SampleInbox // // Created by ShinokiRyosei on 2015/11/05. // Copyright © 2015年 ShinokiRyosei. All rights reserved. // import UIKit class DetailTableViewCell: UITableViewCell { @IBOutlet weak var mainTextView: UITextView! @IBOutlet weak var textView: UITextView! override func awakeFromNib() { super.awakeFromNib() // Initialization code textView.contentInset = UIEdgeInsets(top: -9, left: -4, bottom: 0, right: 0) textView.scrollEnabled = false mainTextView.dataDetectorTypes = .Link mainTextView.editable = false mainTextView.scrollEnabled = false } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
import UIKit class Circle: UIView { var percent:CGFloat = 0 { didSet { setNeedsDisplay() }} private var countLabel: UILabel! override func draw(_ rect: CGRect) { let endAngle = -.pi/2+percent*CGFloat.pi/50 let path = UIBezierPath(arcCenter: rect.center, radius: rect.width/2-5.0, startAngle: CGFloat.pi*3/2, endAngle:endAngle , clockwise: false) path.lineWidth = 3.0 UIColor.orange.setStroke() path.stroke() countLabel.text = "\((5-Int(percent)/20))" } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { countLabel = UILabel(frame: CGRect(x: bounds.midX-30, y: bounds.midY-30, width: 60, height: 60)) countLabel.font = UIFont(name: "Helvetica", size: 70) countLabel.textAlignment = .center countLabel.text = "\(5-percent/20)" addSubview(countLabel) let infoLabel = UILabel(frame: CGRect(x: 0, y: bounds.midX-60, width: bounds.width, height: 30)) infoLabel.font = UIFont(name: "Helvetica", size: 20) infoLabel.textAlignment = .center infoLabel.text = "Новая игра через:" infoLabel.numberOfLines = 0 infoLabel.adjustsFontSizeToFitWidth = true infoLabel.minimumScaleFactor = 0.1 addSubview(infoLabel) let victoryLabel = UILabel(frame: CGRect(x: 0, y: bounds.midX-110, width: bounds.width, height: 50)) victoryLabel.font = UIFont(name: "Helvetica", size: 40) victoryLabel.textAlignment = .center victoryLabel.text = "Победа!!!" addSubview(victoryLabel) } func startAnimating(completion:@escaping ()->Void) { Timer.scheduledTimer(withTimeInterval: 5/100, repeats: true) { timer in self.percent += 1 if self.percent == 100 { timer.invalidate() self.percent = 0 completion() } } } }
import Foundation enum TimelineModels { enum FetchFromListings { struct Request {} struct Response { var productArray: [Product] } struct ViewModel {} } enum FetchFromCategories { struct Request {} struct Response { var categroyArray: [Categroy] } struct ViewModel {} } enum FetchFromListProducts { struct Request {} struct Response { var listProduct: [Product] } struct ViewModel { struct Listing: listingProtocol { let listingId: Int? var listingTitle: String? var listingPrice: String? var isUrgent: Bool? var thumbUrl: URL? var smallUrl: URL? } struct Product { var categoryName: String? var listing: Listing? } var listProduct: [Product] } } enum FetchFromFiltredCategory { struct Request { var categoryName: String } struct Response { struct Category { var categoryName: String var listProduct: [Product] } var listFiltredCategories: [Category] } struct ViewModel { struct Category { var categoryName: String var listProduct: [FetchFromListProducts.ViewModel.Product] } var listFiltredCategories: [Category] } } }
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "EssentialFeed", products: [ .library( name: "EssentialFeed", targets: ["EssentialFeed"]), Product.library( name: "CoreTest", targets: ["CoreTest"] ) ], dependencies: [], targets: [ .target( name: "EssentialFeed", dependencies: []), .testTarget( name: "EssentialFeedTests", dependencies: ["EssentialFeed", "CoreTest"], path: "./Tests/EssentialFeedTests"), .testTarget( name: "EssentialFeedAPIEndToEndTests", dependencies: ["EssentialFeed", "CoreTest"], path: "./Tests/EndToEndTests" ), .target( name: "CoreTest", dependencies: [], path: "./Tests/CoreTest" ) ] )
// // PickerView.swift // MtoM fake // // Created by Student on 1/13/16. // Copyright © 2016 Trương Thắng. All rights reserved. // import UIKit class CityPickerView: PickerView , UIPickerViewDataSource { var cityPickerView = UIPickerView() var dataCityPickerView = ["Nam Dinh","Hai Phong","Hai Duong"] override func createPickerView(){ super.createPickerView() cityPickerView.dataSource = self } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return dataCityPickerView.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return dataCityPickerView[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let data = dataCityPickerView[row] popView.cityButton.setTitle(data, forState: .Normal) } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
// // UdacityParseClient.swift // On The Map // // Created by Johan Smet on 23/06/15. // Copyright (c) 2015 Justcode.be. All rights reserved. // import Foundation class UdacityParseClient : WebApiClient { /////////////////////////////////////////////////////////////////////////////////// // // constants // static let PARSE_APPLICATION_ID : String = "QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr" static let REST_API_KEY : String = "QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY" static let BASE_URL : String = "https://api.parse.com/1/classes/" /////////////////////////////////////////////////////////////////////////////////// // // initializers // override init() { super.init(dataOffset: 0) } /////////////////////////////////////////////////////////////////////////////////// // // request interface // func listStudentLocations(fetchCount : Int, skipCount : Int, completionHandler : (studentLocations : [AnyObject]?, error : String?) -> Void) { let extraHeaders : [String : String] = [ "X-Parse-Application-Id" : UdacityParseClient.PARSE_APPLICATION_ID, "X-Parse-REST-API-Key" : UdacityParseClient.REST_API_KEY ] let parameters : [String : AnyObject] = [ "limit" : fetchCount, "skip" : skipCount, "order" : "-updatedAt" ] // make request startTaskGET(UdacityParseClient.BASE_URL, method: "StudentLocation", parameters: parameters, extraHeaders: extraHeaders) { result, error in if let basicError = error as? NSError { completionHandler(studentLocations: nil, error: UdacityParseClient.formatBasicError(basicError)) } else if let httpError = error as? NSHTTPURLResponse { completionHandler(studentLocations: nil, error: UdacityParseClient.formatHttpError(httpError)) } else { let postResult = result as! NSDictionary; let studentLocations = postResult.valueForKey("results") as! [AnyObject]? completionHandler(studentLocations: studentLocations, error: nil) } } } /////////////////////////////////////////////////////////////////////////////////// // // helper functions // private class func formatBasicError(error : NSError) -> String { return error.localizedDescription } private class func formatHttpError(response : NSHTTPURLResponse) -> String { if (response.statusCode == 403) { return NSLocalizedString("cliInvalidCredentials", comment:"Invalid username or password") } else { return "HTTP-error \(response.statusCode)" } } /////////////////////////////////////////////////////////////////////////////////// // // singleton // static let instance = UdacityParseClient() } func udacityParseClient() -> UdacityParseClient { return UdacityParseClient.instance }
// // CalorieIntake+CoreDataClass.swift // // // Created by Waseem Idelbi on 8/14/20. // // import Foundation import CoreData @objc(CalorieIntake) public class CalorieIntake: NSManagedObject { }
// // Hamburger.swift // QFTemplate // // Created by 情风 on 2019/1/7. // Copyright © 2019 qingfengiOS. All rights reserved. // import UIKit /// 汉堡 class Hamburger: AbstractSandwich { override func prepareBread() { getBurgerBun() } override func addMeat() { addBeefPatty() } override func addCondiments() { addKetchup() addMustard() addCheese() addPickkles() } //MARK: -特殊操作 func getBurgerBun() { print("准备小圆面包") } func addBeefPatty() { print("准备牛肉饼") } func addKetchup() { print("加番茄酱") } func addMustard() { print("加点芥末") } func addCheese() { print("加奶酪") } func addPickkles() { print("加点腌黄瓜") } }
import Foundation import OHHTTPStubs public extension Behaviour { func stubNetworkRequest(stub: Stub) { requests.append(stub) stubRequest() } internal func stubRequest() { for request in requests { stub(condition: isAbsoluteURLString(request.urlString), response: { _ -> HTTPStubsResponse in let stubData = request.jsonReturn.data(using: String.Encoding.utf8) return HTTPStubsResponse(data: stubData!, statusCode: request.httpResponse, headers: nil) }) } } /** READ DATA FILE INTO STRING - parameter: urlString:String - return: String? */ func openFileAndReadIntoString(urlString: String) -> String? { if let dir = Bundle.main.path(forResource: urlString, ofType: "json") { do { let text2 = try String(contentsOfFile: dir) return text2 } catch _ as NSError { return nil } } return nil } }
import Foundation // INSERTION SORT // Rank items by comparing each key in the list var numbersList = [8, 2, 10, 9, 11, 1 ,7] func insertionsort() { var key : Int var y : Int for items in 0...numbersList.count { key = numbersList[items] y = items while y > -1 { if key < numbersList[y] { numbersList.remove(at: y + 1) numbersList.insert(key, at: y) } } } } func insertionSort<T>(array: [T], isOrderedBefore: (T, T) -> Bool) -> [T] { var a = array for x in 1..<a.count { var y = x let temp = a[y] while y > 0 && isOrderedBefore(temp, a[y - 1]) { a[y] = a[y - 1] y -= 1 } a[y] = temp } return a } let list = [2,3,5,6,7,8,8,3,3,2,4,6,6] insertionSort(array: list, isOrderedBefore: >)
// // Notification.swift // MastodonKit // // Created by Ornithologist Coder on 4/9/17. // Copyright © 2017 MastodonKit. All rights reserved. // import Foundation public struct Notification: Codable, Hashable { /// The notification ID. public let id: String /// The notification type. public let type: NotificationType /// The time the notification was created. public let createdAt: Date /// The Account sending the notification to the user. public let account: Account /// The Status associated with the notification, if applicable. public let status: Status? private enum CodingKeys: String, CodingKey { case id case type case createdAt = "created_at" case account case status } }
// // GPPlaceSearchRequest.swift // GPlaceAPI-Swift // // Created by Darshan Patel on 7/23/15. // Copyright (c) 2015 Darshan Patel. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Darshan Patel // // 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 CoreLocation import Alamofire class GPPlaceSearchRequest { typealias GooglePlaceSearchHandler = (GPPlaceSearchResponse?, NSError?)->Void var location: CLLocationCoordinate2D! var radius: Int! var rankby: GPRankBy! var keyword: String? var language: String? var minprice: Int? var maxprice: Int? var name: String? var opennow: Bool? var types:[String]? var pagetoken: String? init (location: CLLocationCoordinate2D) { self.location = location; self.radius = 1000 self.minprice = -1 self.maxprice = -1 self.rankby = .GPRankByProminence } func params() -> Dictionary<String, AnyObject> { var dicParams = Dictionary<String, AnyObject>() dicParams["key"] = GPlaceAPISetup.sharedInstance.Api_Key dicParams["location"] = "\(self.location.latitude),\(self.location.longitude)" if let opRadius = self.radius { dicParams["radius"] = "\(self.radius)"; } if let opKeyWord = self.keyword { dicParams["keyword"] = self.keyword; } if self.maxprice != -1 { dicParams["maxprice"] = "\(self.maxprice)"; } if self.minprice != -1 { dicParams["maxprice"] = "\(self.minprice)"; } if let opName = self.name { dicParams["name"] = self.name } if self.opennow == true { dicParams["opennow"] = "\(self.opennow)" } if let language = self.language { dicParams["language"] = language } if let opPageToken = self.pagetoken { dicParams["pagetoken"] = self.pagetoken } dicParams["rankBy"] = self.rankby.rawValue if let opTypes = self.types { if opTypes.count > 0 { dicParams["types"] = join("|", opTypes) } } return dicParams } func doFetchPlaces(handler : GooglePlaceSearchHandler) { Alamofire.request(.GET, "\(GPlaceConstants.kAPI_PLACES_URL)nearbysearch/json", parameters: self.params(), encoding: .URL).responseJSON(options: .AllowFragments) { (request, response, data, error) -> Void in if error == nil { var gpResponse = GPPlaceSearchResponse(attributes: data as! Dictionary) handler(gpResponse, error) }else { handler(nil, error) } } } }
// // AdoptionDetailViewController.swift // Article // // Created by 陳柏勳 on 2017/5/17. // Copyright © 2017年 LeoChen. All rights reserved. // import UIKit class AdoptionDetailViewController: UIViewController { let adoptionInfo = memberIdCache.sharedInstance() @IBOutlet weak var petName: UILabel! @IBOutlet weak var petGender: UILabel! @IBOutlet weak var petAge: UILabel! @IBOutlet weak var petVariety: UILabel! @IBOutlet weak var contactName: UILabel! @IBOutlet weak var telephoneNumber: UILabel! @IBOutlet weak var email: UILabel! @IBOutlet weak var remark: UILabel! @IBOutlet weak var petImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() petName.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["petName"] as? String petGender.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["petGender"] as? String petAge.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["petAge"] as? String petVariety.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["petVariety"] as? String contactName.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["contactName"] as? String telephoneNumber.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["telephoneNumber"] as? String email.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["email"] as? String remark.text = (self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["remark"] as? String let saveFilePathString = ((self.adoptionInfo.adoptionFireUploadDic?[self.adoptionInfo.adoptionList[adoptionInfo.selectAdoptionRow]])?["AdoptionPetImageFileName"] as? String)! let saveFilePath = NSTemporaryDirectory() + "\(saveFilePathString).data" petImage.image = UIImage(contentsOfFile: saveFilePath)! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // WBStatus.swift // swiftWEBO // // Created by 姬方方 on 2017/5/10. // Copyright © 2017年 JFF. All rights reserved. // import UIKit class WBStatus: NSObject { // Int 类型, 在64位的机器是64位,在32位的机器是32位 //如果不写 Int64 在ipad 2/iphone5/5c/4s/4无法运行 var id: Int64 = 0 //微博信息内容 var text:String? var reposts_count:Int=0 var comments_count:Int=0 var attitudes_count:Int=0 // 注意服务器返回的key要一致 var user:WBUser? // 被转发的原创微博 var retweeted_status:WBStatus? var pic_urls:[WBStatusPicture]? //重写 description 的计算型属性 override var description: String { return yy_modelDescription() } /// 类函数 —》告诉第三方框架yy_MOdel 如果遇到数组类型的属性 数组中存放什么类型的对象 // NSARRAY 保存的对象通常是‘ID’泪腺 ///OC中的泛类型是 swift 推出后 苹果为了兼容给 OC 添加的,从运行时的角度看 仍然不知道数组中存放什么类型的对象 /// - Returns: <#return value description#> class func modelContainerPropertyGenericClass() -> [String:AnyClass] { return ["pic_urls":WBStatusPicture.self] } }
// // Beizer.swift // beizer // // Created by MyGlamm on 8/1/19. // Copyright © 2019 MyGlamm. All rights reserved. // import UIKit @IBDesignable class Beizer: UIView { private var imageView : UIImageView! private var label = UILabel() var labelText = ""{ didSet { label.text = labelText } } override init(frame: CGRect) { super.init(frame: CGRect.zero) setupLabel(text : labelText) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLabel(text : labelText) } private func setupLabel(text : String){ label.text = "My Default value is My Default value is My Default value is My Default value is My Default value is My Default value is" label.numberOfLines = 2 addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 8).isActive = true NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -(frame.width * 0.25)).isActive = true NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0).isActive = true } override func draw(_ rect: CGRect) { let y:CGFloat = 20 let myBezier = UIBezierPath() myBezier.move(to: CGPoint(x: 0, y: y)) myBezier.addLine(to: CGPoint(x: rect.width * 0.7, y: y)) myBezier.addQuadCurve(to: CGPoint(x: rect.width * 0.75, y: 15), controlPoint: CGPoint(x: rect.width * 0.725, y: 20.5)) myBezier.addQuadCurve(to: CGPoint(x: rect.width * 0.85, y: 0), controlPoint: CGPoint(x: rect.width * 0.8, y: 0)) myBezier.addQuadCurve(to: CGPoint(x: rect.width * 0.95, y: 15), controlPoint: CGPoint(x: rect.width * 0.9, y: 0)) myBezier.addQuadCurve(to: CGPoint(x: rect.width , y: 20), controlPoint: CGPoint(x: rect.width * 0.97, y: 20.5)) myBezier.addLine(to: CGPoint(x: rect.width, y: rect.height)) myBezier.addLine(to: CGPoint(x: 0, y: rect.height)) myBezier.close() let context = UIGraphicsGetCurrentContext() context!.setLineWidth(4.0) UIColor.blue.setFill() myBezier.fill() if let image = UIImage.init(named: "70776Copy.png", in: Bundle(for: self.classForCoder), compatibleWith: traitCollection){ print("found it") image.draw(in: CGRect(x: (rect.width * 0.85) - 16 , y: 8, width: rect.width * 0.1, height: rect.width * 0.1)) } } }
// // FileDisplayTableViewController.swift // VoiceRecorder // // Created by Soan Saini on 27/2/17. // Copyright © 2017 Soan Saini. All rights reserved. // import UIKit class FileDisplayTableViewController: UITableViewController { var filePath: String? var fileDisplayViewModel: FileDisplayViewModel? override func viewDidLoad() { super.viewDidLoad() self.clearsSelectionOnViewWillAppear = false fileDisplayViewModel = FileDisplayViewModel(filePath: self.filePath!) self.tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.fileDisplayViewModel?.fileDisplayData?.count)! } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let modelObj = self.fileDisplayViewModel?.fileDisplayData?[indexPath.row]{ switch modelObj.fileType { case .Directory: let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) return cell case .RecordedFile: let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell", for: indexPath) as! RecordedFileTableViewCell cell.configureView(fileMetadata: modelObj) return cell } } else{ let cell = tableView.dequeueReusableCell(withIdentifier: "BlankCell", for: indexPath) return cell } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if let modelObj = self.fileDisplayViewModel?.fileDisplayData?[indexPath.row]{ self.fileDisplayViewModel?.removeFileWithMetaData(fileMetaData: modelObj, index: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let modelObj = self.fileDisplayViewModel?.fileDisplayData?[indexPath.row]{ switch modelObj.fileType { case .Directory: return 65 case .RecordedFile: return 65 } } else{ return 44 } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "playSound", sender: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "playSound"{ let destinationView: MediaPlayerViewController = segue.destination as! MediaPlayerViewController if let indexSelected = self.tableView.indexPathForSelectedRow { let playerData = self.fileDisplayViewModel?.fileDisplayData?[indexSelected.row] destinationView.playerData = playerData } } } }
// // APIConstant.swift // PhotosProject // // Created by Yusuf ali cezik on 20.01.2020. // Copyright © 2020 Yusuf Ali Cezik. All rights reserved. // import Foundation struct APIConstants{ private static let BASE_URL = "https://jsonplaceholder.typicode.com/" private static let PHOTOS = "photos/" private static let ALBUMS = "albums/" private static let USERS = "users/" private static let COMMENTS = "comments" static var user_id: Int! static var album_id: Int! static var photo_id: Int! static var PHOTOS_LIST: String { return BASE_URL + PHOTOS } static var ALBUM: String { return BASE_URL + ALBUMS + String(album_id) } static var USER_DETAILS: String { return BASE_URL + USERS + String(user_id) } //"https://jsonplaceholder.typicode.com/photos/{:id}/comments" isteği tüm commentleri getiriyordu. Posta ait commentler için aşağıdaki url'i kullandım. //postid 100 den fazla olunca herhangi bir comment dönmüyor. Servis bu şekilde olduğundan. static var PHOTO_COMMENTS: String { return BASE_URL + PHOTOS + String(photo_id) + "/" + COMMENTS + "?postId=\(photo_id!)" } }
// // UtilsRepositoryProtocol.swift // WavesWallet-iOS // // Created by Pavel Gubin on 3/12/19. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import RxSwift public protocol UtilsRepositoryProtocol { func timestampServerDiff(accountAddress: String) -> Observable<Int64> }
// // TractorListViewController.swift // TractorApp // // Created by BillBo on 2018/8/23. // Copyright © 2018年 BillBo. All rights reserved. // import UIKit class TractorListViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,InforListTableViewCellDelegate { //定义枚举区分列表类型 enum TractorListType{ case SearchType,ListType,Collect } //TODO:利用闭包实现cell点击回调 ⤵️ typealias cellClickBlock = (_ args:Any)->() var cellBlock:cellClickBlock? func getCellClick(block:cellClickBlock?) -> Void { cellBlock = block } //TODO:利用闭包实现cell点击回调 ⤴️ @IBOutlet weak var mTbv: UITableView! private var listType:TractorListType! init(type:TractorListType) { super.init(nibName: nil, bundle: nil) self.listType = type } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.mTbv.mj_header = MJRefreshStateHeader.init(refreshingTarget: self, refreshingAction: #selector(refresh)) self.mTbv.mj_header.beginRefreshing() } @objc func refresh()->Void { self.showHUD() let reqeust = NetworkRequest.reqeustForTop250List(start: 0, count: 20) NetworkManager.manager.sendRequest(type: Top250Model.self, request: reqeust, success: { [weak self] data in let top250:Top250Model = data as! Top250Model print(top250.title) self?.hideHUD() self?.mTbv.mj_header.endRefreshing() }) { (error) in self.mTbv.mj_header.endRefreshing() self.showTextHUD(message: "请求失败", hideAfterDelay: 2) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:InforListTableViewCell = InforListTableViewCell.xibCell(tableView: tableView, identifier: InforListTableViewCell_ID) as! InforListTableViewCell cell.delegate = (self as InforListTableViewCellDelegate) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 180 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //点击cell ,调用闭包实现回调 if let block = self.cellBlock { block("点击cell 闭包回调 - dosomething") } } //TODO:InforListTableViewCellDelegate func phone(args: Any?) { if args == nil { return } let phoe:String = args as! String let telphone:String = "telprompt://" + phoe let url:URL! = URL.init(string: telphone) if UIApplication.shared.canOpenURL(url) { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:]) { (result) in } } else { UIApplication.shared.openURL(url) } } } func work(args: Any?) { } func navigation(args: Any?) { MapNavigationHelper.naviagion(startAdd: "起点", startLocation: MapDataManager.manager.userLocation!, endLocation: CLLocationCoordinate2DMake(31.469746,120.270756), endAdd: "终点") } func map(args: Any?) { let mapDetailVC:MapDetailViewController! = MapDetailViewController(nibName: nil, bundle: nil) self.parent?.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(mapDetailVC, animated: true) self.parent?.hidesBottomBarWhenPushed = self.listType == TractorListType.ListType ? false : true } func config(args: Any?) { let configVC:ConfigBaseViewController! = ConfigBaseViewController(nibName: nil, bundle: nil) self.parent?.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(configVC, animated: true) self.parent?.hidesBottomBarWhenPushed = self.listType == TractorListType.ListType ? false : true } func collect(args: Any?, cell: UITableViewCell) { let indexP:IndexPath! = self.mTbv.indexPath(for: cell) print(indexP.row) } }