hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
46c8fd0b8e3b5b4795b5be1477c83b14836a9e5e
1,100
/*: ## Adding Items You learned earlier that an array of `String` values has the type `[String]`. Remember from the Instances playground that a type followed by parentheses is how you create an instance of that type. To create a mutable empty array that will hold strings, do this: */ var list = [String]() //: Once you've created the array, there are several ways to add items to it. You can add a single item using the `append` instance method: list.append("Banana") //: You can add an item at a specific index using the `insert` instance method. As with everywhere you use an index, it has to be within the array or the program will crash: list.insert("Kumquat", at: 0) //: You can append a whole array of items using the compound assignment operator `+=`: list += ["Strawberry", "Plum", "Watermelon"] //: - experiment: Practice adding items to the list using each of the three methods. Which do you prefer? When might you want to use each one? //: Move on to find out how to remove items from an array.\ //: [Previous](@previous) | page 9 of 17 | [Next: Removing Items](@next)
44
184
0.72
ac646a04bf94ebc625a43eccabe670d0a27e6213
21,081
// // VerbDetailsViewController.swift // EnglishVerbsiOS // // Created by xengar on 2017-12-13. // Copyright © 2017 xengar. All rights reserved. // import UIKit class VerbDetailsViewController: UIViewController { // MARK: Properties var verb : Verb! var conjugation : Conjugation! @IBOutlet weak var infinitive : UILabel! @IBOutlet weak var simplePast : UILabel! @IBOutlet weak var pastParticiple : UILabel! @IBOutlet weak var phoneticInfinitive : UILabel! @IBOutlet weak var phoneticSimplePast : UILabel! @IBOutlet weak var phoneticPastParticiple : UILabel! @IBOutlet weak var translation : UILabel! @IBOutlet weak var definition : UILabel! @IBOutlet weak var sample1 : UILabel! @IBOutlet weak var sample2 : UILabel! @IBOutlet weak var sample3 : UILabel! @IBOutlet weak var simplePresentI : UILabel! @IBOutlet weak var simplePresentYou : UILabel! @IBOutlet weak var simplePresentHe : UILabel! @IBOutlet weak var simplePresentWe : UILabel! @IBOutlet weak var simplePresentYoup : UILabel! @IBOutlet weak var simplePresentThey : UILabel! @IBOutlet weak var presentContinuousI : UILabel! @IBOutlet weak var presentContinuousYou : UILabel! @IBOutlet weak var presentContinuousHe : UILabel! @IBOutlet weak var presentContinuousWe : UILabel! @IBOutlet weak var presentContinuousYoup : UILabel! @IBOutlet weak var presentContinuousThey : UILabel! @IBOutlet weak var presentPerfectI : UILabel! @IBOutlet weak var presentPerfectYou : UILabel! @IBOutlet weak var presentPerfectHe : UILabel! @IBOutlet weak var presentPerfectWe : UILabel! @IBOutlet weak var presentPerfectYoup : UILabel! @IBOutlet weak var presentPerfectThey : UILabel! @IBOutlet weak var presentPerfectContinuousI : UILabel! @IBOutlet weak var presentPerfectContinuousYou : UILabel! @IBOutlet weak var presentPerfectContinuousHe : UILabel! @IBOutlet weak var presentPerfectContinuousWe : UILabel! @IBOutlet weak var presentPerfectContinuousYoup : UILabel! @IBOutlet weak var presentPerfectContinuousThey : UILabel! @IBOutlet weak var simplePastI : UILabel! @IBOutlet weak var simplePastYou : UILabel! @IBOutlet weak var simplePastHe : UILabel! @IBOutlet weak var simplePastWe : UILabel! @IBOutlet weak var simplePastYoup : UILabel! @IBOutlet weak var simplePastThey : UILabel! @IBOutlet weak var pastContinuousI : UILabel! @IBOutlet weak var pastContinuousYou : UILabel! @IBOutlet weak var pastContinuousHe : UILabel! @IBOutlet weak var pastContinuousWe : UILabel! @IBOutlet weak var pastContinuousYoup : UILabel! @IBOutlet weak var pastContinuousThey : UILabel! @IBOutlet weak var pastPerfectI : UILabel! @IBOutlet weak var pastPerfectYou : UILabel! @IBOutlet weak var pastPerfectHe : UILabel! @IBOutlet weak var pastPerfectWe : UILabel! @IBOutlet weak var pastPerfectYoup : UILabel! @IBOutlet weak var pastPerfectThey : UILabel! @IBOutlet weak var pastPerfectContinuousI : UILabel! @IBOutlet weak var pastPerfectContinuousYou : UILabel! @IBOutlet weak var pastPerfectContinuousHe : UILabel! @IBOutlet weak var pastPerfectContinuousWe : UILabel! @IBOutlet weak var pastPerfectContinuousYoup : UILabel! @IBOutlet weak var pastPerfectContinuousThey : UILabel! @IBOutlet weak var simpleFutureI : UILabel! @IBOutlet weak var simpleFutureYou : UILabel! @IBOutlet weak var simpleFutureHe : UILabel! @IBOutlet weak var simpleFutureWe : UILabel! @IBOutlet weak var simpleFutureYoup : UILabel! @IBOutlet weak var simpleFutureThey : UILabel! @IBOutlet weak var futureContinuousI : UILabel! @IBOutlet weak var futureContinuousYou : UILabel! @IBOutlet weak var futureContinuousHe : UILabel! @IBOutlet weak var futureContinuousWe : UILabel! @IBOutlet weak var futureContinuousYoup : UILabel! @IBOutlet weak var futureContinuousThey : UILabel! @IBOutlet weak var futurePerfectI : UILabel! @IBOutlet weak var futurePerfectYou : UILabel! @IBOutlet weak var futurePerfectHe : UILabel! @IBOutlet weak var futurePerfectWe : UILabel! @IBOutlet weak var futurePerfectYoup : UILabel! @IBOutlet weak var futurePerfectThey : UILabel! @IBOutlet weak var futurePerfectContinuousI : UILabel! @IBOutlet weak var futurePerfectContinuousYou : UILabel! @IBOutlet weak var futurePerfectContinuousHe : UILabel! @IBOutlet weak var futurePerfectContinuousWe : UILabel! @IBOutlet weak var futurePerfectContinuousYoup : UILabel! @IBOutlet weak var futurePerfectContinuousThey : UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. fillVerbDetails(verb) conjugation = processConjugation(verb) fillConjugationDetails(conjugation) } 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. } */ // MARK: - Verb Details private func fillVerbDetails(_ verb : Verb) { infinitive.text = verb.infinitive simplePast.text = verb.simplePast pastParticiple.text = verb.pastParticiple phoneticInfinitive.text = verb.phoneticInfinitive phoneticSimplePast.text = verb.phoneticSimplePast phoneticPastParticiple.text = verb.phoneticPastParticiple translation.text = verb.translationFR definition.text = verb.definition sample1.text = verb.sample1 sample2.text = verb.sample2 sample3.text = verb.sample3 } // MARK: - Verb Conjugations private func processConjugation(_ verb : Verb) -> Conjugation { let c : Conjugation = Conjugation() conjugateSimplePresent(c, verb.infinitive) conjugatePresentContinuous(c, verb.presentParticiple) conjugatePresentPerfect(c, verb.pastParticiple) conjugatePresentPerfectContinuous(c, verb.presentParticiple) conjugateSimplePast(c, verb.simplePast) conjugatePastContinuous(c, verb.presentParticiple) conjugatePastPerfect(c, verb.pastParticiple) conjugatePastPerfectContinuous(c, verb.presentParticiple) conjugateSimpleFuture(c, verb.infinitive) conjugateFutureContinuous(c, verb.presentParticiple) conjugateFuturePerfect(c, verb.pastParticiple) conjugateFuturePerfectContinuous(c, verb.presentParticiple) return c } private func conjugateSimplePresent(_ c : Conjugation, _ infinitive : String) { if (infinitive.count < 2 ) { return } if (infinitive.elementsEqual("be")) { c.simplePresentI = "I am" c.simplePresentYou = "you are" c.simplePresentHe = "he/she/it is" c.simplePresentWe = "we are" c.simplePresentYoup = "you are" c.simplePresentThey = "they are" } else { c.simplePresentI = "I " + infinitive; c.simplePresentYou = "you " + infinitive; // Rules: http://www.ef.com/english-resources/english-grammar/simple-present-tense/ // - In the third person singular the verb always ends in -s // - Verbs ending in -y : the third person changes the -y to -ies: // fly --> flies, cry --> cries // Exception: if there is a vowel before the -y: // play --> plays, pray --> prays // Rules: http://www.grammar.cl/Present/Simple.htm // - Add -es to verbs ending in: -ss, -x, -sh, -ch, -o, -z: // he passes, she catches, he fixes, it pushes, goes, washes, kisses, buzzes if (infinitive.elementsEqual("have")) { // exception c.simplePresentHe = "he/she/it has" } else if (infinitive.hasSuffix("y") && !(infinitive.hasSuffix("ay") || infinitive.hasSuffix("ey") || infinitive.hasSuffix("iy") || infinitive.hasSuffix("oy") || infinitive.hasSuffix("uy"))) { c.simplePresentHe = "he/she/it " + infinitive.prefix(infinitive.count - 1) + "ies" } else if (infinitive.hasSuffix("ss") || infinitive.hasSuffix("x") || infinitive.hasSuffix("sh") || infinitive.hasSuffix("ch") || infinitive.hasSuffix("o") || infinitive.hasSuffix("z")) { c.simplePresentHe = "he/she/it " + infinitive + "es" } else { c.simplePresentHe = "he/she/it " + infinitive + "s" } c.simplePresentWe = "we " + infinitive c.simplePresentYoup = "you " + infinitive c.simplePresentThey = "they " + infinitive } } private func conjugatePresentContinuous(_ c : Conjugation, _ presentParticiple : String) { // Rules: https://www.englishclub.com/grammar/verb-tenses_present-continuous.htm // subject + auxiliary verb be (simple present) + verb -ing (Present Participle) c.presentContinuousI = "I am " + presentParticiple c.presentContinuousYou = "you are " + presentParticiple c.presentContinuousHe = "he/she/it is " + presentParticiple c.presentContinuousWe = "we are " + presentParticiple c.presentContinuousYoup = "you are " + presentParticiple c.presentContinuousThey = "they are " + presentParticiple } private func conjugatePresentPerfect(_ c : Conjugation, _ pastParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/present-perfect/ // subject + auxiliary verb have (present tense) + past participle of verb c.presentPerfectI = "I have " + pastParticiple c.presentPerfectYou = "you have " + pastParticiple c.presentPerfectHe = "he/she/it has " + pastParticiple c.presentPerfectWe = "we have " + pastParticiple c.presentPerfectYoup = "you have " + pastParticiple c.presentPerfectThey = "they have " + pastParticiple } private func conjugatePresentPerfectContinuous(_ c : Conjugation, _ presentParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/present-perfect-continuous/ // subject + present perfect of the verb 'to be' (have/has been) + verb -ing (Present Participle) c.presentPerfectContinuousI = "I have been " + presentParticiple c.presentPerfectContinuousYou = "you have been " + presentParticiple c.presentPerfectContinuousHe = "he/she/it has been " + presentParticiple c.presentPerfectContinuousWe = "we have been " + presentParticiple c.presentPerfectContinuousYoup = "you have been " + presentParticiple c.presentPerfectContinuousThey = "they have been " + presentParticiple } private func conjugateSimplePast(_ c : Conjugation, _ simplePast : String) { // Rules: https://www.grammarly.com/blog/simple-past/ // subject + simple past of verb if (simplePast.elementsEqual("was, were")) { // exception for verb to be c.simplePastI = "I was" c.simplePastYou = "you were" c.simplePastHe = "he/she/it was" c.simplePastWe = "we were" c.simplePastYoup = "you were" c.simplePastThey = "they were" } else { c.simplePastI = "I " + simplePast c.simplePastYou = "you " + simplePast c.simplePastHe = "he/she/it " + simplePast c.simplePastWe = "we " + simplePast c.simplePastYoup = "you " + simplePast c.simplePastThey = "they " + simplePast } } private func conjugatePastContinuous(_ c : Conjugation, _ presentParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/past-continuous-tense/ // subject + past tense of the verb "to be" (was/were) + verb -ing (Present Participle) c.pastContinuousI = "I was " + presentParticiple c.pastContinuousYou = "you were " + presentParticiple c.pastContinuousHe = "he/she/it was " + presentParticiple c.pastContinuousWe = "we were " + presentParticiple c.pastContinuousYoup = "you were " + presentParticiple c.pastContinuousThey = "they were " + presentParticiple } private func conjugatePastPerfect(_ c : Conjugation, _ pastParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/past-perfect-tense/ // subject + past tense of the verb "to have" (had) + Past Participle c.pastPerfectI = "I had " + pastParticiple c.pastPerfectYou = "you had " + pastParticiple c.pastPerfectHe = "he/she/it had " + pastParticiple c.pastPerfectWe = "we had " + pastParticiple c.pastPerfectYoup = "you had " + pastParticiple c.pastPerfectThey = "they had " + pastParticiple } private func conjugatePastPerfectContinuous(_ c : Conjugation, _ presentParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/past-perfect-continuous/ // subject + past perfect of the verb "to be" (had been) + verb -ing (Present Participle) c.pastPerfectContinuousI = "I had been " + presentParticiple c.pastPerfectContinuousYou = "you had been " + presentParticiple c.pastPerfectContinuousHe = "he/she/it had been " + presentParticiple c.pastPerfectContinuousWe = "we had been " + presentParticiple c.pastPerfectContinuousYoup = "you had been " + presentParticiple c.pastPerfectContinuousThey = "they had been " + presentParticiple } private func conjugateSimpleFuture(_ c : Conjugation, _ infinitive : String) { // Rules: http://www.ef.com/english-resources/english-grammar/simple-future-tense/ // subject + "will" or "shall" (less common) + infinitive of verb c.simpleFutureI = "I will " + infinitive c.simpleFutureYou = "you will " + infinitive c.simpleFutureHe = "he/she/it will " + infinitive c.simpleFutureWe = "we will " + infinitive c.simpleFutureYoup = "you will " + infinitive c.simpleFutureThey = "they will " + infinitive } private func conjugateFutureContinuous(_ c : Conjugation, _ presentParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/future-continuous/ // subject + simple future of the verb "to be" (will be) + verb -ing (Present Participle) c.futureContinuousI = "I will be " + presentParticiple c.futureContinuousYou = "you will be " + presentParticiple c.futureContinuousHe = "he/she/it will be " + presentParticiple c.futureContinuousWe = "we will be " + presentParticiple c.futureContinuousYoup = "you will be " + presentParticiple c.futureContinuousThey = "they will be " + presentParticiple } private func conjugateFuturePerfect(_ c : Conjugation, _ pastParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/future-perfect/ // subject + future simple of the verb "to have" (will have) + Past Participle c.futurePerfectI = "I will have " + pastParticiple c.futurePerfectYou = "you will have " + pastParticiple c.futurePerfectHe = "he/she/it will have " + pastParticiple c.futurePerfectWe = "we will have " + pastParticiple c.futurePerfectYoup = "you will have " + pastParticiple c.futurePerfectThey = "they will have " + pastParticiple } private func conjugateFuturePerfectContinuous(_ c : Conjugation, _ presentParticiple : String) { // Rules: http://www.ef.com/english-resources/english-grammar/future-perfect-continuous/ // subject + future perfect of the verb "to be" (will have been) + verb -ing (Present Participle) c.futurePerfectContinuousI = "I will have been " + presentParticiple c.futurePerfectContinuousYou = "you will have been " + presentParticiple c.futurePerfectContinuousHe = "he/she/it will have been " + presentParticiple c.futurePerfectContinuousWe = "we will have been " + presentParticiple c.futurePerfectContinuousYoup = "you will have been " + presentParticiple c.futurePerfectContinuousThey = "they will have been " + presentParticiple } private func fillConjugationDetails(_ c : Conjugation) { simplePresentI.text = c.simplePresentI simplePresentYou.text = c.simplePresentYou simplePresentHe.text = c.simplePresentHe simplePresentWe.text = c.simplePresentWe simplePresentYoup.text = c.simplePresentYoup simplePresentThey.text = c.simplePresentThey presentContinuousI.text = c.presentContinuousI presentContinuousYou.text = c.presentContinuousYou presentContinuousHe.text = c.presentContinuousHe presentContinuousWe.text = c.presentContinuousWe presentContinuousYoup.text = c.presentContinuousYoup presentContinuousThey.text = c.presentContinuousThey presentPerfectI.text = c.presentPerfectI presentPerfectYou.text = c.presentPerfectYou presentPerfectHe.text = c.presentPerfectHe presentPerfectWe.text = c.presentPerfectWe presentPerfectYoup.text = c.presentPerfectYoup presentPerfectThey.text = c.presentPerfectThey presentPerfectContinuousI.text = c.presentPerfectContinuousI presentPerfectContinuousYou.text = c.presentPerfectContinuousYou presentPerfectContinuousHe.text = c.presentPerfectContinuousHe presentPerfectContinuousWe.text = c.presentPerfectContinuousWe presentPerfectContinuousYoup.text = c.presentPerfectContinuousYoup presentPerfectContinuousThey.text = c.presentPerfectContinuousThey simplePastI.text = c.simplePastI simplePastYou.text = c.simplePastYou simplePastHe.text = c.simplePastHe simplePastWe.text = c.simplePastWe simplePastYoup.text = c.simplePastYoup simplePastThey.text = c.simplePastThey pastContinuousI.text = c.pastContinuousI pastContinuousYou.text = c.pastContinuousYou pastContinuousHe.text = c.pastContinuousHe pastContinuousWe.text = c.pastContinuousWe pastContinuousYoup.text = c.pastContinuousYoup pastContinuousThey.text = c.pastContinuousThey pastPerfectI.text = c.pastPerfectI pastPerfectYou.text = c.pastPerfectYou pastPerfectHe.text = c.pastPerfectHe pastPerfectWe.text = c.pastPerfectWe pastPerfectYoup.text = c.pastPerfectYoup pastPerfectThey.text = c.pastPerfectThey pastPerfectContinuousI.text = c.pastPerfectContinuousI pastPerfectContinuousYou.text = c.pastPerfectContinuousYou pastPerfectContinuousHe.text = c.pastPerfectContinuousHe pastPerfectContinuousWe.text = c.pastPerfectContinuousWe pastPerfectContinuousYoup.text = c.pastPerfectContinuousYoup pastPerfectContinuousThey.text = c.pastPerfectContinuousThey simpleFutureI.text = c.simpleFutureI simpleFutureYou.text = c.simpleFutureYou simpleFutureHe.text = c.simpleFutureHe simpleFutureWe.text = c.simpleFutureWe simpleFutureYoup.text = c.simpleFutureYoup simpleFutureThey.text = c.simpleFutureThey futureContinuousI.text = c.futureContinuousI futureContinuousYou.text = c.futureContinuousYou futureContinuousHe.text = c.futureContinuousHe futureContinuousWe.text = c.futureContinuousWe futureContinuousYoup.text = c.futureContinuousYoup futureContinuousThey.text = c.futureContinuousThey futurePerfectI.text = c.futurePerfectI futurePerfectYou.text = c.futurePerfectYou futurePerfectHe.text = c.futurePerfectHe futurePerfectWe.text = c.futurePerfectWe futurePerfectYoup.text = c.futurePerfectYoup futurePerfectThey.text = c.futurePerfectThey futurePerfectContinuousI.text = c.futurePerfectContinuousI futurePerfectContinuousYou.text = c.futurePerfectContinuousYou futurePerfectContinuousHe.text = c.futurePerfectContinuousHe futurePerfectContinuousWe.text = c.futurePerfectContinuousWe futurePerfectContinuousYoup.text = c.futurePerfectContinuousYoup futurePerfectContinuousThey.text = c.futurePerfectContinuousThey } }
49.485915
110
0.682795
e9b0262a4b1b90ab466c9260ed6db4a5a0b286a9
1,539
// // ImageVC.swift // BaseProject // // Created by MAC MINI on 10/01/2018. // Copyright © 2018 Wave. All rights reserved. // import UIKit import FLAnimatedImage class ImageVC: BaseViewController { var img : UIImage! var urlMain : String! @IBOutlet weak var indicator: UIActivityIndicatorView! @IBOutlet weak var image: FLAnimatedImageView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { self.indicator.startAnimating() self.indicator.isHidden = false if urlMain.count > 0 { self.image.backgroundColor = UIColor.black self.image.image = nil self.image.loadGif(url: URL.init(string: WebServiceName.images_baseurl.rawValue + urlMain.RemoveSpace())!) // .sd_setImage(with: URL.init(string: WebServiceName.images_baseurl.rawValue + urlMain.RemoveSpace()), placeholderImage: nil, completed: { (image, error, chache, url) in // self.indicator.isHidden = true // }) }else { self.indicator.isHidden = true self.image.image = img } } @IBAction func Home_Btn(_ sender: Any) { self.GotoHome() } @IBAction func Back_Btn(_ sender: Any) { self.navigationController?.popViewController(animated: true) } }
30.78
185
0.632878
75802f5d44f1bd0cbffdb01d149915e0ca9e617c
12,938
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: gui.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 you 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 PBGui_InputKey: SwiftProtobuf.Enum { typealias RawValue = Int case up // = 0 case down // = 1 case right // = 2 case left // = 3 case ok // = 4 case back // = 5 case UNRECOGNIZED(Int) init() { self = .up } init?(rawValue: Int) { switch rawValue { case 0: self = .up case 1: self = .down case 2: self = .right case 3: self = .left case 4: self = .ok case 5: self = .back default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .up: return 0 case .down: return 1 case .right: return 2 case .left: return 3 case .ok: return 4 case .back: return 5 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension PBGui_InputKey: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [PBGui_InputKey] = [ .up, .down, .right, .left, .ok, .back, ] } #endif // swift(>=4.2) enum PBGui_InputType: SwiftProtobuf.Enum { typealias RawValue = Int ///*< Press event, emitted after debounce case press // = 0 ///*< Release event, emitted after debounce case release // = 1 ///*< Short event, emitted after InputTypeRelease done withing INPUT_LONG_PRESS interval case short // = 2 ///*< Long event, emmited after INPUT_LONG_PRESS interval, asynchronouse to InputTypeRelease case long // = 3 ///*< Repeat event, emmited with INPUT_REPEATE_PRESS period after InputTypeLong event case `repeat` // = 4 case UNRECOGNIZED(Int) init() { self = .press } init?(rawValue: Int) { switch rawValue { case 0: self = .press case 1: self = .release case 2: self = .short case 3: self = .long case 4: self = .repeat default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .press: return 0 case .release: return 1 case .short: return 2 case .long: return 3 case .repeat: return 4 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension PBGui_InputType: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [PBGui_InputType] = [ .press, .release, .short, .long, .repeat, ] } #endif // swift(>=4.2) struct PBGui_ScreenFrame { // 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: Data = Data() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct PBGui_StartScreenStreamRequest { // 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 unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct PBGui_StopScreenStreamRequest { // 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 unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct PBGui_SendInputEventRequest { // 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 key: PBGui_InputKey = .up var type: PBGui_InputType = .press var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct PBGui_StartVirtualDisplayRequest { // 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. /// optional var firstFrame: PBGui_ScreenFrame { get {return _firstFrame ?? PBGui_ScreenFrame()} set {_firstFrame = newValue} } /// Returns true if `firstFrame` has been explicitly set. var hasFirstFrame: Bool {return self._firstFrame != nil} /// Clears the value of `firstFrame`. Subsequent reads from it will return its default value. mutating func clearFirstFrame() {self._firstFrame = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _firstFrame: PBGui_ScreenFrame? = nil } struct PBGui_StopVirtualDisplayRequest { // 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 unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "PB_Gui" extension PBGui_InputKey: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UP"), 1: .same(proto: "DOWN"), 2: .same(proto: "RIGHT"), 3: .same(proto: "LEFT"), 4: .same(proto: "OK"), 5: .same(proto: "BACK"), ] } extension PBGui_InputType: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "PRESS"), 1: .same(proto: "RELEASE"), 2: .same(proto: "SHORT"), 3: .same(proto: "LONG"), 4: .same(proto: "REPEAT"), ] } extension PBGui_ScreenFrame: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ScreenFrame" 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() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBytesField(value: &self.data) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.data.isEmpty { try visitor.visitSingularBytesField(value: self.data, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PBGui_ScreenFrame, rhs: PBGui_ScreenFrame) -> Bool { if lhs.data != rhs.data {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PBGui_StartScreenStreamRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".StartScreenStreamRequest" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PBGui_StartScreenStreamRequest, rhs: PBGui_StartScreenStreamRequest) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PBGui_StopScreenStreamRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".StopScreenStreamRequest" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PBGui_StopScreenStreamRequest, rhs: PBGui_StopScreenStreamRequest) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PBGui_SendInputEventRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".SendInputEventRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "key"), 2: .same(proto: "type"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.key) }() case 2: try { try decoder.decodeSingularEnumField(value: &self.type) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.key != .up { try visitor.visitSingularEnumField(value: self.key, fieldNumber: 1) } if self.type != .press { try visitor.visitSingularEnumField(value: self.type, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PBGui_SendInputEventRequest, rhs: PBGui_SendInputEventRequest) -> Bool { if lhs.key != rhs.key {return false} if lhs.type != rhs.type {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PBGui_StartVirtualDisplayRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".StartVirtualDisplayRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "first_frame"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._firstFrame) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every if/case branch local when no optimizations // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and // https://github.com/apple/swift-protobuf/issues/1182 try { if let v = self._firstFrame { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PBGui_StartVirtualDisplayRequest, rhs: PBGui_StartVirtualDisplayRequest) -> Bool { if lhs._firstFrame != rhs._firstFrame {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension PBGui_StopVirtualDisplayRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".StopVirtualDisplayRequest" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: PBGui_StopVirtualDisplayRequest, rhs: PBGui_StopVirtualDisplayRequest) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } }
31.866995
144
0.713557
7ad3bac04081a6ebf6f2f0d8c400aeaf8dca996d
3,183
// // NSManagedObjectContext+Fetch.swift // TripKit // // Created by Adrian Schoenig on 22/9/16. // // import Foundation import CoreData extension NSManagedObjectContext { public func fetchObjects<E: NSManagedObject>(_ entity: E.Type, sortDescriptors: [NSSortDescriptor], predicate: NSPredicate? = nil, relationshipKeyPathsForPrefetching: [String]? = nil, fetchLimit: Int? = nil) -> [E] { let request = entity.fetchRequest() request.predicate = predicate request.sortDescriptors = sortDescriptors request.relationshipKeyPathsForPrefetching = relationshipKeyPathsForPrefetching if let fetchLimit = fetchLimit, fetchLimit > 0 { // Don't use negative value to enforce no fetch limit // as that is buggy and might set some random fetch // limit rather than returning all results! request.fetchLimit = fetchLimit } do { return try self.fetch(request) .compactMap { if let correct = $0 as? E { return correct } else { assertionFailure("Fetch did something weird and returned \($0). We expected an \(E.self).") return nil } } } catch { TKLog.error("Failed with error: \(error). Please file a bug with steps to reproduce this.") return [] } } public func fetchObjects<E: NSManagedObject>(_ entity: E.Type, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> [E] { let request = entity.fetchRequest() request.predicate = predicate request.sortDescriptors = sortDescriptors do { return try self.fetch(request) .compactMap { if let correct = $0 as? E { return correct } else { assertionFailure("Fetch did something weird and returned \($0). We expected an \(E.self).") return nil } } } catch { TKLog.error("Failed with error: \(error). Please file a bug with steps to reproduce this.") return [] } } public func fetchUniqueObject<E: NSManagedObject>(_ entity: E.Type, predicate: NSPredicate? = nil) -> E? { let request = entity.fetchRequest() request.predicate = predicate request.fetchLimit = 1 do { return try self.fetch(request) .compactMap { if let correct = $0 as? E { return correct } else { assertionFailure("Fetch did something weird and returned \($0). We expected an \(E.self).") return nil } } .first } catch { TKLog.error("Failed with error: \(error). Please file a bug with steps to reproduce this.") return nil } } public func containsObject<E: NSManagedObject>(_ entity: E.Type, predicate: NSPredicate? = nil) -> Bool { let request = entity.fetchRequest() request.predicate = predicate request.fetchLimit = 1 request.resultType = .countResultType do { return try self.count(for: request) > 0 } catch { TKLog.error("Failed with error: \(error). Please file a bug with steps to reproduce this.") return false } } }
30.605769
218
0.617028
3330c65826ebe6ce1be4b1a5525487d93f3dfeb6
3,964
// // EVReflectionEventKitTests.swift // UnitTests // // Created by Vermeer, Edwin on 28/04/2017. // Copyright © 2017 evict. All rights reserved. // #if os(tvOS) // Eventkit is not supported on tvOS #else import XCTest import Foundation import EventKit import EVReflection //import ObjectiveC.runtime /** Testing EVReflection with EKEvent */ extension EKObject : EVReflectable { open override func setValue(_ value: Any!, forUndefinedKey key: String) { if let kvc = self as? EVGenericsKVC { kvc.setGenericValue(value as! AnyObject, forUndefinedKey: key) } else { self.addStatusMessage(.IncorrectKey, message: "The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'") evPrint(.IncorrectKey, "\nWARNING: The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'\n There is no support for optional type, array of optionals or enum properties.\nAs a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information\n") } } override open func value(forUndefinedKey key: String) -> Any? { evPrint(.IncorrectKey, "\nWARNING: The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'\n") return nil } } let store = EKEventStore() class EVReflectionEventKitTests: XCTestCase { func testEventKit() { //TODO: fix // Needs a workaround. See http://stackoverflow.com/questions/43686690/mirror-of-ekevent-does-not-show-the-data let exp = expectation(description: "eventStore") store.requestAccess(to: .event, completion: { (granted, error) in let event = EKEvent(eventStore: store) event.startDate = Date().addingTimeInterval(10000) event.title = "title" event.location = "here" event.endDate = Date().addingTimeInterval(20000) event.notes = "notes" event.calendar = store.defaultCalendarForNewEvents event.addAlarm(EKAlarm(absoluteDate: Date().addingTimeInterval(10000))) //WARNING: You will get events in your agenda! Disable next line if you don't want that //try? store.save(event, span: EKSpan.thisEvent, commit: true) let m = Mirror(reflecting: event) print("mirror children = \(m.children.count)") let oc = self.properties(event) print(oc) for p in oc { var value: Any? = nil // Why can't we get the value like this!? value = event.value(forKey: p) print("\(p) = \(String(describing: value))") } let json = event.toJsonString() print("json = \(json)") let z = EKEvent(json: json) print(z) exp.fulfill() }) waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "\(error?.localizedDescription ?? "")") } } func properties(_ classToInspect: NSObject) -> [String] { var count = UInt32() let classToInspect = NSURL.self let properties = class_copyPropertyList(classToInspect, &count) var propertyNames = [String]() let intCount = Int(count) for i in 0 ..< intCount { let property : objc_property_t = properties![i] guard let propertyName = NSString(utf8String: property_getName(property)) as String? else { debugPrint("Couldn't unwrap property name for \(property)") break } propertyNames.append(propertyName) } free(properties) return propertyNames } } #endif
35.711712
365
0.603683
336c306ce88c639b81cd4757fdde73b21a3fe415
2,313
// // BirthdateAttributedDecorator.swift // ModuleExamples // // Created by Francisco Javier Trujillo Mata on 12/12/2018. // Copyright © 2018 Francisco Javier Trujillo Mata. All rights reserved. // import UIKit class BirthdateAttributedDecorator: CommonAttributedDecorator { override func attributedTitle() -> NSAttributedString? { let attr = NSMutableAttributedString() attr.append(mainAttributedInfo) attr.append(attributedBreakLine) attr.append(descAttributedInfo) return attr.copy() as? NSAttributedString } override func backgroundColor() -> UIColor? { return lightColor } } //MARK: - BirthdateAttributedDecorator private extension BirthdateAttributedDecorator { var mainColor : UIColor { .black } var softColor : UIColor { .gray } var lightColor : UIColor { UIColor(white: 0.9, alpha: 1.0) } var mainFont : UIFont { .boldSystemFont(ofSize:13) } var secondaryFont : UIFont { .systemFont(ofSize:13) } var smalFont : UIFont { .systemFont(ofSize:3) } var mainAttributes : [NSAttributedString.Key : Any] { return [ .font : mainFont, .foregroundColor : mainColor, ] } var softAttributes : [NSAttributedString.Key : Any] { return [ .font : secondaryFont, .foregroundColor : softColor, ] } var smallAttributes : [NSAttributedString.Key : Any] { return [ .font : smalFont, ] } var attributedBreakLine : NSAttributedString { return NSAttributedString(string: "\n", attributes:smallAttributes) } var mainAttributedInfo : NSAttributedString { let attr = NSMutableAttributedString() attr.append(NSAttributedString(string: "Francisco Javier, for your birthdate we'll donate €1 to a non-profit of your choice.\n", attributes: mainAttributes)) return attr } var descAttributedInfo : NSAttributedString { let attr = NSMutableAttributedString() attr.append(NSAttributedString(string: "Create your fundraiser to support a cause you care about, and we'll take care of the donation processing with no fees.\nRections apply.", attributes: softAttributes)) return attr } }
31.684932
214
0.658452
6a8aa43c6148d91f80d04df048588199f4305ed4
424
import XCTest @testable import LeetCode final class ReverseIntegerSpec: XCTestCase { fileprivate let questions: [((Int), Int)] = [ ((321), 123), ((-123), -321), ((120), 21), ((1534236469), 0) ] func testReverseInteger() { let solution = ReverseInteger() for ((x), answer) in questions { XCTAssertEqual(solution.reverse(x), answer) } } }
21.2
55
0.549528
915de6b1f8573112266cb0988714533cbc06c267
738
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import Foundation import Viperit final class ___FILEBASENAMEASIDENTIFIER___Presenter: Presenter { } // MARK: - VIPER COMPONENTS API (Auto-generated code) private extension ___FILEBASENAMEASIDENTIFIER___Presenter { var view: ___FILEBASENAMEASIDENTIFIER___ViewInterface { return _view as! ___FILEBASENAMEASIDENTIFIER___ViewInterface } var interactor: ___FILEBASENAMEASIDENTIFIER___Interactor { return _interactor as! ___FILEBASENAMEASIDENTIFIER___Interactor } var router: ___FILEBASENAMEASIDENTIFIER___Router { return _router as! ___FILEBASENAMEASIDENTIFIER___Router } }
26.357143
71
0.785908
624042c70d4caa9335e62e79671ca3034da3478c
13,869
// // ChartAnimationUtils.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit @objc public enum ChartEasingOption: Int { case Linear case EaseInQuad case EaseOutQuad case EaseInOutQuad case EaseInCubic case EaseOutCubic case EaseInOutCubic case EaseInQuart case EaseOutQuart case EaseInOutQuart case EaseInQuint case EaseOutQuint case EaseInOutQuint case EaseInSine case EaseOutSine case EaseInOutSine case EaseInExpo case EaseOutExpo case EaseInOutExpo case EaseInCirc case EaseOutCirc case EaseInOutCirc case EaseInElastic case EaseOutElastic case EaseInOutElastic case EaseInBack case EaseOutBack case EaseInOutBack case EaseInBounce case EaseOutBounce case EaseInOutBounce } public typealias ChartEasingFunctionBlock = ((elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat); internal func easingFunctionFromOption(easing: ChartEasingOption) -> ChartEasingFunctionBlock { switch easing { case .Linear: return EasingFunctions.Linear; case .EaseInQuad: return EasingFunctions.EaseInQuad; case .EaseOutQuad: return EasingFunctions.EaseOutQuad; case .EaseInOutQuad: return EasingFunctions.EaseInOutQuad; case .EaseInCubic: return EasingFunctions.EaseInCubic; case .EaseOutCubic: return EasingFunctions.EaseOutCubic; case .EaseInOutCubic: return EasingFunctions.EaseInOutCubic; case .EaseInQuart: return EasingFunctions.EaseInQuart; case .EaseOutQuart: return EasingFunctions.EaseOutQuart; case .EaseInOutQuart: return EasingFunctions.EaseInOutQuart; case .EaseInQuint: return EasingFunctions.EaseInQuint; case .EaseOutQuint: return EasingFunctions.EaseOutQuint; case .EaseInOutQuint: return EasingFunctions.EaseInOutQuint; case .EaseInSine: return EasingFunctions.EaseInSine; case .EaseOutSine: return EasingFunctions.EaseOutSine; case .EaseInOutSine: return EasingFunctions.EaseInOutSine; case .EaseInExpo: return EasingFunctions.EaseInExpo; case .EaseOutExpo: return EasingFunctions.EaseOutExpo; case .EaseInOutExpo: return EasingFunctions.EaseInOutExpo; case .EaseInCirc: return EasingFunctions.EaseInCirc; case .EaseOutCirc: return EasingFunctions.EaseOutCirc; case .EaseInOutCirc: return EasingFunctions.EaseInOutCirc; case .EaseInElastic: return EasingFunctions.EaseInElastic; case .EaseOutElastic: return EasingFunctions.EaseOutElastic; case .EaseInOutElastic: return EasingFunctions.EaseInOutElastic; case .EaseInBack: return EasingFunctions.EaseInBack; case .EaseOutBack: return EasingFunctions.EaseOutBack; case .EaseInOutBack: return EasingFunctions.EaseInOutBack; case .EaseInBounce: return EasingFunctions.EaseInBounce; case .EaseOutBounce: return EasingFunctions.EaseOutBounce; case .EaseInOutBounce: return EasingFunctions.EaseInOutBounce; } } internal struct EasingFunctions { internal static let Linear = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return CGFloat(elapsed / duration); }; internal static let EaseInQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position; }; internal static let EaseOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return -position * (position - 2.0); }; internal static let EaseInOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position; } return -0.5 * ((--position) * (position - 2.0) - 1.0); }; internal static let EaseInCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position; }; internal static let EaseOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return (position * position * position + 1.0); }; internal static let EaseInOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position; } position -= 2.0; return 0.5 * (position * position * position + 2.0); }; internal static let EaseInQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position * position; }; internal static let EaseOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return -(position * position * position * position - 1.0); }; internal static let EaseInOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position * position; } position -= 2.0; return -0.5 * (position * position * position * position - 2.0); }; internal static let EaseInQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return position * position * position * position * position; }; internal static let EaseOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return (position * position * position * position * position + 1.0); }; internal static let EaseInOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / (duration / 2.0)); if (position < 1.0) { return 0.5 * position * position * position * position * position; } else { position -= 2.0; return 0.5 * (position * position * position * position * position + 2.0); } }; internal static let EaseInSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( -cos(position * M_PI_2) + 1.0 ); }; internal static let EaseOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( sin(position * M_PI_2) ); }; internal static let EaseInOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; return CGFloat( -0.5 * (cos(M_PI * position) - 1.0) ); }; internal static let EaseInExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return (elapsed == 0) ? 0.0 : CGFloat(pow(2.0, 10.0 * (elapsed / duration - 1.0))); }; internal static let EaseOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return (elapsed == duration) ? 1.0 : (-CGFloat(pow(2.0, -10.0 * elapsed / duration)) + 1.0); }; internal static let EaseInOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0) { return 0.0; } if (elapsed == duration) { return 1.0; } var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { return CGFloat( 0.5 * pow(2.0, 10.0 * (position - 1.0)) ); } return CGFloat( 0.5 * (-pow(2.0, -10.0 * --position) + 2.0) ); }; internal static let EaseInCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); return -(CGFloat(sqrt(1.0 - position * position)) - 1.0); }; internal static let EaseOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position = CGFloat(elapsed / duration); position--; return CGFloat( sqrt(1 - position * position) ); }; internal static let EaseInOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { return CGFloat( -0.5 * (sqrt(1.0 - position * position) - 1.0) ); } position -= 2.0; return CGFloat( 0.5 * (sqrt(1.0 - position * position) + 1.0) ); }; internal static let EaseInElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / duration; if (position == 1.0) { return 1.0; } var p = duration * 0.3; var s = p / (2.0 * M_PI) * asin(1.0); position -= 1.0; return CGFloat( -(pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) ); }; internal static let EaseOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / duration; if (position == 1.0) { return 1.0; } var p = duration * 0.3; var s = p / (2.0 * M_PI) * asin(1.0); return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) + 1.0 ); }; internal static let EaseInOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed == 0.0) { return 0.0; } var position: NSTimeInterval = elapsed / (duration / 2.0); if (position == 2.0) { return 1.0; } var p = duration * (0.3 * 1.5); var s = p / (2.0 * M_PI) * asin(1.0); if (position < 1.0) { position -= 1.0; return CGFloat( -0.5 * (pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) ); } position -= 1.0; return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) * 0.5 + 1.0 ); }; internal static let EaseInBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in let s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / duration; return CGFloat( position * position * ((s + 1.0) * position - s) ); }; internal static let EaseOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in let s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / duration; position--; return CGFloat( (position * position * ((s + 1.0) * position + s) + 1.0) ); }; internal static let EaseInOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var s: NSTimeInterval = 1.70158; var position: NSTimeInterval = elapsed / (duration / 2.0); if (position < 1.0) { s *= 1.525; return CGFloat( 0.5 * (position * position * ((s + 1.0) * position - s)) ); } s *= 1.525; position -= 2.0; return CGFloat( 0.5 * (position * position * ((s + 1.0) * position + s) + 2.0) ); }; internal static let EaseInBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return 1.0 - EaseOutBounce(duration - elapsed, duration); }; internal static let EaseOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in var position: NSTimeInterval = elapsed / duration; if (position < (1.0 / 2.75)) { return CGFloat( 7.5625 * position * position ); } else if (position < (2.0 / 2.75)) { position -= (1.5 / 2.75); return CGFloat( 7.5625 * position * position + 0.75 ); } else if (position < (2.5 / 2.75)) { position -= (2.25 / 2.75); return CGFloat( 7.5625 * position * position + 0.9375 ); } else { position -= (2.625 / 2.75); return CGFloat( 7.5625 * position * position + 0.984375 ); } }; internal static let EaseInOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in if (elapsed < (duration / 2.0)) { return EaseInBounce(elapsed * 2.0, duration) * 0.5; } return EaseOutBounce(elapsed * 2.0 - duration, duration) * 0.5 + 0.5; }; };
35.200508
139
0.599899
019c5e0432d3011c71cc8d8bfaacfaadfa953db5
929
// // iOS_Tip_CalculatorTests.swift // iOS Tip CalculatorTests // // Created by P C on 12/21/20. // import XCTest @testable import iOS_Tip_Calculator class iOS_Tip_CalculatorTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.323529
111
0.672766
f736654b9c9dd0e49062940f9b06cf5ad8cb3a83
310
// // ReusableView.swift // WTFUserInterface // // Created by NP2 on 12/15/19. // Copyright © 2019 shndrs. All rights reserved. // import UIKit protocol ReusableView {} extension ReusableView where Self: UIView { static var reuseIdentifier: String { return String(describing: self) } }
16.315789
49
0.683871
21eea6dc259af95c90d88a4f282a6ae14588f2cf
1,156
// // VisionPowerTests.swift // VisionPowerTests // // Created by larryhou on 04/09/2017. // Copyright © 2017 larryhou. All rights reserved. // import XCTest @testable import VisionPower class VisionPowerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { let layout = AlbumPreviewViewLayout() // This is an example of a performance test case. self.measure { for _ in 0...1000 { layout.fitgrid(dimension:1080) } // Put the code you want to measure the time of here. } } }
24.083333
111
0.600346
fc3a114ed66368588f1593c9a7c2e1cdf2aa6c80
1,234
// // ViewController.swift // CATransitionDemo // // Created by iosci on 2016/11/29. // Copyright © 2016年 secoo. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. changeBackgroundColor() } @IBAction func handleClickAction(_ sender: UIButton) { print(sender.title(for: .normal)!) transition(with: sender.title(for: .normal)!, subType: CATransitionSubtype.fromLeft.rawValue) changeBackgroundColor() } private func transition(with type: String, subType: String) { let animation = CATransition() animation.duration = 0.5 animation.type = CATransitionType(rawValue: type) animation.subtype = CATransitionSubtype(rawValue: subType) animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) view.layer.add(animation, forKey: nil) } var index: Int = 0 private func changeBackgroundColor() { let imageName = (index > 0) ? "02.jpg" : "01.jpg" let image = UIImage(named: imageName) view.backgroundColor = UIColor(patternImage: image!) index = (index == 0) ? 1 : 0 } }
28.045455
96
0.711507
accd155105aee76b3597a7dca1e4043abcf235d3
112
// @expect error func addFive(_ x: inout Int) { x += 5 } var z = 2 addFive(&z) __VERIFIER_assert(z != 7)
10.181818
30
0.589286
3851c6684d015737ba667bb68ca820bacd17b424
309
// // CV2.swift // PodTest // // Created by Yume on 2015/3/22. // Copyright (c) 2015年 Yume. All rights reserved. // import UIKit import CustomView class CV2: CustomViewLayerStyle { @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label3: UILabel! }
18.176471
50
0.686084
e9d738c1484925279d2836b31fe31571854293bf
972
// // AppUIConfig.swift // SimpleMemo // // Created by 原口 弓子 on 2016/07/07. // Copyright © 2016年 原口 弓子. All rights reserved. // import UIKit class AppUIConfig: NSObject { ///ボールドフォント static func fontBold(font size : CGFloat) -> UIFont { return UIFont(name: "HiraKakuProN-W6", size: size)! } ///普通のフォント static func fontNormal(font size : CGFloat) -> UIFont { return UIFont(name: "HiraKakuProN-W3", size: size)! } ///NSDateを表示用に変換 static func convertNSdateForString(date : Date?) -> String { let dateFormatter = DateFormatter() if let formatString = DateFormatter.dateFormat(fromTemplate: "yyyyMMMdd HH:mm", options: 0, locale: NSLocale.current) { dateFormatter.dateFormat = formatString let formattedDateString = dateFormatter.string(from: date ?? Date()) return formattedDateString } return "" } }
24.923077
127
0.608025
7266946ce58bf36956886778bd98221f67de7474
1,107
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- protocol MyProtocol { func bar(); } struct StructTest { func foo() { print("Stop here in StructTest method") //% self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["StructTest"]) } } extension StructTest : MyProtocol { func bar() { print("Stop here in MyProtocol method") //% # disabled self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["StructTest"]) } } class ClassTest { func foo () { print ("Stop here in ClassTest method") //% self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["ClassTest"]) } } var st = StructTest() st.foo() st.bar() var ct = ClassTest() ct.foo()
27
141
0.6486
1431c55ca2cf0f071a2bf4fcbf6283daedf300e7
1,974
// // Copyright (c) 2019 muukii // // 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 /// Dictionary based index storage public struct HashIndex<Schema: EntitySchemaType, HashKey: Hashable, Entity: EntityType>: IndexType, Equatable { // FIXME: To be faster filter, use BTree private var backing: [HashKey : AnyHashable] = [:] public init() { } public mutating func _apply(removing: Set<AnyHashable>, entityName: EntityName) { if Entity.entityName == entityName { var keys: Set<HashKey> = .init() backing.forEach { key, value in if removing.contains(value) { keys.insert(key) } } keys.forEach { backing.removeValue(forKey: $0) } } } public subscript(key: HashKey) -> Entity.EntityID? { get { backing[key] as? Entity.EntityID } set { backing[key] = newValue as AnyHashable } } }
32.9
112
0.693009
9c75e4f435e33c441da2a03ef462be5f286a2e80
904
// // tipcalcTests.swift // tipcalcTests // // Created by Gabriella Alexis on 12/28/20. // Copyright © 2020 CodePath. All rights reserved. // import XCTest @testable import tipcalc class tipcalcTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.828571
111
0.654867
5d8f9fb5e98f6d270210d8ae786a2a758ec7b209
1,236
// // StyleApplicationService.swift // Example Project // // Created by David Jennes on 02/07/2019. // Copyright © 2019 Appwise. All rights reserved. // import AppwiseCore import StatefulUI final class StyleApplicationService: NSObject, ApplicationService { // swiftlint:disable:next discouraged_optional_collection func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).do { $0.barStyle = .black $0.barTintColor = Asset.Style.background.color $0.isTranslucent = false $0.shadowImage = UIImage() } StateEmptyView.appearance().do { $0.titleColor = .white $0.subtitleColor = .white $0.buttonBackgroundColor = Asset.Style.secondary.color $0.tintColor = .white } StateErrorView.appearance().do { $0.titleColor = .white $0.subtitleColor = .white $0.buttonBackgroundColor = Asset.Style.secondary.color $0.tintColor = .white } StateLoadingView.appearance().do { $0.activityIndicatorColor = .white $0.titleColor = .white $0.subtitleColor = .white $0.tintColor = .white } return true } }
26.869565
149
0.728964
de0c92ea74363fc2313ab3494ebea10f71529a5a
1,630
// Copyright © 2021 Brad Howes. All rights reserved. import AudioToolbox import os.log /** Protocol for UI controls that can provide a parameter value. */ public protocol AUParameterValueProvider: AnyObject { /// The current value for a parameter. var value: AUValue { get } } /** Protocol for controls that represent parameter values and can edit them. */ public protocol AUParameterEditor: AnyObject { /// The AUParameter being edited by the control var parameter: AUParameter { get } /** Notification that the parameter should change due to a widget control change. - parameter source: the control that caused the change */ func controlChanged(source: AUParameterValueProvider) func setValue(_ value: AUValue) func updateControl() } public class AUParameterEditorBase: NSObject { public let log: OSLog public let parameter: AUParameter public private(set) var parameterObserverToken: AUParameterObserverToken! public init(parameter: AUParameter) { self.log = Shared.logger("AUParameterEditor(" + parameter.displayName + ")") self.parameter = parameter super.init() parameterObserverToken = parameter.token(byAddingParameterObserver: { address, value in self.parameterChanged(address: address, value: value) }) } private func parameterChanged(address: AUParameterAddress, value: AUValue) { guard address == self.parameter.address else { return } DispatchQueue.main.async { self.handleParameterChanged(value: value) } } @objc internal func handleParameterChanged(value: AUValue) { fatalError("method not overridden by child class")} }
28.103448
114
0.746012
e037e4942e5df3f21bfac6a53f5f3f754d2e95fb
1,233
import Foundation public protocol File { var path: Path { get } var exists: Bool { get } init() init(path: Path) @discardableResult init(write: () -> String) throws @discardableResult init(path: Path, write: () -> String) throws func read() throws -> String func write(_ text: String) throws func remove() throws } struct FileImpl: File { let path: Path init() { self.init(path: .temp(isDirectory: false)) } init(path: Path) { self.path = path } @discardableResult init(write: () -> String) throws { try self.init(path: .temp(isDirectory: false), write: write) } @discardableResult init(path: Path, write: () -> String) throws { self.init(path: path) try self.write(write()) } var exists: Bool { return FileManager.default.fileExists(atPath: path.url.path) } func read() throws -> String { return try String(contentsOf: path.url, encoding: .utf8) } func write(_ text: String) throws { try text.write(to: path.url, atomically: true, encoding: .utf8) } func remove() throws { try FileManager.default.removeItem(at: path.url) } }
20.898305
71
0.595296
e5417534019d63360d5c1914b9aa9dc7222ea97b
2,080
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** An object specifying the Keyword enrichment and related parameters. */ public struct NluEnrichmentKeywords: Codable { /** When `true`, sentiment analysis of keywords will be performed on the specified field. */ public var sentiment: Bool? /** When `true`, emotion detection of keywords will be performed on the specified field. */ public var emotion: Bool? /** The maximum number of keywords to extract for each instance of the specified field. */ public var limit: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case sentiment = "sentiment" case emotion = "emotion" case limit = "limit" } /** Initialize a `NluEnrichmentKeywords` with member variables. - parameter sentiment: When `true`, sentiment analysis of keywords will be performed on the specified field. - parameter emotion: When `true`, emotion detection of keywords will be performed on the specified field. - parameter limit: The maximum number of keywords to extract for each instance of the specified field. - returns: An initialized `NluEnrichmentKeywords`. */ public init( sentiment: Bool? = nil, emotion: Bool? = nil, limit: Int? = nil ) { self.sentiment = sentiment self.emotion = emotion self.limit = limit } }
31.044776
113
0.684615
23e49e79112a79f6eb46781dd79afc6285000b9e
3,778
// // TagsView.swift // llitgi // // Created by Xavi Moll on 16/12/2018. // Copyright © 2018 xmollv. All rights reserved. // import UIKit import Foundation final class TagsView: UIView { //MARK: Private properties private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false return scrollView }() private lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.alignment = .fill stackView.distribution = .fillProportionally stackView.spacing = 8 return stackView }() private var buttonTags: [UIButton: Tag] = [:] //MARK: Public properties var selectedTag: ((Tag) -> Void)? = nil var tagsBackgroundColor: UIColor = .black var tagsTextColor: UIColor = .white var tagsViews: [UIButton] { return self.buttonTags.keys.map { $0 } } //MARK: Lifecycle override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.backgroundColor = .clear self.addSubview(self.scrollView) self.scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true self.scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true self.scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true self.scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true self.scrollView.addSubview(self.stackView) self.stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true self.stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true self.stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true self.stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true self.stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true } //MARK: Public methods func add(tags: [Tag]) { tags.forEach { tag in let tagButton = UIButton() tagButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) tagButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .caption2) tagButton.layer.cornerRadius = 2 tagButton.layer.masksToBounds = true tagButton.backgroundColor = self.tagsBackgroundColor tagButton.setTitleColor(self.tagsTextColor, for: .normal) tagButton.setTitle(tag.name, for: .normal) tagButton.addTarget(self, action: #selector(self.selected(tagButton:)), for: .touchUpInside) self.buttonTags[tagButton] = tag self.stackView.addArrangedSubview(tagButton) } } func clearTags() { self.buttonTags.removeAll() self.stackView.arrangedSubviews.forEach { self.stackView.removeArrangedSubview($0) $0.removeFromSuperview() } } //MARK: Private methods @objc private func selected(tagButton: UIButton) { guard let tag = self.buttonTags[tagButton] else { assertionFailure("Unable to find the tag") return } self.selectedTag?(tag) } }
36.326923
104
0.660138
502b13d0c1961977932c8837a427a8a9101c1414
361
// // FeesViewModelOutput.swift // stock-portfolio-tracker // // Created by nb-058-41b on 1/10/21. // import Foundation protocol FeesViewModelOutputType { var routingState: FeesRouting { get } var fees: [FeeViewItem] { get } var currencyOptions: [CurrencyViewItem] { get } var feesValue: String? { get } var feesSign: String? { get } }
21.235294
51
0.6759
f480e8827218566a499abb3452afbb8af27a613d
2,403
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import FirebaseManifest import Utils private enum Destination { case cpdc, trunk } enum Push { static func pushPodsToCPDC(gitRoot: URL) { push(to: .cpdc, gitRoot: gitRoot) } static func publishPodsToTrunk(gitRoot: URL) { push(to: .trunk, gitRoot: gitRoot) } private static func push(to destination: Destination, gitRoot: URL) { let cpdcLocation = findCpdc(gitRoot: gitRoot) let manifest = FirebaseManifest.shared for pod in manifest.pods.filter({ $0.releasing }) { let warningsOK = pod.allowWarnings ? "--allow-warnings" : "" let command: String = { switch destination { case .cpdc: return "pod repo push --skip-tests --use-json \(warningsOK) \(cpdcLocation) " + pod.skipImportValidation() + " \(pod.podspecName()) " + "--sources=sso://cpdc-internal/firebase.git,https://cdn.cocoapods.org" case .trunk: return "pod trunk push --skip-tests --synchronous \(warningsOK) " + pod.skipImportValidation() + " ~/.cocoapods/repos/\(cpdcLocation)/Specs/\(pod.name)/" + "\(manifest.versionString(pod))/\(pod.name).podspec.json" } }() Shell.executeCommand(command, workingDir: gitRoot) } } private static func findCpdc(gitRoot: URL) -> String { let command = "pod repo list | grep -B2 sso://cpdc-internal/firebase | head -1" let result = Shell.executeCommandFromScript(command, workingDir: gitRoot) switch result { case let .error(code, output): fatalError(""" `pod --version` failed with exit code \(code) Output from `pod repo list`: \(output) """) case let .success(output): print(output) return output.trimmingCharacters(in: .whitespacesAndNewlines) } } }
32.04
99
0.661257
dee3142b5dff18425bbebca7be16aa25c402ac8c
115
// // STTwitter+TVUploader.swift // Pods // // Created by Tomoya Hirano on 2016/08/29. // // import Foundation
11.5
43
0.652174
e0d4d931cfc6ee04f936b03d8bf6cc87472e43a7
1,209
// // OMSearchListTableViewArtistCell.swift // OMusic // // Created by Jonathan Lu on 2020/2/5. // Copyright © 2020 Jonathan Lu. All rights reserved. // import UIKit import SDWebImage //enum ItemType { // case Track // case Playlist // case Album // case Artist //} class OMSearchListTableViewArtistCell: UITableViewCell { @IBOutlet weak private var titleLabel: UILabel! @IBOutlet weak private var iconImageView: UIImageView! private(set) var item: AMArtist! override func awakeFromNib() { super.awakeFromNib() self.selectedBackgroundView = UIView.init(frame: self.frame) self.selectedBackgroundView?.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.3037510702) self.titleLabel.textColor = OMTheme.getTextColor() } func setupCell(item: AMArtist) { self.item = item self.titleLabel.text = item.attributes?.name fetchImage(URL.amCoverUrl(string: item.attributes?.url ?? "", size: 144), imageView: self.iconImageView) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
24.18
116
0.666667
4b636cc11637fb5b2caf1fce2be626e104f6edd9
2,360
/// Copyright (c) 2018 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit func userInputAlert(_ title: String, isSecure: Bool = false, text: String? = nil, callback: @escaping (String) -> Void) { let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) alert.addTextField(configurationHandler: { field in field.isSecureTextEntry = isSecure field.text = text }) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in guard let text = alert.textFields?.first?.text, !text.isEmpty else { userInputAlert(title, callback: callback) return } callback(text) }) let root = UIApplication.shared.keyWindow?.rootViewController root?.present(alert, animated: true, completion: nil) }
47.2
121
0.743644
08bb24119288dac56bd6d835a9632f535875b0be
427
// // JobQueue.swift // Telegrammer // // Created by Givi on 18/03/2019. // import Foundation import NIO public protocol JobQueue { associatedtype Context var jobs: SynchronizedArray<AnyJob<Context>> { get } func shutdownQueue() func scheduleOnce<J: Job>(_ job: J) throws -> Scheduled<J> where J.Context == Context func scheduleRepeated<J: Job>(_ job: J) -> RepeatedTask where J.Context == Context }
21.35
89
0.688525
1a075399e6290c1c7baa77af808fc740f173e53c
4,490
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: em/issuer/v1/issuer.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 you 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 } struct Em_Issuer_V1_Issuer { // 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 = String() var denoms: [String] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Em_Issuer_V1_Issuers { // 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 issuers: [Em_Issuer_V1_Issuer] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "em.issuer.v1" extension Em_Issuer_V1_Issuer: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Issuer" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "address"), 2: .same(proto: "denoms"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.address) }() case 2: try { try decoder.decodeRepeatedStringField(value: &self.denoms) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.address.isEmpty { try visitor.visitSingularStringField(value: self.address, fieldNumber: 1) } if !self.denoms.isEmpty { try visitor.visitRepeatedStringField(value: self.denoms, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Em_Issuer_V1_Issuer, rhs: Em_Issuer_V1_Issuer) -> Bool { if lhs.address != rhs.address {return false} if lhs.denoms != rhs.denoms {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Em_Issuer_V1_Issuers: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Issuers" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "issuers"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.issuers) }() default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.issuers.isEmpty { try visitor.visitRepeatedMessageField(value: self.issuers, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Em_Issuer_V1_Issuers, rhs: Em_Issuer_V1_Issuers) -> Bool { if lhs.issuers != rhs.issuers {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
36.803279
132
0.730958
5684c875f84bcbc5e24774b2e3f616c2ddce09e3
860
// // CheckSurveyResponse.swift // RMBTClient // // Created by Sergey Glushchenko on 2/5/18. // import ObjectMapper open class CheckSurveyResponse: BasicResponse { open var survies: [Survey]? open var survey: Survey? { get { return survies?.first } } override open func mapping(map: Map) { super.mapping(map: map) survies <- map["survey"] } open class Survey: Mappable { open var surveyUrl: String? open var isFilledUp: Bool? /// public init() { } /// required public init?(map: Map) { } /// open func mapping(map: Map) { surveyUrl <- map["survey_url"] isFilledUp <- map["is_filled_up"] } } }
18.297872
47
0.483721
fca1b55dcb50b2aa43485c426904eb22e492f51f
762
// // HourCollectionViewCell.swift // ForecastModule // // Created by Mena Bebawy on 2/7/20. // Copyright © 2020 Mena. All rights reserved. // import UIKit import Entities final class HourCollectionViewCell: UICollectionViewCell { @IBOutlet weak private var houreLabel: UILabel! @IBOutlet weak private var temperatureImageView: UIImageView! @IBOutlet weak private var temperatureLabel: UILabel! static let identifier = "HourCell" static let width: CGFloat = 80 func configure(_ forecast: Forecast) { houreLabel.text = forecast.hour temperatureLabel.text = forecast.main.temperature.celsiusTemperatureStyle() temperatureImageView.kf.setImage(with: URL(string: forecast.weather[0].iconURL)) } }
28.222222
88
0.724409
decb1f412d67927ab03ed401aafcbbec4acf26ab
3,249
// // AppDelegate.swift // twitter_alamofire_demo // // Created by Charles Hieger on 4/4/17. // Copyright © 2017 Charles Hieger. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // MARK: TODO: Check for logged in user NotificationCenter.default.addObserver(forName: Notification.Name("didLogout"), object: nil, queue: OperationQueue.main) { (Notification) in print("Logout notification received") let storyboard = UIStoryboard(name: "Main", bundle: nil) let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginViewController") self.window?.rootViewController = loginVC } if User.current != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let tabBarController = storyboard.instantiateViewController(withIdentifier: "TabBarController") window?.rootViewController = tabBarController } return true } // MARK: TODO: Open URL // OAuth step 2 func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // Handle urlcallback sent from Twitter APIManager.shared.handle(url: url) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.414286
285
0.707295
7601ae00448c764586532d7eaadc6f87ccf15b46
7,789
// // BoundTextFieldTests.swift // BoundTextFieldTests // // Created by Yann Armelin on 16/04/2019. // Copyright © 2019 Yann Armelin. All rights reserved. // import XCTest @testable import AmadeusCheckout fileprivate class RootModel : NSObject { @objc dynamic var value: String = "Foo" @objc dynamic var child = ChildModel() } fileprivate class ChildModel : NSObject { @objc dynamic var nestedValue: String = "Bar" } class BoundTextFieldTests: XCTestCase { var textField: BoundTextField! fileprivate var model: RootModel! override func setUp() { textField = BoundTextField(frame:CGRect(x: 0, y: 0, width: 200, height: 100)) model = RootModel() } override func tearDown() { textField = nil model = nil } func testBinbing() { // Set binding with root property textField.binding = DataModelBinding(model, keyPath: \.value) // Initial value XCTAssertEqual(textField.text , "Foo") // Model to view binding model.value = "Hello" XCTAssertEqual(textField.text , "Hello") XCTAssertEqual(textField.text , textField.viewValue) // View to model binding textField.text = "World" textField.editingChanged() //textField.sendActions(for: .editingChanged) XCTAssertEqual(model.value , "World") XCTAssertEqual(model.value , textField.binding?.value) // Set binding with nested property textField.binding = DataModelBinding(model, keyPath: \.child.nestedValue) // Initial value XCTAssertEqual(textField.text , "Bar") // Model to view binding model.child = ChildModel() model.child.nestedValue = "Batman" XCTAssertEqual(textField.text , "Batman") // View to model binding textField.text = "Superman" textField.editingChanged() XCTAssertEqual(model.child.nestedValue , "Superman") } func testFormatter() { // Set binding with root property textField.binding = DataModelBinding(model, keyPath: \.value) textField.binding?.formatter = { "/"+$0+"/" } XCTAssertEqual(textField.text , "/Foo/") model.value = "Hello" XCTAssertEqual(textField.text , "/Hello/") } func testParser() { // Set binding with root property textField.binding = DataModelBinding(model, keyPath: \.value) textField.binding?.parser = { $0.uppercased() } textField.text = "Superman" textField.editingChanged() XCTAssertEqual(model.value , "SUPERMAN") } class OKValidator: Validator { static let errorMessage = "NOTOK" func isValid(_ value: String, successHandler:@escaping SuccessHandler, failureHandler:@escaping FailureHandler) -> Void { if value == "OK" { successHandler() }else{ failureHandler(OKValidator.errorMessage) } } } func testSynchronousValidator() { // Set binding with root property textField.binding = DataModelBinding(model, keyPath: \.value) textField.binding?.validator = OKValidator() XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.errorText , "NOTOK") textField.text = "Superman" textField.editingChanged() XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.errorText , "NOTOK") textField.text = "OK" textField.editingChanged() XCTAssertEqual(textField.binding?.isValid , true) XCTAssertEqual(textField.errorText , nil) } class OKAsyncValidator: Validator { static let errorMessage = "NOTOK" var expectation: XCTestExpectation? = nil func isValid(_ value: String, successHandler:@escaping SuccessHandler, failureHandler:@escaping FailureHandler) -> Void { DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { if value == "OK" { successHandler() }else{ failureHandler(OKAsyncValidator.errorMessage) } self.expectation?.fulfill() } } } func testAsynchronousValidator() { // Set binding with root property textField.binding = DataModelBinding(model, keyPath: \.value) let asyncValidator = OKAsyncValidator() textField.binding?.validator = asyncValidator asyncValidator.expectation = self.expectation(description: "Accept") XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.binding?.isPending , true) XCTAssertEqual(textField.errorText , nil) waitForExpectations(timeout: 0.1, handler: nil) XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.binding?.isPending , false) XCTAssertEqual(textField.errorText , "NOTOK") asyncValidator.expectation = self.expectation(description: "Reject") textField.text = "OK" textField.editingChanged() XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.binding?.isPending , true) XCTAssertEqual(textField.errorText , nil) waitForExpectations(timeout: 0.1, handler: nil) XCTAssertEqual(textField.binding?.isValid , true) XCTAssertEqual(textField.binding?.isPending , false) XCTAssertEqual(textField.errorText , nil) } class KOValidator: Validator { static let errorMessage: String = "ERROR" func isValid(_ value: String, successHandler: @escaping SuccessHandler, failureHandler: @escaping FailureHandler) { failureHandler(KOValidator.errorMessage) } } func testHideError() { // We set up a field that is always invalid no matter its value textField.binding = DataModelBinding(model, keyPath: \.value) textField.binding?.validator = KOValidator() model.value = "" // Field is invalid, and error is displayed since value has changed XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.errorText , "ERROR") textField.text = "OK" textField.editingChanged() // Field is still invalid and error is invalid XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.errorText , "ERROR") //textField.binding?.hideErrorIfEmpty() // Field is still invalid and is not hidde, because field has a value XCTAssertEqual(textField.binding?.isValid , false) XCTAssertEqual(textField.errorText , "ERROR") } func testBindingAggregator() { let aggregator = DataModelBindingAggregator() let binding1 = DataModelBinding(model, keyPath: \.child.nestedValue) let binding2 = DataModelBinding(model, keyPath: \.value) binding1.validator = OKValidator() binding2.validator = OKValidator() aggregator.add(binding1) aggregator.add(binding2) XCTAssertEqual(aggregator.isValid , false) binding1.value = "OK" binding2.value = "OK" XCTAssertEqual(aggregator.isValid , true) binding2.value = "NOTKO" XCTAssertEqual(aggregator.isValid , false) aggregator.remove(binding2) XCTAssertEqual(aggregator.isValid , true) } }
34.312775
129
0.618179
4a8716300a98727b7dedac34efbb022873b87e14
1,262
// // UIDeviceType.swift // SwiftExtensions // // Created by Ankur on 16/9/20. // import Foundation import UIKit public extension UIDevice { var iPhone: Bool { return UIDevice().userInterfaceIdiom == .phone } var carPlay: Bool { return UIDevice().userInterfaceIdiom == .carPlay } var iPad: Bool { return UIDevice().userInterfaceIdiom == .pad } var tv: Bool { return UIDevice().userInterfaceIdiom == .tv } enum ScreenType: String { case iPhone4 case iPhone5 case iPhone6 case iPhone6Plus case iPhoneX case Unknown } var screenType: ScreenType { guard iPhone else { return .Unknown} switch UIScreen.main.nativeBounds.height { case 960: return .iPhone4 case 1136: return .iPhone5 case 1334: return .iPhone6 case 2208: return .iPhone6Plus case 2436: return .iPhoneX default: return .Unknown } } } public extension UIDevice { var deviceName : String { return UIDevice.current.name } }
19.71875
56
0.528526
e8619ffe99112869e8dd8b1b6eb7bf956148c7a9
5,395
/** * Copyright IBM Corporation 2016 * * 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 XCTest import PersonalityInsightsV2 class PersonalityInsightsTests: XCTestCase { private var personalityInsights: PersonalityInsights! private var mobyDickIntro: String! private var kennedySpeech: String! private let timeout: NSTimeInterval = 5.0 // MARK: - Test Configuration /** Set up for each test by loading text files and instantiating the service. */ override func setUp() { super.setUp() continueAfterFailure = false instantiatePersonalityInsights() loadMobyDickIntro() loadKennedySpeech() } /** Load "MobyDickIntro.txt". */ func loadMobyDickIntro() { let bundle = NSBundle(forClass: self.dynamicType) guard let file = bundle.pathForResource("MobyDickIntro", ofType: "txt") else { XCTFail("Unable to locate MobyDickIntro.txt file.") return } mobyDickIntro = try? String(contentsOfFile: file) guard mobyDickIntro != nil else { XCTFail("Unable to read MobyDickIntro.txt file.") return } } /** Load "KennedySpeech.txt." */ func loadKennedySpeech() { let bundle = NSBundle(forClass: self.dynamicType) guard let file = bundle.pathForResource("KennedySpeech", ofType: "txt") else { XCTFail("Unable to locate KennedySpeech.txt file.") return } kennedySpeech = try? String(contentsOfFile: file) guard kennedySpeech != nil else { XCTFail("Unable to read KennedySpeech.txt file.") return } } /** Instantiate Personality Insights. */ func instantiatePersonalityInsights() { let bundle = NSBundle(forClass: self.dynamicType) guard let file = bundle.pathForResource("Credentials", ofType: "plist"), let credentials = NSDictionary(contentsOfFile: file) as? [String: String], let username = credentials["PersonalityInsightsUsername"], let password = credentials["PersonalityInsightsPassword"] else { XCTFail("Unable to read credentials.") return } personalityInsights = PersonalityInsights(username: username, password: password) } /** Fail false negatives. */ func failWithError(error: NSError) { XCTFail("Positive test failed with error: \(error)") } /** Fail false positives. */ func failWithResult<T>(result: T) { XCTFail("Negative test returned a result.") } /** Wait for expectations. */ func waitForExpectations() { waitForExpectationsWithTimeout(timeout) { error in XCTAssertNil(error, "Timeout") } } // MARK: - Positive Tests /** Analyze the text of Kennedy's speech. */ func testProfile() { let description = "Analyze the text of Kennedy's speech." let expectation = expectationWithDescription(description) personalityInsights.getProfile(text: kennedySpeech, failure: failWithError) { profile in XCTAssertEqual("root", profile.tree.name, "Tree root should be named root") expectation.fulfill() } waitForExpectations() } /** Analyze content items. */ func testContentItem() { let description = "Analyze content items." let expectation = expectationWithDescription(description) let contentItem = PersonalityInsightsV2.ContentItem( id: "245160944223793152", userID: "Bob", sourceID: "Twitter", created: 1427720427, updated: 1427720427, contentType: "text/plain", language: "en", content: kennedySpeech, parentID: "", reply: false, forward: false ) let contentItems = [contentItem, contentItem] personalityInsights.getProfile(contentItems: contentItems, failure: failWithError) { profile in XCTAssertEqual("root", profile.tree.name, "Tree root should be named root") expectation.fulfill() } waitForExpectations() } // MARK: - Negative Tests /** Test getProfile() with text that is too short (less than 100 words). */ func testProfileWithShortText() { let description = "Try to analyze text that is too short (less than 100 words)." let expectation = expectationWithDescription(description) let failure = { (error: NSError) in XCTAssertEqual(error.code, 400) expectation.fulfill() } personalityInsights.getProfile( text: mobyDickIntro, failure: failure, success: failWithResult ) waitForExpectations() } }
33.302469
96
0.628916
db55931367f0f44c4e061baddb72d930d746a2b6
2,341
// // File.swift // // // Created by Florian Kugler on 13-05-2020. // import Foundation public enum TemplateValue: Hashable { case string(String) case rawHTML(String) } public struct EvaluationContext { public init(values: [String : TemplateValue] = [:]) { self.values = values } public var values: [String: TemplateValue] } public struct EvaluationError: Error, Hashable { public var range: Range<String.Index> public var reason: Reason public enum Reason: Hashable { case variableMissing(String) case expectedString } } extension EvaluationContext { public func evaluate(_ expr: AnnotatedExpression) throws -> TemplateValue { switch expr.expression { case .variable(name: let name): guard let value = values[name] else { throw EvaluationError(range: expr.range, reason: .variableMissing(name)) } return value case .tag(let name, let attributes, let body): let bodyValues = try body.map { try self.evaluate($0) } let bodyString = bodyValues.map { value in switch value { case let .string(str): return str.escaped case let .rawHTML(html): return html } }.joined() let attText = try attributes.isEmpty ? "" : " " + attributes.map { (key, value) in guard case let .string(valueText) = try evaluate(value) else { throw EvaluationError(range: value.range, reason: .expectedString) } return "\(key)=\"\(valueText.attributeEscaped)\"" }.joined(separator: " ") let result = "<\(name)\(attText)>\(bodyString)</\(name)>" return .rawHTML(result) case .for(variableName: let variableName, collection: let collection, body: let body): fatalError() } } } extension String { // todo verify that this is secure var escaped: String { self .replacingOccurrences(of: "&", with: "&amp;") .replacingOccurrences(of: "<", with: "&lt;") .replacingOccurrences(of: ">", with: "&gt;") } var attributeEscaped: String { replacingOccurrences(of: "\"", with: "&quot;") } }
30.402597
94
0.571978
d65ab0c5d0da842024a4825c0b617ca373f7b800
852
// // ForwardSelectedCell.swift // Example // // Created by Qiscus on 04/11/20. // Copyright © 2020 Qiscus. All rights reserved. // import UIKit import QiscusCore class ForwardSelectedCell: UICollectionViewCell { @IBOutlet weak var ivAvatar: UIImageView! @IBOutlet weak var lblName: UILabel! var data : RoomModel? { didSet { if data != nil { self.setupUI() } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code self.ivAvatar.layer.cornerRadius = self.ivAvatar.frame.width/2 } private func setupUI() { if let contact = data { ivAvatar.af.setImage(withURL: (contact.avatarUrl ?? URL(string: "http://"))!) self.lblName.text = contact.name } } }
21.846154
89
0.576291
eb273cfcb43fd2fdedf77b4ff4ca2f31f4c2001c
385
// // Created by Kin on 1/18/18. // Copyright (c) 2018 Muo.io. All rights reserved. // import Foundation extension NSNotification.Name { public static let DownLoadingAdd = NSNotification.Name("DownLoadingAdd") public static let DownLoadingRemove = NSNotification.Name("DownLoadingRemove") public static let DownLoadingReload = NSNotification.Name("DownLoadingReload") }
29.615385
83
0.761039
2f7e01960fbd1c76a21ea51d2a988a88f90fb429
2,624
import UIKit import WMF @objc(WMFRecentSearchesViewControllerDelegate) protocol RecentSearchesViewControllerDelegate: NSObjectProtocol { func recentSearchController(_: RecentSearchesViewController, didSelectSearchTerm: MWKRecentSearchEntry?) } @objc(WMFRecentSearchesViewController) class RecentSearchesViewController: ArticleCollectionViewController { @objc weak var recentSearchesViewControllerDelegate: RecentSearchesViewControllerDelegate? @objc var recentSearches: MWKRecentSearchList? @objc func reloadRecentSearches() { collectionView.reloadData() updateHeaderVisibility() updateTrashButtonEnabledState() } func updateHeaderVisibility() { } func updateTrashButtonEnabledState() { } @objc(deselectAllAnimated:) func deselectAll(animated: Bool) { guard let selected = collectionView.indexPathsForSelectedItems else { return } for indexPath in selected { collectionView.deselectItem(at: indexPath, animated: animated) } } override func articleURL(at indexPath: IndexPath) -> URL? { return nil } override func article(at indexPath: IndexPath) -> WMFArticle? { return nil } override func canDelete(at indexPath: IndexPath) -> Bool { return true } override func delete(at indexPath: IndexPath) { guard let entry = recentSearches?.entries[indexPath.item] else { return } recentSearches?.removeEntry(entry) recentSearches?.save() collectionView.reloadData() } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recentSearches?.entries.count ?? 0 } override func configure(cell: ArticleRightAlignedImageCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) { guard let entry = recentSearches?.entries[indexPath.item] else { return } cell.articleSemanticContentAttribute = .unspecified cell.configureForCompactList(at: indexPath.item) cell.titleLabel.text = entry.searchTerm cell.isImageViewHidden = true cell.apply(theme: theme) cell.actions = availableActions(at: indexPath) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { recentSearchesViewControllerDelegate?.recentSearchController(self, didSelectSearchTerm: recentSearches?.entry(at: UInt(indexPath.item))) } }
33.21519
144
0.696646
ed1a69b660c10ac14b4f57762066ca89563a6c54
331
// // BackCoverView.swift // WeatherApp // // Created by Juan Gestal Romani on 11/8/18. // Copyright © 2018 Juan Gestal Romani. All rights reserved. // import UIKit @IBDesignable class BackCoverView: UIView { override func draw(_ rect: CGRect) { StyleKit.drawBackCover(frame: bounds, resizing: .aspectFit) } }
20.6875
67
0.691843
506d377a155a23372efb2d7f69521a6f85b93afa
3,399
// // UtilsEncryption.swift // Plugin // // Created by Quéau Jean Pierre on 18/01/2021. // Copyright © 2021 Max Lynch. All rights reserved. // import Foundation import SQLCipher enum UtilsEncryptionError: Error { case encryptionFailed(message: String) } class UtilsEncryption { // MARK: - EncryptDatabase // swiftlint:disable function_body_length class func encryptDatabase(databaseLocation: String, filePath: String, password: String) throws -> Bool { var ret: Bool = false var oDB: OpaquePointer? do { if UtilsFile.isFileExist(filePath: filePath) { do { let tempPath: String = try UtilsFile .getFilePath(databaseLocation: databaseLocation, fileName: "temp.db") try UtilsFile.renameFile(filePath: filePath, toFilePath: tempPath, databaseLocation: databaseLocation) oDB = try UtilsSQLCipher .openOrCreateDatabase(filename: tempPath, password: "", readonly: false) try _ = UtilsSQLCipher .openOrCreateDatabase(filename: filePath, password: password, readonly: false) var stmt: String = "ATTACH DATABASE '\(filePath)' " stmt.append("AS encrypted KEY '\(password)';") stmt.append("SELECT sqlcipher_export('encrypted');") stmt.append("DETACH DATABASE encrypted;") if sqlite3_exec(oDB, stmt, nil, nil, nil) == SQLITE_OK { try _ = UtilsFile .deleteFile(fileName: "temp.db", databaseLocation: databaseLocation) ret = true } // close the db try UtilsSQLCipher.close(oDB: oDB) } catch UtilsFileError.getFilePathFailed { throw UtilsEncryptionError .encryptionFailed(message: "file path failed") } catch UtilsFileError.renameFileFailed { throw UtilsEncryptionError .encryptionFailed(message: "file rename failed") } catch UtilsSQLCipherError.openOrCreateDatabase(_) { throw UtilsEncryptionError .encryptionFailed(message: "open failed") } catch UtilsSQLCipherError.close(_) { throw UtilsEncryptionError .encryptionFailed(message: "close failed") } catch let error { print("Error: \(error)") throw UtilsEncryptionError .encryptionFailed(message: "Error: \(error)") } } } catch let error { print("Error: \(error)") throw UtilsEncryptionError .encryptionFailed(message: "Error: \(error)") } return ret } } // swiftlint:enable function_body_length
40.464286
80
0.488085
d72a5ea1b0e32912cfb963511ea4c32129835d6d
1,367
// // PageBarItem.swift // baemin // // Created by Stat.So on 2020/11/02. // import UIKit import RxSwift import RxCocoa class PageBarItem: BaseView { let title = PublishRelay<String?>() let isSelected = PublishRelay<Bool>() var selectedFontColor: UIColor? = Color.black var unselectedFontColor: UIColor? = Color.doveGray var selectedFont: UIFont? = Font.small.bold() var unselectedFont: UIFont? = Font.small var button = UIButton() var fullAreaButton = UIButton() } extension PageBarItem { override func setupUI() { super.setupUI() button.asChainable() .setTitleColor(Color.black, for: .normal) .add(to: self) .makeConstraints { (make) in make.center.equalToSuperview() } fullAreaButton.asChainable() .add(to: self) .makeConstraints { (make) in make.edges.equalToSuperview() } } override func setupBinding() { super.setupBinding() title .bind(to: button.rx.title()) .disposed(by: disposeBag) isSelected .subscribe(onNext: { [weak self] in self?.button.setTitleColor( $0 ? self?.selectedFontColor : self?.unselectedFontColor, for: .normal) self?.button.titleLabel?.font = $0 ? self?.selectedFont : self?.unselectedFont }).disposed(by: disposeBag) } }
23.568966
52
0.630578
163a6038a13708551d498a617180f05c454241f6
21,798
import Foundation class Networking { static let shared = Networking() private let session = URLSession.shared typealias NetworkingResponseHandler = ([String: Any]?, URLResponse?, Error?) -> Void enum Method: String { case get = "GET" case post = "POST" } enum ParameterEncoding { case url case urlEncodedInURL case json func encode(_ request: URLRequest, parameters: [String: Any]?) -> URLRequest { guard let parameters = parameters else { return request } guard let httpMethod = request.httpMethod else { return request } guard let url = request.url else { return request } var mutableURLRequest = request switch self { case .url, .urlEncodedInURL: func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&") } func encodesParametersInURL(_ method: Method) -> Bool { switch self { case .urlEncodedInURL: return true default: break } switch method { case .get: return true default: return false } } if let method = Method(rawValue: httpMethod), encodesParametersInURL(method) { if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.url = urlComponents.url } } else { if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.httpBody = query(parameters).data( using: .utf8, allowLossyConversion: false ) } case .json: do { let data = try JSONSerialization.data(withJSONObject: parameters) mutableURLRequest.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("application/json", forHTTPHeaderField: "X-Accept") mutableURLRequest.httpBody = data } catch let error { print("error: \(error)") } } return mutableURLRequest } func queryComponents(_ key: String, _ value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? startIndex let substring = string[startIndex..<endIndex] escaped += (substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet) ?? String(substring)) index = endIndex } } return escaped } } func request(_ urlString: String, method: Method, parameters: [String: Any]? = nil, encoding: ParameterEncoding = .url, headers: [String: String]? = nil, completionHandler: @escaping ([String: Any]?, URLResponse?, Error?) -> Void) { guard let url = URL(string: urlString) else { return } var mutableURLRequest = URLRequest(url: url) mutableURLRequest.httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } let request = encoding.encode(mutableURLRequest, parameters: parameters) let task = session.dataTask(with: request) { data, response, error in var json: [String: Any]? defer { DispatchQueue.main.async { completionHandler(json, response, error as Error?) } } if let httpResponse = response as? HTTPURLResponse, let data = data, httpResponse.url!.absoluteString.contains("api.twitter.com") { let contentType = httpResponse.allHeaderFields["Content-Type"] as? String if contentType == nil || contentType!.contains("application/json") == false { let responseText = String(data: data, encoding: .utf8) // TWITTER SUCKS. API WILL RETURN <application/html> // oauth_token=sample&oauth_token_secret=sample&oauth_callback_confirmed=true json = responseText?.queryStringParameters return } } guard let validData = data, let jsonData = validData.monkeyking_json else { print("requst fail: JSON could not be serialized because input data was nil.") return } json = jsonData } task.resume() } func upload(_ urlString: String, parameters: [String: Any], headers: [String: String]? = nil, completionHandler: @escaping ([String: Any]?, URLResponse?, Error?) -> Void) { let tuple = urlRequestWithComponents(urlString, parameters: parameters) guard let request = tuple.request, let data = tuple.data else { return } var mutableURLRequest = request if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } let uploadTask = session.uploadTask(with: mutableURLRequest, from: data) { data, response, error in var json: [String: Any]? defer { DispatchQueue.main.async { completionHandler(json, response, error as Error?) } } guard let validData = data, let jsonData = validData.monkeyking_json else { print("upload fail: JSON could not be serialized because input data was nil.") return } json = jsonData } uploadTask.resume() } func urlRequestWithComponents(_ urlString: String, parameters: [String: Any], encoding: ParameterEncoding = .url) -> (request: URLRequest?, data: Data?) { guard let url = URL(string: urlString) else { return (nil, nil) } var mutableURLRequest = URLRequest(url: url) mutableURLRequest.httpMethod = Method.post.rawValue let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())" let contentType = "multipart/form-data;boundary="+boundaryConstant mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") var uploadData = Data() // add parameters for (key, value) in parameters { guard let encodeBoundaryData = "\r\n--\(boundaryConstant)\r\n".data(using: .utf8) else { return (nil, nil) } uploadData.append(encodeBoundaryData) if let imageData = value as? Data { let filename = arc4random() let filenameClause = "filename=\"\(filename)\"" let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" let contentDispositionData = contentDispositionString.data(using: .utf8) uploadData.append(contentDispositionData!) // append content type let contentTypeString = "Content-Type: image/JPEG\r\n\r\n" guard let contentTypeData = contentTypeString.data(using: .utf8) else { return (nil, nil) } uploadData.append(contentTypeData) uploadData.append(imageData) } else { guard let encodeDispositionData = "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: .utf8) else { return (nil, nil) } uploadData.append(encodeDispositionData) } } uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: .utf8)!) return (encoding.encode(mutableURLRequest, parameters: nil), uploadData) } func authorizationHeader(for method: Method, urlString: String, appID: String, appKey: String, accessToken:String?, accessTokenSecret: String?, parameters: Dictionary<String, Any>?, isMediaUpload: Bool) -> String { var authorizationParameters = Dictionary<String, Any>() authorizationParameters["oauth_version"] = "1.0" authorizationParameters["oauth_signature_method"] = "HMAC-SHA1" authorizationParameters["oauth_consumer_key"] = appID authorizationParameters["oauth_timestamp"] = String(Int(Date().timeIntervalSince1970)) authorizationParameters["oauth_nonce"] = UUID().uuidString if let accessToken = accessToken { authorizationParameters["oauth_token"] = accessToken } if let parameters = parameters { for (key, value) in parameters where key.hasPrefix("oauth_") { authorizationParameters.updateValue(value, forKey: key) } } var finalParameters = authorizationParameters if isMediaUpload { if let parameters = parameters { for (k, v) in parameters { finalParameters[k] = v } } } authorizationParameters["oauth_signature"] = self.oauthSignature(for: method, urlString: urlString, parameters: finalParameters, appKey: appKey, accessTokenSecret: accessTokenSecret) let authorizationParameterComponents = authorizationParameters.urlEncodedQueryString(using: .utf8).components(separatedBy: "&").sorted() var headerComponents = [String]() for component in authorizationParameterComponents { let subcomponent = component.components(separatedBy: "=") if subcomponent.count == 2 { headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") } } return "OAuth " + headerComponents.joined(separator: ", ") } func oauthSignature(for method: Method, urlString: String, parameters: Dictionary<String, Any>, appKey: String, accessTokenSecret tokenSecret: String?) -> String { let tokenSecret = tokenSecret?.urlEncodedString() ?? "" let encodedConsumerSecret = appKey.urlEncodedString() let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)" let parameterComponents = parameters.urlEncodedQueryString(using: .utf8).components(separatedBy: "&").sorted() let parameterString = parameterComponents.joined(separator: "&") let encodedParameterString = parameterString.urlEncodedString() let encodedURL = urlString.urlEncodedString() let signatureBaseString = "\(method.rawValue)&\(encodedURL)&\(encodedParameterString)" let key = signingKey.data(using: .utf8)! let msg = signatureBaseString.data(using: .utf8)! let sha1 = HMAC.sha1(key: key, message: msg)! return sha1.base64EncodedString(options: []) } } // MARK: URLEncode extension Dictionary { func urlEncodedQueryString(using encoding: String.Encoding) -> String { var parts = [String]() for (key, value) in self { let keyString = "\(key)".urlEncodedString() let valueString = "\(value)".urlEncodedString(keyString == "status") let query: String = "\(keyString)=\(valueString)" parts.append(query) } return parts.joined(separator: "&") } } extension String { var queryStringParameters: Dictionary<String, String> { var parameters = Dictionary<String, String>() let scanner = Scanner(string: self) var key: NSString? var value: NSString? while !scanner.isAtEnd { key = nil scanner.scanUpTo("=", into: &key) scanner.scanString("=", into: nil) value = nil scanner.scanUpTo("&", into: &value) scanner.scanString("&", into: nil) if let key = key as String?, let value = value as String? { parameters.updateValue(value, forKey: key) } } return parameters } func urlEncodedString(_ encodeAll: Bool = false) -> String { var allowedCharacterSet: CharacterSet = .urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\n:#/?@!$&'()*+,;=") if !encodeAll { allowedCharacterSet.insert(charactersIn: "[]") } return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)! } } public struct HMAC { static func sha1(key: Data, message: Data) -> Data? { var key = key.rawBytes let message = message.rawBytes // key if key.count > 64 { key = SHA1(message: Data(bytes: key)).calculate().rawBytes } if (key.count < 64) { key = key + [UInt8](repeating: 0, count: 64 - key.count) } var opad = [UInt8](repeating: 0x5c, count: 64) for (idx, _) in key.enumerated() { opad[idx] = key[idx] ^ opad[idx] } var ipad = [UInt8](repeating: 0x36, count: 64) for (idx, _) in key.enumerated() { ipad[idx] = key[idx] ^ ipad[idx] } let ipadAndMessageHash = SHA1(message: Data(bytes: (ipad + message))).calculate().rawBytes let finalHash = SHA1(message: Data(bytes: opad + ipadAndMessageHash)).calculate().rawBytes let mac = finalHash return Data(bytes: UnsafePointer<UInt8>(mac), count: mac.count) } } // MARK: SHA1 struct SHA1 { var message: Data /** Common part for hash calculation. Prepare header data. */ func prepare(_ len:Int = 64) -> Data { var tmpMessage: Data = self.message // Step 1. Append Padding Bits tmpMessage.append([0x80]) // append one bit (Byte with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) while tmpMessage.count % len != (len - 8) { tmpMessage.append([0x00]) } return tmpMessage } func calculate() -> Data { //var tmpMessage = self.prepare() let len = 64 let h: [UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] var tmpMessage: Data = self.message // Step 1. Append Padding Bits tmpMessage.append([0x80]) // append one bit (Byte with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) while tmpMessage.count % len != (len - 8) { tmpMessage.append([0x00]) } // hash values var hh = h // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. tmpMessage.append((self.message.count * 8).bytes(64 / 8)) // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.count var i = 0; while i < tmpMessage.count { let chunk = tmpMessage.subdata(in: i..<i+min(chunkSizeBytes, leftMessageBytes)) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into eighty 32-bit words: var M = [UInt32](repeating: 0, count: 80) for x in 0..<M.count { switch (x) { case 0...15: var le: UInt32 = 0 let range = NSRange(location:x * MemoryLayout<UInt32>.size, length: MemoryLayout<UInt32>.size) (chunk as NSData).getBytes(&le, range: range) M[x] = le.bigEndian break default: M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], n: 1) break } } var A = hh[0], B = hh[1], C = hh[2], D = hh[3], E = hh[4] // Main loop for j in 0...79 { var f: UInt32 = 0 var k: UInt32 = 0 switch j { case 0...19: f = (B & C) | ((~B) & D) k = 0x5A827999 break case 20...39: f = B ^ C ^ D k = 0x6ED9EBA1 break case 40...59: f = (B & C) | (B & D) | (C & D) k = 0x8F1BBCDC break case 60...79: f = B ^ C ^ D k = 0xCA62C1D6 break default: break } let temp = (rotateLeft(A,n: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff E = D D = C C = rotateLeft(B, n: 30) B = A A = temp } hh[0] = (hh[0] &+ A) & 0xffffffff hh[1] = (hh[1] &+ B) & 0xffffffff hh[2] = (hh[2] &+ C) & 0xffffffff hh[3] = (hh[3] &+ D) & 0xffffffff hh[4] = (hh[4] &+ E) & 0xffffffff i = i + chunkSizeBytes leftMessageBytes -= chunkSizeBytes } // Produce the final hash value (big-endian) as a 160 bit number: let mutableBuff = NSMutableData() hh.forEach { var i = $0.bigEndian mutableBuff.append(&i, length: MemoryLayout<UInt32>.size) } return mutableBuff as Data } } func arrayOfBytes<T>(_ value:T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (MemoryLayout<T>.size * 8) let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytesPointer = valuePointer.withMemoryRebound(to: UInt8.self, capacity: 1) { $0 } var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size,totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } valuePointer.deinitialize(count: totalBytes) valuePointer.deallocate() return bytes } func rotateLeft(_ v: UInt16, n: UInt16) -> UInt16 { return ((v << n) & 0xFFFF) | (v >> (16 - n)) } func rotateLeft(_ v: UInt32, n: UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } func rotateLeft(_ x: UInt64, n: UInt64) -> UInt64 { return (x << n) | (x >> (64 - n)) } extension Int { public func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension Data { var rawBytes: [UInt8] { let count = self.count / MemoryLayout<UInt8>.size var bytesArray = [UInt8](repeating: 0, count: count) (self as NSData).getBytes(&bytesArray, length:count * MemoryLayout<UInt8>.size) return bytesArray } init(bytes: [UInt8]) { self.init(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) } mutating func append(_ bytes: [UInt8]) { self.append(UnsafePointer<UInt8>(bytes), count: bytes.count) } }
42.162476
236
0.549775
0ea01f6ff59a9d3b26cf412dfbd956a93d9acac7
2,112
// // SwiftyEpubKit.swift // // // Created by BoB on 2020/10/02. // struct EpubBook { var name: String var matedata: [BookMata] var pages: [BookPage] } extension EpubBook { private init() { name = "defaultName" matedata = [.author("defaultAuthor")] pages = [.init()] } } let bb = EpubBook( name: "a", matedata: [ .author("defaultAuthor") ], pages: [ .init(), .init(fromString: "<html><body><h1 style=\"font-weight=600pt\">Title</h1></body></html>", ID: "page-1", title: "title-1", playOrder: 1) ]) // let book = Epub(.name="ExampleName") /* A book envolved: example.epub ├── META-INF │ └── container.xml(NOCHANGE) ├── OEBPS │ ├── content.opf │ ├── toc.ncx(FOR EPUB2) [application/x-dtbncx+xml] │ ├── Audio │ │ ├── example.mp3 [audio/mpeg] │ │ └── example.mp4 [audio/mp4](AAC LC audio using MP4 container) │ ├── Font │ │ ├── example.ttf [font/ttf|application/font-sfnt] │ │ ├── example.otf [font/otf|application/font-sfnt │ │ │ |application/vnd.ms-opentype] │ │ ├── example.woff [font/woff|application/font-woff] │ │ └── example.woff2 [font/woff2] │ ├── Images │ │ ├── example.gif [image/gif] │ │ ├── example.jpeg [image/jpeg] │ │ ├── example.jpg [image/jpeg] │ │ ├── example.png [image/png] │ │ └── example.svg [image/svg+xml] │ ├── Script │ │ └── example.js [application/javascript|text/javascript] │ ├── Style │ │ ├── example.css [text/css] │ │ └── common.css [text/css] │ └── Text │ ├── nav.xhtml(FOR EPUB3) [application/xhtml+xml] │ └── example.xhtml [application/xhtml+xml] └── mimetype(NOCHANGE) ┌────────────────────┬───────────────────────┬──────────────────────────┐ │application/smil+xml│ [ MediaOverlays32 ] | Media Overlay documents │ ├────────────────────┼───────────────────────┼──────────────────────────┤ |application/pls+xml │[PRONUNCIATION-LEXICON]|TTS Pronunciation lexicons| └────────────────────┴───────────────────────┴──────────────────────────┘ */
28.931507
143
0.505682
edb7aed35858a177953d45279e6c12523f7a5260
281
// // DateTextFieldDelegate.swift // So Much So Little // // Created by Adland Lee on 7/1/16. // Copyright © 2016 Adland Lee. All rights reserved. // import UIKit class DateTextFieldDelegate: NSObject, UITextFieldDelegate { var datePicker: UIDatePicker! }
16.529412
60
0.683274
2219e0b8cfb13c630a1e5d799834324456c41b9e
261
// // BattleNetAPI+Swift.swift // BattleNetAPI-Example // // Created by Christopher Jennewein on 2/8/21. // import BattleNetAPI import SwiftUI extension BattleNetAPI: ObservableObject { } extension AuthenticationManager: ObservableObject { }
12.428571
51
0.727969
560edeae27dd3165c78d5da451bec775e29bba3f
208
import CoreData @objc(CoreDataFeedImage) public class CoreDataFeedImage: NSManagedObject { @NSManaged var id: UUID @NSManaged var desc: String? @NSManaged var location: String? @NSManaged var url: URL }
20.8
49
0.778846
cc8059dfa879f90169249d129006bb1091cd9471
850
// // UIAlertController+Convenience.swift // Simple Login // // Created by Thanh-Nhon Nguyen on 11/03/2020. // Copyright © 2020 SimpleLogin. All rights reserved. // import UIKit extension UIAlertController { @discardableResult func addTextView(initialText: String? = nil) -> UITextView { let textView = UITextView() textView.text = initialText let textViewController = UIViewController() textViewController.view.addSubview(textView) textView.fillSuperview(padding: UIEdgeInsets(top: 0, left: 10, bottom: 8, right: 10)) textView.layer.borderWidth = 1.0 textView.layer.borderColor = UIColor.lightGray.cgColor setValue(textViewController, forKey: "contentViewController") view.constrainHeight(constant: 200) return textView } }
29.310345
93
0.674118
39d1ce687d3a7dbce43c12e3527c8ab1f05b330c
281
// // UserProvidedImageDestination.swift // ImageCache // // Created by Jared Sinclair on 1/3/20. // Copyright © 2020 Nice Boy LLC. All rights reserved. // extension ImageCache { public enum UserProvidedImageDestination: CaseIterable { case memory, disk } }
17.5625
60
0.690391
6118f071e493f26f68e801e44ac6681b4895b088
1,338
// // Unique.swift // Basis // // Created by Robert Widmann on 9/13/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // /// Abstract Unique objects. Objects of type Unique may be compared for equality and ordering and /// hashed. public class Unique : K0, Equatable, Hashable, Comparable { private let val : Int public var hashValue: Int { get { return self.val } } public init(_ x : Int) { self.val = x } } /// Creates a new object of type Unique. The value returned will not compare equal to any other /// value of type Unique returned by previous calls to newUnique. There is no limit on the number of /// times newUnique may be called. public func newUnique() -> IO<Unique> { return do_({ () -> Unique in let r = !(modifyIORef(innerSource)({ $0 + 1 }) >> readIORef(innerSource)) return Unique(r) }) } public func <=(lhs: Unique, rhs: Unique) -> Bool { return lhs.val <= rhs.val } public func >=(lhs: Unique, rhs: Unique) -> Bool { return lhs.val >= rhs.val } public func >(lhs: Unique, rhs: Unique) -> Bool { return lhs.val > rhs.val } public func <(lhs: Unique, rhs: Unique) -> Bool { return lhs.val < rhs.val } public func ==(lhs: Unique, rhs: Unique) -> Bool { return lhs.val == rhs.val } private let innerSource : IORef<Int> = !newIORef(0)
23.473684
100
0.662182
e00c70a7800bca4e86c4f54a7dc77ffd4e4c1d07
3,127
#if swift(>=4.0) @objcMembers public class SystemTestsAPI: NSObject { static let kRequestTestArrayOfStrings = "com.complex.ern.api.request.testArrayOfStrings" static let kRequestTestMultiArgs = "com.complex.ern.api.request.testMultiArgs" public lazy var requests: SystemTestsAPIRequests = { SystemTestsRequests() }() } @objcMembers public class SystemTestsAPIRequests: NSObject { public func registerTestArrayOfStringsRequestHandler(handler _: @escaping ElectrodeBridgeRequestCompletionHandler) -> UUID? { assertionFailure("should override") return UUID() } public func registerTestMultiArgsRequestHandler(handler _: @escaping ElectrodeBridgeRequestCompletionHandler) -> UUID? { assertionFailure("should override") return UUID() } public func unregisterTestArrayOfStringsRequestHandler(uuid _: UUID) -> ElectrodeBridgeRequestCompletionHandler? { assertionFailure("should override") return nil } public func unregisterTestMultiArgsRequestHandler(uuid _: UUID) -> ElectrodeBridgeRequestCompletionHandler? { assertionFailure("should override") return nil } public func testArrayOfStrings(key _: [String], responseCompletionHandler _: @escaping ([ErnObject]?, ElectrodeFailureMessage?) -> Void) { assertionFailure("should override") } public func testMultiArgs(testMultiArgsData _: TestMultiArgsData, responseCompletionHandler _: @escaping (String?, ElectrodeFailureMessage?) -> Void) { assertionFailure("should override") } } #else public class SystemTestsAPI: NSObject { static let kRequestTestArrayOfStrings = "com.complex.ern.api.request.testArrayOfStrings" static let kRequestTestMultiArgs = "com.complex.ern.api.request.testMultiArgs" public lazy var requests: SystemTestsAPIRequests = { SystemTestsRequests() }() } public class SystemTestsAPIRequests: NSObject { public func registerTestArrayOfStringsRequestHandler(handler _: @escaping ElectrodeBridgeRequestCompletionHandler) -> UUID? { assertionFailure("should override") return UUID() } public func registerTestMultiArgsRequestHandler(handler _: @escaping ElectrodeBridgeRequestCompletionHandler) -> UUID? { assertionFailure("should override") return UUID() } public func unregisterTestArrayOfStringsRequestHandler(uuid _: UUID) -> ElectrodeBridgeRequestCompletionHandler? { assertionFailure("should override") return nil } public func unregisterTestMultiArgsRequestHandler(uuid _: UUID) -> ElectrodeBridgeRequestCompletionHandler? { assertionFailure("should override") return nil } public func testArrayOfStrings(key _: [String], responseCompletionHandler _: @escaping ElectrodeBridgeResponseCompletionHandler) { assertionFailure("should override") } public func testMultiArgs(testMultiArgsData _: TestMultiArgsData, responseCompletionHandler _: @escaping ElectrodeBridgeResponseCompletionHandler) { assertionFailure("should override") } } #endif
37.22619
155
0.743524
4b95041c25b4069aba6738b074532fea302162e2
2,352
import Checksum import Foundation import TuistCore import TuistSupport public protocol GraphContentHashing { func contentHashes(for graph: Graphing) throws -> [TargetNode: String] } public final class GraphContentHasher: GraphContentHashing { private let fileHandler: FileHandling public init(fileHandler: FileHandling = FileHandler.shared) { self.fileHandler = fileHandler } public func contentHashes(for graph: Graphing) throws -> [TargetNode: String] { let hashableTargets = graph.targets.filter { $0.target.product == .framework } let hashes = try hashableTargets.map { try makeContentHash(of: $0) } return Dictionary(uniqueKeysWithValues: zip(hashableTargets, hashes)) } private func makeContentHash(of targetNode: TargetNode) throws -> String { // TODO: extend function to consider build settings, compiler flags, dependencies, and a lot more let sourcesHash = try hashSources(of: targetNode) let productHash = try hash(string: targetNode.target.productName) let platformHash = try hash(string: targetNode.target.platform.rawValue) return try hash(strings: [sourcesHash, productHash, platformHash]) } private func hashSources(of targetNode: TargetNode) throws -> String { let hashes = try targetNode.target.sources.sorted(by: { $0.path < $1.path }).map(md5) let joinedHash = try hash(strings: hashes) return joinedHash } private func hash(string: String) throws -> String { guard let hash = string.checksum(algorithm: .md5) else { throw ContentHashingError.stringHashingFailed(string) } return hash } private func hash(strings: [String]) throws -> String { guard let joinedHash = strings.joined().checksum(algorithm: .md5) else { throw ContentHashingError.stringHashingFailed(strings.joined()) } return joinedHash } private func md5(of source: Target.SourceFile) throws -> String { guard let sourceData = try? fileHandler.readFile(source.path) else { throw ContentHashingError.fileNotFound(source.path) } guard let hash = sourceData.checksum(algorithm: .md5) else { throw ContentHashingError.fileHashingFailed(source.path) } return hash } }
38.557377
105
0.6875
160c1567d9f17548dc1750f85d7aa31d439b2751
2,541
/** * Copyright © 2020 Saleem Abdulrasool <[email protected]> * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause **/ import WinSDK public class ViewController: Responder { /// Managing the View /// The view that the controller manages. public var view: View! { get { loadViewIfNeeded() return self.viewIfLoaded } set { self.viewIfLoaded = newValue } } /// The controller's view or `nil` if the view is not yet loaded. public private(set) var viewIfLoaded: View? /// Indicates if the view is loaded into memory. public var isViewLoaded: Bool { return self.viewIfLoaded == nil ? false : true } /// Creates the view that the controller manages. public func loadView() { self.view = View(frame: .zero) } /// Called after the controller's view is loaded info memory. public func viewDidLoad() { } /// Loads the controller's view if it has not yet been loaded. public func loadViewIfNeeded() { guard !self.isViewLoaded else { return } self.loadView() self.viewDidLoad() } /// A localized string that represents the view this controller manages. public var title: String? { get { let szLength: Int32 = GetWindowTextLengthW(view.hWnd) let buffer: [WCHAR] = Array<WCHAR>(unsafeUninitializedCapacity: Int(szLength) + 1) { $1 = Int(GetWindowTextW(view.hWnd, $0.baseAddress!, CInt($0.count))) } return String(decodingCString: buffer, as: UTF16.self) } set(value) { _ = SetWindowTextW(view.hWnd, value?.LPCWSTR) } } /// The preferred size for the view controller's view. public var preferredContentSize: Size { fatalError("not yet implemented") } override public init() { } // Responder Chain override public var next: Responder? { return view?.superview } } extension ViewController: ContentContainer { public func willTransition(to: Size, with coodinator: ViewControllerTransitionCoordinator) { } public func willTransition(to: TraitCollection, with coordinator: ViewControllerTransitionCoordinator) { } public func size(forChildContentContainer container: ContentContainer, withParentContainerSize parentSize: Size) -> Size { return .zero } public func preferredContentSizeDidChange(forChildContentContainer container: ContentContainer) { } public func systemLayoutFittingSizeDidChange(forChildContentContainer container: ContentContainer) { } }
27.031915
102
0.681621
90b2530eb851a52e69e6e723927bb56b832f3808
4,317
// // FBImageView.swift // FBKit // // Created by Felipe Correia on 10/01/20. // Copyright © 2020 Felip38rito. All rights reserved. // import UIKit /// UIImageView extension to enable /// caching on loading from internet /// and solve the "wrong image in collection error" @IBDesignable public class FBImageView: UIImageView { /// Control variable for showing or not the cached version /// correcting the behaviour of loading wrong image internal var imageURL: String? /// Control if the download will proceed or not internal var proceedDownload: Bool = true /// The default delegate of imageView public var delegate: FBImageDelegate? /// The border as a shape to be able to change stroke behaviour let shapeBorderLayer = CAShapeLayer() // MARK: - Global properties @IBInspectable public var cornerRadius : CGFloat = 0.0 { didSet { self.layer.cornerRadius = self.cornerRadius updateView() } } @IBInspectable public var borderWidth: CGFloat = 0.0 { didSet { updateView() } } @IBInspectable public var borderColor: UIColor = UIColor.clear { didSet { updateView() } } // MARK: - Dash items @IBInspectable public var dashWidth: CGFloat = 1.0 { didSet { updateView() } } @IBInspectable public var dashSpacing: CGFloat = 0.0 { didSet { updateView() } } /** Load image from url via https and store in the cache before showing - Parameter url: URL in string to load from */ public func load(from url: String) { // self.image = nil /// Assing the url to this object for control self.imageURL = url if let cached_object = FBImageCache.current.get(key: url) { self.image = cached_object self.delegate?.didLoadFromCache(self, key: url, image: cached_object) return } /// If the delegate is active then the result of this method will say if the download will be maded if let delegate = self.delegate { proceedDownload = delegate.willDownload(self, url: url) } if proceedDownload { /// Download the image in a background thread DispatchQueue.global().async { [self] in guard let url_remote = URL(string: url) else { return } guard let data = try? Data(contentsOf: url_remote) else { return } /// Setup the image in the main thread DispatchQueue.main.async { guard let image = UIImage(data: data) else { return } /// The bugfix verification: /// Only set the image when the url matches avoinding strange changes in collections if self.imageURL == url { self.image = image self.delegate?.didDownload(self, url: url, image: image) } /// store the image object in cache // FBImageCache.cache.setObject(image, forKey: url as NSString) FBImageCache.current.store(image: image, key: url) } } } } internal func updateView() { /// Setup the border shapeBorderLayer.removeFromSuperlayer() shapeBorderLayer.frame = self.bounds shapeBorderLayer.lineWidth = self.borderWidth shapeBorderLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.cornerRadius).cgPath shapeBorderLayer.fillColor = nil shapeBorderLayer.strokeColor = borderColor.cgColor shapeBorderLayer.lineDashPattern = [dashWidth, dashSpacing].map({ (value) -> NSNumber in return NSNumber(value: Float(value)) }) self.layer.insertSublayer(shapeBorderLayer, at: 0) } /** Convenience method: Load a named asset in the catalog - Parameter name: Name of the asset in the catalog */ public func load(name: String) { self.image = UIImage(named: name) } }
32.954198
110
0.578874
5db02320232212716e2078d4802b4bacdaaab836
4,396
// // BaseCollectionVC.swift // BrokerNewsModule // // Created by Alexej Nenastev on 30/03/2019. // Copyright © 2019 BCS. All rights reserved. // import RxSwift import RxDataSources public typealias CollectionDataSource<Item> = RxCollectionViewSectionedReloadDataSource<DataSourceSection<Item>> public final class CollectionVC<Item>: UIViewController, SceneView, UIScrollViewDelegate { public var disposeBag = DisposeBag() private var refreshControl: UIRefreshControl? public let collectionView: UICollectionView private var footerActivityIndicator = UIActivityIndicatorView(style: .gray) private let dataSource: CollectionDataSource<Item> private let configurator: CollectionSceneConfigurator override public func loadView() { self.view = collectionView } override public func viewDidLoad() { super.viewDidLoad() collectionView.allowsSelection = vm.canSelectItem } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) for indexPath in collectionView.indexPathsForSelectedItems ?? [] { collectionView.deselectItem(at: indexPath, animated: animated) } } public init(dataSource: CollectionDataSource<Item>, configurator: CollectionSceneConfigurator) { self.dataSource = dataSource self.configurator = configurator self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: configurator.layout) collectionView.backgroundColor = .white collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false if configurator.refreshControll { self.refreshControl = UIRefreshControl() if #available(iOS 10.0, *) { collectionView.refreshControl = refreshControl! } else { collectionView.addSubview(refreshControl!) } } super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func bind(reactor: CollectionReactor<Item>) { reactor.state .map { $0.sections } .bind(to: collectionView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) collectionView.rx.itemSelected .delay(configurator.selectedDelay, scheduler: MainScheduler.asyncInstance) .map(Reactor.Action.selected) .bind(to: reactor.action) .disposed(by: disposeBag) if let delegate = configurator.scrollDelegate { collectionView.rx.setDelegate(delegate).disposed(by: disposeBag) } if let refresher = refreshControl { refresher.rx.controlEvent(.valueChanged).asObservable() .subscribe(onNext: { [weak self] in self?.fire(action: .loadData) }) .disposed(by: disposeBag) bindState(\.inProgressRefreshLoading, to: refresher.rx.isRefreshing) } if reactor.canLoadMore { collectionView.rx.didScroll.subscribeNext(self, do: CollectionVC<Item>.loadMoreIfNeed, bag: disposeBag) subscribeNext(reactor.state.map { $0.inProgressLoadMore }, with: CollectionVC.setProgressMore) } } func setRefreshInProgress(inProgress: Bool) { if !inProgress && (refreshControl?.isRefreshing ?? false) { refreshControl?.endRefreshing() } } func setProgressMore(inProgressMore: Bool) { if inProgressMore { footerActivityIndicator.startAnimating() } else { footerActivityIndicator.stopAnimating() } footerActivityIndicator.isHidden = !inProgressMore } public func loadMoreIfNeed() { let scrollView = collectionView as UIScrollView if scrollView.contentSize.height < scrollView.frame.size.height { return } let currentOffset = scrollView.contentOffset.y let maiximumOffset = scrollView.contentSize.height - scrollView.frame.size.height let deltaOffset = maiximumOffset - currentOffset if deltaOffset <= 0 { fire(action: .loadMore) } } }
35.168
115
0.651274
488eaedec002e90e80d6d82e961041e64ed88ad6
1,498
// // ViewController.swift // BugTest // // Created by bong on 2017/10/23. // Copyright © 2017年 Smallfly. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var player: AVPlayer? override func viewDidLoad() { super.viewDidLoad() let url = URL(fileURLWithPath: LocalFile.LandingVedio.path()) player = AVPlayer(url: url) NotificationCenter.default.addObserver( self, selector: #selector(playToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) player?.play() } @objc func playToEnd(_ notification: Notification) { print("play to end") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var filp: UIButton! @IBAction func flip(_ sender: Any) { let collectionview = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "CollectionViewController") UIApplication.shared.keyWindow?.rootViewController = collectionview } } enum LocalFile: String { case LandingVedio = "LandingMV" func path() -> String { return Bundle.main.path(forResource: self.rawValue, ofType: "mp4")! } }
26.280702
142
0.655541
2657d347917196df09e2fa36cd5e24597d12c007
1,830
//: [Previous](@previous) //https://leetcode.com/problems/4sum/ import Foundation class Solution { func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { var result = [[Int]]() guard nums.count >= 4 else { return result } let sortedNums = nums.sorted() for i in 0..<sortedNums.count - 1 { if i > 0 && sortedNums[i] == sortedNums[i-1] { continue } for j in i+1..<sortedNums.count - 1 { if j != i+1 && sortedNums[j] == sortedNums[j-1] { continue } let wantNum = target - sortedNums[i] - sortedNums[j] var k = j + 1, f = sortedNums.count - 1 while k < f { let sum = sortedNums[k] + sortedNums[f] if sum == wantNum { result.append([sortedNums[i], sortedNums[j], sortedNums[k], sortedNums[f]]) k += 1 f -= 1 while k < f && sortedNums[k] == sortedNums[k-1] { k += 1 } while k < f && sortedNums[f] == sortedNums[f+1] { f -= 1 } } else if sum > wantNum { f -= 1 } else { k += 1 } } } } return result } } let testNums = [-1,-5,-5,-3,2,5,0,4] Solution().fourSum(testNums, -7) //: [Next](@next)
28.59375
99
0.33224
1a5aeeb89d152d358e3cbca94fcf213d470f8170
3,442
// RUN: %target-typecheck-verify-swift // Array types. class Base1 { func f0(_ x: [Int]) { } func f0a(_ x: [Int]?) { } func f1(_ x: [[Int]]) { } func f1a(_ x: [[Int]]?) { } func f2(_ x: [([Int]) -> [Int]]) { } func f2a(_ x: [([Int]?) -> [Int]?]?) { } } class Derived1 : Base1 { override func f0(_ x: Array<Int>) { } override func f0a(_ x: Optional<Array<Int>>) { } override func f1(_ x: Array<Array<Int>>) { } override func f1a(_ x: Optional<Array<Array<Int>>>) { } override func f2(_ x: Array<(Array<Int>) -> Array<Int>>) { } override func f2a(_ x: Optional<Array<(Optional<Array<Int>>) -> Optional<Array<Int>>>>) { } } // Array types in generic specializations. struct X<T> { } func testGenericSpec() { _ = X<[Int]>() } // Array types for construction. func constructArray(_ n: Int) { var ones = [Int](repeating: 1, count: n) ones[5] = 0 var matrix = [[Float]]() matrix[1][2] = 3.14159 var _: [Int?] = [Int?]() } // Fix-Its from the old syntax to the new. typealias FixIt0 = Int[] // expected-error{{array types are now written with the brackets around the element type}}{{20-20=[}}{{23-24=}} // Make sure preCheckExpression() properly folds member types. class Outer { class Middle { class Inner {} class GenericInner<V> {} typealias Alias = Inner } class GenericMiddle<U> { class Inner {} } typealias Alias = Middle } class GenericOuter<T> { class Middle { class Inner {} } } func takesMiddle(_: [Outer.Middle]) {} takesMiddle([Outer.Middle]()) func takesInner(_: [Outer.Middle.Inner]) {} takesInner([Outer.Middle.Inner]()) takesInner([Outer.Alias.Inner]()) takesInner([Outer.Middle.Alias]()) takesInner([Outer.Alias.Alias]()) takesInner([array.Outer.Middle.Inner]()) takesInner([array.Outer.Alias.Inner]()) takesInner([array.Outer.Middle.Alias]()) takesInner([array.Outer.Alias.Alias]()) func takesMiddle(_: [GenericOuter<Int>.Middle]) {} takesMiddle([GenericOuter<Int>.Middle]()) func takesInner(_: [GenericOuter<Int>.Middle.Inner]) {} takesInner([GenericOuter<Int>.Middle.Inner]()) takesInner([array.GenericOuter<Int>.Middle.Inner]()) func takesMiddle(_: [Outer.GenericMiddle<Int>]) {} takesMiddle([Outer.GenericMiddle<Int>]()) func takesInner(_: [Outer.GenericMiddle<Int>.Inner]) {} takesInner([Outer.GenericMiddle<Int>.Inner]()) takesInner([array.Outer.GenericMiddle<Int>.Inner]()) func takesInner(_: [Outer.Middle.GenericInner<Int>]) {} takesInner([Outer.Middle.GenericInner<Int>]()) takesInner([array.Outer.Middle.GenericInner<Int>]()) protocol HasAssocType { associatedtype A } func takesAssocType<T : HasAssocType>(_: T, _: [T.A], _: [T.A?]) {} func passAssocType<T : HasAssocType>(_ t: T) { takesAssocType(t, [T.A](), [T.A?]()) } // SR-11134 let sr_11134_1 = [[1, 2, 3][0]] // ok let sr_11134_2 = [[1, 2, 3] [1]] // expected-warning {{unexpected subscript in array literal; did you mean to write two separate elements instead?}} // expected-note@-1 {{add a separator between the elements}}{{28-28=,}} // expected-note@-2 {{remove the space between the elements to silence this warning}}{{28-29=}} let sr_11134_3 = [ [1, 2, 3] [1] // expected-warning {{unexpected subscript in array literal; did you mean to write two separate elements instead?}} // expected-note@-1 {{add a separator between the elements}}{{12-12=,}} // expected-note@-2 {{remove the space between the elements to silence this warning}}{{12-13=}} ]
26.890625
148
0.662406
e0a74c86d0edb5b3e87b3e3ba68ed107823fd080
3,805
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIO print("Please enter line to send to the server") let line = readLine(strippingNewline: true)! private final class EchoHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer private var numBytes = 0 public func channelActive(context: ChannelHandlerContext) { print("Client connected to \(context.remoteAddress!)") // We are connected. It's time to send the message to the server to initialize the ping-pong sequence. var buffer = context.channel.allocator.buffer(capacity: line.utf8.count) buffer.writeString(line) self.numBytes = buffer.readableBytes context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { var byteBuffer = self.unwrapInboundIn(data) self.numBytes -= byteBuffer.readableBytes if self.numBytes == 0 { if let string = byteBuffer.readString(length: byteBuffer.readableBytes) { print("Received: '\(string)' back from the server, closing channel.") } else { print("Received the line back from the server, closing channel") } context.close(promise: nil) } } public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. context.close(promise: nil) } } let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) let bootstrap = ClientBootstrap(group: group) // Enable SO_REUSEADDR. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .channelInitializer { channel in channel.pipeline.addHandler(EchoHandler()) } defer { try! group.syncShutdownGracefully() } // First argument is the program path let arguments = CommandLine.arguments let arg1 = arguments.dropFirst().first let arg2 = arguments.dropFirst(2).first let defaultHost = "::1" let defaultPort: Int = 9999 enum ConnectTo { case ip(host: String, port: Int) case unixDomainSocket(path: String) } let connectTarget: ConnectTo switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) { case (.some(let h), _ , .some(let p)): /* we got two arguments, let's interpret that as host and port */ connectTarget = .ip(host: h, port: p) case (.some(let portString), .none, _): /* couldn't parse as number, expecting unix domain socket path */ connectTarget = .unixDomainSocket(path: portString) case (_, .some(let p), _): /* only one argument --> port */ connectTarget = .ip(host: defaultHost, port: p) default: connectTarget = .ip(host: defaultHost, port: defaultPort) } let channel = try { () -> Channel in switch connectTarget { case .ip(let host, let port): return try bootstrap.connect(host: host, port: port).wait() case .unixDomainSocket(let path): return try bootstrap.connect(unixDomainSocketPath: path).wait() } }() // Will be closed after we echo-ed back to the server. try channel.closeFuture.wait() print("Client closed")
34.908257
112
0.659396
11230f99eb9090634846774357d6b86e603f8881
3,623
// // MenuViewController.swift // AKSwiftSlideMenu // // Created by Ashish on 21/09/15. // Copyright (c) 2015 Kode. All rights reserved. // import UIKit protocol SlideMenuDelegate { func slideMenuItemSelectedAtIndex(_ index : Int32) } class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { /** * Array to display menu options */ @IBOutlet var tblMenuOptions : UITableView! /** * Transparent button to hide menu */ @IBOutlet var btnCloseMenuOverlay : UIButton! /** * Array containing menu options */ var arrayMenuOptions = [Dictionary<String,String>]() /** * Menu button which was tapped to display the menu */ var btnMenu : UIButton! /** * Delegate of the MenuVC */ var delegate : SlideMenuDelegate? override func viewDidLoad() { super.viewDidLoad() tblMenuOptions.tableFooterView = UIView() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateArrayMenuOptions() } func updateArrayMenuOptions(){ arrayMenuOptions.append(["title":"Home", "icon":"HomeIcon"]) arrayMenuOptions.append(["title":"Play", "icon":"PlayIcon"]) tblMenuOptions.reloadData() } @IBAction func onCloseMenuClick(_ button:UIButton!){ btnMenu.tag = 0 if (self.delegate != nil) { var index = Int32(button.tag) if(button == self.btnCloseMenuOverlay){ index = -1 } delegate?.slideMenuItemSelectedAtIndex(index) } UIView.animate(withDuration: 0.3, animations: { () -> Void in self.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width,height: UIScreen.main.bounds.size.height) self.view.layoutIfNeeded() self.view.backgroundColor = UIColor.clear }, completion: { (finished) -> Void in self.view.removeFromSuperview() self.removeFromParent() }) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellMenu")! cell.selectionStyle = UITableViewCell.SelectionStyle.none cell.layoutMargins = UIEdgeInsets.zero cell.preservesSuperviewLayoutMargins = false cell.backgroundColor = UIColor.clear let lblTitle : UILabel = cell.contentView.viewWithTag(101) as! UILabel let imgIcon : UIImageView = cell.contentView.viewWithTag(100) as! UIImageView imgIcon.image = UIImage(named: arrayMenuOptions[indexPath.row]["icon"]!) lblTitle.text = arrayMenuOptions[indexPath.row]["title"]! return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let btn = UIButton(type: UIButton.ButtonType.custom) btn.tag = indexPath.row self.onCloseMenuClick(btn) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayMenuOptions.count } func numberOfSections(in tableView: UITableView) -> Int { return 1; } }
30.965812
160
0.629589
9ce78f3c3c36d85854453c3eb22c8baeb2047b6b
1,065
// // PersistenceManager.swift // grokSwiftREST // // Created by Christina Moulton on 2016-10-29. // Copyright © 2016 Teak Mobile Inc. All rights reserved. // import Foundation enum Path: String { case Public = "Public" case Starred = "Starred" case MyGists = "MyGists" } class PersistenceManager { class private func documentsDirectory() -> NSString { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentDirectory = paths[0] as NSString return documentDirectory } class func saveArray<T: NSCoding>(arrayToSave: [T], path: Path) -> Bool { let file = documentsDirectory().appendingPathComponent(path.rawValue) return NSKeyedArchiver.archiveRootObject(arrayToSave, toFile: file) } class func loadArray<T: NSCoding>(path: Path) -> [T]? { let file = documentsDirectory().appendingPathComponent(path.rawValue) let result = NSKeyedUnarchiver.unarchiveObject(withFile: file) return result as? [T] } }
28.783784
75
0.685446
f8974ab88f6ac853d7fa507759e0011dcb2e1893
1,447
import UIKit import AVFoundation import Photos struct Utils { static func rotationTransform() -> CGAffineTransform { switch UIDevice.current.orientation { case .landscapeLeft: return CGAffineTransform(rotationAngle: CGFloat(Double.pi/2)) case .landscapeRight: return CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2)) case .portraitUpsideDown: return CGAffineTransform(rotationAngle: CGFloat(Double.pi)) default: return CGAffineTransform.identity } } static func videoOrientation() -> AVCaptureVideoOrientation { if UIDevice.current.userInterfaceIdiom == .phone { return .portrait } else { switch UIApplication.shared.statusBarOrientation { case .landscapeLeft: return .landscapeLeft case .landscapeRight: return .landscapeRight default: return .landscapeLeft } } } static func fetchOptions() -> PHFetchOptions { let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] return options } static func format(_ duration: TimeInterval) -> String { let formatter = DateComponentsFormatter() formatter.zeroFormattingBehavior = .pad if duration >= 3600 { formatter.allowedUnits = [.hour, .minute, .second] } else { formatter.allowedUnits = [.minute, .second] } return formatter.string(from: duration) ?? "" } }
27.826923
87
0.69454
bb7ed0fa71f5acd78b3a83d1908247c13acb0ae7
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true{var f=""[1)let a{enum a{class B<T where h:d{class B<h:a
38.833333
87
0.742489
f433a4a5cb9201ac371aad6cd014fe5d9996fe64
6,397
// // File name : BSViewController.swift // // Copyright (c) 2009-2021 Blueshift Corporation. All right reserved. // // 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. // // Created by Blueshift on 2021/11/23 // import UIKit /// BSViewController 초기화 옵션 /// /// ViewController 초기화에서 backButton, closeButton, keyboard 사용여부를 선택하여야합니다. /// 해당 옵션을 선택하기 위해서는 BSViewController를 상속받은 Class에서 BSViewControllerConfiguration Protocol의 options를 리턴해야합니다. /// public protocol BSViewControllerConfiguration { func options() -> [BSVCOption] } public enum BSVCOption { case backButton case closeButton case keyboard } /// UIViewController 기본값 제공 BSViewController /// /// 앱 전체에 일반적으로 사용되는 기능 및 설정값을 제공하는 Base ViewController입니다. /// 옵션을 설정하기 위해서는 BSViewControllerConfiguration protocol을 implementation 해야합니다. /// /// - Variables: /// - emptyLabel /// - isRefresing /// - isLastRow /// - startRowId /// - requestRowCnt /// - cellItems /// /// - Usage: /// ``` /// class TestViewController: BSViewController, /// BaseViewControllerConfiguration { /// /// ... /// /// override options() -> [BSVCOption] { /// return [.backButton, .closeButton] /// } /// } /// ``` open class BSViewController: UIViewController { internal var scrollView:UIScrollView? private var isBackButton = false private var isCloseButton = false private var isKeyboardUse = false //MARK: - Lifecycle open override func viewDidLoad() { super.viewDidLoad() setOptions() initializeUI() } //MARK: - Methods internal func setOptions() { guard let options = options() else { return } for option in options { switch option { case .backButton: self.isBackButton = true case .closeButton: self.isCloseButton = true case .keyboard: self.isKeyboardUse = true } } } open func initializeUI() { self.view.backgroundColor = .white self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.navigationBar.barTintColor = .white self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black] if isBackButton { let leftBtn = UIImage(systemName: "arrow.backward")?.withRenderingMode(.alwaysOriginal) let leftBarButton = UIBarButtonItem(image: leftBtn, style: .plain, target: self, action: #selector(backButtonClicked)) self.navigationItem.leftBarButtonItem = leftBarButton } if isCloseButton { let rightBtn = UIImage(named: "ic_x")?.withRenderingMode(.alwaysOriginal) let rightBarButton = UIBarButtonItem(image: rightBtn, style: .plain, target: self, action: #selector(closeButtonClicked)) self.navigationItem.rightBarButtonItem = rightBarButton } if isKeyboardUse { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) // tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } } open func options() -> [BSVCOption]? { return nil } //MARK: - Actions @objc func dismissKeyboard() { view.endEditing(true) } @objc func backButtonClicked() { navigationController?.popViewController(animated: true) } @objc func closeButtonClicked() { dismiss(animated: true) } //MARK: - Keyboard hide & show @objc open func keyboardWillShow(notification: NSNotification) { guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } if isKeyboardUse { if scrollView != nil { let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height , right: 0.0) scrollView!.contentInset = contentInsets scrollView!.scrollIndicatorInsets = contentInsets } else { if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } } @objc open func keyboardWillHide(notification: NSNotification) { let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0) if scrollView != nil { scrollView!.contentInset = contentInsets scrollView!.scrollIndicatorInsets = contentInsets } if isKeyboardUse { if scrollView != nil { } else { if self.view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } } } } }
35.342541
156
0.63905
d7e4697ae2f5397c89bd55f5bb1486fc1ba3ea99
1,882
// // ViewController.swift // UbiquitousSyncDemo // // Created by T.Hori on 2016/07/28. // Copyright © 2016年 Age Pro. All rights reserved. // import UIKit import RxSwift import RxCocoa let maxValue = 10 class ViewController: UIViewController { @IBOutlet weak var numLabel: UILabel! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var minusButton: UIButton! @IBOutlet weak var plusButton: UIButton! var disposeBag:DisposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // UbiquitousSync.removeiCloudItems4Debug(iCloud_Prefix, cloud: true, local: true) // DEBUG UbiquitousSync.startWithPrefix(iCloud_Prefix, restore:true) Common.sharedInstance.numberValue.asObservable().map{ return "\($0)"} .bindTo(numLabel.rx.text) .addDisposableTo(disposeBag) plusButton.rx.tap.subscribe({ _ in Common.sharedInstance.numberValue.value += 1 if Common.sharedInstance.numberValue.value > maxValue { Common.sharedInstance.numberValue.value = maxValue } }).addDisposableTo(disposeBag) minusButton.rx.tap.subscribe({ _ in Common.sharedInstance.numberValue.value -= 1 if Common.sharedInstance.numberValue.value < -maxValue { Common.sharedInstance.numberValue.value = -maxValue } }).addDisposableTo(disposeBag) resetButton.rx.tap.subscribe({ _ in Common.sharedInstance.numberValue.value = 0 }).addDisposableTo(disposeBag) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
31.366667
104
0.646652
f8bfc09c6af0ae3f69b052a6c2e00cb98ad3b915
997
import Foundation func shell(args: String...) -> Int32 { let task = NSTask() task.launchPath = "/usr/bin/env" task.arguments = args task.launch() task.waitUntilExit() return task.terminationStatus } let arguments = Process.arguments if count(arguments) == 3 { let source = NSURL(fileURLWithPath: arguments[1])! let destination = NSURL(fileURLWithPath: arguments[2])! shell("open", source.path!, "-a", "Deckset") if let app = DecksetApp(), document = app.documents.filter({ $0.file.path == source.path }).first { if document.exportToPDF(destination) { println("Finished saving PDF to \(destination.path!)") } else { fputs("Unable to save PDF to \(destination.path!)\n", stderr) exit(EXIT_FAILURE) } } else { fputs("Unknown error]\n", stderr) exit(EXIT_FAILURE) } } else { fputs("Usage: ./DecksetExport [source] [destination]\n", stderr) exit(EXIT_FAILURE) }
29.323529
103
0.61986
ff5ffaa7ca379d43a6eb56dcb331cd040aebc9a9
5,121
// // StatisticsLoaderTests.swift // DuckDuckGo // // Copyright © 2017 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import OHHTTPStubs @testable import Core class StatisticsLoaderTests: XCTestCase { let appUrls = AppUrls() var mockStatisticsStore: StatisticsStore! var testee: StatisticsLoader! override func setUp() { mockStatisticsStore = MockStatisticsStore() testee = StatisticsLoader(statisticsStore: mockStatisticsStore) } override func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } func testWhenLoadHasSuccessfulAtbAndExtiRequestsThenStoreUpdatedWithVariant() { mockStatisticsStore.variant = "x1" loadSuccessfulAtbStub() loadSuccessfulExiStub() let expect = expectation(description: "Successfult atb and exti updates store") testee.load { () in XCTAssertTrue(self.mockStatisticsStore.hasInstallStatistics) XCTAssertEqual(self.mockStatisticsStore.atb, "v77-5") XCTAssertEqual(self.mockStatisticsStore.retentionAtb, "v77-5") expect.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testWhenLoadHasUnsuccessfulAtbThenStoreNotUpdated() { loadUnsuccessfulAtbStub() loadSuccessfulExiStub() let expect = expectation(description: "Unsuccessfult atb does not update store") testee.load { () in XCTAssertFalse(self.mockStatisticsStore.hasInstallStatistics) XCTAssertNil(self.mockStatisticsStore.atb) XCTAssertNil(self.mockStatisticsStore.retentionAtb) expect.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testWhenLoadHasUnsuccessfulExtiThenStoreNotUpdated() { loadSuccessfulAtbStub() loadUnsuccessfulExiStub() let expect = expectation(description: "Unsuccessfult exti does not update store") testee.load { () in XCTAssertFalse(self.mockStatisticsStore.hasInstallStatistics) XCTAssertNil(self.mockStatisticsStore.atb) XCTAssertNil(self.mockStatisticsStore.retentionAtb) expect.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testWhenRefreshHasSuccessfulAtbRequestThenRetentionAtbUpdated() { mockStatisticsStore.atb = "atb" mockStatisticsStore.retentionAtb = "retentionatb" loadSuccessfulAtbStub() let expect = expectation(description: "Successfult atb updates retention store") testee.refreshRetentionAtb { () in XCTAssertEqual(self.mockStatisticsStore.atb, "atb") XCTAssertEqual(self.mockStatisticsStore.retentionAtb, "v77-5") expect.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testWhenRefreshHasUnsuccessfulAtbRequestThenRetentionAtbNotUpdated() { mockStatisticsStore.atb = "atb" mockStatisticsStore.retentionAtb = "retentionAtb" loadUnsuccessfulAtbStub() let expect = expectation(description: "Unsuccessfult atb does not update store") testee.refreshRetentionAtb { () in XCTAssertEqual(self.mockStatisticsStore.atb, "atb") XCTAssertEqual(self.mockStatisticsStore.retentionAtb, "retentionAtb") expect.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func loadSuccessfulAtbStub() { stub(condition: isHost(appUrls.atb.host!)) { _ in let path = OHPathForFile("MockFiles/atb.json", type(of: self))! return fixture(filePath: path, status: 200, headers: nil) } } func loadUnsuccessfulAtbStub() { stub(condition: isHost(appUrls.atb.host!)) { _ in let path = OHPathForFile("MockFiles/invalid.json", type(of: self))! return fixture(filePath: path, status: 400, headers: nil) } } func loadSuccessfulExiStub() { stub(condition: isPath(appUrls.exti(forAtb: "").path)) { _ -> OHHTTPStubsResponse in let path = OHPathForFile("MockFiles/empty", type(of: self))! return fixture(filePath: path, status: 200, headers: nil) } } func loadUnsuccessfulExiStub() { stub(condition: isPath(appUrls.exti(forAtb: "").path)) { _ -> OHHTTPStubsResponse in let path = OHPathForFile("MockFiles/empty", type(of: self))! return fixture(filePath: path, status: 400, headers: nil) } } }
34.14
92
0.671744
09d3acb33e466605da4f20fd8094eefa8da2d645
1,359
// // NetworkHelper.swift // Elements // // Created by Juan Ceballos on 12/19/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation class NetworkHelper { static let shared = NetworkHelper() private var session: URLSession private init() { session = URLSession(configuration: .default) } func performDataTask(with request: URLRequest, completion: @escaping (Result<Data, AppError>) -> ()) { let dataTask = session.dataTask(with: request) { (data, response, error) in if let error = error { completion(.failure(.networkClientError(error))) return } guard let urlResponse = response as? HTTPURLResponse else { completion(.failure(.noResponse)) return } guard let data = data else { completion(.failure(.noData)) return } switch urlResponse.statusCode { case 200...299: break default: completion(.failure(.badStatusCode(urlResponse.statusCode))) return } completion(.success(data)) } dataTask.resume() } }
26.134615
83
0.509934
aca0b8a2e070caca920ce80d9cc2aed5b1def813
349,609
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. import Foundation import SotoCore extension Kendra { // MARK: Enums public enum AdditionalResultAttributeValueType: String, CustomStringConvertible, Codable { case textWithHighlightsValue = "TEXT_WITH_HIGHLIGHTS_VALUE" public var description: String { return self.rawValue } } public enum ConfluenceAttachmentFieldName: String, CustomStringConvertible, Codable { case author = "AUTHOR" case contentType = "CONTENT_TYPE" case createdDate = "CREATED_DATE" case displayUrl = "DISPLAY_URL" case fileSize = "FILE_SIZE" case itemType = "ITEM_TYPE" case parentId = "PARENT_ID" case spaceKey = "SPACE_KEY" case spaceName = "SPACE_NAME" case url = "URL" case version = "VERSION" public var description: String { return self.rawValue } } public enum ConfluenceBlogFieldName: String, CustomStringConvertible, Codable { case author = "AUTHOR" case displayUrl = "DISPLAY_URL" case itemType = "ITEM_TYPE" case labels = "LABELS" case publishDate = "PUBLISH_DATE" case spaceKey = "SPACE_KEY" case spaceName = "SPACE_NAME" case url = "URL" case version = "VERSION" public var description: String { return self.rawValue } } public enum ConfluencePageFieldName: String, CustomStringConvertible, Codable { case author = "AUTHOR" case contentStatus = "CONTENT_STATUS" case createdDate = "CREATED_DATE" case displayUrl = "DISPLAY_URL" case itemType = "ITEM_TYPE" case labels = "LABELS" case modifiedDate = "MODIFIED_DATE" case parentId = "PARENT_ID" case spaceKey = "SPACE_KEY" case spaceName = "SPACE_NAME" case url = "URL" case version = "VERSION" public var description: String { return self.rawValue } } public enum ConfluenceSpaceFieldName: String, CustomStringConvertible, Codable { case displayUrl = "DISPLAY_URL" case itemType = "ITEM_TYPE" case spaceKey = "SPACE_KEY" case url = "URL" public var description: String { return self.rawValue } } public enum ConfluenceVersion: String, CustomStringConvertible, Codable { case cloud = "CLOUD" case server = "SERVER" public var description: String { return self.rawValue } } public enum ContentType: String, CustomStringConvertible, Codable { case html = "HTML" case msWord = "MS_WORD" case pdf = "PDF" case plainText = "PLAIN_TEXT" case ppt = "PPT" public var description: String { return self.rawValue } } public enum DataSourceStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case creating = "CREATING" case deleting = "DELETING" case failed = "FAILED" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum DataSourceSyncJobStatus: String, CustomStringConvertible, Codable { case aborted = "ABORTED" case failed = "FAILED" case incomplete = "INCOMPLETE" case stopping = "STOPPING" case succeeded = "SUCCEEDED" case syncing = "SYNCING" case syncingIndexing = "SYNCING_INDEXING" public var description: String { return self.rawValue } } public enum DataSourceType: String, CustomStringConvertible, Codable { case confluence = "CONFLUENCE" case custom = "CUSTOM" case database = "DATABASE" case googledrive = "GOOGLEDRIVE" case onedrive = "ONEDRIVE" case s3 = "S3" case salesforce = "SALESFORCE" case servicenow = "SERVICENOW" case sharepoint = "SHAREPOINT" case webcrawler = "WEBCRAWLER" case workdocs = "WORKDOCS" public var description: String { return self.rawValue } } public enum DatabaseEngineType: String, CustomStringConvertible, Codable { case rdsAuroraMysql = "RDS_AURORA_MYSQL" case rdsAuroraPostgresql = "RDS_AURORA_POSTGRESQL" case rdsMysql = "RDS_MYSQL" case rdsPostgresql = "RDS_POSTGRESQL" public var description: String { return self.rawValue } } public enum DocumentAttributeValueType: String, CustomStringConvertible, Codable { case dateValue = "DATE_VALUE" case longValue = "LONG_VALUE" case stringListValue = "STRING_LIST_VALUE" case stringValue = "STRING_VALUE" public var description: String { return self.rawValue } } public enum DocumentStatus: String, CustomStringConvertible, Codable { case failed = "FAILED" case indexed = "INDEXED" case notFound = "NOT_FOUND" case processing = "PROCESSING" case updated = "UPDATED" case updateFailed = "UPDATE_FAILED" public var description: String { return self.rawValue } } public enum ErrorCode: String, CustomStringConvertible, Codable { case internalerror = "InternalError" case invalidrequest = "InvalidRequest" public var description: String { return self.rawValue } } public enum FaqFileFormat: String, CustomStringConvertible, Codable { case csv = "CSV" case csvWithHeader = "CSV_WITH_HEADER" case json = "JSON" public var description: String { return self.rawValue } } public enum FaqStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case creating = "CREATING" case deleting = "DELETING" case failed = "FAILED" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum HighlightType: String, CustomStringConvertible, Codable { case standard = "STANDARD" case thesaurusSynonym = "THESAURUS_SYNONYM" public var description: String { return self.rawValue } } public enum IndexEdition: String, CustomStringConvertible, Codable { case developerEdition = "DEVELOPER_EDITION" case enterpriseEdition = "ENTERPRISE_EDITION" public var description: String { return self.rawValue } } public enum IndexStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case creating = "CREATING" case deleting = "DELETING" case failed = "FAILED" case systemUpdating = "SYSTEM_UPDATING" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum KeyLocation: String, CustomStringConvertible, Codable { case secretManager = "SECRET_MANAGER" case url = "URL" public var description: String { return self.rawValue } } public enum Mode: String, CustomStringConvertible, Codable { case enabled = "ENABLED" case learnOnly = "LEARN_ONLY" public var description: String { return self.rawValue } } public enum Order: String, CustomStringConvertible, Codable { case ascending = "ASCENDING" case descending = "DESCENDING" public var description: String { return self.rawValue } } public enum PrincipalMappingStatus: String, CustomStringConvertible, Codable { case deleted = "DELETED" case deleting = "DELETING" case failed = "FAILED" case processing = "PROCESSING" case succeeded = "SUCCEEDED" public var description: String { return self.rawValue } } public enum PrincipalType: String, CustomStringConvertible, Codable { case group = "GROUP" case user = "USER" public var description: String { return self.rawValue } } public enum QueryIdentifiersEnclosingOption: String, CustomStringConvertible, Codable { case doubleQuotes = "DOUBLE_QUOTES" case none = "NONE" public var description: String { return self.rawValue } } public enum QueryResultType: String, CustomStringConvertible, Codable { case answer = "ANSWER" case document = "DOCUMENT" case questionAnswer = "QUESTION_ANSWER" public var description: String { return self.rawValue } } public enum QuerySuggestionsBlockListStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case activeButUpdateFailed = "ACTIVE_BUT_UPDATE_FAILED" case creating = "CREATING" case deleting = "DELETING" case failed = "FAILED" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum QuerySuggestionsStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum ReadAccessType: String, CustomStringConvertible, Codable { case allow = "ALLOW" case deny = "DENY" public var description: String { return self.rawValue } } public enum RelevanceType: String, CustomStringConvertible, Codable { case notRelevant = "NOT_RELEVANT" case relevant = "RELEVANT" public var description: String { return self.rawValue } } public enum SalesforceChatterFeedIncludeFilterType: String, CustomStringConvertible, Codable { case activeUser = "ACTIVE_USER" case standardUser = "STANDARD_USER" public var description: String { return self.rawValue } } public enum SalesforceKnowledgeArticleState: String, CustomStringConvertible, Codable { case archived = "ARCHIVED" case draft = "DRAFT" case published = "PUBLISHED" public var description: String { return self.rawValue } } public enum SalesforceStandardObjectName: String, CustomStringConvertible, Codable { case account = "ACCOUNT" case campaign = "CAMPAIGN" case `case` = "CASE" case contact = "CONTACT" case contract = "CONTRACT" case document = "DOCUMENT" case group = "GROUP" case idea = "IDEA" case lead = "LEAD" case opportunity = "OPPORTUNITY" case partner = "PARTNER" case pricebook = "PRICEBOOK" case product = "PRODUCT" case profile = "PROFILE" case solution = "SOLUTION" case task = "TASK" case user = "USER" public var description: String { return self.rawValue } } public enum ScoreConfidence: String, CustomStringConvertible, Codable { case high = "HIGH" case low = "LOW" case medium = "MEDIUM" case notAvailable = "NOT_AVAILABLE" case veryHigh = "VERY_HIGH" public var description: String { return self.rawValue } } public enum ServiceNowAuthenticationType: String, CustomStringConvertible, Codable { case httpBasic = "HTTP_BASIC" case oauth2 = "OAUTH2" public var description: String { return self.rawValue } } public enum ServiceNowBuildVersionType: String, CustomStringConvertible, Codable { case london = "LONDON" case others = "OTHERS" public var description: String { return self.rawValue } } public enum SharePointVersion: String, CustomStringConvertible, Codable { case sharepoint2013 = "SHAREPOINT_2013" case sharepoint2016 = "SHAREPOINT_2016" case sharepointOnline = "SHAREPOINT_ONLINE" public var description: String { return self.rawValue } } public enum SortOrder: String, CustomStringConvertible, Codable { case asc = "ASC" case desc = "DESC" public var description: String { return self.rawValue } } public enum ThesaurusStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case activeButUpdateFailed = "ACTIVE_BUT_UPDATE_FAILED" case creating = "CREATING" case deleting = "DELETING" case failed = "FAILED" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum UserContextPolicy: String, CustomStringConvertible, Codable { case attributeFilter = "ATTRIBUTE_FILTER" case userToken = "USER_TOKEN" public var description: String { return self.rawValue } } public enum UserGroupResolutionMode: String, CustomStringConvertible, Codable { case awsSso = "AWS_SSO" case none = "NONE" public var description: String { return self.rawValue } } public enum WebCrawlerMode: String, CustomStringConvertible, Codable { case everything = "EVERYTHING" case hostOnly = "HOST_ONLY" case subdomains = "SUBDOMAINS" public var description: String { return self.rawValue } } // MARK: Shapes public struct AccessControlListConfiguration: AWSEncodableShape & AWSDecodableShape { /// Path to the Amazon Web Services S3 bucket that contains the ACL files. public let keyPath: String? public init(keyPath: String? = nil) { self.keyPath = keyPath } public func validate(name: String) throws { try self.validate(self.keyPath, name: "keyPath", parent: name, max: 1024) try self.validate(self.keyPath, name: "keyPath", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case keyPath = "KeyPath" } } public struct AclConfiguration: AWSEncodableShape & AWSDecodableShape { /// A list of groups, separated by semi-colons, that filters a query response based on user context. The document is only returned to users that are in one of the groups specified in the UserContext field of the Query operation. public let allowedGroupsColumnName: String public init(allowedGroupsColumnName: String) { self.allowedGroupsColumnName = allowedGroupsColumnName } public func validate(name: String) throws { try self.validate(self.allowedGroupsColumnName, name: "allowedGroupsColumnName", parent: name, max: 100) try self.validate(self.allowedGroupsColumnName, name: "allowedGroupsColumnName", parent: name, min: 1) try self.validate(self.allowedGroupsColumnName, name: "allowedGroupsColumnName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: String, CodingKey { case allowedGroupsColumnName = "AllowedGroupsColumnName" } } public struct AdditionalResultAttribute: AWSDecodableShape { /// The key that identifies the attribute. public let key: String /// An object that contains the attribute value. public let value: AdditionalResultAttributeValue /// The data type of the Value property. public let valueType: AdditionalResultAttributeValueType public init(key: String, value: AdditionalResultAttributeValue, valueType: AdditionalResultAttributeValueType) { self.key = key self.value = value self.valueType = valueType } private enum CodingKeys: String, CodingKey { case key = "Key" case value = "Value" case valueType = "ValueType" } } public struct AdditionalResultAttributeValue: AWSDecodableShape { /// The text associated with the attribute and information about the highlight to apply to the text. public let textWithHighlightsValue: TextWithHighlights? public init(textWithHighlightsValue: TextWithHighlights? = nil) { self.textWithHighlightsValue = textWithHighlightsValue } private enum CodingKeys: String, CodingKey { case textWithHighlightsValue = "TextWithHighlightsValue" } } public class AttributeFilter: AWSEncodableShape { /// Performs a logical AND operation on all supplied filters. public let andAllFilters: [AttributeFilter]? /// Returns true when a document contains all of the specified document attributes. This filter is only applicable to StringListValue metadata. public let containsAll: DocumentAttribute? /// Returns true when a document contains any of the specified document attributes. This filter is only applicable to StringListValue metadata. public let containsAny: DocumentAttribute? /// Performs an equals operation on two document attributes. public let equalsTo: DocumentAttribute? /// Performs a greater than operation on two document attributes. Use with a document attribute of type Date or Long. public let greaterThan: DocumentAttribute? /// Performs a greater or equals than operation on two document attributes. Use with a document attribute of type Date or Long. public let greaterThanOrEquals: DocumentAttribute? /// Performs a less than operation on two document attributes. Use with a document attribute of type Date or Long. public let lessThan: DocumentAttribute? /// Performs a less than or equals operation on two document attributes. Use with a document attribute of type Date or Long. public let lessThanOrEquals: DocumentAttribute? /// Performs a logical NOT operation on all supplied filters. public let notFilter: AttributeFilter? /// Performs a logical OR operation on all supplied filters. public let orAllFilters: [AttributeFilter]? public init(andAllFilters: [AttributeFilter]? = nil, containsAll: DocumentAttribute? = nil, containsAny: DocumentAttribute? = nil, equalsTo: DocumentAttribute? = nil, greaterThan: DocumentAttribute? = nil, greaterThanOrEquals: DocumentAttribute? = nil, lessThan: DocumentAttribute? = nil, lessThanOrEquals: DocumentAttribute? = nil, notFilter: AttributeFilter? = nil, orAllFilters: [AttributeFilter]? = nil) { self.andAllFilters = andAllFilters self.containsAll = containsAll self.containsAny = containsAny self.equalsTo = equalsTo self.greaterThan = greaterThan self.greaterThanOrEquals = greaterThanOrEquals self.lessThan = lessThan self.lessThanOrEquals = lessThanOrEquals self.notFilter = notFilter self.orAllFilters = orAllFilters } public func validate(name: String) throws { try self.andAllFilters?.forEach { try $0.validate(name: "\(name).andAllFilters[]") } try self.containsAll?.validate(name: "\(name).containsAll") try self.containsAny?.validate(name: "\(name).containsAny") try self.equalsTo?.validate(name: "\(name).equalsTo") try self.greaterThan?.validate(name: "\(name).greaterThan") try self.greaterThanOrEquals?.validate(name: "\(name).greaterThanOrEquals") try self.lessThan?.validate(name: "\(name).lessThan") try self.lessThanOrEquals?.validate(name: "\(name).lessThanOrEquals") try self.notFilter?.validate(name: "\(name).notFilter") try self.orAllFilters?.forEach { try $0.validate(name: "\(name).orAllFilters[]") } } private enum CodingKeys: String, CodingKey { case andAllFilters = "AndAllFilters" case containsAll = "ContainsAll" case containsAny = "ContainsAny" case equalsTo = "EqualsTo" case greaterThan = "GreaterThan" case greaterThanOrEquals = "GreaterThanOrEquals" case lessThan = "LessThan" case lessThanOrEquals = "LessThanOrEquals" case notFilter = "NotFilter" case orAllFilters = "OrAllFilters" } } public struct AuthenticationConfiguration: AWSEncodableShape & AWSDecodableShape { /// The list of configuration information that's required to connect to and crawl a website host using basic authentication credentials. The list includes the name and port number of the website host. public let basicAuthentication: [BasicAuthenticationConfiguration]? public init(basicAuthentication: [BasicAuthenticationConfiguration]? = nil) { self.basicAuthentication = basicAuthentication } public func validate(name: String) throws { try self.basicAuthentication?.forEach { try $0.validate(name: "\(name).basicAuthentication[]") } try self.validate(self.basicAuthentication, name: "basicAuthentication", parent: name, max: 10) } private enum CodingKeys: String, CodingKey { case basicAuthentication = "BasicAuthentication" } } public struct BasicAuthenticationConfiguration: AWSEncodableShape & AWSDecodableShape { /// Your secret ARN, which you can create in AWS Secrets Manager You use a secret if basic authentication credentials are required to connect to a website. The secret stores your credentials of user name and password. public let credentials: String /// The name of the website host you want to connect to using authentication credentials. For example, the host name of https://a.example.com/page1.html is "a.example.com". public let host: String /// The port number of the website host you want to connect to using authentication credentials. For example, the port for https://a.example.com/page1.html is 443, the standard port for HTTPS. public let port: Int public init(credentials: String, host: String, port: Int) { self.credentials = credentials self.host = host self.port = port } public func validate(name: String) throws { try self.validate(self.credentials, name: "credentials", parent: name, max: 1284) try self.validate(self.credentials, name: "credentials", parent: name, min: 1) try self.validate(self.credentials, name: "credentials", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.host, name: "host", parent: name, max: 253) try self.validate(self.host, name: "host", parent: name, min: 1) try self.validate(self.host, name: "host", parent: name, pattern: "^([^\\s]*)$") try self.validate(self.port, name: "port", parent: name, max: 65535) try self.validate(self.port, name: "port", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case credentials = "Credentials" case host = "Host" case port = "Port" } } public struct BatchDeleteDocumentRequest: AWSEncodableShape { public let dataSourceSyncJobMetricTarget: DataSourceSyncJobMetricTarget? /// One or more identifiers for documents to delete from the index. public let documentIdList: [String] /// The identifier of the index that contains the documents to delete. public let indexId: String public init(dataSourceSyncJobMetricTarget: DataSourceSyncJobMetricTarget? = nil, documentIdList: [String], indexId: String) { self.dataSourceSyncJobMetricTarget = dataSourceSyncJobMetricTarget self.documentIdList = documentIdList self.indexId = indexId } public func validate(name: String) throws { try self.dataSourceSyncJobMetricTarget?.validate(name: "\(name).dataSourceSyncJobMetricTarget") try self.documentIdList.forEach { try validate($0, name: "documentIdList[]", parent: name, max: 2048) try validate($0, name: "documentIdList[]", parent: name, min: 1) } try self.validate(self.documentIdList, name: "documentIdList", parent: name, max: 10) try self.validate(self.documentIdList, name: "documentIdList", parent: name, min: 1) try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case dataSourceSyncJobMetricTarget = "DataSourceSyncJobMetricTarget" case documentIdList = "DocumentIdList" case indexId = "IndexId" } } public struct BatchDeleteDocumentResponse: AWSDecodableShape { /// A list of documents that could not be removed from the index. Each entry contains an error message that indicates why the document couldn't be removed from the index. public let failedDocuments: [BatchDeleteDocumentResponseFailedDocument]? public init(failedDocuments: [BatchDeleteDocumentResponseFailedDocument]? = nil) { self.failedDocuments = failedDocuments } private enum CodingKeys: String, CodingKey { case failedDocuments = "FailedDocuments" } } public struct BatchDeleteDocumentResponseFailedDocument: AWSDecodableShape { /// The error code for why the document couldn't be removed from the index. public let errorCode: ErrorCode? /// An explanation for why the document couldn't be removed from the index. public let errorMessage: String? /// The identifier of the document that couldn't be removed from the index. public let id: String? public init(errorCode: ErrorCode? = nil, errorMessage: String? = nil, id: String? = nil) { self.errorCode = errorCode self.errorMessage = errorMessage self.id = id } private enum CodingKeys: String, CodingKey { case errorCode = "ErrorCode" case errorMessage = "ErrorMessage" case id = "Id" } } public struct BatchGetDocumentStatusRequest: AWSEncodableShape { /// A list of DocumentInfo objects that identify the documents for which to get the status. You identify the documents by their document ID and optional attributes. public let documentInfoList: [DocumentInfo] /// The identifier of the index to add documents to. The index ID is returned by the CreateIndex operation. public let indexId: String public init(documentInfoList: [DocumentInfo], indexId: String) { self.documentInfoList = documentInfoList self.indexId = indexId } public func validate(name: String) throws { try self.documentInfoList.forEach { try $0.validate(name: "\(name).documentInfoList[]") } try self.validate(self.documentInfoList, name: "documentInfoList", parent: name, max: 10) try self.validate(self.documentInfoList, name: "documentInfoList", parent: name, min: 1) try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case documentInfoList = "DocumentInfoList" case indexId = "IndexId" } } public struct BatchGetDocumentStatusResponse: AWSDecodableShape { /// The status of documents. The status indicates if the document is waiting to be indexed, is in the process of indexing, has completed indexing, or failed indexing. If a document failed indexing, the status provides the reason why. public let documentStatusList: [Status]? /// A list of documents that Amazon Kendra couldn't get the status for. The list includes the ID of the document and the reason that the status couldn't be found. public let errors: [BatchGetDocumentStatusResponseError]? public init(documentStatusList: [Status]? = nil, errors: [BatchGetDocumentStatusResponseError]? = nil) { self.documentStatusList = documentStatusList self.errors = errors } private enum CodingKeys: String, CodingKey { case documentStatusList = "DocumentStatusList" case errors = "Errors" } } public struct BatchGetDocumentStatusResponseError: AWSDecodableShape { /// The unique identifier of the document whose status could not be retrieved. public let documentId: String? /// Indicates the source of the error. public let errorCode: ErrorCode? /// States that the API could not get the status of a document. This could be because the request is not valid or there is a system error. public let errorMessage: String? public init(documentId: String? = nil, errorCode: ErrorCode? = nil, errorMessage: String? = nil) { self.documentId = documentId self.errorCode = errorCode self.errorMessage = errorMessage } private enum CodingKeys: String, CodingKey { case documentId = "DocumentId" case errorCode = "ErrorCode" case errorMessage = "ErrorMessage" } } public struct BatchPutDocumentRequest: AWSEncodableShape { /// One or more documents to add to the index. Documents can include custom attributes. For example, 'DataSourceId' and 'DataSourceSyncJobId' are custom attributes that provide information on the synchronization of documents running on a data source. Note, 'DataSourceSyncJobId' could be an optional custom attribute as Amazon Kendra will use the ID of a running sync job. Documents have the following file size limits. 5 MB total size for inline documents 50 MB total size for files from an S3 bucket 5 MB extracted text for any file For more information about file size and transaction per second quotas, see Quotas. public let documents: [Document] /// The identifier of the index to add the documents to. You need to create the index first using the CreateIndex operation. public let indexId: String /// The Amazon Resource Name (ARN) of a role that is allowed to run the BatchPutDocument operation. For more information, see IAM Roles for Amazon Kendra. public let roleArn: String? public init(documents: [Document], indexId: String, roleArn: String? = nil) { self.documents = documents self.indexId = indexId self.roleArn = roleArn } public func validate(name: String) throws { try self.documents.forEach { try $0.validate(name: "\(name).documents[]") } try self.validate(self.documents, name: "documents", parent: name, max: 10) try self.validate(self.documents, name: "documents", parent: name, min: 1) try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") } private enum CodingKeys: String, CodingKey { case documents = "Documents" case indexId = "IndexId" case roleArn = "RoleArn" } } public struct BatchPutDocumentResponse: AWSDecodableShape { /// A list of documents that were not added to the index because the document failed a validation check. Each document contains an error message that indicates why the document couldn't be added to the index. If there was an error adding a document to an index the error is reported in your Amazon Web Services CloudWatch log. For more information, see Monitoring Amazon Kendra with Amazon CloudWatch Logs public let failedDocuments: [BatchPutDocumentResponseFailedDocument]? public init(failedDocuments: [BatchPutDocumentResponseFailedDocument]? = nil) { self.failedDocuments = failedDocuments } private enum CodingKeys: String, CodingKey { case failedDocuments = "FailedDocuments" } } public struct BatchPutDocumentResponseFailedDocument: AWSDecodableShape { /// The type of error that caused the document to fail to be indexed. public let errorCode: ErrorCode? /// A description of the reason why the document could not be indexed. public let errorMessage: String? /// The unique identifier of the document. public let id: String? public init(errorCode: ErrorCode? = nil, errorMessage: String? = nil, id: String? = nil) { self.errorCode = errorCode self.errorMessage = errorMessage self.id = id } private enum CodingKeys: String, CodingKey { case errorCode = "ErrorCode" case errorMessage = "ErrorMessage" case id = "Id" } } public struct CapacityUnitsConfiguration: AWSEncodableShape & AWSDecodableShape { /// The amount of extra query capacity for an index and GetQuerySuggestions capacity. A single extra capacity unit for an index provides 0.1 queries per second or approximately 8,000 queries per day. GetQuerySuggestions capacity is five times the provisioned query capacity for an index, or the base capacity of 2.5 calls per second, whichever is higher. For example, the base capacity for an index is 0.1 queries per second, and GetQuerySuggestions capacity has a base of 2.5 calls per second. If you add another 0.1 queries per second to total 0.2 queries per second for an index, the GetQuerySuggestions capacity is 2.5 calls per second (higher than five times 0.2 queries per second). public let queryCapacityUnits: Int /// The amount of extra storage capacity for an index. A single capacity unit provides 30 GB of storage space or 100,000 documents, whichever is reached first. public let storageCapacityUnits: Int public init(queryCapacityUnits: Int, storageCapacityUnits: Int) { self.queryCapacityUnits = queryCapacityUnits self.storageCapacityUnits = storageCapacityUnits } public func validate(name: String) throws { try self.validate(self.queryCapacityUnits, name: "queryCapacityUnits", parent: name, min: 0) try self.validate(self.storageCapacityUnits, name: "storageCapacityUnits", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case queryCapacityUnits = "QueryCapacityUnits" case storageCapacityUnits = "StorageCapacityUnits" } } public struct ClearQuerySuggestionsRequest: AWSEncodableShape { /// The identifier of the index you want to clear query suggestions from. public let indexId: String public init(indexId: String) { self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" } } public struct ClickFeedback: AWSEncodableShape { /// The Unix timestamp of the date and time that the result was clicked. public let clickTime: Date /// The unique identifier of the search result that was clicked. public let resultId: String public init(clickTime: Date, resultId: String) { self.clickTime = clickTime self.resultId = resultId } public func validate(name: String) throws { try self.validate(self.resultId, name: "resultId", parent: name, max: 73) try self.validate(self.resultId, name: "resultId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clickTime = "ClickTime" case resultId = "ResultId" } } public struct ColumnConfiguration: AWSEncodableShape & AWSDecodableShape { /// One to five columns that indicate when a document in the database has changed. public let changeDetectingColumns: [String] /// The column that contains the contents of the document. public let documentDataColumnName: String /// The column that provides the document's unique identifier. public let documentIdColumnName: String /// The column that contains the title of the document. public let documentTitleColumnName: String? /// An array of objects that map database column names to the corresponding fields in an index. You must first create the fields in the index using the UpdateIndex operation. public let fieldMappings: [DataSourceToIndexFieldMapping]? public init(changeDetectingColumns: [String], documentDataColumnName: String, documentIdColumnName: String, documentTitleColumnName: String? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil) { self.changeDetectingColumns = changeDetectingColumns self.documentDataColumnName = documentDataColumnName self.documentIdColumnName = documentIdColumnName self.documentTitleColumnName = documentTitleColumnName self.fieldMappings = fieldMappings } public func validate(name: String) throws { try self.changeDetectingColumns.forEach { try validate($0, name: "changeDetectingColumns[]", parent: name, max: 100) try validate($0, name: "changeDetectingColumns[]", parent: name, min: 1) try validate($0, name: "changeDetectingColumns[]", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } try self.validate(self.changeDetectingColumns, name: "changeDetectingColumns", parent: name, max: 5) try self.validate(self.changeDetectingColumns, name: "changeDetectingColumns", parent: name, min: 1) try self.validate(self.documentDataColumnName, name: "documentDataColumnName", parent: name, max: 100) try self.validate(self.documentDataColumnName, name: "documentDataColumnName", parent: name, min: 1) try self.validate(self.documentDataColumnName, name: "documentDataColumnName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") try self.validate(self.documentIdColumnName, name: "documentIdColumnName", parent: name, max: 100) try self.validate(self.documentIdColumnName, name: "documentIdColumnName", parent: name, min: 1) try self.validate(self.documentIdColumnName, name: "documentIdColumnName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") try self.validate(self.documentTitleColumnName, name: "documentTitleColumnName", parent: name, max: 100) try self.validate(self.documentTitleColumnName, name: "documentTitleColumnName", parent: name, min: 1) try self.validate(self.documentTitleColumnName, name: "documentTitleColumnName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case changeDetectingColumns = "ChangeDetectingColumns" case documentDataColumnName = "DocumentDataColumnName" case documentIdColumnName = "DocumentIdColumnName" case documentTitleColumnName = "DocumentTitleColumnName" case fieldMappings = "FieldMappings" } } public struct ConfluenceAttachmentConfiguration: AWSEncodableShape & AWSDecodableShape { /// Defines how attachment metadata fields should be mapped to index fields. Before you can map a field, you must first create an index field with a matching type using the console or the UpdateIndex operation. If you specify the AttachentFieldMappings parameter, you must specify at least one field mapping. public let attachmentFieldMappings: [ConfluenceAttachmentToIndexFieldMapping]? /// Indicates whether Amazon Kendra indexes attachments to the pages and blogs in the Confluence data source. public let crawlAttachments: Bool? public init(attachmentFieldMappings: [ConfluenceAttachmentToIndexFieldMapping]? = nil, crawlAttachments: Bool? = nil) { self.attachmentFieldMappings = attachmentFieldMappings self.crawlAttachments = crawlAttachments } public func validate(name: String) throws { try self.attachmentFieldMappings?.forEach { try $0.validate(name: "\(name).attachmentFieldMappings[]") } try self.validate(self.attachmentFieldMappings, name: "attachmentFieldMappings", parent: name, max: 11) try self.validate(self.attachmentFieldMappings, name: "attachmentFieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case attachmentFieldMappings = "AttachmentFieldMappings" case crawlAttachments = "CrawlAttachments" } } public struct ConfluenceAttachmentToIndexFieldMapping: AWSEncodableShape & AWSDecodableShape { /// The name of the field in the data source. You must first create the index field using the UpdateIndex operation. public let dataSourceFieldName: ConfluenceAttachmentFieldName? /// The format for date fields in the data source. If the field specified in DataSourceFieldName is a date field you must specify the date format. If the field is not a date field, an exception is thrown. public let dateFieldFormat: String? /// The name of the index field to map to the Confluence data source field. The index field type must match the Confluence field type. public let indexFieldName: String? public init(dataSourceFieldName: ConfluenceAttachmentFieldName? = nil, dateFieldFormat: String? = nil, indexFieldName: String? = nil) { self.dataSourceFieldName = dataSourceFieldName self.dateFieldFormat = dateFieldFormat self.indexFieldName = indexFieldName } public func validate(name: String) throws { try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, max: 40) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, min: 4) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, pattern: "^(?!\\s).*(?<!\\s)$") try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, max: 30) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, min: 1) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceFieldName = "DataSourceFieldName" case dateFieldFormat = "DateFieldFormat" case indexFieldName = "IndexFieldName" } } public struct ConfluenceBlogConfiguration: AWSEncodableShape & AWSDecodableShape { /// Defines how blog metadata fields should be mapped to index fields. Before you can map a field, you must first create an index field with a matching type using the console or the UpdateIndex operation. If you specify the BlogFieldMappings parameter, you must specify at least one field mapping. public let blogFieldMappings: [ConfluenceBlogToIndexFieldMapping]? public init(blogFieldMappings: [ConfluenceBlogToIndexFieldMapping]? = nil) { self.blogFieldMappings = blogFieldMappings } public func validate(name: String) throws { try self.blogFieldMappings?.forEach { try $0.validate(name: "\(name).blogFieldMappings[]") } try self.validate(self.blogFieldMappings, name: "blogFieldMappings", parent: name, max: 9) try self.validate(self.blogFieldMappings, name: "blogFieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case blogFieldMappings = "BlogFieldMappings" } } public struct ConfluenceBlogToIndexFieldMapping: AWSEncodableShape & AWSDecodableShape { /// The name of the field in the data source. public let dataSourceFieldName: ConfluenceBlogFieldName? /// The format for date fields in the data source. If the field specified in DataSourceFieldName is a date field you must specify the date format. If the field is not a date field, an exception is thrown. public let dateFieldFormat: String? /// The name of the index field to map to the Confluence data source field. The index field type must match the Confluence field type. public let indexFieldName: String? public init(dataSourceFieldName: ConfluenceBlogFieldName? = nil, dateFieldFormat: String? = nil, indexFieldName: String? = nil) { self.dataSourceFieldName = dataSourceFieldName self.dateFieldFormat = dateFieldFormat self.indexFieldName = indexFieldName } public func validate(name: String) throws { try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, max: 40) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, min: 4) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, pattern: "^(?!\\s).*(?<!\\s)$") try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, max: 30) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, min: 1) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceFieldName = "DataSourceFieldName" case dateFieldFormat = "DateFieldFormat" case indexFieldName = "IndexFieldName" } } public struct ConfluenceConfiguration: AWSEncodableShape & AWSDecodableShape { /// Specifies configuration information for indexing attachments to Confluence blogs and pages. public let attachmentConfiguration: ConfluenceAttachmentConfiguration? /// Specifies configuration information for indexing Confluence blogs. public let blogConfiguration: ConfluenceBlogConfiguration? /// A list of regular expression patterns that apply to a URL on the Confluence server. An exclusion pattern can apply to a blog post, a page, a space, or an attachment. Items that match the pattern are excluded from the index. Items that don't match the pattern are included in the index. If a item matches both an exclusion pattern and an inclusion pattern, the item isn't included in the index. public let exclusionPatterns: [String]? /// A list of regular expression patterns that apply to a URL on the Confluence server. An inclusion pattern can apply to a blog post, a page, a space, or an attachment. Items that match the patterns are included in the index. Items that don't match the pattern are excluded from the index. If an item matches both an inclusion pattern and an exclusion pattern, the item isn't included in the index. public let inclusionPatterns: [String]? /// Specifies configuration information for indexing Confluence pages. public let pageConfiguration: ConfluencePageConfiguration? /// The Amazon Resource Name (ARN) of an Secrets Managersecret that contains the key/value pairs required to connect to your Confluence server. The secret must contain a JSON structure with the following keys: username - The user name or email address of a user with administrative privileges for the Confluence server. password - The password associated with the user logging in to the Confluence server. public let secretArn: String /// The URL of your Confluence instance. Use the full URL of the server. For example, https://server.example.com:port/. You can also use an IP address, for example, https://192.168.1.113/. public let serverUrl: String /// Specifies configuration information for indexing Confluence spaces. public let spaceConfiguration: ConfluenceSpaceConfiguration? /// Specifies the version of the Confluence installation that you are connecting to. public let version: ConfluenceVersion /// Specifies the information for connecting to an Amazon VPC. public let vpcConfiguration: DataSourceVpcConfiguration? public init(attachmentConfiguration: ConfluenceAttachmentConfiguration? = nil, blogConfiguration: ConfluenceBlogConfiguration? = nil, exclusionPatterns: [String]? = nil, inclusionPatterns: [String]? = nil, pageConfiguration: ConfluencePageConfiguration? = nil, secretArn: String, serverUrl: String, spaceConfiguration: ConfluenceSpaceConfiguration? = nil, version: ConfluenceVersion, vpcConfiguration: DataSourceVpcConfiguration? = nil) { self.attachmentConfiguration = attachmentConfiguration self.blogConfiguration = blogConfiguration self.exclusionPatterns = exclusionPatterns self.inclusionPatterns = inclusionPatterns self.pageConfiguration = pageConfiguration self.secretArn = secretArn self.serverUrl = serverUrl self.spaceConfiguration = spaceConfiguration self.version = version self.vpcConfiguration = vpcConfiguration } public func validate(name: String) throws { try self.attachmentConfiguration?.validate(name: "\(name).attachmentConfiguration") try self.blogConfiguration?.validate(name: "\(name).blogConfiguration") try self.exclusionPatterns?.forEach { try validate($0, name: "exclusionPatterns[]", parent: name, max: 150) try validate($0, name: "exclusionPatterns[]", parent: name, min: 1) } try self.validate(self.exclusionPatterns, name: "exclusionPatterns", parent: name, max: 100) try self.inclusionPatterns?.forEach { try validate($0, name: "inclusionPatterns[]", parent: name, max: 150) try validate($0, name: "inclusionPatterns[]", parent: name, min: 1) } try self.validate(self.inclusionPatterns, name: "inclusionPatterns", parent: name, max: 100) try self.pageConfiguration?.validate(name: "\(name).pageConfiguration") try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.serverUrl, name: "serverUrl", parent: name, max: 2048) try self.validate(self.serverUrl, name: "serverUrl", parent: name, min: 1) try self.validate(self.serverUrl, name: "serverUrl", parent: name, pattern: "^(https?|ftp|file):\\/\\/([^\\s]*)$") try self.spaceConfiguration?.validate(name: "\(name).spaceConfiguration") try self.vpcConfiguration?.validate(name: "\(name).vpcConfiguration") } private enum CodingKeys: String, CodingKey { case attachmentConfiguration = "AttachmentConfiguration" case blogConfiguration = "BlogConfiguration" case exclusionPatterns = "ExclusionPatterns" case inclusionPatterns = "InclusionPatterns" case pageConfiguration = "PageConfiguration" case secretArn = "SecretArn" case serverUrl = "ServerUrl" case spaceConfiguration = "SpaceConfiguration" case version = "Version" case vpcConfiguration = "VpcConfiguration" } } public struct ConfluencePageConfiguration: AWSEncodableShape & AWSDecodableShape { /// Defines how page metadata fields should be mapped to index fields. Before you can map a field, you must first create an index field with a matching type using the console or the UpdateIndex operation. If you specify the PageFieldMappings parameter, you must specify at least one field mapping. public let pageFieldMappings: [ConfluencePageToIndexFieldMapping]? public init(pageFieldMappings: [ConfluencePageToIndexFieldMapping]? = nil) { self.pageFieldMappings = pageFieldMappings } public func validate(name: String) throws { try self.pageFieldMappings?.forEach { try $0.validate(name: "\(name).pageFieldMappings[]") } try self.validate(self.pageFieldMappings, name: "pageFieldMappings", parent: name, max: 12) try self.validate(self.pageFieldMappings, name: "pageFieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case pageFieldMappings = "PageFieldMappings" } } public struct ConfluencePageToIndexFieldMapping: AWSEncodableShape & AWSDecodableShape { /// The name of the field in the data source. public let dataSourceFieldName: ConfluencePageFieldName? /// The format for date fields in the data source. If the field specified in DataSourceFieldName is a date field you must specify the date format. If the field is not a date field, an exception is thrown. public let dateFieldFormat: String? /// The name of the index field to map to the Confluence data source field. The index field type must match the Confluence field type. public let indexFieldName: String? public init(dataSourceFieldName: ConfluencePageFieldName? = nil, dateFieldFormat: String? = nil, indexFieldName: String? = nil) { self.dataSourceFieldName = dataSourceFieldName self.dateFieldFormat = dateFieldFormat self.indexFieldName = indexFieldName } public func validate(name: String) throws { try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, max: 40) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, min: 4) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, pattern: "^(?!\\s).*(?<!\\s)$") try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, max: 30) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, min: 1) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceFieldName = "DataSourceFieldName" case dateFieldFormat = "DateFieldFormat" case indexFieldName = "IndexFieldName" } } public struct ConfluenceSpaceConfiguration: AWSEncodableShape & AWSDecodableShape { /// Specifies whether Amazon Kendra should index archived spaces. public let crawlArchivedSpaces: Bool? /// Specifies whether Amazon Kendra should index personal spaces. Users can add restrictions to items in personal spaces. If personal spaces are indexed, queries without user context information may return restricted items from a personal space in their results. For more information, see Filtering on user context. public let crawlPersonalSpaces: Bool? /// A list of space keys of Confluence spaces. If you include a key, the blogs, documents, and attachments in the space are not indexed. If a space is in both the ExcludeSpaces and the IncludeSpaces list, the space is excluded. public let excludeSpaces: [String]? /// A list of space keys for Confluence spaces. If you include a key, the blogs, documents, and attachments in the space are indexed. Spaces that aren't in the list aren't indexed. A space in the list must exist. Otherwise, Amazon Kendra logs an error when the data source is synchronized. If a space is in both the IncludeSpaces and the ExcludeSpaces list, the space is excluded. public let includeSpaces: [String]? /// Defines how space metadata fields should be mapped to index fields. Before you can map a field, you must first create an index field with a matching type using the console or the UpdateIndex operation. If you specify the SpaceFieldMappings parameter, you must specify at least one field mapping. public let spaceFieldMappings: [ConfluenceSpaceToIndexFieldMapping]? public init(crawlArchivedSpaces: Bool? = nil, crawlPersonalSpaces: Bool? = nil, excludeSpaces: [String]? = nil, includeSpaces: [String]? = nil, spaceFieldMappings: [ConfluenceSpaceToIndexFieldMapping]? = nil) { self.crawlArchivedSpaces = crawlArchivedSpaces self.crawlPersonalSpaces = crawlPersonalSpaces self.excludeSpaces = excludeSpaces self.includeSpaces = includeSpaces self.spaceFieldMappings = spaceFieldMappings } public func validate(name: String) throws { try self.excludeSpaces?.forEach { try validate($0, name: "excludeSpaces[]", parent: name, max: 255) try validate($0, name: "excludeSpaces[]", parent: name, min: 1) try validate($0, name: "excludeSpaces[]", parent: name, pattern: "^\\P{C}*$") } try self.validate(self.excludeSpaces, name: "excludeSpaces", parent: name, min: 1) try self.includeSpaces?.forEach { try validate($0, name: "includeSpaces[]", parent: name, max: 255) try validate($0, name: "includeSpaces[]", parent: name, min: 1) try validate($0, name: "includeSpaces[]", parent: name, pattern: "^\\P{C}*$") } try self.validate(self.includeSpaces, name: "includeSpaces", parent: name, min: 1) try self.spaceFieldMappings?.forEach { try $0.validate(name: "\(name).spaceFieldMappings[]") } try self.validate(self.spaceFieldMappings, name: "spaceFieldMappings", parent: name, max: 4) try self.validate(self.spaceFieldMappings, name: "spaceFieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case crawlArchivedSpaces = "CrawlArchivedSpaces" case crawlPersonalSpaces = "CrawlPersonalSpaces" case excludeSpaces = "ExcludeSpaces" case includeSpaces = "IncludeSpaces" case spaceFieldMappings = "SpaceFieldMappings" } } public struct ConfluenceSpaceToIndexFieldMapping: AWSEncodableShape & AWSDecodableShape { /// The name of the field in the data source. public let dataSourceFieldName: ConfluenceSpaceFieldName? /// The format for date fields in the data source. If the field specified in DataSourceFieldName is a date field you must specify the date format. If the field is not a date field, an exception is thrown. public let dateFieldFormat: String? /// The name of the index field to map to the Confluence data source field. The index field type must match the Confluence field type. public let indexFieldName: String? public init(dataSourceFieldName: ConfluenceSpaceFieldName? = nil, dateFieldFormat: String? = nil, indexFieldName: String? = nil) { self.dataSourceFieldName = dataSourceFieldName self.dateFieldFormat = dateFieldFormat self.indexFieldName = indexFieldName } public func validate(name: String) throws { try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, max: 40) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, min: 4) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, pattern: "^(?!\\s).*(?<!\\s)$") try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, max: 30) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, min: 1) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceFieldName = "DataSourceFieldName" case dateFieldFormat = "DateFieldFormat" case indexFieldName = "IndexFieldName" } } public struct ConnectionConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the host for the database. Can be either a string (host.subdomain.domain.tld) or an IPv4 or IPv6 address. public let databaseHost: String /// The name of the database containing the document data. public let databaseName: String /// The port that the database uses for connections. public let databasePort: Int /// The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The credentials should be a user/password pair. For more information, see Using a Database Data Source. For more information about Secrets Manager, see What Is Secrets Manager in the Secrets Manager user guide. public let secretArn: String /// The name of the table that contains the document data. public let tableName: String public init(databaseHost: String, databaseName: String, databasePort: Int, secretArn: String, tableName: String) { self.databaseHost = databaseHost self.databaseName = databaseName self.databasePort = databasePort self.secretArn = secretArn self.tableName = tableName } public func validate(name: String) throws { try self.validate(self.databaseHost, name: "databaseHost", parent: name, max: 253) try self.validate(self.databaseHost, name: "databaseHost", parent: name, min: 1) try self.validate(self.databaseName, name: "databaseName", parent: name, max: 100) try self.validate(self.databaseName, name: "databaseName", parent: name, min: 1) try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") try self.validate(self.databasePort, name: "databasePort", parent: name, max: 65535) try self.validate(self.databasePort, name: "databasePort", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.tableName, name: "tableName", parent: name, max: 100) try self.validate(self.tableName, name: "tableName", parent: name, min: 1) try self.validate(self.tableName, name: "tableName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: String, CodingKey { case databaseHost = "DatabaseHost" case databaseName = "DatabaseName" case databasePort = "DatabasePort" case secretArn = "SecretArn" case tableName = "TableName" } } public struct CreateDataSourceRequest: AWSEncodableShape { /// A token that you provide to identify the request to create a data source. Multiple calls to the CreateDataSource operation with the same client token will create only one data source. public let clientToken: String? /// The connector configuration information that is required to access the repository. You can't specify the Configuration parameter when the Type parameter is set to CUSTOM. If you do, you receive a ValidationException exception. The Configuration parameter is required for all other data sources. public let configuration: DataSourceConfiguration? /// A description for the data source. public let description: String? /// The identifier of the index that should be associated with this data source. public let indexId: String /// The code for a language. This allows you to support a language for all documents when creating the data source. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// A unique name for the data source. A data source name can't be changed without deleting and recreating the data source. public let name: String /// The Amazon Resource Name (ARN) of a role with permission to access the data source. For more information, see IAM Roles for Amazon Kendra. You can't specify the RoleArn parameter when the Type parameter is set to CUSTOM. If you do, you receive a ValidationException exception. The RoleArn parameter is required for all other data sources. public let roleArn: String? /// Sets the frequency that Amazon Kendra will check the documents in your repository and update the index. If you don't set a schedule Amazon Kendra will not periodically update the index. You can call the StartDataSourceSyncJob operation to update the index. You can't specify the Schedule parameter when the Type parameter is set to CUSTOM. If you do, you receive a ValidationException exception. public let schedule: String? /// A list of key-value pairs that identify the data source. You can use the tags to identify and organize your resources and to control access to resources. public let tags: [Tag]? /// The type of repository that contains the data source. public let type: DataSourceType public init(clientToken: String? = CreateDataSourceRequest.idempotencyToken(), configuration: DataSourceConfiguration? = nil, description: String? = nil, indexId: String, languageCode: String? = nil, name: String, roleArn: String? = nil, schedule: String? = nil, tags: [Tag]? = nil, type: DataSourceType) { self.clientToken = clientToken self.configuration = configuration self.description = description self.indexId = indexId self.languageCode = languageCode self.name = name self.roleArn = roleArn self.schedule = schedule self.tags = tags self.type = type } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 100) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.configuration?.validate(name: "\(name).configuration") try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.languageCode, name: "languageCode", parent: name, max: 10) try self.validate(self.languageCode, name: "languageCode", parent: name, min: 2) try self.validate(self.languageCode, name: "languageCode", parent: name, pattern: "^[a-zA-Z-]*$") try self.validate(self.name, name: "name", parent: name, max: 1000) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case configuration = "Configuration" case description = "Description" case indexId = "IndexId" case languageCode = "LanguageCode" case name = "Name" case roleArn = "RoleArn" case schedule = "Schedule" case tags = "Tags" case type = "Type" } } public struct CreateDataSourceResponse: AWSDecodableShape { /// A unique identifier for the data source. public let id: String public init(id: String) { self.id = id } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct CreateFaqRequest: AWSEncodableShape { /// A token that you provide to identify the request to create a FAQ. Multiple calls to the CreateFaqRequest operation with the same client token will create only one FAQ. public let clientToken: String? /// A description of the FAQ. public let description: String? /// The format of the input file. You can choose between a basic CSV format, a CSV format that includes customs attributes in a header, and a JSON format that includes custom attributes. The format must match the format of the file stored in the S3 bucket identified in the S3Path parameter. For more information, see Adding questions and answers. public let fileFormat: FaqFileFormat? /// The identifier of the index that contains the FAQ. public let indexId: String /// The code for a language. This allows you to support a language for the FAQ document. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// The name that should be associated with the FAQ. public let name: String /// The Amazon Resource Name (ARN) of a role with permission to access the S3 bucket that contains the FAQs. For more information, see IAM Roles for Amazon Kendra. public let roleArn: String /// The S3 location of the FAQ input data. public let s3Path: S3Path /// A list of key-value pairs that identify the FAQ. You can use the tags to identify and organize your resources and to control access to resources. public let tags: [Tag]? public init(clientToken: String? = CreateFaqRequest.idempotencyToken(), description: String? = nil, fileFormat: FaqFileFormat? = nil, indexId: String, languageCode: String? = nil, name: String, roleArn: String, s3Path: S3Path, tags: [Tag]? = nil) { self.clientToken = clientToken self.description = description self.fileFormat = fileFormat self.indexId = indexId self.languageCode = languageCode self.name = name self.roleArn = roleArn self.s3Path = s3Path self.tags = tags } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 100) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.languageCode, name: "languageCode", parent: name, max: 10) try self.validate(self.languageCode, name: "languageCode", parent: name, min: 2) try self.validate(self.languageCode, name: "languageCode", parent: name, pattern: "^[a-zA-Z-]*$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.s3Path.validate(name: "\(name).s3Path") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case description = "Description" case fileFormat = "FileFormat" case indexId = "IndexId" case languageCode = "LanguageCode" case name = "Name" case roleArn = "RoleArn" case s3Path = "S3Path" case tags = "Tags" } } public struct CreateFaqResponse: AWSDecodableShape { /// The unique identifier of the FAQ. public let id: String? public init(id: String? = nil) { self.id = id } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct CreateIndexRequest: AWSEncodableShape { /// A token that you provide to identify the request to create an index. Multiple calls to the CreateIndex operation with the same client token will create only one index. public let clientToken: String? /// A description for the index. public let description: String? /// The Amazon Kendra edition to use for the index. Choose DEVELOPER_EDITION for indexes intended for development, testing, or proof of concept. Use ENTERPRISE_EDITION for your production databases. Once you set the edition for an index, it can't be changed. The Edition parameter is optional. If you don't supply a value, the default is ENTERPRISE_EDITION. For more information on quota limits for enterprise and developer editions, see Quotas. public let edition: IndexEdition? /// The name for the new index. public let name: String /// An Identity and Access Management(IAM) role that gives Amazon Kendra permissions to access your Amazon CloudWatch logs and metrics. This is also the role used when you use the BatchPutDocument operation to index documents from an Amazon S3 bucket. public let roleArn: String /// The identifier of the KMScustomer managed key (CMK) to use to encrypt data indexed by Amazon Kendra. Amazon Kendra doesn't support asymmetric CMKs. public let serverSideEncryptionConfiguration: ServerSideEncryptionConfiguration? /// A list of key-value pairs that identify the index. You can use the tags to identify and organize your resources and to control access to resources. public let tags: [Tag]? /// The user context policy. ATTRIBUTE_FILTER All indexed content is searchable and displayable for all users. If you want to filter search results on user context, you can use the attribute filters of _user_id and _group_ids or you can provide user and group information in UserContext. USER_TOKEN Enables token-based user access control to filter search results on user context. All documents with no access control and all documents accessible to the user will be searchable and displayable. public let userContextPolicy: UserContextPolicy? /// Enables fetching access levels of groups and users from an AWS Single Sign-On identity source. To configure this, see UserGroupResolutionConfiguration. public let userGroupResolutionConfiguration: UserGroupResolutionConfiguration? /// The user token configuration. public let userTokenConfigurations: [UserTokenConfiguration]? public init(clientToken: String? = CreateIndexRequest.idempotencyToken(), description: String? = nil, edition: IndexEdition? = nil, name: String, roleArn: String, serverSideEncryptionConfiguration: ServerSideEncryptionConfiguration? = nil, tags: [Tag]? = nil, userContextPolicy: UserContextPolicy? = nil, userGroupResolutionConfiguration: UserGroupResolutionConfiguration? = nil, userTokenConfigurations: [UserTokenConfiguration]? = nil) { self.clientToken = clientToken self.description = description self.edition = edition self.name = name self.roleArn = roleArn self.serverSideEncryptionConfiguration = serverSideEncryptionConfiguration self.tags = tags self.userContextPolicy = userContextPolicy self.userGroupResolutionConfiguration = userGroupResolutionConfiguration self.userTokenConfigurations = userTokenConfigurations } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 100) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.name, name: "name", parent: name, max: 1000) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.serverSideEncryptionConfiguration?.validate(name: "\(name).serverSideEncryptionConfiguration") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.userTokenConfigurations?.forEach { try $0.validate(name: "\(name).userTokenConfigurations[]") } try self.validate(self.userTokenConfigurations, name: "userTokenConfigurations", parent: name, max: 1) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case description = "Description" case edition = "Edition" case name = "Name" case roleArn = "RoleArn" case serverSideEncryptionConfiguration = "ServerSideEncryptionConfiguration" case tags = "Tags" case userContextPolicy = "UserContextPolicy" case userGroupResolutionConfiguration = "UserGroupResolutionConfiguration" case userTokenConfigurations = "UserTokenConfigurations" } } public struct CreateIndexResponse: AWSDecodableShape { /// The unique identifier of the index. Use this identifier when you query an index, set up a data source, or index a document. public let id: String? public init(id: String? = nil) { self.id = id } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct CreateQuerySuggestionsBlockListRequest: AWSEncodableShape { /// A token that you provide to identify the request to create a query suggestions block list. public let clientToken: String? /// A user-friendly description for the block list. For example, the description "List of all offensive words that can appear in user queries and need to be blocked from suggestions." public let description: String? /// The identifier of the index you want to create a query suggestions block list for. public let indexId: String /// A user friendly name for the block list. For example, the block list named 'offensive-words' includes all offensive words that could appear in user queries and need to be blocked from suggestions. public let name: String /// The IAM (Identity and Access Management) role used by Amazon Kendra to access the block list text file in your S3 bucket. You need permissions to the role ARN (Amazon Resource Name). The role needs S3 read permissions to your file in S3 and needs to give STS (Security Token Service) assume role permissions to Amazon Kendra. public let roleArn: String /// The S3 path to your block list text file in your S3 bucket. Each block word or phrase should be on a separate line in a text file. For information on the current quota limits for block lists, see Quotas for Amazon Kendra. public let sourceS3Path: S3Path /// A tag that you can assign to a block list that categorizes the block list. public let tags: [Tag]? public init(clientToken: String? = CreateQuerySuggestionsBlockListRequest.idempotencyToken(), description: String? = nil, indexId: String, name: String, roleArn: String, sourceS3Path: S3Path, tags: [Tag]? = nil) { self.clientToken = clientToken self.description = description self.indexId = indexId self.name = name self.roleArn = roleArn self.sourceS3Path = sourceS3Path self.tags = tags } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 100) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9](-*[a-zA-Z0-9])*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.sourceS3Path.validate(name: "\(name).sourceS3Path") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case description = "Description" case indexId = "IndexId" case name = "Name" case roleArn = "RoleArn" case sourceS3Path = "SourceS3Path" case tags = "Tags" } } public struct CreateQuerySuggestionsBlockListResponse: AWSDecodableShape { /// The unique identifier of the created block list. public let id: String? public init(id: String? = nil) { self.id = id } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct CreateThesaurusRequest: AWSEncodableShape { /// A token that you provide to identify the request to create a thesaurus. Multiple calls to the CreateThesaurus operation with the same client token will create only one thesaurus. public let clientToken: String? /// The description for the new thesaurus. public let description: String? /// The unique identifier of the index for the new thesaurus. public let indexId: String /// The name for the new thesaurus. public let name: String /// An AWS Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access thesaurus file specified in SourceS3Path. public let roleArn: String /// The thesaurus file Amazon S3 source path. public let sourceS3Path: S3Path /// A list of key-value pairs that identify the thesaurus. You can use the tags to identify and organize your resources and to control access to resources. public let tags: [Tag]? public init(clientToken: String? = CreateThesaurusRequest.idempotencyToken(), description: String? = nil, indexId: String, name: String, roleArn: String, sourceS3Path: S3Path, tags: [Tag]? = nil) { self.clientToken = clientToken self.description = description self.indexId = indexId self.name = name self.roleArn = roleArn self.sourceS3Path = sourceS3Path self.tags = tags } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 100) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.sourceS3Path.validate(name: "\(name).sourceS3Path") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case description = "Description" case indexId = "IndexId" case name = "Name" case roleArn = "RoleArn" case sourceS3Path = "SourceS3Path" case tags = "Tags" } } public struct CreateThesaurusResponse: AWSDecodableShape { /// The unique identifier of the thesaurus. public let id: String? public init(id: String? = nil) { self.id = id } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct DataSourceConfiguration: AWSEncodableShape & AWSDecodableShape { /// Provides configuration information for connecting to a Confluence data source. public let confluenceConfiguration: ConfluenceConfiguration? /// Provides information necessary to create a data source connector for a database. public let databaseConfiguration: DatabaseConfiguration? /// Provides configuration for data sources that connect to Google Drive. public let googleDriveConfiguration: GoogleDriveConfiguration? /// Provides configuration for data sources that connect to Microsoft OneDrive. public let oneDriveConfiguration: OneDriveConfiguration? /// Provides information to create a data source connector for a document repository in an Amazon S3 bucket. public let s3Configuration: S3DataSourceConfiguration? /// Provides configuration information for data sources that connect to a Salesforce site. public let salesforceConfiguration: SalesforceConfiguration? /// Provides configuration for data sources that connect to ServiceNow instances. public let serviceNowConfiguration: ServiceNowConfiguration? /// Provides information necessary to create a data source connector for a Microsoft SharePoint site. public let sharePointConfiguration: SharePointConfiguration? public let webCrawlerConfiguration: WebCrawlerConfiguration? /// Provides the configuration information to connect to WorkDocs as your data source. public let workDocsConfiguration: WorkDocsConfiguration? public init(confluenceConfiguration: ConfluenceConfiguration? = nil, databaseConfiguration: DatabaseConfiguration? = nil, googleDriveConfiguration: GoogleDriveConfiguration? = nil, oneDriveConfiguration: OneDriveConfiguration? = nil, s3Configuration: S3DataSourceConfiguration? = nil, salesforceConfiguration: SalesforceConfiguration? = nil, serviceNowConfiguration: ServiceNowConfiguration? = nil, sharePointConfiguration: SharePointConfiguration? = nil, webCrawlerConfiguration: WebCrawlerConfiguration? = nil, workDocsConfiguration: WorkDocsConfiguration? = nil) { self.confluenceConfiguration = confluenceConfiguration self.databaseConfiguration = databaseConfiguration self.googleDriveConfiguration = googleDriveConfiguration self.oneDriveConfiguration = oneDriveConfiguration self.s3Configuration = s3Configuration self.salesforceConfiguration = salesforceConfiguration self.serviceNowConfiguration = serviceNowConfiguration self.sharePointConfiguration = sharePointConfiguration self.webCrawlerConfiguration = webCrawlerConfiguration self.workDocsConfiguration = workDocsConfiguration } public func validate(name: String) throws { try self.confluenceConfiguration?.validate(name: "\(name).confluenceConfiguration") try self.databaseConfiguration?.validate(name: "\(name).databaseConfiguration") try self.googleDriveConfiguration?.validate(name: "\(name).googleDriveConfiguration") try self.oneDriveConfiguration?.validate(name: "\(name).oneDriveConfiguration") try self.s3Configuration?.validate(name: "\(name).s3Configuration") try self.salesforceConfiguration?.validate(name: "\(name).salesforceConfiguration") try self.serviceNowConfiguration?.validate(name: "\(name).serviceNowConfiguration") try self.sharePointConfiguration?.validate(name: "\(name).sharePointConfiguration") try self.webCrawlerConfiguration?.validate(name: "\(name).webCrawlerConfiguration") try self.workDocsConfiguration?.validate(name: "\(name).workDocsConfiguration") } private enum CodingKeys: String, CodingKey { case confluenceConfiguration = "ConfluenceConfiguration" case databaseConfiguration = "DatabaseConfiguration" case googleDriveConfiguration = "GoogleDriveConfiguration" case oneDriveConfiguration = "OneDriveConfiguration" case s3Configuration = "S3Configuration" case salesforceConfiguration = "SalesforceConfiguration" case serviceNowConfiguration = "ServiceNowConfiguration" case sharePointConfiguration = "SharePointConfiguration" case webCrawlerConfiguration = "WebCrawlerConfiguration" case workDocsConfiguration = "WorkDocsConfiguration" } } public struct DataSourceGroup: AWSEncodableShape { /// The identifier of the data source group you want to add to your list of data source groups. This is for filtering search results based on the groups' access to documents in that data source. public let dataSourceId: String /// The identifier of the group you want to add to your list of groups. This is for filtering search results based on the groups' access to documents. public let groupId: String public init(dataSourceId: String, groupId: String) { self.dataSourceId = dataSourceId self.groupId = groupId } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.groupId, name: "groupId", parent: name, max: 200) try self.validate(self.groupId, name: "groupId", parent: name, min: 1) try self.validate(self.groupId, name: "groupId", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case groupId = "GroupId" } } public struct DataSourceSummary: AWSDecodableShape { /// The UNIX datetime that the data source was created. public let createdAt: Date? /// The unique identifier for the data source. public let id: String? /// The code for a language. This shows a supported language for all documents in the data source. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// The name of the data source. public let name: String? /// The status of the data source. When the status is ACTIVE the data source is ready to use. public let status: DataSourceStatus? /// The type of the data source. public let type: DataSourceType? /// The UNIX datetime that the data source was lasted updated. public let updatedAt: Date? public init(createdAt: Date? = nil, id: String? = nil, languageCode: String? = nil, name: String? = nil, status: DataSourceStatus? = nil, type: DataSourceType? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.id = id self.languageCode = languageCode self.name = name self.status = status self.type = type self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case id = "Id" case languageCode = "LanguageCode" case name = "Name" case status = "Status" case type = "Type" case updatedAt = "UpdatedAt" } } public struct DataSourceSyncJob: AWSDecodableShape { /// If the reason that the synchronization failed is due to an error with the underlying data source, this field contains a code that identifies the error. public let dataSourceErrorCode: String? /// The UNIX datetime that the synchronization job was completed. public let endTime: Date? /// If the Status field is set to FAILED, the ErrorCode field contains a the reason that the synchronization failed. public let errorCode: ErrorCode? /// If the Status field is set to ERROR, the ErrorMessage field contains a description of the error that caused the synchronization to fail. public let errorMessage: String? /// A unique identifier for the synchronization job. public let executionId: String? /// Maps a batch delete document request to a specific data source sync job. This is optional and should only be supplied when documents are deleted by a data source connector. public let metrics: DataSourceSyncJobMetrics? /// The UNIX datetime that the synchronization job was started. public let startTime: Date? /// The execution status of the synchronization job. When the Status field is set to SUCCEEDED, the synchronization job is done. If the status code is set to FAILED, the ErrorCode and ErrorMessage fields give you the reason for the failure. public let status: DataSourceSyncJobStatus? public init(dataSourceErrorCode: String? = nil, endTime: Date? = nil, errorCode: ErrorCode? = nil, errorMessage: String? = nil, executionId: String? = nil, metrics: DataSourceSyncJobMetrics? = nil, startTime: Date? = nil, status: DataSourceSyncJobStatus? = nil) { self.dataSourceErrorCode = dataSourceErrorCode self.endTime = endTime self.errorCode = errorCode self.errorMessage = errorMessage self.executionId = executionId self.metrics = metrics self.startTime = startTime self.status = status } private enum CodingKeys: String, CodingKey { case dataSourceErrorCode = "DataSourceErrorCode" case endTime = "EndTime" case errorCode = "ErrorCode" case errorMessage = "ErrorMessage" case executionId = "ExecutionId" case metrics = "Metrics" case startTime = "StartTime" case status = "Status" } } public struct DataSourceSyncJobMetricTarget: AWSEncodableShape { /// The ID of the data source that is running the sync job. public let dataSourceId: String /// The ID of the sync job that is running on the data source. If the ID of a sync job is not provided and there is a sync job running, then the ID of this sync job is used and metrics are generated for this sync job. If the ID of a sync job is not provided and there is no sync job running, then no metrics are generated and documents are indexed/deleted at the index level without sync job metrics included. public let dataSourceSyncJobId: String? public init(dataSourceId: String, dataSourceSyncJobId: String? = nil) { self.dataSourceId = dataSourceId self.dataSourceSyncJobId = dataSourceSyncJobId } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.dataSourceSyncJobId, name: "dataSourceSyncJobId", parent: name, max: 100) try self.validate(self.dataSourceSyncJobId, name: "dataSourceSyncJobId", parent: name, min: 1) try self.validate(self.dataSourceSyncJobId, name: "dataSourceSyncJobId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case dataSourceSyncJobId = "DataSourceSyncJobId" } } public struct DataSourceSyncJobMetrics: AWSDecodableShape { /// The number of documents added from the data source up to now in the data source sync. public let documentsAdded: String? /// The number of documents deleted from the data source up to now in the data source sync run. public let documentsDeleted: String? /// The number of documents that failed to sync from the data source up to now in the data source sync run. public let documentsFailed: String? /// The number of documents modified in the data source up to now in the data source sync run. public let documentsModified: String? /// The current number of documents crawled by the current sync job in the data source. public let documentsScanned: String? public init(documentsAdded: String? = nil, documentsDeleted: String? = nil, documentsFailed: String? = nil, documentsModified: String? = nil, documentsScanned: String? = nil) { self.documentsAdded = documentsAdded self.documentsDeleted = documentsDeleted self.documentsFailed = documentsFailed self.documentsModified = documentsModified self.documentsScanned = documentsScanned } private enum CodingKeys: String, CodingKey { case documentsAdded = "DocumentsAdded" case documentsDeleted = "DocumentsDeleted" case documentsFailed = "DocumentsFailed" case documentsModified = "DocumentsModified" case documentsScanned = "DocumentsScanned" } } public struct DataSourceToIndexFieldMapping: AWSEncodableShape & AWSDecodableShape { /// The name of the column or attribute in the data source. public let dataSourceFieldName: String /// The type of data stored in the column or attribute. public let dateFieldFormat: String? /// The name of the field in the index. public let indexFieldName: String public init(dataSourceFieldName: String, dateFieldFormat: String? = nil, indexFieldName: String) { self.dataSourceFieldName = dataSourceFieldName self.dateFieldFormat = dateFieldFormat self.indexFieldName = indexFieldName } public func validate(name: String) throws { try self.validate(self.dataSourceFieldName, name: "dataSourceFieldName", parent: name, max: 100) try self.validate(self.dataSourceFieldName, name: "dataSourceFieldName", parent: name, min: 1) try self.validate(self.dataSourceFieldName, name: "dataSourceFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, max: 40) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, min: 4) try self.validate(self.dateFieldFormat, name: "dateFieldFormat", parent: name, pattern: "^(?!\\s).*(?<!\\s)$") try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, max: 30) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, min: 1) try self.validate(self.indexFieldName, name: "indexFieldName", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceFieldName = "DataSourceFieldName" case dateFieldFormat = "DateFieldFormat" case indexFieldName = "IndexFieldName" } } public struct DataSourceVpcConfiguration: AWSEncodableShape & AWSDecodableShape { /// A list of identifiers of security groups within your Amazon VPC. The security groups should enable Amazon Kendra to connect to the data source. public let securityGroupIds: [String] /// A list of identifiers for subnets within your Amazon VPC. The subnets should be able to connect to each other in the VPC, and they should have outgoing access to the Internet through a NAT device. public let subnetIds: [String] public init(securityGroupIds: [String], subnetIds: [String]) { self.securityGroupIds = securityGroupIds self.subnetIds = subnetIds } public func validate(name: String) throws { try self.securityGroupIds.forEach { try validate($0, name: "securityGroupIds[]", parent: name, max: 200) try validate($0, name: "securityGroupIds[]", parent: name, min: 1) try validate($0, name: "securityGroupIds[]", parent: name, pattern: "^[-0-9a-zA-Z]+$") } try self.validate(self.securityGroupIds, name: "securityGroupIds", parent: name, max: 10) try self.validate(self.securityGroupIds, name: "securityGroupIds", parent: name, min: 1) try self.subnetIds.forEach { try validate($0, name: "subnetIds[]", parent: name, max: 200) try validate($0, name: "subnetIds[]", parent: name, min: 1) try validate($0, name: "subnetIds[]", parent: name, pattern: "^[\\-0-9a-zA-Z]+$") } try self.validate(self.subnetIds, name: "subnetIds", parent: name, max: 6) try self.validate(self.subnetIds, name: "subnetIds", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case securityGroupIds = "SecurityGroupIds" case subnetIds = "SubnetIds" } } public struct DatabaseConfiguration: AWSEncodableShape & AWSDecodableShape { /// Information about the database column that provides information for user context filtering. public let aclConfiguration: AclConfiguration? /// Information about where the index should get the document information from the database. public let columnConfiguration: ColumnConfiguration /// The information necessary to connect to a database. public let connectionConfiguration: ConnectionConfiguration /// The type of database engine that runs the database. public let databaseEngineType: DatabaseEngineType /// Provides information about how Amazon Kendra uses quote marks around SQL identifiers when querying a database data source. public let sqlConfiguration: SqlConfiguration? public let vpcConfiguration: DataSourceVpcConfiguration? public init(aclConfiguration: AclConfiguration? = nil, columnConfiguration: ColumnConfiguration, connectionConfiguration: ConnectionConfiguration, databaseEngineType: DatabaseEngineType, sqlConfiguration: SqlConfiguration? = nil, vpcConfiguration: DataSourceVpcConfiguration? = nil) { self.aclConfiguration = aclConfiguration self.columnConfiguration = columnConfiguration self.connectionConfiguration = connectionConfiguration self.databaseEngineType = databaseEngineType self.sqlConfiguration = sqlConfiguration self.vpcConfiguration = vpcConfiguration } public func validate(name: String) throws { try self.aclConfiguration?.validate(name: "\(name).aclConfiguration") try self.columnConfiguration.validate(name: "\(name).columnConfiguration") try self.connectionConfiguration.validate(name: "\(name).connectionConfiguration") try self.vpcConfiguration?.validate(name: "\(name).vpcConfiguration") } private enum CodingKeys: String, CodingKey { case aclConfiguration = "AclConfiguration" case columnConfiguration = "ColumnConfiguration" case connectionConfiguration = "ConnectionConfiguration" case databaseEngineType = "DatabaseEngineType" case sqlConfiguration = "SqlConfiguration" case vpcConfiguration = "VpcConfiguration" } } public struct DeleteDataSourceRequest: AWSEncodableShape { /// The unique identifier of the data source to delete. public let id: String /// The unique identifier of the index associated with the data source. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DeleteFaqRequest: AWSEncodableShape { /// The identifier of the FAQ to remove. public let id: String /// The index to remove the FAQ from. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DeleteIndexRequest: AWSEncodableShape { /// The identifier of the index to delete. public let id: String public init(id: String) { self.id = id } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 36) try self.validate(self.id, name: "id", parent: name, min: 36) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct DeletePrincipalMappingRequest: AWSEncodableShape { /// The identifier of the data source you want to delete a group from. This is useful if a group is tied to multiple data sources and you want to delete a group from accessing documents in a certain data source. For example, the groups "Research", "Engineering", and "Sales and Marketing" are all tied to the company's documents stored in the data sources Confluence and Salesforce. You want to delete "Research" and "Engineering" groups from Salesforce, so that these groups cannot access customer-related documents stored in Salesforce. Only "Sales and Marketing" should access documents in the Salesforce data source. public let dataSourceId: String? /// The identifier of the group you want to delete. public let groupId: String /// The identifier of the index you want to delete a group from. public let indexId: String /// The timestamp identifier you specify to ensure Amazon Kendra does not override the latest DELETE action with previous actions. The highest number ID, which is the ordering ID, is the latest action you want to process and apply on top of other actions with lower number IDs. This prevents previous actions with lower number IDs from possibly overriding the latest action. The ordering ID can be the UNIX time of the last update you made to a group members list. You would then provide this list when calling PutPrincipalMapping. This ensures your DELETE action for that updated group with the latest members list doesn't get overwritten by earlier DELETE actions for the same group which are yet to be processed. The default ordering ID is the current UNIX time in milliseconds that the action was received by Amazon Kendra. public let orderingId: Int64? public init(dataSourceId: String? = nil, groupId: String, indexId: String, orderingId: Int64? = nil) { self.dataSourceId = dataSourceId self.groupId = groupId self.indexId = indexId self.orderingId = orderingId } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.groupId, name: "groupId", parent: name, max: 1024) try self.validate(self.groupId, name: "groupId", parent: name, min: 1) try self.validate(self.groupId, name: "groupId", parent: name, pattern: "^\\P{C}*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.orderingId, name: "orderingId", parent: name, max: 32_535_158_400_000) try self.validate(self.orderingId, name: "orderingId", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case groupId = "GroupId" case indexId = "IndexId" case orderingId = "OrderingId" } } public struct DeleteQuerySuggestionsBlockListRequest: AWSEncodableShape { /// The unique identifier of the block list that needs to be deleted. public let id: String /// The identifier of the you want to delete a block list from. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 36) try self.validate(self.id, name: "id", parent: name, min: 36) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DeleteThesaurusRequest: AWSEncodableShape { /// The identifier of the thesaurus to delete. public let id: String /// The identifier of the index associated with the thesaurus to delete. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DescribeDataSourceRequest: AWSEncodableShape { /// The unique identifier of the data source to describe. public let id: String /// The identifier of the index that contains the data source. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DescribeDataSourceResponse: AWSDecodableShape { /// Information that describes where the data source is located and how the data source is configured. The specific information in the description depends on the data source provider. public let configuration: DataSourceConfiguration? /// The Unix timestamp of when the data source was created. public let createdAt: Date? /// The description of the data source. public let description: String? /// When the Status field value is FAILED, the ErrorMessage field contains a description of the error that caused the data source to fail. public let errorMessage: String? /// The identifier of the data source. public let id: String? /// The identifier of the index that contains the data source. public let indexId: String? /// The code for a language. This shows a supported language for all documents in the data source. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// The name that you gave the data source when it was created. public let name: String? /// The Amazon Resource Name (ARN) of the role that enables the data source to access its resources. public let roleArn: String? /// The schedule that Amazon Kendra will update the data source. public let schedule: String? /// The current status of the data source. When the status is ACTIVE the data source is ready to use. When the status is FAILED, the ErrorMessage field contains the reason that the data source failed. public let status: DataSourceStatus? /// The type of the data source. public let type: DataSourceType? /// The Unix timestamp of when the data source was last updated. public let updatedAt: Date? public init(configuration: DataSourceConfiguration? = nil, createdAt: Date? = nil, description: String? = nil, errorMessage: String? = nil, id: String? = nil, indexId: String? = nil, languageCode: String? = nil, name: String? = nil, roleArn: String? = nil, schedule: String? = nil, status: DataSourceStatus? = nil, type: DataSourceType? = nil, updatedAt: Date? = nil) { self.configuration = configuration self.createdAt = createdAt self.description = description self.errorMessage = errorMessage self.id = id self.indexId = indexId self.languageCode = languageCode self.name = name self.roleArn = roleArn self.schedule = schedule self.status = status self.type = type self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case configuration = "Configuration" case createdAt = "CreatedAt" case description = "Description" case errorMessage = "ErrorMessage" case id = "Id" case indexId = "IndexId" case languageCode = "LanguageCode" case name = "Name" case roleArn = "RoleArn" case schedule = "Schedule" case status = "Status" case type = "Type" case updatedAt = "UpdatedAt" } } public struct DescribeFaqRequest: AWSEncodableShape { /// The unique identifier of the FAQ. public let id: String /// The identifier of the index that contains the FAQ. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DescribeFaqResponse: AWSDecodableShape { /// The date and time that the FAQ was created. public let createdAt: Date? /// The description of the FAQ that you provided when it was created. public let description: String? /// If the Status field is FAILED, the ErrorMessage field contains the reason why the FAQ failed. public let errorMessage: String? /// The file format used by the input files for the FAQ. public let fileFormat: FaqFileFormat? /// The identifier of the FAQ. public let id: String? /// The identifier of the index that contains the FAQ. public let indexId: String? /// The code for a language. This shows a supported language for the FAQ document. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// The name that you gave the FAQ when it was created. public let name: String? /// The Amazon Resource Name (ARN) of the role that provides access to the S3 bucket containing the input files for the FAQ. public let roleArn: String? public let s3Path: S3Path? /// The status of the FAQ. It is ready to use when the status is ACTIVE. public let status: FaqStatus? /// The date and time that the FAQ was last updated. public let updatedAt: Date? public init(createdAt: Date? = nil, description: String? = nil, errorMessage: String? = nil, fileFormat: FaqFileFormat? = nil, id: String? = nil, indexId: String? = nil, languageCode: String? = nil, name: String? = nil, roleArn: String? = nil, s3Path: S3Path? = nil, status: FaqStatus? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.description = description self.errorMessage = errorMessage self.fileFormat = fileFormat self.id = id self.indexId = indexId self.languageCode = languageCode self.name = name self.roleArn = roleArn self.s3Path = s3Path self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case description = "Description" case errorMessage = "ErrorMessage" case fileFormat = "FileFormat" case id = "Id" case indexId = "IndexId" case languageCode = "LanguageCode" case name = "Name" case roleArn = "RoleArn" case s3Path = "S3Path" case status = "Status" case updatedAt = "UpdatedAt" } } public struct DescribeIndexRequest: AWSEncodableShape { /// The name of the index to describe. public let id: String public init(id: String) { self.id = id } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 36) try self.validate(self.id, name: "id", parent: name, min: 36) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" } } public struct DescribeIndexResponse: AWSDecodableShape { /// For Enterprise edition indexes, you can choose to use additional capacity to meet the needs of your application. This contains the capacity units used for the index. A 0 for the query capacity or the storage capacity indicates that the index is using the default capacity for the index. public let capacityUnits: CapacityUnitsConfiguration? /// The Unix datetime that the index was created. public let createdAt: Date? /// The description of the index. public let description: String? /// Configuration settings for any metadata applied to the documents in the index. public let documentMetadataConfigurations: [DocumentMetadataConfiguration]? /// The Amazon Kendra edition used for the index. You decide the edition when you create the index. public let edition: IndexEdition? /// When th eStatus field value is FAILED, the ErrorMessage field contains a message that explains why. public let errorMessage: String? /// The name of the index. public let id: String? /// Provides information about the number of FAQ questions and answers and the number of text documents indexed. public let indexStatistics: IndexStatistics? /// The name of the index. public let name: String? /// The Amazon Resource Name (ARN) of the IAM role that gives Amazon Kendra permission to write to your Amazon Cloudwatch logs. public let roleArn: String? /// The identifier of the KMScustomer master key (CMK) used to encrypt your data. Amazon Kendra doesn't support asymmetric CMKs. public let serverSideEncryptionConfiguration: ServerSideEncryptionConfiguration? /// The current status of the index. When the value is ACTIVE, the index is ready for use. If the Status field value is FAILED, the ErrorMessage field contains a message that explains why. public let status: IndexStatus? /// The Unix datetime that the index was last updated. public let updatedAt: Date? /// The user context policy for the Amazon Kendra index. public let userContextPolicy: UserContextPolicy? /// Shows whether you have enabled the configuration for fetching access levels of groups and users from an AWS Single Sign-On identity source. public let userGroupResolutionConfiguration: UserGroupResolutionConfiguration? /// The user token configuration for the Amazon Kendra index. public let userTokenConfigurations: [UserTokenConfiguration]? public init(capacityUnits: CapacityUnitsConfiguration? = nil, createdAt: Date? = nil, description: String? = nil, documentMetadataConfigurations: [DocumentMetadataConfiguration]? = nil, edition: IndexEdition? = nil, errorMessage: String? = nil, id: String? = nil, indexStatistics: IndexStatistics? = nil, name: String? = nil, roleArn: String? = nil, serverSideEncryptionConfiguration: ServerSideEncryptionConfiguration? = nil, status: IndexStatus? = nil, updatedAt: Date? = nil, userContextPolicy: UserContextPolicy? = nil, userGroupResolutionConfiguration: UserGroupResolutionConfiguration? = nil, userTokenConfigurations: [UserTokenConfiguration]? = nil) { self.capacityUnits = capacityUnits self.createdAt = createdAt self.description = description self.documentMetadataConfigurations = documentMetadataConfigurations self.edition = edition self.errorMessage = errorMessage self.id = id self.indexStatistics = indexStatistics self.name = name self.roleArn = roleArn self.serverSideEncryptionConfiguration = serverSideEncryptionConfiguration self.status = status self.updatedAt = updatedAt self.userContextPolicy = userContextPolicy self.userGroupResolutionConfiguration = userGroupResolutionConfiguration self.userTokenConfigurations = userTokenConfigurations } private enum CodingKeys: String, CodingKey { case capacityUnits = "CapacityUnits" case createdAt = "CreatedAt" case description = "Description" case documentMetadataConfigurations = "DocumentMetadataConfigurations" case edition = "Edition" case errorMessage = "ErrorMessage" case id = "Id" case indexStatistics = "IndexStatistics" case name = "Name" case roleArn = "RoleArn" case serverSideEncryptionConfiguration = "ServerSideEncryptionConfiguration" case status = "Status" case updatedAt = "UpdatedAt" case userContextPolicy = "UserContextPolicy" case userGroupResolutionConfiguration = "UserGroupResolutionConfiguration" case userTokenConfigurations = "UserTokenConfigurations" } } public struct DescribePrincipalMappingRequest: AWSEncodableShape { /// The identifier of the data source to check the processing of PUT and DELETE actions for mapping users to their groups. public let dataSourceId: String? /// The identifier of the group required to check the processing of PUT and DELETE actions for mapping users to their groups. public let groupId: String /// The identifier of the index required to check the processing of PUT and DELETE actions for mapping users to their groups. public let indexId: String public init(dataSourceId: String? = nil, groupId: String, indexId: String) { self.dataSourceId = dataSourceId self.groupId = groupId self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.groupId, name: "groupId", parent: name, max: 1024) try self.validate(self.groupId, name: "groupId", parent: name, min: 1) try self.validate(self.groupId, name: "groupId", parent: name, pattern: "^\\P{C}*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case groupId = "GroupId" case indexId = "IndexId" } } public struct DescribePrincipalMappingResponse: AWSDecodableShape { /// Shows the identifier of the data source to see information on the processing of PUT and DELETE actions for mapping users to their groups. public let dataSourceId: String? /// Shows the identifier of the group to see information on the processing of PUT and DELETE actions for mapping users to their groups. public let groupId: String? /// Shows the following information on the processing of PUT and DELETE actions for mapping users to their groups: Status – the status can be either PROCESSING, SUCCEEDED, DELETING, DELETED, or FAILED. Last updated – the last date-time an action was updated. Received – the last date-time an action was received or submitted. Ordering ID – the latest action that should process and apply after other actions. Failure reason – the reason an action could not be processed. public let groupOrderingIdSummaries: [GroupOrderingIdSummary]? /// Shows the identifier of the index to see information on the processing of PUT and DELETE actions for mapping users to their groups. public let indexId: String? public init(dataSourceId: String? = nil, groupId: String? = nil, groupOrderingIdSummaries: [GroupOrderingIdSummary]? = nil, indexId: String? = nil) { self.dataSourceId = dataSourceId self.groupId = groupId self.groupOrderingIdSummaries = groupOrderingIdSummaries self.indexId = indexId } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case groupId = "GroupId" case groupOrderingIdSummaries = "GroupOrderingIdSummaries" case indexId = "IndexId" } } public struct DescribeQuerySuggestionsBlockListRequest: AWSEncodableShape { /// The unique identifier of the block list. public let id: String /// The identifier of the index for the block list. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 36) try self.validate(self.id, name: "id", parent: name, min: 36) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DescribeQuerySuggestionsBlockListResponse: AWSDecodableShape { /// Shows the date-time a block list for query suggestions was created. public let createdAt: Date? /// Shows the description for the block list. public let description: String? /// Shows the error message with details when there are issues in processing the block list. public let errorMessage: String? /// Shows the current size of the block list text file in S3. public let fileSizeBytes: Int64? /// Shows the unique identifier of the block list. public let id: String? /// Shows the identifier of the index for the block list. public let indexId: String? /// Shows the current number of valid, non-empty words or phrases in the block list text file. public let itemCount: Int? /// Shows the name of the block list. public let name: String? /// Shows the current IAM (Identity and Access Management) role used by Amazon Kendra to access the block list text file in S3. The role needs S3 read permissions to your file in S3 and needs to give STS (Security Token Service) assume role permissions to Amazon Kendra. public let roleArn: String? /// Shows the current S3 path to your block list text file in your S3 bucket. Each block word or phrase should be on a separate line in a text file. For information on the current quota limits for block lists, see Quotas for Amazon Kendra. public let sourceS3Path: S3Path? /// Shows whether the current status of the block list is ACTIVE or INACTIVE. public let status: QuerySuggestionsBlockListStatus? /// Shows the date-time a block list for query suggestions was last updated. public let updatedAt: Date? public init(createdAt: Date? = nil, description: String? = nil, errorMessage: String? = nil, fileSizeBytes: Int64? = nil, id: String? = nil, indexId: String? = nil, itemCount: Int? = nil, name: String? = nil, roleArn: String? = nil, sourceS3Path: S3Path? = nil, status: QuerySuggestionsBlockListStatus? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.description = description self.errorMessage = errorMessage self.fileSizeBytes = fileSizeBytes self.id = id self.indexId = indexId self.itemCount = itemCount self.name = name self.roleArn = roleArn self.sourceS3Path = sourceS3Path self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case description = "Description" case errorMessage = "ErrorMessage" case fileSizeBytes = "FileSizeBytes" case id = "Id" case indexId = "IndexId" case itemCount = "ItemCount" case name = "Name" case roleArn = "RoleArn" case sourceS3Path = "SourceS3Path" case status = "Status" case updatedAt = "UpdatedAt" } } public struct DescribeQuerySuggestionsConfigRequest: AWSEncodableShape { /// The identifier of the index you want to describe query suggestions settings for. public let indexId: String public init(indexId: String) { self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" } } public struct DescribeQuerySuggestionsConfigResponse: AWSDecodableShape { /// Shows whether Amazon Kendra uses all queries or only uses queries that include user information to generate query suggestions. public let includeQueriesWithoutUserInformation: Bool? /// Shows the date-time query suggestions for an index was last cleared. After you clear suggestions, Amazon Kendra learns new suggestions based on new queries added to the query log from the time you cleared suggestions. Amazon Kendra only considers re-occurences of a query from the time you cleared suggestions. public let lastClearTime: Date? /// Shows the date-time query suggestions for an index was last updated. public let lastSuggestionsBuildTime: Date? /// Shows the minimum number of unique users who must search a query in order for the query to be eligible to suggest to your users. public let minimumNumberOfQueryingUsers: Int? /// Shows the minimum number of times a query must be searched in order for the query to be eligible to suggest to your users. public let minimumQueryCount: Int? /// Shows whether query suggestions are currently in ENABLED mode or LEARN_ONLY mode. By default, Amazon Kendra enables query suggestions.LEARN_ONLY turns off query suggestions for your users. You can change the mode using the UpdateQuerySuggestionsConfig operation. public let mode: Mode? /// Shows how recent your queries are in your query log time window (in days). public let queryLogLookBackWindowInDays: Int? /// Shows whether the status of query suggestions settings is currently Active or Updating. Active means the current settings apply and Updating means your changed settings are in the process of applying. public let status: QuerySuggestionsStatus? /// Shows the current total count of query suggestions for an index. This count can change when you update your query suggestions settings, if you filter out certain queries from suggestions using a block list, and as the query log accumulates more queries for Amazon Kendra to learn from. public let totalSuggestionsCount: Int? public init(includeQueriesWithoutUserInformation: Bool? = nil, lastClearTime: Date? = nil, lastSuggestionsBuildTime: Date? = nil, minimumNumberOfQueryingUsers: Int? = nil, minimumQueryCount: Int? = nil, mode: Mode? = nil, queryLogLookBackWindowInDays: Int? = nil, status: QuerySuggestionsStatus? = nil, totalSuggestionsCount: Int? = nil) { self.includeQueriesWithoutUserInformation = includeQueriesWithoutUserInformation self.lastClearTime = lastClearTime self.lastSuggestionsBuildTime = lastSuggestionsBuildTime self.minimumNumberOfQueryingUsers = minimumNumberOfQueryingUsers self.minimumQueryCount = minimumQueryCount self.mode = mode self.queryLogLookBackWindowInDays = queryLogLookBackWindowInDays self.status = status self.totalSuggestionsCount = totalSuggestionsCount } private enum CodingKeys: String, CodingKey { case includeQueriesWithoutUserInformation = "IncludeQueriesWithoutUserInformation" case lastClearTime = "LastClearTime" case lastSuggestionsBuildTime = "LastSuggestionsBuildTime" case minimumNumberOfQueryingUsers = "MinimumNumberOfQueryingUsers" case minimumQueryCount = "MinimumQueryCount" case mode = "Mode" case queryLogLookBackWindowInDays = "QueryLogLookBackWindowInDays" case status = "Status" case totalSuggestionsCount = "TotalSuggestionsCount" } } public struct DescribeThesaurusRequest: AWSEncodableShape { /// The identifier of the thesaurus to describe. public let id: String /// The identifier of the index associated with the thesaurus to describe. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct DescribeThesaurusResponse: AWSDecodableShape { /// The Unix datetime that the thesaurus was created. public let createdAt: Date? /// The thesaurus description. public let description: String? /// When the Status field value is FAILED, the ErrorMessage field provides more information. public let errorMessage: String? /// The size of the thesaurus file in bytes. public let fileSizeBytes: Int64? /// The identifier of the thesaurus. public let id: String? /// The identifier of the index associated with the thesaurus to describe. public let indexId: String? /// The thesaurus name. public let name: String? /// An AWS Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access thesaurus file specified in SourceS3Path. public let roleArn: String? public let sourceS3Path: S3Path? /// The current status of the thesaurus. When the value is ACTIVE, queries are able to use the thesaurus. If the Status field value is FAILED, the ErrorMessage field provides more information. If the status is ACTIVE_BUT_UPDATE_FAILED, it means that Amazon Kendra could not ingest the new thesaurus file. The old thesaurus file is still active. public let status: ThesaurusStatus? /// The number of synonym rules in the thesaurus file. public let synonymRuleCount: Int64? /// The number of unique terms in the thesaurus file. For example, the synonyms a,b,c and a=>d, the term count would be 4. public let termCount: Int64? /// The Unix datetime that the thesaurus was last updated. public let updatedAt: Date? public init(createdAt: Date? = nil, description: String? = nil, errorMessage: String? = nil, fileSizeBytes: Int64? = nil, id: String? = nil, indexId: String? = nil, name: String? = nil, roleArn: String? = nil, sourceS3Path: S3Path? = nil, status: ThesaurusStatus? = nil, synonymRuleCount: Int64? = nil, termCount: Int64? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.description = description self.errorMessage = errorMessage self.fileSizeBytes = fileSizeBytes self.id = id self.indexId = indexId self.name = name self.roleArn = roleArn self.sourceS3Path = sourceS3Path self.status = status self.synonymRuleCount = synonymRuleCount self.termCount = termCount self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case description = "Description" case errorMessage = "ErrorMessage" case fileSizeBytes = "FileSizeBytes" case id = "Id" case indexId = "IndexId" case name = "Name" case roleArn = "RoleArn" case sourceS3Path = "SourceS3Path" case status = "Status" case synonymRuleCount = "SynonymRuleCount" case termCount = "TermCount" case updatedAt = "UpdatedAt" } } public struct Document: AWSEncodableShape { /// Information on user and group access rights, which is used for user context filtering. public let accessControlList: [Principal]? /// Custom attributes to apply to the document. Use the custom attributes to provide additional information for searching, to provide facets for refining searches, and to provide additional information in the query response. public let attributes: [DocumentAttribute]? /// The contents of the document. Documents passed to the Blob parameter must be base64 encoded. Your code might not need to encode the document file bytes if you're using an Amazon Web Services SDK to call Amazon Kendra operations. If you are calling the Amazon Kendra endpoint directly using REST, you must base64 encode the contents before sending. public let blob: Data? /// The file type of the document in the Blob field. public let contentType: ContentType? /// The list of principal lists that define the hierarchy for which documents users should have access to. public let hierarchicalAccessControlList: [HierarchicalPrincipal]? /// A unique identifier of the document in the index. public let id: String public let s3Path: S3Path? /// The title of the document. public let title: String? public init(accessControlList: [Principal]? = nil, attributes: [DocumentAttribute]? = nil, blob: Data? = nil, contentType: ContentType? = nil, hierarchicalAccessControlList: [HierarchicalPrincipal]? = nil, id: String, s3Path: S3Path? = nil, title: String? = nil) { self.accessControlList = accessControlList self.attributes = attributes self.blob = blob self.contentType = contentType self.hierarchicalAccessControlList = hierarchicalAccessControlList self.id = id self.s3Path = s3Path self.title = title } public func validate(name: String) throws { try self.accessControlList?.forEach { try $0.validate(name: "\(name).accessControlList[]") } try self.attributes?.forEach { try $0.validate(name: "\(name).attributes[]") } try self.hierarchicalAccessControlList?.forEach { try $0.validate(name: "\(name).hierarchicalAccessControlList[]") } try self.validate(self.hierarchicalAccessControlList, name: "hierarchicalAccessControlList", parent: name, max: 30) try self.validate(self.hierarchicalAccessControlList, name: "hierarchicalAccessControlList", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, max: 2048) try self.validate(self.id, name: "id", parent: name, min: 1) try self.s3Path?.validate(name: "\(name).s3Path") } private enum CodingKeys: String, CodingKey { case accessControlList = "AccessControlList" case attributes = "Attributes" case blob = "Blob" case contentType = "ContentType" case hierarchicalAccessControlList = "HierarchicalAccessControlList" case id = "Id" case s3Path = "S3Path" case title = "Title" } } public struct DocumentAttribute: AWSEncodableShape & AWSDecodableShape { /// The identifier for the attribute. public let key: String /// The value of the attribute. public let value: DocumentAttributeValue public init(key: String, value: DocumentAttributeValue) { self.key = key self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 200) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.key, name: "key", parent: name, pattern: "^[a-zA-Z0-9_][a-zA-Z0-9_-]*$") try self.value.validate(name: "\(name).value") } private enum CodingKeys: String, CodingKey { case key = "Key" case value = "Value" } } public struct DocumentAttributeValue: AWSEncodableShape & AWSDecodableShape { /// A date expressed as an ISO 8601 string. It is important for the time zone to be included in the ISO 8601 date-time format. For example, 20120325T123010+01:00 is the ISO 8601 date-time format for March 25th 2012 at 12:30PM (plus 10 seconds) in Central European Time. public let dateValue: Date? /// A long integer value. public let longValue: Int64? /// A list of strings. public let stringListValue: [String]? /// A string, such as "department". public let stringValue: String? public init(dateValue: Date? = nil, longValue: Int64? = nil, stringListValue: [String]? = nil, stringValue: String? = nil) { self.dateValue = dateValue self.longValue = longValue self.stringListValue = stringListValue self.stringValue = stringValue } public func validate(name: String) throws { try self.stringListValue?.forEach { try validate($0, name: "stringListValue[]", parent: name, max: 2048) try validate($0, name: "stringListValue[]", parent: name, min: 1) } try self.validate(self.stringValue, name: "stringValue", parent: name, max: 2048) try self.validate(self.stringValue, name: "stringValue", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case dateValue = "DateValue" case longValue = "LongValue" case stringListValue = "StringListValue" case stringValue = "StringValue" } } public struct DocumentAttributeValueCountPair: AWSDecodableShape { /// The number of documents in the response that have the attribute value for the key. public let count: Int? /// The value of the attribute. For example, "HR." public let documentAttributeValue: DocumentAttributeValue? public init(count: Int? = nil, documentAttributeValue: DocumentAttributeValue? = nil) { self.count = count self.documentAttributeValue = documentAttributeValue } private enum CodingKeys: String, CodingKey { case count = "Count" case documentAttributeValue = "DocumentAttributeValue" } } public struct DocumentInfo: AWSEncodableShape { /// Attributes that identify a specific version of a document to check. The only valid attributes are: version datasourceId jobExecutionId The attributes follow these rules: dataSourceId and jobExecutionId must be used together. version is ignored if dataSourceId and jobExecutionId are not provided. If dataSourceId and jobExecutionId are provided, but version is not, the version defaults to "0". public let attributes: [DocumentAttribute]? /// The unique identifier of the document. public let documentId: String public init(attributes: [DocumentAttribute]? = nil, documentId: String) { self.attributes = attributes self.documentId = documentId } public func validate(name: String) throws { try self.attributes?.forEach { try $0.validate(name: "\(name).attributes[]") } try self.validate(self.documentId, name: "documentId", parent: name, max: 2048) try self.validate(self.documentId, name: "documentId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case attributes = "Attributes" case documentId = "DocumentId" } } public struct DocumentMetadataConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the index field. public let name: String /// Provides manual tuning parameters to determine how the field affects the search results. public let relevance: Relevance? /// Provides information about how the field is used during a search. public let search: Search? /// The data type of the index field. public let type: DocumentAttributeValueType public init(name: String, relevance: Relevance? = nil, search: Search? = nil, type: DocumentAttributeValueType) { self.name = name self.relevance = relevance self.search = search self.type = type } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 30) try self.validate(self.name, name: "name", parent: name, min: 1) try self.relevance?.validate(name: "\(name).relevance") } private enum CodingKeys: String, CodingKey { case name = "Name" case relevance = "Relevance" case search = "Search" case type = "Type" } } public struct DocumentRelevanceConfiguration: AWSEncodableShape { /// The name of the tuning configuration to override document relevance at the index level. public let name: String public let relevance: Relevance public init(name: String, relevance: Relevance) { self.name = name self.relevance = relevance } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 30) try self.validate(self.name, name: "name", parent: name, min: 1) try self.relevance.validate(name: "\(name).relevance") } private enum CodingKeys: String, CodingKey { case name = "Name" case relevance = "Relevance" } } public struct DocumentsMetadataConfiguration: AWSEncodableShape & AWSDecodableShape { /// A prefix used to filter metadata configuration files in the Amazon Web Services S3 bucket. The S3 bucket might contain multiple metadata files. Use S3Prefix to include only the desired metadata files. public let s3Prefix: String? public init(s3Prefix: String? = nil) { self.s3Prefix = s3Prefix } public func validate(name: String) throws { try self.validate(self.s3Prefix, name: "s3Prefix", parent: name, max: 1024) try self.validate(self.s3Prefix, name: "s3Prefix", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case s3Prefix = "S3Prefix" } } public struct Facet: AWSEncodableShape { /// The unique key for the document attribute. public let documentAttributeKey: String? public init(documentAttributeKey: String? = nil) { self.documentAttributeKey = documentAttributeKey } public func validate(name: String) throws { try self.validate(self.documentAttributeKey, name: "documentAttributeKey", parent: name, max: 200) try self.validate(self.documentAttributeKey, name: "documentAttributeKey", parent: name, min: 1) try self.validate(self.documentAttributeKey, name: "documentAttributeKey", parent: name, pattern: "^[a-zA-Z0-9_][a-zA-Z0-9_-]*$") } private enum CodingKeys: String, CodingKey { case documentAttributeKey = "DocumentAttributeKey" } } public struct FacetResult: AWSDecodableShape { /// The key for the facet values. This is the same as the DocumentAttributeKey provided in the query. public let documentAttributeKey: String? /// An array of key/value pairs, where the key is the value of the attribute and the count is the number of documents that share the key value. public let documentAttributeValueCountPairs: [DocumentAttributeValueCountPair]? /// The data type of the facet value. This is the same as the type defined for the index field when it was created. public let documentAttributeValueType: DocumentAttributeValueType? public init(documentAttributeKey: String? = nil, documentAttributeValueCountPairs: [DocumentAttributeValueCountPair]? = nil, documentAttributeValueType: DocumentAttributeValueType? = nil) { self.documentAttributeKey = documentAttributeKey self.documentAttributeValueCountPairs = documentAttributeValueCountPairs self.documentAttributeValueType = documentAttributeValueType } private enum CodingKeys: String, CodingKey { case documentAttributeKey = "DocumentAttributeKey" case documentAttributeValueCountPairs = "DocumentAttributeValueCountPairs" case documentAttributeValueType = "DocumentAttributeValueType" } } public struct FaqStatistics: AWSDecodableShape { /// The total number of FAQ questions and answers contained in the index. public let indexedQuestionAnswersCount: Int public init(indexedQuestionAnswersCount: Int) { self.indexedQuestionAnswersCount = indexedQuestionAnswersCount } private enum CodingKeys: String, CodingKey { case indexedQuestionAnswersCount = "IndexedQuestionAnswersCount" } } public struct FaqSummary: AWSDecodableShape { /// The UNIX datetime that the FAQ was added to the index. public let createdAt: Date? /// The file type used to create the FAQ. public let fileFormat: FaqFileFormat? /// The unique identifier of the FAQ. public let id: String? /// The code for a language. This shows a supported language for the FAQ document as part of the summary information for FAQs. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// The name that you assigned the FAQ when you created or updated the FAQ. public let name: String? /// The current status of the FAQ. When the status is ACTIVE the FAQ is ready for use. public let status: FaqStatus? /// The UNIX datetime that the FAQ was last updated. public let updatedAt: Date? public init(createdAt: Date? = nil, fileFormat: FaqFileFormat? = nil, id: String? = nil, languageCode: String? = nil, name: String? = nil, status: FaqStatus? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.fileFormat = fileFormat self.id = id self.languageCode = languageCode self.name = name self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case fileFormat = "FileFormat" case id = "Id" case languageCode = "LanguageCode" case name = "Name" case status = "Status" case updatedAt = "UpdatedAt" } } public struct GetQuerySuggestionsRequest: AWSEncodableShape { /// The identifier of the index you want to get query suggestions from. public let indexId: String /// The maximum number of query suggestions you want to show to your users. public let maxSuggestionsCount: Int? /// The text of a user's query to generate query suggestions. A query is suggested if the query prefix matches what a user starts to type as their query. Amazon Kendra does not show any suggestions if a user types fewer than two characters or more than 60 characters. A query must also have at least one search result and contain at least one word of more than four characters. public let queryText: String public init(indexId: String, maxSuggestionsCount: Int? = nil, queryText: String) { self.indexId = indexId self.maxSuggestionsCount = maxSuggestionsCount self.queryText = queryText } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.queryText, name: "queryText", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" case maxSuggestionsCount = "MaxSuggestionsCount" case queryText = "QueryText" } } public struct GetQuerySuggestionsResponse: AWSDecodableShape { /// The unique identifier for a list of query suggestions for an index. public let querySuggestionsId: String? /// A list of query suggestions for an index. public let suggestions: [Suggestion]? public init(querySuggestionsId: String? = nil, suggestions: [Suggestion]? = nil) { self.querySuggestionsId = querySuggestionsId self.suggestions = suggestions } private enum CodingKeys: String, CodingKey { case querySuggestionsId = "QuerySuggestionsId" case suggestions = "Suggestions" } } public struct GoogleDriveConfiguration: AWSEncodableShape & AWSDecodableShape { /// A list of MIME types to exclude from the index. All documents matching the specified MIME type are excluded. For a list of MIME types, see Using a Google Workspace Drive data source. public let excludeMimeTypes: [String]? /// A list of identifiers or shared drives to exclude from the index. All files and folders stored on the shared drive are excluded. public let excludeSharedDrives: [String]? /// A list of email addresses of the users. Documents owned by these users are excluded from the index. Documents shared with excluded users are indexed unless they are excluded in another way. public let excludeUserAccounts: [String]? /// A list of regular expression patterns that apply to the path on Google Drive. Items that match the pattern are excluded from the index from both shared drives and users' My Drives. Items that don't match the pattern are included in the index. If an item matches both an exclusion pattern and an inclusion pattern, it is excluded from the index. public let exclusionPatterns: [String]? /// Defines mapping between a field in the Google Drive and a Amazon Kendra index field. If you are using the console, you can define index fields when creating the mapping. If you are using the API, you must first create the field using the UpdateIndex operation. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// A list of regular expression patterns that apply to path on Google Drive. Items that match the pattern are included in the index from both shared drives and users' My Drives. Items that don't match the pattern are excluded from the index. If an item matches both an inclusion pattern and an exclusion pattern, it is excluded from the index. public let inclusionPatterns: [String]? /// The Amazon Resource Name (ARN) of a Secrets Managersecret that contains the credentials required to connect to Google Drive. For more information, see Using a Google Workspace Drive data source. public let secretArn: String public init(excludeMimeTypes: [String]? = nil, excludeSharedDrives: [String]? = nil, excludeUserAccounts: [String]? = nil, exclusionPatterns: [String]? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, inclusionPatterns: [String]? = nil, secretArn: String) { self.excludeMimeTypes = excludeMimeTypes self.excludeSharedDrives = excludeSharedDrives self.excludeUserAccounts = excludeUserAccounts self.exclusionPatterns = exclusionPatterns self.fieldMappings = fieldMappings self.inclusionPatterns = inclusionPatterns self.secretArn = secretArn } public func validate(name: String) throws { try self.excludeMimeTypes?.forEach { try validate($0, name: "excludeMimeTypes[]", parent: name, max: 256) try validate($0, name: "excludeMimeTypes[]", parent: name, min: 1) try validate($0, name: "excludeMimeTypes[]", parent: name, pattern: "^\\P{C}*$") } try self.validate(self.excludeMimeTypes, name: "excludeMimeTypes", parent: name, max: 30) try self.excludeSharedDrives?.forEach { try validate($0, name: "excludeSharedDrives[]", parent: name, max: 256) try validate($0, name: "excludeSharedDrives[]", parent: name, min: 1) try validate($0, name: "excludeSharedDrives[]", parent: name, pattern: "^\\P{C}*$") } try self.validate(self.excludeSharedDrives, name: "excludeSharedDrives", parent: name, max: 100) try self.excludeUserAccounts?.forEach { try validate($0, name: "excludeUserAccounts[]", parent: name, max: 256) try validate($0, name: "excludeUserAccounts[]", parent: name, min: 1) try validate($0, name: "excludeUserAccounts[]", parent: name, pattern: "^\\P{C}*$") } try self.validate(self.excludeUserAccounts, name: "excludeUserAccounts", parent: name, max: 100) try self.exclusionPatterns?.forEach { try validate($0, name: "exclusionPatterns[]", parent: name, max: 150) try validate($0, name: "exclusionPatterns[]", parent: name, min: 1) } try self.validate(self.exclusionPatterns, name: "exclusionPatterns", parent: name, max: 100) try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.inclusionPatterns?.forEach { try validate($0, name: "inclusionPatterns[]", parent: name, max: 150) try validate($0, name: "inclusionPatterns[]", parent: name, min: 1) } try self.validate(self.inclusionPatterns, name: "inclusionPatterns", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") } private enum CodingKeys: String, CodingKey { case excludeMimeTypes = "ExcludeMimeTypes" case excludeSharedDrives = "ExcludeSharedDrives" case excludeUserAccounts = "ExcludeUserAccounts" case exclusionPatterns = "ExclusionPatterns" case fieldMappings = "FieldMappings" case inclusionPatterns = "InclusionPatterns" case secretArn = "SecretArn" } } public struct GroupMembers: AWSEncodableShape { /// A list of sub groups that belong to a group. For example, the sub groups "Research", "Engineering", and "Sales and Marketing" all belong to the group "Company". public let memberGroups: [MemberGroup]? /// A list of users that belong to a group. For example, a list of interns all belong to the "Interns" group. public let memberUsers: [MemberUser]? /// If you have more than 1000 users and/or sub groups for a single group, you need to provide the path to the S3 file that lists your users and sub groups for a group. Your sub groups can contain more than 1000 users, but the list of sub groups that belong to a group (and/or users) must be no more than 1000. You can download this example S3 file that uses the correct format for listing group members. Note, dataSourceId is optional. The value of type for a group is always GROUP and for a user it is always USER. public let s3PathforGroupMembers: S3Path? public init(memberGroups: [MemberGroup]? = nil, memberUsers: [MemberUser]? = nil, s3PathforGroupMembers: S3Path? = nil) { self.memberGroups = memberGroups self.memberUsers = memberUsers self.s3PathforGroupMembers = s3PathforGroupMembers } public func validate(name: String) throws { try self.memberGroups?.forEach { try $0.validate(name: "\(name).memberGroups[]") } try self.validate(self.memberGroups, name: "memberGroups", parent: name, max: 1000) try self.validate(self.memberGroups, name: "memberGroups", parent: name, min: 1) try self.memberUsers?.forEach { try $0.validate(name: "\(name).memberUsers[]") } try self.validate(self.memberUsers, name: "memberUsers", parent: name, max: 1000) try self.validate(self.memberUsers, name: "memberUsers", parent: name, min: 1) try self.s3PathforGroupMembers?.validate(name: "\(name).s3PathforGroupMembers") } private enum CodingKeys: String, CodingKey { case memberGroups = "MemberGroups" case memberUsers = "MemberUsers" case s3PathforGroupMembers = "S3PathforGroupMembers" } } public struct GroupOrderingIdSummary: AWSDecodableShape { /// The reason an action could not be processed. An action can be a PUT or DELETE action for mapping users to their groups. public let failureReason: String? /// The last date-time an action was updated. An action can be a PUT or DELETE action for mapping users to their groups. public let lastUpdatedAt: Date? /// The order in which actions should complete processing. An action can be a PUT or DELETE action for mapping users to their groups. public let orderingId: Int64? /// The date-time an action was received by Amazon Kendra. An action can be a PUT or DELETE action for mapping users to their groups. public let receivedAt: Date? /// The current processing status of actions for mapping users to their groups. The status can be either PROCESSING, SUCCEEDED, DELETING, DELETED, or FAILED. public let status: PrincipalMappingStatus? public init(failureReason: String? = nil, lastUpdatedAt: Date? = nil, orderingId: Int64? = nil, receivedAt: Date? = nil, status: PrincipalMappingStatus? = nil) { self.failureReason = failureReason self.lastUpdatedAt = lastUpdatedAt self.orderingId = orderingId self.receivedAt = receivedAt self.status = status } private enum CodingKeys: String, CodingKey { case failureReason = "FailureReason" case lastUpdatedAt = "LastUpdatedAt" case orderingId = "OrderingId" case receivedAt = "ReceivedAt" case status = "Status" } } public struct GroupSummary: AWSDecodableShape { /// The identifier of the group you want group summary information on. public let groupId: String? /// The timestamp identifier used for the latest PUT or DELETE action. public let orderingId: Int64? public init(groupId: String? = nil, orderingId: Int64? = nil) { self.groupId = groupId self.orderingId = orderingId } private enum CodingKeys: String, CodingKey { case groupId = "GroupId" case orderingId = "OrderingId" } } public struct HierarchicalPrincipal: AWSEncodableShape { /// A list of principal lists that define the hierarchy for which documents users should have access to. Each hierarchical list specifies which user or group has allow or deny access for each document. public let principalList: [Principal] public init(principalList: [Principal]) { self.principalList = principalList } public func validate(name: String) throws { try self.principalList.forEach { try $0.validate(name: "\(name).principalList[]") } } private enum CodingKeys: String, CodingKey { case principalList = "PrincipalList" } } public struct Highlight: AWSDecodableShape { /// The zero-based location in the response string where the highlight starts. public let beginOffset: Int /// The zero-based location in the response string where the highlight ends. public let endOffset: Int /// Indicates whether the response is the best response. True if this is the best response; otherwise, false. public let topAnswer: Bool? /// The highlight type. public let type: HighlightType? public init(beginOffset: Int, endOffset: Int, topAnswer: Bool? = nil, type: HighlightType? = nil) { self.beginOffset = beginOffset self.endOffset = endOffset self.topAnswer = topAnswer self.type = type } private enum CodingKeys: String, CodingKey { case beginOffset = "BeginOffset" case endOffset = "EndOffset" case topAnswer = "TopAnswer" case type = "Type" } } public struct IndexConfigurationSummary: AWSDecodableShape { /// The Unix timestamp when the index was created. public let createdAt: Date /// Indicates whether the index is a enterprise edition index or a developer edition index. public let edition: IndexEdition? /// A unique identifier for the index. Use this to identify the index when you are using operations such as Query, DescribeIndex, UpdateIndex, and DeleteIndex. public let id: String? /// The name of the index. public let name: String? /// The current status of the index. When the status is ACTIVE, the index is ready to search. public let status: IndexStatus /// The Unix timestamp when the index was last updated by the UpdateIndex operation. public let updatedAt: Date public init(createdAt: Date, edition: IndexEdition? = nil, id: String? = nil, name: String? = nil, status: IndexStatus, updatedAt: Date) { self.createdAt = createdAt self.edition = edition self.id = id self.name = name self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case edition = "Edition" case id = "Id" case name = "Name" case status = "Status" case updatedAt = "UpdatedAt" } } public struct IndexStatistics: AWSDecodableShape { /// The number of question and answer topics in the index. public let faqStatistics: FaqStatistics /// The number of text documents indexed. public let textDocumentStatistics: TextDocumentStatistics public init(faqStatistics: FaqStatistics, textDocumentStatistics: TextDocumentStatistics) { self.faqStatistics = faqStatistics self.textDocumentStatistics = textDocumentStatistics } private enum CodingKeys: String, CodingKey { case faqStatistics = "FaqStatistics" case textDocumentStatistics = "TextDocumentStatistics" } } public struct JsonTokenTypeConfiguration: AWSEncodableShape & AWSDecodableShape { /// The group attribute field. public let groupAttributeField: String /// The user name attribute field. public let userNameAttributeField: String public init(groupAttributeField: String, userNameAttributeField: String) { self.groupAttributeField = groupAttributeField self.userNameAttributeField = userNameAttributeField } public func validate(name: String) throws { try self.validate(self.groupAttributeField, name: "groupAttributeField", parent: name, max: 2048) try self.validate(self.groupAttributeField, name: "groupAttributeField", parent: name, min: 1) try self.validate(self.userNameAttributeField, name: "userNameAttributeField", parent: name, max: 2048) try self.validate(self.userNameAttributeField, name: "userNameAttributeField", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case groupAttributeField = "GroupAttributeField" case userNameAttributeField = "UserNameAttributeField" } } public struct JwtTokenTypeConfiguration: AWSEncodableShape & AWSDecodableShape { /// The regular expression that identifies the claim. public let claimRegex: String? /// The group attribute field. public let groupAttributeField: String? /// The issuer of the token. public let issuer: String? /// The location of the key. public let keyLocation: KeyLocation /// The Amazon Resource Name (arn) of the secret. public let secretManagerArn: String? /// The signing key URL. public let url: String? /// The user name attribute field. public let userNameAttributeField: String? public init(claimRegex: String? = nil, groupAttributeField: String? = nil, issuer: String? = nil, keyLocation: KeyLocation, secretManagerArn: String? = nil, url: String? = nil, userNameAttributeField: String? = nil) { self.claimRegex = claimRegex self.groupAttributeField = groupAttributeField self.issuer = issuer self.keyLocation = keyLocation self.secretManagerArn = secretManagerArn self.url = url self.userNameAttributeField = userNameAttributeField } public func validate(name: String) throws { try self.validate(self.claimRegex, name: "claimRegex", parent: name, max: 100) try self.validate(self.claimRegex, name: "claimRegex", parent: name, min: 1) try self.validate(self.claimRegex, name: "claimRegex", parent: name, pattern: "^\\P{C}*$") try self.validate(self.groupAttributeField, name: "groupAttributeField", parent: name, max: 100) try self.validate(self.groupAttributeField, name: "groupAttributeField", parent: name, min: 1) try self.validate(self.groupAttributeField, name: "groupAttributeField", parent: name, pattern: "^\\P{C}*$") try self.validate(self.issuer, name: "issuer", parent: name, max: 65) try self.validate(self.issuer, name: "issuer", parent: name, min: 1) try self.validate(self.issuer, name: "issuer", parent: name, pattern: "^\\P{C}*$") try self.validate(self.secretManagerArn, name: "secretManagerArn", parent: name, max: 1284) try self.validate(self.secretManagerArn, name: "secretManagerArn", parent: name, min: 1) try self.validate(self.secretManagerArn, name: "secretManagerArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.url, name: "url", parent: name, max: 2048) try self.validate(self.url, name: "url", parent: name, min: 1) try self.validate(self.url, name: "url", parent: name, pattern: "^(https?|ftp|file):\\/\\/([^\\s]*)$") try self.validate(self.userNameAttributeField, name: "userNameAttributeField", parent: name, max: 100) try self.validate(self.userNameAttributeField, name: "userNameAttributeField", parent: name, min: 1) try self.validate(self.userNameAttributeField, name: "userNameAttributeField", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case claimRegex = "ClaimRegex" case groupAttributeField = "GroupAttributeField" case issuer = "Issuer" case keyLocation = "KeyLocation" case secretManagerArn = "SecretManagerArn" case url = "URL" case userNameAttributeField = "UserNameAttributeField" } } public struct ListDataSourceSyncJobsRequest: AWSEncodableShape { /// The identifier of the data source. public let id: String /// The identifier of the index that contains the data source. public let indexId: String /// The maximum number of synchronization jobs to return in the response. If there are fewer results in the list, this response contains only the actual results. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of jobs. public let nextToken: String? /// When specified, the synchronization jobs returned in the list are limited to jobs between the specified dates. public let startTimeFilter: TimeRange? /// When specified, only returns synchronization jobs with the Status field equal to the specified status. public let statusFilter: DataSourceSyncJobStatus? public init(id: String, indexId: String, maxResults: Int? = nil, nextToken: String? = nil, startTimeFilter: TimeRange? = nil, statusFilter: DataSourceSyncJobStatus? = nil) { self.id = id self.indexId = indexId self.maxResults = maxResults self.nextToken = nextToken self.startTimeFilter = startTimeFilter self.statusFilter = statusFilter } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" case maxResults = "MaxResults" case nextToken = "NextToken" case startTimeFilter = "StartTimeFilter" case statusFilter = "StatusFilter" } } public struct ListDataSourceSyncJobsResponse: AWSDecodableShape { /// A history of synchronization jobs for the data source. public let history: [DataSourceSyncJob]? /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of jobs. public let nextToken: String? public init(history: [DataSourceSyncJob]? = nil, nextToken: String? = nil) { self.history = history self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case history = "History" case nextToken = "NextToken" } } public struct ListDataSourcesRequest: AWSEncodableShape { /// The identifier of the index that contains the data source. public let indexId: String /// The maximum number of data sources to return. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of data sources (DataSourceSummaryItems). public let nextToken: String? public init(indexId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.indexId = indexId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListDataSourcesResponse: AWSDecodableShape { /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of data sources. public let nextToken: String? /// An array of summary information for one or more data sources. public let summaryItems: [DataSourceSummary]? public init(nextToken: String? = nil, summaryItems: [DataSourceSummary]? = nil) { self.nextToken = nextToken self.summaryItems = summaryItems } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case summaryItems = "SummaryItems" } } public struct ListFaqsRequest: AWSEncodableShape { /// The index that contains the FAQ lists. public let indexId: String /// The maximum number of FAQs to return in the response. If there are fewer results in the list, this response contains only the actual results. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of FAQs. public let nextToken: String? public init(indexId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.indexId = indexId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListFaqsResponse: AWSDecodableShape { /// information about the FAQs associated with the specified index. public let faqSummaryItems: [FaqSummary]? /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of FAQs. public let nextToken: String? public init(faqSummaryItems: [FaqSummary]? = nil, nextToken: String? = nil) { self.faqSummaryItems = faqSummaryItems self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case faqSummaryItems = "FaqSummaryItems" case nextToken = "NextToken" } } public struct ListGroupsOlderThanOrderingIdRequest: AWSEncodableShape { /// The identifier of the data source for getting a list of groups mapped to users before a given ordering timestamp identifier. public let dataSourceId: String? /// The identifier of the index for getting a list of groups mapped to users before a given ordering or timestamp identifier. public let indexId: String /// The maximum number of returned groups that are mapped to users before a given ordering or timestamp identifier. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of groups that are mapped to users before a given ordering or timestamp identifier. public let nextToken: String? /// The timestamp identifier used for the latest PUT or DELETE action for mapping users to their groups. public let orderingId: Int64 public init(dataSourceId: String? = nil, indexId: String, maxResults: Int? = nil, nextToken: String? = nil, orderingId: Int64) { self.dataSourceId = dataSourceId self.indexId = indexId self.maxResults = maxResults self.nextToken = nextToken self.orderingId = orderingId } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.orderingId, name: "orderingId", parent: name, max: 32_535_158_400_000) try self.validate(self.orderingId, name: "orderingId", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case indexId = "IndexId" case maxResults = "MaxResults" case nextToken = "NextToken" case orderingId = "OrderingId" } } public struct ListGroupsOlderThanOrderingIdResponse: AWSDecodableShape { /// Summary information for list of groups that are mapped to users before a given ordering or timestamp identifier. public let groupsSummaries: [GroupSummary]? /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of groups that are mapped to users before a given ordering or timestamp identifier. public let nextToken: String? public init(groupsSummaries: [GroupSummary]? = nil, nextToken: String? = nil) { self.groupsSummaries = groupsSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case groupsSummaries = "GroupsSummaries" case nextToken = "NextToken" } } public struct ListIndicesRequest: AWSEncodableShape { /// The maximum number of data sources to return. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of indexes (DataSourceSummaryItems). public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListIndicesResponse: AWSDecodableShape { /// An array of summary information for one or more indexes. public let indexConfigurationSummaryItems: [IndexConfigurationSummary]? /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of indexes. public let nextToken: String? public init(indexConfigurationSummaryItems: [IndexConfigurationSummary]? = nil, nextToken: String? = nil) { self.indexConfigurationSummaryItems = indexConfigurationSummaryItems self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case indexConfigurationSummaryItems = "IndexConfigurationSummaryItems" case nextToken = "NextToken" } } public struct ListQuerySuggestionsBlockListsRequest: AWSEncodableShape { /// The identifier of the index for a list of all block lists that exist for that index. For information on the current quota limits for block lists, see Quotas for Amazon Kendra. public let indexId: String /// The maximum number of block lists to return. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of block lists (BlockListSummaryItems). public let nextToken: String? public init(indexId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.indexId = indexId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListQuerySuggestionsBlockListsResponse: AWSDecodableShape { /// Summary items for a block list. This includes summary items on the block list ID, block list name, when the block list was created, when the block list was last updated, and the count of block words/phrases in the block list. For information on the current quota limits for block lists, see Quotas for Amazon Kendra. public let blockListSummaryItems: [QuerySuggestionsBlockListSummary]? /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of block lists. public let nextToken: String? public init(blockListSummaryItems: [QuerySuggestionsBlockListSummary]? = nil, nextToken: String? = nil) { self.blockListSummaryItems = blockListSummaryItems self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case blockListSummaryItems = "BlockListSummaryItems" case nextToken = "NextToken" } } public struct ListTagsForResourceRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the index, FAQ, or data source to get a list of tags for. public let resourceARN: String public init(resourceARN: String) { self.resourceARN = resourceARN } public func validate(name: String) throws { try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011) try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case resourceARN = "ResourceARN" } } public struct ListTagsForResourceResponse: AWSDecodableShape { /// A list of tags associated with the index, FAQ, or data source. public let tags: [Tag]? public init(tags: [Tag]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags = "Tags" } } public struct ListThesauriRequest: AWSEncodableShape { /// The identifier of the index associated with the thesaurus to list. public let indexId: String /// The maximum number of thesauri to return. public let maxResults: Int? /// If the previous response was incomplete (because there is more data to retrieve), Amazon Kendra returns a pagination token in the response. You can use this pagination token to retrieve the next set of thesauri (ThesaurusSummaryItems). public let nextToken: String? public init(indexId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.indexId = indexId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 800) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case indexId = "IndexId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListThesauriResponse: AWSDecodableShape { /// If the response is truncated, Amazon Kendra returns this token that you can use in the subsequent request to retrieve the next set of thesauri. public let nextToken: String? /// An array of summary information for a thesaurus or multiple thesauri. public let thesaurusSummaryItems: [ThesaurusSummary]? public init(nextToken: String? = nil, thesaurusSummaryItems: [ThesaurusSummary]? = nil) { self.nextToken = nextToken self.thesaurusSummaryItems = thesaurusSummaryItems } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case thesaurusSummaryItems = "ThesaurusSummaryItems" } } public struct MemberGroup: AWSEncodableShape { /// The identifier of the data source for the sub group you want to map to a group. public let dataSourceId: String? /// The identifier of the sub group you want to map to a group. public let groupId: String public init(dataSourceId: String? = nil, groupId: String) { self.dataSourceId = dataSourceId self.groupId = groupId } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.groupId, name: "groupId", parent: name, max: 1024) try self.validate(self.groupId, name: "groupId", parent: name, min: 1) try self.validate(self.groupId, name: "groupId", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case groupId = "GroupId" } } public struct MemberUser: AWSEncodableShape { /// The identifier of the user you want to map to a group. public let userId: String public init(userId: String) { self.userId = userId } public func validate(name: String) throws { try self.validate(self.userId, name: "userId", parent: name, max: 1024) try self.validate(self.userId, name: "userId", parent: name, min: 1) try self.validate(self.userId, name: "userId", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case userId = "UserId" } } public struct OneDriveConfiguration: AWSEncodableShape & AWSDecodableShape { /// A Boolean value that specifies whether local groups are disabled (True) or enabled (False). public let disableLocalGroups: Bool? /// List of regular expressions applied to documents. Items that match the exclusion pattern are not indexed. If you provide both an inclusion pattern and an exclusion pattern, any item that matches the exclusion pattern isn't indexed. The exclusion pattern is applied to the file name. public let exclusionPatterns: [String]? /// A list of DataSourceToIndexFieldMapping objects that map Microsoft OneDrive fields to custom fields in the Amazon Kendra index. You must first create the index fields before you map OneDrive fields. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// A list of regular expression patterns. Documents that match the pattern are included in the index. Documents that don't match the pattern are excluded from the index. If a document matches both an inclusion pattern and an exclusion pattern, the document is not included in the index. The exclusion pattern is applied to the file name. public let inclusionPatterns: [String]? /// A list of user accounts whose documents should be indexed. public let oneDriveUsers: OneDriveUsers /// The Amazon Resource Name (ARN) of an Secrets Managersecret that contains the user name and password to connect to OneDrive. The user namd should be the application ID for the OneDrive application, and the password is the application key for the OneDrive application. public let secretArn: String /// The Azure Active Directory domain of the organization. public let tenantDomain: String public init(disableLocalGroups: Bool? = nil, exclusionPatterns: [String]? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, inclusionPatterns: [String]? = nil, oneDriveUsers: OneDriveUsers, secretArn: String, tenantDomain: String) { self.disableLocalGroups = disableLocalGroups self.exclusionPatterns = exclusionPatterns self.fieldMappings = fieldMappings self.inclusionPatterns = inclusionPatterns self.oneDriveUsers = oneDriveUsers self.secretArn = secretArn self.tenantDomain = tenantDomain } public func validate(name: String) throws { try self.exclusionPatterns?.forEach { try validate($0, name: "exclusionPatterns[]", parent: name, max: 150) try validate($0, name: "exclusionPatterns[]", parent: name, min: 1) } try self.validate(self.exclusionPatterns, name: "exclusionPatterns", parent: name, max: 100) try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.inclusionPatterns?.forEach { try validate($0, name: "inclusionPatterns[]", parent: name, max: 150) try validate($0, name: "inclusionPatterns[]", parent: name, min: 1) } try self.validate(self.inclusionPatterns, name: "inclusionPatterns", parent: name, max: 100) try self.oneDriveUsers.validate(name: "\(name).oneDriveUsers") try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.tenantDomain, name: "tenantDomain", parent: name, max: 256) try self.validate(self.tenantDomain, name: "tenantDomain", parent: name, min: 1) try self.validate(self.tenantDomain, name: "tenantDomain", parent: name, pattern: "^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-z]{2,}$") } private enum CodingKeys: String, CodingKey { case disableLocalGroups = "DisableLocalGroups" case exclusionPatterns = "ExclusionPatterns" case fieldMappings = "FieldMappings" case inclusionPatterns = "InclusionPatterns" case oneDriveUsers = "OneDriveUsers" case secretArn = "SecretArn" case tenantDomain = "TenantDomain" } } public struct OneDriveUsers: AWSEncodableShape & AWSDecodableShape { /// A list of users whose documents should be indexed. Specify the user names in email format, for example, username@tenantdomain. If you need to index the documents of more than 100 users, use the OneDriveUserS3Path field to specify the location of a file containing a list of users. public let oneDriveUserList: [String]? /// The S3 bucket location of a file containing a list of users whose documents should be indexed. public let oneDriveUserS3Path: S3Path? public init(oneDriveUserList: [String]? = nil, oneDriveUserS3Path: S3Path? = nil) { self.oneDriveUserList = oneDriveUserList self.oneDriveUserS3Path = oneDriveUserS3Path } public func validate(name: String) throws { try self.oneDriveUserList?.forEach { try validate($0, name: "oneDriveUserList[]", parent: name, max: 256) try validate($0, name: "oneDriveUserList[]", parent: name, min: 1) try validate($0, name: "oneDriveUserList[]", parent: name, pattern: "^(?!\\s).+@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$") } try self.validate(self.oneDriveUserList, name: "oneDriveUserList", parent: name, max: 100) try self.validate(self.oneDriveUserList, name: "oneDriveUserList", parent: name, min: 1) try self.oneDriveUserS3Path?.validate(name: "\(name).oneDriveUserS3Path") } private enum CodingKeys: String, CodingKey { case oneDriveUserList = "OneDriveUserList" case oneDriveUserS3Path = "OneDriveUserS3Path" } } public struct Principal: AWSEncodableShape { /// Whether to allow or deny access to the principal. public let access: ReadAccessType /// The identifier of the data source the principal should access documents from. public let dataSourceId: String? /// The name of the user or group. public let name: String /// The type of principal. public let type: PrincipalType public init(access: ReadAccessType, dataSourceId: String? = nil, name: String, type: PrincipalType) { self.access = access self.dataSourceId = dataSourceId self.name = name self.type = type } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.name, name: "name", parent: name, max: 200) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case access = "Access" case dataSourceId = "DataSourceId" case name = "Name" case type = "Type" } } public struct ProxyConfiguration: AWSEncodableShape & AWSDecodableShape { /// Your secret ARN, which you can create in AWS Secrets Manager The credentials are optional. You use a secret if web proxy credentials are required to connect to a website host. Amazon Kendra currently support basic authentication to connect to a web proxy server. The secret stores your credentials. public let credentials: String? /// The name of the website host you want to connect to via a web proxy server. For example, the host name of https://a.example.com/page1.html is "a.example.com". public let host: String /// The port number of the website host you want to connect to via a web proxy server. For example, the port for https://a.example.com/page1.html is 443, the standard port for HTTPS. public let port: Int public init(credentials: String? = nil, host: String, port: Int) { self.credentials = credentials self.host = host self.port = port } public func validate(name: String) throws { try self.validate(self.credentials, name: "credentials", parent: name, max: 1284) try self.validate(self.credentials, name: "credentials", parent: name, min: 1) try self.validate(self.credentials, name: "credentials", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.host, name: "host", parent: name, max: 253) try self.validate(self.host, name: "host", parent: name, min: 1) try self.validate(self.host, name: "host", parent: name, pattern: "^([^\\s]*)$") try self.validate(self.port, name: "port", parent: name, max: 65535) try self.validate(self.port, name: "port", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case credentials = "Credentials" case host = "Host" case port = "Port" } } public struct PutPrincipalMappingRequest: AWSEncodableShape { /// The identifier of the data source you want to map users to their groups. This is useful if a group is tied to multiple data sources, but you only want the group to access documents of a certain data source. For example, the groups "Research", "Engineering", and "Sales and Marketing" are all tied to the company's documents stored in the data sources Confluence and Salesforce. However, "Sales and Marketing" team only needs access to customer-related documents stored in Salesforce. public let dataSourceId: String? /// The identifier of the group you want to map its users to. public let groupId: String /// The list that contains your users or sub groups that belong the same group. For example, the group "Company" includes the user "CEO" and the sub groups "Research", "Engineering", and "Sales and Marketing". If you have more than 1000 users and/or sub groups for a single group, you need to provide the path to the S3 file that lists your users and sub groups for a group. Your sub groups can contain more than 1000 users, but the list of sub groups that belong to a group (and/or users) must be no more than 1000. public let groupMembers: GroupMembers /// The identifier of the index you want to map users to their groups. public let indexId: String /// The timestamp identifier you specify to ensure Amazon Kendra does not override the latest PUT action with previous actions. The highest number ID, which is the ordering ID, is the latest action you want to process and apply on top of other actions with lower number IDs. This prevents previous actions with lower number IDs from possibly overriding the latest action. The ordering ID can be the UNIX time of the last update you made to a group members list. You would then provide this list when calling PutPrincipalMapping. This ensures your PUT action for that updated group with the latest members list doesn't get overwritten by earlier PUT actions for the same group which are yet to be processed. The default ordering ID is the current UNIX time in milliseconds that the action was received by Amazon Kendra. public let orderingId: Int64? /// The Amazon Resource Name (ARN) of a role that has access to the S3 file that contains your list of users or sub groups that belong to a group. For more information, see IAM roles for Amazon Kendra. public let roleArn: String? public init(dataSourceId: String? = nil, groupId: String, groupMembers: GroupMembers, indexId: String, orderingId: Int64? = nil, roleArn: String? = nil) { self.dataSourceId = dataSourceId self.groupId = groupId self.groupMembers = groupMembers self.indexId = indexId self.orderingId = orderingId self.roleArn = roleArn } public func validate(name: String) throws { try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, max: 100) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, min: 1) try self.validate(self.dataSourceId, name: "dataSourceId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.groupId, name: "groupId", parent: name, max: 1024) try self.validate(self.groupId, name: "groupId", parent: name, min: 1) try self.validate(self.groupId, name: "groupId", parent: name, pattern: "^\\P{C}*$") try self.groupMembers.validate(name: "\(name).groupMembers") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.orderingId, name: "orderingId", parent: name, max: 32_535_158_400_000) try self.validate(self.orderingId, name: "orderingId", parent: name, min: 0) try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") } private enum CodingKeys: String, CodingKey { case dataSourceId = "DataSourceId" case groupId = "GroupId" case groupMembers = "GroupMembers" case indexId = "IndexId" case orderingId = "OrderingId" case roleArn = "RoleArn" } } public struct QueryRequest: AWSEncodableShape { /// Enables filtered searches based on document attributes. You can only provide one attribute filter; however, the AndAllFilters, NotFilter, and OrAllFilters parameters contain a list of other filters. The AttributeFilter parameter enables you to create a set of filtering rules that a document must satisfy to be included in the query results. public let attributeFilter: AttributeFilter? /// Overrides relevance tuning configurations of fields or attributes set at the index level. If you use this API to override the relevance tuning configured at the index level, but there is no relevance tuning configured at the index level, then Amazon Kendra does not apply any relevance tuning. If there is relevance tuning configured at the index level, but you do not use this API to override any relevance tuning in the index, then Amazon Kendra uses the relevance tuning that is configured at the index level. If there is relevance tuning configured for fields at the index level, but you use this API to override only some of these fields, then for the fields you did not override, the importance is set to 1. public let documentRelevanceOverrideConfigurations: [DocumentRelevanceConfiguration]? /// An array of documents attributes. Amazon Kendra returns a count for each attribute key specified. You can use this information to help narrow the search for your user. public let facets: [Facet]? /// The unique identifier of the index to search. The identifier is returned in the response from the CreateIndex operation. public let indexId: String /// Query results are returned in pages the size of the PageSize parameter. By default, Amazon Kendra returns the first page of results. Use this parameter to get result pages after the first one. public let pageNumber: Int? /// Sets the number of results that are returned in each page of results. The default page size is 10. The maximum number of results returned is 100. If you ask for more than 100 results, only 100 are returned. public let pageSize: Int? /// Sets the type of query. Only results for the specified query type are returned. public let queryResultTypeFilter: QueryResultType? /// The text to search for. public let queryText: String /// An array of document attributes to include in the response. No other document attributes are included in the response. By default all document attributes are included in the response. public let requestedDocumentAttributes: [String]? /// Provides information that determines how the results of the query are sorted. You can set the field that Amazon Kendra should sort the results on, and specify whether the results should be sorted in ascending or descending order. In the case of ties in sorting the results, the results are sorted by relevance. If you don't provide sorting configuration, the results are sorted by the relevance that Amazon Kendra determines for the result. public let sortingConfiguration: SortingConfiguration? /// The user context token or user and group information. public let userContext: UserContext? /// Provides an identifier for a specific user. The VisitorId should be a unique identifier, such as a GUID. Don't use personally identifiable information, such as the user's email address, as the VisitorId. public let visitorId: String? public init(attributeFilter: AttributeFilter? = nil, documentRelevanceOverrideConfigurations: [DocumentRelevanceConfiguration]? = nil, facets: [Facet]? = nil, indexId: String, pageNumber: Int? = nil, pageSize: Int? = nil, queryResultTypeFilter: QueryResultType? = nil, queryText: String, requestedDocumentAttributes: [String]? = nil, sortingConfiguration: SortingConfiguration? = nil, userContext: UserContext? = nil, visitorId: String? = nil) { self.attributeFilter = attributeFilter self.documentRelevanceOverrideConfigurations = documentRelevanceOverrideConfigurations self.facets = facets self.indexId = indexId self.pageNumber = pageNumber self.pageSize = pageSize self.queryResultTypeFilter = queryResultTypeFilter self.queryText = queryText self.requestedDocumentAttributes = requestedDocumentAttributes self.sortingConfiguration = sortingConfiguration self.userContext = userContext self.visitorId = visitorId } public func validate(name: String) throws { try self.attributeFilter?.validate(name: "\(name).attributeFilter") try self.documentRelevanceOverrideConfigurations?.forEach { try $0.validate(name: "\(name).documentRelevanceOverrideConfigurations[]") } try self.validate(self.documentRelevanceOverrideConfigurations, name: "documentRelevanceOverrideConfigurations", parent: name, max: 500) try self.facets?.forEach { try $0.validate(name: "\(name).facets[]") } try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.queryText, name: "queryText", parent: name, max: 1000) try self.validate(self.queryText, name: "queryText", parent: name, min: 1) try self.validate(self.queryText, name: "queryText", parent: name, pattern: "^\\P{C}*$") try self.requestedDocumentAttributes?.forEach { try validate($0, name: "requestedDocumentAttributes[]", parent: name, max: 200) try validate($0, name: "requestedDocumentAttributes[]", parent: name, min: 1) try validate($0, name: "requestedDocumentAttributes[]", parent: name, pattern: "^[a-zA-Z0-9_][a-zA-Z0-9_-]*$") } try self.validate(self.requestedDocumentAttributes, name: "requestedDocumentAttributes", parent: name, max: 100) try self.validate(self.requestedDocumentAttributes, name: "requestedDocumentAttributes", parent: name, min: 1) try self.sortingConfiguration?.validate(name: "\(name).sortingConfiguration") try self.userContext?.validate(name: "\(name).userContext") try self.validate(self.visitorId, name: "visitorId", parent: name, max: 256) try self.validate(self.visitorId, name: "visitorId", parent: name, min: 1) try self.validate(self.visitorId, name: "visitorId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") } private enum CodingKeys: String, CodingKey { case attributeFilter = "AttributeFilter" case documentRelevanceOverrideConfigurations = "DocumentRelevanceOverrideConfigurations" case facets = "Facets" case indexId = "IndexId" case pageNumber = "PageNumber" case pageSize = "PageSize" case queryResultTypeFilter = "QueryResultTypeFilter" case queryText = "QueryText" case requestedDocumentAttributes = "RequestedDocumentAttributes" case sortingConfiguration = "SortingConfiguration" case userContext = "UserContext" case visitorId = "VisitorId" } } public struct QueryResult: AWSDecodableShape { /// Contains the facet results. A FacetResult contains the counts for each attribute key that was specified in the Facets input parameter. public let facetResults: [FacetResult]? /// The unique identifier for the search. You use QueryId to identify the search when using the feedback API. public let queryId: String? /// The results of the search. public let resultItems: [QueryResultItem]? /// The total number of items found by the search; however, you can only retrieve up to 100 items. For example, if the search found 192 items, you can only retrieve the first 100 of the items. public let totalNumberOfResults: Int? public init(facetResults: [FacetResult]? = nil, queryId: String? = nil, resultItems: [QueryResultItem]? = nil, totalNumberOfResults: Int? = nil) { self.facetResults = facetResults self.queryId = queryId self.resultItems = resultItems self.totalNumberOfResults = totalNumberOfResults } private enum CodingKeys: String, CodingKey { case facetResults = "FacetResults" case queryId = "QueryId" case resultItems = "ResultItems" case totalNumberOfResults = "TotalNumberOfResults" } } public struct QueryResultItem: AWSDecodableShape { /// One or more additional attributes associated with the query result. public let additionalAttributes: [AdditionalResultAttribute]? /// An array of document attributes for the document that the query result maps to. For example, the document author (Author) or the source URI (SourceUri) of the document. public let documentAttributes: [DocumentAttribute]? /// An extract of the text in the document. Contains information about highlighting the relevant terms in the excerpt. public let documentExcerpt: TextWithHighlights? /// The unique identifier for the document. public let documentId: String? /// The title of the document. Contains the text of the title and information for highlighting the relevant terms in the title. public let documentTitle: TextWithHighlights? /// The URI of the original location of the document. public let documentURI: String? /// A token that identifies a particular result from a particular query. Use this token to provide click-through feedback for the result. For more information, see Submitting feedback . public let feedbackToken: String? /// The unique identifier for the query result. public let id: String? /// Indicates the confidence that Amazon Kendra has that a result matches the query that you provided. Each result is placed into a bin that indicates the confidence, VERY_HIGH, HIGH, MEDIUM and LOW. You can use the score to determine if a response meets the confidence needed for your application. The field is only set to LOW when the Type field is set to DOCUMENT and Amazon Kendra is not confident that the result matches the query. public let scoreAttributes: ScoreAttributes? /// The type of document. public let type: QueryResultType? public init(additionalAttributes: [AdditionalResultAttribute]? = nil, documentAttributes: [DocumentAttribute]? = nil, documentExcerpt: TextWithHighlights? = nil, documentId: String? = nil, documentTitle: TextWithHighlights? = nil, documentURI: String? = nil, feedbackToken: String? = nil, id: String? = nil, scoreAttributes: ScoreAttributes? = nil, type: QueryResultType? = nil) { self.additionalAttributes = additionalAttributes self.documentAttributes = documentAttributes self.documentExcerpt = documentExcerpt self.documentId = documentId self.documentTitle = documentTitle self.documentURI = documentURI self.feedbackToken = feedbackToken self.id = id self.scoreAttributes = scoreAttributes self.type = type } private enum CodingKeys: String, CodingKey { case additionalAttributes = "AdditionalAttributes" case documentAttributes = "DocumentAttributes" case documentExcerpt = "DocumentExcerpt" case documentId = "DocumentId" case documentTitle = "DocumentTitle" case documentURI = "DocumentURI" case feedbackToken = "FeedbackToken" case id = "Id" case scoreAttributes = "ScoreAttributes" case type = "Type" } } public struct QuerySuggestionsBlockListSummary: AWSDecodableShape { /// The date-time summary information for a query suggestions block list was last created. public let createdAt: Date? /// The identifier of a block list. public let id: String? /// The number of items in the block list file. public let itemCount: Int? /// The name of the block list. public let name: String? /// The status of the block list. public let status: QuerySuggestionsBlockListStatus? /// The date-time the block list was last updated. public let updatedAt: Date? public init(createdAt: Date? = nil, id: String? = nil, itemCount: Int? = nil, name: String? = nil, status: QuerySuggestionsBlockListStatus? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.id = id self.itemCount = itemCount self.name = name self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case id = "Id" case itemCount = "ItemCount" case name = "Name" case status = "Status" case updatedAt = "UpdatedAt" } } public struct Relevance: AWSEncodableShape & AWSDecodableShape { /// Specifies the time period that the boost applies to. For example, to make the boost apply to documents with the field value within the last month, you would use "2628000s". Once the field value is beyond the specified range, the effect of the boost drops off. The higher the importance, the faster the effect drops off. If you don't specify a value, the default is 3 months. The value of the field is a numeric string followed by the character "s", for example "86400s" for one day, or "604800s" for one week. Only applies to DATE fields. public let duration: String? /// Indicates that this field determines how "fresh" a document is. For example, if document 1 was created on November 5, and document 2 was created on October 31, document 1 is "fresher" than document 2. You can only set the Freshness field on one DATE type field. Only applies to DATE fields. public let freshness: Bool? /// The relative importance of the field in the search. Larger numbers provide more of a boost than smaller numbers. public let importance: Int? /// Determines how values should be interpreted. When the RankOrder field is ASCENDING, higher numbers are better. For example, a document with a rating score of 10 is higher ranking than a document with a rating score of 1. When the RankOrder field is DESCENDING, lower numbers are better. For example, in a task tracking application, a priority 1 task is more important than a priority 5 task. Only applies to LONG and DOUBLE fields. public let rankOrder: Order? /// A list of values that should be given a different boost when they appear in the result list. For example, if you are boosting a field called "department," query terms that match the department field are boosted in the result. However, you can add entries from the department field to boost documents with those values higher. For example, you can add entries to the map with names of departments. If you add "HR",5 and "Legal",3 those departments are given special attention when they appear in the metadata of a document. When those terms appear they are given the specified importance instead of the regular importance for the boost. public let valueImportanceMap: [String: Int]? public init(duration: String? = nil, freshness: Bool? = nil, importance: Int? = nil, rankOrder: Order? = nil, valueImportanceMap: [String: Int]? = nil) { self.duration = duration self.freshness = freshness self.importance = importance self.rankOrder = rankOrder self.valueImportanceMap = valueImportanceMap } public func validate(name: String) throws { try self.validate(self.duration, name: "duration", parent: name, max: 10) try self.validate(self.duration, name: "duration", parent: name, min: 1) try self.validate(self.duration, name: "duration", parent: name, pattern: "^[0-9]+[s]$") try self.validate(self.importance, name: "importance", parent: name, max: 10) try self.validate(self.importance, name: "importance", parent: name, min: 1) try self.valueImportanceMap?.forEach { try validate($0.key, name: "valueImportanceMap.key", parent: name, max: 50) try validate($0.key, name: "valueImportanceMap.key", parent: name, min: 1) try validate($0.value, name: "valueImportanceMap[\"\($0.key)\"]", parent: name, max: 10) try validate($0.value, name: "valueImportanceMap[\"\($0.key)\"]", parent: name, min: 1) } } private enum CodingKeys: String, CodingKey { case duration = "Duration" case freshness = "Freshness" case importance = "Importance" case rankOrder = "RankOrder" case valueImportanceMap = "ValueImportanceMap" } } public struct RelevanceFeedback: AWSEncodableShape { /// Whether to document was relevant or not relevant to the search. public let relevanceValue: RelevanceType /// The unique identifier of the search result that the user provided relevance feedback for. public let resultId: String public init(relevanceValue: RelevanceType, resultId: String) { self.relevanceValue = relevanceValue self.resultId = resultId } public func validate(name: String) throws { try self.validate(self.resultId, name: "resultId", parent: name, max: 73) try self.validate(self.resultId, name: "resultId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case relevanceValue = "RelevanceValue" case resultId = "ResultId" } } public struct S3DataSourceConfiguration: AWSEncodableShape & AWSDecodableShape { /// Provides the path to the S3 bucket that contains the user context filtering files for the data source. For the format of the file, see Access control for S3 data sources. public let accessControlListConfiguration: AccessControlListConfiguration? /// The name of the bucket that contains the documents. public let bucketName: String public let documentsMetadataConfiguration: DocumentsMetadataConfiguration? /// A list of glob patterns for documents that should not be indexed. If a document that matches an inclusion prefix or inclusion pattern also matches an exclusion pattern, the document is not indexed. Some examples are: *.png , *.jpg will exclude all PNG and JPEG image files in a directory (files with the extensions .png and .jpg). *internal* will exclude all files in a directory that contain 'internal' in the file name, such as 'internal', 'internal_only', 'company_internal'. **/*internal* will exclude all internal-related files in a directory and its subdirectories. public let exclusionPatterns: [String]? /// A list of glob patterns for documents that should be indexed. If a document that matches an inclusion pattern also matches an exclusion pattern, the document is not indexed. Some examples are: *.txt will include all text files in a directory (files with the extension .txt). **/*.txt will include all text files in a directory and its subdirectories. *tax* will include all files in a directory that contain 'tax' in the file name, such as 'tax', 'taxes', 'income_tax'. public let inclusionPatterns: [String]? /// A list of S3 prefixes for the documents that should be included in the index. public let inclusionPrefixes: [String]? public init(accessControlListConfiguration: AccessControlListConfiguration? = nil, bucketName: String, documentsMetadataConfiguration: DocumentsMetadataConfiguration? = nil, exclusionPatterns: [String]? = nil, inclusionPatterns: [String]? = nil, inclusionPrefixes: [String]? = nil) { self.accessControlListConfiguration = accessControlListConfiguration self.bucketName = bucketName self.documentsMetadataConfiguration = documentsMetadataConfiguration self.exclusionPatterns = exclusionPatterns self.inclusionPatterns = inclusionPatterns self.inclusionPrefixes = inclusionPrefixes } public func validate(name: String) throws { try self.accessControlListConfiguration?.validate(name: "\(name).accessControlListConfiguration") try self.validate(self.bucketName, name: "bucketName", parent: name, max: 63) try self.validate(self.bucketName, name: "bucketName", parent: name, min: 3) try self.validate(self.bucketName, name: "bucketName", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$") try self.documentsMetadataConfiguration?.validate(name: "\(name).documentsMetadataConfiguration") try self.exclusionPatterns?.forEach { try validate($0, name: "exclusionPatterns[]", parent: name, max: 150) try validate($0, name: "exclusionPatterns[]", parent: name, min: 1) } try self.validate(self.exclusionPatterns, name: "exclusionPatterns", parent: name, max: 100) try self.inclusionPatterns?.forEach { try validate($0, name: "inclusionPatterns[]", parent: name, max: 150) try validate($0, name: "inclusionPatterns[]", parent: name, min: 1) } try self.validate(self.inclusionPatterns, name: "inclusionPatterns", parent: name, max: 100) try self.inclusionPrefixes?.forEach { try validate($0, name: "inclusionPrefixes[]", parent: name, max: 150) try validate($0, name: "inclusionPrefixes[]", parent: name, min: 1) } try self.validate(self.inclusionPrefixes, name: "inclusionPrefixes", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case accessControlListConfiguration = "AccessControlListConfiguration" case bucketName = "BucketName" case documentsMetadataConfiguration = "DocumentsMetadataConfiguration" case exclusionPatterns = "ExclusionPatterns" case inclusionPatterns = "InclusionPatterns" case inclusionPrefixes = "InclusionPrefixes" } } public struct S3Path: AWSEncodableShape & AWSDecodableShape { /// The name of the S3 bucket that contains the file. public let bucket: String /// The name of the file. public let key: String public init(bucket: String, key: String) { self.bucket = bucket self.key = key } public func validate(name: String) throws { try self.validate(self.bucket, name: "bucket", parent: name, max: 63) try self.validate(self.bucket, name: "bucket", parent: name, min: 3) try self.validate(self.bucket, name: "bucket", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$") try self.validate(self.key, name: "key", parent: name, max: 1024) try self.validate(self.key, name: "key", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case bucket = "Bucket" case key = "Key" } } public struct SalesforceChatterFeedConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the column in the Salesforce FeedItem table that contains the content to index. Typically this is the Body column. public let documentDataFieldName: String /// The name of the column in the Salesforce FeedItem table that contains the title of the document. This is typically the Title column. public let documentTitleFieldName: String? /// Maps fields from a Salesforce chatter feed into Amazon Kendra index fields. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// Filters the documents in the feed based on status of the user. When you specify ACTIVE_USERS only documents from users who have an active account are indexed. When you specify STANDARD_USER only documents for Salesforce standard users are documented. You can specify both. public let includeFilterTypes: [SalesforceChatterFeedIncludeFilterType]? public init(documentDataFieldName: String, documentTitleFieldName: String? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, includeFilterTypes: [SalesforceChatterFeedIncludeFilterType]? = nil) { self.documentDataFieldName = documentDataFieldName self.documentTitleFieldName = documentTitleFieldName self.fieldMappings = fieldMappings self.includeFilterTypes = includeFilterTypes } public func validate(name: String) throws { try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, max: 100) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, min: 1) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.validate(self.includeFilterTypes, name: "includeFilterTypes", parent: name, max: 2) try self.validate(self.includeFilterTypes, name: "includeFilterTypes", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case documentDataFieldName = "DocumentDataFieldName" case documentTitleFieldName = "DocumentTitleFieldName" case fieldMappings = "FieldMappings" case includeFilterTypes = "IncludeFilterTypes" } } public struct SalesforceConfiguration: AWSEncodableShape & AWSDecodableShape { /// Specifies configuration information for Salesforce chatter feeds. public let chatterFeedConfiguration: SalesforceChatterFeedConfiguration? /// Indicates whether Amazon Kendra should index attachments to Salesforce objects. public let crawlAttachments: Bool? /// A list of regular expression patterns. Documents that match the patterns are excluded from the index. Documents that don't match the patterns are included in the index. If a document matches both an exclusion pattern and an inclusion pattern, the document is not included in the index. The regex is applied to the name of the attached file. public let excludeAttachmentFilePatterns: [String]? /// A list of regular expression patterns. Documents that match the patterns are included in the index. Documents that don't match the patterns are excluded from the index. If a document matches both an inclusion pattern and an exclusion pattern, the document is not included in the index. The regex is applied to the name of the attached file. public let includeAttachmentFilePatterns: [String]? /// Specifies configuration information for the knowledge article types that Amazon Kendra indexes. Amazon Kendra indexes standard knowledge articles and the standard fields of knowledge articles, or the custom fields of custom knowledge articles, but not both. public let knowledgeArticleConfiguration: SalesforceKnowledgeArticleConfiguration? /// The Amazon Resource Name (ARN) of an Secrets Managersecret that contains the key/value pairs required to connect to your Salesforce instance. The secret must contain a JSON structure with the following keys: authenticationUrl - The OAUTH endpoint that Amazon Kendra connects to get an OAUTH token. consumerKey - The application public key generated when you created your Salesforce application. consumerSecret - The application private key generated when you created your Salesforce application. password - The password associated with the user logging in to the Salesforce instance. securityToken - The token associated with the user account logging in to the Salesforce instance. username - The user name of the user logging in to the Salesforce instance. public let secretArn: String /// The instance URL for the Salesforce site that you want to index. public let serverUrl: String /// Provides configuration information for processing attachments to Salesforce standard objects. public let standardObjectAttachmentConfiguration: SalesforceStandardObjectAttachmentConfiguration? /// Specifies the Salesforce standard objects that Amazon Kendra indexes. public let standardObjectConfigurations: [SalesforceStandardObjectConfiguration]? public init(chatterFeedConfiguration: SalesforceChatterFeedConfiguration? = nil, crawlAttachments: Bool? = nil, excludeAttachmentFilePatterns: [String]? = nil, includeAttachmentFilePatterns: [String]? = nil, knowledgeArticleConfiguration: SalesforceKnowledgeArticleConfiguration? = nil, secretArn: String, serverUrl: String, standardObjectAttachmentConfiguration: SalesforceStandardObjectAttachmentConfiguration? = nil, standardObjectConfigurations: [SalesforceStandardObjectConfiguration]? = nil) { self.chatterFeedConfiguration = chatterFeedConfiguration self.crawlAttachments = crawlAttachments self.excludeAttachmentFilePatterns = excludeAttachmentFilePatterns self.includeAttachmentFilePatterns = includeAttachmentFilePatterns self.knowledgeArticleConfiguration = knowledgeArticleConfiguration self.secretArn = secretArn self.serverUrl = serverUrl self.standardObjectAttachmentConfiguration = standardObjectAttachmentConfiguration self.standardObjectConfigurations = standardObjectConfigurations } public func validate(name: String) throws { try self.chatterFeedConfiguration?.validate(name: "\(name).chatterFeedConfiguration") try self.excludeAttachmentFilePatterns?.forEach { try validate($0, name: "excludeAttachmentFilePatterns[]", parent: name, max: 150) try validate($0, name: "excludeAttachmentFilePatterns[]", parent: name, min: 1) } try self.validate(self.excludeAttachmentFilePatterns, name: "excludeAttachmentFilePatterns", parent: name, max: 100) try self.includeAttachmentFilePatterns?.forEach { try validate($0, name: "includeAttachmentFilePatterns[]", parent: name, max: 150) try validate($0, name: "includeAttachmentFilePatterns[]", parent: name, min: 1) } try self.validate(self.includeAttachmentFilePatterns, name: "includeAttachmentFilePatterns", parent: name, max: 100) try self.knowledgeArticleConfiguration?.validate(name: "\(name).knowledgeArticleConfiguration") try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.validate(self.serverUrl, name: "serverUrl", parent: name, max: 2048) try self.validate(self.serverUrl, name: "serverUrl", parent: name, min: 1) try self.validate(self.serverUrl, name: "serverUrl", parent: name, pattern: "^(https?|ftp|file):\\/\\/([^\\s]*)$") try self.standardObjectAttachmentConfiguration?.validate(name: "\(name).standardObjectAttachmentConfiguration") try self.standardObjectConfigurations?.forEach { try $0.validate(name: "\(name).standardObjectConfigurations[]") } try self.validate(self.standardObjectConfigurations, name: "standardObjectConfigurations", parent: name, max: 17) try self.validate(self.standardObjectConfigurations, name: "standardObjectConfigurations", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case chatterFeedConfiguration = "ChatterFeedConfiguration" case crawlAttachments = "CrawlAttachments" case excludeAttachmentFilePatterns = "ExcludeAttachmentFilePatterns" case includeAttachmentFilePatterns = "IncludeAttachmentFilePatterns" case knowledgeArticleConfiguration = "KnowledgeArticleConfiguration" case secretArn = "SecretArn" case serverUrl = "ServerUrl" case standardObjectAttachmentConfiguration = "StandardObjectAttachmentConfiguration" case standardObjectConfigurations = "StandardObjectConfigurations" } } public struct SalesforceCustomKnowledgeArticleTypeConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the field in the custom knowledge article that contains the document data to index. public let documentDataFieldName: String /// The name of the field in the custom knowledge article that contains the document title. public let documentTitleFieldName: String? /// One or more objects that map fields in the custom knowledge article to fields in the Amazon Kendra index. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// The name of the configuration. public let name: String public init(documentDataFieldName: String, documentTitleFieldName: String? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, name: String) { self.documentDataFieldName = documentDataFieldName self.documentTitleFieldName = documentTitleFieldName self.fieldMappings = fieldMappings self.name = name } public func validate(name: String) throws { try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, max: 100) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, min: 1) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: String, CodingKey { case documentDataFieldName = "DocumentDataFieldName" case documentTitleFieldName = "DocumentTitleFieldName" case fieldMappings = "FieldMappings" case name = "Name" } } public struct SalesforceKnowledgeArticleConfiguration: AWSEncodableShape & AWSDecodableShape { /// Provides configuration information for custom Salesforce knowledge articles. public let customKnowledgeArticleTypeConfigurations: [SalesforceCustomKnowledgeArticleTypeConfiguration]? /// Specifies the document states that should be included when Amazon Kendra indexes knowledge articles. You must specify at least one state. public let includedStates: [SalesforceKnowledgeArticleState] /// Provides configuration information for standard Salesforce knowledge articles. public let standardKnowledgeArticleTypeConfiguration: SalesforceStandardKnowledgeArticleTypeConfiguration? public init(customKnowledgeArticleTypeConfigurations: [SalesforceCustomKnowledgeArticleTypeConfiguration]? = nil, includedStates: [SalesforceKnowledgeArticleState], standardKnowledgeArticleTypeConfiguration: SalesforceStandardKnowledgeArticleTypeConfiguration? = nil) { self.customKnowledgeArticleTypeConfigurations = customKnowledgeArticleTypeConfigurations self.includedStates = includedStates self.standardKnowledgeArticleTypeConfiguration = standardKnowledgeArticleTypeConfiguration } public func validate(name: String) throws { try self.customKnowledgeArticleTypeConfigurations?.forEach { try $0.validate(name: "\(name).customKnowledgeArticleTypeConfigurations[]") } try self.validate(self.customKnowledgeArticleTypeConfigurations, name: "customKnowledgeArticleTypeConfigurations", parent: name, max: 10) try self.validate(self.customKnowledgeArticleTypeConfigurations, name: "customKnowledgeArticleTypeConfigurations", parent: name, min: 1) try self.validate(self.includedStates, name: "includedStates", parent: name, max: 3) try self.validate(self.includedStates, name: "includedStates", parent: name, min: 1) try self.standardKnowledgeArticleTypeConfiguration?.validate(name: "\(name).standardKnowledgeArticleTypeConfiguration") } private enum CodingKeys: String, CodingKey { case customKnowledgeArticleTypeConfigurations = "CustomKnowledgeArticleTypeConfigurations" case includedStates = "IncludedStates" case standardKnowledgeArticleTypeConfiguration = "StandardKnowledgeArticleTypeConfiguration" } } public struct SalesforceStandardKnowledgeArticleTypeConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the field that contains the document data to index. public let documentDataFieldName: String /// The name of the field that contains the document title. public let documentTitleFieldName: String? /// One or more objects that map fields in the knowledge article to Amazon Kendra index fields. The index field must exist before you can map a Salesforce field to it. public let fieldMappings: [DataSourceToIndexFieldMapping]? public init(documentDataFieldName: String, documentTitleFieldName: String? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil) { self.documentDataFieldName = documentDataFieldName self.documentTitleFieldName = documentTitleFieldName self.fieldMappings = fieldMappings } public func validate(name: String) throws { try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, max: 100) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, min: 1) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case documentDataFieldName = "DocumentDataFieldName" case documentTitleFieldName = "DocumentTitleFieldName" case fieldMappings = "FieldMappings" } } public struct SalesforceStandardObjectAttachmentConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the field used for the document title. public let documentTitleFieldName: String? /// One or more objects that map fields in attachments to Amazon Kendra index fields. public let fieldMappings: [DataSourceToIndexFieldMapping]? public init(documentTitleFieldName: String? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil) { self.documentTitleFieldName = documentTitleFieldName self.fieldMappings = fieldMappings } public func validate(name: String) throws { try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case documentTitleFieldName = "DocumentTitleFieldName" case fieldMappings = "FieldMappings" } } public struct SalesforceStandardObjectConfiguration: AWSEncodableShape & AWSDecodableShape { /// The name of the field in the standard object table that contains the document contents. public let documentDataFieldName: String /// The name of the field in the standard object table that contains the document title. public let documentTitleFieldName: String? /// One or more objects that map fields in the standard object to Amazon Kendra index fields. The index field must exist before you can map a Salesforce field to it. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// The name of the standard object. public let name: SalesforceStandardObjectName public init(documentDataFieldName: String, documentTitleFieldName: String? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, name: SalesforceStandardObjectName) { self.documentDataFieldName = documentDataFieldName self.documentTitleFieldName = documentTitleFieldName self.fieldMappings = fieldMappings self.name = name } public func validate(name: String) throws { try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, max: 100) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, min: 1) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case documentDataFieldName = "DocumentDataFieldName" case documentTitleFieldName = "DocumentTitleFieldName" case fieldMappings = "FieldMappings" case name = "Name" } } public struct ScoreAttributes: AWSDecodableShape { /// A relative ranking for how well the response matches the query. public let scoreConfidence: ScoreConfidence? public init(scoreConfidence: ScoreConfidence? = nil) { self.scoreConfidence = scoreConfidence } private enum CodingKeys: String, CodingKey { case scoreConfidence = "ScoreConfidence" } } public struct Search: AWSEncodableShape & AWSDecodableShape { /// Determines whether the field is returned in the query response. The default is true. public let displayable: Bool? /// Indicates that the field can be used to create search facets, a count of results for each value in the field. The default is false . public let facetable: Bool? /// Determines whether the field is used in the search. If the Searchable field is true, you can use relevance tuning to manually tune how Amazon Kendra weights the field in the search. The default is true for string fields and false for number and date fields. public let searchable: Bool? /// Determines whether the field can be used to sort the results of a query. If you specify sorting on a field that does not have Sortable set to true, Amazon Kendra returns an exception. The default is false. public let sortable: Bool? public init(displayable: Bool? = nil, facetable: Bool? = nil, searchable: Bool? = nil, sortable: Bool? = nil) { self.displayable = displayable self.facetable = facetable self.searchable = searchable self.sortable = sortable } private enum CodingKeys: String, CodingKey { case displayable = "Displayable" case facetable = "Facetable" case searchable = "Searchable" case sortable = "Sortable" } } public struct SeedUrlConfiguration: AWSEncodableShape & AWSDecodableShape { /// The list of seed or starting point URLs of the websites you want to crawl. The list can include a maximum of 100 seed URLs. public let seedUrls: [String] /// You can choose one of the following modes: HOST_ONLY – crawl only the website host names. For example, if the seed URL is "abc.example.com", then only URLs with host name "abc.example.com" are crawled. SUBDOMAINS – crawl the website host names with subdomains. For example, if the seed URL is "abc.example.com", then "a.abc.example.com" and "b.abc.example.com" are also crawled. EVERYTHING – crawl the website host names with subdomains and other domains that the webpages link to. The default mode is set to HOST_ONLY. public let webCrawlerMode: WebCrawlerMode? public init(seedUrls: [String], webCrawlerMode: WebCrawlerMode? = nil) { self.seedUrls = seedUrls self.webCrawlerMode = webCrawlerMode } public func validate(name: String) throws { try self.seedUrls.forEach { try validate($0, name: "seedUrls[]", parent: name, max: 2048) try validate($0, name: "seedUrls[]", parent: name, min: 1) try validate($0, name: "seedUrls[]", parent: name, pattern: "^(https?):\\/\\/([^\\s]*)$") } try self.validate(self.seedUrls, name: "seedUrls", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case seedUrls = "SeedUrls" case webCrawlerMode = "WebCrawlerMode" } } public struct ServerSideEncryptionConfiguration: AWSEncodableShape & AWSDecodableShape { /// The identifier of the KMScustomer master key (CMK). Amazon Kendra doesn't support asymmetric CMKs. public let kmsKeyId: String? public init(kmsKeyId: String? = nil) { self.kmsKeyId = kmsKeyId } public func validate(name: String) throws { try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 2048) try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case kmsKeyId = "KmsKeyId" } } public struct ServiceNowConfiguration: AWSEncodableShape & AWSDecodableShape { /// Determines the type of authentication used to connect to the ServiceNow instance. If you choose HTTP_BASIC, Amazon Kendra is authenticated using the user name and password provided in the AWS Secrets Manager secret in the SecretArn field. When you choose OAUTH2, Amazon Kendra is authenticated using the OAuth token and secret provided in the Secrets Manager secret, and the user name and password are used to determine which information Amazon Kendra has access to. When you use OAUTH2 authentication, you must generate a token and a client secret using the ServiceNow console. For more information, see Using a ServiceNow data source. public let authenticationType: ServiceNowAuthenticationType? /// The ServiceNow instance that the data source connects to. The host endpoint should look like the following: {instance}.service-now.com. public let hostUrl: String /// Provides configuration information for crawling knowledge articles in the ServiceNow site. public let knowledgeArticleConfiguration: ServiceNowKnowledgeArticleConfiguration? /// The Amazon Resource Name (ARN) of the Secrets Manager secret that contains the user name and password required to connect to the ServiceNow instance. public let secretArn: String /// Provides configuration information for crawling service catalogs in the ServiceNow site. public let serviceCatalogConfiguration: ServiceNowServiceCatalogConfiguration? /// The identifier of the release that the ServiceNow host is running. If the host is not running the LONDON release, use OTHERS. public let serviceNowBuildVersion: ServiceNowBuildVersionType public init(authenticationType: ServiceNowAuthenticationType? = nil, hostUrl: String, knowledgeArticleConfiguration: ServiceNowKnowledgeArticleConfiguration? = nil, secretArn: String, serviceCatalogConfiguration: ServiceNowServiceCatalogConfiguration? = nil, serviceNowBuildVersion: ServiceNowBuildVersionType) { self.authenticationType = authenticationType self.hostUrl = hostUrl self.knowledgeArticleConfiguration = knowledgeArticleConfiguration self.secretArn = secretArn self.serviceCatalogConfiguration = serviceCatalogConfiguration self.serviceNowBuildVersion = serviceNowBuildVersion } public func validate(name: String) throws { try self.validate(self.hostUrl, name: "hostUrl", parent: name, max: 2048) try self.validate(self.hostUrl, name: "hostUrl", parent: name, min: 1) try self.validate(self.hostUrl, name: "hostUrl", parent: name, pattern: "^(?!(^(https?|ftp|file):\\/\\/))[a-z0-9-]+(\\.service-now\\.com)$") try self.knowledgeArticleConfiguration?.validate(name: "\(name).knowledgeArticleConfiguration") try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.serviceCatalogConfiguration?.validate(name: "\(name).serviceCatalogConfiguration") } private enum CodingKeys: String, CodingKey { case authenticationType = "AuthenticationType" case hostUrl = "HostUrl" case knowledgeArticleConfiguration = "KnowledgeArticleConfiguration" case secretArn = "SecretArn" case serviceCatalogConfiguration = "ServiceCatalogConfiguration" case serviceNowBuildVersion = "ServiceNowBuildVersion" } } public struct ServiceNowKnowledgeArticleConfiguration: AWSEncodableShape & AWSDecodableShape { /// Indicates whether Amazon Kendra should index attachments to knowledge articles. public let crawlAttachments: Bool? /// The name of the ServiceNow field that is mapped to the index document contents field in the Amazon Kendra index. public let documentDataFieldName: String /// The name of the ServiceNow field that is mapped to the index document title field. public let documentTitleFieldName: String? /// List of regular expressions applied to knowledge articles. Items that don't match the inclusion pattern are not indexed. The regex is applied to the field specified in the PatternTargetField public let excludeAttachmentFilePatterns: [String]? /// Mapping between ServiceNow fields and Amazon Kendra index fields. You must create the index field before you map the field. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// A query that selects the knowledge articles to index. The query can return articles from multiple knowledge bases, and the knowledge bases can be public or private. The query string must be one generated by the ServiceNow console. For more information, see Specifying documents to index with a query. public let filterQuery: String? /// List of regular expressions applied to knowledge articles. Items that don't match the inclusion pattern are not indexed. The regex is applied to the field specified in the PatternTargetField. public let includeAttachmentFilePatterns: [String]? public init(crawlAttachments: Bool? = nil, documentDataFieldName: String, documentTitleFieldName: String? = nil, excludeAttachmentFilePatterns: [String]? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, filterQuery: String? = nil, includeAttachmentFilePatterns: [String]? = nil) { self.crawlAttachments = crawlAttachments self.documentDataFieldName = documentDataFieldName self.documentTitleFieldName = documentTitleFieldName self.excludeAttachmentFilePatterns = excludeAttachmentFilePatterns self.fieldMappings = fieldMappings self.filterQuery = filterQuery self.includeAttachmentFilePatterns = includeAttachmentFilePatterns } public func validate(name: String) throws { try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, max: 100) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, min: 1) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.excludeAttachmentFilePatterns?.forEach { try validate($0, name: "excludeAttachmentFilePatterns[]", parent: name, max: 150) try validate($0, name: "excludeAttachmentFilePatterns[]", parent: name, min: 1) } try self.validate(self.excludeAttachmentFilePatterns, name: "excludeAttachmentFilePatterns", parent: name, max: 100) try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.validate(self.filterQuery, name: "filterQuery", parent: name, max: 2048) try self.validate(self.filterQuery, name: "filterQuery", parent: name, min: 1) try self.validate(self.filterQuery, name: "filterQuery", parent: name, pattern: "^\\P{C}*$") try self.includeAttachmentFilePatterns?.forEach { try validate($0, name: "includeAttachmentFilePatterns[]", parent: name, max: 150) try validate($0, name: "includeAttachmentFilePatterns[]", parent: name, min: 1) } try self.validate(self.includeAttachmentFilePatterns, name: "includeAttachmentFilePatterns", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case crawlAttachments = "CrawlAttachments" case documentDataFieldName = "DocumentDataFieldName" case documentTitleFieldName = "DocumentTitleFieldName" case excludeAttachmentFilePatterns = "ExcludeAttachmentFilePatterns" case fieldMappings = "FieldMappings" case filterQuery = "FilterQuery" case includeAttachmentFilePatterns = "IncludeAttachmentFilePatterns" } } public struct ServiceNowServiceCatalogConfiguration: AWSEncodableShape & AWSDecodableShape { /// Indicates whether Amazon Kendra should crawl attachments to the service catalog items. public let crawlAttachments: Bool? /// The name of the ServiceNow field that is mapped to the index document contents field in the Amazon Kendra index. public let documentDataFieldName: String /// The name of the ServiceNow field that is mapped to the index document title field. public let documentTitleFieldName: String? /// A list of regular expression patterns. Documents that match the patterns are excluded from the index. Documents that don't match the patterns are included in the index. If a document matches both an exclusion pattern and an inclusion pattern, the document is not included in the index. The regex is applied to the file name of the attachment. public let excludeAttachmentFilePatterns: [String]? /// Mapping between ServiceNow fields and Amazon Kendra index fields. You must create the index field before you map the field. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// A list of regular expression patterns. Documents that match the patterns are included in the index. Documents that don't match the patterns are excluded from the index. If a document matches both an exclusion pattern and an inclusion pattern, the document is not included in the index. The regex is applied to the file name of the attachment. public let includeAttachmentFilePatterns: [String]? public init(crawlAttachments: Bool? = nil, documentDataFieldName: String, documentTitleFieldName: String? = nil, excludeAttachmentFilePatterns: [String]? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, includeAttachmentFilePatterns: [String]? = nil) { self.crawlAttachments = crawlAttachments self.documentDataFieldName = documentDataFieldName self.documentTitleFieldName = documentTitleFieldName self.excludeAttachmentFilePatterns = excludeAttachmentFilePatterns self.fieldMappings = fieldMappings self.includeAttachmentFilePatterns = includeAttachmentFilePatterns } public func validate(name: String) throws { try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, max: 100) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, min: 1) try self.validate(self.documentDataFieldName, name: "documentDataFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.excludeAttachmentFilePatterns?.forEach { try validate($0, name: "excludeAttachmentFilePatterns[]", parent: name, max: 150) try validate($0, name: "excludeAttachmentFilePatterns[]", parent: name, min: 1) } try self.validate(self.excludeAttachmentFilePatterns, name: "excludeAttachmentFilePatterns", parent: name, max: 100) try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.includeAttachmentFilePatterns?.forEach { try validate($0, name: "includeAttachmentFilePatterns[]", parent: name, max: 150) try validate($0, name: "includeAttachmentFilePatterns[]", parent: name, min: 1) } try self.validate(self.includeAttachmentFilePatterns, name: "includeAttachmentFilePatterns", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case crawlAttachments = "CrawlAttachments" case documentDataFieldName = "DocumentDataFieldName" case documentTitleFieldName = "DocumentTitleFieldName" case excludeAttachmentFilePatterns = "ExcludeAttachmentFilePatterns" case fieldMappings = "FieldMappings" case includeAttachmentFilePatterns = "IncludeAttachmentFilePatterns" } } public struct SharePointConfiguration: AWSEncodableShape & AWSDecodableShape { /// TRUE to include attachments to documents stored in your Microsoft SharePoint site in the index; otherwise, FALSE. public let crawlAttachments: Bool? /// A Boolean value that specifies whether local groups are disabled (True) or enabled (False). public let disableLocalGroups: Bool? /// The Microsoft SharePoint attribute field that contains the title of the document. public let documentTitleFieldName: String? /// A list of regular expression patterns. Documents that match the patterns are excluded from the index. Documents that don't match the patterns are included in the index. If a document matches both an exclusion pattern and an inclusion pattern, the document is not included in the index. The regex is applied to the display URL of the SharePoint document. public let exclusionPatterns: [String]? /// A list of DataSourceToIndexFieldMapping objects that map Microsoft SharePoint attributes to custom fields in the Amazon Kendra index. You must first create the index fields using the UpdateIndex operation before you map SharePoint attributes. For more information, see Mapping Data Source Fields. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// A list of regular expression patterns. Documents that match the patterns are included in the index. Documents that don't match the patterns are excluded from the index. If a document matches both an inclusion pattern and an exclusion pattern, the document is not included in the index. The regex is applied to the display URL of the SharePoint document. public let inclusionPatterns: [String]? /// The Amazon Resource Name (ARN) of credentials stored in Secrets Manager. The credentials should be a user/password pair. If you use SharePoint Server, you also need to provide the sever domain name as part of the credentials. For more information, see Using a Microsoft SharePoint Data Source. For more information about Secrets Manager, see What Is Secrets Manager in the Secrets Manager user guide. public let secretArn: String /// The version of Microsoft SharePoint that you are using as a data source. public let sharePointVersion: SharePointVersion public let sslCertificateS3Path: S3Path? /// The URLs of the Microsoft SharePoint site that contains the documents that should be indexed. public let urls: [String] /// Set to TRUE to use the Microsoft SharePoint change log to determine the documents that need to be updated in the index. Depending on the size of the SharePoint change log, it may take longer for Amazon Kendra to use the change log than it takes it to determine the changed documents using the Amazon Kendra document crawler. public let useChangeLog: Bool? public let vpcConfiguration: DataSourceVpcConfiguration? public init(crawlAttachments: Bool? = nil, disableLocalGroups: Bool? = nil, documentTitleFieldName: String? = nil, exclusionPatterns: [String]? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, inclusionPatterns: [String]? = nil, secretArn: String, sharePointVersion: SharePointVersion, sslCertificateS3Path: S3Path? = nil, urls: [String], useChangeLog: Bool? = nil, vpcConfiguration: DataSourceVpcConfiguration? = nil) { self.crawlAttachments = crawlAttachments self.disableLocalGroups = disableLocalGroups self.documentTitleFieldName = documentTitleFieldName self.exclusionPatterns = exclusionPatterns self.fieldMappings = fieldMappings self.inclusionPatterns = inclusionPatterns self.secretArn = secretArn self.sharePointVersion = sharePointVersion self.sslCertificateS3Path = sslCertificateS3Path self.urls = urls self.useChangeLog = useChangeLog self.vpcConfiguration = vpcConfiguration } public func validate(name: String) throws { try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, max: 100) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, min: 1) try self.validate(self.documentTitleFieldName, name: "documentTitleFieldName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_.]*$") try self.exclusionPatterns?.forEach { try validate($0, name: "exclusionPatterns[]", parent: name, max: 150) try validate($0, name: "exclusionPatterns[]", parent: name, min: 1) } try self.validate(self.exclusionPatterns, name: "exclusionPatterns", parent: name, max: 100) try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.inclusionPatterns?.forEach { try validate($0, name: "inclusionPatterns[]", parent: name, max: 150) try validate($0, name: "inclusionPatterns[]", parent: name, min: 1) } try self.validate(self.inclusionPatterns, name: "inclusionPatterns", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 1284) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 1) try self.validate(self.secretArn, name: "secretArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.sslCertificateS3Path?.validate(name: "\(name).sslCertificateS3Path") try self.urls.forEach { try validate($0, name: "urls[]", parent: name, max: 2048) try validate($0, name: "urls[]", parent: name, min: 1) try validate($0, name: "urls[]", parent: name, pattern: "^(https?|ftp|file):\\/\\/([^\\s]*)$") } try self.validate(self.urls, name: "urls", parent: name, max: 100) try self.validate(self.urls, name: "urls", parent: name, min: 1) try self.vpcConfiguration?.validate(name: "\(name).vpcConfiguration") } private enum CodingKeys: String, CodingKey { case crawlAttachments = "CrawlAttachments" case disableLocalGroups = "DisableLocalGroups" case documentTitleFieldName = "DocumentTitleFieldName" case exclusionPatterns = "ExclusionPatterns" case fieldMappings = "FieldMappings" case inclusionPatterns = "InclusionPatterns" case secretArn = "SecretArn" case sharePointVersion = "SharePointVersion" case sslCertificateS3Path = "SslCertificateS3Path" case urls = "Urls" case useChangeLog = "UseChangeLog" case vpcConfiguration = "VpcConfiguration" } } public struct SiteMapsConfiguration: AWSEncodableShape & AWSDecodableShape { /// The list of sitemap URLs of the websites you want to crawl. The list can include a maximum of three sitemap URLs. public let siteMaps: [String] public init(siteMaps: [String]) { self.siteMaps = siteMaps } public func validate(name: String) throws { try self.siteMaps.forEach { try validate($0, name: "siteMaps[]", parent: name, max: 2048) try validate($0, name: "siteMaps[]", parent: name, min: 1) try validate($0, name: "siteMaps[]", parent: name, pattern: "^(https?):\\/\\/([^\\s]*)$") } try self.validate(self.siteMaps, name: "siteMaps", parent: name, max: 3) } private enum CodingKeys: String, CodingKey { case siteMaps = "SiteMaps" } } public struct SortingConfiguration: AWSEncodableShape { /// The name of the document attribute used to sort the response. You can use any field that has the Sortable flag set to true. You can also sort by any of the following built-in attributes: _category _created_at _last_updated_at _version _view_count public let documentAttributeKey: String /// The order that the results should be returned in. In case of ties, the relevance assigned to the result by Amazon Kendra is used as the tie-breaker. public let sortOrder: SortOrder public init(documentAttributeKey: String, sortOrder: SortOrder) { self.documentAttributeKey = documentAttributeKey self.sortOrder = sortOrder } public func validate(name: String) throws { try self.validate(self.documentAttributeKey, name: "documentAttributeKey", parent: name, max: 200) try self.validate(self.documentAttributeKey, name: "documentAttributeKey", parent: name, min: 1) try self.validate(self.documentAttributeKey, name: "documentAttributeKey", parent: name, pattern: "^[a-zA-Z0-9_][a-zA-Z0-9_-]*$") } private enum CodingKeys: String, CodingKey { case documentAttributeKey = "DocumentAttributeKey" case sortOrder = "SortOrder" } } public struct SqlConfiguration: AWSEncodableShape & AWSDecodableShape { /// Determines whether Amazon Kendra encloses SQL identifiers for tables and column names in double quotes (") when making a database query. By default, Amazon Kendra passes SQL identifiers the way that they are entered into the data source configuration. It does not change the case of identifiers or enclose them in quotes. PostgreSQL internally converts uppercase characters to lower case characters in identifiers unless they are quoted. Choosing this option encloses identifiers in quotes so that PostgreSQL does not convert the character's case. For MySQL databases, you must enable the ansi_quotes option when you set this field to DOUBLE_QUOTES. public let queryIdentifiersEnclosingOption: QueryIdentifiersEnclosingOption? public init(queryIdentifiersEnclosingOption: QueryIdentifiersEnclosingOption? = nil) { self.queryIdentifiersEnclosingOption = queryIdentifiersEnclosingOption } private enum CodingKeys: String, CodingKey { case queryIdentifiersEnclosingOption = "QueryIdentifiersEnclosingOption" } } public struct StartDataSourceSyncJobRequest: AWSEncodableShape { /// The identifier of the data source to synchronize. public let id: String /// The identifier of the index that contains the data source. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct StartDataSourceSyncJobResponse: AWSDecodableShape { /// Identifies a particular synchronization job. public let executionId: String? public init(executionId: String? = nil) { self.executionId = executionId } private enum CodingKeys: String, CodingKey { case executionId = "ExecutionId" } } public struct Status: AWSDecodableShape { /// The unique identifier of the document. public let documentId: String? /// The current status of a document. If the document was submitted for deletion, the status is NOT_FOUND after the document is deleted. public let documentStatus: DocumentStatus? /// Indicates the source of the error. public let failureCode: String? /// Provides detailed information about why the document couldn't be indexed. Use this information to correct the error before you resubmit the document for indexing. public let failureReason: String? public init(documentId: String? = nil, documentStatus: DocumentStatus? = nil, failureCode: String? = nil, failureReason: String? = nil) { self.documentId = documentId self.documentStatus = documentStatus self.failureCode = failureCode self.failureReason = failureReason } private enum CodingKeys: String, CodingKey { case documentId = "DocumentId" case documentStatus = "DocumentStatus" case failureCode = "FailureCode" case failureReason = "FailureReason" } } public struct StopDataSourceSyncJobRequest: AWSEncodableShape { /// The identifier of the data source for which to stop the synchronization jobs. public let id: String /// The identifier of the index that contains the data source. public let indexId: String public init(id: String, indexId: String) { self.id = id self.indexId = indexId } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") } private enum CodingKeys: String, CodingKey { case id = "Id" case indexId = "IndexId" } } public struct SubmitFeedbackRequest: AWSEncodableShape { /// Tells Amazon Kendra that a particular search result link was chosen by the user. public let clickFeedbackItems: [ClickFeedback]? /// The identifier of the index that was queried. public let indexId: String /// The identifier of the specific query for which you are submitting feedback. The query ID is returned in the response to the Query operation. public let queryId: String /// Provides Amazon Kendra with relevant or not relevant feedback for whether a particular item was relevant to the search. public let relevanceFeedbackItems: [RelevanceFeedback]? public init(clickFeedbackItems: [ClickFeedback]? = nil, indexId: String, queryId: String, relevanceFeedbackItems: [RelevanceFeedback]? = nil) { self.clickFeedbackItems = clickFeedbackItems self.indexId = indexId self.queryId = queryId self.relevanceFeedbackItems = relevanceFeedbackItems } public func validate(name: String) throws { try self.clickFeedbackItems?.forEach { try $0.validate(name: "\(name).clickFeedbackItems[]") } try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.queryId, name: "queryId", parent: name, max: 36) try self.validate(self.queryId, name: "queryId", parent: name, min: 1) try self.validate(self.queryId, name: "queryId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.relevanceFeedbackItems?.forEach { try $0.validate(name: "\(name).relevanceFeedbackItems[]") } } private enum CodingKeys: String, CodingKey { case clickFeedbackItems = "ClickFeedbackItems" case indexId = "IndexId" case queryId = "QueryId" case relevanceFeedbackItems = "RelevanceFeedbackItems" } } public struct Suggestion: AWSDecodableShape { /// The unique UUID (universally unique identifier) of a single query suggestion. public let id: String? /// The value for the unique UUID (universally unique identifier) of a single query suggestion. The value is the text string of a suggestion. public let value: SuggestionValue? public init(id: String? = nil, value: SuggestionValue? = nil) { self.id = id self.value = value } private enum CodingKeys: String, CodingKey { case id = "Id" case value = "Value" } } public struct SuggestionHighlight: AWSDecodableShape { /// The zero-based location in the response string where the highlight starts. public let beginOffset: Int? /// The zero-based location in the response string where the highlight ends. public let endOffset: Int? public init(beginOffset: Int? = nil, endOffset: Int? = nil) { self.beginOffset = beginOffset self.endOffset = endOffset } private enum CodingKeys: String, CodingKey { case beginOffset = "BeginOffset" case endOffset = "EndOffset" } } public struct SuggestionTextWithHighlights: AWSDecodableShape { /// The beginning and end of the query suggestion text that should be highlighted. public let highlights: [SuggestionHighlight]? /// The query suggestion text to display to the user. public let text: String? public init(highlights: [SuggestionHighlight]? = nil, text: String? = nil) { self.highlights = highlights self.text = text } private enum CodingKeys: String, CodingKey { case highlights = "Highlights" case text = "Text" } } public struct SuggestionValue: AWSDecodableShape { /// The SuggestionTextWithHighlights structure that contains the query suggestion text and highlights. public let text: SuggestionTextWithHighlights? public init(text: SuggestionTextWithHighlights? = nil) { self.text = text } private enum CodingKeys: String, CodingKey { case text = "Text" } } public struct Tag: AWSEncodableShape & AWSDecodableShape { /// The key for the tag. Keys are not case sensitive and must be unique for the index, FAQ, or data source. public let key: String /// The value associated with the tag. The value may be an empty string but it can't be null. public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 128) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.value, name: "value", parent: name, max: 256) } private enum CodingKeys: String, CodingKey { case key = "Key" case value = "Value" } } public struct TagResourceRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the index, FAQ, or data source to tag. public let resourceARN: String /// A list of tag keys to add to the index, FAQ, or data source. If a tag already exists, the existing value is replaced with the new value. public let tags: [Tag] public init(resourceARN: String, tags: [Tag]) { self.resourceARN = resourceARN self.tags = tags } public func validate(name: String) throws { try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011) try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1) try self.tags.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case resourceARN = "ResourceARN" case tags = "Tags" } } public struct TagResourceResponse: AWSDecodableShape { public init() {} } public struct TextDocumentStatistics: AWSDecodableShape { /// The total size, in bytes, of the indexed documents. public let indexedTextBytes: Int64 /// The number of text documents indexed. public let indexedTextDocumentsCount: Int public init(indexedTextBytes: Int64, indexedTextDocumentsCount: Int) { self.indexedTextBytes = indexedTextBytes self.indexedTextDocumentsCount = indexedTextDocumentsCount } private enum CodingKeys: String, CodingKey { case indexedTextBytes = "IndexedTextBytes" case indexedTextDocumentsCount = "IndexedTextDocumentsCount" } } public struct TextWithHighlights: AWSDecodableShape { /// The beginning and end of the text that should be highlighted. public let highlights: [Highlight]? /// The text to display to the user. public let text: String? public init(highlights: [Highlight]? = nil, text: String? = nil) { self.highlights = highlights self.text = text } private enum CodingKeys: String, CodingKey { case highlights = "Highlights" case text = "Text" } } public struct ThesaurusSummary: AWSDecodableShape { /// The Unix datetime that the thesaurus was created. public let createdAt: Date? /// The identifier of the thesaurus. public let id: String? /// The name of the thesaurus. public let name: String? /// The status of the thesaurus. public let status: ThesaurusStatus? /// The Unix datetime that the thesaurus was last updated. public let updatedAt: Date? public init(createdAt: Date? = nil, id: String? = nil, name: String? = nil, status: ThesaurusStatus? = nil, updatedAt: Date? = nil) { self.createdAt = createdAt self.id = id self.name = name self.status = status self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case id = "Id" case name = "Name" case status = "Status" case updatedAt = "UpdatedAt" } } public struct TimeRange: AWSEncodableShape { /// The UNIX datetime of the end of the time range. public let endTime: Date? /// The UNIX datetime of the beginning of the time range. public let startTime: Date? public init(endTime: Date? = nil, startTime: Date? = nil) { self.endTime = endTime self.startTime = startTime } private enum CodingKeys: String, CodingKey { case endTime = "EndTime" case startTime = "StartTime" } } public struct UntagResourceRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the index, FAQ, or data source to remove the tag from. public let resourceARN: String /// A list of tag keys to remove from the index, FAQ, or data source. If a tag key does not exist on the resource, it is ignored. public let tagKeys: [String] public init(resourceARN: String, tagKeys: [String]) { self.resourceARN = resourceARN self.tagKeys = tagKeys } public func validate(name: String) throws { try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011) try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1) try self.tagKeys.forEach { try validate($0, name: "tagKeys[]", parent: name, max: 128) try validate($0, name: "tagKeys[]", parent: name, min: 1) } try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 200) } private enum CodingKeys: String, CodingKey { case resourceARN = "ResourceARN" case tagKeys = "TagKeys" } } public struct UntagResourceResponse: AWSDecodableShape { public init() {} } public struct UpdateDataSourceRequest: AWSEncodableShape { public let configuration: DataSourceConfiguration? /// The new description for the data source. public let description: String? /// The unique identifier of the data source to update. public let id: String /// The identifier of the index that contains the data source to update. public let indexId: String /// The code for a language. This allows you to support a language for all documents when updating the data source. English is supported by default. For more information on supported languages, including their codes, see Adding documents in languages other than English. public let languageCode: String? /// The name of the data source to update. The name of the data source can't be updated. To rename a data source you must delete the data source and re-create it. public let name: String? /// The Amazon Resource Name (ARN) of the new role to use when the data source is accessing resources on your behalf. public let roleArn: String? /// The new update schedule for the data source. public let schedule: String? public init(configuration: DataSourceConfiguration? = nil, description: String? = nil, id: String, indexId: String, languageCode: String? = nil, name: String? = nil, roleArn: String? = nil, schedule: String? = nil) { self.configuration = configuration self.description = description self.id = id self.indexId = indexId self.languageCode = languageCode self.name = name self.roleArn = roleArn self.schedule = schedule } public func validate(name: String) throws { try self.configuration?.validate(name: "\(name).configuration") try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.languageCode, name: "languageCode", parent: name, max: 10) try self.validate(self.languageCode, name: "languageCode", parent: name, min: 2) try self.validate(self.languageCode, name: "languageCode", parent: name, pattern: "^[a-zA-Z-]*$") try self.validate(self.name, name: "name", parent: name, max: 1000) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") } private enum CodingKeys: String, CodingKey { case configuration = "Configuration" case description = "Description" case id = "Id" case indexId = "IndexId" case languageCode = "LanguageCode" case name = "Name" case roleArn = "RoleArn" case schedule = "Schedule" } } public struct UpdateIndexRequest: AWSEncodableShape { /// Sets the number of additional storage and query capacity units that should be used by the index. You can change the capacity of the index up to 5 times per day. If you are using extra storage units, you can't reduce the storage capacity below that required to meet the storage needs for your index. public let capacityUnits: CapacityUnitsConfiguration? /// A new description for the index. public let description: String? /// The document metadata to update. public let documentMetadataConfigurationUpdates: [DocumentMetadataConfiguration]? /// The identifier of the index to update. public let id: String /// The name of the index to update. public let name: String? /// A new IAM role that gives Amazon Kendra permission to access your Amazon CloudWatch logs. public let roleArn: String? /// The user context policy. public let userContextPolicy: UserContextPolicy? /// Enables fetching access levels of groups and users from an AWS Single Sign-On identity source. To configure this, see UserGroupResolutionConfiguration. public let userGroupResolutionConfiguration: UserGroupResolutionConfiguration? /// The user token configuration. public let userTokenConfigurations: [UserTokenConfiguration]? public init(capacityUnits: CapacityUnitsConfiguration? = nil, description: String? = nil, documentMetadataConfigurationUpdates: [DocumentMetadataConfiguration]? = nil, id: String, name: String? = nil, roleArn: String? = nil, userContextPolicy: UserContextPolicy? = nil, userGroupResolutionConfiguration: UserGroupResolutionConfiguration? = nil, userTokenConfigurations: [UserTokenConfiguration]? = nil) { self.capacityUnits = capacityUnits self.description = description self.documentMetadataConfigurationUpdates = documentMetadataConfigurationUpdates self.id = id self.name = name self.roleArn = roleArn self.userContextPolicy = userContextPolicy self.userGroupResolutionConfiguration = userGroupResolutionConfiguration self.userTokenConfigurations = userTokenConfigurations } public func validate(name: String) throws { try self.capacityUnits?.validate(name: "\(name).capacityUnits") try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.documentMetadataConfigurationUpdates?.forEach { try $0.validate(name: "\(name).documentMetadataConfigurationUpdates[]") } try self.validate(self.documentMetadataConfigurationUpdates, name: "documentMetadataConfigurationUpdates", parent: name, max: 500) try self.validate(self.id, name: "id", parent: name, max: 36) try self.validate(self.id, name: "id", parent: name, min: 36) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.name, name: "name", parent: name, max: 1000) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.userTokenConfigurations?.forEach { try $0.validate(name: "\(name).userTokenConfigurations[]") } try self.validate(self.userTokenConfigurations, name: "userTokenConfigurations", parent: name, max: 1) } private enum CodingKeys: String, CodingKey { case capacityUnits = "CapacityUnits" case description = "Description" case documentMetadataConfigurationUpdates = "DocumentMetadataConfigurationUpdates" case id = "Id" case name = "Name" case roleArn = "RoleArn" case userContextPolicy = "UserContextPolicy" case userGroupResolutionConfiguration = "UserGroupResolutionConfiguration" case userTokenConfigurations = "UserTokenConfigurations" } } public struct UpdateQuerySuggestionsBlockListRequest: AWSEncodableShape { /// The description for a block list. public let description: String? /// The unique identifier of a block list. public let id: String /// The identifier of the index for a block list. public let indexId: String /// The name of a block list. public let name: String? /// The IAM (Identity and Access Management) role used to access the block list text file in S3. public let roleArn: String? /// The S3 path where your block list text file sits in S3. If you update your block list and provide the same path to the block list text file in S3, then Amazon Kendra reloads the file to refresh the block list. Amazon Kendra does not automatically refresh your block list. You need to call the UpdateQuerySuggestionsBlockList API to refresh you block list. If you update your block list, then Amazon Kendra asynchronously refreshes all query suggestions with the latest content in the S3 file. This means changes might not take effect immediately. public let sourceS3Path: S3Path? public init(description: String? = nil, id: String, indexId: String, name: String? = nil, roleArn: String? = nil, sourceS3Path: S3Path? = nil) { self.description = description self.id = id self.indexId = indexId self.name = name self.roleArn = roleArn self.sourceS3Path = sourceS3Path } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.id, name: "id", parent: name, max: 36) try self.validate(self.id, name: "id", parent: name, min: 36) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9](-*[a-zA-Z0-9])*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.sourceS3Path?.validate(name: "\(name).sourceS3Path") } private enum CodingKeys: String, CodingKey { case description = "Description" case id = "Id" case indexId = "IndexId" case name = "Name" case roleArn = "RoleArn" case sourceS3Path = "SourceS3Path" } } public struct UpdateQuerySuggestionsConfigRequest: AWSEncodableShape { /// TRUE to include queries without user information (i.e. all queries, irrespective of the user), otherwise FALSE to only include queries with user information. If you pass user information to Amazon Kendra along with the queries, you can set this flag to FALSE and instruct Amazon Kendra to only consider queries with user information. If you set to FALSE, Amazon Kendra only considers queries searched at least MinimumQueryCount times across MinimumNumberOfQueryingUsers unique users for suggestions. If you set to TRUE, Amazon Kendra ignores all user information and learns from all queries. public let includeQueriesWithoutUserInformation: Bool? /// The identifier of the index you want to update query suggestions settings for. public let indexId: String /// The minimum number of unique users who must search a query in order for the query to be eligible to suggest to your users. Increasing this number might decrease the number of suggestions. However, this ensures a query is searched by many users and is truly popular to suggest to users. How you tune this setting depends on your specific needs. public let minimumNumberOfQueryingUsers: Int? /// The the minimum number of times a query must be searched in order to be eligible to suggest to your users. Decreasing this number increases the number of suggestions. However, this affects the quality of suggestions as it sets a low bar for a query to be considered popular to suggest to users. How you tune this setting depends on your specific needs. public let minimumQueryCount: Int? /// Set the mode to ENABLED or LEARN_ONLY. By default, Amazon Kendra enables query suggestions. LEARN_ONLY mode allows you to turn off query suggestions. You can to update this at any time. In LEARN_ONLY mode, Amazon Kendra continues to learn from new queries to keep suggestions up to date for when you are ready to switch to ENABLED mode again. public let mode: Mode? /// How recent your queries are in your query log time window. The time window is the number of days from current day to past days. By default, Amazon Kendra sets this to 180. public let queryLogLookBackWindowInDays: Int? public init(includeQueriesWithoutUserInformation: Bool? = nil, indexId: String, minimumNumberOfQueryingUsers: Int? = nil, minimumQueryCount: Int? = nil, mode: Mode? = nil, queryLogLookBackWindowInDays: Int? = nil) { self.includeQueriesWithoutUserInformation = includeQueriesWithoutUserInformation self.indexId = indexId self.minimumNumberOfQueryingUsers = minimumNumberOfQueryingUsers self.minimumQueryCount = minimumQueryCount self.mode = mode self.queryLogLookBackWindowInDays = queryLogLookBackWindowInDays } public func validate(name: String) throws { try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.minimumNumberOfQueryingUsers, name: "minimumNumberOfQueryingUsers", parent: name, max: 10000) try self.validate(self.minimumNumberOfQueryingUsers, name: "minimumNumberOfQueryingUsers", parent: name, min: 1) try self.validate(self.minimumQueryCount, name: "minimumQueryCount", parent: name, max: 10000) try self.validate(self.minimumQueryCount, name: "minimumQueryCount", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case includeQueriesWithoutUserInformation = "IncludeQueriesWithoutUserInformation" case indexId = "IndexId" case minimumNumberOfQueryingUsers = "MinimumNumberOfQueryingUsers" case minimumQueryCount = "MinimumQueryCount" case mode = "Mode" case queryLogLookBackWindowInDays = "QueryLogLookBackWindowInDays" } } public struct UpdateThesaurusRequest: AWSEncodableShape { /// The updated description of the thesaurus. public let description: String? /// The identifier of the thesaurus to update. public let id: String /// The identifier of the index associated with the thesaurus to update. public let indexId: String /// The updated name of the thesaurus. public let name: String? /// The updated role ARN of the thesaurus. public let roleArn: String? public let sourceS3Path: S3Path? public init(description: String? = nil, id: String, indexId: String, name: String? = nil, roleArn: String? = nil, sourceS3Path: S3Path? = nil) { self.description = description self.id = id self.indexId = indexId self.name = name self.roleArn = roleArn self.sourceS3Path = sourceS3Path } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, pattern: "^\\P{C}*$") try self.validate(self.id, name: "id", parent: name, max: 100) try self.validate(self.id, name: "id", parent: name, min: 1) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.indexId, name: "indexId", parent: name, max: 36) try self.validate(self.indexId, name: "indexId", parent: name, min: 36) try self.validate(self.indexId, name: "indexId", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1284) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:[a-z0-9-\\.]{1,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[a-z0-9-\\.]{0,63}:[^/].{0,1023}$") try self.sourceS3Path?.validate(name: "\(name).sourceS3Path") } private enum CodingKeys: String, CodingKey { case description = "Description" case id = "Id" case indexId = "IndexId" case name = "Name" case roleArn = "RoleArn" case sourceS3Path = "SourceS3Path" } } public struct Urls: AWSEncodableShape & AWSDecodableShape { /// Provides the configuration of the seed or starting point URLs of the websites you want to crawl. You can choose to crawl only the website host names, or the website host names with subdomains, or the website host names with subdomains and other domains that the webpages link to. You can list up to 100 seed URLs. public let seedUrlConfiguration: SeedUrlConfiguration? /// Provides the configuration of the sitemap URLs of the websites you want to crawl. Only URLs belonging to the same website host names are crawled. You can list up to three sitemap URLs. public let siteMapsConfiguration: SiteMapsConfiguration? public init(seedUrlConfiguration: SeedUrlConfiguration? = nil, siteMapsConfiguration: SiteMapsConfiguration? = nil) { self.seedUrlConfiguration = seedUrlConfiguration self.siteMapsConfiguration = siteMapsConfiguration } public func validate(name: String) throws { try self.seedUrlConfiguration?.validate(name: "\(name).seedUrlConfiguration") try self.siteMapsConfiguration?.validate(name: "\(name).siteMapsConfiguration") } private enum CodingKeys: String, CodingKey { case seedUrlConfiguration = "SeedUrlConfiguration" case siteMapsConfiguration = "SiteMapsConfiguration" } } public struct UserContext: AWSEncodableShape { /// The list of data source groups you want to filter search results based on groups' access to documents in that data source. public let dataSourceGroups: [DataSourceGroup]? /// The list of groups you want to filter search results based on the groups' access to documents. public let groups: [String]? /// The user context token for filtering search results for a user. It must be a JWT or a JSON token. public let token: String? /// The identifier of the user you want to filter search results based on their access to documents. public let userId: String? public init(dataSourceGroups: [DataSourceGroup]? = nil, groups: [String]? = nil, token: String? = nil, userId: String? = nil) { self.dataSourceGroups = dataSourceGroups self.groups = groups self.token = token self.userId = userId } public func validate(name: String) throws { try self.dataSourceGroups?.forEach { try $0.validate(name: "\(name).dataSourceGroups[]") } try self.validate(self.dataSourceGroups, name: "dataSourceGroups", parent: name, max: 2048) try self.validate(self.dataSourceGroups, name: "dataSourceGroups", parent: name, min: 1) try self.groups?.forEach { try validate($0, name: "groups[]", parent: name, max: 200) try validate($0, name: "groups[]", parent: name, min: 1) try validate($0, name: "groups[]", parent: name, pattern: "^\\P{C}*$") } try self.validate(self.groups, name: "groups", parent: name, max: 2048) try self.validate(self.groups, name: "groups", parent: name, min: 1) try self.validate(self.token, name: "token", parent: name, max: 100_000) try self.validate(self.token, name: "token", parent: name, min: 1) try self.validate(self.token, name: "token", parent: name, pattern: "^\\P{C}*$") try self.validate(self.userId, name: "userId", parent: name, max: 200) try self.validate(self.userId, name: "userId", parent: name, min: 1) try self.validate(self.userId, name: "userId", parent: name, pattern: "^\\P{C}*$") } private enum CodingKeys: String, CodingKey { case dataSourceGroups = "DataSourceGroups" case groups = "Groups" case token = "Token" case userId = "UserId" } } public struct UserGroupResolutionConfiguration: AWSEncodableShape & AWSDecodableShape { /// The identity store provider (mode) you want to use to fetch access levels of groups and users. AWS Single Sign-On is currently the only available mode. Your users and groups must exist in an AWS SSO identity source in order to use this mode. public let userGroupResolutionMode: UserGroupResolutionMode public init(userGroupResolutionMode: UserGroupResolutionMode) { self.userGroupResolutionMode = userGroupResolutionMode } private enum CodingKeys: String, CodingKey { case userGroupResolutionMode = "UserGroupResolutionMode" } } public struct UserTokenConfiguration: AWSEncodableShape & AWSDecodableShape { /// Information about the JSON token type configuration. public let jsonTokenTypeConfiguration: JsonTokenTypeConfiguration? /// Information about the JWT token type configuration. public let jwtTokenTypeConfiguration: JwtTokenTypeConfiguration? public init(jsonTokenTypeConfiguration: JsonTokenTypeConfiguration? = nil, jwtTokenTypeConfiguration: JwtTokenTypeConfiguration? = nil) { self.jsonTokenTypeConfiguration = jsonTokenTypeConfiguration self.jwtTokenTypeConfiguration = jwtTokenTypeConfiguration } public func validate(name: String) throws { try self.jsonTokenTypeConfiguration?.validate(name: "\(name).jsonTokenTypeConfiguration") try self.jwtTokenTypeConfiguration?.validate(name: "\(name).jwtTokenTypeConfiguration") } private enum CodingKeys: String, CodingKey { case jsonTokenTypeConfiguration = "JsonTokenTypeConfiguration" case jwtTokenTypeConfiguration = "JwtTokenTypeConfiguration" } } public struct WebCrawlerConfiguration: AWSEncodableShape & AWSDecodableShape { /// Provides configuration information required to connect to websites using authentication. You can connect to websites using basic authentication of user name and password. You must provide the website host name and port number. For example, the host name of https://a.example.com/page1.html is "a.example.com" and the port is 443, the standard port for HTTPS. You use a secret in AWS Secrets Manager to store your authentication credentials. public let authenticationConfiguration: AuthenticationConfiguration? /// Specifies the number of levels in a website that you want to crawl. The first level begins from the website seed or starting point URL. For example, if a website has 3 levels – index level (i.e. seed in this example), sections level, and subsections level – and you are only interested in crawling information up to the sections level (i.e. levels 0-1), you can set your depth to 1. The default crawl depth is set to 2. public let crawlDepth: Int? /// The maximum size (in MB) of a webpage or attachment to crawl. Files larger than this size (in MB) are skipped/not crawled. The default maximum size of a webpage or attachment is set to 50 MB. public let maxContentSizePerPageInMegaBytes: Float? /// The maximum number of URLs on a webpage to include when crawling a website. This number is per webpage. As a website’s webpages are crawled, any URLs the webpages link to are also crawled. URLs on a webpage are crawled in order of appearance. The default maximum links per page is 100. public let maxLinksPerPage: Int? /// The maximum number of URLs crawled per website host per minute. A minimum of one URL is required. The default maximum number of URLs crawled per website host per minute is 300. public let maxUrlsPerMinuteCrawlRate: Int? /// Provides configuration information required to connect to your internal websites via a web proxy. You must provide the website host name and port number. For example, the host name of https://a.example.com/page1.html is "a.example.com" and the port is 443, the standard port for HTTPS. Web proxy credentials are optional and you can use them to connect to a web proxy server that requires basic authentication. To store web proxy credentials, you use a secret in AWS Secrets Manager. public let proxyConfiguration: ProxyConfiguration? /// The regular expression pattern to exclude certain URLs to crawl. If there is a regular expression pattern to include certain URLs that conflicts with the exclude pattern, the exclude pattern takes precedence. public let urlExclusionPatterns: [String]? /// The regular expression pattern to include certain URLs to crawl. If there is a regular expression pattern to exclude certain URLs that conflicts with the include pattern, the exclude pattern takes precedence. public let urlInclusionPatterns: [String]? /// Specifies the seed or starting point URLs of the websites or the sitemap URLs of the websites you want to crawl. You can include website subdomains. You can list up to 100 seed URLs and up to three sitemap URLs. You can only crawl websites that use the secure communication protocol, Hypertext Transfer Protocol Secure (HTTPS). If you receive an error when crawling a website, it could be that the website is blocked from crawling. When selecting websites to index, you must adhere to the Amazon Acceptable Use Policy and all other Amazon terms. Remember that you must only use the Amazon Kendra web crawler to index your own webpages, or webpages that you have authorization to index. public let urls: Urls public init(authenticationConfiguration: AuthenticationConfiguration? = nil, crawlDepth: Int? = nil, maxContentSizePerPageInMegaBytes: Float? = nil, maxLinksPerPage: Int? = nil, maxUrlsPerMinuteCrawlRate: Int? = nil, proxyConfiguration: ProxyConfiguration? = nil, urlExclusionPatterns: [String]? = nil, urlInclusionPatterns: [String]? = nil, urls: Urls) { self.authenticationConfiguration = authenticationConfiguration self.crawlDepth = crawlDepth self.maxContentSizePerPageInMegaBytes = maxContentSizePerPageInMegaBytes self.maxLinksPerPage = maxLinksPerPage self.maxUrlsPerMinuteCrawlRate = maxUrlsPerMinuteCrawlRate self.proxyConfiguration = proxyConfiguration self.urlExclusionPatterns = urlExclusionPatterns self.urlInclusionPatterns = urlInclusionPatterns self.urls = urls } public func validate(name: String) throws { try self.authenticationConfiguration?.validate(name: "\(name).authenticationConfiguration") try self.validate(self.crawlDepth, name: "crawlDepth", parent: name, max: 10) try self.validate(self.crawlDepth, name: "crawlDepth", parent: name, min: 0) try self.validate(self.maxContentSizePerPageInMegaBytes, name: "maxContentSizePerPageInMegaBytes", parent: name, max: 50.0) try self.validate(self.maxContentSizePerPageInMegaBytes, name: "maxContentSizePerPageInMegaBytes", parent: name, min: 1e-06) try self.validate(self.maxLinksPerPage, name: "maxLinksPerPage", parent: name, max: 1000) try self.validate(self.maxLinksPerPage, name: "maxLinksPerPage", parent: name, min: 1) try self.validate(self.maxUrlsPerMinuteCrawlRate, name: "maxUrlsPerMinuteCrawlRate", parent: name, max: 300) try self.validate(self.maxUrlsPerMinuteCrawlRate, name: "maxUrlsPerMinuteCrawlRate", parent: name, min: 1) try self.proxyConfiguration?.validate(name: "\(name).proxyConfiguration") try self.urlExclusionPatterns?.forEach { try validate($0, name: "urlExclusionPatterns[]", parent: name, max: 150) try validate($0, name: "urlExclusionPatterns[]", parent: name, min: 1) } try self.validate(self.urlExclusionPatterns, name: "urlExclusionPatterns", parent: name, max: 100) try self.urlInclusionPatterns?.forEach { try validate($0, name: "urlInclusionPatterns[]", parent: name, max: 150) try validate($0, name: "urlInclusionPatterns[]", parent: name, min: 1) } try self.validate(self.urlInclusionPatterns, name: "urlInclusionPatterns", parent: name, max: 100) try self.urls.validate(name: "\(name).urls") } private enum CodingKeys: String, CodingKey { case authenticationConfiguration = "AuthenticationConfiguration" case crawlDepth = "CrawlDepth" case maxContentSizePerPageInMegaBytes = "MaxContentSizePerPageInMegaBytes" case maxLinksPerPage = "MaxLinksPerPage" case maxUrlsPerMinuteCrawlRate = "MaxUrlsPerMinuteCrawlRate" case proxyConfiguration = "ProxyConfiguration" case urlExclusionPatterns = "UrlExclusionPatterns" case urlInclusionPatterns = "UrlInclusionPatterns" case urls = "Urls" } } public struct WorkDocsConfiguration: AWSEncodableShape & AWSDecodableShape { /// TRUE to include comments on documents in your index. Including comments in your index means each comment is a document that can be searched on. The default is set to FALSE. public let crawlComments: Bool? /// A list of regular expression patterns to exclude certain files in your Amazon WorkDocs site repository. Files that match the patterns are excluded from the index. Files that don’t match the patterns are included in the index. If a file matches both an inclusion pattern and an exclusion pattern, the exclusion pattern takes precedence and the file isn’t included in the index. public let exclusionPatterns: [String]? /// A list of DataSourceToIndexFieldMapping objects that map Amazon WorkDocs field names to custom index field names in Amazon Kendra. You must first create the custom index fields using the UpdateIndex operation before you map to Amazon WorkDocs fields. For more information, see Mapping Data Source Fields. The Amazon WorkDocs data source field names need to exist in your Amazon WorkDocs custom metadata. public let fieldMappings: [DataSourceToIndexFieldMapping]? /// A list of regular expression patterns to include certain files in your Amazon WorkDocs site repository. Files that match the patterns are included in the index. Files that don't match the patterns are excluded from the index. If a file matches both an inclusion pattern and an exclusion pattern, the exclusion pattern takes precedence and the file isn’t included in the index. public let inclusionPatterns: [String]? /// The identifier of the directory corresponding to your Amazon WorkDocs site repository. You can find the organization ID in the AWS Directory Service by going to Active Directory, then Directories. Your Amazon WorkDocs site directory has an ID, which is the organization ID. You can also set up a new Amazon WorkDocs directory in the AWS Directory Service console and enable a Amazon WorkDocs site for the directory in the Amazon WorkDocs console. public let organizationId: String /// TRUE to use the change logs to update documents in your index instead of scanning all documents. If you are syncing your Amazon WorkDocs data source with your index for the first time, all documents are scanned. After your first sync, you can use the change logs to update your documents in your index for future syncs. The default is set to FALSE. public let useChangeLog: Bool? public init(crawlComments: Bool? = nil, exclusionPatterns: [String]? = nil, fieldMappings: [DataSourceToIndexFieldMapping]? = nil, inclusionPatterns: [String]? = nil, organizationId: String, useChangeLog: Bool? = nil) { self.crawlComments = crawlComments self.exclusionPatterns = exclusionPatterns self.fieldMappings = fieldMappings self.inclusionPatterns = inclusionPatterns self.organizationId = organizationId self.useChangeLog = useChangeLog } public func validate(name: String) throws { try self.exclusionPatterns?.forEach { try validate($0, name: "exclusionPatterns[]", parent: name, max: 150) try validate($0, name: "exclusionPatterns[]", parent: name, min: 1) } try self.validate(self.exclusionPatterns, name: "exclusionPatterns", parent: name, max: 100) try self.fieldMappings?.forEach { try $0.validate(name: "\(name).fieldMappings[]") } try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, max: 100) try self.validate(self.fieldMappings, name: "fieldMappings", parent: name, min: 1) try self.inclusionPatterns?.forEach { try validate($0, name: "inclusionPatterns[]", parent: name, max: 150) try validate($0, name: "inclusionPatterns[]", parent: name, min: 1) } try self.validate(self.inclusionPatterns, name: "inclusionPatterns", parent: name, max: 100) try self.validate(self.organizationId, name: "organizationId", parent: name, max: 12) try self.validate(self.organizationId, name: "organizationId", parent: name, min: 12) try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^d-[0-9a-fA-F]{10}$") } private enum CodingKeys: String, CodingKey { case crawlComments = "CrawlComments" case exclusionPatterns = "ExclusionPatterns" case fieldMappings = "FieldMappings" case inclusionPatterns = "InclusionPatterns" case organizationId = "OrganizationId" case useChangeLog = "UseChangeLog" } } }
59.437096
846
0.664191
1e95a0a7dac635d06afccd8dc4674f699d55d25a
485
// // Cache.swift // IBAMobileBank // // Created by László Teveli on 2020. 04. 06.. // Copyright © 2020. Shamkhal Guliyev. All rights reserved. // import Foundation public protocol AnalyticsLoggerProtocol { func logEvent(name: String, parameters: [String: String]) } public class ConsoleLogger: AnalyticsLoggerProtocol { public init() {} public func logEvent(name: String, parameters: [String : String]) { print("[Analytics]", name, parameters) } }
22.045455
71
0.682474
5019da16a23c6deb25708a4000e81e53c30409c1
463
// // Created by Scott Moon on 2019-05-02. // Copyright (c) 2019 Scott Moon. All rights reserved. // import Foundation public struct MalformedURLError { private enum Constant { static let translationKet = "error.global.network" } public init() { } } extension MalformedURLError: ErrorType { // MARK: - Protocol Variables public var raw: Error? { return nil } public var messageKey: String { return Constant.translationKet } }
15.433333
54
0.686825
c1470b537a6add5ebc4825c439bd884c9c2c954e
4,342
// // FontListViewController.swift // Fonts // // Created by Molly Maskrey on 7/11/16. // Copyright © 2016 MollyMaskrey. All rights reserved. // import UIKit class FontListViewController: UITableViewController { var fontNames: [String] = [] var showsFavorites:Bool = false private var cellPointSize: CGFloat! private static let cellIdentifier = "FontName" override func viewDidLoad() { super.viewDidLoad() let preferredTableViewFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) cellPointSize = preferredTableViewFont.pointSize tableView.estimatedRowHeight = cellPointSize if showsFavorites { navigationItem.rightBarButtonItem = editButtonItem } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if showsFavorites { fontNames = FavoritesList.sharedFavoritesList.favorites tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return fontNames.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: FontListViewController.cellIdentifier, for: indexPath) cell.textLabel?.font = fontForDisplay(atIndexPath: indexPath as NSIndexPath) cell.textLabel?.text = fontNames[indexPath.row] cell.detailTextLabel?.text = fontNames[indexPath.row] return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return showsFavorites } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if !showsFavorites { return } if editingStyle == UITableViewCellEditingStyle.delete { // Delete the row from the data source let favorite = fontNames[indexPath.row] FavoritesList.sharedFavoritesList.removeFavorite(fontName: favorite) fontNames = FavoritesList.sharedFavoritesList.favorites tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade) } } override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { FavoritesList.sharedFavoritesList.moveItem(fromIndex: sourceIndexPath.row, toIndex: destinationIndexPath.row) fontNames = FavoritesList.sharedFavoritesList.favorites } func fontForDisplay(atIndexPath indexPath: NSIndexPath) -> UIFont { let fontName = fontNames[indexPath.row] return UIFont(name: fontName, size: cellPointSize)! } // MARK: - 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. let tableViewCell = sender as! UITableViewCell let indexPath = tableView.indexPath(for: tableViewCell)! let font = fontForDisplay(atIndexPath: indexPath as NSIndexPath) if segue.identifier == "ShowFontSizes" { let sizesVC = segue.destination as! FontSizesViewController sizesVC.title = font.fontName sizesVC.font = font } else { let infoVC = segue.destination as! FontInfoViewController infoVC.title = font.fontName infoVC.font = font infoVC.favorite = FavoritesList.sharedFavoritesList.favorites.contains(font.fontName) } } }
35.300813
137
0.637264
75a800e3e1195ade5991c6d57cbd658ebc24d737
284
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSData { { } func a { deinit { { class A { protocol B { enum S { struct D { let start = ( { class case ,
14.947368
87
0.707746
d57803d85b55b625929dcf33f8016e8b40286055
220
import SwiftUI struct NewsfeedView: View { var body: some View { WebView.newsfeed } } struct NewsfeedView_Previews: PreviewProvider { static var previews: some View { NewsfeedView() } }
15.714286
47
0.654545
0e0cb9c5d38ca67dec9271563af1aa5b3f7b9359
711
// // XCTestManifests.swift // // Created by Kyle Jessup on 2015-10-19. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import XCTest #if !os(OSX) && !os(iOS) public func allTests() -> [XCTestCaseEntry] { return [ testCase(PerfectSQLiteTests.allTests) ] } #endif
25.392857
80
0.544304
61b32b8d8ca694723610ec96ed14105c9c43fde1
2,042
// // CakeResumeFetcher.swift // JobHunter // // Created by Nelson on 2020/11/18. // import Foundation import Combine import SwiftSoup struct CakeResumeFetcher: Fetcher { var name: String { return "CakeResume" } func fetchJobs(at page: UInt) -> AnyPublisher<[Job], CustomError> { var request = URLRequest(url: URL(string: "https://www.cakeresume.com/jobs/popular?ref=job_search_view_all_jobs&page=\(page)")!) request.httpMethod = "GET" return fetchContent(for: request, using: jobsParser) } private let jobsParser: Parser<Job> = { content in let document: Document = try SwiftSoup.parse(content) let query = "div.job > div.job-item" let elements = try document.select(query) let jobs = elements.array().compactMap { e -> Job? in guard let titleNode = try? e.select(".job-list-item-content > .job-title > .job-link-wrapper").first(), let companyNode = try? e.select(".job-list-item-content > .page-name").first(), let urlNode = try? e.select(".job-list-item-content > .job-title .job-link-wrapper > a").first() else { return nil } guard let title = try? titleNode.text(), let company = try? companyNode.text(), let url = try? urlNode.absUrl("href") else { return nil } var job = Job(title: title, company: company, url: URL(string: url)!) if let salary = try? e.select(".job-salary").first()?.text(), !salary.isEmpty { job.salary = salary } if let logo = try? e.select(".job-list-item-content > .job-title > .company-logo-wrapper > img").first()?.attr("src"), !logo.isEmpty { job.logo = URL(string: logo) } if let location = try? e.select(".job-list-item-tags .location-section").text(), !location.isEmpty { job.location = location } return job } return jobs } }
36.464286
146
0.577865
46d575e613cba2791e36a6f4a047457591114099
827
// // Virus.swift // Book_Sources // // Created by Mateus Rodrigues on 22/03/19. // import Foundation import GameplayKit public class Virus: GKEntity { weak var entityManager: EntityManager? init(entityManager: EntityManager) { self.entityManager = entityManager super.init() self.addComponent(SpriteComponent(imageNamed: "🦠")) self.addComponent(VirusComponent()) self.addComponent(PhysicsComponent(for: spriteComponent.node)) spriteComponent.node.physicsBody?.categoryBitMask = CategoryMask.virus.rawValue } public override func update(deltaTime seconds: TimeInterval) { super.update(deltaTime: seconds) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
25.060606
87
0.675937
0144e0de047462396f2289e6d87bdd3a494c7a34
38,395
// // UserFilesViewController.swift // MySampleApp // // // Copyright 2017 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.16 // import UIKit import WebKit import MobileCoreServices import AWSMobileHubHelper import AVFoundation import AVKit import ObjectiveC let UserFilesPublicDirectoryName = "public" let UserFilesPrivateDirectoryName = "private" let UserFilesProtectedDirectoryName = "protected" let UserFilesUploadsDirectoryName = "uploads" private var cellAssociationKey: UInt8 = 0 class UserFilesViewController: UITableViewController { @IBOutlet weak var pathLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! var prefix: String! fileprivate var manager: AWSUserFileManager! fileprivate var contents: [AWSContent]? fileprivate var dateFormatter: DateFormatter! fileprivate var marker: String? fileprivate var didLoadAllContents: Bool! fileprivate var segmentedControlSelected: Int = 0; // MARK:- View lifecycle override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self manager = AWSUserFileManager.defaultUserFileManager() // Sets up the UIs. navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(UserFilesViewController.showContentManagerActionOptions(_:))) // Sets up the date formatter. dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short dateFormatter.locale = Locale.current tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension didLoadAllContents = false if let prefix = prefix { print("Prefix already initialized to \(prefix)") } else { self.prefix = "\(UserFilesPublicDirectoryName)/" } refreshContents() updateUserInterface() loadMoreContents() } fileprivate func updateUserInterface() { DispatchQueue.main.async { if let prefix = self.prefix { var pathText = "\(prefix)" var startFrom = prefix.startIndex var offset = 0 let maxPathTextLength = 50 if prefix.hasPrefix(UserFilesPublicDirectoryName) { startFrom = UserFilesPublicDirectoryName.endIndex } else if prefix.hasPrefix(UserFilesPrivateDirectoryName) { let userId = AWSIdentityManager.default().identityId! startFrom = UserFilesPrivateDirectoryName.endIndex offset = userId.characters.count + 1 } else if prefix.hasPrefix(UserFilesProtectedDirectoryName) { startFrom = UserFilesProtectedDirectoryName.endIndex } else if prefix.hasPrefix(UserFilesUploadsDirectoryName) { startFrom = UserFilesUploadsDirectoryName.endIndex } startFrom = prefix.characters.index(startFrom, offsetBy: offset + 1) pathText = "\(prefix.substring(from: startFrom))" if pathText.characters.count > maxPathTextLength { pathText = "...\(pathText.substring(from: pathText.characters.index(pathText.endIndex, offsetBy: -maxPathTextLength)))" } self.pathLabel.text = "\(pathText)" } else { self.pathLabel.text = "/" } self.segmentedControl.selectedSegmentIndex = self.segmentedControlSelected self.tableView.reloadData() } } func onSignIn (_ success: Bool) { // handle successful sign in if (success) { if let mainViewController = self.navigationController?.viewControllers[0] as? MainViewController { mainViewController.setupRightBarButtonItem() mainViewController.updateTheme() } } else { // handle cancel operation from user } } // MARK:- Content Manager user action methods @IBAction func changeDirectory(_ sender: UISegmentedControl) { manager = AWSUserFileManager.defaultUserFileManager() switch(sender.selectedSegmentIndex) { case 0: //Public Directory prefix = "\(UserFilesPublicDirectoryName)/" break case 1: //Private Directory if (AWSSignInManager.sharedInstance().isLoggedIn) { let userId = AWSIdentityManager.default().identityId! prefix = "\(UserFilesPrivateDirectoryName)/\(userId)/" } else { sender.selectedSegmentIndex = self.segmentedControlSelected let alertController = UIAlertController(title: "Info", message: "Private user file storage is only available to users who are signed-in. Would you like to sign in?", preferredStyle: .alert) let signInAction = UIAlertAction(title: "Sign In", style: .default, handler: {[weak self](action: UIAlertAction) -> Void in guard let strongSelf = self else { return } let loginStoryboard = UIStoryboard(name: "SignIn", bundle: nil) let loginController: SignInViewController = loginStoryboard.instantiateViewController(withIdentifier: "SignIn") as! SignInViewController loginController.canCancel = true loginController.didCompleteSignIn = strongSelf.onSignIn let navController = UINavigationController(rootViewController: loginController) strongSelf.navigationController?.present(navController, animated: true, completion: nil) }) alertController.addAction(signInAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } break case 2: // Protected Directory if AWSSignInManager.sharedInstance().isLoggedIn { let userId = AWSIdentityManager.default().identityId! prefix = "\(UserFilesProtectedDirectoryName)/\(userId)/"; } else { prefix = "\(UserFilesProtectedDirectoryName)/"; } break case 3: // Uploads Directory prefix = "\(UserFilesUploadsDirectoryName)/" break default: break } segmentedControlSelected = sender.selectedSegmentIndex contents = [] loadMoreContents() } func showContentManagerActionOptions(_ sender: AnyObject) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let uploadObjectAction = UIAlertAction(title: "Upload", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.showImagePicker() }) alertController.addAction(uploadObjectAction) let createFolderAction = UIAlertAction(title: "New Folder", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.askForDirectoryName() }) alertController.addAction(createFolderAction) let refreshAction = UIAlertAction(title: "Refresh", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.refreshContents() }) alertController.addAction(refreshAction) let downloadObjectsAction = UIAlertAction(title: "Download Recent", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.downloadObjectsToFillCache() }) alertController.addAction(downloadObjectsAction) let changeLimitAction = UIAlertAction(title: "Set Cache Size", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.showDiskLimitOptions() }) alertController.addAction(changeLimitAction) let removeAllObjectsAction = UIAlertAction(title: "Clear Cache", style: .destructive, handler: {[unowned self](action: UIAlertAction) -> Void in self.manager.clearCache() self.updateUserInterface() }) alertController.addAction(removeAllObjectsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func refreshContents() { marker = nil loadMoreContents() } fileprivate func loadMoreContents() { let uploadsDirectory = "\(UserFilesUploadsDirectoryName)/" if prefix == uploadsDirectory { updateUserInterface() return } manager.listAvailableContents(withPrefix: prefix, marker: marker) {[weak self] (contents: [AWSContent]?, nextMarker: String?, error: Error?) in guard let strongSelf = self else { return } if let error = error { strongSelf.showSimpleAlertWithTitle("Error", message: "Failed to load the list of contents.", cancelButtonTitle: "OK") print("Failed to load the list of contents. \(error)") } if let contents = contents, contents.count > 0 { strongSelf.contents = contents if let nextMarker = nextMarker, !nextMarker.isEmpty { strongSelf.didLoadAllContents = false } else { strongSelf.didLoadAllContents = true } strongSelf.marker = nextMarker } else { strongSelf.checkUserProtectedFolder() } strongSelf.updateUserInterface() } } fileprivate func showDiskLimitOptions() { let alertController = UIAlertController(title: "Disk Cache Size", message: nil, preferredStyle: .actionSheet) for number: Int in [1, 5, 20, 50, 100] { let byteLimitOptionAction = UIAlertAction(title: "\(number) MB", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.manager.maxCacheSize = UInt(number) * 1024 * 1024 self.updateUserInterface() }) alertController.addAction(byteLimitOptionAction) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func downloadObjectsToFillCache() { manager.listRecentContents(withPrefix: prefix) {[weak self] (contents: [AWSContent]?, error: Error?) in guard let strongSelf = self else { return } contents?.forEach({ (content: AWSContent) in if !content.isCached && !content.isDirectory { strongSelf.downloadContent(content, pinOnCompletion: false) } }) } } // MARK:- Content user action methods fileprivate func showActionOptionsForContent(_ rect: CGRect, content: AWSContent) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if alertController.popoverPresentationController != nil { alertController.popoverPresentationController?.sourceView = self.view alertController.popoverPresentationController?.sourceRect = CGRect(x: rect.midX, y: rect.midY, width: 1.0, height: 1.0) } if content.isCached { let openAction = UIAlertAction(title: "Open", style: .default, handler: {(action: UIAlertAction) -> Void in DispatchQueue.main.async { self.openContent(content) } }) alertController.addAction(openAction) } // Allow opening of remote files natively or in browser based on their type. let openRemoteAction = UIAlertAction(title: "Open Remote", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.openRemoteContent(content) }) alertController.addAction(openRemoteAction) // If the content hasn't been downloaded, and it's larger than the limit of the cache, // we don't allow downloading the contentn. if content.knownRemoteByteCount + 4 * 1024 < self.manager.maxCacheSize { // 4 KB is for local metadata. var title = "Download" if let downloadedDate = content.downloadedDate, let knownRemoteLastModifiedDate = content.knownRemoteLastModifiedDate, knownRemoteLastModifiedDate.compare(downloadedDate) == .orderedDescending { title = "Download Latest Version" } let downloadAction = UIAlertAction(title: title, style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.downloadContent(content, pinOnCompletion: false) }) alertController.addAction(downloadAction) } let downloadAndPinAction = UIAlertAction(title: "Download & Pin", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in self.downloadContent(content, pinOnCompletion: true) }) alertController.addAction(downloadAndPinAction) if content.isCached { if content.isPinned { let unpinAction = UIAlertAction(title: "Unpin", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in content.unPin() self.updateUserInterface() }) alertController.addAction(unpinAction) } else { let pinAction = UIAlertAction(title: "Pin", style: .default, handler: {[unowned self](action: UIAlertAction) -> Void in content.pin() self.updateUserInterface() }) alertController.addAction(pinAction) } let removeAction = UIAlertAction(title: "Delete Local Copy", style: .destructive, handler: {[unowned self](action: UIAlertAction) -> Void in content.removeLocal() self.updateUserInterface() }) alertController.addAction(removeAction) } let removeFromRemoteAction = UIAlertAction(title: "Delete Remote File", style: .destructive, handler: {[unowned self](action: UIAlertAction) -> Void in self.confirmForRemovingContent(content) }) alertController.addAction(removeFromRemoteAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func downloadContent(_ content: AWSContent, pinOnCompletion: Bool) { content.download(with: .ifNewerExists, pinOnCompletion: pinOnCompletion, progressBlock: {[weak self] (content: AWSContent, progress: Progress) in guard let strongSelf = self else { return } if strongSelf.contents!.contains( where: {$0 == content} ) { strongSelf.tableView.reloadData() } }) {[weak self] (content: AWSContent?, data: Data?, error: Error?) in guard let strongSelf = self else { return } if let error = error { print("Failed to download a content from a server. \(error)") strongSelf.showSimpleAlertWithTitle("Error", message: "Failed to download a content from a server.", cancelButtonTitle: "OK") } strongSelf.updateUserInterface() } } fileprivate func openContent(_ content: AWSContent) { if content.isAudioVideo() { // Video and sound files let directories: [AnyObject] = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [AnyObject] let cacheDirectoryPath = directories.first as! String let movieURL: URL = URL(fileURLWithPath: "\(cacheDirectoryPath)/\(content.key.getLastPathComponent())") try? content.cachedData.write(to: movieURL, options: [.atomic]) let player = AVPlayer(url: movieURL) let playerViewController = AVPlayerViewController() playerViewController.player = player self.present(playerViewController, animated: true) { playerViewController.player!.play() } } else if content.isImage() { // Image files // Image files let storyboard = UIStoryboard(name: "UserFiles", bundle: nil) let imageViewController = storyboard.instantiateViewController(withIdentifier: "UserFilesImageViewController") as! UserFilesImageViewController imageViewController.image = UIImage(data: content.cachedData) imageViewController.title = content.key navigationController?.pushViewController(imageViewController, animated: true) } else { showSimpleAlertWithTitle("Sorry!", message: "We can only open image, video, and sound files.", cancelButtonTitle: "OK") } } fileprivate func openRemoteContent(_ content: AWSContent) { content.getRemoteFileURL {[weak self] (url: URL?, error: Error?) in guard let strongSelf = self else { return } guard let url = url else { print("Error getting URL for file. \(error)") return } if content.isAudioVideo() { // Open Audio and Video files natively in app. let player = AVPlayer(url: url) let playerViewController = AVPlayerViewController() playerViewController.player = player strongSelf.present(playerViewController, animated: true) { playerViewController.player!.play() } } else { // Open other file types like PDF in web browser. //UIApplication.sharedApplication().openURL(url) let storyboard: UIStoryboard = UIStoryboard(name: "UserFiles", bundle: nil) let webViewController: UserFilesWebViewController = storyboard.instantiateViewController(withIdentifier: "UserFilesWebViewController") as! UserFilesWebViewController webViewController.url = url webViewController.title = content.key strongSelf.navigationController?.pushViewController(webViewController, animated: true) } } } fileprivate func confirmForRemovingContent(_ content: AWSContent) { let alertController = UIAlertController(title: "Confirm", message: "Do you want to delete the content from the server? This cannot be undone.", preferredStyle: .alert) let okayAction = UIAlertAction(title: "Yes", style: .default) {[weak self] (action: UIAlertAction) in guard let strongSelf = self else { return } strongSelf.removeContent(content) } alertController.addAction(okayAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func removeContent(_ content: AWSContent) { content.removeRemoteContent {[weak self] (content: AWSContent?, error: Error?) in guard let strongSelf = self else { return } DispatchQueue.main.async { if let error = error { print("Failed to delete an object from the remote server. \(error)") strongSelf.showSimpleAlertWithTitle("Error", message: "Failed to delete an object from the remote server.", cancelButtonTitle: "OK") } else { strongSelf.showSimpleAlertWithTitle("Object Deleted", message: "The object has been deleted successfully.", cancelButtonTitle: "OK") strongSelf.refreshContents() } } } } // MARK:- Content uploads fileprivate func showImagePicker() { let imagePickerController: UIImagePickerController = UIImagePickerController() imagePickerController.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String] imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } fileprivate func askForFilename(_ data: Data) { let alertController = UIAlertController(title: "File Name", message: "Please specify the file name.", preferredStyle: .alert) alertController.addTextField(configurationHandler: nil) let doneAction = UIAlertAction(title: "Done", style: .default) {[unowned self] (action: UIAlertAction) in let specifiedKey = alertController.textFields!.first!.text! if specifiedKey.characters.count == 0 { self.showSimpleAlertWithTitle("Error", message: "The file name cannot be empty.", cancelButtonTitle: "OK") return } else { let key: String = "\(self.prefix!)\(specifiedKey)" self.uploadWithData(data, forKey: key) } } alertController.addAction(doneAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func askForDirectoryName() { let alertController: UIAlertController = UIAlertController(title: "Directory Name", message: "Please specify the directory name.", preferredStyle: .alert) alertController.addTextField(configurationHandler: nil) let doneAction = UIAlertAction(title: "Done", style: .default) {[unowned self] (action: UIAlertAction) in let specifiedKey = alertController.textFields!.first!.text! guard specifiedKey.characters.count != 0 else { self.showSimpleAlertWithTitle("Error", message: "The directory name cannot be empty.", cancelButtonTitle: "OK") return } let key = "\(self.prefix!)\(specifiedKey)/" self.createFolderForKey(key) } alertController.addAction(doneAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func uploadLocalContent(_ localContent: AWSLocalContent) { localContent.uploadWithPin(onCompletion: false, progressBlock: {[weak self] (content: AWSLocalContent, progress: Progress) in guard let strongSelf = self else { return } DispatchQueue.main.async { // Update the upload UI if it is a new upload and the table is not yet updated if(strongSelf.tableView.numberOfRows(inSection: 0) == 0 || strongSelf.tableView.numberOfRows(inSection: 0) < strongSelf.manager.uploadingContents.count) { strongSelf.updateUploadUI() } else { strongSelf.tableView.reloadData() } } }, completionHandler: {[weak self] (content: AWSLocalContent?, error: Error?) in guard let strongSelf = self else { return } strongSelf.updateUploadUI() if let error = error { print("Failed to upload an object. \(error)") strongSelf.showSimpleAlertWithTitle("Error", message: "Failed to upload an object.", cancelButtonTitle: "OK") } else { if localContent.key.hasPrefix(UserFilesUploadsDirectoryName) { strongSelf.showSimpleAlertWithTitle("File upload", message: "File upload completed successfully for \(localContent.key).", cancelButtonTitle: "Okay") } strongSelf.refreshContents() } }) updateUploadUI() } fileprivate func uploadWithData(_ data: Data, forKey key: String) { let localContent = manager.localContent(with: data, key: key) uploadLocalContent(localContent) } fileprivate func createFolderForKey(_ key: String) { let localContent = manager.localContent(with: nil, key: key) uploadLocalContent(localContent) } fileprivate func updateUploadUI() { DispatchQueue.main.async { self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return manager.uploadingContents.count } if let contents = self.contents { if isPrefixUploadsFolder() { // Uploads folder is write-only and table view show only one cell with that info return 1 } else if isPrefixUserProtectedFolder() { // the first cell of the table view is the .. folder return contents.count + 1 } else { return contents.count } } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "UserFilesUploadCell", for: indexPath) as! UserFilesUploadCell if indexPath.row < manager.uploadingContents.count { let localContent: AWSLocalContent = manager.uploadingContents[indexPath.row] cell.localContent = localContent } cell.prefix = prefix return cell } let cell: UserFilesCell = tableView.dequeueReusableCell(withIdentifier: "UserFilesCell", for: indexPath) as! UserFilesCell var content: AWSContent? = nil if isPrefixUserProtectedFolder() { if indexPath.row > 0 && indexPath.row < contents!.count + 1 { content = contents![indexPath.row - 1] } } else { if indexPath.row < contents!.count { content = contents![indexPath.row] } } cell.prefix = prefix cell.content = content if isPrefixUserProtectedFolder() && indexPath.row == 0 { cell.fileNameLabel.text = ".." cell.accessoryType = .disclosureIndicator cell.detailLabel.text = "This is a folder" } else if isPrefixUploadsFolder() { cell.fileNameLabel.text = "This folder is write only" cell.accessoryType = .disclosureIndicator cell.detailLabel.text = "" } return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let contents = self.contents, indexPath.row == contents.count - 1, !didLoadAllContents { loadMoreContents() } } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // Process only if it is a listed file. Ignore actions for files that are uploading. if indexPath.section != 0 { var content: AWSContent? if isPrefixUploadsFolder() { showImagePicker() return } else if !isPrefixUserProtectedFolder() { content = contents![indexPath.row] } else { if indexPath.row > 0 { content = contents![indexPath.row - 1] } else { let storyboard: UIStoryboard = UIStoryboard(name: "UserFiles", bundle: nil) let viewController: UserFilesViewController = storyboard.instantiateViewController(withIdentifier: "UserFiles") as! UserFilesViewController viewController.prefix = "\(UserFilesProtectedDirectoryName)/" viewController.segmentedControlSelected = self.segmentedControlSelected navigationController?.pushViewController(viewController, animated: true) return } } if content!.isDirectory { let storyboard: UIStoryboard = UIStoryboard(name: "UserFiles", bundle: nil) let viewController: UserFilesViewController = storyboard.instantiateViewController(withIdentifier: "UserFiles") as! UserFilesViewController viewController.prefix = content!.key viewController.segmentedControlSelected = self.segmentedControlSelected navigationController?.pushViewController(viewController, animated: true) } else { let rowRect = tableView.rectForRow(at: indexPath); showActionOptionsForContent(rowRect, content: content!) } } } } // MARK:- UIImagePickerControllerDelegate extension UserFilesViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { dismiss(animated: true, completion: nil) let mediaType = info[UIImagePickerControllerMediaType] as! NSString // Handle image uploads if mediaType.isEqual(to: kUTTypeImage as String) { let image: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage askForFilename(UIImagePNGRepresentation(image)!) } // Handle Video Uploads if mediaType.isEqual(to: kUTTypeMovie as String) { let videoURL: URL = info[UIImagePickerControllerMediaURL] as! URL askForFilename(try! Data(contentsOf: videoURL)) } } } class UserFilesCell: UITableViewCell { @IBOutlet weak var fileNameLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var keepImageView: UIImageView! @IBOutlet weak var downloadedImageView: UIImageView! @IBOutlet weak var progressView: UIProgressView! var prefix: String? var content: AWSContent! { didSet { if self.content == nil { fileNameLabel.text = "" downloadedImageView.isHidden = true keepImageView.isHidden = true detailLabel.text = "" accessoryType = .disclosureIndicator progressView.isHidden = true detailLabel.textColor = UIColor.black return } var displayFilename: String = self.content.key if let prefix = self.prefix { if displayFilename.characters.count > prefix.characters.count { displayFilename = displayFilename.substring(from: prefix.endIndex) } } fileNameLabel.text = displayFilename downloadedImageView.isHidden = !content.isCached keepImageView.isHidden = !content.isPinned var contentByteCount: UInt = content.fileSize if contentByteCount == 0 { contentByteCount = content.knownRemoteByteCount } if content.isDirectory { detailLabel.text = "This is a folder" accessoryType = .disclosureIndicator } else { detailLabel.text = contentByteCount.aws_stringFromByteCount() accessoryType = .none } if let downloadedDate = content.downloadedDate, let knownRemoteLastModifiedDate = content.knownRemoteLastModifiedDate, knownRemoteLastModifiedDate.compare(downloadedDate) == .orderedDescending { detailLabel.text = "\(detailLabel.text!) - New Version Available" detailLabel.textColor = UIColor.blue } else { detailLabel.textColor = UIColor.black } if content.status == .running { progressView.progress = Float(content.progress.fractionCompleted) progressView.isHidden = false } else { progressView.isHidden = true } } } } class UserFilesImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var image: UIImage! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) imageView.image = image } } class UserFilesWebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! var url: URL! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) webView.delegate = self webView.dataDetectorTypes = UIDataDetectorTypes() webView.scalesPageToFit = true webView.loadRequest(URLRequest(url: url)) } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { print("The URL content failed to load \(error)") webView.loadHTMLString("<html><body><h1>Cannot Open the content of the URL.</h1></body></html>", baseURL: nil) } } class UserFilesUploadCell: UITableViewCell { @IBOutlet weak var fileNameLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! var prefix: String? var localContent: AWSLocalContent! { didSet { var displayFilename: String = localContent.key if self.prefix != nil && displayFilename.hasPrefix(self.prefix!) { displayFilename = displayFilename.substring(from: self.prefix!.endIndex) } fileNameLabel.text = displayFilename progressView.progress = Float(localContent.progress.fractionCompleted) } } } // MARK: - Utility extension UserFilesViewController { fileprivate func showSimpleAlertWithTitle(_ title: String, message: String, cancelButtonTitle cancelTitle: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } fileprivate func checkUserProtectedFolder() { let userId = AWSIdentityManager.default().identityId! if isPrefixUserProtectedFolder() { let localContent = self.manager.localContent(with: nil, key: "\(UserFilesProtectedDirectoryName)/\(userId)/") localContent.uploadWithPin(onCompletion: false, progressBlock: {(content: AWSLocalContent?, progress: Progress?) in }, completionHandler: {[weak self](content: AWSContent?, error: Error?) in guard let strongSelf = self else { return } strongSelf.updateUploadUI() if let error = error { print("Failed to load the list of contents. \(error)") strongSelf.showSimpleAlertWithTitle("Error", message: "Failed to load the list of contents.", cancelButtonTitle: "OK") } strongSelf.updateUserInterface() }) } } fileprivate func isPrefixUserProtectedFolder() -> Bool { let userId = AWSIdentityManager.default().identityId! let protectedUserDirectory = "\(UserFilesProtectedDirectoryName)/\(userId)/" return AWSSignInManager.sharedInstance().isLoggedIn && protectedUserDirectory == prefix } fileprivate func isPrefixUploadsFolder() -> Bool { let uploadsDirectory = "\(UserFilesUploadsDirectoryName)/" return uploadsDirectory == prefix } } extension AWSContent { fileprivate func isAudioVideo() -> Bool { let lowerCaseKey = self.key.lowercased() return lowerCaseKey.hasSuffix(".mov") || lowerCaseKey.hasSuffix(".mp4") || lowerCaseKey.hasSuffix(".mpv") || lowerCaseKey.hasSuffix(".3gp") || lowerCaseKey.hasSuffix(".mpeg") || lowerCaseKey.hasSuffix(".aac") || lowerCaseKey.hasSuffix(".mp3") } fileprivate func isImage() -> Bool { let lowerCaseKey = self.key.lowercased() return lowerCaseKey.hasSuffix(".jpg") || lowerCaseKey.hasSuffix(".png") || lowerCaseKey.hasSuffix(".jpeg") } } extension UInt { fileprivate func aws_stringFromByteCount() -> String { if self < 1024 { return "\(self) B" } if self < 1024 * 1024 { return "\(self / 1024) KB" } if self < 1024 * 1024 * 1024 { return "\(self / 1024 / 1024) MB" } return "\(self / 1024 / 1024 / 1024) GB" } } extension String { fileprivate func getLastPathComponent() -> String { let nsstringValue: NSString = self as NSString return nsstringValue.lastPathComponent } }
45.599762
209
0.621774
f5acfbd0a4dd0c42b3068eafb7450266127ed5d6
922
import UIKit struct DefaultTableViewCellViewModel { let text: String? let detail: String? } final class DefaultTableViewCell: UITableViewCell { // MARK: - Initializers init() { super.init(style: .default, reuseIdentifier: "DefaultTableViewCell") } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: "DefaultTableViewCell") } required init?(coder aDecoder: NSCoder) { preconditionFailure() } } // MARK: - ViewModelConfigurable Conformance extension DefaultTableViewCell { func configure(for viewModel: DefaultTableViewCellViewModel?) { guard let viewModel = viewModel else { return } textLabel?.text = viewModel.text textLabel?.tintColor = UIColor.black detailTextLabel?.text = viewModel.detail detailTextLabel?.tintColor = UIColor.gray } }
21.952381
79
0.698482
1db2dde202e39001c50f95a797df8de23e2234ee
3,831
// // LearningStep.swift // // Copyright © 2020 Apple Inc. All rights reserved. // import Foundation import SPCCore // Title optional // Code types: there already // Image/Animation/Video // Assessment types: checkboxes, multiple choice public class LearningStep { public enum StepType: String { case unknown case check case code case context case experiment case find public var localizedName: String { switch self { case .unknown: return NSLocalizedString("Unknown", tableName: "SPCLearningTrails", comment: "Learning step type: unknown") case .check: return NSLocalizedString("Check", tableName: "SPCLearningTrails", comment: "Learning step type: check") case .code: return NSLocalizedString("Code", tableName: "SPCLearningTrails", comment: "Learning step type: code") case .context: return NSLocalizedString("Context", tableName: "SPCLearningTrails", comment: "Learning step type: context") case .experiment: return NSLocalizedString("Experiment", tableName: "SPCLearningTrails", comment: "Learning step type: experiment") case .find: return NSLocalizedString("Find", tableName: "SPCLearningTrails", comment: "Learning step type: find") } } } public var identifier: String public var index: Int = 0 public var type: StepType = .unknown public weak var parentTrail: LearningTrail? public var title: String? public var rootBlock = LearningBlock.createRootBlock() public var blocks: [LearningBlock] { return flattenendBlocks(rootBlock.childBlocks) } private func flattenendBlocks(_ blocks: [LearningBlock]) -> [LearningBlock] { return blocks.flatMap { (myBlock) -> [LearningBlock] in var result = [myBlock] result += flattenendBlocks(myBlock.childBlocks) return result } } public var signature: String { return blocks.map { $0.signature }.joined(separator: "\n") } /// True if the step is assessable. public var isAssessable: Bool = false /// The current state of assessment for this step. public var assessmentState: LearningAssessment.State = .unknown private var stateHasBeenLoaded = false public init(in trail: LearningTrail, identifier: String, index: Int) { self.parentTrail = trail self.identifier = identifier self.index = index } func initializeState() { rootBlock.initializeVisibleState(visible: true) rootBlock.initializeGroupState(level: 0) } // Loads any previously saved state. func loadState(isValid: Bool) { guard !stateHasBeenLoaded else { return } stateHasBeenLoaded = true guard let responseBlock = blocks.filter({ $0.blockType == .response }).first else { return } // Currently only response blocks need state loaded. // One response block per step max. let xmlContent = responseBlock.xmlPackagedContent(.linesLeftTrimmed) if let learningResponse = LearningResponse(identifier: responseBlock.accessibilityIdentifier, xml: xmlContent, attributes: responseBlock.attributes) { if !isValid { learningResponse.clearState() assessmentState = .unknown } _ = learningResponse.loadState() if isAssessable && learningResponse.isAnsweredCorrectly { assessmentState = .completedSuccessfully } } } } extension LearningStep: Equatable { public static func == (lhs: LearningStep, rhs: LearningStep) -> Bool { return lhs.identifier == rhs.identifier } }
35.146789
158
0.643435
8f4510f3d63df25580e92f2d11b5497d70aa0aba
1,549
@testable import WeightScale import Foundation class StubUserDefaultsWrapper: UserDefaultsWrapper { private(set) var saveData_argument_key: String = "" private(set) var saveData_argument_value: Double = -1.0 func saveData(key: String, value: Double) { saveData_argument_key = key saveData_argument_value = value } private(set) var saveDataBool_argument_key: String = "" private(set) var saveDataBool_argument_value: Bool = false func saveData(key: String, value: Bool) { saveDataBool_argument_key = key saveDataBool_argument_value = value } private(set) var saveDataDate_argument_key: String = "" private(set) var saveDataDate_argument_value: Date = Date() func saveData(key: String, value: Date) { saveDataDate_argument_key = key saveDataDate_argument_value = value } private(set) var loadData_argument_key: String = "" var loadData_returnValue = -1.0 func loadData(key: String) -> Double { loadData_argument_key = key return loadData_returnValue } private(set) var loadDataBool_argument_key: String = "" var loadDataBool_returnValue = false func loadData(key: String) -> Bool { loadDataBool_argument_key = key return loadDataBool_returnValue } private(set) var loadDataDate_argument_key: String = "" var loadDataDate_returnValue: Date? = nil func loadData(key: String) -> Date? { loadDataDate_argument_key = key return loadDataDate_returnValue } }
32.270833
63
0.699161
ef2121e36fabddd5f9372510a567ad48b3a0c4de
1,408
// // proj_DODUITests.swift // proj_DODUITests // // Created by 이강욱 on 2021/04/05. // import XCTest class proj_DODUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.744186
182
0.65483
0a5cf4b880967bfc664e9e2dfeecf560a2d49018
6,901
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Workflow import XCTest extension WorkflowAction { /// Returns a state tester containing `self`. public static func tester(withState state: WorkflowType.State) -> WorkflowActionTester<WorkflowType, Self> { return WorkflowActionTester(state: state) } } /// Testing helper that chains action sending and state/output assertions /// to make tests easier to write. /// /// ``` /// MyWorkflow.Action /// .tester(withState: .firstState) /// .send(action: .exampleAction) /// .verifyOutput { output in /// XCTAssertEqual(.finished, output) /// } /// .verifyState { state in /// XCTAssertEqual(.differentState, state) /// } /// ``` /// /// Or to assert that an action produces no output: /// /// ``` /// MyWorkflow.Action /// .tester(withState: .firstState) /// .send(action: .actionProducingNoOutput) /// .assertNoOutput() /// .verifyState { state in /// XCTAssertEqual(.differentState, state) /// } /// ``` /// /// If your State or Output are `Equatable`, you can use the convenience assertion methods: /// ``` /// MyWorkflow.Action /// .tester(withState: .firstState) /// .send(action: .exampleAction) /// .assert(output: .finished) /// .assert(state: .differentState) /// ``` public struct WorkflowActionTester<WorkflowType, Action> where Action: WorkflowAction, Action.WorkflowType == WorkflowType { /// The current state internal let state: WorkflowType.State internal let output: WorkflowType.Output? /// Initializes a new state tester fileprivate init(state: WorkflowType.State, output: WorkflowType.Output? = nil) { self.state = state self.output = output } /// Sends an action to the reducer. /// /// - parameter action: The action to send. /// /// - returns: A new state tester containing the state and output (if any) after the update. @discardableResult public func send(action: Action) -> WorkflowActionTester<WorkflowType, Action> { var newState = state let output = action.apply(toState: &newState) return WorkflowActionTester(state: newState, output: output) } /// Asserts that the action produced no output /// /// - returns: A tester containing the current state and output. @discardableResult public func assertNoOutput( file: StaticString = #file, line: UInt = #line ) -> WorkflowActionTester<WorkflowType, Action> { if let output = output { XCTFail("Expected no output, but got \(output).", file: file, line: line) } return self } /// Invokes the given closure (which is intended to contain test assertions) with the produced output. /// If the previous action produced no output, the triggers a test failure and does not execute the closure. /// /// - parameter assertions: A closure that accepts a single output value. /// /// - returns: A tester containing the current state and output. @discardableResult public func verifyOutput( file: StaticString = #file, line: UInt = #line, _ assertions: (WorkflowType.Output) -> Void ) -> WorkflowActionTester<WorkflowType, Action> { guard let output = output else { XCTFail("No output was produced", file: file, line: line) return self } assertions(output) return self } /// Invokes the given closure (which is intended to contain test assertions) with the current state. /// /// - parameter assertions: A closure that accepts a single state value. /// /// - returns: A tester containing the current state and output. @discardableResult public func verifyState(_ assertions: (WorkflowType.State) -> Void) -> WorkflowActionTester<WorkflowType, Action> { assertions(state) return self } /// Invokes the given closure (which is intended to contain test assertions) with the current state. /// /// - parameter assertions: A closure that accepts a single state value. /// /// - returns: A tester containing the current state. } extension WorkflowActionTester where WorkflowType.State: Equatable { /// Triggers a test failure if the current state does not match the given expected state /// /// - Parameters: /// - expectedState: The expected state /// - returns: A tester containing the current state and output. @discardableResult public func assert(state expectedState: WorkflowType.State, file: StaticString = #file, line: UInt = #line) -> WorkflowActionTester<WorkflowType, Action> { return verifyState { actualState in XCTAssertEqual(actualState, expectedState, file: file, line: line) } } } extension WorkflowActionTester where WorkflowType.Output: Equatable { /// Triggers a test failure if the produced output does not match the given expected output /// /// - Parameters: /// - expectedState: The expected output /// - returns: A tester containing the current state and output. @discardableResult public func assert(output expectedOutput: WorkflowType.Output, file: StaticString = #file, line: UInt = #line) -> WorkflowActionTester<WorkflowType, Action> { return verifyOutput { actualOutput in XCTAssertEqual(actualOutput, expectedOutput, file: file, line: line) } } } extension WorkflowActionTester { private func legacyVerifyOutputShim(_ assertions: (WorkflowType.Output?) -> Void) -> WorkflowActionTester<WorkflowType, Action> { assertions(output) return self } @available(*, deprecated, message: "use `send(action:)` followed by `verifyOutput(_:)`, `verify(output:)` or `assertNoOutput()`") @discardableResult public func send(action: Action, outputAssertions: (WorkflowType.Output?) -> Void = { _ in }) -> WorkflowActionTester<WorkflowType, Action> { return send(action: action) .legacyVerifyOutputShim(outputAssertions) } @available(*, deprecated, renamed: "verifyState") @discardableResult public func assertState(_ assertions: (WorkflowType.State) -> Void) -> WorkflowActionTester<WorkflowType, Action> { return verifyState(assertions) } }
37.505435
162
0.670917
337e9aab7d6f024d4068dc2a7729f23e3c084ef6
2,642
import _Differentiation import Foundation infix operator • : MultiplicationPrecedence struct Vector: Differentiable, AdditiveArithmetic, Hashable { var x, y: Double static let zero = Vector(x: 0, y: 0) static let unitX = Vector(x: 1, y: 0) static let unitY = Vector(x: 0, y: 1) @differentiable(reverse) var normalized: Vector { Vector(x: x / magnitude, y: y / magnitude) } @differentiable(reverse) var perpendicular: Vector { Vector(x: y , y: -x) } @differentiable(reverse) static func + (_ lhs: Vector, _ rhs: Vector) -> Vector { Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } @differentiable(reverse) static func - (_ lhs: Vector, _ rhs: Vector) -> Vector { Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } @differentiable(reverse) static func * (_ lhs: Double, _ rhs: Vector) -> Vector { Vector(x: lhs * rhs.x, y: lhs * rhs.y) } @differentiable(reverse) static func / (_ lhs: Vector, _ rhs: Double) -> Vector { Vector(x: lhs.x / rhs, y: lhs.y / rhs) } @differentiable(reverse) static func • (_ lhs: Vector, _ rhs: Vector) -> Double { lhs.x * rhs.x + lhs.y * rhs.y } @differentiable(reverse) var magnitude: Double { sqrt(x * x + y * y) } } extension Vector: ExpressibleByArrayLiteral { init(arrayLiteral elements: Double...) { precondition(elements.count == 2) x = elements[0] y = elements[1] } } // MARK: - // FIXME: Workaround for derivatives and functions in different files func sqrt(_ x: Double) -> Double { Darwin.sqrt(x) } @derivative(of: sqrt) func vjpSqrt(_ x: Double) -> (value: Double, pullback: (Double) -> (Double)) { (value: sqrt(x), pullback: { chain in chain * (1 / (2 * sqrt(x))) } ) } // MARK: - // FIXME: Workaround for non-differentiable co-routines (https://bugs.swift.org/browse/TF-1078) extension Array { @differentiable(reverse where Element: Differentiable) func updated(at index: Int, with newValue: Element) -> [Element] { var result = self result[index] = newValue return result } } extension Array where Element: Differentiable { @derivative(of: updated) func vjpUpdated(at index: Int, with newValue: Element) -> ( value: [Element], pullback: (TangentVector) -> (TangentVector, Element.TangentVector) ) { let value = updated(at: index, with: newValue) return (value, { v in var dself = v dself.base[index] = .zero return (dself, v[index]) }) } }
27.520833
95
0.595382
56e9580c6e5f9c88927f9ef229a2a36c75a3332f
3,647
import Foundation import Result import JacKit fileprivate let jack = Jack() extension Weibo { public class SignInResult: BaseSignInResult, SignInResultType { public var nickname: String? { return userInfo["screen_name"] as? String } public var gender: Gender? { if let text = userInfo["gender"] as? String { switch text { case "m": return .male case "f": return .female default: return nil } } else { return nil } } public var avatarURL: URL? { for key in ["avatar_large", "profile_image_url"] { if let urlString = userInfo[key] as? String, let url = URL(string: urlString) { return url } } return nil } public var location: String? { return userInfo["location"] as? String } } // used in login and constructing sharing request var authorizationRequest: WBAuthorizeRequest { let request = WBAuthorizeRequest() request.redirectURI = "https://api.weibo.com/oauth2/default.html" request.scope = "all" request.shouldShowWebViewForAuthIfCannotSSO = true // disable H5 signIn request.shouldOpenWeiboAppInstallPageIfNotInstalled = true return request } public static func signIn(completion: @escaping SignInCompletion) { Weibo.shared._signIn(completion: completion) } private func _signIn(completion: @escaping SignInCompletion) { begin(.login(completion: completion)) WeiboSDK.send(authorizationRequest) } func _getUserInfo(accessToken: String, userID: String, completion block: @escaping ([String: Any]?, SocialKit.Error?) -> ()) { let baseURLString = "https://api.weibo.com/2/users/show.json" guard var urlcmp = URLComponents(string: baseURLString) else { end(with: .signIn(result: nil, error: .api(reason: "Creating URLComponents from url string (\(baseURLString)) failed"))) return } urlcmp.queryItems = [ URLQueryItem(name: "access_token", value: accessToken), URLQueryItem(name: "uid", value: userID), ] guard let url = urlcmp.url else { end(with: .signIn(result: nil, error: .api(reason: "Appending query itesms to base URL string failed"))) return } let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: url) { data, response, error in guard error == nil else { block(nil, SocialKit.Error.send(reason: "network error, \(error!)")) return } guard let httpResponse = response as? HTTPURLResponse else { block(nil, SocialKit.Error.send(reason: "URL loading error, casting to HTTPURLResponse failed")) return } guard 200..<300 ~= httpResponse.statusCode else { let code = httpResponse.statusCode let text = HTTPURLResponse.localizedString(forStatusCode: code) block(nil, SocialKit.Error.send(reason: "URL loading error, unexpected status code \(code) - \(text)")) return } guard let data = data else { block(nil, SocialKit.Error.send(reason: "URL loading error, no data received")) return } do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { block(json, nil) } else { block(nil, SocialKit.Error.api(reason: "casting deserialized object to `[String: Any]` failed.")) } } catch { let e = SocialKit.Error.api(reason: "deserializing response JSON data failed, \(error)") block(nil, e) } } task.resume() } }
30.140496
128
0.644639
268db36a2226c85aa465636496a7b2f1d587de9c
677
import Foundation @testable import xkcd_viewer class MockAPIManager: APIManager { var fetchComicCalledTimes: Int = 0 var fetchComicThrowsException = false var fetchComicReturn: Comic? var callThrough = true override func fetchComic(withId identifier: String, completion: @escaping (Comic?, String?) -> Void) { fetchComicCalledTimes += 1 if callThrough { super.fetchComic(withId: "", completion: completion) } else { if fetchComicThrowsException { completion(nil, "Failed") } else { completion(fetchComicReturn, nil) } } } }
26.038462
106
0.604136
ed37f9a243307e9b3d519b7d60313ccf956e9bf2
3,006
// // ContactVC.swift // UberRider // // Created by lieon on 2017/3/31. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit class ContactVC: UIViewController { @IBOutlet weak var tableView: UITableView! fileprivate var contactVM: ContactViewModel = ContactViewModel() @IBAction func backAction(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func addAction(_ sender: Any) { addContact() } override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } extension ContactVC: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contactVM.contacts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ContactCell = tableView.dequeueReusableCell(for: indexPath) if indexPath.row <= contactVM.contacts.count - 1 { cell.textLabel?.text = contactVM.contacts[indexPath.row].name } return cell } } extension ContactVC: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let destVC: ChatVC = UIStoryboard.findVC(storyboardName: StoryboardName.chat, identifier: ChatVC.identifier) if indexPath.row <= contactVM.contacts.count - 1 { destVC.tofriendID = contactVM.contacts[indexPath.row].id ?? "" destVC.tofriendName = contactVM.contacts[indexPath.row].name ?? "" navigationController?.pushViewController(destVC, animated: true) } } } extension ContactVC { fileprivate func setupUI() { tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: CellID.contactCellID) tableView.register(UINib(nibName: NibName.contactCell, bundle: nil), forCellReuseIdentifier: ContactCell.identifier) } fileprivate func loadData() { contactVM.getContacts { self.tableView.reloadData() } } fileprivate func addContact() { let alter = UIAlertController(title: "Add A Friend", message: nil, preferredStyle: .alert) alter.addTextField { textFied in textFied.placeholder = "Please enter a valid email" } let enterAction = UIAlertAction(title: "OK", style: .default) { (action) in if let textField = alter.textFields?.first, let email = textField.text { self.contactVM.addConact(email: email, callback: { mesage in self.show(title: "Add Info", message: mesage) }) } } alter.addAction(enterAction) present(alter, animated: true, completion: nil) } }
32.322581
124
0.644711
034e7c13fc21297b6fad39edde3b34840af6d72c
2,896
// // ViewController.swift // Example // // Created by muukii on 2016/11/22. // Copyright © 2016 muukii. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxOrigami final class ViewController: UIViewController { // MARK: - Properties @IBOutlet weak var scaleBox: UIView! @IBOutlet weak var box: UIView! @IBOutlet weak var maxColorBox: UIView! @IBOutlet weak var minColorBox: UIView! @IBOutlet weak var progressSlider: UISlider! @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var valueSlider: UISlider! @IBOutlet weak var minLabel: UILabel! @IBOutlet weak var maxLabel: UILabel! let disposeBag = DisposeBag() // MARK: - Functions override func viewDidLoad() { super.viewDidLoad() let animation = CABasicAnimation(keyPath: "transform") animation.fromValue = CATransform3DMakeScale(0.5, 1, 1) animation.toValue = CATransform3DMakeScale(1.9, 0.4, 1) animation.duration = 1 scaleBox.layer.add(animation, forKey: nil) // self.scaleBox.transform = CGAffineTransform(scaleX: 0.5, y: 1) // UIView.animate(withDuration: 1, animations: { // self.scaleBox.transform = CGAffineTransform(scaleX: 1.9, y: 0.4) // }) scaleBox.layer.speed = 0 let startColor = UIColor(red:0.24, green:0.42, blue:0.58, alpha:1.00) let endColor = UIColor(red:0.93, green:0.72, blue:0.16, alpha:1.00) minColorBox.backgroundColor = startColor maxColorBox.backgroundColor = endColor minLabel.text = String(valueSlider.minimumValue) maxLabel.text = String(valueSlider.maximumValue) let progress = valueSlider.rx.value .progress( start: Observable.just(valueSlider.minimumValue), end: Observable.just(valueSlider.maximumValue) ) .do(onNext: { progress in // Debug presentation self.progressSlider.value = Float(progress) self.progressLabel.text = String(Float(progress)) }) .shareReplay(1) progress .transition( start: Observable<UIColor>.just(startColor), end: Observable<UIColor>.just(endColor) ) .bindNext { color in self.box.backgroundColor = color } .addDisposableTo(disposeBag) progress .asTimeOffset() .bindNext { time in self.scaleBox.layer.timeOffset = time } progress .progress( start: Observable<CGFloat>.just(0), end: Observable<CGFloat>.just(0.3) ) .transition( start: Observable<CGFloat>.just(0), end: Observable<CGFloat>.just(1) ) .bindNext { alpha in } progress.transition( start: Observable<CGFloat>.just(0.1), end: Observable<CGFloat>.just(1.3) ) .debug() .bindNext { scale in // self.scaleBox.transform = CGAffineTransform(scaleX: scale, y: scale) } .addDisposableTo(disposeBag) } }
26.09009
78
0.660221
4b1417fe4ab96f019cc14b0e276771f9eccee2a3
11,498
// Copyright 2020 Espressif Systems // // 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. // // ESPProvision.swift // ESPProvision // import Foundation /// Provision class which exposes the main API for provisioning /// the device with Wifi credentials. class ESPProvision { private let session: ESPSession private let transportLayer: ESPCommunicable private let securityLayer: ESPCodeable public static let CONFIG_TRANSPORT_KEY = "transport" public static let CONFIG_SECURITY_KEY = "security1" public static let CONFIG_PROOF_OF_POSSESSION_KEY = "proofOfPossession" public static let CONFIG_BASE_URL_KEY = "baseUrl" public static let CONFIG_WIFI_AP_KEY = "wifiAPPrefix" public static let CONFIG_TRANSPORT_WIFI = "wifi" public static let CONFIG_TRANSPORT_BLE = "ble" public static let CONFIG_SECURITY_SECURITY0 = "security0" public static let CONFIG_SECURITY_SECURITY1 = "security1" /// Create Provision object with a Session object /// Here the Provision class will require a session /// which has been successfully initialised by calling Session.initialize /// /// - Parameter session: Initialised session object init(session: ESPSession) { ESPLog.log("Initialising provision class.") self.session = session transportLayer = session.transportLayer securityLayer = session.securityLayer } /// Send Configuration information relating to the Home /// Wifi network which the device should use for Internet access /// /// - Parameters: /// - ssid: ssid of the home network /// - passphrase: passphrase /// - completionHandler: handler called when config data is sent func configureWifi(ssid: String, passphrase: String, completionHandler: @escaping (Espressif_Status, Error?) -> Swift.Void) { ESPLog.log("Sending configuration info of home network to device.") if session.isEstablished { do { let message = try createSetWifiConfigRequest(ssid: ssid, passphrase: passphrase) if let message = message { transportLayer.SendConfigData(path: transportLayer.utility.configPath, data: message) { response, error in guard error == nil, response != nil else { ESPLog.log("Error while sending config data error: \(error.debugDescription)") completionHandler(Espressif_Status.internalError, error) return } ESPLog.log("Received response.") let status = self.processSetWifiConfigResponse(response: response) completionHandler(status, nil) } } } catch { ESPLog.log("Error while creating config request error: \(error.localizedDescription)") completionHandler(Espressif_Status.internalError, error) } } } /// Apply all current configurations on the device. /// A typical flow will be /// Initialize session -> Set config (1 or more times) -> Apply config /// This API call will also start a poll for getting Wifi connection status from the device /// /// - Parameters: /// - completionHandler: handler to be called when apply config message is sent /// - wifiStatusUpdatedHandler: handler to be called when wifi status is updated on the device func applyConfigurations(completionHandler: @escaping (Espressif_Status, Error?) -> Void, wifiStatusUpdatedHandler: @escaping (Espressif_WifiStationState, Espressif_WifiConnectFailedReason, Error?) -> Void) { ESPLog.log("Applying Wi-Fi configuration...") if session.isEstablished { do { let message = try createApplyConfigRequest() if let message = message { transportLayer.SendConfigData(path: transportLayer.utility.configPath, data: message) { response, error in guard error == nil, response != nil else { ESPLog.log("Error while applying Wi-Fi configuration: \(error.debugDescription)") completionHandler(Espressif_Status.internalError, error) return } ESPLog.log("Received response.") let status = self.processApplyConfigResponse(response: response) completionHandler(status, nil) self.pollForWifiConnectionStatus { wifiStatus, failReason, error in wifiStatusUpdatedHandler(wifiStatus, failReason, error) } } } } catch { ESPLog.log("Error while creating configuration request: \(error.localizedDescription)") completionHandler(Espressif_Status.internalError, error) } } } private func pollForWifiConnectionStatus(completionHandler: @escaping (Espressif_WifiStationState, Espressif_WifiConnectFailedReason, Error?) -> Swift.Void) { do { ESPLog.log("Start polling for Wi-Fi connection status...") let message = try createGetWifiConfigRequest() if let message = message { transportLayer.SendConfigData(path: transportLayer.utility.configPath, data: message) { response, error in guard error == nil, response != nil else { ESPLog.log("Error on polling request: \(error.debugDescription)") completionHandler(Espressif_WifiStationState.disconnected, Espressif_WifiConnectFailedReason.UNRECOGNIZED(0), error) return } ESPLog.log("Response received.") do { let (stationState, failReason) = try self.processGetWifiConfigStatusResponse(response: response) if stationState == .connected { ESPLog.log("Status: connected.") completionHandler(stationState, Espressif_WifiConnectFailedReason.UNRECOGNIZED(0), nil) } else if stationState == .connecting { ESPLog.log("Status: connecting.") sleep(5) self.pollForWifiConnectionStatus(completionHandler: completionHandler) } else { ESPLog.log("Status: failed.") completionHandler(stationState, failReason, nil) } } catch { ESPLog.log("Error while processing response: \(error.localizedDescription)") completionHandler(Espressif_WifiStationState.disconnected, Espressif_WifiConnectFailedReason.UNRECOGNIZED(0), error) } } } } catch { ESPLog.log("Error while creating polling request: \(error.localizedDescription)") completionHandler(Espressif_WifiStationState.connectionFailed, Espressif_WifiConnectFailedReason.UNRECOGNIZED(0), error) } } private func createSetWifiConfigRequest(ssid: String, passphrase: String) throws -> Data? { ESPLog.log("Create set Wi-Fi config request.") var configData = Espressif_WiFiConfigPayload() configData.msg = Espressif_WiFiConfigMsgType.typeCmdSetConfig configData.cmdSetConfig.ssid = Data(ssid.bytes) configData.cmdSetConfig.passphrase = Data(passphrase.bytes) return try securityLayer.encrypt(data: configData.serializedData()) } private func createApplyConfigRequest() throws -> Data? { ESPLog.log("Create apply config request.") var configData = Espressif_WiFiConfigPayload() configData.cmdApplyConfig = Espressif_CmdApplyConfig() configData.msg = Espressif_WiFiConfigMsgType.typeCmdApplyConfig return try securityLayer.encrypt(data: configData.serializedData()) } private func createGetWifiConfigRequest() throws -> Data? { ESPLog.log("Create get Wi-Fi config request.") var configData = Espressif_WiFiConfigPayload() configData.cmdGetStatus = Espressif_CmdGetStatus() configData.msg = Espressif_WiFiConfigMsgType.typeCmdGetStatus return try securityLayer.encrypt(data: configData.serializedData()) } private func processSetWifiConfigResponse(response: Data?) -> Espressif_Status { ESPLog.log("Process set Wi-Fi config response.") guard let response = response else { return Espressif_Status.invalidArgument } let decryptedResponse = securityLayer.decrypt(data: response)! var responseStatus: Espressif_Status = .invalidArgument do { let configResponse = try Espressif_WiFiConfigPayload(serializedData: decryptedResponse) responseStatus = configResponse.respGetStatus.status } catch { ESPLog.log(error.localizedDescription) } return responseStatus } private func processApplyConfigResponse(response: Data?) -> Espressif_Status { ESPLog.log("Process apply Wi-Fi config response.") guard let response = response else { return Espressif_Status.invalidArgument } let decryptedResponse = securityLayer.decrypt(data: response)! var responseStatus: Espressif_Status = .invalidArgument do { let configResponse = try Espressif_WiFiConfigPayload(serializedData: decryptedResponse) responseStatus = configResponse.respApplyConfig.status } catch { ESPLog.log(error.localizedDescription) } return responseStatus } private func processGetWifiConfigStatusResponse(response: Data?) throws -> (Espressif_WifiStationState, Espressif_WifiConnectFailedReason) { ESPLog.log("Process get Wi-Fi config status response.") guard let response = response else { return (Espressif_WifiStationState.disconnected, Espressif_WifiConnectFailedReason.UNRECOGNIZED(-1)) } let decryptedResponse = securityLayer.decrypt(data: response)! var responseStatus = Espressif_WifiStationState.disconnected var failReason = Espressif_WifiConnectFailedReason.UNRECOGNIZED(-1) let configResponse = try Espressif_WiFiConfigPayload(serializedData: decryptedResponse) responseStatus = configResponse.respGetStatus.staState failReason = configResponse.respGetStatus.failReason return (responseStatus, failReason) } }
47.908333
162
0.636545
2613a3bcbdf44718c3d7a93d906afcfee843c095
9,692
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-2020 Datadog, Inc. */ import Foundation #if !DD_COMPILED_FOR_INTEGRATION_TESTS /// This file is compiled both for Unit and Integration tests. /// * The Unit Tests target can see `Datadog` by `@testable import Datadog`. /// * In Integration Tests target we want to compile `Datadog` in "Release" configuration, so testability is not possible. /// This compiler statement gives both targets the visibility of `RUMDataModels.swift` either by import or direct compilation. @testable import Datadog #endif /// An error thrown by the `RUMSessionMatcher` if it spots an inconsistency in tracked RUM Session, e.g. when /// two RUM View events have the same `view.id` but different path (which is not allowed by the RUM product constraints). struct RUMSessionConsistencyException: Error, CustomStringConvertible { let description: String } internal class RUMSessionMatcher { // MARK: - Initialization /// Takes the array of `RUMEventMatchers` and groups them by session ID. /// For each distinct session ID, the `RUMSessionMatcher` is created. /// Each `RUMSessionMatcher` groups its RUM Events by kind and `ViewVisit`. class func groupMatchersBySessions(_ matchers: [RUMEventMatcher]) throws -> [RUMSessionMatcher] { let eventMatchersBySessionID: [String: [RUMEventMatcher]] = try Dictionary(grouping: matchers) { eventMatcher in try eventMatcher.jsonMatcher.value(forKeyPath: "session.id") as String } return try eventMatchersBySessionID .map { try RUMSessionMatcher(sessionEventMatchers: $0.value) } } // MARK: - View Visits /// Single RUM View visit tracked in this RUM Session. /// Groups all the `RUMEvents` send during this visit. class ViewVisit { /// The identifier of all `RUM Views` tracked during this visit. let viewID: String init(viewID: String) { self.viewID = viewID } /// The `name` of the visited RUM View. /// Corresponds to the "VIEW NAME" in RUM Explorer. fileprivate(set) var name: String = "" /// The `path` of the visited RUM View. /// Corresponds to the "VIEW URL" in RUM Explorer. fileprivate(set) var path: String = "" /// `RUMView` events tracked during this visit. fileprivate(set) var viewEvents: [RUMViewEvent] = [] /// `RUMEventMatchers` corresponding to item in `viewEvents`. fileprivate(set) var viewEventMatchers: [RUMEventMatcher] = [] /// `RUMAction` events tracked during this visit. fileprivate(set) var actionEvents: [RUMActionEvent] = [] /// `RUMResource` events tracked during this visit. fileprivate(set) var resourceEvents: [RUMResourceEvent] = [] /// `RUMError` events tracked during this visit. fileprivate(set) var errorEvents: [RUMErrorEvent] = [] } /// An array of view visits tracked during this RUM Session. /// Each `ViewVisit` is determined by unique `view.id` and groups all RUM events linked to that `view.id`. let viewVisits: [ViewVisit] private init(sessionEventMatchers: [RUMEventMatcher]) throws { // Sort events so they follow increasing time order let sessionEventOrderedByTime = try sessionEventMatchers.sorted { firstEvent, secondEvent in let firstEventTime: UInt64 = try firstEvent.jsonMatcher.value(forKeyPath: "date") let secondEventTime: UInt64 = try secondEvent.jsonMatcher.value(forKeyPath: "date") return firstEventTime < secondEventTime } let eventsMatchersByType: [String: [RUMEventMatcher]] = try Dictionary(grouping: sessionEventOrderedByTime) { eventMatcher in try eventMatcher.jsonMatcher.value(forKeyPath: "type") as String } // Get RUM Events by kind: let viewEventMatchers = eventsMatchersByType["view"] ?? [] let viewEvents: [RUMViewEvent] = try viewEventMatchers.map { matcher in try matcher.model() } let actionEvents: [RUMActionEvent] = try (eventsMatchersByType["action"] ?? []) .map { matcher in try matcher.model() } let resourceEvents: [RUMResourceEvent] = try (eventsMatchersByType["resource"] ?? []) .map { matcher in try matcher.model() } let errorEvents: [RUMErrorEvent] = try (eventsMatchersByType["error"] ?? []) .map { matcher in try matcher.model() } // Validate each group of events individually try validate(rumResourceEvents: resourceEvents) // Group RUMView events into ViewVisits: let uniqueViewIDs = Set(viewEvents.map { $0.view.id }) let visits = uniqueViewIDs.map { viewID in ViewVisit(viewID: viewID) } var visitsByViewID: [String: ViewVisit] = [:] visits.forEach { visit in visitsByViewID[visit.viewID] = visit } // Group RUM Events and their matchers by View Visits: try zip(viewEvents, viewEventMatchers).forEach { rumEvent, matcher in if let visit = visitsByViewID[rumEvent.view.id] { visit.viewEvents.append(rumEvent) visit.viewEventMatchers.append(matcher) if visit.name.isEmpty { visit.name = rumEvent.view.name! } else if visit.name != rumEvent.view.name { throw RUMSessionConsistencyException( description: "The RUM View name: \(rumEvent) is different than other RUM View names for the same `view.id`." ) } if visit.path.isEmpty { visit.path = rumEvent.view.url } else if visit.path != rumEvent.view.url { throw RUMSessionConsistencyException( description: "The RUM View url: \(rumEvent) is different than other RUM View urls for the same `view.id`." ) } } else { throw RUMSessionConsistencyException( description: "Cannot link RUM Event: \(rumEvent) to `RUMSessionMatcher.ViewVisit` by `view.id`." ) } } try actionEvents.forEach { rumEvent in if let visit = visitsByViewID[rumEvent.view.id] { visit.actionEvents.append(rumEvent) } else { throw RUMSessionConsistencyException( description: "Cannot link RUM Event: \(rumEvent) to `RUMSessionMatcher.ViewVisit` by `view.id`." ) } } try resourceEvents.forEach { rumEvent in if let visit = visitsByViewID[rumEvent.view.id] { visit.resourceEvents.append(rumEvent) } else { throw RUMSessionConsistencyException( description: "Cannot link RUM Event: \(rumEvent) to `RUMSessionMatcher.ViewVisit` by `view.id`." ) } } try errorEvents.forEach { rumEvent in if let visit = visitsByViewID[rumEvent.view.id] { visit.errorEvents.append(rumEvent) } else { throw RUMSessionConsistencyException( description: "Cannot link RUM Event: \(rumEvent) to `RUMSessionMatcher.ViewVisit` by `view.id`." ) } } // Sort visits by time let visitsEventOrderedByTime = visits.sorted { firstVisit, secondVisit in let firstVisitTime = firstVisit.viewEvents[0].date let secondVisitTime = secondVisit.viewEvents[0].date return firstVisitTime < secondVisitTime } // Sort view events in each visit by document version visits.forEach { visit in visit.viewEvents = visit.viewEvents.sorted { viewUpdate1, viewUpdate2 in viewUpdate1.dd.documentVersion < viewUpdate2.dd.documentVersion } } // Validate ViewVisit's view.isActive for each events try visits.forEach { visit in var viewWasPreviouslyActive = false try visit.viewEvents.enumerated().forEach { index, viewEvent in let viewIsActive = viewEvent.view.isActive! if index == 0 { if !viewIsActive { throw RUMSessionConsistencyException( description: "A `RUMSessionMatcher.ViewVisit` can't have a first event with an inactive `View`." ) } } else { if !viewWasPreviouslyActive && viewIsActive { throw RUMSessionConsistencyException( description: "A `RUMSessionMatcher.ViewVisit` can't have an event where a `View` is active after the `View` was marked as inactive." ) } } viewWasPreviouslyActive = viewIsActive } } self.viewVisits = visitsEventOrderedByTime } } private func validate(rumResourceEvents: [RUMResourceEvent]) throws { // Each `RUMResourceEvent` should have unique ID let ids = Set(rumResourceEvents.map { $0.resource.id }) if ids.count != rumResourceEvents.count { throw RUMSessionConsistencyException( description: "`resource.id` should be unique - found at least two RUMResourceEvents with the same `resource.id`." ) } }
44.458716
160
0.622266
0151c8a516a0943d5b65dd93373da221ee4126c9
816
// // Simulator.swift // Concurrency // // Created by tommy trojan on 4/11/15. // Copyright (c) 2015 Skyground Media Inc. All rights reserved. // import Foundation class Simulator { class var sharedInstance: Simulator { struct Static { static let instance: Simulator = Simulator() } return Static.instance } func runSimulatorWithMinTime( minTime:Int, maxTime:Int ) -> Double { //Calculate random thread wait time let ms:Int = ( Int(rand()) % ((maxTime - minTime) * 1000) ) + (minTime * 1000) let waitTime:Double = Double(ms) / 1000.0; let timer:Void = NSThread.sleepForTimeInterval(waitTime) print( "Simulator.runSimulatorWithMinTime:", waitTime ) return waitTime } }
24.727273
86
0.601716
fbbade753490f48b3a0fe7b3466e7bb37e799b73
85
import Foundation struct Pair: Codable { let name: String let url: String }
12.142857
22
0.682353
4b80f9952cb39eaa4d384b5c2020ce422f2cbce7
2,667
// // TestCreateExercise.swift // Fitness TrackerUITests // // Created by Maruf Nebil Ogunc on 17.08.2018. // Copyright © 2018 Maruf Nebil Ogunc. All rights reserved. // import XCTest class TestCreateExercise: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCreateExercise() { let app = XCUIApplication() app.buttons["Create Workout"].tap() app.navigationBars["Create Workout"].buttons["Add"].tap() app.textFields["Exercise Name"].tap() app.textFields["Exercise Name"].typeText("Test Exercise") app.textFields["Exercise Name"].typeText("\n") let element = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).children(matching: .other).element let upButton = element.children(matching: .button).matching(identifier: "up").element(boundBy: 0) upButton.tap() upButton.tap() upButton.tap() XCTAssertTrue(app.staticTexts["3 Sets"].exists) let upButton2 = element.children(matching: .button).matching(identifier: "up").element(boundBy: 1) upButton2.tap() upButton2.tap() upButton2.tap() upButton2.tap() XCTAssertTrue(app.staticTexts["4 Reps"].exists) let upButton3 = element.children(matching: .button).matching(identifier: "up").element(boundBy: 2) upButton3.tap() upButton3.tap() upButton3.tap() XCTAssertTrue(app.staticTexts["60 Seconds Rest"].exists) app.navigationBars["Create Exercise"].buttons["Add"].tap() XCTAssertTrue(app.staticTexts["Test Exercise"].exists) XCTAssertTrue(app.staticTexts["3"].exists) XCTAssertTrue(app.staticTexts["4"].exists) XCTAssertTrue(app.staticTexts["60s"].exists) } }
36.040541
182
0.64342
28372aec8d1e496b793112fcee0a6cd412c4a7c0
2,686
// // TableStyleUICollectionViewLayout.swift // CollectionViewLayoutSamples // // Created by 鳥居 隆弘 on 2017/12/25. // Copyright © 2017年 mediba. All rights reserved. // import UIKit class TableStyleUICollectionViewLayout: UICollectionViewLayout { var cellPadding = CGFloat(8.0) var cache = [UICollectionViewLayoutAttributes]() var contentHeight = CGFloat(0.0) var contentWidth: CGFloat { let insets = collectionView!.contentInset return collectionView!.bounds.width - (insets.left + insets.right) } //MARK:- Layout LifeCycle /** 1. レイアウトの事前計算を行う */ override func prepare() { super.prepare() guard cache.isEmpty else{ return } let columnWidth = contentWidth var yOffset: CGFloat = 0 //準備する個数 for item in 0 ..< 80 /*collectionView!.numberOfItems(inSection: 0)*/ { let indexPath = IndexPath(item: item, section: 0) let height:CGFloat = 100.0 let frame = CGRect(x: CGFloat(0), y: yOffset, width: columnWidth, height: height) let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = insetFrame cache.append(attributes) contentHeight = max(contentHeight, frame.maxY) yOffset = yOffset + height } } /** 2. コンテンツのサイズを返す */ override var collectionViewContentSize : CGSize { let height = CGFloat(collectionView!.numberOfItems(inSection: 0) * 100) return CGSize(width: contentWidth, height: height) } /** 3. 表示する要素のリストを返す */ override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() for (count, attributes) in cache.enumerated() { if count >= collectionView!.numberOfItems(inSection: 0){ break } if attributes.frame.intersects(rect) { layoutAttributes.append(attributes) } } return layoutAttributes } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cache[ indexPath.row ] } }
26.333333
105
0.556962
abeb353938190881f2e5b27ce930d20f8d243915
5,894
//import XCTest // //@testable import SteamPress //import Fluent //import Vapor //import Foundation // //class BlogPostTests: XCTestCase { // // static var allTests = [ // ("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests), // ("testThatSlugUrlCalculatedCorrectlyForTitleWithSpaces", testThatSlugUrlCalculatedCorrectlyForTitleWithSpaces), // ("testThatSlugUrlCalculatedCorrectlyForTitleWithPunctuation", testThatSlugUrlCalculatedCorrectlyForTitleWithPunctuation), // ("testThatSlugUrlNotChangedWhenSetWithValidSlugUrl", testThatSlugUrlNotChangedWhenSetWithValidSlugUrl), // ("testThatSlugUrlStripsWhitespace", testThatSlugUrlStripsWhitespace), // ("testNumbersRemainInUrl", testNumbersRemainInUrl), // ("testSlugUrlLowerCases", testSlugUrlLowerCases), // ("testEverythingWithLotsOfCharacters", testEverythingWithLotsOfCharacters), // ("testSlugUrlGivenUniqueNameIfDuplicate", testSlugUrlGivenUniqueNameIfDuplicate), // ("testShortSnippet", testShortSnippet), // ("testLongSnippet", testLongSnippet), // ("testCreatedAndEditedDateInISOFormForAllContext", testCreatedAndEditedDateInISOFormForAllContext) // ] // // private var database: Database! // // override func setUp() { // database = try! Database(MemoryDriver()) // try! Droplet.prepare(database: database) // } // // override func tearDown() { // try! Droplet.teardown(database: database) // } // // func testLinuxTestSuiteIncludesAllTests() { // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) // let thisClass = type(of: self) // let linuxCount = thisClass.allTests.count // let darwinCount = Int(thisClass // .defaultTestSuite.testCaseCount) // XCTAssertEqual(linuxCount, darwinCount, // "\(darwinCount - linuxCount) tests are missing from allTests") // #endif // } // // func testThatSlugUrlCalculatedCorrectlyForTitleWithSpaces() { // let title = "This is a title" // let expectedSlugUrl = "this-is-a-title" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post.slugUrl) // } // // func testThatSlugUrlCalculatedCorrectlyForTitleWithPunctuation() { // let title = "This is an awesome post!" // let expectedSlugUrl = "this-is-an-awesome-post" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post.slugUrl) // } // // func testThatSlugUrlNotChangedWhenSetWithValidSlugUrl() { // let slugUrl = "this-is-a-title" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: slugUrl) // XCTAssertEqual(slugUrl, post.slugUrl) // } // // func testThatSlugUrlStripsWhitespace() { // let title = " Title " // let expectedSlugUrl = "title" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post.slugUrl) // } // // func testNumbersRemainInUrl() { // let title = "The 2nd url" // let expectedSlugUrl = "the-2nd-url" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post.slugUrl) // } // // func testSlugUrlLowerCases() { // let title = "AN AMAZING POST" // let expectedSlugUrl = "an-amazing-post" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post.slugUrl) // } // // func testEverythingWithLotsOfCharacters() { // let title = " This should remove! \nalmost _all_ of the @ punctuation, but it doesn't?" // let expectedSlugUrl = "this-should-remove-almost-all-of-the-punctuation-but-it-doesnt" // let post = TestDataBuilder.anyPost(author: TestDataBuilder.anyUser(), slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post.slugUrl) // } // // func testSlugUrlGivenUniqueNameIfDuplicate() throws { // let title = "A duplicated title" // let expectedSlugUrl = "a-duplicated-title-2" // let author = TestDataBuilder.anyUser() // try author.save() // let post1 = TestDataBuilder.anyPost(author: author, slugUrl: title) // try post1.save() // let post2 = TestDataBuilder.anyPost(author: author, slugUrl: title) // XCTAssertEqual(expectedSlugUrl, post2.slugUrl) // // } // // func testShortSnippet() { // let post = TestDataBuilder.anyLongPost(author: TestDataBuilder.anyUser()) // let shortSnippet = post.shortSnippet() // XCTAssertLessThan(shortSnippet.count, 500) // } // // func testLongSnippet() { // let post = TestDataBuilder.anyLongPost(author: TestDataBuilder.anyUser()) // let shortSnippet = post.longSnippet() // XCTAssertLessThan(shortSnippet.count, 1500) // } // // // func testCreatedAndEditedDateInISOFormForAllContext() throws { // let created = Date(timeIntervalSince1970: 1.0) // let lastEdited = Date(timeIntervalSince1970: 10.0) // let author = TestDataBuilder.anyUser() // try author.save() // let post = TestDataBuilder.anyPost(author: author, creationDate: created) // post.lastEdited = lastEdited // try post.save() // let node = try post.makeNode(in: BlogPostContext.all) // // XCTAssertEqual(node["created_date_iso8601"]?.string, "1970-01-01T00:00:01+0000") // XCTAssertEqual(node["last_edited_date_iso8601"]?.string, "1970-01-01T00:00:10+0000") // } // // // TODO test tag pivot logic // // TODO test context make node stuff // //}
42.402878
131
0.666271
4b1e55f322c120c7171b6059fb7c02131fc4fee3
1,607
// // TweetList.swift // brain-marks // // Created by Shloak Aggarwal on 11/04/21. // import SwiftUI struct TweetList: View { let category: AWSCategory @StateObject var viewModel = TweetListViewModel() var body: some View { tweetList .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .principal) { HStack { Image(systemName: category.imageName ?? "swift") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 25, height: 25) Text(category.name) } } } .onAppear { viewModel.fetchTweets(category: category) } } @ViewBuilder var tweetList: some View { if viewModel.tweets.isEmpty { emptyListView } else { tweets } } var emptyListView: some View { Text("No tweets saved!") .font(.title3) .fontWeight(.medium) } var tweets: some View { List { ForEach(viewModel.tweets) { tweet in TweetCard(tweet: tweet) .onTapGesture { viewModel.openTwitter(tweetID: tweet.tweetID, authorUsername: tweet.authorUsername!) } } .onDelete { offsets in viewModel.deleteTweet(at: offsets) } } } }
25.109375
108
0.464219
e6a5aff03142fff5967a0ea1180224e75a66d5b7
392
// // Constants.swift // Instagram_Firestore_App_Clone // // Created by 윤병일 on 2021/04/18. // import Firebase let COLLECTION_USERS = Firestore.firestore().collection("users") let COLLECTION_FOLLOWERS = Firestore.firestore().collection("followers") let COLLECTION_FOLLOWING = Firestore.firestore().collection("following") let COLLECTION_POSTS = Firestore.firestore().collection("posts")
28
72
0.772959