label
int64 0
1
| text
stringlengths 0
2.8M
|
---|---|
0 | //
// LocationInfo.swift
// ConcurrentDispatchQueue
//
// Created by Rob Kerr on 1/20/21.
//
import Foundation
struct LocationInfo : Decodable {
let lon: Double
let lat: Double
let foundedYear: Int
let population: Int
let areaCode: String
let imageUrl: String
var weather: Weather?
mutating func setWeather(weather: Weather) {
self.weather = weather
}
}
|
0 | // (c) 2022 and onwards The vChewing Project (MIT-NTL License).
// ====================
// This code is released under the MIT license (SPDX-License-Identifier: MIT)
// ... with NTL restriction stating that:
// No trademark license is granted to use the trade names, trademarks, service
// marks, or product names of Contributor, except as required to fulfill notice
// requirements defined in MIT License.
import XCTest
@testable import Tekkon
extension TekkonTestsKeyboardArrangments {
func testStarlightKeysB() throws {
var composer = Tekkon.Composer(arrange: .ofStarlight)
XCTAssertEqual(composer.convertSequenceToRawComposition("lt0"), "ㄌㄟ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("lf"), "ㄌㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lf7"), "ㄌㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lf8"), "ㄌㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lf9"), "ㄌㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lw"), "ㄌㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lw7"), "ㄌㄡˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lw8"), "ㄌㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lw9"), "ㄌㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lw0"), "ㄌㄡ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("lm7"), "ㄌㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lm8"), "ㄌㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lm9"), "ㄌㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lk"), "ㄌㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lk7"), "ㄌㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lk8"), "ㄌㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lk9"), "ㄌㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lg"), "ㄌㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lg7"), "ㄌㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lg8"), "ㄌㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lg9"), "ㄌㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("li"), "ㄌㄧ")
XCTAssertEqual(composer.convertSequenceToRawComposition("li7"), "ㄌㄧˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("li8"), "ㄌㄧˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("li9"), "ㄌㄧˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("li0"), "ㄌㄧ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("lia8"), "ㄌㄧㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lie"), "ㄌㄧㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lie7"), "ㄌㄧㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lie8"), "ㄌㄧㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lie9"), "ㄌㄧㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lif"), "ㄌㄧㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lif7"), "ㄌㄧㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lif8"), "ㄌㄧㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lif9"), "ㄌㄧㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("liw"), "ㄌㄧㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("liw7"), "ㄌㄧㄡˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("liw8"), "ㄌㄧㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("liw9"), "ㄌㄧㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lim"), "ㄌㄧㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lim7"), "ㄌㄧㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lim8"), "ㄌㄧㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lim9"), "ㄌㄧㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lin7"), "ㄌㄧㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lin8"), "ㄌㄧㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lin9"), "ㄌㄧㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lik7"), "ㄌㄧㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lik8"), "ㄌㄧㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lik9"), "ㄌㄧㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lig"), "ㄌㄧㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lig7"), "ㄌㄧㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lig8"), "ㄌㄧㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lig9"), "ㄌㄧㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lu"), "ㄌㄨ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lu7"), "ㄌㄨˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lu8"), "ㄌㄨˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lu9"), "ㄌㄨˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("luo"), "ㄌㄨㄛ")
XCTAssertEqual(composer.convertSequenceToRawComposition("luo7"), "ㄌㄨㄛˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("luo8"), "ㄌㄨㄛˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("luo9"), "ㄌㄨㄛˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("luo0"), "ㄌㄨㄛ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("lum7"), "ㄌㄨㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lum8"), "ㄌㄨㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lum9"), "ㄌㄨㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lun"), "ㄌㄨㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lun7"), "ㄌㄨㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lun8"), "ㄌㄨㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lun9"), "ㄌㄨㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lug"), "ㄌㄨㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lug7"), "ㄌㄨㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lug8"), "ㄌㄨㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lug9"), "ㄌㄨㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lv"), "ㄌㄩ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lv7"), "ㄌㄩˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lv8"), "ㄌㄩˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lv9"), "ㄌㄩˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lve"), "ㄌㄩㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lve8"), "ㄌㄩㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lve9"), "ㄌㄩㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lvm7"), "ㄌㄩㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("lvm8"), "ㄌㄩㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ga"), "ㄍㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ga7"), "ㄍㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ga8"), "ㄍㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ga9"), "ㄍㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ga0"), "ㄍㄚ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("ge"), "ㄍㄜ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ge7"), "ㄍㄜˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ge8"), "ㄍㄜˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ge9"), "ㄍㄜˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ge0"), "ㄍㄜ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("gy"), "ㄍㄞ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gy8"), "ㄍㄞˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gy9"), "ㄍㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gt8"), "ㄍㄟˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gf"), "ㄍㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gf8"), "ㄍㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gf9"), "ㄍㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gw"), "ㄍㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gw8"), "ㄍㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gw9"), "ㄍㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gm"), "ㄍㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gm8"), "ㄍㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gm9"), "ㄍㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gn"), "ㄍㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gn7"), "ㄍㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gn8"), "ㄍㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gn9"), "ㄍㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gk"), "ㄍㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gk8"), "ㄍㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gk9"), "ㄍㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gg"), "ㄍㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gg8"), "ㄍㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gg9"), "ㄍㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gu"), "ㄍㄨ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gu7"), "ㄍㄨˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gu8"), "ㄍㄨˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gu9"), "ㄍㄨˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gua"), "ㄍㄨㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gua7"), "ㄍㄨㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gua8"), "ㄍㄨㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gua9"), "ㄍㄨㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guo"), "ㄍㄨㄛ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guo7"), "ㄍㄨㄛˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guo8"), "ㄍㄨㄛˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guo9"), "ㄍㄨㄛˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guy"), "ㄍㄨㄞ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guy8"), "ㄍㄨㄞˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guy9"), "ㄍㄨㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gut"), "ㄍㄨㄟ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gut8"), "ㄍㄨㄟˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gut9"), "ㄍㄨㄟˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gum"), "ㄍㄨㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gum8"), "ㄍㄨㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gum9"), "ㄍㄨㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gun"), "ㄍㄨㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gun8"), "ㄍㄨㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gun9"), "ㄍㄨㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guk"), "ㄍㄨㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guk8"), "ㄍㄨㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("guk9"), "ㄍㄨㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gug"), "ㄍㄨㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gug7"), "ㄍㄨㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gug8"), "ㄍㄨㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("gug9"), "ㄍㄨㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ka"), "ㄎㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ka8"), "ㄎㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ka9"), "ㄎㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ke"), "ㄎㄜ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ke7"), "ㄎㄜˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ke8"), "ㄎㄜˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ke9"), "ㄎㄜˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ky"), "ㄎㄞ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ky8"), "ㄎㄞˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ky9"), "ㄎㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kf"), "ㄎㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kf8"), "ㄎㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kf9"), "ㄎㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kw"), "ㄎㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kw8"), "ㄎㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kw9"), "ㄎㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("km"), "ㄎㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("km8"), "ㄎㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("km9"), "ㄎㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kn"), "ㄎㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kn8"), "ㄎㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kn9"), "ㄎㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kk"), "ㄎㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kk7"), "ㄎㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kk8"), "ㄎㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kk9"), "ㄎㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kg"), "ㄎㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kg8"), "ㄎㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ku"), "ㄎㄨ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ku7"), "ㄎㄨˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ku8"), "ㄎㄨˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ku9"), "ㄎㄨˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kua"), "ㄎㄨㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kua8"), "ㄎㄨㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kua9"), "ㄎㄨㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuo9"), "ㄎㄨㄛˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuy"), "ㄎㄨㄞ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuy8"), "ㄎㄨㄞˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuy9"), "ㄎㄨㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kut"), "ㄎㄨㄟ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kut7"), "ㄎㄨㄟˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kut8"), "ㄎㄨㄟˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kut9"), "ㄎㄨㄟˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kum"), "ㄎㄨㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kum8"), "ㄎㄨㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kum9"), "ㄎㄨㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kun"), "ㄎㄨㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kun8"), "ㄎㄨㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kun9"), "ㄎㄨㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuk"), "ㄎㄨㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuk7"), "ㄎㄨㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuk8"), "ㄎㄨㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kuk9"), "ㄎㄨㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kug"), "ㄎㄨㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kug8"), "ㄎㄨㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("kug9"), "ㄎㄨㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ha"), "ㄏㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ha7"), "ㄏㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ha8"), "ㄏㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("he"), "ㄏㄜ")
XCTAssertEqual(composer.convertSequenceToRawComposition("he7"), "ㄏㄜˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("he8"), "ㄏㄜˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("he9"), "ㄏㄜˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hy"), "ㄏㄞ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hy7"), "ㄏㄞˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hy8"), "ㄏㄞˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hy9"), "ㄏㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ht"), "ㄏㄟ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ht8"), "ㄏㄟˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hf"), "ㄏㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hf7"), "ㄏㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hf8"), "ㄏㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hf9"), "ㄏㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hw"), "ㄏㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hw7"), "ㄏㄡˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hw8"), "ㄏㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hw9"), "ㄏㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hm"), "ㄏㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hm7"), "ㄏㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hm8"), "ㄏㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hm9"), "ㄏㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hn"), "ㄏㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hn7"), "ㄏㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hn8"), "ㄏㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hn9"), "ㄏㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hk"), "ㄏㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hk7"), "ㄏㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hk8"), "ㄏㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hk9"), "ㄏㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hg"), "ㄏㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hg7"), "ㄏㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hg9"), "ㄏㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hu"), "ㄏㄨ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hu7"), "ㄏㄨˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hu8"), "ㄏㄨˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hu9"), "ㄏㄨˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hua"), "ㄏㄨㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hua7"), "ㄏㄨㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hua8"), "ㄏㄨㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hua9"), "ㄏㄨㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huo"), "ㄏㄨㄛ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huo7"), "ㄏㄨㄛˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huo8"), "ㄏㄨㄛˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huo9"), "ㄏㄨㄛˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huo0"), "ㄏㄨㄛ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("huy7"), "ㄏㄨㄞˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huy9"), "ㄏㄨㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hut"), "ㄏㄨㄟ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hut7"), "ㄏㄨㄟˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hut8"), "ㄏㄨㄟˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hut9"), "ㄏㄨㄟˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hum"), "ㄏㄨㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hum7"), "ㄏㄨㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hum8"), "ㄏㄨㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hum9"), "ㄏㄨㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hun"), "ㄏㄨㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hun7"), "ㄏㄨㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hun8"), "ㄏㄨㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hun9"), "ㄏㄨㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huk"), "ㄏㄨㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huk7"), "ㄏㄨㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huk8"), "ㄏㄨㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huk9"), "ㄏㄨㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("huk0"), "ㄏㄨㄤ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("hug"), "ㄏㄨㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hug7"), "ㄏㄨㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hug8"), "ㄏㄨㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("hug9"), "ㄏㄨㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ji"), "ㄐㄧ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ji7"), "ㄐㄧˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ji8"), "ㄐㄧˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ji9"), "ㄐㄧˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jia"), "ㄐㄧㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jia7"), "ㄐㄧㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jia8"), "ㄐㄧㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jia9"), "ㄐㄧㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jie"), "ㄐㄧㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jie7"), "ㄐㄧㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jie8"), "ㄐㄧㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jie9"), "ㄐㄧㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jie0"), "ㄐㄧㄝ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("jif"), "ㄐㄧㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jif7"), "ㄐㄧㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jif8"), "ㄐㄧㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jif9"), "ㄐㄧㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jiw"), "ㄐㄧㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jiw8"), "ㄐㄧㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jiw9"), "ㄐㄧㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jim"), "ㄐㄧㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jim8"), "ㄐㄧㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jim9"), "ㄐㄧㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jin"), "ㄐㄧㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jin8"), "ㄐㄧㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jin9"), "ㄐㄧㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jik"), "ㄐㄧㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jik7"), "ㄐㄧㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jik8"), "ㄐㄧㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jik9"), "ㄐㄧㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jig"), "ㄐㄧㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jig8"), "ㄐㄧㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jig9"), "ㄐㄧㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jv"), "ㄐㄩ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jv7"), "ㄐㄩˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jv8"), "ㄐㄩˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jv9"), "ㄐㄩˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jve"), "ㄐㄩㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jve7"), "ㄐㄩㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jve8"), "ㄐㄩㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jve9"), "ㄐㄩㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvm"), "ㄐㄩㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvm8"), "ㄐㄩㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvm9"), "ㄐㄩㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvn"), "ㄐㄩㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvn7"), "ㄐㄩㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvn8"), "ㄐㄩㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvn9"), "ㄐㄩㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvg"), "ㄐㄩㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvg8"), "ㄐㄩㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jvg9"), "ㄐㄩㄥˋ")
// XCTAssertEqual(composer.convertSequenceToRawComposition("q0"), "ㄑ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("qi"), "ㄑㄧ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qi7"), "ㄑㄧˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qi8"), "ㄑㄧˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qi9"), "ㄑㄧˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qia"), "ㄑㄧㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qia7"), "ㄑㄧㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qia8"), "ㄑㄧㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qia9"), "ㄑㄧㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qie"), "ㄑㄧㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qie7"), "ㄑㄧㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qie8"), "ㄑㄧㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qie9"), "ㄑㄧㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qif"), "ㄑㄧㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qif7"), "ㄑㄧㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qif8"), "ㄑㄧㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qif9"), "ㄑㄧㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qiw"), "ㄑㄧㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qiw7"), "ㄑㄧㄡˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qiw8"), "ㄑㄧㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qiw9"), "ㄑㄧㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qim"), "ㄑㄧㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qim7"), "ㄑㄧㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qim8"), "ㄑㄧㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qim9"), "ㄑㄧㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qin"), "ㄑㄧㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qin7"), "ㄑㄧㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qin8"), "ㄑㄧㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qin9"), "ㄑㄧㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qik"), "ㄑㄧㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qik7"), "ㄑㄧㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qik8"), "ㄑㄧㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qik9"), "ㄑㄧㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qig"), "ㄑㄧㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qig7"), "ㄑㄧㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qig8"), "ㄑㄧㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qig9"), "ㄑㄧㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qv"), "ㄑㄩ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qv7"), "ㄑㄩˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qv8"), "ㄑㄩˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qv9"), "ㄑㄩˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qve"), "ㄑㄩㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qve7"), "ㄑㄩㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qve9"), "ㄑㄩㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvm"), "ㄑㄩㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvm7"), "ㄑㄩㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvm8"), "ㄑㄩㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvm9"), "ㄑㄩㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvn"), "ㄑㄩㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvn7"), "ㄑㄩㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvn8"), "ㄑㄩㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvn9"), "ㄑㄩㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvg"), "ㄑㄩㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvg7"), "ㄑㄩㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvg8"), "ㄑㄩㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("qvg9"), "ㄑㄩㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xi"), "ㄒㄧ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xi7"), "ㄒㄧˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xi8"), "ㄒㄧˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xi9"), "ㄒㄧˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xia"), "ㄒㄧㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xia7"), "ㄒㄧㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xia8"), "ㄒㄧㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xia9"), "ㄒㄧㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xie"), "ㄒㄧㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xie7"), "ㄒㄧㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xie8"), "ㄒㄧㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xie9"), "ㄒㄧㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xif"), "ㄒㄧㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xif7"), "ㄒㄧㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xif8"), "ㄒㄧㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xif9"), "ㄒㄧㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xiw"), "ㄒㄧㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xiw7"), "ㄒㄧㄡˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xiw8"), "ㄒㄧㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xiw9"), "ㄒㄧㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xim"), "ㄒㄧㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xim7"), "ㄒㄧㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xim8"), "ㄒㄧㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xim9"), "ㄒㄧㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xin"), "ㄒㄧㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xin7"), "ㄒㄧㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xin8"), "ㄒㄧㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xin9"), "ㄒㄧㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xik"), "ㄒㄧㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xik7"), "ㄒㄧㄤˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xik8"), "ㄒㄧㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xik9"), "ㄒㄧㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xig"), "ㄒㄧㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xig7"), "ㄒㄧㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xig8"), "ㄒㄧㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xig9"), "ㄒㄧㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xv"), "ㄒㄩ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xv7"), "ㄒㄩˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xv8"), "ㄒㄩˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xv9"), "ㄒㄩˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xve"), "ㄒㄩㄝ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xve7"), "ㄒㄩㄝˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xve8"), "ㄒㄩㄝˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xve9"), "ㄒㄩㄝˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvm"), "ㄒㄩㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvm7"), "ㄒㄩㄢˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvm8"), "ㄒㄩㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvm9"), "ㄒㄩㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvn"), "ㄒㄩㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvn7"), "ㄒㄩㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvn9"), "ㄒㄩㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvg"), "ㄒㄩㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvg7"), "ㄒㄩㄥˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvg8"), "ㄒㄩㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("xvg9"), "ㄒㄩㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("j"), "ㄓ")
XCTAssertEqual(composer.convertSequenceToRawComposition("j7"), "ㄓˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("j8"), "ㄓˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("j9"), "ㄓˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ja"), "ㄓㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ja7"), "ㄓㄚˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ja8"), "ㄓㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ja9"), "ㄓㄚˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("je"), "ㄓㄜ")
XCTAssertEqual(composer.convertSequenceToRawComposition("je7"), "ㄓㄜˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("je8"), "ㄓㄜˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("je9"), "ㄓㄜˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("je0"), "ㄓㄜ˙")
XCTAssertEqual(composer.convertSequenceToRawComposition("jy"), "ㄓㄞ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jy7"), "ㄓㄞˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jy8"), "ㄓㄞˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jy9"), "ㄓㄞˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jt9"), "ㄓㄟˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jf"), "ㄓㄠ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jf7"), "ㄓㄠˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jf8"), "ㄓㄠˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jf9"), "ㄓㄠˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jw"), "ㄓㄡ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jw7"), "ㄓㄡˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jw8"), "ㄓㄡˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jw9"), "ㄓㄡˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jm"), "ㄓㄢ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jm8"), "ㄓㄢˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jm9"), "ㄓㄢˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jn"), "ㄓㄣ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jn7"), "ㄓㄣˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jn8"), "ㄓㄣˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jn9"), "ㄓㄣˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jk"), "ㄓㄤ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jk8"), "ㄓㄤˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jk9"), "ㄓㄤˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jg"), "ㄓㄥ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jg8"), "ㄓㄥˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jg9"), "ㄓㄥˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ju"), "ㄓㄨ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ju7"), "ㄓㄨˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ju8"), "ㄓㄨˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("ju9"), "ㄓㄨˋ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jua"), "ㄓㄨㄚ")
XCTAssertEqual(composer.convertSequenceToRawComposition("jua8"), "ㄓㄨㄚˇ")
XCTAssertEqual(composer.convertSequenceToRawComposition("juo"), "ㄓㄨㄛ")
XCTAssertEqual(composer.convertSequenceToRawComposition("juo7"), "ㄓㄨㄛˊ")
XCTAssertEqual(composer.convertSequenceToRawComposition("juo9"), "ㄓㄨㄛˋ")
}
}
|
0 | //
// Created by Dmitry Ivanenko on 20.01.2020.
// Copyright © 2020 Dmitry Ivanenko. All rights reserved.
//
import SwiftUI
import SwiftUIFlux
extension KeyboardView {
struct Component: ConnectedView {
struct Props {
let selectDigit: (Int) -> Void
let addComma: () -> Void
let removeLast: () -> Void
let removeAll: () -> Void
}
func map(state: AppFeature.State, dispatch: @escaping DispatchFunction) -> Props {
return Props(
selectDigit: { digit in
dispatch(KeyboardFeature.Actions.AddDigit(digit: digit))
},
addComma: {
dispatch(KeyboardFeature.Actions.AddComma())
},
removeLast: {
dispatch(KeyboardFeature.Actions.RemoveLastSymbol())
},
removeAll: {
dispatch(KeyboardFeature.Actions.RemoveAll())
}
)
}
func body(props: Props) -> some View {
KeyboardView(
selectDigit: props.selectDigit,
addComma: props.addComma,
removeLast: props.removeLast,
removeAll: props.removeAll
)
}
}
}
|
0 | //
// WithdrawalHistory.swift
// BittrexTracker
//
// Created by Matthew Dovey on 21/01/2019.
// Copyright © 2019 Matthew Dovey. All rights reserved.
//
import Foundation
/// The data structure for the result of the Withdrawal History Request
public struct WithdrawalHistory: Decodable {
public let paymentUuid: String?
public let currency: String?
public let amount: Double?
public let address: String?
public let opened: String?
public let authorized: Bool?
public let pendingPayments: Bool?
public let txCost: Double?
public let txId: String?
public let canceled: Bool?
public let invalidAddress: Bool?
private enum CodingKeys: String, CodingKey {
case paymentUuid = "PaymentUUID"
case currency = "Currency"
case amount = "Amount"
case address = "Address"
case opened = "Opened"
case authorized = "Authorized"
case pendingPayments = "PendingPayments"
case txCost = "TxCost"
case txId = "TxID"
case canceled = "Canceled"
case invalidAddress = "InvalidAddress"
}
}
|
0 | //
// DefaultAxisValueFormatter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
@objc(ChartDefaultAxisValueFormatter)
open class DefaultAxisValueFormatter: NSObject, IAxisValueFormatter
{
public typealias Block = (
_ value: Double,
_ axis: AxisBase?) -> String
public typealias MarketBlock = (
_ value: Double,
_ market: String,
_ axis: AxisBase?) -> String
@objc open var block: Block?
@objc open var marketBlock: MarketBlock?
@objc open var hasAutoDecimals: Bool = false
private var _formatter: NumberFormatter?
@objc open var formatter: NumberFormatter?
{
get { return _formatter }
set
{
hasAutoDecimals = false
_formatter = newValue
}
}
// TODO: Documentation. Especially the nil case
private var _decimals: Int?
open var decimals: Int?
{
get { return _decimals }
set
{
_decimals = newValue
if let digits = newValue
{
self.formatter?.minimumFractionDigits = digits
self.formatter?.maximumFractionDigits = digits
self.formatter?.usesGroupingSeparator = true
}
}
}
public override init()
{
super.init()
self.formatter = NumberFormatter()
hasAutoDecimals = true
}
@objc public init(formatter: NumberFormatter)
{
super.init()
self.formatter = formatter
}
@objc public init(decimals: Int)
{
super.init()
self.formatter = NumberFormatter()
self.formatter?.usesGroupingSeparator = true
self.decimals = decimals
hasAutoDecimals = true
}
@objc public init(block: @escaping Block)
{
super.init()
self.block = block
}
@objc public init(marketBlock: @escaping MarketBlock)
{
super.init()
self.marketBlock = marketBlock
}
@objc public static func with(block: @escaping Block) -> DefaultAxisValueFormatter?
{
return DefaultAxisValueFormatter(block: block)
}
open func stringForValue(_ value: Double,
axis: AxisBase?) -> String
{
if let block = block {
return block(value, axis)
} else {
return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
}
}
public func stringForValue(_ value: Double, market: String, axis: AxisBase?) -> String {
if let block = marketBlock {
return block(value, market, axis)
} else {
return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
}
}
}
|
0 | //
// Transaction.swift
// Transaction
//
// Created by Sjors Provoost on 18/06/2019.
// Copyright © 2019 Blockchain. Distributed under the MIT software
// license, see the accompanying file LICENSE.md
import Foundation
import CLibWally
public typealias Satoshi = UInt64
public struct TxOutput {
let wally_tx_output: wally_tx_output
public let network: Network
public var amount: Satoshi {
return self.wally_tx_output.satoshi
}
public let scriptPubKey: ScriptPubKey
public var address: String? {
if let address = Address(self.scriptPubKey, self.network) {
return address.description
}
return nil
}
public init (_ scriptPubKey: ScriptPubKey, _ amount: Satoshi, _ network: Network) {
self.network = network
self.scriptPubKey = scriptPubKey
var scriptpubkey_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: scriptPubKey.bytes.count)
let scriptpubkey_bytes_len = scriptPubKey.bytes.count
scriptPubKey.bytes.copyBytes(to: scriptpubkey_bytes, count: scriptpubkey_bytes_len)
var output: UnsafeMutablePointer<wally_tx_output>?
defer {
if let wally_tx_output = output {
wally_tx_output.deallocate()
}
}
precondition(wally_tx_output_init_alloc(amount, scriptpubkey_bytes, scriptpubkey_bytes_len, &output) == WALLY_OK)
precondition(output != nil)
self.wally_tx_output = output!.pointee
}
public init (tx_output: wally_tx_output, scriptPubKey: ScriptPubKey, network: Network) {
self.network = network
self.wally_tx_output = tx_output
self.scriptPubKey = scriptPubKey
}
}
public struct TxInput {
var wally_tx_input: UnsafeMutablePointer<wally_tx_input>?
let transaction: Transaction
public var vout: UInt32 {
return self.wally_tx_input!.pointee.index
}
public var sequence: UInt32 {
return self.wally_tx_input!.pointee.sequence
}
public var scriptPubKey: ScriptPubKey
public var scriptSig: ScriptSig?
public var witness: Witness?
public var amount: Satoshi
// For P2SH wrapped SegWit, we set scriptSig automatically
public init? (_ tx: Transaction, _ vout: UInt32, _ amount: Satoshi, _ scriptSig: ScriptSig?, _ witness: Witness?, _ scriptPubKey: ScriptPubKey) {
if tx.hash == nil {
return nil
}
self.witness = witness
if (witness == nil) {
self.scriptSig = scriptSig
} else {
switch witness!.type {
case .payToWitnessPubKeyHash(_):
break
case .payToScriptHashPayToWitnessPubKeyHash(let pubKey):
self.scriptSig = ScriptSig(.payToScriptHashPayToWitnessPubKeyHash(pubKey))
}
}
self.scriptPubKey = scriptPubKey
self.amount = amount
let sequence: UInt32 = 0xFFFFFFFF
self.transaction = tx
let tx_hash_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: tx.hash!.count)
let tx_hash_bytes_len = tx.hash!.count
tx.hash!.copyBytes(to: tx_hash_bytes, count: tx_hash_bytes_len)
precondition(wally_tx_input_init_alloc(tx_hash_bytes, tx_hash_bytes_len, vout, sequence, nil, 0, self.witness == nil ? nil : self.witness!.stack!, &self.wally_tx_input) == WALLY_OK)
precondition(self.wally_tx_input != nil)
}
public var signed: Bool {
return (self.scriptSig != nil && self.scriptSig!.signature != nil) || (self.witness != nil && !self.witness!.dummy)
}
}
public struct Transaction {
var hash: Data? = nil
var wally_tx: UnsafeMutablePointer<wally_tx>?
public var inputs: [TxInput]? = nil
var outputs: [TxOutput]? = nil
init (_ wally_tx: wally_tx) {
self.wally_tx = UnsafeMutablePointer<wally_tx>.allocate(capacity: 1)
self.wally_tx!.initialize(to: wally_tx)
}
public init? (_ description: String) {
if let hex = Data(description) {
if hex.count != SHA256_LEN { // Not a transaction hash
var tx_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: hex.count)
hex.copyBytes(to: tx_bytes, count: hex.count)
defer {
tx_bytes.deallocate()
}
if (wally_tx_from_bytes(tx_bytes, hex.count, UInt32(WALLY_TX_FLAG_USE_WITNESS), &self.wally_tx) == WALLY_OK) {
precondition(self.wally_tx != nil)
return
}
}
if hex.count == SHA256_LEN { // 32 bytes, but not a valid transaction, so treat as a hash
self.hash = Data(hex.reversed())
return
}
}
return nil
}
public init (_ inputs: [TxInput], _ outputs: [TxOutput]) {
self.inputs = inputs
self.outputs = outputs
let version: UInt32 = 1
let lockTime: UInt32 = 0
precondition(wally_tx_init_alloc(version, lockTime, inputs.count, outputs.count, &self.wally_tx) == WALLY_OK)
precondition(self.wally_tx != nil)
for input in inputs {
self.addInput(input)
}
for output in outputs {
self.addOutput(output)
}
}
public var description: String? {
if (self.wally_tx == nil) {
return nil
}
// If we have TxInput objects, make sure they're all signed. Otherwise we've been initialized
// from a hex string, so we'll just try to reserialize what we have.
if (self.inputs != nil) {
for input in self.inputs! {
if !input.signed {
return nil
}
}
}
var output: UnsafeMutablePointer<Int8>?
defer {
wally_free_string(output)
}
precondition(wally_tx_to_hex(self.wally_tx, UInt32(WALLY_TX_FLAG_USE_WITNESS), &output) == WALLY_OK)
precondition(output != nil)
return String(cString: output!)
}
mutating func addInput (_ input: TxInput) {
precondition(wally_tx_add_input(self.wally_tx, input.wally_tx_input) == WALLY_OK)
}
mutating func addOutput (_ output: TxOutput) {
let tx_output = UnsafeMutablePointer<wally_tx_output>.allocate(capacity: 1)
defer {
tx_output.deallocate()
}
tx_output.pointee = output.wally_tx_output
precondition(wally_tx_add_output(self.wally_tx, tx_output) == WALLY_OK)
}
var totalIn: Satoshi? {
var tally: Satoshi = 0
if let inputs = self.inputs {
for input in inputs {
tally += input.amount
}
} else {
return nil
}
return tally
}
var totalOut: Satoshi? {
if (self.wally_tx == nil) {
return nil
}
var value_out = UnsafeMutablePointer<UInt64>.allocate(capacity: 1)
defer {
value_out.deallocate()
}
precondition(wally_tx_get_total_output_satoshi(self.wally_tx, value_out) == WALLY_OK)
return value_out.pointee;
}
var funded: Bool? {
if let totalOut = self.totalOut {
if let totalIn = self.totalIn {
return totalOut <= totalIn
}
}
return nil
}
public var vbytes: Int? {
if (self.wally_tx == nil) {
return nil
}
precondition(self.inputs != nil)
// Set scriptSig for all unsigned inputs to .feeWorstCase
for (index, input) in self.inputs!.enumerated() {
if (!input.signed) {
if let scriptSig = input.scriptSig {
let scriptSigWorstCase = scriptSig.render(.feeWorstCase)!
let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: scriptSigWorstCase.count)
let bytes_len = scriptSigWorstCase.count
scriptSigWorstCase.copyBytes(to: bytes, count: bytes_len)
precondition(wally_tx_set_input_script(self.wally_tx, index, bytes, bytes_len) == WALLY_OK)
}
}
}
var value_out = UnsafeMutablePointer<Int>.allocate(capacity: 1)
defer {
value_out.deallocate()
}
precondition(wally_tx_get_vsize(self.wally_tx, value_out) == WALLY_OK)
return value_out.pointee;
}
public var fee: Satoshi? {
if let totalOut = self.totalOut {
if let totalIn = self.totalIn {
if totalIn >= totalOut {
return self.totalIn! - self.totalOut!
}
}
}
return nil
}
public var feeRate: Float64? {
if let fee = self.fee {
if let vbytes = self.vbytes {
precondition(vbytes > 0)
return Float64(fee) / Float64(vbytes)
}
}
return nil
}
public mutating func sign (_ privKeys: [HDKey]) -> Bool {
if self.wally_tx == nil {
return false
}
precondition(self.inputs != nil)
if privKeys.count != self.inputs!.count {
return false
}
// Loop through inputs to sign:
for (i, _) in self.inputs!.enumerated() {
let hasWitness = self.inputs![i].witness != nil
var message_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(SHA256_LEN))
defer {
message_bytes.deallocate()
}
if (hasWitness) {
switch (self.inputs![i].witness!.type) {
case .payToScriptHashPayToWitnessPubKeyHash(let pubKey):
let scriptSig = self.inputs![i].scriptSig!.render(.signed)!
let bytes_scriptsig = UnsafeMutablePointer<UInt8>.allocate(capacity: scriptSig.count)
let bytes_scriptsig_len = scriptSig.count
scriptSig.copyBytes(to: bytes_scriptsig, count: bytes_scriptsig_len)
precondition(wally_tx_set_input_script(self.wally_tx, i, bytes_scriptsig, bytes_scriptsig_len) == WALLY_OK)
fallthrough
case .payToWitnessPubKeyHash(let pubKey):
// Check that we're using the right public key:
var tmp = privKeys[i].wally_ext_key.pub_key
let pub_key = [UInt8](UnsafeBufferPointer(start: &tmp.0, count: Int(EC_PUBLIC_KEY_LEN)))
let pubKeyData = Data(pub_key)
precondition(pubKey.data == pubKeyData)
let scriptCode = self.inputs![i].witness!.scriptCode
let scriptcode_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: scriptCode.count)
scriptCode.copyBytes(to: scriptcode_bytes, count: scriptCode.count)
precondition(wally_tx_get_btc_signature_hash(self.wally_tx, i, scriptcode_bytes, scriptCode.count, self.inputs![i].amount, UInt32(WALLY_SIGHASH_ALL), UInt32(WALLY_TX_FLAG_USE_WITNESS), message_bytes, Int(SHA256_LEN)) == WALLY_OK)
}
} else {
// Prep input for signing:
let scriptPubKey = self.inputs![i].scriptPubKey.bytes
let scriptpubkey_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: scriptPubKey.count)
scriptPubKey.copyBytes(to: scriptpubkey_bytes, count: scriptPubKey.count)
// Create hash for signing
precondition(wally_tx_get_btc_signature_hash(self.wally_tx, i, scriptpubkey_bytes, scriptPubKey.count, 0, UInt32(WALLY_SIGHASH_ALL), 0, message_bytes, Int(SHA256_LEN)) == WALLY_OK)
}
var compact_sig_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(EC_SIGNATURE_LEN))
defer {
compact_sig_bytes.deallocate()
}
// Sign hash using private key (without 0 prefix)
precondition(EC_MESSAGE_HASH_LEN == SHA256_LEN)
var tmp = privKeys[i].wally_ext_key.priv_key
let privKey = [UInt8](UnsafeBufferPointer(start: &tmp.1, count: Int(EC_PRIVATE_KEY_LEN)))
// Ensure private key is valid
precondition(wally_ec_private_key_verify(privKey, Int(EC_PRIVATE_KEY_LEN)) == WALLY_OK)
precondition(wally_ec_sig_from_bytes(privKey, Int(EC_PRIVATE_KEY_LEN), message_bytes, Int(EC_MESSAGE_HASH_LEN), UInt32(EC_FLAG_ECDSA | EC_FLAG_GRIND_R), compact_sig_bytes, Int(EC_SIGNATURE_LEN)) == WALLY_OK)
// Check that signature is valid and for the correct public key:
var tmpPub = privKeys[i].wally_ext_key.pub_key
let pubKey = [UInt8](UnsafeBufferPointer(start: &tmpPub.0, count: Int(EC_PUBLIC_KEY_LEN)))
precondition(wally_ec_sig_verify(pubKey, Int(EC_PUBLIC_KEY_LEN), message_bytes, Int(EC_MESSAGE_HASH_LEN), UInt32(EC_FLAG_ECDSA), compact_sig_bytes, Int(EC_SIGNATURE_LEN)) == WALLY_OK)
// Convert to low s form:
let sig_norm_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(EC_SIGNATURE_LEN))
defer {
sig_norm_bytes.deallocate()
}
precondition(wally_ec_sig_normalize(compact_sig_bytes, Int(EC_SIGNATURE_LEN), sig_norm_bytes, Int(EC_SIGNATURE_LEN)) == WALLY_OK)
// Convert normalized signature to DER
let sig_bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(EC_SIGNATURE_DER_MAX_LEN))
var sig_bytes_written = UnsafeMutablePointer<Int>.allocate(capacity: 1)
defer {
sig_bytes.deallocate()
sig_bytes_written.deallocate()
}
precondition(wally_ec_sig_to_der(sig_norm_bytes, Int(EC_SIGNATURE_LEN), sig_bytes, Int(EC_SIGNATURE_DER_MAX_LEN), sig_bytes_written) == WALLY_OK)
// Store signature in TxInput
let signature = Data(bytes: sig_bytes, count: sig_bytes_written.pointee)
if (hasWitness) {
let witness = self.inputs![i].witness!.signed(signature)
self.inputs![i].witness = witness
precondition(wally_tx_set_input_witness(self.wally_tx!, i, witness.stack!) == WALLY_OK)
} else {
self.inputs![i].scriptSig!.signature = signature
// Update scriptSig:
let signedScriptSig = self.inputs![i].scriptSig!.render(.signed)!
let bytes_signed_scriptsig = UnsafeMutablePointer<UInt8>.allocate(capacity: signedScriptSig.count)
let bytes_signed_scriptsig_len = signedScriptSig.count
signedScriptSig.copyBytes(to: bytes_signed_scriptsig, count: bytes_signed_scriptsig_len)
precondition(wally_tx_set_input_script(self.wally_tx, i, bytes_signed_scriptsig, bytes_signed_scriptsig_len) == WALLY_OK)
}
}
return true
}
}
|
0 | //
// Commit.swift
// gitlab-iOS
//
// Created by Xplorld on 2016/3/20.
// Copyright © 2016年 dyweb. All rights reserved.
//
import ObjectMapper
import Alamofire
class Commit : Mappable {
var project:Project?
var id:String?
var short_id:String?
var title:String?
var author_name:String?
var author_email:String?
var created_at:NSDate?
var message:String?
required init?(_ map: Map) {}
func mapping(map: Map) {
id <- map["id"]
short_id <- map["short_id"]
title <- map["title"]
author_name <- map["author_name"]
author_email <- map["author_email"]
created_at <- (map["created_at"],GitLabDateTransform())
message <- map["message"]
}
}
enum CommitRouter : HostProvidedURLRequestConvertible {
case List(id:Int) //id
case Single(id:Int,sha:String)
typealias ReturnType = Commit
var path:String {
let base = "/projects"
switch self {
case .List(let id):
return base + "/\(id)/repository/commits"
case .Single(let id, let sha):
return base + "/\(id)/repository/commits/\(sha)"
}
}
var parameters:[String:AnyObject]? {return nil }
var method:Alamofire.Method {return Alamofire.Method.GET}
}
|
0 |
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.rootViewController = MainViewController()
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {}
func applicationDidEnterBackground(application: UIApplication) {}
func applicationWillEnterForeground(application: UIApplication) {}
func applicationDidBecomeActive(application: UIApplication) {}
func applicationWillTerminate(application: UIApplication) {}
}
|
0 | //
// BaseCache.swift
// Repository
//
// Created by Tiago Janela on 1/30/20.
// Copyright © 2020 Crédito Agrícola. All rights reserved.
//
import Foundation
open class BaseCache<T, R: Hashable>: CacheProtocol {
typealias T = T
typealias R = R
public init() { }
open func load(request: R) -> T? {
fatalError("Subclasses must implement")
}
open func save(request: R, object: T?) {
fatalError("Subclasses must implement")
}
open func clear() {
fatalError("Subclasses must implement")
}
}
|
0 | //
// MarkdownDocument.swift
// UTNotes
//
// Created by 倪可塑 on 2021/5/8.
//
import UIKit
class MarkdownDocument : UIDocument {
var text = ""
override func contents(forType typeName: String) throws -> Any {
return text.data(using: .utf8) ?? Data()
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
guard let contents = contents as? Data else {
fatalError()
}
text = String(data: contents, encoding: .utf8) ?? ""
}
}
|
0 | //
// PlainShapeList.swift
// iGeometry
//
// Created by Nail Sharipov on 24.12.2019.
// Copyright © 2019 iShape. All rights reserved.
//
public struct PlainShapeList {
public static let empty = PlainShapeList(points: [], layouts: [], segments: [])
public struct Segment: Equatable {
public let begin: Int
public let length: Int
public var end: Int {
return begin + length - 1
}
public init(begin: Int, length: Int) {
self.begin = begin
self.length = length
}
}
public private (set) var points: [IntPoint]
public private (set) var layouts: [PlainShape.Layout]
public private (set) var segments: [Segment]
public init(minimumPointsCapacity: Int, minimumLayoutsCapacity: Int, minimumSegmentsCapacity: Int) {
self.points = [IntPoint]()
self.points.reserveCapacity(minimumPointsCapacity)
self.layouts = [PlainShape.Layout]()
self.layouts.reserveCapacity(minimumLayoutsCapacity)
self.segments = [Segment]()
self.segments.reserveCapacity(minimumSegmentsCapacity)
}
public init(points: [IntPoint], layouts: [PlainShape.Layout], segments: [Segment]) {
self.points = points
self.layouts = layouts
self.segments = segments
}
public init(plainShape: PlainShape) {
self.segments = [Segment(begin: 0, length: plainShape.layouts.count)]
self.layouts = plainShape.layouts
self.points = plainShape.points
}
public func get(index: Int) -> PlainShape {
let segment = self.segments[index]
let layouts = Array(self.layouts[segment.begin...segment.end])
var offset: Int = 0
if index > 0 {
for i in 0..<index {
let s = self.segments[i]
let l = self.layouts[s.end]
offset += l.end + 1
}
}
let pointBegin = layouts[0].begin + offset
let pointEnd = layouts[layouts.count - 1].end + offset
let points = Array(self.points[pointBegin...pointEnd])
return PlainShape(points: points, layouts: layouts)
}
public mutating func add(plainShape: PlainShape) {
self.segments.append(Segment(begin: self.layouts.count, length: plainShape.layouts.count))
self.points.append(contentsOf: plainShape.points)
self.layouts.append(contentsOf: plainShape.layouts)
}
public mutating func append(list: PlainShapeList) {
for i in 0..<list.layouts.count {
let plainShape = list.get(index: i)
self.add(plainShape: plainShape)
}
}
}
|
0 | //
// RxViewModelType.swift
// SergdortStyle
//
// Created by Yoshinori Imajo on 2019/01/01.
// Copyright © 2019 Yoshinori Imajo. All rights reserved.
//
protocol ViewModelType {
associatedtype Input
associatedtype Output
func transform(input: Input) -> Output
}
|
0 | class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triagle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
|
0 | import XCTest
@testable import StringMetric
class StringMetricTests: XCTestCase {
func testDistanceLevenshtein() {
XCTAssertEqual("".distanceLevenshtein(between: "sitting"), 7)
XCTAssertEqual("kitten".distanceLevenshtein(between: ""), 6)
XCTAssertEqual("kitten".distanceLevenshtein(between: "sitting"), 3)
XCTAssertEqual("君子和而不同".distanceLevenshtein(between: "小人同而不和"), 4)
}
func testDistanceDamerauLevenshtein() {
XCTAssertEqual("".distanceDamerauLevenshtein(between: "sitting"), 7)
XCTAssertEqual("kitten".distanceDamerauLevenshtein(between: ""), 6)
XCTAssertEqual("kitten".distanceDamerauLevenshtein(between: "sitting"), 3)
XCTAssertEqual("CA".distanceDamerauLevenshtein(between: "AC"), 1)
XCTAssertEqual("specter".distanceDamerauLevenshtein(between: "spectre"), 1)
XCTAssertEqual("CA".distanceDamerauLevenshtein(between: "ABC"), 2)
XCTAssertEqual("君子和而不同".distanceDamerauLevenshtein(between: "小人同而不和"), 4)
}
func testDistanceHamming() {
XCTAssertEqual("karolin".distanceHamming(between: "kathrin"), 3)
XCTAssertEqual("karolin".distanceHamming(between: "kerstin"), 3)
XCTAssertEqual("1011101".distanceHamming(between: "1001001"), 2)
XCTAssertEqual("2173896".distanceHamming(between: "2233796"), 3)
}
func testDistanceMostFreqK() {
XCTAssertEqual("research".distanceMostFreqK(between: "seeking", K: 2), 6)
}
func testDistanceJoraWinkler() {
XCTAssertEqual("".distanceJaroWinkler(between: ""), 1.0)
XCTAssertEqual("".distanceJaroWinkler(between: "Yo"), 0.0)
XCTAssertEqual("search".distanceJaroWinkler(between: "find"), 0.0)
XCTAssertEqual("search".distanceJaroWinkler(between: "search"), 1.0)
XCTAssertEqualWithAccuracy("MARTHA".distanceJaroWinkler(between: "MARHTA"), 0.961, accuracy: 0.001)
XCTAssertEqualWithAccuracy("DWAYNE".distanceJaroWinkler(between: "DUANE"), 0.84, accuracy: 0.001)
XCTAssertEqualWithAccuracy("DIXON".distanceJaroWinkler(between: "DICKSONX"), 0.814, accuracy: 0.001)
XCTAssertEqualWithAccuracy("kitten".distanceJaroWinkler(between: "sitting"), 0.746, accuracy: 0.001)
XCTAssertEqualWithAccuracy("君子和而不同".distanceJaroWinkler(between: "小人同而不和"), 0.555, accuracy: 0.001)
}
static let allTests = [
("testDistanceLevenshtein", testDistanceLevenshtein),
("testDistanceDamerauLevenshtein", testDistanceDamerauLevenshtein),
("testDistanceHamming", testDistanceHamming),
("testDistanceMostFreqK", testDistanceMostFreqK),
("testDistanceJoraWinkler", testDistanceJoraWinkler),
]
}
|
0 | //
// ContentView.swift
// TempConverter
//
// Created by Thomas DURAND on 17/01/2020.
// Copyright © 2020 Thomas DURAND. All rights reserved.
//
import SwiftUI
struct ConverterView<T: Converter>: View {
let converter: T
@State private var inputValue = ""
@State private var inputUnit = 0
@State private var outputUnit = 1
var output: Measurement<Dimension> {
let decimalInputValue = Double(inputValue) ?? 0
let inputDimension = converter.units[inputUnit]
let outputDimension = converter.units[outputUnit]
return Measurement(value: decimalInputValue, unit: inputDimension).converted(to: outputDimension)
}
var formatter: MeasurementFormatter {
let formatter = MeasurementFormatter()
formatter.unitOptions = .providedUnit
return formatter
}
var body: some View {
Form {
Section(header: Text("What's the input \(converter.name.lowercased())?")) {
TextField("Enter a \(converter.name.lowercased())", text: $inputValue)
.keyboardType(.decimalPad)
UnitSelectorView(units: converter.units, selection: $inputUnit)
}
Section(header: Text("What's the expected output unit?")) {
UnitSelectorView(units: converter.units, selection: $outputUnit)
}
Section(header: Text("Converted \(converter.name.lowercased())")) {
Text("\(output, formatter: formatter)")
}
}
.navigationBarTitle("\(converter.name) converter")
}
}
struct ConverterView_Previews: PreviewProvider {
static var previews: some View {
ConverterView(converter: Temperature())
}
}
|
0 | //
// DisplayLink.swift
// VHUD
//
// Created by xxxAIRINxxx on 2016/07/26.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
final class DisplayLink {
var completion: ((Void) -> Void)?
var updateDurationCallback: ((Double) -> Void)?
var needLoop: Bool = false
let duration: TimeInterval
private(set) var currentDuration: TimeInterval = 0
private(set) var percentComplete: Double = 0
private var displayLink: CADisplayLink?
deinit {
self.closeLink()
}
init(_ duration: TimeInterval) {
self.duration = duration
}
func reset() {
self.closeLink()
self.percentComplete = 0
self.currentDuration = self.duration
}
func start() {
self.reset()
self.updateDurationCallback?(0)
self.startLink()
}
private func startLink() {
self.displayLink = CADisplayLink(target: self, selector: #selector(self.updateDuration(_:)))
self.displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
private func closeLink() {
self.displayLink?.invalidate()
self.displayLink = nil
}
@objc private func updateDuration(_ displayLink: CADisplayLink) {
if self.currentDuration <= 0 { return }
self.currentDuration -= displayLink.duration
let percentComplete = (self.duration - self.currentDuration) / self.duration
let c = ceil(percentComplete * 100) / 100
if c != self.percentComplete {
self.percentComplete = c
self.updateDurationCallback?(c)
}
if self.currentDuration <= 0 {
self.completion?()
if self.needLoop {
self.start()
} else {
self.reset()
}
}
}
}
|
0 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b
class B<T where h:a{struct S<P{{}struct Q{var _=b<T=c func c
|
1 |
// RUN: not %target-swift-frontend %s -typecheck
var d{protocol A{{}class a:A{}typealias e:A.E{{}}class A:a |
0 | //
// Model.swift
// MVVM
//
import Foundation
import ObjectMapper
open class Model: NSObject, Mappable {
required public init?(map: Map) {
super.init()
mapping(map: map)
}
open func mapping(map: Map) {}
}
open class HeaderFooterModel: Model {
open var title = ""
open var footer = ""
open var desc = ""
public convenience init(withTitle title: String, desc: String, footer: String) {
self.init(JSON: ["title": title, "desc": desc, "footer": footer])!
}
open override func mapping(map: Map) {
title <- map["title"]
desc <- map["desc"]
footer <- map["footer"]
}
}
public extension Model {
/*
JSON to model
*/
static func fromJSON<T: Mappable>(_ JSON: Any?) -> T? {
return Mapper<T>().map(JSONObject: JSON)
}
static func fromJSON<T: Mappable>(_ JSONString: String) -> T? {
return Mapper<T>().map(JSONString: JSONString)
}
static func fromJSON<T: Mappable>(_ data: Data) -> T? {
if let JSONString = String(data: data, encoding: .utf8) {
return Mapper<T>().map(JSONString: JSONString)
}
return nil
}
/*
JSON to model array
*/
static func fromJSONArray<T: Mappable>(_ JSON: Any?) -> [T] {
return Mapper<T>().mapArray(JSONObject: JSON) ?? []
}
static func fromJSONArray<T: Mappable>(_ JSONString: String) -> [T] {
return Mapper<T>().mapArray(JSONString: JSONString) ?? []
}
static func fromJSONArray<T: Mappable>(_ data: Data) -> [T] {
if let JSONString = String(data: data, encoding: .utf8) {
return Mapper<T>().mapArray(JSONString: JSONString) ?? []
}
return []
}
}
|
0 | //
// UploadRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 12/7/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import SwiftyJSON
typealias UploadResult = APIResult<UploadRequest>
class UploadRequest: APIRequest {
let requiredVersion = Version(0, 60, 0)
let method: HTTPMethod = .post
var path: String {
return "/api/v1/rooms.upload/\(roomId)"
}
let contentType: String
let roomId: String
let data: Data
let filename: String
let mimetype: String
let msg: String
let description: String
let boundary = "Boundary-\(String.random())"
init(roomId: String, data: Data, filename: String, mimetype: String, msg: String = "", description: String = "") {
self.roomId = roomId
self.data = data
self.filename = filename
self.mimetype = mimetype
self.msg = msg
self.description = description
self.contentType = "multipart/form-data; boundary=\(boundary)"
}
func body() -> Data? {
var data = Data()
let boundaryPrefix = "--\(boundary)\r\n"
data.appendString(boundaryPrefix)
data.appendString("Content-Disposition: form-data; name=\"msg\"\r\n\r\n")
data.appendString(msg)
data.appendString("\r\n".appending(boundaryPrefix))
data.appendString("Content-Disposition: form-data; name=\"description\"\r\n\r\n")
data.appendString(description)
data.appendString("\r\n".appending(boundaryPrefix))
data.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n")
data.appendString("Content-Type: \(mimetype)\r\n\r\n")
data.append(self.data)
data.appendString("\r\n--".appending(boundary.appending("--")))
return data
}
}
extension APIResult where T == UploadRequest {
var error: String? {
return raw?["error"].string
}
}
|
0 | //: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class CountAnimationLabel: UILabel {
var startTime: CFTimeInterval!
var fromValue: Int!
var toValue: Int!
var duration: TimeInterval!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
override func awakeFromNib() {
super.awakeFromNib()
initialSetup()
}
init() {
super.init(frame: .zero)
initialSetup()
}
private func initialSetup() {
textAlignment = .right
}
func animate(from fromValue: Int, to toValue: Int, duration: TimeInterval) {
text = "\(fromValue)"
self.startTime = CACurrentMediaTime()
self.fromValue = fromValue
self.toValue = toValue
self.duration = duration
let link = CADisplayLink(target: self, selector: #selector(updateValue))
link.add(to: .current, forMode: .commonModes)
}
@objc func updateValue(link: CADisplayLink) {
let dt = (link.timestamp - self.startTime) / duration
if dt >= 1.0 {
text = "\(toValue!)"
link.invalidate()
return
}
let current = Int(Double(toValue - fromValue) * dt) + fromValue
text = "\(current)"
//print("\(link.timestamp), \(link.targetTimestamp)")
}
}
class MyViewController : UIViewController {
var label: CountAnimationLabel!
override func loadView() {
let view = UIView()
view.backgroundColor = .white
label = CountAnimationLabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
let button = UIButton()
button.frame = CGRect(x: 150, y: 300, width: 50, height: 20)
button.setTitleColor(.blue, for: .normal)
button.setTitle("start!", for: .normal)
button.addTarget(self, action: #selector(animation), for: .touchUpInside)
view.addSubview(label)
view.addSubview(button)
self.view = view
}
@objc func animation() {
label.animate(from: 150, to: 1030, duration: 3)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
|
0 | //
// ViewController.swift
// Custom-Checkbox-iOS
//
// Created by Alejandro Donzer on 25/02/2018.
// Copyright © 2018 Alejandro Donzer. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var userReadCheckbox: Checkbox!
@IBOutlet weak var othersReadCheckbox: Checkbox!
@IBOutlet weak var groupExecCheckbox: Checkbox!
@IBOutlet weak var othersExecCheckbox: Checkbox!
@IBOutlet weak var groupWriteCheckbox: Checkbox!
@IBOutlet weak var groupReadCheckbox: Checkbox!
@IBOutlet weak var othersWriteCheckbox: Checkbox!
@IBOutlet weak var userExecCheckbox: Checkbox!
@IBOutlet weak var userWriteCheckbox: Checkbox!
@IBOutlet weak var userPickerView: UIPickerView!
@IBOutlet weak var othersPickerView: UIPickerView!
@IBOutlet weak var groupPickerView: UIPickerView!
fileprivate var checkboxes: [Checkbox]
fileprivate enum CheckboxIndex {
static let userRead = 0
static let userWrite = 1
static let userExec = 2
static let othersRead = 3
static let othersWrite = 4
static let othersExec = 5
static let groupRead = 6
static let groupWrite = 7
static let groupExec = 8
}
required init?(coder aDecoder: NSCoder) {
checkboxes = []
super.init(coder: aDecoder)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
let pickerViews = [userPickerView!, othersPickerView!, groupPickerView!]
checkboxes = [userReadCheckbox!, userWriteCheckbox!, userExecCheckbox!, othersReadCheckbox!, othersWriteCheckbox!, othersExecCheckbox!,
groupReadCheckbox!, groupWriteCheckbox!, groupExecCheckbox!]
for pickerView in pickerViews {
pickerView.delegate = self
pickerView.dataSource = self
}
for checkbox in checkboxes {
checkbox.addTarget(self, action: #selector(changeMode), for: .touchUpInside)
}
}
@objc fileprivate func changeMode(sender: Checkbox) {
switch sender {
case userReadCheckbox, userWriteCheckbox, userExecCheckbox:
selectPickerViewRow(pickerView: userPickerView, readCheckbox: userReadCheckbox, writeCheckbox: userWriteCheckbox, execCheckbox: userExecCheckbox)
break
case othersReadCheckbox, othersWriteCheckbox, othersExecCheckbox:
selectPickerViewRow(pickerView: othersPickerView, readCheckbox: othersReadCheckbox, writeCheckbox: othersWriteCheckbox, execCheckbox: othersExecCheckbox)
break
case groupReadCheckbox, groupWriteCheckbox, groupExecCheckbox:
selectPickerViewRow(pickerView: groupPickerView, readCheckbox: groupReadCheckbox, writeCheckbox: groupWriteCheckbox, execCheckbox: groupExecCheckbox)
break
default:
break
}
}
fileprivate func selectPickerViewRow(pickerView: UIPickerView, readCheckbox: Checkbox, writeCheckbox: Checkbox, execCheckbox: Checkbox) {
let first = readCheckbox.isSelected.hashValue
let second = writeCheckbox.isSelected.hashValue
let third = execCheckbox.isSelected.hashValue
let source = String(String(first) + String(second) + String(third))
let value = Int(source, radix: 2)!
pickerView.selectRow(value, inComponent: 0, animated: false)
}
fileprivate func setCheckboxStates(row: Int, indexes: [Int]) {
var binaryRow = String(row, radix: 2)
var length = binaryRow.count
while length < 3 {
binaryRow = "0" + binaryRow
length = binaryRow.count
}
var j = 0
for i in indexes {
checkboxes[i].setState(state: binaryRow[binaryRow.index(binaryRow.startIndex, offsetBy: j)] == "1" ? .checked : .unchecked)
j += 1
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 8
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
return NSAttributedString(string: String(row), attributes: [.foregroundColor: UIColor.white])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch pickerView {
case userPickerView:
setCheckboxStates(row: row, indexes: [CheckboxIndex.userRead, CheckboxIndex.userWrite, CheckboxIndex.userExec])
break
case othersPickerView:
setCheckboxStates(row: row, indexes: [CheckboxIndex.othersRead, CheckboxIndex.othersWrite, CheckboxIndex.othersExec])
break
case groupPickerView:
setCheckboxStates(row: row, indexes: [CheckboxIndex.groupRead, CheckboxIndex.groupWrite, CheckboxIndex.groupExec])
break
default:
break
}
}
}
|
0 | //
// OnboardingDataSource.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 03/03/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import UIKit
class OnboardingDataSource: NSObject, UIPageViewControllerDataSource {
private let pages: [UIViewController]
var count: Int {
return pages.count
}
init(storyboard: UIStoryboard) {
let first = OnboardingPageViewController.loadFromStoryboard(storyboard: storyboard, withConfiguartion: RealPrivacyConfiguration())
let second = OnboardingPageViewController.loadFromStoryboard(storyboard: storyboard, withConfiguartion: ContentBlockingConfiguration())
let third = OnboardingPageViewController.loadFromStoryboard(storyboard: storyboard, withConfiguartion: TrackingConfiguration())
let fourth = OnboardingPageViewController.loadFromStoryboard(storyboard: storyboard, withConfiguartion: PrivacyRightConfiguration())
fourth.isLastPage = true
self.pages = [first, second, third, fourth]
super.init()
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let current = pages.index(of: viewController), let previous = previousIndex(current) {
return pages[previous]
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let current = pages.index(of: viewController), let next = nextIndex(current) {
return pages[next]
}
return nil
}
func controller(forIndex index: Int) -> UIViewController {
return pages[index]
}
func index(of controller: UIViewController) -> Int? {
return pages.index(of: controller)
}
func previousIndex(_ index: Int) -> Int? {
return pages.index(index, offsetBy: -1, limitedBy: 0)
}
func nextIndex(_ index: Int) -> Int? {
return pages.index(index, offsetBy: +1, limitedBy: pages.count-1)
}
func lastIndex() -> Int {
return pages.count - 1
}
}
|
0 | //
// TweenState.swift
// STween
//
// Created by Adam Graham on 8/13/16.
// Copyright © 2016 Adam Graham. All rights reserved.
//
/// The state of a tween.
public enum TweenState {
/// The state of a tween that is brand new or has just been revived.
case new
/// The state of a tween that has been stopped and is no longer updating.
case inactive
/// The state of a tween that has been started and is currently updating.
case active
/// The state of a tween that is waiting for its delay to elapse before starting.
case delayed
/// The state of a tween that has been started but is paused.
case paused
/// The state of a tween that has been completed.
case completed
/// The state of a tween that has been killed.
case killed
}
extension TweenState {
// MARK: State Machine Helpers
/// Returns `true` if a tween can be updated –
/// must currently be in an `active` state.
internal var canUpdate: Bool {
switch self {
case .active:
return true
default:
return false
}
}
/// Returns `true` if a tween can be started –
/// must be in a `new` or `inactive` state.
internal var canStart: Bool {
switch self {
case .new, .inactive:
return true
default:
return false
}
}
/// Returns `true` if a tween can be stopped –
/// must be in an `active`, `delayed`, or `paused` state.
internal var canStop: Bool {
switch self {
case .active, .delayed, .paused:
return true
default:
return false
}
}
/// Returns `true` if a tween can be restarted –
/// must *not* be in a `killed` state.
internal var canRestart: Bool {
switch self {
case .killed:
return false
default:
return true
}
}
/// Returns `true` if a tween can be paused –
/// must be in an `active` or `delayed` state.
internal var canPause: Bool {
switch self {
case .active, .delayed:
return true
default:
return false
}
}
/// Returns `true` if a tween can be resumed –
/// must be in a `paused` state.
internal var canResume: Bool {
switch self {
case .paused:
return true
default:
return false
}
}
/// Returns `true` if a tween can be completed –
/// must *not* already be in a `completed` state and not be in a `killed` state.
internal var canComplete: Bool {
switch self {
case .completed, .killed:
return false
default:
return true
}
}
/// Returns `true` if a tween can be killed –
/// must *not* already be in a `killed` state.
internal var canKill: Bool {
switch self {
case .killed:
return false
default:
return true
}
}
/// Returns `true` if a tween can be revived –
/// must be in a `killed` state.
internal var canRevive: Bool {
switch self {
case .killed:
return true
default:
return false
}
}
}
|
0 | import UIKit
extension UIApplication {
class func presentedViewController(rootController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = rootController as? UINavigationController {
return presentedViewController(rootController: navigationController.visibleViewController)
}
if let tabBarController = rootController as? UITabBarController {
if let selectedController = tabBarController.selectedViewController {
return presentedViewController(rootController: selectedController)
}
}
if let presented = rootController?.presentedViewController {
return presentedViewController(rootController: presented)
}
return rootController
}
}
|
0 | //
// LoginViewController.swift
// TVMazeApp
//
// Created by Carlos Alcala on 7/27/19.
// Copyright © 2019 Carlos Alcala. All rights reserved.
//
import UIKit
import LocalAuthentication
class LoginViewController: UIViewController {
let defaults = UserDefaults.standard
var isTouchEnabled:Bool = false
var userPIN = ""
var context = LAContext()
enum AuthenticationState {
case loggedin, loggedout
}
// authentication state.
var state = AuthenticationState.loggedout {
didSet {
if state == .loggedin {
showHome()
}
}
}
@IBOutlet weak var pinLabel: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
setupSettings()
hideKeyboardWhenTappedAround()
context.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)
// initial app state
state = .loggedout
}
@IBAction func loginAction(_ sender: UIButton) {
login()
}
func login() {
if isTouchEnabled {
checkAuthentication()
} else {
if userPIN == pinLabel.text {
showHome()
} else {
showError(title: "Login Error", message: "The PIN is wrong. Please try again")
}
}
}
func setupSettings() {
isTouchEnabled = defaults.bool(forKey: "UseTouchID")
userPIN = defaults.string(forKey: "UsePIN") ?? ""
}
func showHome() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
self.present(vc, animated: true)
}
// check login state
func checkAuthentication() {
if state == .loggedin {
state = .loggedout
} else {
context = LAContext()
context.localizedCancelTitle = "Enter PIN"
// First check if we have the needed hardware support.
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
let reason = "Log in to your account"
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason ) { success, error in
if success {
DispatchQueue.main.async { [unowned self] in
self.state = .loggedin
}
} else {
print(error?.localizedDescription ?? "Failed to authenticate")
self.showError(title: "Login Error", message: "Failed to authenticate")
}
}
} else {
print(error?.localizedDescription ?? "Can't evaluate policy")
self.showError(title: "Login Error", message: "Failed to authenticate")
}
}
}
}
|
0 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "EV3SDK",
platforms: [
.macOS(.v10_13),
.iOS(.v8)
],
products: [
.library(name: "EV3SDK", targets: ["EV3SDK"])
],
targets: [
.target(name: "EV3SDK", path: "EV3IOS")
]
)
|
0 | /*
* Copyright (c) 2020, The Magma Authors
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* 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
/// This is a class created for handling Key related functions for TLS communication
public class KeyHelper {
///Initialize class, receives no parameters and does not call any class function.
init(){}
///This function creates a 2048 bytes RSA public and private key and stores it in keychain. It is used to create the key to create the csr request.
func generateRSAKeyPairForAlias (alias : String) {
var publicKeyMaybe: SecKey? = nil
var privateKeyMaybe: SecKey? = nil
let publicKeyAttributes = [
kSecAttrApplicationTag as String: alias + "Public",
kSecAttrLabel as String: alias + "Public"
] as CFDictionary
let privateKeyAttributes = [
kSecAttrApplicationTag as String: alias + "Private",
kSecAttrLabel as String: alias + "Private"
] as CFDictionary
let err = SecKeyGeneratePair( [
kSecAttrIsPermanent as String: kCFBooleanTrue!,
kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits as String: 2048,
kSecPrivateKeyAttrs as String: privateKeyAttributes,
kSecPublicKeyAttrs as String: publicKeyAttributes
] as NSDictionary, &publicKeyMaybe, &privateKeyMaybe)
assert(err == errSecSuccess)
}
///This function retrieves a key from keychain as Data type. Assumes there exists a key with the attributes specified.
func getKeyAsData(alias : String, keyType : CFString) -> Data {
var tempKeyRef: CFTypeRef?
let getDataQuery : [String: Any] = [ kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: alias,
kSecAttrKeyType as String: keyType,
kSecReturnData as String: true]
SecItemCopyMatching(getDataQuery as CFDictionary, &tempKeyRef)
return tempKeyRef as! Data
}
///This function retrieves a key from keychain as SecKey type. Assumes there exists a key with the attributes specified.
func getKeyAsSecKey(alias : String, keyType : CFString) -> SecKey {
var tempKeyRef: CFTypeRef?
let getDataQuery : [String: Any] = [ kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: alias,
kSecAttrKeyType as String: keyType,
kSecReturnRef as String: true]
SecItemCopyMatching(getDataQuery as CFDictionary, &tempKeyRef)
return tempKeyRef as! SecKey
}
///This function deletes a key from keychain. Assumes there exists a key with the attributes specified.
func DeleteKeyFromKeyChain(alias : String, keyType : CFString) {
let deleteKeyQuery : [String: Any] = [ kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: alias,
kSecAttrKeyType as String: keyType
]
SecItemDelete(deleteKeyQuery as CFDictionary)
}
///This function deletes a key from keychain. Assumes there exists a key with the attributes specified.
func getKeyAsBase64String(alias : String, keyType : CFString) -> String {
var tempKeyRef: CFTypeRef?
let getDataQuery : [String: Any] = [ kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: alias,
kSecAttrKeyType as String: keyType,
kSecReturnData as String: true]
SecItemCopyMatching(getDataQuery as CFDictionary, &tempKeyRef)
return NSData(data: tempKeyRef as! Data).base64EncodedString()
}
}
|
0 | //
// SubmissionImageCell.swift
// Breadit
//
// Created by William Hester on 4/23/16.
// Copyright © 2016 William Hester. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
class SubmissionLinkCellView: SubmissionCellView {
private static let previewHeight: CGFloat = 150
weak var delegate: ContentDelegate!
var linkContent: UIView!
var thumbnailImage: UIImageView!
var linkDescription: UILabel!
var thumbnailWidth: NSLayoutConstraint!
var request: Request?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
linkContent = UIView()
thumbnailImage = UIImageView()
linkDescription = UILabel()
linkContent.backgroundColor = Colors.secondaryColor
linkContent.layer.borderColor = Colors.borderColor.CGColor
linkContent.layer.borderWidth = 1.0
linkContent.layer.cornerRadius = 4.0
linkContent.clipsToBounds = true
linkDescription.textColor = Colors.secondaryTextColor
stackView.addArrangedSubview(linkContent)
linkContent.addSubview(thumbnailImage)
linkContent.addSubview(linkDescription)
linkContent.translatesAutoresizingMaskIntoConstraints = false
thumbnailImage.translatesAutoresizingMaskIntoConstraints = false
linkDescription.translatesAutoresizingMaskIntoConstraints = false
thumbnailImage.heightAnchor.constraintEqualToConstant(60).active = true
thumbnailWidth = thumbnailImage.widthAnchor.constraintEqualToConstant(60)
thumbnailWidth.active = true
thumbnailImage.topAnchor.constraintEqualToAnchor(linkContent.topAnchor).active = true
thumbnailImage.leftAnchor.constraintEqualToAnchor(linkContent.leftAnchor).active = true
linkDescription.centerYAnchor.constraintEqualToAnchor(linkContent.centerYAnchor).active = true
linkDescription.leftAnchor.constraintEqualToAnchor(thumbnailImage.rightAnchor, constant: 8).active = true
linkDescription.rightAnchor.constraintEqualToAnchor(linkContent.rightAnchor).active = true
linkContent.heightAnchor.constraintEqualToAnchor(thumbnailImage.heightAnchor).active = true
let tapDetector = UITapGestureRecognizer(target: self, action: #selector(contentTapped(_:)))
tapDetector.delegate = self
tapDetector.cancelsTouchesInView = true
linkContent.userInteractionEnabled = true
linkContent.addGestureRecognizer(tapDetector)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
thumbnailImage?.image = nil
thumbnailWidth.constant = 60
if let request = request {
request.cancel()
self.request = nil
}
}
func contentTapped(gestureDetector: UITapGestureRecognizer) {
delegate?.contentTapped(submission.link!)
}
}
|
0 |
import UIKit
class ListTableViewController: UITableViewController,UITableViewDataSource,UITableViewDelegate {
let kConsumerKey = "1tcROctuu-yJUrOl9_NtSg"
let kConsumerSecret = "vHASjU5Zk6_f6Ze6sUhBQ-ys8gs"
let kToken = "Su398qprNpeQBDuvsQmx1B4KpXZv0mJm"
let kTokenSecret = "cjkq8UquMprYC6l5C1qN9zB5QOw"
var resturants: [Resturant]?
var restaurantName:String = ""
var numberOfRestaurantsOffset:Int = 0 //the starting point for restaurants retrived in search starting zero
var maxNumberOfSearchedRestaurants:Int = 20
var mapViewController: MapViewController!
func didPressMapView(){
self.navigationController?.pushViewController(self.mapViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.mapViewController = MapViewController()
// set action then set target to the Map Bar Button
self.navigationItem.rightBarButtonItem?.action = Selector("didPressMapView")
self.navigationItem.rightBarButtonItem?.target = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
seachForRestaurants(shouldReload: true, offsetValue: self.numberOfRestaurantsOffset )
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
tableView.delegate = self
tableView.dataSource = self
tableView.addInfiniteScrollingWithActionHandler { () -> Void in
self.tableView.infiniteScrollingView.stopAnimating()
self.seachForRestaurants(shouldReload: false, offsetValue: self.resturants!.count )
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let rests = self.resturants {
return count(rests)
}
return 0
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailView") {
// data to pass values too.
var detailView = segue.destinationViewController as! DetailsViewController
// access data from DetailViewController
let selectedRow = self.tableView.indexPathForSelectedRow()?.row
if let rests = self.resturants {
detailView.resturant = rests[selectedRow!]
}
}
}
// animation for cell
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let rotationTransform = CATransform3DTranslate(CATransform3DIdentity, -500, 10, 0)
cell.layer.transform = rotationTransform
UIView.animateWithDuration(1.5, animations: { () -> Void in
cell.layer.transform = CATransform3DIdentity
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! RestaurantListTableViewCell
if let rests = self.resturants{
let rest = rests[indexPath.row];
print(rest)
cell.restaurantName.text = "\(indexPath.row + 1). \(rest.name)"
// cell.restaurantAddress.text = rest.address
cell.restaurantCategory.text = rest.categories
cell.restaurantImage.sd_setImageWithURL(NSURL(string: rest.imageUrl))
cell.restaurantRatingImage.sd_setImageWithURL(NSURL(string: rest.ratingImageUrl))
cell.restaurantImage.layer.cornerRadius = 5
cell.restaurantImage.layer.masksToBounds = true
}
// Configure the cell...
return cell
}
func seachForRestaurants(shouldReload:Bool = true, offsetValue:Int ) {
var parameters = [
"location": "Toronto",
"radius_filter":"10000",
"cc": "CA",
"term":"cheap_eats",
]
var yelpClient = YelpClient(consumerKey: kConsumerKey, consumerSecret: kConsumerSecret, accessToken: kToken, accessSecret: kTokenSecret)
yelpClient.searchWithTerm("", parameters: parameters, offset: offsetValue, limit: 20, success: { (results: [Resturant]?) -> Void in
if let rests = results {
if shouldReload{
self.resturants = rests
self.mapViewController.resturants = rests
}else {
if let originalRests = self.resturants {
var newRests = originalRests + rests
self.resturants = newRests
self.mapViewController.resturants = newRests
}
}
self.tableView.reloadData()
}
})
{ (operation: AFHTTPRequestOperation!,error: NSError!) -> Void in
println("failed")
}
}
}
|
0 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
(v: C {
struct S<T {
protocol h : NSObject {
class
case c,
|
0 | //
// _FakeCaptureSettings.swift
// iCimulator
//
// Created by Yuiga Wada on 2019/10/21.
// Copyright © 2019 Yuiga Wada. All rights reserved.
//
import UIKit
import AVFoundation
open class _FakeCapturePhotoSettings: NSObject {
public override init() {}
public convenience init(format: [String : Any]?) {self.init()}
public convenience init(rawPixelFormatType: OSType) {self.init()}
public convenience init(rawPixelFormatType: OSType, processedFormat: [String : Any]?) {self.init()}
public convenience init(rawPixelFormatType: OSType, rawFileType: AVFileType?, processedFormat: [String : Any]?, processedFileType: AVFileType?) {self.init()}
public convenience init(from photoSettings: FakeCapturePhotoSettings) {self.init()}
open var uniqueID: Int64 = 0
open var format: [String : Any]? = ["":""]
open var processedFileType: AVFileType? = .mp4
open var rawPhotoPixelFormatType: OSType = .max
open var rawFileType: AVFileType? = .mp4
open var flashMode: FakeCaptureDevice.FlashMode = .auto
open var isAutoRedEyeReductionEnabled = true
/* If u wanna use photoQualityPrioritization, comment out below code! */
//open var photoQualityPrioritization: FakeCapturePhotoOutput.QualityPrioritization = .quality
open var isAutoStillImageStabilizationEnabled = true
open var isAutoVirtualDeviceFusionEnabled = true
open var isAutoDualCameraFusionEnabled = true
open lazy var virtualDeviceConstituentPhotoDeliveryEnabledDevices: [FakeCaptureDevice] = [FakeCaptureDevice()]
open var isDualCameraDualPhotoDeliveryEnabled = true
open var isHighResolutionPhotoEnabled = true
open var isDepthDataDeliveryEnabled = true
open var embedsDepthDataInPhoto = true
open var isDepthDataFiltered = true
open var isCameraCalibrationDataDeliveryEnabled = true
open var isPortraitEffectsMatteDeliveryEnabled = true
open var embedsPortraitEffectsMatteInPhoto = true
/* If u wanna use enabledSemanticSegmentationMatteTypes, comment out below code! */
//open var enabledSemanticSegmentationMatteTypes: [AVSemanticSegmentationMatte.MatteType] = [.hair]
open var embedsSemanticSegmentationMattesInPhoto = true
open var metadata: [String : Any] = ["":""]
open var livePhotoMovieFileURL: URL?
open var livePhotoVideoCodecType: AVVideoCodecType = .jpeg
open var livePhotoMovieMetadata: [AVMetadataItem]! = []
open var __availablePreviewPhotoPixelFormatTypes: [NSNumber] = [1]
open var previewPhotoFormat: [String : Any]? = ["":""]
open var availableEmbeddedThumbnailPhotoCodecTypes: [AVVideoCodecType] = [.jpeg]
open var embeddedThumbnailPhotoFormat: [String : Any]? = ["":""]
open var availableRawEmbeddedThumbnailPhotoCodecTypes: [AVVideoCodecType] = [.jpeg]
open var rawEmbeddedThumbnailPhotoFormat: [String : Any]? = ["":""]
public var availablePreviewPhotoPixelFormatTypes: [OSType] = [.max]
}
|
0 | //
// RxPanModalShowable.swift
// RxPanModal
//
// Created by Meng Li on 2019/08/06.
// Copyright © 2018 XFLAG. All rights 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.
import PanModal
import RxCocoa
import RxSwift
import UIKit
public protocol RxPanModalShowable {
}
extension RxPanModalShowable where Self: UIViewController {
public func showPanModal(_ panModal: RxPanModal) {
guard let viewController = panModal.viewController else {
return
}
RxPanModalManager.shared.addViewController(viewController)
presentPanModal(viewController)
}
public func showCustomPanModal(_ panModal: RxPanModal) {
guard let viewController = panModal.viewController else {
return
}
RxPanModalManager.shared.addViewController(viewController)
presentCustomPanModal(viewController)
}
private func presentCustomPanModal(_ viewControllerToPresent: PanModalPresentable.LayoutType, sourceView: UIView? = nil, sourceRect: CGRect = .zero) {
viewControllerToPresent.modalPresentationStyle = .custom
viewControllerToPresent.modalPresentationCapturesStatusBarAppearance = true
viewControllerToPresent.transitioningDelegate = PanModalPresentationDelegate.default
present(viewControllerToPresent, animated: true, completion: nil)
}
}
extension Reactive where Base: UIViewController, Base: RxPanModalShowable {
public var panModal: Binder<RxPanModal> {
return Binder(base) { viewController, panModal in
viewController.showPanModal(panModal)
}
}
public var customPanModal: Binder<RxPanModal> {
Binder(base) { viewController, panModal in
viewController.showCustomPanModal(panModal)
}
}
}
|
0 | //
// EndpointTests.swift
// DittoTests
//
// Created by alex.huo on 2019/2/18.
// Copyright © 2019 blessingsoft. All rights reserved.
//
import XCTest
@testable import Ditto
class EndpointTests: 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 testEndpoint() {
let normal = Endpoint(url: URL(string: "ditto://foo/:bar")!)
XCTAssertEqual(normal.scheme, "ditto")
XCTAssertEqual(normal.host, nil)
XCTAssertEqual(normal.pathComponents, ["foo", ":bar"])
let path = Endpoint(url: URL(string: "/foo/:bar")!)
XCTAssertEqual(path.scheme, nil)
XCTAssertEqual(path.host, nil)
XCTAssertEqual(path.pathComponents, ["foo", ":bar"])
let path1 = Endpoint(url: URL(string: "foo/:bar")!)
XCTAssertEqual(path1.scheme, nil)
XCTAssertEqual(path1.host, nil)
XCTAssertEqual(path1.pathComponents, ["foo", ":bar"])
let full = Endpoint(url: URL(string: "ditto://www.ditto.com/foo/:bar")!)
XCTAssertEqual(full.scheme, "ditto")
XCTAssertEqual(full.host, "www.ditto.com")
XCTAssertEqual(full.pathComponents, ["foo", ":bar"])
let withoutPath = Endpoint(url: URL(string: "ditto://www.ditto.com")!)
XCTAssertEqual(withoutPath.scheme, "ditto")
XCTAssertEqual(withoutPath.host, "www.ditto.com")
XCTAssertEqual(withoutPath.pathComponents, [])
let withoutPath1 = Endpoint(url: URL(string: "ditto://www.ditto.com/")!)
XCTAssertEqual(withoutPath1.scheme, "ditto")
XCTAssertEqual(withoutPath1.host, "www.ditto.com")
XCTAssertEqual(withoutPath1.pathComponents, [])
let withoutScheme = Endpoint(url: URL(string: "www.ditto.com/foo/:bar")!)
XCTAssertEqual(withoutScheme.scheme, nil)
XCTAssertEqual(withoutScheme.host, "www.ditto.com")
XCTAssertEqual(withoutScheme.pathComponents, ["foo", ":bar"])
let scheme = Endpoint(url: URL(string: "ditto://")!)
XCTAssertEqual(scheme.scheme, "ditto")
XCTAssertEqual(scheme.host, nil)
XCTAssertEqual(scheme.pathComponents, [])
let https = Endpoint(url: URL(string: "https://www.ditto.com/foo/:bar")!)
XCTAssertEqual(https.scheme, "https")
XCTAssertEqual(https.host, "www.ditto.com")
XCTAssertEqual(https.pathComponents, ["foo", ":bar"])
}
}
|
0 | //
// ContentView.swift
// AutoFormatter
//
// Created by Sachin Gupta on 12/20/20.
//
import SwiftUI
struct ContentView: View {
@AutoFormatter(type:.phone) var phoneNumber:String
@AutoFormatter(type:.zipcode) var zipCode:String
@AutoFormatter(type:.currency) var currencyValue:String
var body: some View {
VStack {
Text("Text Formatting")
.padding()
TextField("Phone Number", text: $phoneNumber).onReceive(phoneNumber.publisher.collect()) {
self.phoneNumber = String($0.prefix(10))
}
TextField("ZipCode", text: $zipCode) .onReceive(zipCode.publisher.collect()) {
self.zipCode = String($0.prefix(9))
}
TextField("Currency", text: $currencyValue) .onReceive(currencyValue.publisher.collect()) {
self.currencyValue = String($0.prefix(9))
}
Spacer()
}.padding(20)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
0 | import SwiftUI
import AVKit
struct OnboardingCardView: View {
@Binding var isShowing: Bool
let card: OnboardCard
let width: CGFloat
let height: CGFloat
var body: some View {
VStack {
HStack(alignment: .center) {
Text(card.title)
.font(.largeTitle)
.fontWeight(.bold)
.padding(.leading, 5.0)
Spacer()
Button {
withAnimation(.linear(duration: 0.3)) {
isShowing = false
}
} label: {
Image(systemName: "xmark.circle.fill")
}.buttonStyle(IconButtonStyle())
}.padding(.top, 5.0)
if let videoInfo = card.videoInfo {
if let url = card.pathToVideo {
VideoPlayer(player: AVPlayer(url: url))
.frame(width: videoInfo.ratio * videoInfo.newHeight, height: videoInfo.newHeight)
}
} else {
Image(card.image)
.resizable()
.scaledToFit()
}
Text(card.text)
.font(.title3)
.padding(.all)
if let linkInfo = card.linkInfo {
Button(linkInfo.title) {
if let url = URL(string: linkInfo.webLink) {
UIApplication.shared.open(url)
}
}.buttonStyle(TextButtonStyle())
}
Spacer()
}.padding(.horizontal)
.padding(.top, 10)
.background(RoundedRectangle(cornerRadius: 25)
.fill(Color(.secondarySystemBackground)))
}
}
struct OnboardingCardView_Previews: PreviewProvider {
static let onboardSet = OnboardSet.previewSet()
static var previews: some View {
Group {
OnboardingCardView(isShowing: .constant(true), card: onboardSet.cards[0], width: .infinity, height: .infinity)
.previewLayout(.sizeThatFits)
OnboardingCardView(isShowing: .constant(true), card: onboardSet.cards[1], width: .infinity, height: .infinity)
.preferredColorScheme(.dark)
.previewLayout(.sizeThatFits)
OnboardingCardView(isShowing: .constant(true), card: onboardSet.cards[2], width: .infinity, height: .infinity)
.preferredColorScheme(.dark)
.previewLayout(.sizeThatFits)
}
}
}
|
0 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// NetworkError.swift
//
// Created by Nacho Soto on 3/31/22.
// swiftlint:disable multiline_parameters
import Foundation
/// Represents an error created by `HTTPClient`.
enum NetworkError: Swift.Error, Equatable {
case decoding(NSError, Source)
case offlineConnection(Source)
case networkError(NSError, Source)
case dnsError(failedURL: URL, resolvedHost: String?, Source)
case unableToCreateRequest(HTTPRequest.Path, Source)
case unexpectedResponse(URLResponse?, Source)
case errorResponse(ErrorResponse, HTTPStatusCode, Source)
}
extension NetworkError {
static func decoding(
_ error: Error,
_ data: Data,
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
// Explicitly logging errors since it might help debugging issues.
Logger.error(Strings.network.parsing_json_error(error: error))
Logger.error(Strings.network.json_data_received(
dataString: String(data: data, encoding: .utf8) ?? ""
))
return .decoding(error as NSError, .init(file: file, function: function, line: line))
}
static func offlineConnection(
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
return .offlineConnection(.init(file: file, function: function, line: line))
}
static func networkError(
_ error: Error,
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
return .networkError(error as NSError, .init(file: file, function: function, line: line))
}
static func dnsError(
failedURL: URL, resolvedHost: String?,
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
return .dnsError(failedURL: failedURL, resolvedHost: resolvedHost,
.init(file: file, function: function, line: line))
}
static func unableToCreateRequest(
_ path: HTTPRequest.Path,
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
return .unableToCreateRequest(path, .init(file: file, function: function, line: line))
}
static func unexpectedResponse(
_ response: URLResponse?,
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
return .unexpectedResponse(response, .init(file: file, function: function, line: line))
}
static func errorResponse(
_ response: ErrorResponse, _ statusCode: HTTPStatusCode,
file: String = #fileID, function: String = #function, line: UInt = #line
) -> Self {
return .errorResponse(response, statusCode, .init(file: file, function: function, line: line))
}
}
extension NetworkError: ErrorCodeConvertible {
var asPurchasesError: Error {
switch self {
case let .decoding(error, source):
return ErrorUtils.unexpectedBackendResponse(
withSubError: error,
fileName: source.file,
functionName: source.function,
line: source.line
)
case let .offlineConnection(source):
return ErrorUtils.offlineConnectionError(
fileName: source.file,
functionName: source.function,
line: source.line
)
case let .networkError(error, source):
return ErrorUtils.networkError(
withUnderlyingError: error,
fileName: source.file,
functionName: source.function,
line: source.line
)
case let .dnsError(failedURL, resolvedHost, source):
return ErrorUtils.networkError(
message: NetworkStrings.blocked_network(url: failedURL, newHost: resolvedHost).description,
withUnderlyingError: self,
fileName: source.file,
functionName: source.function,
line: source.line
)
case let .unableToCreateRequest(path, source):
return ErrorUtils.networkError(
extraUserInfo: [
"request_url": path.description
],
fileName: source.file,
functionName: source.function,
line: source.line
)
case let .unexpectedResponse(response, source):
return ErrorUtils.unexpectedBackendResponseError(
extraUserInfo: [
"response": response?.description ?? ""
],
fileName: source.file,
functionName: source.function,
line: source.line
)
case let .errorResponse(response, statusCode, source):
return response.asBackendError(with: statusCode,
file: source.file,
function: source.function,
line: source.line)
}
}
}
extension NetworkError: DescribableError {}
extension NetworkError {
/// Whether the network request producing this error actually synced the data.
var successfullySynced: Bool {
return self.errorStatusCode?.isSuccessfullySynced ?? false
}
/// Whether the network request producing this error can be completed.
/// If `false`, the response was a server error.
var finishable: Bool {
if let statusCode = self.errorStatusCode {
return !statusCode.isServerError
} else {
return false
}
}
private var errorStatusCode: HTTPStatusCode? {
switch self {
case let .errorResponse(_, statusCode, _):
return statusCode
case .offlineConnection,
.decoding,
.networkError,
.dnsError,
.unableToCreateRequest,
.unexpectedResponse:
return nil
}
}
}
extension NetworkError {
typealias Source = ErrorSource
}
|
0 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// 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 XCTest
import Result
import BrightFutures
import Result
class BrightFuturesTests: 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()
}
}
extension BrightFuturesTests {
func testCompletedFuture() {
let f = Future<Int, NoError>.succeeded(2)
let completeExpectation = self.expectationWithDescription("immediate complete")
f.onComplete { result in
XCTAssert(result.isSuccess)
completeExpectation.fulfill()
}
let successExpectation = self.expectationWithDescription("immediate success")
f.onSuccess { value in
XCTAssert(value == 2, "Computation should be returned")
successExpectation.fulfill()
}
f.onFailure { _ in
XCTFail("failure block should not get called")
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testCompletedVoidFuture() {
let f = Future<Void, NoError>.succeeded()
XCTAssert(f.isCompleted, "void future should be completed")
XCTAssert(f.isSuccess, "void future should be success")
}
func testFailedFuture() {
let error = NSError(domain: "test", code: 0, userInfo: nil)
let f = Future<Void, NSError>.failed(error)
let completeExpectation = self.expectationWithDescription("immediate complete")
f.onComplete { result in
switch result {
case .Success(let val):
XCTAssert(false)
case .Failure(let boxedErr):
XCTAssertEqual(boxedErr.value, error)
}
completeExpectation.fulfill()
}
let failureExpectation = self.expectationWithDescription("immediate failure")
f.onFailure { err in
XCTAssert(err == error)
failureExpectation.fulfill()
}
f.onSuccess { value in
XCTFail("success should not be called")
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testCompleteAfterFuture() {
let f = Future<Int, NoError>.completeAfter(1, withValue: 3)
XCTAssertFalse(f.isCompleted)
NSThread.sleepForTimeInterval(0.2)
XCTAssertFalse(f.isCompleted)
NSThread.sleepForTimeInterval(1.0)
XCTAssert(f.isCompleted)
if let val = f.value {
XCTAssertEqual(val, 3);
}
}
// this is inherently impossible to test, but we'll give it a try
func testNeverCompletingFuture() {
let f = Future<Int, NoError>.never()
XCTAssert(!f.isCompleted)
sleep(UInt32(Double(arc4random_uniform(100))/100.0))
XCTAssert(!f.isCompleted)
}
func testForceTypeSuccess() {
let f: Future<Double, NoError> = Future.succeeded(NSTimeInterval(3.0))
let f1: Future<NSTimeInterval, NoError> = f.forceType()
XCTAssertEqual(NSTimeInterval(3.0), f1.result!.value!, "Should be a time interval")
}
func testAsVoid() {
let f = future(fibonacci(10))
let e = self.expectation()
f.asVoid().onComplete { v in
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testForceTypeFailure() {
class TestError: ErrorType {
var nsError: NSError {
return NSError(domain: "", code: 1, userInfo: nil)
}
}
class SubError: TestError {
override var nsError: NSError {
return NSError(domain: "", code: 2, userInfo: nil)
}
}
let f: Future<NoValue, TestError> = Future.failed(SubError())
let f1: Future<NoValue, SubError> = f.forceType()
XCTAssertEqual(f1.result!.error!.nsError.code, 2, "Should be a SubError")
}
func testControlFlowSyntax() {
let f = future { _ in
fibonacci(10)
}
let e = self.expectationWithDescription("the computation succeeds")
f.onSuccess { value in
XCTAssert(value == 55)
e.fulfill()
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func testControlFlowSyntaxWithError() {
let f : Future<String?, NSError> = future {
Result(error: NSError(domain: "NaN", code: 0, userInfo: nil))
}
let failureExpectation = self.expectationWithDescription("failure expected")
f.onFailure { error in
XCTAssert(error.domain == "NaN")
failureExpectation.fulfill()
}
self.waitForExpectationsWithTimeout(3, handler: nil)
}
func testAutoClosure() {
let names = ["Steve", "Tim"]
let f = future(names.count)
let e = self.expectation()
f.onSuccess { value in
XCTAssert(value == 2)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
let e1 = self.expectation()
Future<Int, NSError>.succeeded(fibonacci(10)).onSuccess { value in
XCTAssert(value == 55);
e1.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testAutoClosureWithResult() {
let f = future(Result<Int, NoError>(value:2))
let e = self.expectation()
f.onSuccess { value in
XCTAssert(value == 2)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
let f1 = future(Result<Int,BrightFuturesError<NoError>>(error: .NoSuchElement))
let e1 = self.expectation()
f1.onFailure { error in
XCTAssertEqual(error.nsError, BrightFuturesError<NoError>.NoSuchElement.nsError)
e1.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testSuccessPromise() {
let p = Promise<Int, NoError>()
Queue.global.async {
p.success(fibonacci(10))
}
let e = self.expectationWithDescription("complete expectation")
p.future.onComplete { result in
switch result {
case .Success(let val):
XCTAssert(Int(55) == val.value)
case .Failure(_):
XCTAssert(false)
}
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testFailurePromise() {
let p = Promise<Int, TestError>()
Queue.global.async {
p.failure(TestError.JustAnError)
}
let e = self.expectationWithDescription("complete expectation")
p.future.onComplete { result in
switch result {
case .Success(let val):
XCTFail("should not be success")
case .Failure(let err):
XCTAssertEqual(err.value, TestError.JustAnError)
}
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testPromiseCompleteWithSuccess() {
let p = Promise<Int, TestError>()
p.complete(Result(value: 2))
XCTAssert(p.future.isSuccess)
XCTAssert(p.future.forced()! == Result<Int, TestError>(value:2))
}
func testPromiseCompleteWithFailure() {
let p = Promise<Int, TestError>()
p.complete(Result(error: TestError.JustAnError))
XCTAssert(p.future.isFailure)
XCTAssert(p.future.forced()! == Result<Int, TestError>(error:TestError.JustAnError))
}
func testPromiseTrySuccessTwice() {
let p = Promise<Int, NoError>()
XCTAssert(p.trySuccess(1))
XCTAssertFalse(p.trySuccess(2))
XCTAssertEqual(p.future.forced()!.value!, 1)
}
func testPromiseTryFailureTwice() {
let p = Promise<Int, TestError>()
XCTAssert(p.tryFailure(TestError.JustAnError))
XCTAssertFalse(p.tryFailure(TestError.JustAnotherError))
XCTAssertEqual(p.future.forced()!.error!, TestError.JustAnError)
}
func testCustomExecutionContext() {
let f = future(context: ImmediateExecutionContext) {
fibonacci(10)
}
let e = self.expectationWithDescription("immediate success expectation")
f.onSuccess(context: ImmediateExecutionContext) { value in
e.fulfill()
}
self.waitForExpectationsWithTimeout(0, handler: nil)
}
func testMainExecutionContext() {
let e = self.expectation()
future { _ -> Int in
XCTAssert(!NSThread.isMainThread())
return 1
}.onSuccess(context: Queue.main.context) { value in
XCTAssert(NSThread.isMainThread())
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testDefaultCallbackExecutionContextFromMain() {
let f = Future<Int, NoError>.succeeded(1)
let e = self.expectation()
f.onSuccess { _ in
XCTAssert(NSThread.isMainThread(), "the callback should run on main")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testDefaultCallbackExecutionContextFromBackground() {
let f = Future<Int, NoError>.succeeded(1)
let e = self.expectation()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
f.onSuccess { _ in
XCTAssert(!NSThread.isMainThread(), "the callback should not be on the main thread")
e.fulfill()
}
return
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testPromoteErrorNoSuchElement() {
let f: Future<Int, BrightFuturesError<TestError>> = promoteError(future(3).filter { _ in false })
let e = self.expectation()
f.onFailure { err in
XCTAssert(err == BrightFuturesError<TestError>.NoSuchElement)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
}
// MARK: Functional Composition
/**
* This extension contains all tests related to functional composition
*/
extension BrightFuturesTests {
func testAndThen() {
var answer = 10
let e = self.expectation()
let f = Future<Int, NoError>.succeeded(4)
let f1 = f.andThen { result in
if let val = result.value {
answer *= val
}
return
}
let f2 = f1.andThen { result in
answer += 2
}
f.onSuccess { fval in
f1.onSuccess { f1val in
f2.onSuccess { f2val in
XCTAssertEqual(fval, f1val, "future value should be passed transparantly")
XCTAssertEqual(f1val, f2val, "future value should be passed transparantly")
e.fulfill()
}
return
}
return
}
self.waitForExpectationsWithTimeout(2, handler: nil)
XCTAssertEqual(42, answer, "andThens should be executed in order")
}
func testSimpleMap() {
let e = self.expectation()
func divideByFive(i: Int) -> Int {
return i / 5
}
Future<Int, NoError>.succeeded(fibonacci(10)).map(divideByFive).onSuccess { val in
XCTAssertEqual(val, 11, "The 10th fibonacci number (55) divided by 5 is 11")
e.fulfill()
return
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testMapSuccess() {
let e = self.expectation()
future {
fibonacci(10)
}.map { value -> String in
if value > 5 {
return "large"
}
return "small"
}.map { sizeString -> Bool in
return sizeString == "large"
}.onSuccess { numberIsLarge in
XCTAssert(numberIsLarge)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testMapFailure() {
let e = self.expectation()
future { () -> Result <Int,NSError> in
Result(error: NSError(domain: "Tests", code: 123, userInfo: nil))
}.map { number in
XCTAssert(false, "map should not be evaluated because of failure above")
}.map { number in
XCTAssert(false, "this map should also not be evaluated because of failure above")
}.onFailure { error in
XCTAssert(error.domain == "Tests")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testRecover() {
let e = self.expectation()
let f = Future<Int, TestError>.failed(TestError.JustAnError).recover { _ in
return 3
}.onSuccess { val in
XCTAssertEqual(val, 3)
e.fulfill()
}
let recov: () -> Int = {
return 5
}
let e1 = self.expectation()
(Future<Int, TestError>.failed(TestError.JustAnError) ?? recov()).onSuccess { value in
XCTAssert(value == 5)
e1.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testSkippedRecover() {
let e = self.expectation()
future { _ in
3
}.recover { _ in
XCTFail("recover task should not be executed")
return 5
}.onSuccess { value in
XCTAssert(value == 3)
e.fulfill()
}
let e1 = self.expectation()
let recov: () -> Int = {
XCTFail("recover task should not be executed")
return 5
}
(future(3) ?? recov()).onSuccess { value in
XCTAssert(value == 3)
e1.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testRecoverWith() {
let e = self.expectation()
future {
Result(error: NSError(domain: "NaN", code: 0, userInfo: nil))
}.recoverWith { _ in
return future { _ in
fibonacci(5)
}
}.onSuccess { value in
XCTAssert(value == 5)
e.fulfill()
}
let e1 = self.expectation()
let f: Future<Int, NoError> = Future<Int, NSError>.failed(NSError(domain: "NaN", code: 0, userInfo: nil)) ?? future(fibonacci(5))
f.onSuccess {
XCTAssertEqual($0, 5)
e1.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testZip() {
let f = Future<Int, NoError>.succeeded(1)
let f1 = Future<Int, NoError>.succeeded(2)
let e = self.expectation()
f.zip(f1).onSuccess { (let a, let b) in
XCTAssertEqual(a, 1)
XCTAssertEqual(b, 2)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testZipThisFails() {
let f: Future<Bool, NSError> = future { () -> Result<Bool,NSError> in
sleep(1)
return Result(error: NSError(domain: "test", code: 2, userInfo: nil))
}
let f1 = Future<Int, NSError>.succeeded(2)
let e = self.expectation()
f.zip(f1).onFailure { error in
XCTAssert(error.domain == "test")
XCTAssertEqual(error.code, 2)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testZipThatFails() {
let f = future { () -> Result<Int,NSError> in
sleep(1)
return Result(error: NSError(domain: "tester", code: 3, userInfo: nil))
}
let f1 = Future<Int, NSError>.succeeded(2)
let e = self.expectation()
f1.zip(f).onFailure { error in
XCTAssert(error.domain == "tester")
XCTAssertEqual(error.code, 3)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testZipBothFail() {
let f = future { () -> Result<Int,NSError> in
sleep(1)
return Result(error: NSError(domain: "f-error", code: 3, userInfo: nil))
}
let f1 = future { () -> Result<Int,NSError> in
sleep(1)
return Result(error: NSError(domain: "f1-error", code: 4, userInfo: nil))
}
let e = self.expectation()
f.zip(f1).onFailure { error in
XCTAssert(error.domain == "f-error")
XCTAssertEqual(error.code, 3)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testFilterNoSuchElement() {
let e = self.expectation()
Future<Int, NoError>.succeeded(3).filter { $0 > 5}.onComplete { result in
if let err = result.error {
XCTAssert(err.nsError.code == 0, "filter should yield no result")
}
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testFilterPasses() {
let e = self.expectation()
Future<String, NoError>.succeeded("Thomas").filter { $0.hasPrefix("Th") }.onComplete { result in
if let val = result.value {
XCTAssert(val == "Thomas", "Filter should pass")
}
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testFilterFailedFuture() {
let f = Future<Int, TestError>.failed(TestError.JustAnError)
let e = self.expectation()
f.filter { _ in false }.onFailure { error in
XCTAssert(error == BrightFuturesError(external: TestError.JustAnError))
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testForcedFuture() {
var x = 10
let f: Future<Void, NoError> = future { () -> () in
NSThread.sleepForTimeInterval(0.5)
x = 3
}
f.forced()
XCTAssertEqual(x, 3)
}
func testForcedFutureWithTimeout() {
let f: Future<Void, NoError> = future {
NSThread.sleepForTimeInterval(0.5)
}
XCTAssert(f.forced(0.1) == nil)
XCTAssert(f.forced(0.5) != nil)
}
func testForcingCompletedFuture() {
let f = Future<Int, NoError>.succeeded(1)
XCTAssertEqual(f.forced()!.value!, 1)
}
func testFlatMap() {
let e = self.expectation()
let finalString = "Greg"
let flatMapped = Future<String, NoError>.succeeded("Thomas").flatMap { _ in
return Future<String, NoError>.succeeded(finalString)
}
flatMapped.onSuccess { s in
XCTAssertEqual(s, finalString, "strings are not equal")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testFlatMapByPassingFunction() {
let e = self.expectation()
func toString(n: Int) -> Future<String, NoError> {
return Future<String, NoError>.succeeded("\(n)")
}
let n = 1
let flatMapped = Future<Int, NoError>.succeeded(n).flatMap(toString)
flatMapped.onSuccess { s in
XCTAssertEqual(s, "\(n)", "strings are not equal")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
}
// MARK: FutureUtils
/**
* This extension contains all tests related to FutureUtils
*/
extension BrightFuturesTests {
func testUtilsTraverseSuccess() {
let n = 10
let f = traverse(Array(1...n)) { i in
Future<Int, NoError>.succeeded(fibonacci(i))
}
let e = self.expectation()
f.onSuccess { fibSeq in
XCTAssertEqual(fibSeq.count, n)
for var i = 0; i < fibSeq.count; i++ {
XCTAssertEqual(fibSeq[i], fibonacci(i+1))
}
e.fulfill()
}
self.waitForExpectationsWithTimeout(4, handler: nil)
}
func testUtilsTraverseEmpty() {
let e = self.expectation()
traverse([Int]()) {Future<Int, NoError>.succeeded($0)}.onSuccess { res in
XCTAssertEqual(res.count, 0);
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsTraverseSingleError() {
let e = self.expectation()
let evenFuture: Int -> Future<Bool, NSError> = { i in
return future {
if i % 2 == 0 {
return Result(value: true)
} else {
return Result(error: NSError(domain: "traverse-single-error", code: i, userInfo: nil))
}
}
}
let f = traverse([2,4,6,8,9,10], context: Queue.global.context, evenFuture)
f.onFailure { err in
XCTAssertEqual(err.code, 9)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsTraverseMultipleErrors() {
let e = self.expectation()
let evenFuture: Int -> Future<Bool, NSError> = { i in
return future { err in
if i % 2 == 0 {
return Result(value: true)
} else {
return Result(error: NSError(domain: "traverse-single-error", code: i, userInfo: nil))
}
}
}
traverse([20,22,23,26,27,30], evenFuture).onFailure { err in
XCTAssertEqual(err.code, 23)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsTraverseWithExecutionContext() {
let e = self.expectation()
traverse(Array(1...10), context: Queue.main.context) { _ -> Future<Int, NoError> in
XCTAssert(NSThread.isMainThread())
return Future.succeeded(1)
}.onComplete { _ in
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFold() {
// create a list of Futures containing the Fibonacci sequence
let fibonacciList = (1...10).map { val in
fibonacciFuture(val)
}
let e = self.expectation()
fold(fibonacciList, 0, { $0 + $1 }).onSuccess { val in
XCTAssertEqual(val, 143)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFoldWithError() {
let error = NSError(domain: "fold-with-error", code: 0, userInfo: nil)
// create a list of Futures containing the Fibonacci sequence and one error
let fibonacciList = (1...10).map { val -> Future<Int, NSError> in
if val == 3 {
return Future<Int, NSError>.failed(error)
} else {
return promoteError(fibonacciFuture(val))
}
}
let e = self.expectation()
fold(fibonacciList, 0, { $0 + $1 }).onFailure { err in
XCTAssertEqual(err, error)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFoldWithExecutionContext() {
let e = self.expectation()
fold([Future<Int, NoError>.succeeded(1)], context: Queue.main.context, 10) { remainder, elem -> Int in
XCTAssert(NSThread.isMainThread())
return remainder + elem
}.onSuccess { val in
XCTAssertEqual(val, 11)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFoldWithEmptyList() {
let z = "NaN"
let e = self.expectation()
fold([Future<String, NoError>](), z, { $0 + $1 }).onSuccess { val in
XCTAssertEqual(val, z)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFirstCompleted() {
let futures: [Future<Int, NoError>] = [
Future.completeAfter(0.2, withValue: 3),
Future.completeAfter(0.3, withValue: 13),
Future.completeAfter(0.4, withValue: 23),
Future.completeAfter(0.3, withValue: 4),
Future.completeAfter(0.1, withValue: 9),
Future.completeAfter(0.4, withValue: 83),
]
let e = self.expectation()
firstCompletedOf(futures).onSuccess { val in
XCTAssertEqual(val, 9)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsSequence() {
let futures = (1...10).map { fibonacciFuture($0) }
let e = self.expectation()
sequence(futures).onSuccess { fibs in
for (index, num) in enumerate(fibs) {
XCTAssertEqual(fibonacci(index+1), num)
}
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsSequenceEmpty() {
let e = self.expectation()
sequence([Future<Int, NoError>]()).onSuccess { val in
XCTAssertEqual(val.count, 0)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFindSuccess() {
let futures: [Future<Int, NoError>] = [
Future.succeeded(1),
Future.completeAfter(0.2, withValue: 3),
Future.succeeded(5),
Future.succeeded(7),
Future.completeAfter(0.3, withValue: 8),
Future.succeeded(9)
];
let f = find(futures, context: Queue.global.context) { val in
return val % 2 == 0
}
let e = self.expectation()
f.onSuccess { val in
XCTAssertEqual(val, 8, "First matching value is 8")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testUtilsFindNoSuchElement() {
let futures: [Future<Int, NoError>] = [
Future.succeeded(1),
Future.completeAfter(0.2, withValue: 3),
Future.succeeded(5),
Future.succeeded(7),
Future.completeAfter(0.4, withValue: 9),
];
let f = find(futures) { val in
return val % 2 == 0
}
let e = self.expectation()
f.onFailure { err in
XCTAssertEqual(err.nsError.code, 0, "No matching elements")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
}
/**
* This extension contains miscellaneous tests
*/
extension BrightFuturesTests {
// Creates a lot of futures and adds completion blocks concurrently, which should all fire
func testStress() {
let instances = 100;
var successfulFutures = [Future<Int, NSError>]()
var failingFutures = [Future<Int, NSError>]()
let contexts: [ExecutionContext] = [ImmediateExecutionContext, Queue.main.context, Queue.global.context]
let randomContext: () -> ExecutionContext = { contexts[Int(arc4random_uniform(UInt32(contexts.count)))] }
let randomFuture: () -> Future<Int, NSError> = {
if arc4random() % 2 == 0 {
return successfulFutures[Int(arc4random_uniform(UInt32(successfulFutures.count)))]
} else {
return failingFutures[Int(arc4random_uniform(UInt32(failingFutures.count)))]
}
}
var finalSum = 0;
for _ in 1...instances {
var future: Future<Int, NSError>
if arc4random() % 2 == 0 {
let futureResult: Int = Int(arc4random_uniform(10))
finalSum += futureResult
future = self.succeedingFuture(futureResult)
successfulFutures.append(future)
} else {
future = self.failingFuture()
failingFutures.append(future)
}
let context = randomContext()
let e = self.expectationWithDescription("future completes in context \(context)")
future.onComplete(context: context) { res in
e.fulfill()
}
}
for _ in 1...instances*10 {
let f = randomFuture()
let context = randomContext()
let e = self.expectationWithDescription("future completes in context \(context)")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
usleep(arc4random_uniform(100))
f.onComplete(context: context) { res in
e.fulfill()
}
}
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func testSerialCallbacks() {
let p = Promise<Void, NoError>()
var executingCallbacks = 0
for _ in 0..<10 {
let e = self.expectation()
p.future.onComplete(context: Queue.global.context) { _ in
XCTAssert(executingCallbacks == 0, "This should be the only executing callback")
executingCallbacks++
// sleep a bit to increase the chances of other callback blocks executing
NSThread.sleepForTimeInterval(0.06)
executingCallbacks--
e.fulfill()
}
let e1 = self.expectation()
p.future.onComplete(context: Queue.main.context) { _ in
XCTAssert(executingCallbacks == 0, "This should be the only executing callback")
executingCallbacks++
// sleep a bit to increase the chances of other callback blocks executing
NSThread.sleepForTimeInterval(0.06)
executingCallbacks--
e1.fulfill()
}
}
p.success()
self.waitForExpectationsWithTimeout(5, handler: nil)
}
// Test for https://github.com/Thomvis/BrightFutures/issues/18
func testCompletionBlockOnMainQueue() {
var key = "mainqueuespecifickey"
let value = "value"
let valuePointer = getMutablePointer(value)
dispatch_queue_set_specific(dispatch_get_main_queue(), &key, valuePointer, nil)
XCTAssertEqual(dispatch_get_specific(&key), valuePointer, "value should have been set on the main (i.e. current) queue")
let e = self.expectation()
Future<Int, NoError>.succeeded(1).onSuccess(context: Queue.main.context) { val in
XCTAssertEqual(dispatch_get_specific(&key), valuePointer, "we should now too be on the main queue")
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
}
/**
* This extension contains utility methods used in the tests above
*/
extension XCTestCase {
func expectation() -> XCTestExpectation {
return self.expectationWithDescription("no description")
}
func failingFuture<U>() -> Future<U, NSError> {
return future { error in
usleep(arc4random_uniform(100))
return Result(error: NSError(domain: "failedFuture", code: 0, userInfo: nil))
}
}
func succeedingFuture<U>(val: U) -> Future<U, NSError> {
return future { _ in
usleep(arc4random_uniform(100))
return Result(value: val)
}
}
}
func fibonacci(n: Int) -> Int {
switch n {
case 0...1:
return n
default:
return fibonacci(n - 1) + fibonacci(n - 2)
}
}
func fibonacciFuture(n: Int) -> Future<Int, NoError> {
return Future<Int, NoError>.succeeded(fibonacci(n))
}
func getMutablePointer (object: AnyObject) -> UnsafeMutablePointer<Void> {
return UnsafeMutablePointer<Void>(bitPattern: Word(ObjectIdentifier(object).uintValue))
}
|
0 | //
// UZShareView.swift
// UizaSDK
//
// Created by Nam Kennic on 5/3/18.
// Copyright © 2018 Nam Kennic. All rights reserved.
//
import UIKit
import FrameLayoutKit
import SwiftIcons
open class UZEndscreenView: UIView {
open lazy var blurView: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
open lazy var titleLabel: UILabel = UILabel()
open lazy var replayButton: UZButton = UZButton()
open lazy var shareButton: UZButton = UZButton()
let frameLayout = StackFrameLayout(axis: .horizontal)
open var allButtons: [UIButton] { [replayButton, shareButton] }
open var title: String? {
get { titleLabel.text }
set {
titleLabel.text = newValue
setNeedsLayout()
}
}
init() {
super.init(frame: .zero)
setupUI()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open func setupUI() {
backgroundColor = UIColor(white: 0.0, alpha: 0.35)
if #available(iOS 8.2, *) {
titleLabel.font = UIFont.systemFont(ofSize: 15, weight: .medium)
} else {
titleLabel.font = UIFont.systemFont(ofSize: 15)
}
titleLabel.textColor = .white
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 3
titleLabel.isHidden = true
let buttonColor = UIColor.white
replayButton.setImage(UIImage(icon: .googleMaterialDesign(.replay), size: CGSize(width: 32, height: 32),
textColor: buttonColor, backgroundColor: .clear), for: .normal)
shareButton.setImage(UIImage(icon: .googleMaterialDesign(.share), size: CGSize(width: 32, height: 32),
textColor: buttonColor, backgroundColor: .clear), for: .normal)
replayButton.setBorderColor(buttonColor, for: .normal)
shareButton.setBorderColor(buttonColor, for: .normal)
replayButton.borderSize = 1.0
shareButton.borderSize = 1.0
replayButton.isRoundedButton = true
shareButton.isRoundedButton = true
replayButton.extendSize = CGSize(width: 24, height: 24)
shareButton.extendSize = CGSize(width: 24, height: 24)
replayButton.tag = UZButtonTag.replay.rawValue
shareButton.tag = UZButtonTag.share.rawValue
// addSubview(blurView)
// addSubview(titleLabel)
addSubview(replayButton)
addSubview(shareButton)
addSubview(frameLayout)
// frameLayout + titleLabel
(frameLayout + replayButton).alignment = (.center, .center)
(frameLayout + shareButton).alignment = (.center, .center)
frameLayout.spacing = 30
frameLayout.distribution = .center
frameLayout.padding(top: 20, left: 20, bottom: 20, right: 20)
}
override open func layoutSubviews() {
super.layoutSubviews()
blurView.frame = bounds
frameLayout.frame = bounds
}
}
|
0 | struct ReceiverSelection : Codable {
let receiver: Receiver
let mediaType: MediaType?
let filePath: String?
}
|
0 | //
// UIDeviceExtension.swift
// DNSwiftProject
//
// Created by mainone on 16/12/26.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
private let DeviceList = [
/* iPod 5 */ "iPod5,1": "iPod Touch 5",
/* iPod 6 */ "iPod7,1": "iPod Touch 6",
/* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4",
/* iPhone 4S */ "iPhone4,1": "iPhone 4S",
/* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5",
/* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C",
/* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S",
/* iPhone 6 */ "iPhone7,2": "iPhone 6",
/* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus",
/* iPhone 6S */ "iPhone8,1": "iPhone 6S",
/* iPhone 6S Plus */ "iPhone8,2": "iPhone 6S Plus",
/* iPhone 7 */ "iPhone9,1": "iPhone 7", "iPhone9,3": "iPhone 7",
/* iPhone 7 Plus */ "iPhone9,2": "iPhone 7 Plus", "iPhone9,4": "iPhone 7 Plus",
/* iPhone SE */ "iPhone8,4": "iPhone SE",
/* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2",
/* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3",
/* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4",
/* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air",
/* iPad Air 2 */ "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2",
/* iPad Mini */ "iPad2,5": "iPad Mini", "iPad2,6": "iPad Mini", "iPad2,7": "iPad Mini",
/* iPad Mini 2 */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2",
/* iPad Mini 3 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3",
/* iPad Mini 4 */ "iPad5,1": "iPad Mini 4", "iPad5,2": "iPad Mini 4",
/* iPad Pro */ "iPad6,7": "iPad Pro", "iPad6,8": "iPad Pro",
/* AppleTV */ "AppleTV5,3": "AppleTV",
/* Simulator */ "x86_64": "Simulator", "i386": "Simulator"
]
extension UIDevice {
// 设备名称
public class func deviceModelReadable() -> String {
return DeviceList[deviceModel()] ?? deviceModel()
}
public class func deviceModel() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
var identifier = ""
let mirror = Mirror(reflecting: machine)
for child in mirror.children {
let value = child.value
if let value = value as? Int8, value != 0 {
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
return identifier
}
}
|
0 | /*
* Copyright (c) 2017-2018 Runtime Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import CommonCrypto
internal extension Data {
// MARK: - Convert data to and from types
init<T>(from value: T) {
var value = value
self = withUnsafePointer(to: &value) { (pointer) -> Data in
Data(buffer: UnsafeBufferPointer(start: pointer, count: 1))
}
}
func read<T: FixedWidthInteger>(offset: Int = 0) -> T {
let length = MemoryLayout<T>.size
#if swift(>=5.0)
return subdata(in: offset ..< offset + length).withUnsafeBytes { $0.load(as: T.self) }
#else
return subdata(in: offset ..< offset + length).withUnsafeBytes { $0.pointee }
#endif
}
func readBigEndian<R: FixedWidthInteger>(offset: Int = 0) -> R {
let r: R = read(offset: offset)
return r.bigEndian
}
// MARK: - Hex Encoding
struct HexEncodingOptions: OptionSet {
public let rawValue: Int
public static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
public static let space = HexEncodingOptions(rawValue: 1 << 1)
public static let prepend0x = HexEncodingOptions(rawValue: 1 << 2)
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
func hexEncodedString(options: HexEncodingOptions = []) -> String {
if isEmpty {
return "0 bytes"
}
var format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
if options.contains(.space) {
format.append(" ")
}
let prefix = options.contains(.prepend0x) ? "0x" : ""
return prefix + map { String(format: format, $0) }.joined()
}
// MARK: - Fragmentation
func fragment(size: Int) -> [Data] {
return stride(from: 0, to: self.count, by: size).map {
Data(self[$0..<Swift.min($0 + size, self.count)])
}
}
// MARK: - SHA 256
func sha256() -> [UInt8] {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
withUnsafeBytes {
_ = CC_SHA256($0.baseAddress, CC_LONG(count), &hash)
}
return hash
}
}
|
0 | //
// CameraCell.swift
// Pods
//
// Created by Joakim Gyllström on 2015-09-26.
//
//
import UIKit
import AVFoundation
/**
*/
final class CameraCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraBackground: UIView!
var cameraOverlayView: UIView?
var cameraOverlayAlpha: CGFloat {
get {
return cameraOverlayView?.alpha ?? 0
}
set {
if cameraOverlayView == nil {
let overlayView = UIView(frame: cameraBackground.bounds)
overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlayView.backgroundColor = .black
overlayView.isHidden = true
cameraBackground.addSubview(overlayView)
cameraOverlayView = overlayView
}
cameraOverlayView?.alpha = newValue
}
}
@objc var takePhotoIcon: UIImage? {
didSet {
imageView.image = session?.isRunning == true ? takePhotoIcon?.withRenderingMode(.alwaysTemplate) : takePhotoIcon
}
}
@objc var session: AVCaptureSession? { return captureLayer?.session }
@objc var captureLayer: AVCaptureVideoPreviewLayer?
@objc let sessionQueue = DispatchQueue(label: "AVCaptureVideoPreviewLayer", attributes: [])
private var observers = [NSObjectProtocol]()
override func awakeFromNib() {
super.awakeFromNib()
// Don't trigger camera access for the background
guard AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized else {
return
}
do {
// Prepare avcapture session
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSession.Preset.medium
// Hook upp device
let device = AVCaptureDevice.default(for: AVMediaType.video)
let input = try AVCaptureDeviceInput(device: device!)
session.addInput(input)
// Setup capture layer
let captureLayer = AVCaptureVideoPreviewLayer(session: session)
captureLayer.frame = bounds
captureLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
cameraBackground.layer.addSublayer(captureLayer)
self.captureLayer = captureLayer
observers = [
NotificationCenter.default.addObserver(forName: .AVCaptureSessionDidStartRunning, object: session, queue: .main, using: self.handleRunningStateChangeNotification(_:)),
NotificationCenter.default.addObserver(forName: .AVCaptureSessionDidStopRunning, object: session, queue: .main, using: self.handleRunningStateChangeNotification(_:)),
NotificationCenter.default.addObserver(forName: .AVCaptureSessionWasInterrupted, object: session, queue: .main, using: self.handleRunningStateChangeNotification(_:)),
]
} catch {
// Do nothing.
}
}
deinit {
observers.forEach { NotificationCenter.default.removeObserver($0) }
}
override func layoutSubviews() {
super.layoutSubviews()
captureLayer?.frame = bounds
}
@objc func startLiveBackground() {
sessionQueue.async { () -> Void in
self.session?.startRunning()
}
}
@objc func stopLiveBackground() {
sessionQueue.async { () -> Void in
self.session?.stopRunning()
}
}
private func handleRunningStateChangeNotification(_ : Notification) {
guard let session = session else { return }
captureLayer?.isHidden = !session.isRunning
if let cameraOverlayView = cameraOverlayView {
cameraOverlayView.isHidden = !session.isRunning
cameraOverlayView.bringSubviewToFront(cameraOverlayView)
}
imageView.image = session.isRunning ? takePhotoIcon?.withRenderingMode(.alwaysTemplate) : takePhotoIcon
}
}
|
0 | // Copyright 2020 Itty Bitty Apps Pty Ltd
import Foundation
import AppStoreConnect_Swift_SDK
import Model
import SwiftyTextTable
// MARK: - API conveniences
extension Model.Device {
init( _ attributes: AppStoreConnect_Swift_SDK.Device.Attributes) {
self.init(
udid: attributes.udid,
addedDate: attributes.addedDate,
name: attributes.name,
deviceClass: attributes.deviceClass?.rawValue,
model: attributes.model,
platform: attributes.platform?.rawValue,
status: attributes.status?.rawValue
)
}
init(_ apiDevice: AppStoreConnect_Swift_SDK.Device) {
self.init(apiDevice.attributes)
}
init(_ response: AppStoreConnect_Swift_SDK.DeviceResponse) {
self.init(response.data)
}
}
// MARK: - TextTable conveniences
extension Model.Device: ResultRenderable, TableInfoProvider {
static func tableColumns() -> [TextTableColumn] {
return [
TextTableColumn(header: "UDID"),
TextTableColumn(header: "Name"),
TextTableColumn(header: "Date Added"),
TextTableColumn(header: "Device Class"),
TextTableColumn(header: "Model"),
TextTableColumn(header: "Platform"),
TextTableColumn(header: "Status"),
]
}
var tableRow: [CustomStringConvertible] {
return [
udid,
name,
addedDate?.formattedDate,
deviceClass,
model,
platform,
status,
].map { $0 ?? "" }
}
}
|
0 | //
// UIColor+Extensions.swift
// SampleProject
//
// Created by Pavan Kumar Valluru on 16/02/2017.
// Copyright © 2017 Pavan Kumar Valluru. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
let newRed = CGFloat(red)/255
let newGreen = CGFloat(green)/255
let newBlue = CGFloat(blue)/255
self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
|
0 | //
// MockTimerFactory.swift
//
// Created by Luciano Polit on 3/4/18.
//
import Foundation
import AwesomeUtilities
public class MockTimerFactory: TimerFactory {
public private(set) var builders: [MockBuilder] = []
public var completionExecutors: [CompletionExecutor<Timer>] {
return builders.compactMap { $0.completionExecutor }
}
public override func create() -> Builder {
let builder = MockBuilder()
builders.append(builder)
return builder
}
public class MockBuilder: Builder {
public private(set) var timeInterval: TimeInterval?
public private(set) var repeats: Bool?
public private(set) var completion: ((Timer) -> ())?
public private(set) var timer: Timer?
public private(set) var completionExecutor: CompletionExecutor<Timer>?
public override func timeInterval(_ timeInterval: TimeInterval) -> Self {
self.timeInterval = timeInterval
return self
}
public override func repeats(_ repeats: Bool) -> Self {
self.repeats = repeats
return self
}
public override func completion(_ completion: @escaping (Timer) -> ()) -> Self {
self.completion = completion
return self
}
public override func build() -> Timer {
timer = super.build()
completionExecutor = CompletionExecutor(sender: timer!, completion: completion)
return timer!
}
}
}
|
0 | //
// AppControllerRouter.swift
// DiveLane
//
// Created by NewUser on 27/09/2018.
// Copyright © 2018 Matter Inc. All rights reserved.
//
import UIKit
import web3swift
import BigInt
class EIP681Router {
let transactionsService = TransactionsService()
let etherscanService = EtherscanService()
let model = EIP681Model()
public func sendCustomTransaction(parsed: Web3.EIP681Code, usingWindow window: UIWindow) {
switch parsed.functionName {
case "transfer":
sendERC20TokenTransaction(parsed: parsed, usingWindow: window)
default:
sendArbitraryTransactionToContract(parsed: parsed, usingWindow: window)
}
}
public func sendETHTransaction(parsed: Web3.EIP681Code, usingWindow window: UIWindow) {
let targetAddress = model.getParsedAddress(targetAddress: parsed.targetAddress)
let controller = SendSettingsViewController(tokenAddress: "",
amount: parsed.amount ?? 0,
destinationAddress: targetAddress.address,
isFromDeepLink: true)
self.showController(controller, window: window)
}
public func sendERC20TokenTransaction(parsed: Web3.EIP681Code, usingWindow window: UIWindow) {
let tokenAddress = parsed.function?.inputs[0].name
guard let amount = parsed.function?.inputs[1].name else { return }
let targetAddress = model.getParsedAddress(targetAddress: parsed.targetAddress)
let controller = SendSettingsViewController(tokenAddress: tokenAddress,
amount: BigUInt(amount)!,
destinationAddress: targetAddress.address,
isFromDeepLink: true)
showController(controller, window: window)
}
public func sendArbitraryTransactionToContract(parsed: Web3.EIP681Code, usingWindow window: UIWindow) {
model.changeCurrentNetowrk(chainId: parsed.chainID)
let web3 = web3swift.web3(provider: InfuraProvider(CurrentNetwork.currentNetwork ?? Networks.Mainnet)!)
CurrentWeb.currentWeb = web3
//Preparing the options
var options: Web3Options = Web3Options.defaultOptions()
options.gasLimit = parsed.gasLimit
options.gasPrice = parsed.gasPrice
options.value = parsed.amount
let contractAddress = model.getParsedAddress(targetAddress: parsed.targetAddress)
guard let methodName = parsed.functionName else { return }
guard let params = parsed.function?.inputs.map({ return Parameter(type: $0.type.abiRepresentation,
value: $0.name) }) else {
return
}
let data = parsed.parameters.map {
return $0.value
}
findABI(contractAddress: contractAddress,
params: params,
data: data,
methodName: methodName,
options: options,
usingWindow: window)
}
public func findABI(contractAddress: EthereumAddress, params: [Parameter], data: [AnyObject],
methodName: String, options: Web3Options, usingWindow window: UIWindow) {
etherscanService.getAbi(forContractAddress: contractAddress.address) { (result) in
switch result {
case .Success(let abi):
self.showArbitratySendingScreen(data: data, params: params,
contractAddress: contractAddress,
contractAbi: abi, methodName: methodName,
options: options, usingWindow: window)
case .Error:
//If there is no ABI posted on etherscan.
let contractAbi = self.model.getContractABI(contractAddress: contractAddress)
self.showArbitratySendingScreen(data: data, params: params,
contractAddress: contractAddress, contractAbi: contractAbi,
methodName: methodName, options: options, usingWindow: window)
}
}
}
public func showArbitratySendingScreen(data: [AnyObject],
params: [Parameter],
contractAddress: EthereumAddress,
contractAbi: String,
methodName: String,
options: Web3Options,
usingWindow window: UIWindow) {
self.transactionsService
.prepareTransactionToContract(
data: data,
contractAbi: contractAbi,
contractAddress: contractAddress.address,
method: methodName,
predefinedOptions: options) { (result) in
switch result {
case .Error(let error):
let controller = AppController().goToApp()
self.showController(controller,
window: window)
showErrorAlert(for: controller,
error: error,
completion: nil)
case .Success(let intermediate):
let controller = SendArbitraryTransactionViewController(
params: params,
transactionInfo:
TransactionInfo(
contractAddress: contractAddress.address,
transactionIntermediate:
intermediate,
methodName: methodName)
)
self.showController(controller,
window: window)
}
}
}
private func showController(_ controller: UIViewController, window: UIWindow) {
window.rootViewController = controller
window.makeKeyAndVisible()
}
}
|
0 | //
// AService.swift
// ZRouterTests
//
// Created by zuik on 2018/4/28.
// Copyright © 2018 zuik. All rights reserved.
//
import Foundation
import ZRouter
import ZIKRouter
import ZIKRouter.Internal
class AService {
var title: String?
}
protocol AServiceInput: class {
var title: String? { get set }
}
protocol AServiceInputAdapter: class {
var title: String? { get set }
}
protocol AServiceInputAdapter2: class {
var title: String? { get set }
}
@objc protocol AServiceInputObjcAdapter: ZIKServiceRoutable {
var title: String? { get set }
}
@objc protocol AServiceInputObjcAdapter2: ZIKServiceRoutable {
var title: String? { get set }
}
@objc protocol AServiceInputObjcAdapter3: ZIKServiceRoutable {
var title: String? { get set }
}
extension AService: ZIKRoutableService, AServiceInput, AServiceInputAdapter, AServiceInputAdapter2, AServiceInputObjcAdapter, AServiceInputObjcAdapter2, AServiceInputObjcAdapter3 {
}
extension RoutableService where Protocol == AServiceInput {
init() { self.init(declaredProtocol: Protocol.self) }
}
extension RoutableService where Protocol == AServiceInputAdapter {
init() { self.init(declaredProtocol: Protocol.self) }
}
protocol AServiceModuleInput: class {
var title: String? { get set }
func makeDestinationCompletion(_ block: @escaping (AServiceInput) -> Void)
}
protocol AServiceModuleInput2: class {
var title: String? { get set }
func makeDestinationCompletion(_ block: @escaping (AServiceInput) -> Void)
}
protocol AServiceModuleInputAdapter: class {
var title: String? { get set }
func makeDestinationCompletion(_ block: @escaping (AServiceInput) -> Void)
}
@objc protocol AServiceModuleInputObjcAdapter: ZIKServiceModuleRoutable {
var title: String? { get set }
func makeDestinationCompletion(_ block: @escaping (AServiceInputObjcAdapter) -> Void)
}
extension RoutableServiceModule where Protocol == AServiceModuleInput {
init() { self.init(declaredProtocol: Protocol.self) }
}
extension RoutableServiceModule where Protocol == AServiceModuleInput2 {
init() { self.init(declaredProtocol: Protocol.self) }
}
extension RoutableServiceModule where Protocol == AServiceModuleInputAdapter {
init() { self.init(declaredProtocol: Protocol.self) }
}
class AServiceModuleConfiguration: ZIKPerformRouteConfiguration, AServiceModuleInput, AServiceModuleInputAdapter, AServiceModuleInputObjcAdapter {
var completion: ((AServiceInput) -> Void)?
var objcCompletion: ((AServiceInputObjcAdapter) -> Void)?
var title: String?
func makeDestinationCompletion(_ block: @escaping (AServiceInput) -> Void) {
completion = block
}
func makeDestinationCompletion(_ block: @escaping (AServiceInputObjcAdapter) -> Void) {
objcCompletion = block
}
override func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! AServiceModuleConfiguration
copy.title = self.title
return copy
}
}
class AServiceRouter: ZIKServiceRouter<AnyObject, AServiceModuleConfiguration> {
override class func registerRoutableDestination() {
registerService(AService.self)
if !TEST_BLOCK_ROUTE {
register(RoutableService<AServiceInput>())
register(RoutableServiceModule<AServiceModuleInput>())
}
}
override class func defaultRouteConfiguration() -> AServiceModuleConfiguration {
return AServiceModuleConfiguration()
}
override func destination(with configuration: AServiceModuleConfiguration) -> AnyObject? {
if TestConfig.routeShouldFail {
return nil
}
return AService()
}
override func prepareDestination(_ destination: AnyObject, configuration: AServiceModuleConfiguration) {
guard let destination = destination as? AServiceInput else {
return
}
if let title = configuration.title {
destination.title = title
}
}
override func didFinishPrepareDestination(_ destination: AnyObject, configuration: AServiceModuleConfiguration) {
if let completion = configuration.completion, let destination = destination as? AServiceInput {
completion(destination)
configuration.completion = nil
}
}
}
class AServiceAdapter: ZIKServiceRouteAdapter {
override static func registerRoutableDestination() {
ZIKAnyServiceRouter.register(RoutableServiceModule<AServiceModuleInput2>(), forMakingService: AService.self) { () -> AServiceModuleInput2 in
class AServiceModuleConfiguration: ServiceMakeableConfiguration<AServiceInput, (String) -> Void>, AServiceModuleInput2 {
var title: String? {
didSet {
makeDestination = { [unowned self] () in
if TestConfig.routeShouldFail {
return nil
}
let destination = AService()
destination.title = self.title
return destination
}
}
}
func makeDestinationCompletion(_ block: @escaping (AServiceInput) -> Void) {
self.didMakeDestination = block
}
func makeDestinationCompletion(_ block: @escaping (AServiceInputObjcAdapter) -> Void) {
self.didMakeDestination = { d in
if let d = d as? AServiceInputObjcAdapter {
block(d)
}
}
}
}
let config = AServiceModuleConfiguration({_ in})
config.makeDestination = {
if TestConfig.routeShouldFail {
return nil
}
let destination = AService()
return destination
}
return config
}
register(adapter: RoutableService<AServiceInputObjcAdapter>(), forAdaptee: RoutableService<AServiceInputAdapter>())
register(adapter: RoutableService<AServiceInputAdapter>(), forAdaptee: RoutableService<AServiceInputObjcAdapter2>())
register(adapter: RoutableService<AServiceInputObjcAdapter2>(), forAdaptee: RoutableService<AServiceInputObjcAdapter3>())
register(adapter: RoutableService<AServiceInputObjcAdapter3>(), forAdaptee: RoutableService<AServiceInput>())
register(adapter: RoutableServiceModule<AServiceModuleInputAdapter>(), forAdaptee: RoutableServiceModule<AServiceModuleInputObjcAdapter>())
register(adapter: RoutableServiceModule<AServiceModuleInputObjcAdapter>(), forAdaptee: RoutableServiceModule<AServiceModuleInput>())
}
}
|
0 | //
// TableViewCell1.swift
// SearchBar
//
import UIKit
class TableViewCell1: UITableViewCell {
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var yearLbl: UILabel!
@IBOutlet weak var byLbl: UILabel!
@IBOutlet weak var imgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
} // #26
|
0 | @_exported import Vapor
extension Droplet {
public func setup() throws {
try collection(Routes.self)
get("index") { req in
return try self.view.make("index")
}
}
}
|
0 | //
// ProductsDataSource.swift
// Podest
//
// Created by Michael Nisi on 14.04.18.
// Copyright © 2018 Michael Nisi. All rights reserved.
//
import UIKit
import StoreKit
import os.log
private let log = OSLog.disabled
protocol CellProductsDelegate: class {
func cell(_ cell: UICollectionViewCell, payProductMatching productIdentifier: String)
}
/// Provides a single section presenting in-app purchasing.
final class ProductsDataSource: NSObject, SectionedDataSource {
/// For making an attributed paragraph.
struct Info: Summarizable {
var summary: String?
var title: String
var author: String?
var guid: String
}
/// Enumerates item types provided by this data source.
enum Item: Hashable {
case article(Info)
case offline
case empty
case product(SKProduct)
case thanks
case failed(String)
case loading
case restoring
}
static var messageCellID = "MessageCellID"
static var productCellID = "ProductCellID"
static var productsHeaderID = "ProductsHeaderID"
static var productsFooterID = "ProductsFooterID"
static var articleCellID = "ArticleCollectionViewCellID"
private var _sections = [[Item.loading]]
/// The current sections of this data source.
///
/// Sections must be accessed on the main queue.
var sections: [Array<Item>] {
get {
dispatchPrecondition(condition: .onQueue(.main))
return _sections
}
set {
dispatchPrecondition(condition: .onQueue(.main))
_sections = newValue
}
}
/// The central change handler called when the collection changed.
var sectionsChangeHandler: (([[Change<Item>]]) -> Void)?
/// Receives the index path of the product currently being purchased.
var purchasingHandler: ((IndexPath) -> Void)?
lazy var priceFormatter: NumberFormatter = {
let fmt = NumberFormatter()
fmt.formatterBehavior = .behavior10_4
fmt.numberStyle = .currency
return fmt
}()
/// Speculates if we are currently displaying a message.
var isMessage: Bool {
guard sections.count == 1,
sections.first?.count == 1,
let first = sections.first?.first else {
return false
}
switch first {
case .article, .product:
return false
case .offline, .empty, .thanks, .failed, .loading, .restoring:
return true
}
}
/// A distinct worker queue for diffing.
private var worker = DispatchQueue.global()
private let store: Shopping
private let contact: Contact
/// Creates a new products data source.
///
/// - Parameters:
/// - store: The store API to use.
/// - contact: The sellers contact information.
init(store: Shopping, contact: Contact) {
self.store = store
self.contact = contact
}
}
// MARK: - UICollectionViewDataSource
extension ProductsDataSource: UICollectionViewDataSource {
/// Registers nib objects with `collectionView` under identifiers.
static func registerCells(with collectionView: UICollectionView) {
let pairs = [
("MessageCollectionViewCell", messageCellID),
("ProductCell", productCellID),
("ArticleCollectionViewCell", articleCellID)
]
for p in pairs {
let nib = UINib(nibName: p.0, bundle: .main)
collectionView.register(nib, forCellWithReuseIdentifier: p.1)
}
}
// numberOfSections == 1
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int
) -> Int {
return sections[section].count
}
func storeItem(where indexPath: IndexPath) -> Item {
return sections[indexPath.section][indexPath.row]
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let item = storeItem(where: indexPath)
switch item {
case .article(let info):
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.articleCellID,
for: indexPath) as! ArticleCollectionViewCell
cell.textView.attributedText = StringRepository.makeSummaryWithHeadline(info: info)
cell.textView.delegate = self
return cell
case .offline:
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.messageCellID,
for: indexPath) as! MessageCollectionViewCell
cell.title.text = "You’re offline."
return cell
case .empty:
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.messageCellID,
for: indexPath) as! MessageCollectionViewCell
cell.title.text = "No products available at the moment."
return cell
case .product(let product):
os_log("** product: %{public}@", log: log, type: .debug, product.productIdentifier)
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.productCellID,
for: indexPath) as! ProductCell
priceFormatter.locale = product.priceLocale
// In the meantime, I’ve grown sceptical about this self-configuring
// cells technique. I’d rather encapsulate all configuration in the data
// source, in one place. Having to switch into cell implementations,
// while working on the data source is distracting.
let p = priceFormatter.string(for: product.price) ?? "Sorry"
cell.data = ProductCell.Data(
productIdentifier: product.productIdentifier,
productName: product.localizedTitle,
productDescription: product.localizedDescription + "\n\(p) per year.",
price: p
)
cell.delegate = self
return cell
case .thanks:
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.messageCellID,
for: indexPath) as! MessageCollectionViewCell
cell.title.text = "Thank you!"
return cell
case .failed(let desc):
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.messageCellID,
for: indexPath) as! MessageCollectionViewCell
cell.title.text = desc
return cell
case .loading:
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.messageCellID,
for: indexPath) as! MessageCollectionViewCell
cell.title.text = "Loading Products…"
return cell
case .restoring:
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsDataSource.messageCellID,
for: indexPath) as! MessageCollectionViewCell
cell.title.text = "Restoring Purchases…"
return cell
}
}
}
// MARK: - UITextViewDelegate
extension ProductsDataSource: UITextViewDelegate {
func textView(
_ textView: UITextView,
shouldInteractWith URL: URL,
in characterRange: NSRange,
interaction: UITextItemInteraction
) -> Bool {
switch URL.absoluteString {
case "restore:":
store.restore()
return false
default:
return true
}
}
}
// MARK: - CellProductsDelegate
extension ProductsDataSource: CellProductsDelegate {
func cell(
_ cell: UICollectionViewCell,
payProductMatching productIdentifier: String
) {
store.payProduct(matching: productIdentifier)
}
}
// MARK: - ShoppingDelegate
extension ProductsDataSource: StoreDelegate {
/// Submits `new` items as our new sole section to the change handler on the
/// main queue.
private func submit(_ items: [Item]) {
// Capturing old sections on the main queue.
DispatchQueue.main.async { [weak self] in
guard let old = self?.sections else {
return
}
// Offloading diffing to a worker queue.
self?.worker.async {
let changes = ProductsDataSource.makeChanges(old: old, new: [items])
DispatchQueue.main.async {
self?.sectionsChangeHandler?(changes)
}
}
}
}
func store(_ store: Shopping, offers products: [SKProduct], error: ShoppingError?) {
os_log("store: offers: %{public}@", log: log, type: .debug, products)
guard error == nil else {
let er = error!
switch er {
case .offline:
submit([.offline])
default:
submit([.empty])
}
return
}
guard !products.isEmpty else {
return submit([.empty])
}
let claim = Info(
summary: """
Help me deliver podcasts. Here are three ways you can enjoy podcasts \
with Podest for one year and support my work.
""",
title: "Making apps is hard",
author: "Michael Nisi",
guid: UUID().uuidString
)
let explain = Info(
summary:"""
Choose your price for a non-renewing subscription, granting you to use \
this app without restrictions for one year.
<p>
Of course, you can always <a href="restore:">restore</a> previous purchases.
</p>
""",
title: "Choose your price",
author: "Michael Nisi",
guid: UUID().uuidString
)
let open = Info(
summary:"""
If you feel so inclined, please create issues on \
<a href="\(contact.github)">GitHub</a>.
<p>
<a href="mailto:\(contact.email)">Email me</a> if you have any \
questions.
</p>
""",
title: "100% Open Source",
author: "Michael Nisi",
guid: UUID().uuidString
)
submit(
[.article(claim)] +
products.map { .product($0) } +
[.article(explain), .article(open)]
)
}
private func indexPath(matching productIdentifier: ProductIdentifier) -> IndexPath?{
for (sectionIndex, section) in sections.enumerated() {
for (itemIndex, item) in section.enumerated() {
if case .product(let product) = item {
if product.productIdentifier == productIdentifier {
return IndexPath(item: itemIndex, section: sectionIndex)
}
}
}
}
return nil
}
func store(_ store: Shopping, purchasing productIdentifier: String) {
os_log("store: purchasing: %{public}@",
log: log, type: .debug, productIdentifier)
DispatchQueue.main.async { [weak self] in
guard let ip = self?.indexPath(matching: productIdentifier) else {
os_log("store: no matching product found in sections: %{public}@",
log: log, productIdentifier)
return
}
self?.purchasingHandler?(ip)
}
}
func storeRestoring(_ store: Shopping) {
os_log("store: restoring", log: log, type: .debug)
submit([.restoring])
}
func storeRestored(
_ store: Shopping,
productIdentifiers: [String]
) {
os_log("store: restored: %{public}@",
log: log, type: .debug, productIdentifiers)
guard !productIdentifiers.isEmpty else {
return submit([.failed("Sorry, no previous purchases to restore.")])
}
submit([.thanks])
}
func store(_ store: Shopping, purchased productIdentifier: String) {
os_log("store: purchased: %{public}@",
log: log, type: .debug, productIdentifier)
submit([.thanks])
}
/// Produces items from `error`.
private static func makeItems(error: ShoppingError) -> [Item] {
switch error {
case .cancelled:
return [.failed("Your purchase has been cancelled.")]
case .failed, .invalidProduct:
return [.failed("Your purchase failed.")]
case .notRestored:
return [.failed("Not restored.")]
case .offline:
return [.offline]
case .serviceUnavailable:
return [.failed("The App Store is not available at the moment.")]
}
}
func store(_ store: Shopping, error: ShoppingError) {
os_log("store: error: %{public}@", log: log, error as CVarArg)
submit(ProductsDataSource.makeItems(error: error))
}
}
|
0 | //
// Measurement.swift
// cardiola
//
// Created by Janusch Jacoby on 30/01/16.
// Copyright © 2016 BPPolze. All rights reserved.
//
import RealmSwift
import Foundation
import Charts
class Measurement: Object, PersistentModel {
static let SYSTOLIC_MAX = 200
static let SYSTOLIC_AVG = 120
static let DIASTOLIC_MAX = 130
static let DIASTOLIC_AVG = 75
static let HEART_RATE_MAX = 160
static let HEART_RATE_RESTING = 70
static let HEART_RATE_STRESS = 130
// MARK: Properties
dynamic var patient: Patient?
private let _heartRate = RealmOptional<Int>()
var heartRate: Int? {
get {
return _heartRate.value
}
set(newValue) {
_heartRate.value = newValue
}
}
private let _systolicPressure = RealmOptional<Int>()
var systolicPressure: Int? {
get {
return _systolicPressure.value
}
set(newValue) {
_systolicPressure.value = newValue
}
}
private let _diastolicPressure = RealmOptional<Int>()
var diastolicPressure: Int? {
get {
return _diastolicPressure.value
}
set(newValue) {
_diastolicPressure.value = newValue
}
}
var hasBloodPressure: Bool {
return self.diastolicPressure != nil || self.systolicPressure != nil
}
var hasHeartRate: Bool {
return self.heartRate != nil
}
dynamic var date: NSDate?
var formattedDate: String {
return formatDate(self.date, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.NoStyle)
}
var formattedTime: String {
return formatDate(self.date, dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.ShortStyle)
}
// MARK: Charts
// provides x and y values for plotting the attribute radar
var attributeRadar: ([String], [ChartDataEntry]) {
let xValues = ["Systolischer Blutdruck", "Diastolischer Blutdruck", "Pulsrate", "Blutzucker", "Sauferstoffsättigung", "Persönliches Befinden"]
// TODO: support missing vital parameters
let properties = [self.systolicPressure, self.diastolicPressure, self.heartRate, 0, 0, 0]
let yValues = properties.enumerate().map() {
return ($0.1 != nil) ? ChartDataEntry(value: 1.0, xIndex: $0.0) : ChartDataEntry(value: 0.0, xIndex: $0.0)
}
return (xValues, yValues)
}
// MARK: Initialization
convenience init(heartRate: Int, systolicPressure: Int, diastolicPressure: Int) {
self.init()
self.heartRate = heartRate
self.systolicPressure = systolicPressure
self.diastolicPressure = diastolicPressure
self.date = NSDate()
}
convenience init(systolicPressure: Int, diastolicPressure: Int) {
self.init(heartRate: 0, systolicPressure: systolicPressure, diastolicPressure: diastolicPressure)
}
convenience init(heartRate: Int) {
self.init(heartRate: heartRate, systolicPressure: 0, diastolicPressure: 0)
}
// MARK: Factory methods
internal static func createRandom() -> Measurement {
let systolic = random(min: 120, max: 180)
let diastolic = random(min: 70, max: 100)
let heartRate = random(min: 60, max: 130)
let measurement = Measurement(heartRate: heartRate, systolicPressure: systolic, diastolicPressure: diastolic)
return measurement
}
// MARK: PersistentModel
dynamic var id: String = NSUUID().UUIDString
override static func primaryKey() -> String? {
return "id"
}
}
// define convenience methods on measurement arrays
extension _ArrayType where Generator.Element == Measurement {
func averageHeartRate() -> Double? {
guard self.count != 0 else {
return nil
}
let heartRates = self.flatMap({ $0.heartRate })
return Double(heartRates.reduce(0, combine: {$0 + $1 })) / Double(self.count)
}
func maxHeartRate() -> Int? {
guard self.count != 0 else {
return nil
}
let heartRates = self.flatMap({ $0.heartRate })
return heartRates.maxElement()
}
}
|
0 | import Foundation
import BigInt
extension Decimal {
var decimalCount: Int {
max(-exponent, 0)
}
func significantDecimalCount(threshold: Decimal, maxDecimals: Int) -> Int {
for decimalCount in 0..<maxDecimals {
if self * pow(10, decimalCount) >= threshold {
return decimalCount
}
}
return maxDecimals
}
init?(bigUInt: BigUInt, decimal: Int) {
guard let significand = Decimal(string: bigUInt.description) else {
return nil
}
self.init(sign: .plus, exponent: -decimal, significand: significand)
}
}
|
0 | //
// KulayTests.swift
// KulayTests
//
// Created by Eric Brewer on 8/12/16.
// Copyright © 2016 Bunga. All rights reserved.
//
import XCTest
@testable import Kulay
class KulayTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
|
0 | import XCTest
import SwiftAST
class TypeFormatterTests: XCTestCase {
func testAsStringFunctionSignature() {
let sig1 = FunctionSignature(name: "abc", parameters: [],
returnType: .int, isStatic: false)
let sig2 = FunctionSignature(name: "abc",
parameters: [ParameterSignature(label: "a", name: "b", type: .float)],
returnType: .void,
isStatic: false)
let sig3 = FunctionSignature(name: "abc",
parameters: [ParameterSignature(label: "a", name: "b", type: .float),
ParameterSignature(label: "c", name: "c", type: .int)],
returnType: .void,
isStatic: true)
XCTAssertEqual("abc() -> Int", TypeFormatter.asString(signature: sig1, includeName: true))
XCTAssertEqual("() -> Int", TypeFormatter.asString(signature: sig1, includeName: false))
XCTAssertEqual("abc(a b: Float)", TypeFormatter.asString(signature: sig2, includeName: true))
XCTAssertEqual("(a b: Float)", TypeFormatter.asString(signature: sig2, includeName: false))
XCTAssertEqual("static abc(a b: Float, c: Int)", TypeFormatter.asString(signature: sig3, includeName: true))
XCTAssertEqual("static (a b: Float, c: Int)", TypeFormatter.asString(signature: sig3, includeName: false))
XCTAssertEqual("(a b: Float, c: Int)", TypeFormatter.asString(signature: sig3, includeName: false, includeStatic: false))
// Test default values for `includeName`
XCTAssertEqual("() -> Int", TypeFormatter.asString(signature: sig1))
XCTAssertEqual("(a b: Float)", TypeFormatter.asString(signature: sig2))
XCTAssertEqual("static (a b: Float, c: Int)", TypeFormatter.asString(signature: sig3))
}
func testAsStringParameterDefaultValue() {
let parameters = [
ParameterSignature(label: "label", name: "name", type: .int, hasDefaultValue: true)
]
XCTAssertEqual("(label name: Int = default)", TypeFormatter.asString(parameters: parameters))
}
}
|
0 | //
// ViewController.swift
// SimonSays
//
// Created by Joseph Turk on 4/20/17.
// Copyright © 2017 JosephTurk. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
0 | //
// GiftModel.swift
// LiveGiftView
//
// Created by shuhui on 2020/9/19.
//
import UIKit
class GiftModel: NSObject {
/// 礼物的id 加上 用户的id
var key:String = ""
/// 礼物数量
var number:Int = 1
deinit {
print("释放==\(self)")
}
}
|
0 | //
// VoiceDetailCtrlr.swift
// Talk
//
// Created by CP3 on 10/10/19.
// Copyright © 2019 CP3. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
import Bricking
class VoiceDetailCtrlr: UIViewController {
private let synthesizer = AVSpeechSynthesizer()
private let voice: AVSpeechSynthesisVoice
init(voice: AVSpeechSynthesisVoice) {
self.voice = voice
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.white
let button = UIButton(type: .custom)
button.setTitleColor(UIColor.black, for: UIControl.State.normal)
button.setTitle("Talk", for: UIControl.State.normal)
view.asv(button)
button.width(62).centerInContainer() ~ 30
button.addTarget(self, action: #selector(talk), for: UIControl.Event.touchUpInside)
}
@objc func talk() {
let array = ["小朋友,请找出您听到的单词对应的图片吧!"]
array.forEach{
let utterance = AVSpeechUtterance(string: $0)
utterance.rate = 0.4
utterance.postUtteranceDelay = 2.0
utterance.voice = voice
self.synthesizer.speak(utterance)
}
}
}
|
0 | //
// ViewController.swift
// SnowEffectViewBuilder
//
// Created by DADA on 11/24/2019.
// Copyright (c) 2019 DADA. All rights reserved.
//
import UIKit
import SnowEffectViewBuilder
class ViewController: UIViewController {
private let toggle = UISwitch()
override func viewDidLoad() {
setupToggle()
let emitter = SnowEffectViewBuilder.createLayer(
type: .circle(size: CGSize(width: 1.0, height: 1.0), color: UIColor(white: 0.85, alpha: 1.0)),
size: self.view.bounds.size)
self.view.layer.addSublayer(emitter)
}
private func setupToggle() {
self.view.addSubview(toggle)
self.toggle.addTarget(self, action: #selector(setupSnowEffect(sender:)), for: .valueChanged)
self.toggle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
toggle.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0),
toggle.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30)])
}
@objc func setupSnowEffect(sender: UISwitch) {
UIView.animate(withDuration: 0.4) {
self.view.backgroundColor = sender.isOn ? UIColor.black : UIColor.white
}
}
}
|
0 | ////
/// EditorialJoinCell.swift
//
class EditorialJoinCell: EditorialCellContent {
private let joinLabel = StyledLabel(style: .editorialHeader)
private let joinCaption = StyledLabel(style: .editorialCaption)
private let emailField = ElloTextField()
private let usernameField = ElloTextField()
private let passwordField = ElloTextField()
private let submitButton = StyledButton(style: .editorialJoin)
var onJoinChange: ((Editorial.JoinInfo) -> Void)?
private var isValid: Bool {
guard
let email = emailField.text,
let username = usernameField.text,
let password = passwordField.text
else { return false }
return Validator.hasValidSignUpCredentials(
email: email,
username: username,
password: password,
isTermsChecked: true
)
}
@objc
func submitTapped() {
guard
let email = emailField.text,
let username = usernameField.text,
let password = passwordField.text
else { return }
let info: Editorial.JoinInfo = (
email: emailField.text, username: usernameField.text, password: passwordField.text,
submitted: true
)
onJoinChange?(info)
emailField.isEnabled = false
usernameField.isEnabled = false
passwordField.isEnabled = false
submitButton.isEnabled = false
let responder: EditorialToolsResponder? = findResponder()
responder?.submitJoin(
cell: self.editorialCell,
email: email,
username: username,
password: password
)
}
override func style() {
super.style()
joinLabel.text = InterfaceString.Editorials.Join
joinLabel.isMultiline = true
joinCaption.text = InterfaceString.Editorials.JoinCaption
joinCaption.isMultiline = true
ElloTextFieldView.styleAsEmailField(emailField)
ElloTextFieldView.styleAsUsernameField(usernameField)
ElloTextFieldView.styleAsPasswordField(passwordField)
emailField.backgroundColor = .white
emailField.placeholder = InterfaceString.Editorials.EmailPlaceholder
usernameField.backgroundColor = .white
usernameField.placeholder = InterfaceString.Editorials.UsernamePlaceholder
passwordField.backgroundColor = .white
passwordField.placeholder = InterfaceString.Editorials.PasswordPlaceholder
submitButton.isEnabled = false
submitButton.title = InterfaceString.Editorials.SubmitJoin
}
override func updateConfig() {
super.updateConfig()
emailField.text = config.join?.email
usernameField.text = config.join?.username
passwordField.text = config.join?.password
let enabled = !(config.join?.submitted ?? false)
emailField.isEnabled = enabled
usernameField.isEnabled = enabled
passwordField.isEnabled = enabled
submitButton.isEnabled = enabled
}
override func bindActions() {
super.bindActions()
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
emailField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
usernameField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
passwordField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
}
override func arrange() {
super.arrange()
editorialContentView.addSubview(joinLabel)
editorialContentView.addSubview(joinCaption)
editorialContentView.addSubview(emailField)
editorialContentView.addSubview(usernameField)
editorialContentView.addSubview(passwordField)
editorialContentView.addSubview(submitButton)
joinLabel.snp.makeConstraints { make in
make.top.equalTo(editorialContentView).inset(Size.smallTopMargin)
make.leading.equalTo(editorialContentView).inset(Size.defaultMargin)
make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin)
.priority(Priority.required)
}
joinCaption.snp.makeConstraints { make in
make.top.equalTo(joinLabel.snp.bottom).offset(Size.textFieldMargin)
make.leading.equalTo(editorialContentView).inset(Size.defaultMargin)
make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin)
.priority(Priority.required)
}
let fields = [emailField, usernameField, passwordField]
fields.forEach { field in
field.snp.makeConstraints { make in
make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin)
}
}
submitButton.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight).priority(Priority.required)
make.bottom.equalTo(editorialContentView).offset(-Size.defaultMargin.bottom)
make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin)
}
}
override func layoutSubviews() {
super.layoutSubviews()
layoutIfNeeded() // why-t-f is this necessary!?
// doing this simple height calculation in auto layout was a total waste of time
let fields = [emailField, usernameField, passwordField]
let textFieldsBottom = frame.height - Size.defaultMargin.bottom - Size.buttonHeight
- Size.textFieldMargin
var remainingHeight = textFieldsBottom - joinCaption.frame.maxY - Size.textFieldMargin
- CGFloat(fields.count) * Size.joinMargin
if remainingHeight < Size.minFieldHeight * 3 {
joinCaption.isHidden = true
remainingHeight += joinCaption.frame.height + Size.textFieldMargin
}
else {
joinCaption.isVisible = true
}
let fieldHeight: CGFloat = min(
max(ceil(remainingHeight / 3), Size.minFieldHeight),
Size.maxFieldHeight
)
var y: CGFloat = textFieldsBottom
for field in fields.reversed() {
y -= fieldHeight
field.frame.origin.y = y
field.frame.size.height = fieldHeight
y -= Size.joinMargin
}
}
override func prepareForReuse() {
super.prepareForReuse()
onJoinChange = nil
}
}
extension EditorialJoinCell {
@objc
func textFieldDidChange() {
let info: Editorial.JoinInfo = (
email: emailField.text, username: usernameField.text, password: passwordField.text,
submitted: false
)
onJoinChange?(info)
submitButton.isEnabled = isValid
}
}
|
0 | import PackageDescription
let package = Package(
name: "SCRAM",
dependencies: [
.Package(url: "https://github.com/CryptoKitten/PBKDF2.git", majorVersion: 0, minor: 8),
]
)
|
0 | import Foundation
struct ErrorJson: Decodable {
let code: Int
let body: String
}
|
0 | //
// HomeNavigationController.swift
// NetableExample
//
// Created by Brendan on 2021-09-14.
// Copyright © 2021 Steamclock Software. All rights reserved.
//
import Combine
import Netable
import UIKit
class HomeNavigationController: UINavigationController {
private var cancellables = [AnyCancellable]()
override func viewDidLoad() {
super.viewDidLoad()
print("--- vdl")
UserRepository.shared.netable.requestFailureDelegate = self
}
}
extension HomeNavigationController: RequestFailureDelegate {
func requestDidFail<T>(_ request: T, error: NetableError) where T : Request {
print("==== request did fail")
// Ignore 401 unauthorized errors, we'll handle those in the UserRepository
if case let NetableError.httpError(statusCode, _) = error, statusCode == 401 {
return
}
let alert = UIAlertController(title: "Error", message: error.errorDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true, completion: nil)
}
}
|
0 | // 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 {
func g: a {
struct d<T: T where g<T where g: T: a {
var d = compose(Any) {
class
case c,
|
0 | //
// 17.12.swift
// Leetcode-Swift
//
// Created by 95cc on 2021/7/13.
//
import Foundation
/*
面试题 17.12. BiNode (简单)
https://leetcode-cn.com/problems/binode-lcci/
*/
class Solution_Jindian_17_12 {
/// 递归
func convertBiNode(_ root: TreeNode?) -> TreeNode? {
if root == nil {
return nil
}
let dummyNode: TreeNode? = TreeNode(0)
var tail = dummyNode
inorder(root, &tail)
return dummyNode?.right
}
func inorder(_ root: TreeNode?, _ tail: inout TreeNode?) {
if root == nil {
return
}
let left = root?.left
let right = root?.right
inorder(left, &tail)
tail?.right = root
root?.left = nil
tail = tail?.right
inorder(right, &tail)
}
/// 迭代解法
func convertBiNode_1(_ root: TreeNode?) -> TreeNode? {
if root == nil {
return nil
}
let dummyNode: TreeNode? = TreeNode(0)
var tail = dummyNode
var node = root
var stack = [TreeNode?]()
while node != nil || !stack.isEmpty {
while node != nil {
stack.append(node)
node = node?.left
}
node = stack.removeLast()
let right = node?.right
node?.left = nil
node?.right = nil
tail?.right = node
tail = tail?.right
node = right
}
return dummyNode?.right
}
/*
测试用例:
1. 功能:满二叉搜索树、都在左/右子树的二叉搜索树、普通二叉搜索树
2. 特殊:只有1个节点的二叉树搜索树
*/
func test() {
}
}
|
0 | //
// CanvasLayer.swift
// Canvas
//
// Created by Adeola Uthman on 10/7/18.
//
import Foundation
/** A layer of the canvas that contains drawing data. */
public class CanvasLayer {
/************************
* *
* VARIABLES *
* *
************************/
// -- PRIVATE VARS
/** The array of nodes on this layer. */
internal var drawings: [Node] = []
/** The type of layer this is: raster or vector. */
internal var type: LayerType = .raster
/** The nodes on this layer that are selected. */
internal var selectedNodes: [Node] = []
// -- PUBLIC VARS
/** Whether or not this layer is visible. */
public var isVisible: Bool = true
/** Whether or not this layer allows drawing. */
public var allowsDrawing: Bool = true
// -- COMPUTED PROPERTIES
/** The number of nodes (drawings) on this layer. */
public var nodeCount: Int {
return self.drawings.count
}
/** All of the nodes on this layer. */
public var nodes: [Node] {
return self.drawings
}
/************************
* *
* INIT *
* *
************************/
public init(type: LayerType) {
self.type = type
}
/************************
* *
* FUNCTIONS *
* *
************************/
/** Clears the drawing on this layer. */
public func clear(from canvas: Canvas) {
drawings = []
canvas.setNeedsDisplay()
}
/** Adds a new node (drawing) to this layer. */
public func add(node: Node, on canvas: Canvas) {
drawings.append(node)
canvas.setNeedsDisplay()
}
/** Returns the node at the given index. */
public func get(at: Int) -> Node? {
if at < 0 || at >= drawings.count { return nil }
return drawings[at]
}
/** Selects the given nodes on this layer. */
public func select(nodes: [Node], on canvas: Canvas) {
self.selectedNodes = nodes
canvas.setNeedsDisplay()
}
/** Returns the nodes that are selected. */
public func getSelectedNodes() -> [Node] {
return self.selectedNodes
}
/** Removes the node at the given index from this layer. */
public func removeNode(at: Int) -> Node {
let n = self.drawings.remove(at: at)
return n
}
/************************
* *
* LAYOUT *
* *
************************/
}
|
0 | //
// MediaPlayerAgentProtocol.swift
// NuguAgents
//
// Created by yonghoonKwon on 2020/07/06.
// Copyright (c) 2020 SK Telecom Co., Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// `MediaPlayerAgent` handles directives for media-player.
///
/// `MediaPlayerAgent` is used when playing media directly in the app.
public protocol MediaPlayerAgentProtocol: CapabilityAgentable {
/// The object that acts as the delegate of `MediaPlayerAgent`
var delegate: MediaPlayerAgentDelegate? { get set }
}
|
0 | //
// YAxisRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ChartYAxisRenderer)
open class YAxisRenderer: AxisRendererBase
{
public init(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, transformer: Transformer?)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: yAxis)
}
/// draws the y-axis labels to the screen
open override func renderAxisLabels(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler
else { return }
if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled
{
return
}
let xoffset = yAxis.xOffset
let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset
let dependency = yAxis.axisDependency
let labelPosition = yAxis.labelPosition
var xPos = CGFloat(0.0)
var textAlign: NSTextAlignment
if dependency == .left
{
if labelPosition == .outsideChart
{
textAlign = .right
xPos = viewPortHandler.offsetLeft - xoffset
}
else
{
textAlign = .left
xPos = viewPortHandler.offsetLeft + xoffset
}
}
else
{
if labelPosition == .outsideChart
{
textAlign = .left
xPos = viewPortHandler.contentRight + xoffset
}
else
{
textAlign = .right
xPos = viewPortHandler.contentRight - xoffset
}
}
drawYLabels(
context: context,
fixedPosition: xPos,
positions: transformedPositions(),
offset: yoffset - yAxis.labelFont.lineHeight,
textAlign: textAlign)
}
open override func renderAxisLine(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler
else { return }
if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(yAxis.axisLineColor.cgColor)
context.setLineWidth(yAxis.axisLineWidth)
if yAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if yAxis.axisDependency == .left
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
else
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
context.restoreGState()
}
/**
自定义颜色变化
*/
func UIColorFromRGB (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}//结束
/// draws the y-labels on the specified x-position
internal func drawYLabels(
context: CGContext,
fixedPosition: CGFloat,
positions: [CGPoint],
offset: CGFloat,
textAlign: NSTextAlignment)
{
guard
let yAxis = self.axis as? YAxis
else { return }
let labelFont = yAxis.labelFont
var labelTextColor = yAxis.labelTextColor
let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1
let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1)
for i in stride(from: from, to: to, by: 1)
{
let text = yAxis.getFormattedLabel(i)
// ChartUtils.drawText(//原生
// context: context,
// text: text,
// point: CGPoint(x: fixedPosition, y: positions[i].y + offset),
// align: textAlign,
// attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
//自定义颜色变化
if yAxis.isChangeColor {
if i < 3 {
labelTextColor = UIColorFromRGB(hex: "46b97c");
}else if i == 3{
labelTextColor = NSUIColor.black;
}else{
labelTextColor = UIColorFromRGB(hex: "ff5353");
}
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(x: fixedPosition, y: positions[i].y + offset),
align: textAlign,
attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}else{
labelTextColor = NSUIColor.black;
ChartUtils.drawText(//原生
context: context,
text: text,
point: CGPoint(x: fixedPosition, y: positions[i].y + offset),
align: textAlign,
attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}//结束
}
}
open override func renderGridLines(context: CGContext)
{
guard let
yAxis = self.axis as? YAxis
else { return }
if !yAxis.isEnabled
{
return
}
if yAxis.drawGridLinesEnabled
{
let positions = transformedPositions()
context.saveGState()
defer { context.restoreGState() }
context.clip(to: self.gridClippingRect)
context.setShouldAntialias(yAxis.gridAntialiasEnabled)
context.setStrokeColor(yAxis.gridColor.cgColor)
context.setLineWidth(yAxis.gridLineWidth)
context.setLineCap(yAxis.gridLineCap)
if yAxis.gridLineDashLengths != nil
{
context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
// draw the grid
for i in 0 ..< positions.count
{
//x轴的网格线去掉
if i != 0 {
drawGridLine(context: context, position: positions[i])
}//结束
// drawGridLine(context: context, position: positions[i])//原始代码
}
}
if yAxis.drawZeroLineEnabled
{
// draw zero line
drawZeroLine(context: context)
}
}
open var gridClippingRect: CGRect
{
var contentRect = viewPortHandler?.contentRect ?? CGRect.zero
let dy = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
open func drawGridLine(
context: CGContext,
position: CGPoint)
{
guard
let viewPortHandler = self.viewPortHandler
else { return }
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.strokePath()
}
open func transformedPositions() -> [CGPoint]
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer
else { return [CGPoint]() }
var positions = [CGPoint]()
positions.reserveCapacity(yAxis.entryCount)
let entries = yAxis.entries
for i in stride(from: 0, to: yAxis.entryCount, by: 1)
{
positions.append(CGPoint(x: 0.0, y: entries[i]))
}
transformer.pointValuesToPixel(&positions)
return positions
}
/// Draws the zero line at the specified position.
open func drawZeroLine(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler,
let transformer = self.transformer,
let zeroLineColor = yAxis.zeroLineColor
else { return }
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= yAxis.zeroLineWidth / 2.0
clippingRect.size.height += yAxis.zeroLineWidth
context.clip(to: clippingRect)
context.setStrokeColor(zeroLineColor.cgColor)
context.setLineWidth(yAxis.zeroLineWidth)
let pos = transformer.pixelForValues(x: 0.0, y: 0.0)
if yAxis.zeroLineDashLengths != nil
{
context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: pos.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: pos.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
open override func renderLimitLines(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let viewPortHandler = self.viewPortHandler,
let transformer = self.transformer
else { return }
var limitLines = yAxis.limitLines
if limitLines.count == 0
{
return
}
context.saveGState()
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.characters.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if l.labelPosition == .rightTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if l.labelPosition == .rightBottom
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if l.labelPosition == .leftTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
}
}
context.restoreGState()
}
}
|
0 | import XCTest
import Cuckoo
import RealmSwift
@testable import HSBitcoinKit
class TransactionSyncerTests: XCTestCase {
private var mockRealmFactory: MockIRealmFactory!
private var mockTransactionProcessor: MockITransactionProcessor!
private var mockAddressManager: MockIAddressManager!
private var mockBloomFilterManager: MockIBloomFilterManager!
private var maxRetriesCount: Int!
private var retriesPeriod: Double!
private var totalRetriesPeriod: Double!
private var realm: Realm!
private var syncer: TransactionSyncer!
override func setUp() {
super.setUp()
realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "TestRealm"))
try! realm.write {
realm.deleteAll()
}
mockRealmFactory = MockIRealmFactory()
stub(mockRealmFactory) { mock in
when(mock.realm.get).thenReturn(realm)
}
mockTransactionProcessor = MockITransactionProcessor()
mockAddressManager = MockIAddressManager()
mockBloomFilterManager = MockIBloomFilterManager()
stub(mockTransactionProcessor) { mock in
when(mock.process(transactions: any(), inBlock: any(), skipCheckBloomFilter: any(), realm: any())).thenDoNothing()
}
stub(mockAddressManager) { mock in
when(mock.fillGap()).thenDoNothing()
}
stub(mockBloomFilterManager) { mock in
when(mock.regenerateBloomFilter()).thenDoNothing()
}
maxRetriesCount = 3
retriesPeriod = 60
totalRetriesPeriod = 60 * 60 * 24
syncer = TransactionSyncer(
realmFactory: mockRealmFactory, processor: mockTransactionProcessor, addressManager: mockAddressManager, bloomFilterManager: mockBloomFilterManager,
maxRetriesCount: maxRetriesCount, retriesPeriod: retriesPeriod, totalRetriesPeriod: totalRetriesPeriod)
}
override func tearDown() {
mockRealmFactory = nil
mockTransactionProcessor = nil
mockAddressManager = nil
mockBloomFilterManager = nil
maxRetriesCount = nil
retriesPeriod = nil
totalRetriesPeriod = nil
realm = nil
syncer = nil
super.tearDown()
}
func testPendingTransactions() {
let relayedTransaction = TestData.p2pkhTransaction
let newTransaction = TestData.p2wpkhTransaction
let newSentTransaction = TestData.p2pkTransaction
let sentTransaction = SentTransaction(reversedHashHex: newSentTransaction.reversedHashHex)
relayedTransaction.status = .relayed
newTransaction.status = .new
newSentTransaction.status = .new
sentTransaction.lastSendTime = CACurrentMediaTime() - retriesPeriod - 1
try! realm.write {
realm.add(relayedTransaction)
realm.add(newTransaction)
realm.add(newSentTransaction)
realm.add(sentTransaction)
}
var transactions = syncer.pendingTransactions()
XCTAssertEqual(transactions.count, 2)
XCTAssertEqual(transactions.first!.dataHash, newTransaction.dataHash)
XCTAssertEqual(transactions.last!.dataHash, newSentTransaction.dataHash)
try! realm.write {
realm.delete(newTransaction)
// sentTransaction retriesCount has exceeded
sentTransaction.retriesCount = maxRetriesCount
}
transactions = syncer.pendingTransactions()
XCTAssertEqual(transactions.count, 0)
try! realm.write {
sentTransaction.retriesCount = 0
// sentTransaction retriesPeriod has not elapsed
sentTransaction.lastSendTime = CACurrentMediaTime()
}
transactions = syncer.pendingTransactions()
XCTAssertEqual(transactions.count, 0)
try! realm.write {
sentTransaction.lastSendTime = CACurrentMediaTime() - retriesPeriod - 1
// sentTransaction totalRetriesPeriod has elapsed
sentTransaction.firstSendTime = CACurrentMediaTime() - totalRetriesPeriod - 1
}
transactions = syncer.pendingTransactions()
XCTAssertEqual(transactions.count, 0)
}
func testHandleSentTransaction() {
let transaction = TestData.p2pkhTransaction
transaction.status = .new
try! realm.write {
realm.add(transaction)
}
syncer.handle(sentTransaction: transaction)
let sentTransaction = realm.objects(SentTransaction.self).last!
XCTAssertEqual(sentTransaction.reversedHashHex, transaction.reversedHashHex)
XCTAssertEqual(sentTransaction.retriesCount, 0)
XCTAssertLessThanOrEqual(abs(CACurrentMediaTime() - sentTransaction.firstSendTime), 0.1)
XCTAssertLessThanOrEqual(abs(CACurrentMediaTime() - sentTransaction.lastSendTime), 0.1)
}
func testHandleSentTransaction_SentTransactionExists() {
let transaction = TestData.p2pkhTransaction
transaction.status = .new
let sentTransaction = SentTransaction(reversedHashHex: transaction.reversedHashHex)
sentTransaction.firstSendTime = sentTransaction.firstSendTime - 100
sentTransaction.lastSendTime = sentTransaction.lastSendTime - 100
try! realm.write {
realm.add(transaction)
realm.add(sentTransaction)
}
syncer.handle(sentTransaction: transaction)
XCTAssertEqual(sentTransaction.reversedHashHex, transaction.reversedHashHex)
XCTAssertEqual(sentTransaction.retriesCount, 1)
XCTAssertLessThanOrEqual(abs(CACurrentMediaTime() - sentTransaction.firstSendTime - 100), 0.1)
XCTAssertLessThanOrEqual(abs(CACurrentMediaTime() - sentTransaction.lastSendTime), 0.1)
}
func testHandleSentTransaction_transactionNotExists() {
let transaction = TestData.p2pkhTransaction
transaction.status = .new
syncer.handle(sentTransaction: transaction)
XCTAssertEqual(realm.objects(SentTransaction.self).count, 0)
}
func testHandleSentTransaction_transactionIsNotNew() {
let transaction = TestData.p2pkhTransaction
transaction.status = .relayed
syncer.handle(sentTransaction: transaction)
XCTAssertEqual(realm.objects(SentTransaction.self).count, 0)
}
func testHandle_emptyTransactions() {
syncer.handle(transactions: [])
verify(mockTransactionProcessor, never()).process(transactions: any(), inBlock: any(), skipCheckBloomFilter: any(), realm: any())
verify(mockAddressManager, never()).fillGap()
verify(mockBloomFilterManager, never()).regenerateBloomFilter()
}
func testHandle_NeedToUpdateBloomFilter() {
let transactions = [TestData.p2pkhTransaction]
stub(mockTransactionProcessor) { mock in
when(mock.process(transactions: equal(to: transactions), inBlock: any(), skipCheckBloomFilter: any(), realm: any())).thenThrow(BloomFilterManager.BloomFilterExpired())
}
syncer.handle(transactions: transactions)
verify(mockTransactionProcessor).process(transactions: equal(to: transactions), inBlock: equal(to: nil), skipCheckBloomFilter: equal(to: false), realm: any())
verify(mockAddressManager).fillGap()
verify(mockBloomFilterManager).regenerateBloomFilter()
}
func testHandle_NotNeedToUpdateBloomFilter() {
let transactions = [TestData.p2pkhTransaction]
stub(mockTransactionProcessor) { mock in
when(mock.process(transactions: equal(to: transactions), inBlock: any(), skipCheckBloomFilter: equal(to: false), realm: any())).thenDoNothing()
}
syncer.handle(transactions: transactions)
verify(mockTransactionProcessor).process(transactions: equal(to: transactions), inBlock: equal(to: nil), skipCheckBloomFilter: equal(to: false), realm: any())
verify(mockAddressManager, never()).fillGap()
verify(mockBloomFilterManager, never()).regenerateBloomFilter()
}
func testShouldRequestTransaction_TransactionExists() {
let transaction = TestData.p2wpkhTransaction
try! realm.write {
realm.add(transaction)
}
XCTAssertEqual(syncer.shouldRequestTransaction(hash: transaction.dataHash), false)
}
func testShouldRequestTransaction_TransactionNotExists() {
let transaction = TestData.p2wpkhTransaction
XCTAssertEqual(syncer.shouldRequestTransaction(hash: transaction.dataHash), true)
}
}
|
0 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a
{
class B<T>: b { func a<T.C(f: ([Void{
"\(f: a<U : B<T where T>: a
let f = compose(object1: B<T where T>: S<Int>
class B<T : B<T>
{
|
0 |
public protocol AbstractCollection: Java.Collection where Self: Object {
func size() -> Int32
func iterator<R>() -> R? where R: Java.Iterator, R.E == T
}
public extension AbstractCollection {
func box() -> AbstractCollectionProxy<E> {
AbstractCollectionProxy<E>(self)
}
}
public extension AbstractCollection where Self: Object {
func isEmpty() -> Bool {
self.javaObject.call(method: AbstractCollection__method__3, [])
}
func contains(o: Object?) -> Bool {
self.javaObject.call(method: AbstractCollection__method__4, [o.toJavaParameter()])
}
func toArray() -> [Object?] {
self.javaObject.call(method: AbstractCollection__method__5, [])
}
func toArray<T>(a: [T?]) -> [T?] where T: Object {
self.javaObject.call(method: AbstractCollection__method__6, [a.toJavaParameter()])
}
func add(e: E?) -> Bool {
self.javaObject.call(method: AbstractCollection__method__7, [e.toJavaParameter()])
}
func remove(o: Object?) -> Bool {
self.javaObject.call(method: AbstractCollection__method__8, [o.toJavaParameter()])
}
func containsAll<T0, T1>(c: T1?) -> Bool where T0: Object, T1: Java.Collection, T1.E == T0 {
self.javaObject.call(method: AbstractCollection__method__9, [c.toJavaParameter()])
}
func addAll<T0, T1>(c: T1?) -> Bool where T0: Object, T1: Java.Collection, T1.E == T0 {
self.javaObject.call(method: AbstractCollection__method__10, [c.toJavaParameter()])
}
func removeAll<T0, T1>(c: T1?) -> Bool where T0: Object, T1: Java.Collection, T1.E == T0 {
self.javaObject.call(method: AbstractCollection__method__11, [c.toJavaParameter()])
}
func retainAll<T0, T1>(c: T1?) -> Bool where T0: Object, T1: Java.Collection, T1.E == T0 {
self.javaObject.call(method: AbstractCollection__method__12, [c.toJavaParameter()])
}
func clear() {
self.javaObject.call(method: AbstractCollection__method__13, [])
}
func iterator() -> Java.IteratorProxy<E>? {
self.javaObject.call(method: AbstractCollection__method__1, [])
}
}
open class AbstractCollectionProxy<E: JObjectConvertible>: Object, JInterfaceProxy, AbstractCollection {
public typealias Proto = AbstractCollection
public typealias T = E
override open class var javaClass: JClass {
AbstractCollection__class
}
fileprivate convenience init<P: AbstractCollection>(_ obj: P) where P.E == E {
self.init(obj.toJavaObject()!)
}
open func size() -> Int32 {
self.javaObject.call(method: AbstractCollection__method__2, [])
}
open func iterator<R>() -> R? where R: Java.Iterator, R.E == T {
self.javaObject.call(method: Iterable__method__0, [])
}
}
// ------------------------------------------------------------------------------------
private let AbstractCollection__class = findJavaClass(fqn: "java/util/AbstractCollection")!
private let AbstractCollection__method__1 = AbstractCollection__class.getMethodID(name: "iterator", sig: "()Ljava/util/Iterator;")!
private let AbstractCollection__method__2 = AbstractCollection__class.getMethodID(name: "size", sig: "()I")!
private let AbstractCollection__method__3 = AbstractCollection__class.getMethodID(name: "isEmpty", sig: "()Z")!
private let AbstractCollection__method__4 = AbstractCollection__class.getMethodID(name: "contains", sig: "(Ljava/lang/Object;)Z")!
private let AbstractCollection__method__5 = AbstractCollection__class.getMethodID(name: "toArray", sig: "()[Ljava/lang/Object;")!
private let AbstractCollection__method__6 = AbstractCollection__class.getMethodID(name: "toArray", sig: "([Ljava/lang/Object;)[Ljava/lang/Object;")!
private let AbstractCollection__method__7 = AbstractCollection__class.getMethodID(name: "add", sig: "(Ljava/lang/Object;)Z")!
private let AbstractCollection__method__8 = AbstractCollection__class.getMethodID(name: "remove", sig: "(Ljava/lang/Object;)Z")!
private let AbstractCollection__method__9 = AbstractCollection__class.getMethodID(name: "containsAll", sig: "(Ljava/util/Collection;)Z")!
private let AbstractCollection__method__10 = AbstractCollection__class.getMethodID(name: "addAll", sig: "(Ljava/util/Collection;)Z")!
private let AbstractCollection__method__11 = AbstractCollection__class.getMethodID(name: "removeAll", sig: "(Ljava/util/Collection;)Z")!
private let AbstractCollection__method__12 = AbstractCollection__class.getMethodID(name: "retainAll", sig: "(Ljava/util/Collection;)Z")!
private let AbstractCollection__method__13 = AbstractCollection__class.getMethodID(name: "clear", sig: "()V")!
private let Iterable__method__0 = AbstractCollection__class.getMethodID(name: "iterator", sig: "()Ljava/util/Iterator;")!
|
0 | //
// SearchHistoryViewController.swift
// FlickrSearch
//
// Created by Bhanuja Tirumareddy on 9/13/18.
// Copyright © 2017 Bhanuja. All rights reserved.
//
import UIKit
protocol SearchHistoryViewControllerDelegate: class {
func userDidSelect(searchText: String) -> Void
}
class SearchHistoryViewController: UIViewController {
@IBOutlet weak var searchTableView: UITableView?
weak var delegate: SearchHistoryViewControllerDelegate?
}
extension SearchHistoryViewController {
override func viewDidLoad() {
super.viewDidLoad()
searchTableView?.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 0))
searchTableView?.keyboardDismissMode = .onDrag
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func reloadTableView() -> Void {
searchTableView?.reloadData()
}
}
extension SearchHistoryViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return SearchHistoryManager.history.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath)
cell.textLabel?.text = SearchHistoryManager.history[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.userDidSelect(searchText: SearchHistoryManager.history[indexPath.row])
}
}
|
0 | //
// Coordinator.swift
// StanwoodAnalytics_Example
//
// Created by Ronan on 25/07/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
class Coordinator {
let window: UIWindow
let dataProvider: DataProvider
let actions: Actionable
init(window: UIWindow, actions: Actionable, dataProvider: DataProvider) {
self.window = window
self.actions = actions
self.dataProvider = dataProvider
}
func start() {
if let navigationController = window.rootViewController as? UINavigationController {
let viewController = navigationController.viewControllers.first as! ViewController
FirstScreenWireframe.prepare(viewController: viewController, actions: actions as! FirstScreenActionable)
}
}
func showNextScreen() {
let secondScreenActions = actions as! SecondScreenActionable
let secondScreenViewController = secondScreen(actions: secondScreenActions)
let navigationController = window.rootViewController as! UINavigationController
navigationController.pushViewController(secondScreenViewController, animated: true)
}
func secondScreen(actions: SecondScreenActionable) -> SecondScreenViewController {
let parameters = dataProvider as SecondScreenParameterable
let viewController = SecondWireframe.makeViewController()
SecondWireframe.prepare(viewController: viewController, parameters: parameters, actions: actions)
return viewController
}
}
|
0 | //
// UIImage+Extension.swift
// Flix
//
// Created by Pann Cherry on 4/9/22.
// Copyright © 2022 Pann Cherry. All rights reserved.
//
import UIKit
extension UIImage {
func rounded(radius: CGFloat) -> UIImage {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
draw(in: rect)
return UIGraphicsGetImageFromCurrentImageContext()!
}
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
|
0 | import AppKit
final class ListTransactions : NSObject {
static let shared = ListTransactions()
var entities = [EntityTransactions]()
var ascending = false
var viewContext : NSManagedObjectContext?
override init () {
if let context = mainObjectContext
{
self.viewContext = context
}
}
// delete Transaction
func remove(entity: EntityTransactions)
{
viewContext!.undoManager?.beginUndoGrouping()
viewContext!.undoManager?.setActionName("DeleteTransaction")
viewContext!.delete(entity)
viewContext!.undoManager?.endUndoGrouping()
}
func find(uuid: UUID) -> EntityTransactions
{
let fetchRequest = NSFetchRequest<EntityTransactions>(entityName: "EntityTransactions")
do {
entities = try viewContext!.fetch(fetchRequest)
} catch {
print("Error fetching data from CoreData")
}
if let i = entities.firstIndex(where: {$0.uuid == uuid}) {
return entities[i]
}
return entities.first!
}
func getAllComment() -> [String] {
var comments = [String]()
let entityTransactions = getAllDatas()
for entityTransaction in entityTransactions {
let splitTransactions = entityTransaction.sousOperations?.allObjects as! [EntitySousOperations]
for splitTransaction in splitTransactions {
let comment = splitTransaction.libelle ?? ""
comments.append(comment)
}
}
return comments.uniqueElements
}
func getAllDatas(ascending: Bool = true) -> [EntityTransactions] {
guard currentAccount != nil else { return [] }
self.ascending = ascending
let fetchRequest = NSFetchRequest<EntityTransactions>(entityName: "EntityTransactions")
let predicate = NSPredicate(format: "account == %@", currentAccount!)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "datePointage", ascending: ascending),
NSSortDescriptor(key: "dateOperation", ascending: ascending)]
do {
entities = try viewContext!.fetch(fetchRequest)
} catch {
print("Error fetching data from CoreData")
return []
}
if currentAccount?.isDemo == true {
adjustDate()
}
return entities
}
func adjustDate () {
guard entities.isEmpty == false else {return}
let diffDate = (entities.first?.dateOperation!.timeIntervalSinceNow)!
for entity in entities {
entity.datePointage = (entity.datePointage! - diffDate).noon
entity.dateOperation = (entity.dateOperation! - diffDate).noon
}
currentAccount?.isDemo = false
}
}
public extension Sequence where Element: Equatable {
var uniqueElements: [Element] {
return self.reduce(into: []) {
uniqueElements, element in
if !uniqueElements.contains(element) {
uniqueElements.append(element)
}
}
}
}
// MARK: convert dictionary to class
class GroupedYearOperations : NSObject {
let year : String
var allMonth : [GroupedMonthOperations]
init( dictionary: (key: String, value: [String: [Transaction]])) {
self.year = dictionary.key
self.allMonth = [GroupedMonthOperations]()
let months = (dictionary.value).map { (key: String , value: [Transaction]) -> GroupedMonthOperations in
return GroupedMonthOperations(month : key , Transactions: value)
}
self.allMonth = months.sorted(by: {$0.month > $1.month})
}
}
class GroupedMonthOperations : NSObject {
let month : String
let transactions : [ Transaction ]
init( month: String, Transactions: [Transaction]) {
self.month = month
let idAllOperation = (0 ..< Transactions.count).map { (i) -> Transaction in
return Transaction(year : Transactions[i].year, id: Transactions[i].id, entityTransaction: Transactions[i].entityTransaction)
}
self.transactions = idAllOperation.sorted(by: { $0.entityTransaction.datePointage!.timeIntervalSince1970 > $1.entityTransaction.datePointage!.timeIntervalSince1970 })
}
}
class Transaction : NSObject {
let cb : Bool
let year : String
let id : String
let entityTransaction : EntityTransactions
init( year: String, id: String, entityTransaction: EntityTransactions) {
self.year = year
self.id = id
self.entityTransaction = entityTransaction
let mode = self.entityTransaction.paymentMode?.name
self.cb = mode == Localizations.PaymentMethod.Bank_Card ? true : false
}
}
|
0 |
public protocol P {
static func stat()
}
extension Int: P {
public static func stat() {}
}
public func external_opaque() -> some P {
return 0
}
@inlinable
public func external_inlinable() -> some P {
return 0
}
|
0 | //
// VideoCutter.swift
// VideoSplash
//
// Created by Toygar Dündaralp on 8/3/15.
// Copyright (c) 2015 Toygar Dündaralp. All rights reserved.
//
import UIKit
import AVFoundation
extension String {
var convert: NSString { return (self as NSString) }
}
public class VideoCutter: NSObject {
public func cropVideoWithUrl(videoUrl url: URL, startTime: CGFloat, duration: CGFloat, completion: ((_ videoPath: NSURL?, _ error: NSError?) -> Void)?) {
DispatchQueue.global().async() {
let asset = AVURLAsset(url: url, options: nil)
let exportSession = AVAssetExportSession(asset: asset, presetName: "AVAssetExportPresetHighestQuality")
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
var outputURL = paths.object(at: 0) as! String
let manager = FileManager.default
do {
try manager.createDirectory(atPath: outputURL, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
outputURL = outputURL.convert.appendingPathComponent("output.mp4")
do {
try manager.removeItem(atPath: outputURL)
} catch _ {
}
if let exportSession = exportSession as AVAssetExportSession? {
exportSession.outputURL = NSURL(fileURLWithPath: outputURL) as URL
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputFileType = AVFileType.mp4
let start = CMTimeMakeWithSeconds(Float64(startTime), preferredTimescale: 600)
let duration = CMTimeMakeWithSeconds(Float64(duration), preferredTimescale: 600)
let range = CMTimeRangeMake(start: start, duration: duration)
exportSession.timeRange = range
exportSession.exportAsynchronously { () -> Void in
switch exportSession.status {
case .completed:
completion?(exportSession.outputURL as NSURL?, nil)
case .failed:
print("Failed: \(String(describing: exportSession.error))")
case .cancelled:
print("Failed: \(String(describing: exportSession.error))")
default:
print("default case")
}
}
}
}
}
}
|
0 | //
// BaseTableViewController.swift
// EndlessWork
//
// Created by WangXun on 2018/7/23.
// Copyright © 2018年 WangXun. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import MJRefresh
// MARK: - View Model
/// Table View Controller的View Model基类
class BaseTableViewControllerViewModel: BaseViewControllerViewModel {
// MARK: - Property
// to view
/// 数据源
let dataSource = Variable<[SectionViewModelProtocol]?>(nil)
/// 是否开启下拉刷新
let isEnablePullRefresh = Variable<Bool>(false)
/// 是否开启上拉加载更多
let isEnablePushLoadmore = Variable<Bool>(false)
/// 是否开启编辑Cell
let isEnableEditCell = Variable<Bool>(false)
/// 结束下拉刷新
let callEndPullRefresh = PublishSubject<Void>()
/// 结束上拉更多
let callEndPushLoadMore = PublishSubject<Void>()
/// 刷新table
let callReload = PublishSubject<Void>()
// from view
/// 点击一行
let didSelectRow = PublishSubject<IndexPath>()
/// 提交删除一行
let didCommitDeleteRow = PublishSubject<IndexPath>()
/// 触发了下拉刷新
let didPullRefresh = PublishSubject<Void>()
/// 触发了上拉更多
let didPushLoadMore = PublishSubject<Void>()
// MARK: - Method
override init() {
super.init()
dataSource.asObservable()
.map({ (_) -> Void in })
.bind(to: callReload)
.disposed(by: disposeBag)
}
/// 根据section找到对应的section view model
func fetchSectionViewModel(by section: Int) -> SectionViewModelProtocol? {
return dataSource.value?.ew.element(of: section)
}
/// 根据indexPath找到对应的cell view model
func fetchCellViewModel(by indexPath: IndexPath) -> TableViewCellViewModelProtocol? {
return dataSource.value?.ew.element(of: indexPath.section)?.cellViewModels.ew.element(of: indexPath.row)
}
}
// MARK: - View Controller
/// Table View Controller基类,可以使用MVVM
class BaseTableViewController: BaseViewController {
// MARK: - Property
/// tableview,可以用xib连接,也可以代码创建
@IBOutlet weak var tableView: UITableView?
// MARK: - Public Method
/// 子类重写此方法,来指定cell的viewModel对应的view类型
open func cellClass(from cellViewModel: TableViewCellViewModelProtocol?) -> TableCellCompatible.Type? {
return BaseTableViewCell.self
}
/// 子类重写此方法,来指定section的viewModel对应的header view类型,返回空表示无header
open func sectionHeaderClass(from sectionViewModel: SectionViewModelProtocol?) -> SectionViewCompatible.Type? {
return nil
}
/// 子类重写此方法,来指定section的viewModel对应的footer view类型,返回空表示无footer
open func sectionFooterClass(from sectionViewModel: SectionViewModelProtocol?) -> SectionViewCompatible.Type? {
return nil
}
/// 子类重写此方法,在需要自定义时,返回一个的刷新用的header(当开启下拉刷新时)
open func customRefreshHeaderClass() -> MJRefreshHeader.Type {
return MJRefreshHeader.self
}
/// 子类重写此方法,在需要自定义时,返回一个刷新用的footer(当开启上拉更多时)
open func customRefreshFooterClass() -> MJRefreshFooter.Type {
return MJRefreshFooter.self
}
// MARK: - Life Cycle
override func viewSetup() {
super.viewSetup()
/// table view 初始化
if tableView == nil { // 如果没有通过iboutlet连接,那么创建一个
let aTableView = UITableView(frame: view.bounds, style: .plain)
view.addSubview(aTableView)
aTableView.separatorStyle = .none
aTableView.dataSource = self
aTableView.delegate = self
tableView = aTableView
}
}
override func viewBindViewModel() {
super.viewBindViewModel()
guard let vm = viewModel as? BaseTableViewControllerViewModel else {
return
}
/// 启用下拉刷新
vm.isEnablePullRefresh
.asDriver()
.drive(onNext: { [weak self] (value) in
self?.tableView?.mj_header = value == false ? nil : self?.creatRefreshHeader()
})
.disposed(by: disposeBag)
/// 启用上拉更多
vm.isEnablePushLoadmore
.asDriver()
.drive(onNext: { [weak self] (value) in
self?.tableView?.mj_footer = value == false ? nil : self?.createRefreshFooter()
})
.disposed(by: disposeBag)
/// 结束下拉刷新
vm.callEndPullRefresh
.asDriver(onErrorJustReturn: ())
.drive(onNext: { [weak self] (_) in
self?.tableView?.mj_header.endRefreshing()
})
.disposed(by: disposeBag)
/// 结束上拉更多
vm.callEndPushLoadMore
.asDriver(onErrorJustReturn: ())
.drive(onNext: { [weak self] (_) in
self?.tableView?.mj_footer.endRefreshing()
})
.disposed(by: disposeBag)
/// 刷新
vm.callReload
.asDriver(onErrorJustReturn: ())
.drive(onNext: { [weak self] (_) in
self?.tableView?.reloadData()
})
.disposed(by: disposeBag)
}
// MARK: - Private Method
/// 创建下拉控件
private func creatRefreshHeader() -> MJRefreshHeader? {
let headerView = customRefreshHeaderClass().init(refreshingBlock: { [weak self] in
(self?.viewModel as? BaseTableViewControllerViewModel)?.didPullRefresh.onNext(())
})
return headerView
}
/// 创建上拉卡控件
private func createRefreshFooter() -> MJRefreshFooter? {
let footerView = customRefreshFooterClass().init(refreshingBlock: { [weak self] in
(self?.viewModel as? BaseTableViewControllerViewModel)?.didPushLoadMore.onNext(())
})
return footerView
}
}
// MARK: - TableView DataSource, Delegate
extension BaseTableViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
guard let dataSourceValue = (viewModel as? BaseTableViewControllerViewModel)?.dataSource.value else {
return 0
}
return dataSourceValue.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard var sectionVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchSectionViewModel(by: section) else {
return 0
}
sectionVM.callReloadSection = { [weak tableView] in
tableView?.reloadSections([section], with: .automatic)
}
return sectionVM.cellViewModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard var cellVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchCellViewModel(by: indexPath) else {
return UITableViewCell()
}
guard let cellClass = self.cellClass(from: cellVM) else {
return UITableViewCell()
}
var cell = tableView.dequeueReusableCell(withIdentifier: cellClass.reuseID(with: cellVM))
if cell == nil {
cell = cellClass.createInstance(with: cellVM)
}
(cell as? TableCellCompatible)?.updateView(with: cellVM)
cellVM.callReloadCell = { [weak tableView] in
tableView?.reloadRows(at: [indexPath], with: .automatic)
}
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let cellVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchCellViewModel(by: indexPath) else {
return 0
}
guard let cellClass = self.cellClass(from: cellVM) else {
return 0
}
return cellClass.height(with: cellVM, tableSize: tableView.bounds.size)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
(viewModel as? BaseTableViewControllerViewModel)?.didSelectRow.onNext(indexPath)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sectionVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchSectionViewModel(by: section) else {
return nil
}
guard let sectionHeaderClass = sectionHeaderClass(from: sectionVM) else {
return nil
}
let reuseID = sectionHeaderClass.reuseID(with: sectionVM)
var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseID)
if headerView == nil {
headerView = sectionHeaderClass.createInstance(with: sectionVM)
}
(headerView as? SectionViewCompatible)?.updateView(with: sectionVM)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let sectionVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchSectionViewModel(by: section) else {
return 0
}
guard let sectionHeaderClass = sectionHeaderClass(from: sectionVM) else {
return 0
}
return sectionHeaderClass.height(with: sectionVM, tableSize: tableView.bounds.size)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let sectionVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchSectionViewModel(by: section) else {
return nil
}
guard let sectionFooterClass = sectionFooterClass(from: sectionVM) else {
return nil
}
let reuseID = sectionFooterClass.reuseID(with: sectionVM)
var footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseID)
if footerView == nil {
footerView = sectionFooterClass.createInstance(with: sectionVM)
}
(footerView as? SectionViewCompatible)?.updateView(with: sectionVM)
return footerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let sectionVM = (viewModel as? BaseTableViewControllerViewModel)?.fetchSectionViewModel(by: section) else {
return 0
}
guard let sectionFooterClass = sectionFooterClass(from: sectionVM) else {
return 0
}
return sectionFooterClass.height(with: sectionVM, tableSize: tableView.bounds.size)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return (viewModel as? BaseTableViewControllerViewModel)?.isEnableEditCell.value ?? false
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return (viewModel as? BaseTableViewControllerViewModel)?.isEnableEditCell.value == true ? "删除" : nil
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
(viewModel as? BaseTableViewControllerViewModel)?.didCommitDeleteRow.onNext(indexPath)
}
}
}
|
0 | import VertexGUI
let app = try VertexGUI.Application()
try! app.createWindow(widgetRoot: Root(rootWidget: MainView()))
do {
try app.start()
} catch {
print("an error occurred while running the app:", error)
}
|
0 | //
// BottomView.swift
// Temp
//
// Created by 정유경 on 2020/01/15.
// Copyright © 2020 정유경. All rights reserved.
//
import UIKit
import MobileCoreServices
protocol BottomViewDelegate: class {
func playButtonAction(_ sender: UIButton)
}
protocol BottomViewImagePickerDelegate: class {
func cameraButtonAction()
}
class WalkControl: UIView {
// MARK: UI
let stopButton: UIButton = {
let button = UIButton()
button.tag = 0
button.layer.borderColor = #colorLiteral(red: 0.4474043121, green: 0.7858899112, blue: 0.7191998518, alpha: 1)
button.layer.borderWidth = 8
button.setImage(UIImage(named: "play"), for: .normal)
button.addTarget(self, action: #selector(stopButtonTouched), for: .touchUpInside)
return button
}()
let playButton: UIButton = {
let button = UIButton()
button.tag = 1
button.backgroundColor = #colorLiteral(red: 0.4474043121, green: 0.7858899112, blue: 0.7191998518, alpha: 1)
button.setImage(UIImage(named: "play2"), for: .normal)
button.addTarget(self, action: #selector(playButtonTouched), for: .touchUpInside)
return button
}()
let cameraButton: UIButton = {
let button = UIButton()
button.backgroundColor = #colorLiteral(red: 0.4474043121, green: 0.7858899112, blue: 0.7191998518, alpha: 1)
button.setImage(UIImage(named: "camera2"), for: .normal)
button.addTarget(self, action: #selector(cameraButtonTouched), for: .touchUpInside)
return button
}()
weak var delegate: BottomViewDelegate?
weak var imagePickerDelegate: BottomViewImagePickerDelegate?
// play, pause, stop
enum ButtonStatus: String {
case play, pause2, stop2
}
var currentStatus = ButtonStatus.play {
didSet {
self.stopButton.setImage(UIImage(named: currentStatus.rawValue), for: .normal)
self.stopButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
// MARK: Initialize
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
private func setupUI() {
self.stopButton.layer.cornerRadius = UI.buttonSize / 2
self.playButton.layer.cornerRadius = UI.buttonSize / 4
self.cameraButton.layer.cornerRadius = UI.buttonSize / 4
}
private struct UI {
static let buttonSize: CGFloat = 120
static let spacing: CGFloat = 32
}
func setupConstraints() {
[self.stopButton, self.playButton, self.cameraButton]
.forEach { self.addSubview($0) }
self.stopButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.stopButton.topAnchor.constraint(equalTo: self.topAnchor),
self.stopButton.bottomAnchor.constraint(equalTo: self.bottomAnchor),
self.stopButton.centerXAnchor.constraint(equalTo: self.centerXAnchor),
self.stopButton.widthAnchor.constraint(equalToConstant: UI.buttonSize),
self.stopButton.heightAnchor.constraint(equalToConstant: UI.buttonSize),
])
self.playButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.playButton.trailingAnchor.constraint(equalTo: self.stopButton.leadingAnchor, constant: -UI.spacing),
self.playButton.centerYAnchor.constraint(equalTo: self.stopButton.centerYAnchor),
self.playButton.widthAnchor.constraint(equalToConstant: UI.buttonSize / 2),
self.playButton.heightAnchor.constraint(equalToConstant: UI.buttonSize / 2),
])
self.cameraButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.cameraButton.leadingAnchor.constraint(equalTo: self.stopButton.trailingAnchor, constant: UI.spacing),
self.cameraButton.centerYAnchor.constraint(equalTo: self.stopButton.centerYAnchor),
self.cameraButton.widthAnchor.constraint(equalToConstant: UI.buttonSize / 2),
self.cameraButton.heightAnchor.constraint(equalToConstant: UI.buttonSize / 2),
])
}
// MARK: Actions
@objc func stopButtonTouched(_ sender: UIButton) {
delegate?.playButtonAction(sender)
}
@objc func playButtonTouched(_ sender: UIButton) {
stopButton.setImage(UIImage(named: "pause2"), for: .normal)
delegate?.playButtonAction(sender)
playButton.alpha = 0
}
@objc func cameraButtonTouched(_ sender: UIButton) {
imagePickerDelegate?.cameraButtonAction()
}
func setStatus(status: ButtonStatus) {
switch status {
case .play:
currentStatus = .pause2
case .pause2:
currentStatus = .stop2
case.stop2:
currentStatus = .pause2
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0 | // Copyright (C) 2019 Parrot Drones SAS
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the Parrot Company nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
import Foundation
import GroundSdk
/// Base class for all Manual Copter piloting interface component controller
class ManualPilotingItfController: ActivablePilotingItfController {
/// Constructor
///
/// - Parameter activationController: activation controller that owns this piloting interface controller
init(activationController: PilotingItfActivationController) {
super.init(activationController: activationController, sendsPilotingCommands: true)
}
override func didDisconnect() {
super.didDisconnect()
}
override func requestActivation() {
notifyActive()
}
override func requestDeactivation() {
notifyIdle()
}
func activate() -> Bool {
return droneController.pilotingItfActivationController.activate(pilotingItf: self)
}
}
|
0 | //
// ScanListView.swift
// SwiftUI-BLE-Project
//
// Created by kazuya ito on 2021/02/02.
//
import SwiftUI
struct ScanListView: View {
@EnvironmentObject var bleManager: CoreBluetoothViewModel
var body: some View {
VStack {
NavigationLink("", destination: ScanDetailView(isRootViewActive: $bleManager.isConnected),
isActive: $bleManager.isConnected)
Button(action: {
if bleManager.isSearching {
bleManager.stopScan()
} else {
bleManager.startScan()
}
}) {
UIButtonView(text: bleManager.isSearching ? "スキャンを停止する" : "スキャンを開始する")
}
Text(bleManager.isBlePower ? "" : "Bluetooth設定がOFFです")
.padding(10)
PeripheralCells()
.navigationBarTitle("SwiftUI-BLE")
}
}
struct UIButtonView: View {
var text: String
var body: some View {
Text(text)
.frame(width: 350, height: 50, alignment: .center)
.foregroundColor(Color.blue)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, lineWidth: 2))
}
}
struct PeripheralCells: View {
@EnvironmentObject var bleManager: CoreBluetoothViewModel
var body: some View {
List {
ForEach(0..<bleManager.foundPeripherals.count, id: \.self) { num in
Button(action: {
bleManager.connectPeripheral(bleManager.foundPeripherals[num])
}) {
HStack {
Text("\(bleManager.foundPeripherals[num].name)")
Spacer()
Text("\(bleManager.foundPeripherals[num].rssi) dBm")
}
}
}
}
}
}
}
|
0 | //
// String+Localized.swift
// StripeUICore
//
// Created by Mel Ludowise on 9/16/21.
//
import Foundation
@_spi(STP) import StripeCore
// Localized strings that are used in multiple contexts. Collected here to avoid re-translation
// We use snake case to make long names easier to read.
@_spi(STP) public extension String.Localized {
static var address: String {
STPLocalizedString(
"Address",
"""
Caption for Address field on address form
Section header for address fields
"""
)
}
static var address_line1: String {
STPLocalizedString("Address line 1", "Address line 1 placeholder for billing address form.\nLabel for address line 1 field")
}
static var address_line2: String {
STPLocalizedString("Address line 2", "Label for address line 2 field")
}
static var country_or_region: String {
STPLocalizedString("Country or region", "Country selector and postal code entry form header title\nLabel of an address field")
}
static var country: String {
STPLocalizedString("Country", "Caption for Country field on address form")
}
static var email: String {
STPLocalizedString("Email", "Label for Email field on form")
}
static var name: String {
STPLocalizedString("Name", "Label for Name field on form")
}
static var full_name: String {
STPLocalizedString("Full name", "Label for Full name field on form")
}
static var given_name: String {
STPLocalizedString("First", "Label for first (given) name field")
}
static var family_name: String {
STPLocalizedString("Last", "Label for last (family) name field")
}
static var nameOnAccount: String {
STPLocalizedString("Name on account", "Label for Name on account field on form")
}
static var company: String {
STPLocalizedString("Company", "Label for Company field on form")
}
static var invalid_email: String {
STPLocalizedString("Your email is invalid.", "Error message when email is invalid")
}
static var billing_same_as_shipping: String {
STPLocalizedString("Billing address is same as shipping", "Label for a checkbox that makes customers billing address same as their shipping address")
}
// MARK: - Phone number
static var phone: String {
STPLocalizedString("Phone", "Caption for Phone field on address form")
}
static var incomplete_phone_number: String {
STPLocalizedString("Incomplete phone number", "Error description for incomplete phone number")
}
static var invalid_phone_number: String {
STPLocalizedString("Unable to parse phone number", "Error string when we can't parse a phone number")
}
static var optional_field: String {
STPLocalizedString(
"%@ (optional)",
"The label of a text field that is optional. For example, 'Email (optional)' or 'Name (optional)"
)
}
static var other: String {
STPLocalizedString("Other", "An option in a dropdown selector indicating the customer's desired selection is not in the list. e.g., 'Choose your bank: Bank1, Bank2, Other'")
}
// MARK: City field labels
static var city: String {
STPLocalizedString("City", "Caption for City field on address form")
}
static var district: String {
STPLocalizedString("District", "Label for the district field on an address form")
}
static var suburb: String {
STPLocalizedString("Suburb", "Label of an address field")
}
static var post_town: String {
STPLocalizedString("Town or city", "Label of an address field")
}
static var suburb_or_city: String {
STPLocalizedString("Suburb or city", "Label of an address field")
}
// MARK: Postal code field labels
static var eircode: String {
STPLocalizedString("Eircode", "Label of an address field")
}
static var postal_pin: String {
"PIN" // Intentionally left as-is
}
static var postal_code: String {
STPLocalizedString(
"Postal code",
"""
Label of an address field
Short string for postal code (text used in non-US countries)
"""
)
}
static var zip: String {
STPLocalizedString(
"ZIP",
"""
Label of an address field
Short string for zip code (United States only)
Zip code placeholder US only
"""
)
}
static var your_zip_is_incomplete: String {
STPLocalizedString("Your ZIP is incomplete.", "Error message for when ZIP code in form is incomplete (US only)")
}
static var your_postal_code_is_incomplete: String {
STPLocalizedString("Your postal code is incomplete.", "Error message for when postal code in form is incomplete")
}
// MARK: State field labels
static var area: String {
STPLocalizedString("Area", "Label of an address field")
}
static var county: String {
STPLocalizedString(
"County",
"""
Caption for County field on address form (only countries that use county, like United Kingdom)
Label of an address field
"""
)
}
static var department: String {
STPLocalizedString("Department", "Label of an address field")
}
static var do_si: String {
STPLocalizedString("Do Si", "Label of an address field")
}
static var emirate: String {
STPLocalizedString("Emirate", "Label of an address field")
}
static var island: String {
STPLocalizedString("Island", "Label of an address field")
}
static var oblast: String {
STPLocalizedString("Oblast", "Label of an address field")
}
static var parish: String {
STPLocalizedString("Parish", "Label of an address field")
}
static var prefecture: String {
STPLocalizedString("Prefecture", "Label of an address field")
}
static var province: String {
STPLocalizedString(
"Province",
"""
Caption for Province field on address form (only countries that use province, like Canada)
Label of an address field
"""
)
}
static var state: String {
STPLocalizedString(
"State",
"""
Caption for State field on address form (only countries that use state , like United States)
Label of an address field
"""
)
}
// MARK: - Account
static var accountNumber: String {
STPLocalizedString(
"Account number",
"""
Caption for account number
"""
)
}
static var incompleteBSBEntered: String {
STPLocalizedString(
"The BSB you entered is incomplete.",
"Error string displayed to user when they have entered an incomplete BSB number.")
}
static var removeBankAccountEndingIn: String {
STPLocalizedString(
"Remove bank account ending in %@",
"Content for alert popup prompting to confirm removing a saved bank account. e.g. 'Remove bank account ending in 4242'")
}
static var removeBankAccount: String {
STPLocalizedString(
"Remove bank account",
"Title for confirmation alert to remove a saved bank account payment method")
}
// MARK: - Control strings
static var error: String {
return STPLocalizedString("Error", "Text for error labels")
}
static var cancel: String {
STPLocalizedString("Cancel", "Button title to cancel action in an alert")
}
static var ok: String {
STPLocalizedString("OK", "ok button")
}
static var `continue`: String {
STPLocalizedString("Continue", "Text for continue button")
}
static var remove: String {
STPLocalizedString("Remove", "Button title for confirmation alert to remove a saved payment method")
}
static var useRotorToAccessLinks: String {
STPLocalizedString(
"Use rotor to access links",
"Accessibility hint indicating to use the accessibility rotor to open links. The word 'rotor' should be localized to match Apple's language here: https://support.apple.com/HT204783"
)
}
}
|
0 | import Foundation
final class es_CO: OneOther, PluralizationRule {
let locale: LocaleIdentifier = "es-CO"
}
|
0 | //
// CustomSegmentedControl.swift
// Ripelist
//
// Created by Aaron Williamson on 6/24/15.
// Copyright (c) 2015 Aaron Williamson. All rights reserved.
//
import UIKit
class CustomSegmentedControl: UISegmentedControl {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let _ = touches.first {
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
self.tintColor = UIColor.whiteColor()
}
super.touchesBegan(touches , withEvent:event)
}
} |
0 | //
// Coordinator.swift
// Radiant Tap Essentials
//
// Copyright © 2016 Radiant Tap
// MIT License · http://choosealicense.com/licenses/mit/
//
import UIKit
/*
Coordinators are a design pattern that encourages decoupling view controllers
such that they know as little as possible about how they are presented.
As such, View Controllers should never directly push/pop or present other VCs.
They should not be aware of their existence.
That is Coordinator's job.
Coordinators can be “nested” such that child coordinators encapsulate different flows
and prevent any one of them from becoming too large.
Each coordinator has an identifier to simplify logging and debugging.
Identifier is also used as key for the `childCoordinators` dictionary.
You should never use this class directly (although you can).
Make a proper subclass and add specific behavior for the given particular usage.
Note: Don't overthink this. Idea is to have fairly small number of coordinators in the app.
If you embed controllers into other VC (thus using them as simple UI components),
then keep that flow inside the given container controller.
Expose to Coordinator only those behaviors that cause push/pop/present to bubble up.
*/
/// Main Coordinator instance, where T is UIViewController or any of its subclasses.
open class Coordinator<T: UIViewController>: NSObject, Coordinating {
public let rootViewController: T
/// You need to supply UIViewController (or any of its subclasses) that will be loaded as root of the UI hierarchy.
/// Usually one of container controllers (UINavigationController, UITabBarController etc).
///
/// - parameter rootViewController: UIViewController at the top of the hierarchy.
/// - returns: Coordinator instance, fully prepared but started yet.
///
/// Note: if you override this init, you must call `super`.
public init(rootViewController: T?) {
guard let rvc = rootViewController else {
fatalError("Must supply UIViewController (or any of its subclasses) or override this init and instantiate VC in there.")
}
self.rootViewController = rvc
}
open lazy var identifier: String = {
return String(describing: type(of: self))
}()
// MARK:- Lifecycle
private(set) public var isStarted: Bool = false
/// Tells the coordinator to create/display its initial view controller and take over the user flow.
/// Use this method to configure your `rootViewController` (if it isn't already).
///
/// Some examples:
/// * instantiate and assign `viewControllers` for UINavigationController or UITabBarController
/// * assign itself (Coordinator) as delegate for the shown UIViewController(s)
/// * setup closure entry/exit points
/// etc.
///
/// - Parameter completion: An optional `Callback` executed at the end.
///
/// Note: if you override this method, you must call `super` and pass the `completion` closure.
open func start(with completion: @escaping () -> Void = {}) {
rootViewController.parentCoordinator = self
isStarted = true
completion()
}
/// Tells the coordinator that it is done and that it should
/// clear out its backyard.
///
/// Possible stuff to do here: dismiss presented controller or pop back pushed ones.
///
/// - Parameter completion: Closure to execute at the end.
///
/// Note: if you override this method, you must call `super` and pass the `completion` closure.
open func stop(with completion: @escaping () -> Void = {}) {
rootViewController.parentCoordinator = nil
completion()
}
/// By default, calls `stopChild` on the given Coordinator, passing in the `completion` block.
///
/// (See also comments for this method in the Coordinating protocol)
///
/// Note: if you override this method, you should call `super` and pass the `completion` closure.
open func coordinatorDidFinish(_ coordinator: Coordinating, completion: @escaping () -> Void = {}) {
stopChild(coordinator: coordinator, completion: completion)
}
/// Coordinator can be in memory, but it‘s not currently displaying anything.
/// For example, parentCoordinator started some other Coordinator which then took over root VC to display its VCs,
/// but did not stop this one.
///
/// Parent Coordinator can then re-activate this one, in which case it should take-over the
/// the ownership of the root VC.
///
/// Note: if you override this method, you should call `super`
///
/// By default, it sets itself as `parentCoordinator` for its `rootViewController`.
open func activate() {
rootViewController.parentCoordinator = self
}
// MARK:- Containment
open weak var parent: Coordinating?
/// A dictionary of child Coordinators, where key is Coordinator's identifier property.
/// The only way to add/remove something is through `startChild` / `stopChild` methods.
private(set) public var childCoordinators: [String: Coordinating] = [:]
/**
Adds new child coordinator and starts it.
- Parameter coordinator: The coordinator implementation to start.
- Parameter completion: An optional `Callback` passed to the coordinator's `start()` method.
*/
public func startChild(coordinator: Coordinating, completion: @escaping () -> Void = {}) {
childCoordinators[coordinator.identifier] = coordinator
coordinator.parent = self
coordinator.start(with: completion)
}
/**
Stops the given child coordinator and removes it from the `childCoordinators` array
- Parameter coordinator: The coordinator implementation to stop.
- Parameter completion: An optional `Callback` passed to the coordinator's `stop()` method.
*/
public func stopChild(coordinator: Coordinating, completion: @escaping () -> Void = {}) {
coordinator.parent = nil
coordinator.stop {
[unowned self] in
self.childCoordinators.removeValue(forKey: coordinator.identifier)
completion()
}
}
}
|
0 | // Copyright 2017-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
//
// SecureDatagramSocket.swift
// GoldenGate
//
// Created by Marcel Jackwerth on 12/21/17.
//
import Foundation
import GoldenGateXP
public class SecureDatagramClient {
public struct Options {
public let base: DtlsOptions
public var pskIdentity: NSData
public var psk: NSData
public var ticket: NSData?
public init(base: DtlsOptions, pskIdentity: Data, psk: Data, ticket: Data? = nil) {
self.base = base
self.pskIdentity = pskIdentity as NSData
self.psk = psk as NSData
self.ticket = ticket as NSData?
}
}
// Utility to hold reference to the Swift objects
internal class OptionsContainer {
private var options: Options
internal var gg: UnsafeHeapAllocatedValue<GG_TlsClientOptions>
internal init(options: Options) {
self.options = options
let pskIdentityRef = self.options.pskIdentity.bytes.assumingMemoryBound(to: UInt8.self)
let pskRef = self.options.psk.bytes.assumingMemoryBound(to: UInt8.self)
let ticket = self.options.ticket?.bytes.assumingMemoryBound(to: UInt8.self)
self.gg = UnsafeHeapAllocatedValue(
GG_TlsClientOptions(
base: self.options.base.gg,
psk_identity: pskIdentityRef,
psk_identity_size: self.options.pskIdentity.length,
psk: pskRef,
psk_size: self.options.psk.length,
ticket: ticket,
ticket_size: self.options.ticket?.length ?? 0
)
)
}
internal var ref: UnsafeMutablePointer<GG_TlsClientOptions> {
return gg.pointer
}
}
private init() { }
}
|
0 | //
// widget.swift
// ModuleKit
//
// Created by Serhiy Mytrovtsiy on 10/04/2020.
// Using Swift 5.0.
// Running on macOS 10.15.
//
// Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved.
//
import Cocoa
import os.log
import StatsKit
public enum widget_t: String {
case unknown = ""
case mini = "mini"
case lineChart = "line_chart"
case barChart = "bar_chart"
case pieChart = "pie_chart"
case networkChart = "network_chart"
case speed = "speed"
case battery = "battery"
case sensors = "sensors"
case memory = "memory"
public func new(store: UnsafePointer<Store>, module: String, config: NSDictionary, defaultWidget: widget_t) -> Widget? {
var preview: widget_p? = nil
var item: widget_p? = nil
guard let widgetConfig: NSDictionary = config[self.rawValue] as? NSDictionary else {
return nil
}
switch self {
case .mini:
preview = Mini(title: module, config: widgetConfig, store: store, preview: true)
item = Mini(title: module, config: widgetConfig, store: store, preview: false)
break
case .lineChart:
preview = LineChart(title: module, config: widgetConfig, store: store, preview: true)
item = LineChart(title: module, config: widgetConfig, store: store, preview: false)
break
case .barChart:
preview = BarChart(title: module, config: widgetConfig, store: store, preview: true)
item = BarChart(title: module, config: widgetConfig, store: store, preview: false)
break
case .pieChart:
preview = PieChart(title: module, config: widgetConfig, store: store, preview: true)
item = PieChart(title: module, config: widgetConfig, store: store, preview: false)
break
case .networkChart:
preview = NetworkChart(title: module, config: widgetConfig, store: store, preview: true)
item = NetworkChart(title: module, config: widgetConfig, store: store, preview: false)
break
case .speed:
preview = SpeedWidget(title: module, config: widgetConfig, store: store, preview: true)
item = SpeedWidget(title: module, config: widgetConfig, store: store, preview: false)
break
case .battery:
preview = BatterykWidget(title: module, config: widgetConfig, store: store, preview: true)
item = BatterykWidget(title: module, config: widgetConfig, store: store, preview: false)
break
case .sensors:
preview = SensorsWidget(title: module, config: widgetConfig, store: store, preview: true)
item = SensorsWidget(title: module, config: widgetConfig, store: store, preview: false)
break
case .memory:
preview = MemoryWidget(title: module, config: widgetConfig, store: store, preview: true)
item = MemoryWidget(title: module, config: widgetConfig, store: store, preview: false)
break
default: break
}
if let preview = preview, let item = item {
return Widget(self, defaultWidget: defaultWidget, module: module, preview: preview, item: item)
}
return nil
}
public func name() -> String {
switch self {
case .mini: return LocalizedString("Mini widget")
case .lineChart: return LocalizedString("Line chart widget")
case .barChart: return LocalizedString("Bar chart widget")
case .pieChart: return LocalizedString("Pie chart widget")
case .networkChart: return LocalizedString("Network chart widget")
case .speed: return LocalizedString("Speed widget")
case .battery: return LocalizedString("Battery widget")
case .sensors: return LocalizedString("Text widget")
case .memory: return LocalizedString("Memory widget")
default: return ""
}
}
}
extension widget_t: CaseIterable {}
public protocol widget_p: NSView {
var type: widget_t { get }
var title: String { get }
var widthHandler: ((CGFloat) -> Void)? { get set }
func setValues(_ values: [value_t])
func settings(width: CGFloat) -> NSView
}
open class WidgetWrapper: NSView, widget_p {
public var type: widget_t
public var title: String
public var widthHandler: ((CGFloat) -> Void)? = nil
public init(_ type: widget_t, title: String, frame: NSRect) {
self.type = type
self.title = title
super.init(frame: frame)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setWidth(_ width: CGFloat) {
if self.frame.width == width {
return
}
DispatchQueue.main.async {
self.setFrameSize(NSSize(width: width, height: self.frame.size.height))
}
self.widthHandler?(width)
}
// MARK: - stubs
open func settings(width: CGFloat) -> NSView { return NSView() }
open func setValues(_ values: [value_t]) {}
}
public class Widget {
public let type: widget_t
public let defaultWidget: widget_t
public let module: String
public let preview: widget_p
public let item: widget_p
public var isActive: Bool {
get {
return self.list.contains{ $0 == self.type }
}
set {
if newValue {
self.list.append(self.type)
} else {
self.list.removeAll{ $0 == self.type }
}
}
}
private var config: NSDictionary = NSDictionary()
private var menuBarItem: NSStatusItem? = nil
private let log: OSLog
private var list: [widget_t] {
get {
let string = Store.shared.string(key: "\(self.module)_widget", defaultValue: self.defaultWidget.rawValue)
return string.split(separator: ",").map{ (widget_t(rawValue: String($0)) ?? .unknown)}
}
set {
Store.shared.set(key: "\(self.module)_widget", value: newValue.map{ $0.rawValue }.joined(separator: ","))
}
}
public init(_ type: widget_t, defaultWidget: widget_t, module: String, preview: widget_p, item: widget_p) {
self.type = type
self.module = module
self.preview = preview
self.item = item
self.defaultWidget = defaultWidget
self.log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: self.module)
self.item.widthHandler = { [weak self] value in
if let s = self, let item = s.menuBarItem, item.length != value {
item.length = value
os_log(.debug, log: s.log, "widget %s change width to %.2f", "\(s.type)", value)
}
}
}
// show item in the menu bar
public func enable() {
guard self.isActive else {
return
}
DispatchQueue.main.async(execute: {
self.menuBarItem = NSStatusBar.system.statusItem(withLength: self.item.frame.width)
self.menuBarItem?.autosaveName = "\(self.module)_\(self.type.name())"
self.menuBarItem?.button?.addSubview(self.item)
if let item = self.menuBarItem, !item.isVisible {
self.menuBarItem?.isVisible = true
}
self.menuBarItem?.button?.target = self
self.menuBarItem?.button?.action = #selector(self.togglePopup)
self.menuBarItem?.button?.sendAction(on: [.leftMouseDown, .rightMouseDown])
})
os_log(.debug, log: log, "widget %s enabled", self.type.rawValue)
}
// remove item from the menu bar
public func disable() {
if let item = self.menuBarItem {
NSStatusBar.system.removeStatusItem(item)
}
self.menuBarItem = nil
os_log(.debug, log: log, "widget %s disabled", self.type.rawValue)
}
// toggle the widget
public func toggle() {
self.isActive = !self.isActive
if !self.isActive {
self.disable()
} else {
self.enable()
}
NotificationCenter.default.post(name: .toggleWidget, object: nil, userInfo: ["module": self.module])
}
@objc private func togglePopup(_ sender: Any) {
if let item = self.menuBarItem, let window = item.button?.window {
NotificationCenter.default.post(name: .togglePopup, object: nil, userInfo: [
"module": self.module,
"origin": window.frame.origin,
"center": window.frame.width/2,
])
}
}
}
|
0 | //
// ZHReqManager.swift
// ZHYRXSwiftDemo
//
// Created by 赵宏亚 on 2019/7/29.
// Copyright © 2019 赵宏亚. All rights reserved.
//
import Foundation
import UIKit
import Moya
import Result
import RxSwift
//enum ReqManager {
// // 登录接口
// case Login(loginPlatform: String, mobile: String, password: String)
// // 强制更新
// case CheckUpdate(platformType:String,verCode:NSInteger,verName:String,appName:String)
//}
//
//
//protocol ZHReqType {
// var addXAuth: Bool { get }
//}
//
//let netWorkHudPlugin = NetworkActivityPlugin{ (change) ->() in
// if change == .began{
// isNetWorkVisible(true)
// }else{
// isNetWorkVisible(false)
// }
//}
//
//func isNetWorkVisible(_ isShow:Bool){
//
// UIApplication.shared.isNetworkActivityIndicatorVisible = isShow;
//}
//
//let requestClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<ReqManager>.RequestResultClosure) in
//
// guard var request = try? endpoint.urlRequest() else { return }
//
// request.timeoutInterval = 30
// done(.success(request))
//}
|
0 | //
// AppDelegate.swift
// MiniPlayer
//
// Created by zqayc@example.com on 07/15/2020.
// Copyright (c) 2020 zqayc@example.com. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
|
0 | //
// CourseChoosingServiceTableView.swift
// mala-ios
//
// Created by 王新宇 on 2/18/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
private let CourseChoosingServiceTableViewCellReuseId = "CourseChoosingServiceTableViewCellReuseId"
class CourseChoosingServiceTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
// MARK: - Property
var services: [OtherServiceModel] = MalaOtherService
// MARK: - Constructed
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func configure() {
delegate = self
dataSource = self
bounces = false
separatorColor = UIColor(named: .SeparatorLine)
register(CourseChoosingServiceTableViewCell.self, forCellReuseIdentifier: CourseChoosingServiceTableViewCellReuseId)
}
// MARK: - Delegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return MalaLayout_OtherServiceCellHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 跳转到对应的ViewController
if let type = (services[indexPath.row].viewController) as? UIViewController.Type {
let viewController = type.init()
(viewController as? CouponViewController)?.justShow = false
(viewController as? CouponViewController)?.onlyValid = true
viewController.hidesBottomBarWhenPushed = true
self.viewController()?.navigationController?.pushViewController(viewController, animated: true)
}
}
// MARK: - DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 若非首次购课,不显示第二项[建档测评服务]
return MalaIsHasBeenEvaluatedThisSubject == true ? MalaOtherService.count : (MalaOtherService.count-1)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CourseChoosingServiceTableViewCellReuseId, for: indexPath)
(cell as! CourseChoosingServiceTableViewCell).service = self.services[indexPath.row]
return cell
}
}
// MARK: - CourseChoosingServiceTableViewCell
class CourseChoosingServiceTableViewCell: UITableViewCell {
// MARK: Property
var service: OtherServiceModel? {
didSet{
guard let model = service else { return }
if model.type == .coupon {
configure()
}
self.titleLabel.text = service?.title
if let amount = MalaCurrentCourse.coupon?.amount, amount != 0 {
updateUserInterface()
return
}
switch model.priceHandleType {
case .discount:
self.priceHandleLabel.text = model.price?.priceCNY == nil ? "" : "-"
self.priceLabel.text = model.price?.priceCNY
break
case .reduce:
let oldPrice = String(format: "¥%d", (model.price ?? 0))
let attr = NSMutableAttributedString(string: oldPrice)
attr.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: 1), range: NSMakeRange(0, oldPrice.characters.count))
self.priceHandleLabel.attributedText = attr
self.priceLabel.text = String(format: "¥%d", 0)
break
case .none:
self.priceHandleLabel.text = ""
self.priceLabel.text = L10n.donTUseCoupon
break
}
}
}
private var myContext = 0
private var didAddObserve = false
// MARK: - Components
/// 标题Label
private lazy var titleLabel: UILabel = {
let label = UILabel(
fontSize: 14,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 右箭头标示
private lazy var detailImageView: UIImageView = {
let imageView = UIImageView(imageName: "rightArrow")
return imageView
}()
/// 价格Label
private lazy var priceLabel: UILabel = {
let label = UILabel(
text: "",
fontSize: 14,
textColor: UIColor(named: .ArticleTitle)
)
return label
}()
/// 价格处理Label
private lazy var priceHandleLabel: UILabel = {
let label = UILabel(
text: "",
fontSize: 14,
textColor: UIColor(named: .ArticleTitle)
)
return label
}()
// MARK: - Constructed
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUserInterface()
updateUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
selectionStyle = .none
separatorInset = UIEdgeInsets.zero
layoutMargins = UIEdgeInsets.zero
preservesSuperviewLayoutMargins = false
// Subviews
contentView.addSubview(titleLabel)
contentView.addSubview(detailImageView)
contentView.addSubview(priceLabel)
contentView.addSubview(priceHandleLabel)
// Autolayout
titleLabel.snp.makeConstraints { (maker) -> Void in
maker.left.equalTo(contentView)
maker.height.equalTo(14)
maker.centerY.equalTo(contentView)
}
detailImageView.snp.makeConstraints { (maker) -> Void in
maker.right.equalTo(contentView)
maker.centerY.equalTo(contentView)
}
priceLabel.snp.makeConstraints { (maker) -> Void in
maker.height.equalTo(14)
maker.right.equalTo(detailImageView.snp.left).offset(-6)
maker.centerY.equalTo(contentView)
}
priceHandleLabel.snp.makeConstraints { (maker) -> Void in
maker.height.equalTo(14)
maker.right.equalTo(priceLabel.snp.left).offset(-6)
maker.centerY.equalTo(contentView)
}
}
private func configure() {
MalaCurrentCourse.addObserver(self, forKeyPath: "coupon", options: .new, context: &myContext)
didAddObserve = true
}
// MARK: - Override
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// 选择优惠券时更新UI
updateUserInterface()
}
private func updateUserInterface() {
// 选择优惠券时更新UI
if let title = MalaCurrentCourse.coupon?.name, title == L10n.donTUseCoupon {
self.priceHandleLabel.text = ""
self.priceLabel.text = L10n.donTUseCoupon
}else if let amount = MalaCurrentCourse.coupon?.amount, amount != 0 {
self.priceHandleLabel.text = "-"
self.priceLabel.text = MalaCurrentCourse.coupon?.amount.priceCNY
}else {
self.priceHandleLabel.text = ""
self.priceLabel.text = L10n.donTUseCoupon
}
if let title = MalaCurrentCourse.coupon?.name, title != "" {
self.titleLabel.text = title
}else {
self.titleLabel.text = L10n.coupon
}
}
deinit {
if didAddObserve {
MalaCurrentCourse.removeObserver(self, forKeyPath: "coupon", context: &myContext)
}
}
}
|
0 | import Foundation
enum ConnectionMonitor {
case webSocketChannel(WebSocketChannel)
case signalingChannel(SignalingChannel)
case peerChannel(PeerChannel)
var state: ConnectionState {
get {
switch self {
case .webSocketChannel(let chan):
return chan.state
case .signalingChannel(let chan):
return chan.state
case .peerChannel(let chan):
return ConnectionState(chan.state)
}
}
}
func disconnect() {
let error = SoraError.connectionTimeout
switch self {
case .webSocketChannel(let chan):
chan.disconnect(error: error)
case .signalingChannel(let chan):
// タイムアウトはシグナリングのエラーと考える
chan.disconnect(error: error, reason: .signalingFailure)
case .peerChannel(let chan):
// タイムアウトはシグナリングのエラーと考える
chan.disconnect(error: error, reason: .signalingFailure)
}
}
}
class ConnectionTimer {
public var monitors: [ConnectionMonitor]
public var timeout: Int
public var isRunning: Bool = false
private var timer: Timer?
public init(monitors: [ConnectionMonitor], timeout: Int) {
self.monitors = monitors
self.timeout = timeout
}
public func run(timeout: Int? = nil, handler: @escaping () -> Void) {
if let timeout = timeout {
self.timeout = timeout
}
Logger.debug(type: .connectionTimer,
message: "run (timeout: \(self.timeout) seconds)")
timer = Timer(timeInterval: TimeInterval(self.timeout), repeats: false)
{ timer in
Logger.debug(type: .connectionTimer, message: "validate timeout")
for monitor in self.monitors {
if monitor.state.isConnecting {
Logger.debug(type: .connectionTimer,
message: "found timeout")
for monitor in self.monitors {
if !monitor.state.isDisconnected {
monitor.disconnect()
}
}
handler()
self.stop()
return
}
}
Logger.debug(type: .connectionTimer, message: "all OK")
}
RunLoop.main.add(timer!, forMode: RunLoop.Mode.common)
isRunning = true
}
public func stop() {
Logger.debug(type: .connectionTimer, message: "stop")
timer?.invalidate()
isRunning = false
}
}
|
0 | //
// DictionaryMethods.swift
// DictionaryMethods
//
// Created by Jim Campagno on 12/28/16.
// Copyright © 2016 Jim Campagno. All rights reserved.
//
import Foundation
class DictionaryMethods {
// Questions #1, #2, #3, #6 and #7
var starWarsHeroes:[String] = ["Luke Skywalker", "Princess Leia", "Han Solo", "Rey"]
var starWarsVillains:[String] = ["Darth Vader", "Emperor Palpatine"]
var starWarsDroids:[String] = ["R2-D2", "C-3P0", "IG-88", "BB-8"]
// Question #4
func addKyloRen() {
starWarsVillains.append("Kylo Ren")
}
// Question #5
func remove(droid:String) -> Bool {
let toBeRemoved = starWarsDroids.index(of: droid)
if toBeRemoved == nil {
return false
} else {
starWarsDroids.remove(at: toBeRemoved!)
return true
}
}
// Question #6
var starWarsCharacters:[String : [String]] = [String: [String]]()
func createStarWarsCharacters() {
starWarsCharacters.updateValue(starWarsHeroes, forKey: "Heroes")
starWarsCharacters.updateValue(starWarsVillains, forKey: "Villains")
starWarsCharacters.updateValue(starWarsDroids, forKey: "Droids")
}
// Question #7
var starWarsGangsters:[String] = ["Watto", "Jabba the Hutt"]
func createStarWarsGangsters() {
starWarsCharacters.updateValue(starWarsGangsters, forKey: "Gangsters")
}
// Question #8
func description(characters:[String : [String]]) -> String {
var sentence = "--Star Wars Characters--"
for (type, names) in characters {
sentence += "\n\(type.uppercased())"
for (index, name) in names.enumerated() {
sentence += "\n\(index + 1). \(name)"
}
}
return sentence
}
// Question #9
func addHearts() {
for (type, names) in starWarsCharacters {
var updatedNames = names
for (index, name) in updatedNames.enumerated() {
if name.contains("o") {
let updatedName = name.replacingOccurrences(of: "o", with: "❤️")
updatedNames[index] = updatedName
}
}
starWarsCharacters[type] = updatedNames
}
}
}
|
0 | //
// ADImageSticker.swift
// ADPhotoKit
//
// Created by xu on 2021/7/23.
//
import Foundation
struct ADStickerInfo {
let image: UIImage
let transform: CGAffineTransform
let scale: CGFloat
let center: CGPoint
let sticker: ADTextSticker?
}
class ADImageSticker: ADImageEditTool {
var image: UIImage {
switch style {
case .text:
return Bundle.image(name: "icons_filled_text2", module: .imageEdit) ?? UIImage()
case .image:
return Bundle.image(name: "icons_filled_sticker", module: .imageEdit) ?? UIImage()
}
}
var isSelected: Bool = false
var contentLockStatus: ((Bool) -> Void)?
var toolConfigView: (UIView & ADToolConfigable)?
var toolInteractView: (UIView & ADToolInteractable)?
private var textStkrs: [ADWeakProxy] = []
private var imageStkrs: [ADWeakProxy] = []
func toolDidSelect(ctx: UIViewController?) -> Bool {
switch style {
case .text:
let sticker = ADImageEditConfigurable.textStickerEditVC(sticker: nil)
sticker.textDidEdit = { [weak self] image, sticker in
let content = ADTextStickerContentView(image: image, sticker: sticker)
self?.textStkrs.append(ADWeakProxy(target: content))
ADStickerInteractView.share.addContent(content)
}
sticker.modalPresentationStyle = .custom
sticker.transitioningDelegate = ctx as? UIViewControllerTransitioningDelegate
ctx?.present(sticker, animated: true, completion: nil)
case .image:
let sticker = ADImageEditConfigurable.imageStickerSelectVC()
sticker.imageDidSelect = { [weak self] image in
let content = ADImageStickerContentView(image: image)
self?.imageStkrs.append(ADWeakProxy(target: content))
ADStickerInteractView.share.addContent(content)
}
sticker.modalPresentationStyle = .custom
sticker.transitioningDelegate = ctx as? UIViewControllerTransitioningDelegate
ctx?.present(sticker, animated: true, completion: nil)
}
return false
}
enum Style {
case text
case image
}
let style: Style
init(style: Style) {
self.style = style
toolInteractView = ADStickerInteractView.share
}
var identifier: String {
switch style {
case .text:
return "ADImageSticker-Text"
case .image:
return "ADImageSticker-Image"
}
}
func encode() -> Any? {
switch style {
case .text:
let stkrs: [ADStickerInfo] = textStkrs.compactMap { $0.target }.map { obj in
let content = (obj as! ADTextStickerContentView)
return ADStickerInfo(image: content.image, transform: content.transform, scale: content.scale, center: content.center, sticker: content.sticker)
}
return ["stkrs":stkrs]
case .image:
let stkrs: [ADStickerInfo] = imageStkrs.compactMap { $0.target }.map { obj in
let content = obj as! ADImageStickerContentView
return ADStickerInfo(image: content.image, transform: content.transform, scale: content.scale, center: content.center, sticker: nil)
}
return ["stkrs":stkrs]
}
}
func decode(from: Any) {
if let json = from as? Dictionary<String,Any> {
if let stkrs = json["stkrs"] as? [ADStickerInfo] {
switch style {
case .text:
for item in stkrs {
let content = ADTextStickerContentView(image: item.image, sticker: item.sticker!)
content.transform = item.transform
content.center = item.center
content.scale = item.scale
textStkrs.append(ADWeakProxy(target: content))
ADStickerInteractView.share.appendContent(content)
}
case .image:
for item in stkrs {
let content = ADImageStickerContentView(image: item.image)
content.transform = item.transform
content.center = item.center
content.scale = item.scale
imageStkrs.append(ADWeakProxy(target: content))
ADStickerInteractView.share.appendContent(content)
}
}
}
}
}
}
|
0 | import Foundation
enum ArgumentError: Error {
case BaseUnset
case BaseDoesNotExist
}
struct CLI {
private let options: IcloudoffloadOptions
private let version: String
init(options: IcloudoffloadOptions, version: String) {
self.options = options
self.version = version
}
func run() throws {
if options.version == true {
print("Version " + self.version)
return
}
var baseUrl: URL?
let fileManager = FileManager.default
if options.base == "" {
throw ArgumentError.BaseUnset
} else {
if fileManager.dirExists(atPath: options.base) {
baseUrl = URL(fileURLWithPath: options.base)
} else {
throw ArgumentError.BaseDoesNotExist
}
}
if let safeBaseUrl = baseUrl {
OffloadItems(baseURL: safeBaseUrl, verbose: options.verbose)
}
}
}
|
0 | #!/usr/bin/swift
//
// main.swift
// MakeRepo v0.1.0
//
// Created by Garric Nahapetian on 11/25/16.
// Credit to John Sundell and SwiftPlate: https://github.com/JohnSundell/SwiftPlate
//
import Foundation
// MARK: - Globals
let usrLocalBinPath = "/usr/local/bin"
// MARK: - Functions
func printError(_ message: String) {
print("👮 \(message)")
}
func askForDestinationPath() -> String {
print("💾 Where would you like to save the tool? (Leave empty and hit return to save at path: \(usrLocalBinPath))")
let fileManager = FileManager.default
let path = readLine() ?? ""
guard !path.isEmpty else {
return "\(usrLocalBinPath)"
}
guard fileManager.fileExists(atPath: path) else {
printError("That path doesn't exist. Try again.")
return askForDestinationPath()
}
return path
}
func askForUsername() -> String {
print("👤 What's your GitHub username? (Required: see https://developer.github.com/v3/repos/#create)")
let username = readLine()
guard let _username = username else {
return askForUsername()
}
return _username
}
func askForToken() -> String {
print("🔑 What's your API Token? (GitHub API Token with \"repo\" scope required: see https://developer.github.com/v3/auth/#basic-authentication)")
let token = readLine()
guard let _token = token else {
return askForToken()
}
return _token
}
func shouldProceed() -> Bool {
print("🚦 Proceed? Y (yes) or N (no)?")
let answer = readLine() ?? ""
switch answer.lowercased() {
case "y":
return true
case "n":
return false
default:
printError("Invalid response. Enter either Y, y, N, or n.")
return shouldProceed()
}
}
func performCommand(description: String, command: () throws -> Void) rethrows {
print("👉 \(description)...")
try command()
print("✅ Done")
}
func generateExecutableFromFile(atPath path: String) throws {
let generateExecutableTask = Process()
generateExecutableTask.launchPath = "/bin/bash"
generateExecutableTask.arguments = [
"-c",
"xcrun swiftc \(path)"
]
generateExecutableTask.launch()
generateExecutableTask.waitUntilExit()
}
// MARK: - Program
print("👋🏽 Welcome to the MakeRepo Generator 👋🏽")
print("💥 MakeRepo is a Command Line Tool for easily creating GitHub repos 💥")
print("💪🏽 This Generator will create the MakeRepo tool for you 💪🏽")
let destinationPath = askForDestinationPath() + "/makerepo"
let username = askForUsername()
let token = askForToken()
print("---")
print(" The Generator will now create the tool using the following parameters:")
print("💾 Destination: \(destinationPath)")
print("👤 Username: \(username)")
print("🔑 API Token: \(token)")
print("---")
guard shouldProceed() else {
exit(0)
}
do {
let fileManager = FileManager.default
let currentDirectoryPath = fileManager.currentDirectoryPath
let templatePath = "\(currentDirectoryPath)/template.swift"
let temporaryDirectoryPath = "\(currentDirectoryPath)/temp"
let temporaryFilePath = "\(temporaryDirectoryPath)/_makerepo.swift"
let secondaryFilePath = "\(currentDirectoryPath)/_makerepo.swift"
let executableFilePath = "\(currentDirectoryPath)/_makerepo"
performCommand(description: "Removing any previous temporary directory") {
try? fileManager.removeItem(atPath: temporaryDirectoryPath)
}
try performCommand(description: "Making temporary directory") {
try fileManager.createDirectory(
atPath: temporaryDirectoryPath,
withIntermediateDirectories: false,
attributes: nil
)
}
try performCommand(description: "Copying the template") {
try fileManager.copyItem(atPath: templatePath, toPath: temporaryFilePath)
}
try performCommand(description: "Filling in the template") {
let templateContents = try String(contentsOfFile: temporaryFilePath)
let finalContents = templateContents
.replacingOccurrences(of: "{USERNAME}", with: username)
.replacingOccurrences(of: "{TOKEN}", with: token)
try finalContents.write(
toFile: secondaryFilePath,
atomically: false,
encoding: .utf8
)
}
try performCommand(description: "Generating executable from file") {
try generateExecutableFromFile(atPath: secondaryFilePath)
}
try performCommand(description: "Moving executable to: \(destinationPath)") {
try fileManager.moveItem(
atPath: executableFilePath,
toPath: "\(destinationPath)"
)
}
try performCommand(description: "Removing temporary files and directories") {
try fileManager.removeItem(atPath: temporaryDirectoryPath)
try fileManager.removeItem(atPath: secondaryFilePath)
}
print("🎉 All done 🎉")
if destinationPath == usrLocalBinPath + "/makerepo" {
print("You can now run makerepo from anywhere on the command line to instantly make remote repos on your GitHub!")
} else {
print("You can now run ./makerepo from this directory. To run makerepo from any directory, move makeRepo to path: \(usrLocalBinPath) .")
}
print("You can remove the cloned project now. Enjoy!")
} catch {
printError(error.localizedDescription)
}
|
0 | //
// GraphigViewController.swift
// FirstApp
//
// Created by Emma Barme on 11/09/2015.
// Copyright (c) 2015 Emma Barme. All rights reserved.
//
import UIKit
import Charts
class GraphingViewController: UIViewController {
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var graphView: GraphView!
@IBOutlet weak var chartViewContainer: GraphLineChartViewContainer!
@IBOutlet weak var chartView: GraphLineChartView!
var graphingModel = GraphingModel()
override func viewDidLoad() {
setChartViewProperties()
}
@IBAction func changeValueSlider(sender: UISlider) {
label.text = "\(Int(slider.value))"
}
@IBAction func pushValue() {
graphingModel.addValue(Int(slider.value))
if (graphView.hidden == false)
{
graphView.graphPoints = graphingModel.accessRawData()
graphView.setNeedsDisplay()
}
else if (chartView.hidden == false)
{
setChartView()
}
}
//Redraw graph when rotate
override func viewDidLayoutSubviews() {
graphView.setNeedsDisplay()
}
@IBAction func graphTypeSelection(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
chartViewContainer.hidden = true
graphView.hidden = false
graphView.graphPoints = graphingModel.accessRawData()
graphView.setNeedsDisplay()
case 1:
chartViewContainer.hidden = false
graphView.hidden = true
setChartView()
default:
break;
}
}
func setChartView () {
let data = graphingModel.accessRawData()
var xLabels = [String]()
var values = [Double]()
for i in 0..<data.count {
xLabels.append("")
values.append(Double(data[i]))
}
let chartData = chartView.setChart(xLabels, values: values)
chartView.data = chartData
}
func setChartViewProperties () {
//Set chartView properties
chartViewContainer.hidden = true
chartView.noDataText = "" //Delete the yellow info message that says the data is empty
chartView.backgroundColor = UIColor.clearColor()
chartView.drawGridBackgroundEnabled = false //Delete the ugly grey background
//Axis
chartView.xAxis.labelPosition = .Bottom
chartView.xAxis.axisLineWidth *= 4
chartView.xAxis.axisLineColor = chartView.axisColor
chartView.getAxis(ChartYAxis.AxisDependency.Left).axisLineWidth *= 4
chartView.getAxis(ChartYAxis.AxisDependency.Left).axisLineColor = chartView.axisColor
chartView.getAxis(ChartYAxis.AxisDependency.Left).labelTextColor = chartView.axisColor
chartView.getAxis(ChartYAxis.AxisDependency.Left).labelFont = UIFont.systemFontOfSize(16.0)
chartView.getAxis(ChartYAxis.AxisDependency.Right).axisLineWidth *= 4
chartView.getAxis(ChartYAxis.AxisDependency.Right).axisLineColor = chartView.axisColor
chartView.getAxis(ChartYAxis.AxisDependency.Right).drawLabelsEnabled = false
//No grid lines
chartView.xAxis.drawGridLinesEnabled = false
chartView.getAxis(ChartYAxis.AxisDependency.Right).drawGridLinesEnabled = false
chartView.getAxis(ChartYAxis.AxisDependency.Left).drawGridLinesEnabled = false
//Legends
chartView.legend.setCustom(colors: [UIColor?](), labels: [String?]()) //No legend
chartView.descriptionText = "" //No description text at the bottom right
}
} |
0 | //
// DGMCharacter.swift
// dgmpp
//
// Created by Artem Shimanski on 14.12.2017.
//
import Foundation
import cwrapper
public class DGMImplant: DGMType, Codable {
public convenience init(typeID: DGMTypeID) throws {
guard let type = dgmpp_implant_create(dgmpp_type_id(typeID)) else { throw DGMError.typeNotFound(typeID)}
self.init(type, owned: true)
}
public convenience init(_ other: DGMImplant) {
self.init(dgmpp_implant_copy(other.handle), owned: true)
}
public var slot: Int {
return Int(dgmpp_implant_get_slot(handle))
}
public required init(_ handle: dgmpp_handle, owned: Bool) {
super.init(handle, owned: owned)
}
public convenience required init(from decoder: Decoder) throws {
let typeID = try decoder.container(keyedBy: CodingKeys.self).decode(DGMTypeID.self, forKey: .typeID)
try self.init(typeID: typeID)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(typeID, forKey: .typeID)
}
enum CodingKeys: String, CodingKey {
case typeID
}
}
public class DGMBooster: DGMType, Codable {
public convenience init(typeID: DGMTypeID) throws {
guard let type = dgmpp_booster_create(dgmpp_type_id(typeID)) else { throw DGMError.typeNotFound(typeID)}
self.init(type, owned: true)
}
public convenience init(_ other: DGMBooster) {
self.init(dgmpp_booster_copy(other.handle), owned: true)
}
public var slot: Int {
return Int(dgmpp_booster_get_slot(handle))
}
public required init(_ handle: dgmpp_handle, owned: Bool) {
super.init(handle, owned: owned)
}
public convenience required init(from decoder: Decoder) throws {
let typeID = try decoder.container(keyedBy: CodingKeys.self).decode(DGMTypeID.self, forKey: .typeID)
try self.init(typeID: typeID)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(typeID, forKey: .typeID)
}
enum CodingKeys: String, CodingKey {
case typeID
}
}
public class DGMSkill: DGMType {
public var level: Int {
get {
return Int(dgmpp_skill_get_level(handle))
}
set {
dgmpp_skill_set_level(handle, Int32(newValue))
}
}
}
public class DGMCharacter: DGMType, Codable {
public convenience init() throws {
self.init(dgmpp_character_create()!, owned: true)
}
public convenience init(_ other: DGMCharacter) {
self.init(dgmpp_character_copy(other.handle), owned: true)
}
public var name: String {
get {
return String(cString: dgmpp_character_get_name(handle));
}
set {
guard let string = newValue.cString(using: .utf8) else {return}
dgmpp_character_set_name(handle, string)
}
}
public var ship: DGMShip? {
get {
guard let ship = dgmpp_character_get_ship(handle) else {return nil}
return DGMShip(ship)
}
set {
dgmpp_character_set_ship(handle, newValue?.handle)
}
}
// public var structure: DGMStructure? {
// get {
// guard let structure = dgmpp_character_get_structure(handle) else {return nil}
// return DGMStructure(structure)
// }
// set {
// dgmpp_character_set_structure(handle, newValue?.handle)
// }
// }
public func setSkillLevels(_ level: Int) {
dgmpp_character_set_skill_levels(handle, Int32(level))
}
public func add(_ implant: DGMImplant, replace: Bool = false) throws {
guard dgmpp_character_add_implant_v2(handle, implant.handle, replace ? 1 : 0) != 0 else { throw DGMError.cannotFit(implant)}
}
public func add(_ booster: DGMBooster, replace: Bool = false) throws {
guard dgmpp_character_add_booster_v2(handle, booster.handle, replace ? 1 : 0) != 0 else { throw DGMError.cannotFit(booster)}
}
public func remove(_ implant: DGMImplant) {
dgmpp_character_remove_implant(handle, implant.handle)
}
public func remove(_ booster: DGMBooster) {
dgmpp_character_remove_booster(handle, booster.handle)
}
public var implants: [DGMImplant] {
return DGMArray<DGMImplant>(dgmpp_character_copy_implants(handle)).array
}
public var boosters: [DGMBooster] {
return DGMArray<DGMBooster>(dgmpp_character_copy_boosters(handle)).array
}
public var skills: [DGMSkill] {
return DGMArray<DGMSkill>(dgmpp_character_copy_skills(handle)).array
}
public var droneControlDistance: DGMMeter {
return dgmpp_character_get_drone_control_distance(handle)
}
public required init(_ handle: dgmpp_handle, owned: Bool) {
super.init(handle, owned: owned)
}
public convenience required init(from decoder: Decoder) throws {
try self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.decode([DGMImplant].self, forKey: .implants).forEach { try add($0) }
try container.decode([DGMImplant].self, forKey: .boosters).forEach { try add($0) }
ship = try container.decodeIfPresent(DGMShip.self, forKey: .ship)
if let identifier = try container.decodeIfPresent(Int.self, forKey: .identifier) {
self.identifier = identifier
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(implants, forKey: .implants)
try container.encode(boosters, forKey: .boosters)
try container.encodeIfPresent(ship, forKey: .ship)
try container.encode(identifier, forKey: .identifier)
}
enum CodingKeys: String, CodingKey {
case implants
case boosters
case ship
case identifier
}
}
|
0 | import UIKit
class UITextViewWithoutMenu: UITextView {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
@IBDesignable class UIMongolTextView: UIView {
// FIXME: long load time
// MARK:- Unique to TextView
// ********* Unique to TextView *********
fileprivate var view = UITextViewWithoutMenu()
fileprivate let rotationView = UIView()
fileprivate var userInteractionEnabledForSubviews = true
fileprivate let mongolFontName = "ChimeeWhiteMirrored"
fileprivate let defaultFontSize: CGFloat = 17
fileprivate let mongolTextStorage = MongolTextStorage()
@IBInspectable var text: String {
get {
//return view.text
return mongolTextStorage.unicode
}
set {
mongolTextStorage.unicode = newValue
view.text = mongolTextStorage.render()
//view.text = newValue
}
}
@IBInspectable var fontSize: CGFloat {
get {
if let font = view.font {
return font.pointSize
} else {
return 0.0
}
}
set {
view.font = UIFont(name: mongolFontName, size: newValue)
}
}
@IBInspectable var textColor: UIColor {
get {
if let color = view.textColor {
return color
} else {
return UIColor.black
}
}
set {
view.textColor = newValue
}
}
@IBInspectable var centerText: Bool {
get {
return view.textAlignment == NSTextAlignment.center
}
set {
if newValue {
view.textAlignment = NSTextAlignment.center
}
}
}
@IBInspectable var editable: Bool {
get {
return view.isEditable
}
set {
view.isEditable = newValue
}
}
@IBInspectable var selectable: Bool {
get {
return view.isSelectable
}
set {
view.isSelectable = newValue
}
}
var scrollEnabled: Bool {
get {
return view.isScrollEnabled
}
set {
view.isScrollEnabled = newValue
}
}
var attributedText: NSAttributedString! {
get {
return view.attributedText
}
set {
view.attributedText = newValue
}
}
var contentSize: CGSize {
get {
return CGSize(width: view.contentSize.height, height: view.contentSize.width)
}
set {
view.contentSize = CGSize(width: newValue.height, height: newValue.width)
}
}
var underlyingTextView: UITextViewWithoutMenu {
get {
return view
}
set {
view = newValue
}
}
// TODO: Switch the sides to account for rotation
var textContainerInset: UIEdgeInsets {
get {
return view.textContainerInset
}
set {
view.textContainerInset = newValue
}
}
override var intrinsicContentSize : CGSize {
return CGSize(width: view.frame.height, height: view.frame.width)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
// swap the length and width coming in and going out
let fitSize = view.sizeThatFits(CGSize(width: size.height, height: size.width))
return CGSize(width: fitSize.height, height: fitSize.width)
}
func selectedText() -> String? {
// TODO: this could give error if selected range has emoji
// get the current selected range / cursor position
guard let selection = view.selectedTextRange else {
return nil
}
// get caret or selected range
// "view.selectedRange" may be easier but use method below as a first step for future emoji support
let startGlyphIndex = view.offset(from: view.beginningOfDocument, to: selection.start)
let length = view.offset(from: selection.start, to: selection.end)
let selectedRange = NSRange(location: startGlyphIndex, length: length)
// insert or replace selection with unicode
return mongolTextStorage.unicodeForGlyphRange(selectedRange)
}
func insertMongolText(_ unicode: String) {
// get the current selected range / cursor position
// TODO: this could give error if selected range has emoji
if let selection = view.selectedTextRange {
// get caret or selected range
// "view.selectedRange" may be easier but use method below as a first step for future emoji support
let startGlyphIndex = view.offset(from: view.beginningOfDocument, to: selection.start)
let length = view.offset(from: selection.start, to: selection.end)
let selectedRange = NSRange(location: startGlyphIndex, length: length)
// insert or replace selection with unicode
mongolTextStorage.insertUnicodeForGlyphRange(selectedRange, unicodeToInsert: unicode)
// render unicode again
// FIXME: It is inefficient and unnesessary to render everything
view.text = mongolTextStorage.render()
// set caret position
if let newPosition = view.position(from: view.beginningOfDocument, in: UITextLayoutDirection.right, offset: mongolTextStorage.glyphIndexForCursor) {
view.selectedTextRange = view.textRange(from: newPosition, to: newPosition)
}
}
}
func replaceWordAtCursorWith(_ replacementString: String) {
// get the cursor position
if let cursorRange = view.selectedTextRange {
let cursorPosition = view.offset(from: view.beginningOfDocument, to: cursorRange.start)
mongolTextStorage.replaceWordAtCursorWith(replacementString, atGlyphIndex: cursorPosition)
// render unicode again
// FIXME: It is inefficient and unnesessary to render everything
view.text = mongolTextStorage.render()
// set caret position
if let newPosition = view.position(from: view.beginningOfDocument, in: UITextLayoutDirection.right, offset: mongolTextStorage.glyphIndexForCursor) {
view.selectedTextRange = view.textRange(from: newPosition, to: newPosition)
}
}
}
func deleteBackward() {
// get the current selected range / cursor position
// TODO: this could give error if selected range has emoji
if let selection = view.selectedTextRange {
// get caret or selected range
// "view.selectedRange" may be easier but use method below as a first step for future emoji support
let startGlyphIndex = view.offset(from: view.beginningOfDocument, to: selection.start)
let length = view.offset(from: selection.start, to: selection.end)
let selectedRange = NSRange(location: startGlyphIndex, length: length)
// delete unicode backward
mongolTextStorage.deleteBackwardsAtGlyphRange(selectedRange)
// render unicode again
// FIXME: It is inefficient and unnesessary to render everything
view.text = mongolTextStorage.render()
// set caret position
if let newPosition = view.position(from: view.beginningOfDocument, in: UITextLayoutDirection.right, offset: mongolTextStorage.glyphIndexForCursor) {
view.selectedTextRange = view.textRange(from: newPosition, to: newPosition)
}
}
}
func unicodeCharBeforeCursor() -> String? {
// get the cursor position
if let cursorRange = view.selectedTextRange {
let cursorPosition = view.offset(from: view.beginningOfDocument, to: cursorRange.start)
return mongolTextStorage.unicodeCharBeforeCursor(cursorPosition)
}
return nil
}
func oneMongolWordBeforeCursor() -> String? {
// get the cursor position
if let cursorRange = view.selectedTextRange {
let cursorPosition = view.offset(from: view.beginningOfDocument, to: cursorRange.start)
return mongolTextStorage.unicodeOneWordBeforeCursor(cursorPosition)
}
return nil
}
func twoMongolWordsBeforeCursor() -> (String?, String?) {
// get the cursor position
if let cursorRange = view.selectedTextRange {
let cursorPosition = view.offset(from: view.beginningOfDocument, to: cursorRange.start)
return mongolTextStorage.unicodeTwoWordsBeforeCursor(cursorPosition)
}
return (nil, nil)
}
func setup() {
// 1-10: ᠨᠢᠭᠡ ᠬᠤᠶᠠᠷ ᠭᠤᠷᠪᠠ ᠳᠦᠷᠪᠡ ᠲᠠᠪᠤ ᠵᠢᠷᠭᠤᠭᠠ ᠳᠤᠯᠤᠭᠠ ᠨᠠᠢ᠌ᠮᠠ ᠶᠢᠰᠦ ᠠᠷᠪᠠ
// FIXME: UI related settings should go in LayoutSubviews
//view.backgroundColor = UIColor.yellowColor()
rotationView.isUserInteractionEnabled = userInteractionEnabledForSubviews
self.view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(rotationView)
rotationView.addSubview(view)
// add constraints to pin TextView to rotation view edges.
let leadingConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: rotationView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: rotationView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0)
let topConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: rotationView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: rotationView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
rotationView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
// set font if user didn't specify size in IB
if self.view.font?.fontName != mongolFontName {
view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
rotationView.transform = CGAffineTransform.identity
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.transform = translateRotateFlip()
if self.view.text.isEmpty == false {
self.view.scrollRangeToVisible(NSMakeRange(0, 1))
}
// could do this instead of using constraints
//view.frame = rotationView.bounds
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
|
0 |
import Foundation
class Video: BaseModel {
var dynamic_cover:Cover?
var play_addr_lowbr:Play_url?
var width:Int?
var ratio:String?
var play_addr:Play_url?
var cover:Cover?
var height:Int?
var bit_rate = [Bit_rate]()
var origin_cover:Cover?
var duration:Int?
var download_addr:Download_addr?
var has_watermark:Bool?
}
class Bit_rate: BaseModel {
var bit_rate: Int?
var gear_name: String?
var quality_type: Int?
}
class Download_addr: BaseModel {
var url_list = [String]()
var uri: String?
}
|