hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
09d311a25405b044e0902a9109ad249803b1129c | 2,211 | //
// AppDelegate.swift
// FireStoreHelper
//
// Created by [email protected] on 02/21/2018.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.042553 | 285 | 0.757123 |
dd9a13f139b7eda4732f5b740cd80946e339db7e | 4,761 | //
// GraphViewController.swift
// DataSafer
//
// Created by Fellipe Thufik Costa Gomes Hoashi on 10/1/16.
// Copyright © 2016 Fellipe Thufik Costa Gomes Hoashi. All rights reserved.
//
import UIKit
import VBPieChart
class GraphViewController: UIViewController {
@IBOutlet weak var lblExecutado: UILabel!
@IBOutlet weak var lblExecutando: UILabel!
@IBOutlet weak var lblAgendado: UILabel!
@IBOutlet weak var lblRestaurando: UILabel!
@IBOutlet weak var lblRestaurado: UILabel!
@IBOutlet weak var lblFalha: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.configView()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func configView(){
self.ConfigLabels()
self.configGraph()
self.view.backgroundColor = Cores.appBackgroundColor
}
private func ConfigLabels()
{
lblExecutado.clipsToBounds = true
lblExecutado.layer.cornerRadius = 10
lblExecutando.clipsToBounds = true
lblExecutando.layer.cornerRadius = 10
lblAgendado.clipsToBounds = true
lblAgendado.layer.cornerRadius = 10
lblFalha.clipsToBounds = true
lblFalha.layer.cornerRadius = 10
lblRestaurado.clipsToBounds = true
lblRestaurado.layer.cornerRadius = 10
lblRestaurando.clipsToBounds = true
lblRestaurando.layer.cornerRadius = 10
lblExecutado.backgroundColor = Cores.executado
lblExecutando.backgroundColor = Cores.executando
lblAgendado.backgroundColor = Cores.agendado
lblFalha.backgroundColor = Cores.falha
lblRestaurado.backgroundColor = Cores.restaurado
lblRestaurando.backgroundColor = Cores.restaurando
let status = AppDelegate.token.user!.statusBackups!
lblExecutado.text = percentageValue(status.executado!)
lblExecutando.text = percentageValue(status.executando!)
lblAgendado.text = percentageValue(status.agendado!)
lblFalha.text = percentageValue(status.falha!)
lblRestaurado.text = percentageValue(status.restaurado!)
lblRestaurando.text = percentageValue(status.restaurando!)
}
private func percentageValue(value : Int) -> String
{
let status = AppDelegate.token.user!.statusBackups!
let sum = (status.executado! + status.falha! + status.agendado! + status.executando! + status.restaurado! + status.restaurando!)
let floatSum = Float(sum)
let newValue = Float(value * 100)
let percentage = newValue / floatSum
return String(format: "%.1f%", percentage)
}
private func configGraph()
{
let dictionarie = [
[
"name" : "Executado",
"value" : AppDelegate.token.user!.statusBackups!.executado!,
"color" : Cores.executado
],
[
"name" : "Falha",
"value" : AppDelegate.token.user!.statusBackups!.falha!,
"color" : Cores.falha
],
[
"name" : "Agendado",
"value" : AppDelegate.token.user!.statusBackups!.agendado!,
"color" : Cores.agendado
],
[
"name" : "Executando",
"value" : AppDelegate.token.user!.statusBackups!.executando!,
"color" : Cores.executando
],
[
"name" : "Restaurado",
"value" : AppDelegate.token.user!.statusBackups!.restaurado!,
"color" : Cores.restaurado
],
[
"name" : "Restaurando",
"value" : AppDelegate.token.user!.statusBackups!.restaurando!,
"color" : Cores.restaurando
]
]
let vbpiechart = VBPieChart(frame: CGRect(x: 30, y: 100, width: 250, height: 250))
vbpiechart.holeRadiusPrecent = 0.3
vbpiechart.setChartValues(dictionarie, animation: false)
self.view.addSubview(vbpiechart)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 31.95302 | 136 | 0.599034 |
db9642d6fe2d88b39489f32dd0c8bde10c758b9b | 2,732 | //
// PatternTests.swift
// NESwftTests
//
// Created by HIROTA Ichiro on 2018/11/10.
// Copyright © 2018 HIROTA Ichiro. All rights reserved.
//
import XCTest
@testable import NESwft
class PatternTests: XCTestCase {
func testPat8() {
let data = Data(bytes: [0x41, 0xC2, 0x44, 0x48, 0x10, 0x20, 0x40, 0x80,
0x01, 0x02, 0x04, 0x08, 0x16, 0x21, 0x42, 0x87])
let pat8 = Pat8(data: data)
XCTAssertEqual(pat8[0, 0], 0)
XCTAssertEqual(pat8[1, 0], 1)
XCTAssertEqual(pat8[7, 0], 3)
XCTAssertEqual(pat8[7, 7], 2)
}
func testPat16() {
let bT: [UInt8] = [
1,2,2,2,2,2,2,2,
1,0,0,0,0,0,0,2,
1,0,0,0,0,0,0,2,
1,0,0,0,0,0,0,2,
1,0,0,0,0,0,0,2,
1,0,0,0,0,0,0,2,
1,0,0,0,0,0,0,2,
1,0,0,0,0,0,0,2,
]
let bB: [UInt8] = [
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
3,3,3,3,3,3,3,3,
]
let pT = StubPattern(size: Size(width: 8, height: 8), bytes: bT)
let pB = StubPattern(size: Size(width: 8, height: 8), bytes: bB)
let p = Pat16(top: pT, bottom: pB)
XCTAssertEqual(p[0, 0], 1)
XCTAssertEqual(p[7, 0], 2)
XCTAssertEqual(p[0, 8], 1)
XCTAssertEqual(p[7, 8], 3)
XCTAssertEqual(p[0, 15], 3)
XCTAssertEqual(p[0, 15], 3)
}
func testVFlip() {
let b: [UInt8] = [
1,2,2,2,2,2,2,2,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
0,0,0,0,0,0,0,3,
]
let p = StubPattern(size: Size(width: 8, height: 8), bytes: b)
let v = VFlip(pat: p)
XCTAssertEqual(v[0, 0], 0)
XCTAssertEqual(v[0, 7], 1)
XCTAssertEqual(v[7, 0], 3)
XCTAssertEqual(v[7, 7], 2)
}
func testHFlip() {
let b: [UInt8] = [
1,2,2,2,2,2,2,2,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
1,0,0,0,0,0,0,3,
0,0,0,0,0,0,0,3,
]
let p = StubPattern(size: Size(width: 8, height: 8), bytes: b)
let h = HFlip(pat: p)
XCTAssertEqual(h[0, 0], 2)
XCTAssertEqual(h[0, 7], 3)
XCTAssertEqual(h[7, 0], 1)
XCTAssertEqual(h[7, 7], 0)
}
}
struct StubPattern: Pattern {
var size: Size
var bytes: [UInt8]
subscript(x: Int, y: Int) -> UInt8 { return bytes[y * 8 + x] }
}
| 27.049505 | 80 | 0.456076 |
46e97c7d9f241c70493864fafada71b8298d4ccb | 2,170 | //
// AudioCaptureModel.swift
// MultipeerLiveKit
//
// Created by hayaoMac on 2019/03/11.
// Copyright © 2019年 Takashi Miyazaki. All rights reserved.
//
import AVFoundation
final class AudioCaptureModel: NSObject, AudioOutputDelegate {
private var engine: AVAudioEngine!
private var playerNode: AVAudioPlayerNode!
private var mixerNode: AVAudioMixerNode!
private var nodeBus: AVAudioNodeBus = 0
private var bufferLate: Double = 0.1
private var inputNode: AVAudioInputNode!
private (set) var outputBuffer: AVAudioPCMBuffer!
private let avAudioFormat: AVAudioFormat?
init(avAudioFormat: AVAudioFormat?, nodeBus: AVAudioNodeBus=0, bufferLate: Double=0.1) throws {
self.avAudioFormat = avAudioFormat
super.init()
self.nodeBus = nodeBus
self.bufferLate = bufferLate
try self.engineInit()
}
func audioRecordEnableTo(_ active: Bool) throws {
if active {
installTap()
try engineStart()
} else {
engineStop()
removeTap()
}
}
private func engineInit() throws {
engine = AVAudioEngine()
mixerNode = AVAudioMixerNode()
let mainMixerNode = engine.mainMixerNode
inputNode = engine.inputNode
engine.attach(mixerNode)
engine.connect(mixerNode, to: mainMixerNode, format: avAudioFormat)
engine.connect(inputNode, to: mixerNode, format: avAudioFormat)
}
private func engineStart() throws {
engine.prepare()
try engine.start()
}
private func engineStop() {
engine.stop()
}
private func removeTap() {
mixerNode.removeTap(onBus: nodeBus)
}
private func installTap() {
guard let _avAudioFormat = self.avAudioFormat else {
return
}
let bufferSize = _avAudioFormat.sampleRate * bufferLate
mixerNode.installTap(onBus: nodeBus, bufferSize: AVAudioFrameCount(bufferSize), format: self.avAudioFormat, block: {[weak self](buffer, _) in
self?.outputBuffer = buffer
})
}
deinit {
Log("deinit:\(self.className)")
}
}
| 27.820513 | 149 | 0.645161 |
b9b9f80d09efdd86b93fb97f11c20590da5f29d7 | 1,929 | //
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyright (C) 2004 Sam Hocevar <[email protected]>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
// 0. You just DO WHAT THE FUCK YOU WANT TO.
//
//
// LevelTests.swift
// Tests
//
// Created by Bojan Dimovski on 14.2.18.
//
import XCTest
@testable import Troop
class LevelTests: XCTestCase {
func testValidRawLevels() {
check(.verbose, for: 0)
check(.debug, for: 1)
check(.info, for: 2)
check(.warning, for: 3)
check(.error, for: 4)
}
private func check(_ level: Troop.Level, for rawValue: Int) {
let checkedLevel = Troop.Level(rawValue: rawValue)
XCTAssertNotNil(checkedLevel)
if let checkedLevel = checkedLevel {
XCTAssertEqual(level, checkedLevel)
}
}
func testAllLevelValues() {
let allCases = Troop.Level.allCases
XCTAssertEqual(allCases.count, 5)
}
func testLevelComparison() {
XCTAssertTrue(Troop.Level.debug > Troop.Level.verbose)
XCTAssertFalse(Troop.Level.info > Troop.Level.warning)
XCTAssertTrue(Troop.Level.info >= Troop.Level.debug)
XCTAssertTrue(Troop.Level.verbose <= Troop.Level.warning)
XCTAssertFalse(Troop.Level.warning <= Troop.Level.debug )
}
func testLevelMapping() {
check(.default, for: .verbose)
check(.default, for: .debug)
check(.default, for: .info)
check(.warning, for: .warning)
check(.fault, for: .error)
}
private func check(_ level: MockLevel, for mappedLevel: Troop.Level) {
let checkedLevel = MockLevel(level: mappedLevel)
XCTAssertNotNil(checkedLevel)
if let checkedLevel = checkedLevel {
XCTAssertEqual(level, checkedLevel)
}
}
}
| 25.381579 | 71 | 0.697252 |
756c4930460556b0c8a993ff062f18ce313c50f5 | 1,921 | //
// BackfireApp.swift
// Shared
//
// Created by David Jensenius on 2021-04-07.
//
import SwiftUI
import CoreData
@main
struct BackfireApp: App {
@ObservedObject var boardManager = BLEManager()
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
#if os(iOS)
TabView {
ContentView(boardManager: self.boardManager)
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.tabItem {
Image(systemName: "speedometer")
Text("Dashboard")
}
TripView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.tabItem {
Image(systemName: "map")
Text("Rides")
}
/*
BackfireAppDebug(boardManager: self.boardManager)
.tabItem {
Image(systemName: "printer")
Text("Raw Data")
}
*/
SettingsView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.tabItem {
Image(systemName: "gear")
Text("Settings")
}
}
#else
TripView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.tabItem {
Image(systemName: "map")
Text("Rides")
}
#endif
}
}
}
| 33.12069 | 105 | 0.435711 |
16ec3ef6e11c72a2819792a98929c2a09e5eb5c4 | 689 | //
// Api+Auth.swift
// BoostSDK
//
// Created by Ondrej Rafaj on 01/04/2018.
// Copyright © 2018 LiveUI. All rights reserved.
//
import Foundation
extension Api {
/// Authentication with username and password
public func auth(email: String, password: String) throws -> Promise<Login> {
let data = Login.Request(email: email, password: password)
return try networking.post(path: "auth", object: data)
}
/// Authentication refresh using persistent token
public func auth(token: String) throws -> Promise<Token> {
let data = Token.Request(token: token)
return try networking.post(path: "token", object: data)
}
}
| 25.518519 | 80 | 0.651669 |
9bfabcff1be97a0c14e45f11a1d21c2deb67ac98 | 104 | public enum TokenError: Error {
case invalidHex
case notRegistered
case alreadyRegistered
}
| 17.333333 | 31 | 0.740385 |
236e155b36efde047acdc5aa3eea65757a43325d | 12,020 | //
// SM.swift
// API
//
// Created by Zhang Shengliang on 2018/10/25.
// Copyright © 2018年 Cho. All rights reserved.
//
import Foundation
import UIKit
protocol Api {
var headers:[String:String] { get }
var fullyURL: URL { get }
var baseURL: String { get }
var version: String { get }
var path: String { get }
var parameters: [String: Any] { get }
}
public enum HTTPmethod: String{
case post = "POST"
case get = "GET"
case put = "PUT"
case delete = "DELETE"
}
struct Domain {
#if DEBUG//Sandbox
static let apiDomain = "api-sandbox.sm.com"
static let webDomain = "ss-sandbox.sm.com"
#else
static let apiDomain = "api.sm.com"
static let webDomain = "ss.sm.com"
#endif
}
protocol SMApi {
var method: HTTPmethod { get }
var tokenNeeded: Bool { get }
}
extension SMApi {
var token:(userId: String, appToken: String)? {
return nil
}
var commonHeader: [String: String] {
var headers = [String: String]()
if tokenNeeded, let token = token {
headers["userId"] = token.userId
headers["appToken"] = token.appToken
}
return headers
}
}
enum SoundMoovzApi: Api{
var headers:[String:String] {
var _headers = [String:String]()
let username = "BM"
let password = "PW"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
_headers["Authorization"] = "Basic \(base64LoginString)"
_headers["User-Agent"] = "SoundMoovz/\(Bundle.main.infoDictionary!["CFBundleShortVersionString"]!) (\(UIDevice.current.systemName) \(UIDevice.current.systemVersion);)"
_headers["Accept-Language"] = "\(Locale.current.identifier)"
switch self {
case .live(let live):
live.headers.forEach({ (key, value) in
_headers[key] = value
}) }
return _headers
}
var fullyURL: URL {
return URL(string: "\(baseURL)\(path)")!
}
var version: String {
return "/v1"
}
var path: String {
switch self {
case .live(let l): return l.path
}
}
var parameters: [String: Any] {
switch self {
case .live(let l): return l.params
}
}
// func run<B: Body>(with service: SoundMoovzApiService) -> Observable<(HTTPURLResponse, B)>? {
func run<B: Body>() -> (HTTPURLResponse, B)? {
let smApi: SMApi
switch self {
case .live(let api): smApi = api
}
if smApi.tokenNeeded && smApi.token == nil { return nil }
switch smApi.method {
// case .get: return service.get(api: self)
// case .put: return service.put(api: self)
// case .post: return service.post(api: self)
default: return nil
}
}
var baseURL: String {
return "https://" + Domain.apiDomain + "/api"
}
case live(Live)
enum Live: SMApi
{
case start
case finish(liveId: String)
case message(liveId: String, message: String)
var path: String {
let base = "/lives"
switch self {
case .start: return base
case .finish(let liveId): return base + "/\(liveId)/finish"
case .message(let liveId, _): return base + "/\(liveId)/message"
}
}
var method: HTTPmethod {
switch self {
case .start: return .post
case .finish: return .put
case .message: return .post
}
}
var tokenNeeded: Bool {
switch self {
case .start, .finish, .message:
return true
default:
return false
}
}
var params:[String: Any] {
var params = [String: Any]()
switch self {
case .message(_, let message):
params["message"] = message
default:
break
}
return params
}
var headers:[String: String] {
return commonHeader
}
}
}
class Body//: Mappable
{
var status:ApiStatus.Status200?
var message:String?
var finishAt:Date?
var url:URL?
var date:Int64?
// required init?(map: Map) {}
// func mapping(map: Map)
// {
// status <- (map["status"], EnumTransform<ApiStatus.Status200>())
// message <- map["message"]
// finishAt <- map["finishAt"]
// url <- (map["url"], URLTransform())
// date <- map["date"]
// }
}
class Live:Body
{
var liveId:String?
var streamPath:String?
var start:Date?
// override func mapping(map: Map)
// {
// super.mapping(map: map)
//
// liveId <- map["liveId"]
// streamPath <- map["streamPath"]
// start <- map["start"]
// }
}
enum ApiStatus{
enum Status200:String{
case OK = "ok"
case InMaintenance = "In Maintenance"
case UpdateRequired = "Update Required"
case UpdateNotify = "Update Notify"
func toNSError() -> NSError{
return NSError(domain: "", code: 200, userInfo: [NSLocalizedDescriptionKey:self.rawValue])
}
}
case NoError
case Success_200(status:Status200?)
case AuthorizationRequired_401
case NotFound_404
case Unavailable_503
case StandardError(resp:HTTPURLResponse)
case UnknownError_999
init(code:Int){
switch code {
case 0: self = .NoError
case 200: self = .Success_200(status: nil)
case 401: self = .AuthorizationRequired_401
case 404: self = .NotFound_404
case 503: self = .Unavailable_503
default: self = .UnknownError_999
}
}
var code:Int{
switch self {
case .NoError:
return 0
case .Success_200:
return 200
case .AuthorizationRequired_401:
return 401
case .NotFound_404:
return 404
case .Unavailable_503:
return 503
case .StandardError(let resp):
return resp.statusCode
case .UnknownError_999:
return 999
}
}
var message:String{
switch self {
case .NoError:
return "no error"
case .Success_200:
return "success"
case .AuthorizationRequired_401:
return "Authorization required"
case .NotFound_404:
return "ErrorMsgKey.NotFound"
case .Unavailable_503:
return "Server temporary unavailable."
case .StandardError(let resp):
return "response status \(resp.statusCode)"
case .UnknownError_999:
return "ErrorMsgKey.Unknown"
}
}
func toNSError() -> NSError{
switch self {
case .Success_200(let status):
if let _s = status {
return _s.toNSError()
}
default:
break;
}
return NSError(domain: "", code: self.code, userInfo: [NSLocalizedDescriptionKey:self.message])
}
}
class SoundMoovzApiService
{
/*
private(set) var error:Variable<ApiStatus> = Variable(ApiStatus.NoError)
static private var isShowingAlert:Variable<Bool> = Variable(false)
private let db = DisposeBag()
init(){
error.asObservable()
.subscribe(onNext:{ (apistatus:ApiStatus) in
switch apistatus {
case .UnknownError_999:
SoundMoovzApiService.showAlertError(title: "Global.Error".localized, message: "Global.NetworkUnable".localized)
default:
break
}
})
.addDisposableTo(db)
}
func baseBehavior<B: Body>(apiService:Observable<(HTTPURLResponse, B)>) -> Observable<(HTTPURLResponse, B)>{
return Observable.create({ (obs) -> Disposable in
return apiService
.subscribe(onNext: { [unowned self](resp, body) in
guard (200..<300) ~= resp.statusCode else{
let error = ApiStatus(code: resp.statusCode)
if case .AuthorizationRequired_401 = error, (resp.url?.absoluteString ?? "").hasPrefix(SoundMoovzApi.soundshare(ss: .base).baseURL) {
// SoudShareAPI401エラーの場合、強制ログアウトする
self.error.value = error
AccountManager.shared.logout(confirm: false)
} else {
self.error.value = ApiStatus.StandardError(resp: resp)
if let message = body.message {
SoundMoovzApiService.showAlertError(title: "Global.Error".localized, message: message.localized)
}
}
obs.onError(self.error.value.toNSError())
return
}
if let status = body.status, status != .OK {
// update required
if status == .UpdateRequired{
if let path = body.url {
PopUp.shared.showUpdateAlert(status: ServerStatus.UpdateRequired,
msg: body.message ?? status.rawValue,
path: path.absoluteString,
targetVC: UIApplication.topViewController())
}
}
self.error.value = ApiStatus.Success_200(status: status)
obs.onError(status.toNSError())
}
// success
obs.onNext((resp, body))
obs.onCompleted()
}, onError: { [unowned self](err:Error) in
LOG("api error \(err)")
var apistatus = ApiStatus.UnknownError_999
if let aferror = err as? Alamofire.AFError {
switch aferror {
case .responseSerializationFailed(reason: .inputDataNilOrZeroLength):
// ignore
apistatus = ApiStatus.NoError
default:
break
}
}
self.error.value = apistatus
obs.onError(apistatus.toNSError())
})
})
}
func get<B: Body>(api:SoundMoovzApi) -> Observable<(HTTPURLResponse, B)>{
LOG("api get \(api.fullyURL.absoluteString) \(api.parameters.description)")
let _api = api as Api
return baseBehavior(apiService: ApiService.get(api: _api))
}
*/
}
| 29.245742 | 175 | 0.481115 |
3840db3bb3385af8ede281233e299002171aa935 | 2,852 | //
// SCMoreViewController.swift
// CardsHelper
//
// Created by Stephen Cao on 18/6/19.
// Copyright © 2019 Stephencao Cao. All rights reserved.
//
import UIKit
private let reuseIdentifier = "more_cell"
private let appId = "1472094123"
private let emailAddress = "[email protected]"
class SCMoreViewController: UIViewController {
private let titleInfoArray = [
["title": "Rate us on the App Store", "iconName": "btn_rate","content":"We'd love to hear your feedback, whether you've got ideas on how we can improve - and would really appreciate it if you rate us on the App Store."],
["title": "Contact us", "iconName": "btn_email","content":"You can email us if you have any comments, suggestions or even ideas.\nYour opinion is very important to us."],
["title": "Fork us on GitHub", "iconName": "btn_fork", "content":"This is a free and open source application.\nIf you are interested in this app and want to make it become better, contact us to know more."],
["title": "About", "iconName": "btn_about", "content": "Produced by: Rui Cao\nVersion: v1.0.2\nCopyright © 2019 Rui Cao. All rights reserved."]]
private let tableView = UITableView(frame: UIScreen.main.bounds)
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
private extension SCMoreViewController{
func setupUI(){
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.rowHeight = 110
tableView.register(UINib(nibName: "SCMoreTableViewCell", bundle: nil), forCellReuseIdentifier: reuseIdentifier)
tableView.backgroundColor = .clear
}
}
extension SCMoreViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleInfoArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! SCMoreTableViewCell
cell.content = titleInfoArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
guard let url = URL(string: "itms-apps://itunes.apple.com/app/" + appId) else{
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
case 1:
guard let url = URL(string: "mailto:\(emailAddress)") else{
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
default:
break
}
}
}
| 42.567164 | 228 | 0.669004 |
e2186c3e65ea506f1f6a64aa26756fa8c1d75194 | 1,229 | //
// CategoryBook.swift
// RecipeAssistant
//
// Created by phuong vb on 11/16/21.
// Copyright © 2021 Apple. All rights reserved.
//
import Foundation
import Intents
struct CategoryModel: Decodable {
let identifier: String
let displayString: String
let dishes: [DishModel]?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = try container.decode(String.self, forKey: .identifier)
displayString = try container.decode(String.self, forKey: .displayString)
dishes = try container.decodeIfPresent(Array<DishModel>.self, forKey: .dishes)
}
enum CodingKeys: String, CodingKey {
case identifier = "id"
case displayString = "name"
case dishes = "items"
}
var category: Category {
let intentModel = Category(identifier: identifier, display: displayString)
intentModel.dishes = dishes?.map { $0.dish }
return intentModel
}
}
extension Category: CaseIterable {
public typealias AllCases = [Category]
public static var allCases: [Category] {
(JsonLoader.load(fileName: "restaurants") as [CategoryModel]).map { $0.category }
}
}
| 27.311111 | 89 | 0.672091 |
f776eaa34c53ff17c2c6f01bb6227aa3d2aa8052 | 2,587 | //
// RandomQuestionStrategy.swift
// RabbleWabble
//
// Created by 근성가이 on 2019/10/27.
// Copyright © 2019 근성가이. All rights reserved.
//
import GameplayKit.GKRandomSource
//Ramdom을 직접 구현할 수 있지만, 이미 작성된 로직을 가져와 쓸 수 있다.
//GameplayKit.GKRandomSource는 크기가 매우 작고 범위를 지정할 수 있기 때문에 효율이 좋다.
//public class RandomQuestionStrategy: QuestionStrategy { //QuestionStrategy 구현
// //RandomQuestionStrategy는 임의의 순대대로 question이 표시된다.
// //MARK: - Properties
// public var correctCount: Int = 0
// public var incorrectCount: Int = 0
// private let questionGroup: QuestionGroup
// private var questionIndex = 0
// private let questions: [Question]
//
// //MARK: - Object Lifecycle
// public init(questionGroup: QuestionGroup) {
// self.questionGroup = questionGroup
//
// let randomSource = GKRandomSource.sharedRandom() //Singleton
// self.questions = randomSource.arrayByShufflingObjects(in: questionGroup.questions) as! [Question]
// //arrayByShufflingObjects 메서드는 배열을 인자로 받아, 임의의 순서로 섞는다.
// //NSArray를 반환하기 때문에 캐스팅 해 준다.
// }
//
// //MARK: - QuestionStrategy
// public var title: String {
// return questionGroup.title
// }
//
// public func currentQuestion() -> Question {
// return questions[questionIndex]
// }
//
// public func advanceToNextQuestion() -> Bool {
// guard questionIndex + 1 < questions.count else {
// return false
// }
//
// questionIndex += 1
//
// return true
// }
//
// public func markQuestionCorrect(_ question: Question) {
// correctCount += 1
// }
//
// public func markQuestionIncorrect(_ question: Question) {
// incorrectCount += 1
// }
//
// public func questionIndexTitle() -> String {
// return "\(questionIndex + 1)/\(questions.count)"
// }
//}
//Memento Pattern을 구현하면서 공통의 로직은 BaseQuestionStrategy로 이동한다.
public class RandomQuestionStrategy: BaseQuestionStrategy {
public convenience init(questionGroupCaretaker: QuestionGroupCaretaker) {
let questionGroup = questionGroupCaretaker.selectedQuestionGroup!
let randomSource = GKRandomSource.sharedRandom()
let questions = randomSource.arrayByShufflingObjects(in: questionGroup.questions) as! [Question]
//arrayByShufflingObjects 메서드는 배열을 인자로 받아, 임의의 순서로 섞는다.
//NSArray를 반환하기 때문에 캐스팅 해 준다.
self.init(questionGroupCaretaker: questionGroupCaretaker, questions: questions)
//임의의 순서대로 questions를 전달한다.
}
}
//논리의 대부분이 BaseQuestionStrategy에서 처리되므로 코드가 훨씬 짧아진다.
| 31.168675 | 107 | 0.666409 |
bf72d7fa6634c1450d1327b10933c16030130615 | 2,221 | //
// SystemKeyboardSpaceButton.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-01-10.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This view mimics the system space button, which starts with
displaying the `localeText`, then fading to the `spaceText`.
If you don't provide a `localeText`, this view will use the
context's current locale. If you don't provide a `spaceText`,
it will use the localized `KKL10n.space` text.
Provide empty strings if you don't want to display any text.
This view creates a `SystemKeyboardSpaceButtonContent` then
applies a keyboard button style and gestures to it.
*/
public struct SystemKeyboardSpaceButton: View {
public init(
localeText: String? = nil,
spaceText: String? = nil,
actionHandler: KeyboardActionHandler,
appearance: KeyboardAppearance) {
self.actionHandler = actionHandler
self.appearance = appearance
self.content = SystemKeyboardSpaceButtonContent(
localeText: localeText,
spaceText: spaceText ?? KKL10n.space.text(for: context),
appearance: appearance)
}
private var content: SystemKeyboardSpaceButtonContent
private let actionHandler: KeyboardActionHandler
private let appearance: KeyboardAppearance
private var action: KeyboardAction { .space }
@State private var isPressed = false
@EnvironmentObject private var context: KeyboardContext
public var body: some View {
content
.systemKeyboardButtonStyle(
appearance.systemKeyboardButtonStyle(for: action, isPressed: isPressed))
.keyboardGestures(
for: action,
context: context,
isPressed: $isPressed,
actionHandler: actionHandler)
}
}
struct SystemKeyboardSpaceButton_Previews: PreviewProvider {
static let actionHandler = PreviewKeyboardActionHandler()
static let appearance = PreviewKeyboardAppearance()
static var previews: some View {
SystemKeyboardSpaceButton(actionHandler: actionHandler, appearance: appearance)
.keyboardPreview()
}
}
| 31.728571 | 88 | 0.685727 |
38a53fbedb66f51236486491400f3a5e0eb0149f | 7,010 | //
// ETMultiColumnView.swift
// ETMultiColumnView
//
// Created by Jan Čislinský on 20/01/2017.
//
//
import UIKit
public protocol MultiColumnConfigurable {
init(with config: ETMultiColumnView.Configuration)
func customize(with config: ETMultiColumnView.Configuration) throws
static func identifier(with config: ETMultiColumnView.Configuration) -> String
static func height(with config: ETMultiColumnView.Configuration, width: CGFloat) throws -> CGFloat
}
/// Configurable multi-column view
public final class ETMultiColumnView: UIView, MultiColumnConfigurable {
// MARK: - Variables
// MARK: private
/// Cell configuration structure
fileprivate var config: Configuration
fileprivate let borderLayer: CALayer
fileprivate let path = UIBezierPath()
// MARK: - Initialization
/// The only ETMultiColumnView constructor.
/// There is set up reuseIdentifier for given content. Subviews are createdl.
public init(with config: Configuration) {
self.config = config
borderLayer = CALayer()
super.init(frame: .zero)
setupSubviews()
layer.addSublayer(borderLayer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Content
// MARK: - private
/// Setup subviews based on current configuration.
fileprivate func setupSubviews() {
config.columns.forEach { columnConfig in
addSubview(columnConfig.viewProvider.make())
borderLayer.addSublayer(CAShapeLayer())
}
}
/// Customize columns with content from current configuration.
fileprivate func customizeColumns() throws {
let subviewsCount = subviews.count
var lastRightEdge: CGFloat = 0.0
let columnsWithSizes = try config.columnsWithSizes(in: frame.size.width)
let maxHeight = columnsWithSizes.maxHeight
borderLayer.frame = bounds
for (offset, columnWrapper) in columnsWithSizes.enumerated() {
guard offset < subviewsCount else { return }
let subview = subviews[offset]
subview.frame = makeFrame(for: columnWrapper, x: lastRightEdge, maxHeight: maxHeight)
config.columns[offset].viewProvider.customize(view: subview)
adjustBorder(on: borderLayer, at: offset, x: lastRightEdge, columnWrapper)
lastRightEdge += columnWrapper.size.width
}
// Adjusts height of view accrding maxHeight
frame = CGRect(origin: frame.origin, size: CGSize(width: frame.width, height: maxHeight))
}
fileprivate func makeFrame(for columnWrapper: ETMultiColumnView.Configuration.ColumnWrapper, x: CGFloat, maxHeight: CGFloat) -> CGRect {
let edgeInsets = columnWrapper.edges.insets
let columnWidth = columnWrapper.size.width
let inWidth = columnWidth - edgeInsets.horizontal
let inHeight = columnWrapper.size.height - edgeInsets.vertical
let contentSize = CGSize(width: inWidth, height: inHeight)
let top: CGFloat
switch columnWrapper.alignment {
case .bottom:
top = maxHeight - contentSize.height - edgeInsets.bottom
case .middle:
top = (maxHeight - contentSize.height)/2.0
case .top:
top = edgeInsets.top
}
return CGRect(origin: CGPoint(x: x + edgeInsets.left, y: top), size: contentSize).integral
}
fileprivate func adjustBorder(on border: CALayer, at idx: Int, x: CGFloat, _ wrapper: ETMultiColumnView.Configuration.ColumnWrapper) {
let layer = border.sublayers?[idx]
let columnSize = CGSize(width: wrapper.size.width, height: frame.height)
layer?.frame = CGRect(origin: CGPoint(x: x, y: 0), size: columnSize)
if wrapper.borders.isEmpty {
hideBorders(column: layer)
}
wrapper.borders.forEach {
switch $0 {
case let .left(width: borderWidth, color: borderColor):
showLeftBorder(column: layer, width: borderWidth, color: borderColor)
}
}
}
/// Will show left border with given properties (color, width)
///
/// - Parameters:
/// - layer: expects CAShapeLayer
/// - width: border width
/// - color: border color
fileprivate func showLeftBorder(column layer: CALayer?, width: CGFloat, color: UIColor) {
guard let sublayer = layer as? CAShapeLayer else { return }
path.removeAllPoints()
path.move(to: .zero)
path.addLine(to: CGPoint(x: 0, y: frame.height))
sublayer.path = path.cgPath
sublayer.strokeColor = color.cgColor
sublayer.lineWidth = width
}
fileprivate func hideBorders(column layer: CALayer?) {
guard let sublayer = layer as? CAShapeLayer else { return }
sublayer.path = nil
}
// MARK: - Actions
// MARK: public
/// Customize cell with content. When layout missmatch configurations occurs, Error is thrown.
///
/// - Parameter config: cell configuration
/// - Throws: `ETMultiColumnViewError.columnsCountMissmatch`, `ETMultiColumnViewError.heighMissmatch`
public func customize(with config: Configuration) throws {
guard self.config.columns.count == config.columns.count else {
let errorDescription = "expected: \(self.config.columns.count) columns, got: \(config.columns.count) columns"
throw ETMultiColumnView.Error.columnsCountMissmatch(description: errorDescription)
}
// Updates local config
self.config = config
// Adjusts background
backgroundColor = config.backgroundColor
// Customizes content according new configuration
try customizeColumns()
}
}
// MARK: - Static
public extension ETMultiColumnView {
/// Returns unique identifier for given configuration
///
/// - Parameter config: cell configuration
/// - Returns: unique string - hash from cell configuaration layout parameters
static func identifier(with config: ETMultiColumnView.Configuration) -> String {
let cellId = NSStringFromClass(ETMultiColumnView.self)
let columnsId = config.columns.reduce("") { return $0 + $1.viewProvider.reuseId }
return cellId + columnsId
}
/// Returns height of cell for given configuration
///
/// - Parameter config: cell configuration
/// - Returns: height of cell for given configuration
static func height(with config: ETMultiColumnView.Configuration, width: CGFloat) throws -> CGFloat {
let columnsWithSizes = try config.columnsWithSizes(in: width)
return columnsWithSizes.maxHeight
}
}
// MARK: - Helpers
private extension Collection where Iterator.Element == ETMultiColumnView.Configuration.ColumnWrapper {
var maxHeight: CGFloat {
return self.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0.0
}
}
| 35.226131 | 140 | 0.666904 |
695a6fc14600ce99a186d0e9f7d726edd76349d6 | 648 | //
// MySumallyViewModel.swift
// PracticeApp
//
// Created by Atsushi Miyake on 2018/09/09.
// Copyright © 2018年 Atsushi Miyake. All rights reserved.
//
import Foundation
import RxSwift
import Connectable
final class MySumallyViewModel: Connectable {}
extension OutputSpace where Definer: MySumallyViewModel {
var updateMySumallies: Observable<[MySumallySectionModel]> {
return Observable.just(ItemCollectionCell.CellType.allCases)
.map { $0.map(MySumallySectionItem.normalItem) }
.map(MySumallySectionModel.normalSection)
.map { [$0] }
.share(replay: 1, scope: .forever)
}
}
| 27 | 68 | 0.697531 |
5dd906ad5eed2763f9214141769ea97823781a7e | 343 | //
// GenderizerAPI.swift
// Example
//
// Created by Lukasz Szarkowicz on 10/09/2021.
// Copyright © 2021 Mobilee. All rights reserved.
//
import Foundation
import Netify
class GenderizerAPI: API {
var baseURL: String = "https://api.genderize.io"
var apiHeaders: HTTPHeaders? = nil
var modifiers: [RequestModifier]? = nil
}
| 20.176471 | 52 | 0.693878 |
e5eec1e8678bc439b7fba67cff8c3a38f3f63e13 | 8,100 | //
// ViewController.swift
// memory-card
//
// Created by 陈国民 on 2018/12/2.
// Copyright © 2018 陈国民. All rights reserved.
//
import UIKit
import pop
fileprivate let sizePercent: CGFloat = 0.1
class ViewController: UIViewController {
var currentIndex: Int = 0
var initialLocation: CGFloat = 0
var cardViews = [UIView]()
override func viewDidLoad() {
super.viewDidLoad()
showCardZone()
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(recognizer:)))
self.view.addGestureRecognizer(recognizer)
}
@objc func handleGesture(recognizer: UIPanGestureRecognizer) {
let location = recognizer.location(in: self.view)
if recognizer.state == .began {
self.initialLocation = location.x
let cardView = createCardView()
cardView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
cardView.isHidden = true
self.view.addSubview(cardView)
if let firstView = cardViews.first {
self.view.insertSubview(cardView, belowSubview: firstView)
}
self.setScale(withScalePercent: 1 - CGFloat(self.cardViews.count) * sizePercent, duration: 0.25, cardView: cardView)
self.setCenter(CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2 + 150 - 20 - (sizePercent * 0 * 400)), duration: 0.25, cardView: cardView, index: 0)
self.cardViews.insert(cardView, at: 0)
return
}
// Move the last card according with gesture
let cardView = self.cardViews[self.cardViews.count - 1]
let transLocation = recognizer.translation(in: self.view)
cardView.center = CGPoint(x: cardView.center.x + transLocation.x, y: cardView.center.y + transLocation.y)
let xOffPercent = (cardView.center.x - self.view.bounds.width / 2) / self.view.bounds.width / 2
let scalePercent = 1 - abs(xOffPercent) * 0.3
let rotation = CGFloat.pi / 4 * xOffPercent
self.setScale(withScalePercent: scalePercent, duration: 0.0001, cardView: cardView)
self.setRotation(withAngle: rotation, duration: 0.001, cardView: cardView)
recognizer.setTranslation(.zero, in: self.view)
// Update card in background
for (i, card) in cardViews.enumerated() {
if cardView == card {
continue
}
var percent = abs(xOffPercent)
if percent > 1 {
percent = 1.0
}
let scalePercent = 1 - (sizePercent * CGFloat(self.cardViews.count - 1 - i) - sizePercent * abs(percent))
self.setScale(withScalePercent: scalePercent, duration: 0.0001, cardView: card)
let viewCenterY = self.view.bounds.height / 2
let centerY:CGFloat = viewCenterY + 150 - 20 - sizePercent * 400 * (CGFloat(i) - 1 + abs(percent))
let cardCenter = CGPoint(x: self.view.bounds.width / 2, y: centerY)
self.setCenter(cardCenter, duration: 0.0001, cardView: card, index: i)
}
if recognizer.state == .ended {
if cardView.center.x > 120 && cardView.center.x < self.view.bounds.width - 120 {
if let firstCardView = self.cardViews.first {
firstCardView.removeFromSuperview()
self.cardViews.remove(at: 0)
self.cardReCenterOrDismiss(isDismiss: false, cardView: cardView)
}
} else {
self.cardReCenterOrDismiss(isDismiss: true, cardView: cardView)
}
}
}
func showCardZone() {
for i in 0..<4 {
let cardView = createCardView()
cardView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
self.setScale(withScalePercent: 1 - sizePercent * CGFloat(3 - i), duration: 0.0001, cardView: cardView)
let targetCenter = calcCardCenter(index: i)
self.setCenter(targetCenter, duration: 0.1, cardView: cardView, index: i)
cardView.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2 - 10 * CGFloat(i) + 50)
self.view.addSubview(cardView)
self.cardViews.append(cardView)
self.currentIndex = i
}
}
func setCenter(_ center: CGPoint, duration: TimeInterval, cardView: UIView, index: Int) {
let ani = POPBasicAnimation(propertyNamed: kPOPViewCenter)
ani?.toValue = NSValue(cgPoint: center)
ani?.duration = duration
ani?.completionBlock = { ani, isFinish in
if isFinish {
cardView.isHidden = false
}
}
cardView.pop_add(ani, forKey: "center")
}
func setScale(withScalePercent percent: CGFloat, duration: TimeInterval, cardView: UIView) {
let ani = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
ani?.toValue = NSValue(cgSize: CGSize(width: percent, height: percent))
ani?.duration = duration
cardView.layer.pop_add(ani, forKey: "scale")
}
func setRotation(withAngle angle: CGFloat, duration: TimeInterval, cardView: UIView) {
let ani = POPBasicAnimation(propertyNamed: kPOPLayerRotation)
ani?.toValue = NSNumber(value: Float(angle))
ani?.duration = duration
ani?.timingFunction = CAMediaTimingFunction(name: .easeOut)
cardView.layer.pop_add(ani, forKey: "rotation")
}
func cardReCenterOrDismiss(isDismiss: Bool, cardView: UIView) {
if isDismiss {
setRotation(withAngle: 0, duration: 0.25, cardView: cardView)
if cardView.center.x < self.view.bounds.width / 2 {
// Slip out of screen in left side
self.setCenter(CGPoint(x: -150, y: cardView.center.y), duration: 0.25, cardView: cardView, index: 0)
} else {
// Slip out of screen in right side
self.setCenter(CGPoint(x: self.view.bounds.width + cardView.bounds.size.width / 2, y: cardView.center.y), duration: 0.25, cardView: cardView, index: 0)
}
self.perform(#selector(removeCard(cardView:)), with: cardView, afterDelay: 0.25)
} else {
self.setScale(withScalePercent: 1, duration: 0.25, cardView: cardView)
self.setRotation(withAngle: 0, duration: 0.25, cardView: cardView)
let targetCenter = calcCardCenter(index: 3)
self.setCenter(targetCenter, duration: 0.25, cardView: cardView, index: 3)
self.perform(#selector(removeCard(cardView:)), with: nil, afterDelay: 0.25)
}
}
@objc func removeCard(cardView: UIView?) {
// Remove cardView after animate is finished.
if cardView != nil {
cardView!.removeFromSuperview()
self.cardViews.removeAll(where: {$0 == cardView})
}
// Re location the coard
for (i, card) in self.cardViews.enumerated() {
self.setScale(withScalePercent: calcScale(index: i), duration: 0.1, cardView: card)
self.setCenter(calcCardCenter(index: i), duration: 0.1, cardView: card, index: i)
}
}
private func calcScale(index: Int) -> CGFloat {
return 1 - sizePercent * CGFloat(self.cardViews.count - 1 - index)
}
// Calculate center pointer of ith card
private func calcCardCenter(index: Int) -> CGPoint {
let viewCenterY = self.view.bounds.height / 2
return CGPoint(x: self.view.bounds.width / 2, y: viewCenterY + 150 - 20 - (sizePercent * CGFloat(index) * 400))
}
private func createCardView() -> UIView {
//return Bundle.main.loadNibNamed("NumberCardView", owner: self, options: nil)?.first as! UIView
let cardView = Bundle.main.loadNibNamed("TextCardView", owner: self, options: nil)?.first as! TextCardView
cardView.numLabel?.text = "\(arc4random() % 10)"
return cardView
}
}
| 44.021739 | 181 | 0.608025 |
e425a0f8c3a1dc26d9b36e921ff1946c9c48d29d | 915 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %{python} %S/../Inputs/not.py "%target-run %t/a.out" 2>&1 | %{python} %utils/backtrace-check
// NOTE: not.py is used above instead of "not --crash" because %target-run
// doesn't pass through the crash, and `not` may not be available when running
// on a remote host.
// This is not supported on watchos, ios, or tvos
// UNSUPPORTED: OS=watchos
// UNSUPPORTED: OS=ios
// UNSUPPORTED: OS=tvos
// REQUIRES: swift_stdlib_asserts
// REQUIRES: executable_test
// Backtraces are not emitted when optimizations are enabled. This test can not
// run when optimizations are enabled.
// REQUIRES: swift_test_mode_optimize_none
// This file just causes a crash in the runtime to check whether or not a stack
// trace is produced from the runtime.
func main() {
let x = UnsafePointer<Int>(bitPattern: 0)!
print("\(x.pointee)")
}
main()
| 30.5 | 100 | 0.708197 |
03df22a77440a5ffc565ef8d9199aa0b503e576c | 29,899 | import IOKit
import Foundation
//------------------------------------------------------------------------------
// MARK: Type Aliases
// http://stackoverflow.com/a/22383661
//------------------------------------------------------------------------------
// Floating point, unsigned, 14 bits exponent, 2 bits fraction
public typealias FPE2 = (UInt8, UInt8)
// Floating point, signed, 7 bits exponent, 8 bits fraction
public typealias SP78 = (UInt8, UInt8)
// Data returned from SMC
public typealias SMCBytes = (
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8)
//------------------------------------------------------------------------------
// MARK: Standard Library Extensions
//------------------------------------------------------------------------------
extension UInt32 {
init(fromBytes bytes: (UInt8, UInt8, UInt8, UInt8)) {
// TODO: Broken up due to "Expression was too complex" error as of Swift 4.
let byte0 = UInt32(bytes.0) << 24
let byte1 = UInt32(bytes.1) << 16
let byte2 = UInt32(bytes.2) << 8
let byte3 = UInt32(bytes.3)
self = byte0 | byte1 | byte2 | byte3
}
}
extension UInt16 {
init(fromBytes bytes: (UInt8, UInt8)) {
let byte0 = UInt16(bytes.0) << 16
let byte1 = UInt16(bytes.1)
self = byte0 | byte1
}
}
extension Bool {
init(fromByte byte: UInt8) {
self = byte == 1 ? true : false
}
}
public extension Int {
init(fromFPE2 bytes: FPE2) {
self = (Int(bytes.0) << 6) + (Int(bytes.1) >> 2)
}
func toFPE2() -> FPE2 {
return (UInt8(self >> 6), UInt8((self << 2) ^ ((self >> 6) << 8)))
}
}
extension Double {
init(fromSP78 bytes: SP78) {
// FIXME: Handle second byte
let sign = bytes.0 & 0x80 == 0 ? 1.0 : -1.0
self = sign * Double(bytes.0 & 0x7F) // AND to mask sign bit
}
}
// Thanks to Airspeed Velocity for the great idea!
// http://airspeedvelocity.net/2015/05/22/my-talk-at-swift-summit/
public extension FourCharCode {
init(fromString str: String) {
precondition(str.count == 4)
self = str.utf8.reduce(0) { sum, character in
return sum << 8 | UInt32(character)
}
}
init(fromStaticString str: StaticString) {
precondition(str.utf8CodeUnitCount == 4)
self = str.withUTF8Buffer { buffer in
// TODO: Broken up due to "Expression was too complex" error as of Swift 4.
let byte0 = UInt32(buffer[0]) << 24
let byte1 = UInt32(buffer[1]) << 16
let byte2 = UInt32(buffer[2]) << 8
let byte3 = UInt32(buffer[3])
return byte0 | byte1 | byte2 | byte3
}
}
func toString() -> String {
return String(describing: UnicodeScalar(self >> 24 & 0xff)!) +
String(describing: UnicodeScalar(self >> 16 & 0xff)!) +
String(describing: UnicodeScalar(self >> 8 & 0xff)!) +
String(describing: UnicodeScalar(self & 0xff)!)
}
}
//------------------------------------------------------------------------------
// MARK: Defined by AppleSMC.kext
//------------------------------------------------------------------------------
/// Defined by AppleSMC.kext
///
/// This is the predefined struct that must be passed to communicate with the
/// AppleSMC driver. While the driver is closed source, the definition of this
/// struct happened to appear in the Apple PowerManagement project at around
/// version 211, and soon after disappeared. It can be seen in the PrivateLib.c
/// file under pmconfigd. Given that it is C code, this is the closest
/// translation to Swift from a type perspective.
///
/// ### Issues
///
/// * Padding for struct alignment when passed over to C side
/// * Size of struct must be 80 bytes
/// * C array's are bridged as tuples
///
/// http://www.opensource.apple.com/source/PowerManagement/PowerManagement-211/
public struct SMCParamStruct {
// I/O Kit function selector
public enum Selector: UInt8 {
case kSMCHandleYPCEvent = 2
case kSMCReadKey = 5
case kSMCWriteKey = 6
case kSMCGetKeyFromIndex = 8
case kSMCGetKeyInfo = 9
}
// Return codes for SMCParamStruct.result property
public enum Result: UInt8 {
case kSMCSuccess = 0
case kSMCError = 1
case kSMCKeyNotFound = 132
}
public struct SMCVersion {
var major: CUnsignedChar = 0
var minor: CUnsignedChar = 0
var build: CUnsignedChar = 0
var reserved: CUnsignedChar = 0
var release: CUnsignedShort = 0
}
public struct SMCPLimitData {
var version: UInt16 = 0
var length: UInt16 = 0
var cpuPLimit: UInt32 = 0
var gpuPLimit: UInt32 = 0
var memPLimit: UInt32 = 0
}
public struct SMCKeyInfoData {
// How many bytes written to SMCParamStruct.bytes
var dataSize: IOByteCount = 0
// Type of data written to SMCParamStruct.bytes. This lets us know how
// to interpret it (translate it to human readable)
var dataType: UInt32 = 0
var dataAttributes: UInt8 = 0
}
// FourCharCode telling the SMC what we want
var key: UInt32 = 0
var vers = SMCVersion()
var pLimitData = SMCPLimitData()
var keyInfo = SMCKeyInfoData()
// Padding for struct alignment when passed over to C side
var padding: UInt16 = 0
// Result of an operation
var result: UInt8 = 0
var status: UInt8 = 0
// Method selector
var data8: UInt8 = 0
var data32: UInt32 = 0
// Data returned from the SMC
var bytes: SMCBytes = (
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0))
}
//------------------------------------------------------------------------------
// MARK: SMC Client
//------------------------------------------------------------------------------
// SMC data type information
public struct DataTypes {
// Fan information struct
public static let FDS = DataType(type: FourCharCode(fromStaticString: "{fds"), size: 16)
public static let Flag = DataType(type: FourCharCode(fromStaticString: "flag"), size: 1)
// See type aliases
public static let FPE2 = DataType(type: FourCharCode(fromStaticString: "fpe2"), size: 2)
public static let SP78 = DataType(type: FourCharCode(fromStaticString: "sp78"), size: 2)
public static let UInt8 = DataType(type: FourCharCode(fromStaticString: "ui8 "), size: 1)
public static let UInt16 = DataType(type: FourCharCode(fromStaticString: "ui16"), size: 2)
public static let UInt32 = DataType(type: FourCharCode(fromStaticString: "ui32"), size: 4)
}
public struct SMCKey {
let code: FourCharCode
let info: DataType
}
public struct DataType: Equatable {
let type: FourCharCode
let size: UInt32
}
public func ==(lhs: DataType, rhs: DataType) -> Bool {
return lhs.type == rhs.type && lhs.size == rhs.size
}
// Apple System Management Controller (SMC) user-space client for Intel-based
// Macs. Works by talking to the AppleSMC.kext (kernel extension), the closed
// source driver for the SMC.
public struct SMCKit {
public enum SMCError: Error {
// AppleSMC driver not found
case driverNotFound
// Failed to open a connection to the AppleSMC driver
case failedToOpen
// This SMC key is not valid on this machine
case keyNotFound(code: String)
// Requires root privileges
case notPrivileged
// Fan speed must be > 0 && <= fanMaxSpeed
case unsafeFanSpeed
// Unknown error
// https://developer.apple.com/library/mac/qa/qa1075/_index.html
// - parameter kIOReturn: I/O Kit error code
// - parameter SMCResult: SMC specific return code
case unknown(kIOReturn: kern_return_t, SMCResult: UInt8)
}
// Connection to the SMC driver
fileprivate static var connection: io_connect_t = 0
// Open connection to the SMC driver.
// This must be done first before any other calls
public static func open() throws {
let service = IOServiceGetMatchingService(
kIOMasterPortDefault,
IOServiceMatching("AppleSMC"))
if service == 0 {
throw SMCError.driverNotFound
}
let result = IOServiceOpen(
service, mach_task_self_, 0, &SMCKit.connection)
IOObjectRelease(service)
if result != kIOReturnSuccess {
throw SMCError.failedToOpen
}
}
// Close connection to the SMC driver
@discardableResult
public static func close() -> Bool {
let result = IOServiceClose(SMCKit.connection)
return result == kIOReturnSuccess ? true : false
}
// Get information about a key
public static func keyInformation(_ key: FourCharCode) throws -> DataType {
var inputStruct = SMCParamStruct()
inputStruct.key = key
inputStruct.data8 = SMCParamStruct.Selector.kSMCGetKeyInfo.rawValue
let outputStruct = try callDriver(&inputStruct)
return DataType(
type: outputStruct.keyInfo.dataType,
size: outputStruct.keyInfo.dataSize)
}
// Get information about the key at index
public static func keyInformationAtIndex(_ index: Int) throws -> FourCharCode {
var inputStruct = SMCParamStruct()
inputStruct.data8 = SMCParamStruct.Selector.kSMCGetKeyFromIndex.rawValue
inputStruct.data32 = UInt32(index)
let outputStruct = try callDriver(&inputStruct)
return outputStruct.key
}
// Read data of a key
public static func readData(_ key: SMCKey) throws -> SMCBytes {
var inputStruct = SMCParamStruct()
inputStruct.key = key.code
inputStruct.keyInfo.dataSize = UInt32(key.info.size)
inputStruct.data8 = SMCParamStruct.Selector.kSMCReadKey.rawValue
let outputStruct = try callDriver(&inputStruct)
return outputStruct.bytes
}
// Write data for a key
public static func writeData(_ key: SMCKey, data: SMCBytes) throws {
var inputStruct = SMCParamStruct()
inputStruct.key = key.code
inputStruct.bytes = data
inputStruct.keyInfo.dataSize = UInt32(key.info.size)
inputStruct.data8 = SMCParamStruct.Selector.kSMCWriteKey.rawValue
_ = try callDriver(&inputStruct)
}
// Make a call to the SMC driver
public static func callDriver(
_ inputStruct: inout SMCParamStruct,
selector: SMCParamStruct.Selector = .kSMCHandleYPCEvent)
throws -> SMCParamStruct {
assert(MemoryLayout<SMCParamStruct>.stride == 80, "SMCParamStruct size is != 80")
var outputStruct = SMCParamStruct()
let inputStructSize = MemoryLayout<SMCParamStruct>.stride
var outputStructSize = MemoryLayout<SMCParamStruct>.stride
let result = IOConnectCallStructMethod(
SMCKit.connection,
UInt32(selector.rawValue),
&inputStruct,
inputStructSize,
&outputStruct,
&outputStructSize)
switch (result, outputStruct.result) {
case (kIOReturnSuccess, SMCParamStruct.Result.kSMCSuccess.rawValue):
return outputStruct
case (kIOReturnSuccess, SMCParamStruct.Result.kSMCKeyNotFound.rawValue):
throw SMCError.keyNotFound(code: inputStruct.key.toString())
case (kIOReturnNotPrivileged, _):
throw SMCError.notPrivileged
default:
throw SMCError.unknown(kIOReturn: result, SMCResult: outputStruct.result)
}
}
}
//------------------------------------------------------------------------------
// MARK: General
//------------------------------------------------------------------------------
extension SMCKit {
// Get all valid SMC keys for this machine
public static func allKeys() throws -> [SMCKey] {
let count = try keyCount()
var keys = [SMCKey]()
for i in 0 ..< count {
let key = try keyInformationAtIndex(i)
let info = try keyInformation(key)
keys.append(SMCKey(code: key, info: info))
}
return keys
}
// Get the number of valid SMC keys for this machine
public static func keyCount() throws -> Int {
let key = SMCKey(
code: FourCharCode(fromStaticString: "#KEY"),
info: DataTypes.UInt32)
let data = try readData(key)
return Int(UInt32(fromBytes: (data.0, data.1, data.2, data.3)))
}
// Check if the key is valid
public static func isKeyFound(_ code: FourCharCode) throws -> Bool {
do {
_ = try keyInformation(code)
}
catch SMCError.keyNotFound {
return false
}
return true
}
}
//------------------------------------------------------------------------------
// MARK: Temperature
//------------------------------------------------------------------------------
// The list is NOT exhaustive. In addition, the names of the sensors may not be
// mapped to the correct hardware component.
//
// Sources
// * powermetrics(1)
// * https://www.apple.com/downloads/dashboard/status/istatpro.html
// * https://github.com/hholtmann/smcFanControl
// * https://github.com/jedda/OSX-Monitoring-Tools
// * http://www.opensource.apple.com/source/net_snmp/
// * http://www.parhelia.ch/blog/statics/k3_keys.html
public struct TemperatureSensors {
public static let AMBIENT_AIR_0 = TemperatureSensor(name: "AMBIENT_AIR_0", code: FourCharCode(fromStaticString: "TA0P"))
public static let AMBIENT_AIR_1 = TemperatureSensor(name: "AMBIENT_AIR_1", code: FourCharCode(fromStaticString: "TA1P"))
// Via powermetrics(1)
public static let CPU_0_DIE = TemperatureSensor(name: "CPU_0_DIE", code: FourCharCode(fromStaticString: "TC0F"))
public static let CPU_0_DIODE = TemperatureSensor(name: "CPU_0_DIODE", code: FourCharCode(fromStaticString: "TC0D"))
public static let CPU_0_HEATSINK = TemperatureSensor(name: "CPU_0_HEATSINK", code: FourCharCode(fromStaticString: "TC0H"))
public static let CPU_0_PROXIMITY = TemperatureSensor(name: "CPU_0_PROXIMITY", code: FourCharCode(fromStaticString: "TC0P"))
public static let CPU_1 = TemperatureSensor(name: "CPU_1", code: FourCharCode(fromStaticString: "TC1C"))
public static let CPU_2 = TemperatureSensor(name: "CPU_1", code: FourCharCode(fromStaticString: "TC1C"))
public static let ENCLOSURE_BASE_0 = TemperatureSensor(name: "ENCLOSURE_BASE_0", code: FourCharCode(fromStaticString: "TB0T"))
public static let ENCLOSURE_BASE_1 = TemperatureSensor(name: "ENCLOSURE_BASE_1", code: FourCharCode(fromStaticString: "TB1T"))
public static let ENCLOSURE_BASE_2 = TemperatureSensor(name: "ENCLOSURE_BASE_2", code: FourCharCode(fromStaticString: "TB2T"))
public static let ENCLOSURE_BASE_3 = TemperatureSensor(name: "ENCLOSURE_BASE_3", code: FourCharCode(fromStaticString: "TB3T"))
public static let GPU_0_DIODE = TemperatureSensor(name: "GPU_0_DIODE", code: FourCharCode(fromStaticString: "TG0D"))
public static let GPU_0_HEATSINK = TemperatureSensor(name: "GPU_0_HEATSINK", code: FourCharCode(fromStaticString: "TG0H"))
public static let GPU_0_PROXIMITY = TemperatureSensor(name: "GPU_0_PROXIMITY", code: FourCharCode(fromStaticString: "TG0P"))
public static let HDD_PROXIMITY = TemperatureSensor(name: "HDD_PROXIMITY", code: FourCharCode(fromStaticString: "TH0P"))
public static let HEATSINK_0 = TemperatureSensor(name: "HEATSINK_0", code: FourCharCode(fromStaticString: "Th0H"))
public static let HEATSINK_1 = TemperatureSensor(name: "HEATSINK_1", code: FourCharCode(fromStaticString: "Th1H"))
public static let HEATSINK_2 = TemperatureSensor(name: "HEATSINK_2", code: FourCharCode(fromStaticString: "Th2H"))
public static let LCD_PROXIMITY = TemperatureSensor(name: "LCD_PROXIMITY", code: FourCharCode(fromStaticString: "TL0P"))
public static let MEM_SLOT_0 = TemperatureSensor(name: "MEM_SLOT_0", code: FourCharCode(fromStaticString: "TM0S"))
public static let MEM_SLOTS_PROXIMITY = TemperatureSensor(name: "MEM_SLOTS_PROXIMITY", code: FourCharCode(fromStaticString: "TM0P"))
public static let MISC_PROXIMITY = TemperatureSensor(name: "MISC_PROXIMITY", code: FourCharCode(fromStaticString: "Tm0P"))
public static let NORTHBRIDGE = TemperatureSensor(name: "NORTHBRIDGE", code: FourCharCode(fromStaticString: "TN0H"))
public static let NORTHBRIDGE_DIODE = TemperatureSensor(name: "NORTHBRIDGE_DIODE", code: FourCharCode(fromStaticString: "TN0D"))
public static let NORTHBRIDGE_PROXIMITY = TemperatureSensor(name: "NORTHBRIDGE_PROXIMITY", code: FourCharCode(fromStaticString: "TN0P"))
public static let ODD_PROXIMITY = TemperatureSensor(name: "ODD_PROXIMITY", code: FourCharCode(fromStaticString: "TO0P"))
public static let PALM_REST = TemperatureSensor(name: "PALM_REST", code: FourCharCode(fromStaticString: "Ts0P"))
public static let PWR_SUPPLY_PROXIMITY = TemperatureSensor(name: "PWR_SUPPLY_PROXIMITY", code: FourCharCode(fromStaticString: "Tp0P"))
public static let THUNDERBOLT_0 = TemperatureSensor(name: "THUNDERBOLT_0",code: FourCharCode(fromStaticString: "TI0P"))
public static let THUNDERBOLT_1 = TemperatureSensor(name: "THUNDERBOLT_1", code: FourCharCode(fromStaticString: "TI1P"))
public static let all = [
AMBIENT_AIR_0.code : AMBIENT_AIR_0,
AMBIENT_AIR_1.code : AMBIENT_AIR_1,
CPU_0_DIE.code : CPU_0_DIE,
CPU_0_DIODE.code : CPU_0_DIODE,
CPU_0_HEATSINK.code : CPU_0_HEATSINK,
CPU_0_PROXIMITY.code : CPU_0_PROXIMITY,
ENCLOSURE_BASE_0.code : ENCLOSURE_BASE_0,
ENCLOSURE_BASE_1.code : ENCLOSURE_BASE_1,
ENCLOSURE_BASE_2.code : ENCLOSURE_BASE_2,
ENCLOSURE_BASE_3.code : ENCLOSURE_BASE_3,
GPU_0_DIODE.code : GPU_0_DIODE,
GPU_0_HEATSINK.code : GPU_0_HEATSINK,
GPU_0_PROXIMITY.code : GPU_0_PROXIMITY,
HDD_PROXIMITY.code : HDD_PROXIMITY,
HEATSINK_0.code : HEATSINK_0,
HEATSINK_1.code : HEATSINK_1,
HEATSINK_2.code : HEATSINK_2,
MEM_SLOT_0.code : MEM_SLOT_0,
MEM_SLOTS_PROXIMITY.code: MEM_SLOTS_PROXIMITY,
PALM_REST.code : PALM_REST,
LCD_PROXIMITY.code : LCD_PROXIMITY,
MISC_PROXIMITY.code : MISC_PROXIMITY,
NORTHBRIDGE.code : NORTHBRIDGE,
NORTHBRIDGE_DIODE.code : NORTHBRIDGE_DIODE,
NORTHBRIDGE_PROXIMITY.code : NORTHBRIDGE_PROXIMITY,
ODD_PROXIMITY.code : ODD_PROXIMITY,
PWR_SUPPLY_PROXIMITY.code : PWR_SUPPLY_PROXIMITY,
THUNDERBOLT_0.code : THUNDERBOLT_0,
THUNDERBOLT_1.code : THUNDERBOLT_1]
}
public struct TemperatureSensor {
public let name: String
public let code: FourCharCode
}
public enum TemperatureUnit {
case celius
case fahrenheit
case kelvin
public static func toFahrenheit(_ celius: Double) -> Double {
// https://en.wikipedia.org/wiki/Fahrenheit#Definition_and_conversions
return (celius * 1.8) + 32
}
public static func toKelvin(_ celius: Double) -> Double {
// https://en.wikipedia.org/wiki/Kelvin
return celius + 273.15
}
}
extension SMCKit {
public static func allKnownTemperatureSensors() throws -> [TemperatureSensor] {
var sensors = [TemperatureSensor]()
for sensor in TemperatureSensors.all.values {
if try isKeyFound(sensor.code) { sensors.append(sensor) }
}
return sensors
}
public static func allUnknownTemperatureSensors() throws -> [TemperatureSensor] {
let keys = try allKeys()
return keys
.filter {
$0.code.toString().hasPrefix("T")
&& $0.info == DataTypes.SP78
&& TemperatureSensors.all[$0.code] == nil }
.map {
TemperatureSensor(name: "Unknown", code: $0.code) }
}
// Get current temperature of a sensor
public static func temperature(
_ sensorCode: FourCharCode,
unit: TemperatureUnit = .celius)
throws -> Double {
let data = try readData(SMCKey(code: sensorCode, info: DataTypes.SP78))
let temperatureInCelius = Double(fromSP78: (data.0, data.1))
switch unit {
case .celius:
return temperatureInCelius
case .fahrenheit:
return TemperatureUnit.toFahrenheit(temperatureInCelius)
case .kelvin:
return TemperatureUnit.toKelvin(temperatureInCelius)
}
}
}
//------------------------------------------------------------------------------
// MARK: Fan
//------------------------------------------------------------------------------
public struct Fan {
// TODO: Should we start the fan id from 1 instead of 0?
public let id: Int
public let name: String
public let minSpeed: Int
public let maxSpeed: Int
}
extension SMCKit {
public static func allFans() throws -> [Fan] {
let count = try fanCount()
var fans = [Fan]()
for i in 0 ..< count {
fans.append(try SMCKit.fan(i))
}
return fans
}
public static func fan(_ id: Int) throws -> Fan {
let name = try fanName(id)
let minSpeed = try fanMinSpeed(id)
let maxSpeed = try fanMaxSpeed(id)
return Fan(id: id, name: name, minSpeed: minSpeed, maxSpeed: maxSpeed)
}
// Number of fans this machine has. All Intel based Macs, except for the
// 2015 MacBook (8,1), have at least 1
public static func fanCount() throws -> Int {
let key = SMCKey(
code: FourCharCode(fromStaticString: "FNum"),
info: DataTypes.UInt8)
let data = try readData(key)
return Int(data.0)
}
public static func fanName(_ id: Int) throws -> String {
let key = SMCKey(
code: FourCharCode(fromString: "F\(id)ID"),
info: DataTypes.FDS)
let data = try readData(key)
// The last 12 bytes of '{fds' data type, a custom struct defined by the
// AppleSMC.kext that is 16 bytes, contains the fan name
let c1 = String(UnicodeScalar(data.4))
let c2 = String(UnicodeScalar(data.5))
let c3 = String(UnicodeScalar(data.6))
let c4 = String(UnicodeScalar(data.7))
let c5 = String(UnicodeScalar(data.8))
let c6 = String(UnicodeScalar(data.9))
let c7 = String(UnicodeScalar(data.10))
let c8 = String(UnicodeScalar(data.11))
let c9 = String(UnicodeScalar(data.12))
let c10 = String(UnicodeScalar(data.13))
let c11 = String(UnicodeScalar(data.14))
let c12 = String(UnicodeScalar(data.15))
let name = c1 + c2 + c3 + c4 + c5 + c6 + c7 + c8 + c9 + c10 + c11 + c12
let characterSet = CharacterSet.whitespaces
return name.trimmingCharacters(in: characterSet)
}
public static func fanCurrentSpeed(_ id: Int) throws -> Int {
let key = SMCKey(
code: FourCharCode(fromString: "F\(id)Ac"),
info: DataTypes.FPE2)
let data = try readData(key)
return Int(fromFPE2: (data.0, data.1))
}
public static func fanMinSpeed(_ id: Int) throws -> Int {
let key = SMCKey(
code: FourCharCode(fromString: "F\(id)Mn"),
info: DataTypes.FPE2)
let data = try readData(key)
return Int(fromFPE2: (data.0, data.1))
}
public static func fanMaxSpeed(_ id: Int) throws -> Int {
let key = SMCKey(
code: FourCharCode(fromString: "F\(id)Mx"),
info: DataTypes.FPE2)
let data = try readData(key)
return Int(fromFPE2: (data.0, data.1))
}
public static func fanGetModes() throws -> Int {
let key = SMCKey(
code: FourCharCode(fromString: "FS! "),
info: DataTypes.UInt16)
let bytes = try readData(key)
return Int(UInt16(fromBytes: (bytes.0, bytes.1)))
}
public static func fanIsAuto(_ id: Int) throws -> Bool {
let flags = try fanGetModes()
let mode = flags & Int(id + 1)
return mode == 0
}
public static func fanSetAuto(_ id: Int, _ auto: Bool) throws {
var flags = try fanGetModes()
let flag = Int(id + 1)
if (!auto) {
flags |= flag
}
else {
flags &= ~flag
}
let byte0 = UInt8(flags >> 8)
let byte1 = UInt8(flags)
let bytes: SMCBytes = (
byte0, byte1, UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0))
let key = SMCKey(
code: FourCharCode(fromString: "FS! "),
info: DataTypes.UInt16)
try writeData(key, data: bytes)
}
/// Requires root privileges. By minimum we mean that OS X can interject and
/// raise the fan speed if needed, however it will not go below this.
///
/// WARNING: You are playing with hardware here, BE CAREFUL.
///
/// - Throws: Of note, `SMCKit.SMCError`'s `UnsafeFanSpeed` and `NotPrivileged`
public static func fanSetMinSpeed(_ id: Int, _ speed: Int) throws {
let maxSpeed = try fanMaxSpeed(id)
if speed <= 0 || speed > maxSpeed {
throw SMCError.unsafeFanSpeed
}
let data = speed.toFPE2()
let bytes: SMCBytes = (
data.0, data.1, UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0))
let key = SMCKey(
code: FourCharCode(fromString: "F\(id)Mn"),
info: DataTypes.FPE2)
try writeData(key, data: bytes)
}
public static func fanSetTargetSpeed(_ id: Int, _ speed: Int) throws {
let maxSpeed = try fanMaxSpeed(id)
if speed < 0 || speed > maxSpeed {
throw SMCError.unsafeFanSpeed
}
let data = speed.toFPE2()
let bytes: SMCBytes = (
data.0, data.1, UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0),
UInt8(0), UInt8(0))
let key = SMCKey(
code: FourCharCode(fromString: "F\(id)Tg"),
info: DataTypes.FPE2)
try writeData(key, data: bytes)
}
}
//------------------------------------------------------------------------------
// MARK: Miscellaneous
//------------------------------------------------------------------------------
public struct batteryInfo {
public let batteryCount: Int
public let isACPresent: Bool
public let isBatteryPowered: Bool
public let isBatteryOk: Bool
public let isCharging: Bool
}
extension SMCKit {
public static func isOpticalDiskDriveFull() throws -> Bool {
// TODO: Should we catch key not found? That just means the machine
// doesn't have an ODD. Returning false though is not fully correct.
// Maybe we could throw a no ODD error instead?
let key = SMCKey(code: FourCharCode(fromStaticString: "MSDI"),
info: DataTypes.Flag)
let data = try readData(key)
return Bool(fromByte: data.0)
}
public static func batteryInformation() throws -> batteryInfo {
let batteryCountKey = SMCKey(code: FourCharCode(fromStaticString: "BNum"), info: DataTypes.UInt8)
let batteryPoweredKey = SMCKey(code: FourCharCode(fromStaticString: "BATP"), info: DataTypes.Flag)
let batteryInfoKey = SMCKey(code: FourCharCode(fromStaticString: "BSIn"), info: DataTypes.UInt8)
let batteryCountData = try readData(batteryCountKey)
let batteryCount = Int(batteryCountData.0)
let isBatteryPoweredData = try readData(batteryPoweredKey)
let isBatteryPowered = Bool(fromByte: isBatteryPoweredData.0)
let batteryInfoData = try readData(batteryInfoKey)
let isCharging = batteryInfoData.0 & 1 == 1 ? true : false
let isACPresent = (batteryInfoData.0 >> 1) & 1 == 1 ? true : false
let isBatteryOk = (batteryInfoData.0 >> 6) & 1 == 1 ? true : false
return batteryInfo(batteryCount: batteryCount, isACPresent: isACPresent,
isBatteryPowered: isBatteryPowered,
isBatteryOk: isBatteryOk,
isCharging: isCharging)
}
}
| 40.295148 | 140 | 0.60885 |
293cda6266bcee7d7fb4496acd3ec8c7e6deacdc | 3,626 | //
// GroupMembership.swift
// BoxSDK-iOS
//
// Created by Cary Cheng on 9/3/19.
// Copyright © 2019 box. All rights reserved.
//
import Foundation
/// Specifies role of the user within a Group.
public enum GroupRole: BoxEnum {
/// Default permission for a user in a Group.
case member
/// The admin of the Group.
case admin
/// A custom object type for defining access that is not yet implemented
case customValue(String)
/// Creates a new value
///
/// - Parameter value: String representation of an GroupRole rawValue
public init(_ value: String) {
switch value {
case "member":
self = .member
case "admin":
self = .admin
default:
self = .customValue(value)
}
}
/// Returns string representation of type that can be used in a request.
public var description: String {
switch self {
case .member:
return "member"
case .admin:
return "admin"
case let .customValue(userValue):
return userValue
}
}
}
/// Membership of a group
public class GroupMembership: BoxModel {
/// Permissions of group membership
public struct ConfigurablePermissions: BoxInnerModel {
/// Group can run reports
public let canRunReports: Bool
/// Group can login instantly
public let canInstantLogin: Bool
/// Group can create accounts
public let canCreateAccounts: Bool
/// Group can edit accounts
public let canEditAccounts: Bool
}
// MARK: - BoxModel
private static var resourceType: String = "group_membership"
/// Box item type
public var type: String
public private(set) var rawData: [String: Any]
/// The ID of the association between a user and a group.
public let id: String
/// A user object associated with the group.
public let user: User?
/// The group the user is associated with.
public let group: Group?
/// The role of the user within the group. The default is `member` with an option for `admin`.
public let role: GroupRole?
/// Permissions of an individual group member.
public let configurablePermissions: ConfigurablePermissions?
/// The date time this membership was created at.
public let createdAt: Date?
/// The date time this membership was modified at.
public let modifiedAt: Date?
/// Initializer.
///
/// - Parameter json: JSON dictionary.
/// - Throws: Decoding error.
public required init(json: [String: Any]) throws {
guard let itemType = json["type"] as? String else {
throw BoxCodingError(message: .typeMismatch(key: "type"))
}
guard itemType == GroupMembership.resourceType else {
throw BoxCodingError(message: .valueMismatch(key: "type", value: itemType, acceptedValues: [GroupMembership.resourceType]))
}
rawData = json
type = itemType
id = try BoxJSONDecoder.decode(json: json, forKey: "id")
user = try BoxJSONDecoder.optionalDecode(json: json, forKey: "user")
group = try BoxJSONDecoder.optionalDecode(json: json, forKey: "group")
createdAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "created_at")
modifiedAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "modified_at")
role = try BoxJSONDecoder.optionalDecodeEnum(json: json, forKey: "role")
configurablePermissions = try BoxJSONDecoder.optionalDecode(json: json, forKey: "configurable_permissions")
}
}
| 33.266055 | 135 | 0.645891 |
7917300ad66b70f4d2d1d078ed95b8b6dbe5d565 | 4,903 | //
// TouchIDTableViewController.swift
// Throttle
//
// Created by Kaitlyn Lee on 3/20/16.
// Copyright © 2016 Gigster. All rights reserved.
//
import UIKit
class TouchIDTableViewController: UITableViewController {
let kTouchIDCellIdentifier = "touchIDCellIdentifier"
var settingsService:SettingsService!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
let auth = ConfigFactory.getAuth();
settingsService = SettingsService(auth: auth)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "enableTouchID:", name: "enableTouchIDNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "disableTouchID:", name: "disableTouchIDNotification", object: nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "enableTouchIDNotification:", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "disableTouchIDNotification:", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kTouchIDCellIdentifier, forIndexPath: indexPath) as! TouchIDSettingTableViewCell
cell.backgroundColor = tableViewCellDarkerBlue()
cell.enableTouchIDSwitch.on = settingsService.isTouchIDEnabledOrSet()
// Configure the cell...
return cell
}
func enableTouchID(notification:NSNotification) {
self.saveTouchIDSetting(true)
let controller = AlertUtil.getSimpleAlert("Touch ID", message: "Touch ID has been activated. You will be asked for your fingerprint the next time you open the app.");
self.presentViewController(controller, animated: true, completion: nil);
}
func disableTouchID(notification:NSNotification) {
self.saveTouchIDSetting(false)
}
func saveTouchIDSetting(enable:Bool) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
self.settingsService.setTouchIDEnabled(enable);
};
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 38.007752 | 167 | 0.717316 |
21d20fc7dd65854046d3750e04ff0c08f8dcba89 | 951 | //
// ViewController.swift
// IOS TIP CALCULATOR PROJECT
//
// Created by crystal on 2/11/22.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var tipAmountLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calculateTip(_ sender: Any) {
let bill = Double(billAmountTextField.text!) ?? 0
let tipPercentages = [0.15, 0.18, 0.2]
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipAmountLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| 22.642857 | 72 | 0.607781 |
e2d55dfdbf2b04d965fd4b05814a59ee0664aec7 | 14,571 | typealias JSONDictionary = [String: AnyObject]
public let MBGeocoderErrorDomain = "com.mapbox.MapboxGeocoder"
/// The Mapbox access token specified in the main application bundle’s Info.plist.
let defaultAccessToken = NSBundle.mainBundle().objectForInfoDictionaryKey("MGLMapboxAccessToken") as? String
extension NSCharacterSet {
/**
Returns the character set including the characters allowed in the “geocoding query” (file name) part of a Geocoding API URL request.
*/
internal class func geocodingQueryAllowedCharacterSet() -> NSCharacterSet {
let characterSet = NSCharacterSet.URLPathAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
characterSet.removeCharactersInString("/;")
return characterSet
}
}
extension CLLocationCoordinate2D {
/**
Initializes a coordinate pair based on the given GeoJSON array.
*/
internal init(geoJSON array: [Double]) {
assert(array.count == 2)
self.init(latitude: array[1], longitude: array[0])
}
}
extension CLLocation {
/**
Initializes a CLLocation object with the given coordinate pair.
*/
internal convenience init(coordinate: CLLocationCoordinate2D) {
self.init(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
/**
A geocoder object that allows you to query the [Mapbox Geocoding API](https://www.mapbox.com/api-documentation/?language=Swift#geocoding) for known places corresponding to a given location. The query may take the form of a geographic coordinate or a human-readable string.
The geocoder object allows you to perform both forward and reverse geocoding. _Forward geocoding_ takes a human-readable query, such as a place name or address, and produces any number of geographic coordinates that correspond to that query. _Reverse geocoding_ takes a geographic coordinate and produces a hierarchy of places, often beginning with an address, that describes the coordinate’s location.
Each result produced by the geocoder object is stored in a `Placemark` object. Depending on your query and the available data, the placemark object may contain a variety of information, such as the name, address, region, or contact information for a place, or some combination thereof.
*/
@objc(MBGeocoder)
public class Geocoder: NSObject {
/**
A closure (block) to be called when a geocoding request is complete.
- parameter placemarks: An array of `Placemark` objects. For reverse geocoding requests, this array represents a hierarchy of places, beginning with the most local place, such as an address, and ending with the broadest possible place, which is usually a country. By contrast, forward geocoding requests may return multiple placemark objects in situations where the specified address matched more than one location.
If the request was canceled or there was an error obtaining the placemarks, this parameter is `nil`. This is not to be confused with the situation in which no results were found, in which case the array is present but empty.
- parameter attribution: A legal notice indicating the source, copyright status, and terms of use of the placemark data.
- parameter error: The error that occurred, or `nil` if the placemarks were obtained successfully.
*/
public typealias CompletionHandler = (placemarks: [GeocodedPlacemark]?, attribution: String?, error: NSError?) -> Void
/**
A closure (block) to be called when a geocoding request is complete.
- parameter placemarksByQuery: An array of arrays of `Placemark` objects, one placemark array for each query. For reverse geocoding requests, these arrays represent hierarchies of places, beginning with the most local place, such as an address, and ending with the broadest possible place, which is usually a country. By contrast, forward geocoding requests may return multiple placemark objects in situations where the specified address matched more than one location.
If the request was canceled or there was an error obtaining the placemarks, this parameter is `nil`. This is not to be confused with the situation in which no results were found, in which case the array is present but empty.
- parameter attributionsByQuery: An array of legal notices indicating the sources, copyright statuses, and terms of use of the placemark data for each query.
- parameter error: The error that occurred, or `nil` if the placemarks were obtained successfully.
*/
public typealias BatchCompletionHandler = (placemarksByQuery: [[GeocodedPlacemark]]?, attributionsByQuery: [String]?, error: NSError?) -> Void
/**
The shared geocoder object.
To use this object, a Mapbox [access token](https://www.mapbox.com/help/define-access-token/) should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
*/
public static let sharedGeocoder = Geocoder(accessToken: nil)
/// The API endpoint to request the geocodes from.
internal var apiEndpoint: NSURL
/// The Mapbox access token to associate the request with.
internal let accessToken: String
/**
Initializes a newly created geocoder object with an optional access token and host.
- parameter accessToken: A Mapbox [access token](https://www.mapbox.com/help/define-access-token/). If an access token is not specified when initializing the geocoder object, it should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
- parameter host: An optional hostname to the server API. The Mapbox Geocoding API endpoint is used by default.
*/
public init(accessToken: String?, host: String?) {
let accessToken = accessToken ?? defaultAccessToken
assert(accessToken != nil && !accessToken!.isEmpty, "A Mapbox access token is required. Go to <https://www.mapbox.com/studio/account/tokens/>. In Info.plist, set the MGLMapboxAccessToken key to your access token, or use the Geocoder(accessToken:host:) initializer.")
self.accessToken = accessToken!
let baseURLComponents = NSURLComponents()
baseURLComponents.scheme = "https"
baseURLComponents.host = host ?? "api.mapbox.com"
self.apiEndpoint = baseURLComponents.URL!
}
/**
Initializes a newly created geocoder object with an optional access token.
The snapshot instance sends requests to the Mapbox Geocoding API endpoint.
- parameter accessToken: A Mapbox [access token](https://www.mapbox.com/help/define-access-token/). If an access token is not specified when initializing the geocoder object, it should be specified in the `MGLMapboxAccessToken` key in the main application bundle’s Info.plist.
*/
public convenience init(accessToken: String?) {
self.init(accessToken: accessToken, host: nil)
}
// MARK: Geocoding a Location
/**
Submits a geocoding request to search for placemarks and delivers the results to the given closure.
This method retrieves the placemarks asynchronously over a network connection. If a connection error or server error occurs, details about the error are passed into the given completion handler in lieu of the placemarks.
Geocoding results may be displayed atop a Mapbox map. They may be cached but may not be stored permanently. To use the results in other contexts or store them permanently, use the `batchGeocode(options:completionHandler:)` method with a Mapbox enterprise plan.
- parameter options: A `ForwardGeocodeOptions` or `ReverseGeocodeOptions` object indicating what to search for.
- parameter completionHandler: The closure (block) to call with the resulting placemarks. This closure is executed on the application’s main thread.
- returns: The data task used to perform the HTTP request. If, while waiting for the completion handler to execute, you no longer want the resulting placemarks, cancel this task.
*/
public func geocode(options options: GeocodeOptions, completionHandler: CompletionHandler) -> NSURLSessionDataTask {
let url = URLForGeocoding(options: options)
let task = dataTaskWithURL(url, completionHandler: { (json) in
let featureCollection = json as! JSONDictionary
assert(featureCollection["type"] as? String == "FeatureCollection")
let features = featureCollection["features"] as! [JSONDictionary]
let attribution = featureCollection["attribution"] as? String
let placemarks = features.flatMap { GeocodedPlacemark(featureJSON: $0) }
completionHandler(placemarks: placemarks, attribution: attribution, error: nil)
}) { (error) in
completionHandler(placemarks: nil, attribution: nil, error: error)
}
task.resume()
return task
}
/**
Submits a batch geocoding request to search for placemarks and delivers the results to the given closure.
This method retrieves the placemarks asynchronously over a network connection. If a connection error or server error occurs, details about the error are passed into the given completion handler in lieu of the placemarks.
Batch geocoding requires a Mapbox enterprise plan and allows you to store the resulting placemark data as part of a private database.
- parameter options: A `ForwardBatchGeocodeOptions` or `ReverseBatchGeocodeOptions` object indicating what to search for.
- parameter completionHandler: The closure (block) to call with the resulting placemarks. This closure is executed on the application’s main thread.
- returns: The data task used to perform the HTTP request. If, while waiting for the completion handler to execute, you no longer want the resulting placemarks, cancel this task.
*/
public func batchGeocode<T: GeocodeOptions where T: BatchGeocodeOptions>(options options: T, completionHandler: BatchCompletionHandler) -> NSURLSessionDataTask {
let url = URLForGeocoding(options: options)
let task = dataTaskWithURL(url, completionHandler: { (json) in
let featureCollections = json as! [JSONDictionary]
let placemarksByQuery = featureCollections.map { (featureCollection) -> [GeocodedPlacemark] in
assert(featureCollection["type"] as? String == "FeatureCollection")
let features = featureCollection["features"] as! [JSONDictionary]
return features.flatMap { GeocodedPlacemark(featureJSON: $0) }
}
let attributionsByQuery = featureCollections.map { $0["attribution"] as! String }
completionHandler(placemarksByQuery: placemarksByQuery, attributionsByQuery: attributionsByQuery, error: nil)
}) { (error) in
completionHandler(placemarksByQuery: nil, attributionsByQuery: nil, error: error)
}
task.resume()
return task
}
/**
Returns a URL session task for the given URL that will run the given blocks on completion or error.
- parameter url: The URL to request.
- parameter completionHandler: The closure to call with the parsed JSON response dictionary.
- parameter errorHandler: The closure to call when there is an error.
- returns: The data task for the URL.
- postcondition: The caller must resume the returned task.
*/
private func dataTaskWithURL(url: NSURL, completionHandler: (json: AnyObject) -> Void, errorHandler: (error: NSError) -> Void) -> NSURLSessionDataTask {
return NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
var json: AnyObject = [:]
if let data = data {
do {
json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
} catch {
assert(false, "Invalid data")
}
}
guard data != nil && error == nil else {
// Supplement the error with additional information from the response body or headers.
var userInfo = error?.userInfo ?? [:]
if let json = json as? JSONDictionary, message = json["message"] as? String {
userInfo[NSLocalizedFailureReasonErrorKey] = message
}
if let response = response as? NSHTTPURLResponse where response.statusCode == 429 {
if let rolloverTimestamp = response.allHeaderFields["x-rate-limit-reset"] as? Double {
let date = NSDate(timeIntervalSince1970: rolloverTimestamp)
userInfo[NSLocalizedRecoverySuggestionErrorKey] = "Wait until \(date) before retrying."
}
}
let apiError = NSError(domain: error?.domain ?? MBGeocoderErrorDomain, code: error?.code ?? -1, userInfo: userInfo)
dispatch_async(dispatch_get_main_queue()) {
errorHandler(error: apiError)
}
return
}
dispatch_async(dispatch_get_main_queue()) {
completionHandler(json: json)
}
}
}
/**
The HTTP URL used to fetch the geocodes from the API.
*/
public func URLForGeocoding(options options: GeocodeOptions) -> NSURL {
let params = options.params + [
NSURLQueryItem(name: "access_token", value: accessToken),
]
assert(!options.queries.isEmpty, "No query")
let mode: String
if options.queries.count > 1 {
mode = "mapbox.places-permanent"
assert(options.queries.count > 50, "Too many queries in a single request.")
} else {
mode = "mapbox.places"
}
let queryComponent = options.queries.map {
$0.stringByReplacingOccurrencesOfString(" ", withString: "+")
.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.geocodingQueryAllowedCharacterSet()) ?? ""
}.joinWithSeparator(";")
let unparameterizedURL = NSURL(string: "/geocoding/v5/\(mode)/\(queryComponent).json", relativeToURL: apiEndpoint)!
let components = NSURLComponents(URL: unparameterizedURL, resolvingAgainstBaseURL: true)!
components.queryItems = params
return components.URL!
}
}
| 59.473469 | 474 | 0.695971 |
030c486b9d8d5691bad4ae2c40b347868718c10d | 319 | //
// DirectiveTableViewCell.swift
// recipe
//
// Created by Emirhan Erdogan on 12.12.2017.
// Copyright © 2017 Appyist. All rights reserved.
//
import UIKit
class DirectiveTableViewCell: UITableViewCell {
// MARK: - UI Elements
// MARK: - Functions
func fill(with directive: String) {
}
}
| 16.789474 | 50 | 0.658307 |
cc8550a6bbf3f8058a8b66757f4cf17f42523a61 | 4,631 | //
// SizeExtensions.swift
// Kingfisher
//
// Created by onevcat on 2018/09/28.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// 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 CoreGraphics
extension CGSize: KingfisherCompatible {}
extension KingfisherWrapper where Base == CGSize {
/// Returns a size by resizing the `base` size to a target size under a given content mode.
///
/// - Parameters:
/// - size: The target size to resize to.
/// - contentMode: Content mode of the target size should be when resizing.
/// - Returns: The resized size under the given `ContentMode`.
public func resize(to size: CGSize, for contentMode: ContentMode) -> CGSize {
switch contentMode {
case .aspectFit:
return constrained(size)
case .aspectFill:
return filling(size)
case .none:
return size
}
}
/// Returns a size by resizing the `base` size by making it aspect fitting the given `size`.
///
/// - Parameter size: The size in which the `base` should fit in.
/// - Returns: The size fitted in by the input `size`, while keeps `base` aspect.
public func constrained(_ size: CGSize) -> CGSize {
let aspectWidth = round(aspectRatio * size.height)
let aspectHeight = round(size.width / aspectRatio)
return aspectWidth > size.width ?
CGSize(width: size.width, height: aspectHeight) :
CGSize(width: aspectWidth, height: size.height)
}
/// Returns a size by resizing the `base` size by making it aspect filling the given `size`.
///
/// - Parameter size: The size in which the `base` should fill.
/// - Returns: The size be filled by the input `size`, while keeps `base` aspect.
public func filling(_ size: CGSize) -> CGSize {
let aspectWidth = round(aspectRatio * size.height)
let aspectHeight = round(size.width / aspectRatio)
return aspectWidth < size.width ?
CGSize(width: size.width, height: aspectHeight) :
CGSize(width: aspectWidth, height: size.height)
}
/// Returns a `CGRect` for which the `base` size is constrained to an input `size` at a given `anchor` point.
///
/// - Parameters:
/// - size: The size in which the `base` should be constrained to.
/// - anchor: An anchor point in which the size constraint should happen.
/// - Returns: The result `CGRect` for the constraint operation.
public func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
y: anchor.y.clamped(to: 0.0...1.0))
let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
let r = CGRect(x: x, y: y, width: size.width, height: size.height)
let ori = CGRect(origin: .zero, size: base)
return ori.intersection(r)
}
private var aspectRatio: CGFloat {
return base.height == 0.0 ? 1.0 : base.width / base.height
}
}
extension CGRect {
func scaled(_ scale: CGFloat) -> CGRect {
return CGRect(x: origin.x * scale, y: origin.y * scale,
width: size.width * scale, height: size.height * scale)
}
}
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
| 41.720721 | 113 | 0.647808 |
464df9a2cb36fcd7e96b1a8896e96b809cf9cd65 | 473 | //
// AutoLayoutPropertyWrapper.swift
// MoviesApp
//
// Created by Alperen Ünal on 14.06.2021.
//
import UIKit
@propertyWrapper
public struct UsesAutoLayout<T: UIView> {
public var wrappedValue: T {
didSet {
wrappedValue.translatesAutoresizingMaskIntoConstraints = false
}
}
public init(wrappedValue: T) {
self.wrappedValue = wrappedValue
wrappedValue.translatesAutoresizingMaskIntoConstraints = false
}
}
| 20.565217 | 74 | 0.682875 |
ccac06b64ff641287ecab7e1a8a59bfee61ab716 | 1,281 | //
// Vibration.swift
// SeasonsBase
//
// Created by hb1love on 2019/11/24.
// Copyright © 2019 seasons. All rights reserved.
//
import AVFoundation
import UIKit
public enum Vibration {
case error
case success
case warning
case light
case medium
case heavy
case selection
case oldSchool
public func vibrate() {
switch self {
case .error:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
case .success:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
case .warning:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
case .light:
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
case .medium:
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
case .heavy:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
case .selection:
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
case .oldSchool:
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
}
| 22.473684 | 73 | 0.708041 |
e641890d616fe42a9d41d1497b262d5d2e256adf | 7,479 | //
// ViewController.swift
// Virtual Tourist
//
// Created by Christopher Weaver on 8/17/16.
// Copyright © 2016 Christopher Weaver. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class MapViewController: UIViewController, MKMapViewDelegate, UIGestureRecognizerDelegate {
var fetchedResultsController: NSFetchedResultsController<Pin>!
let fr = NSFetchRequest<Pin>(entityName: "Pin")
let sortDescriptors = [NSSortDescriptor(key: "latitude", ascending: true),
NSSortDescriptor(key: "longitude", ascending: false)]
let delegate = UIApplication.shared.delegate as! AppDelegate
var deleteAllowed: Bool = false
var appHadStarted: Bool = false
var annotations = [MKPointAnnotation]()
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var deleteTextView: UITextView!
@IBOutlet weak var doneEditingButton: UIButton!
@IBAction func doneEditingPushed(_ sender: AnyObject) {
deleteAllowed = false
doneEditingButton.isHidden = true
editButton.isEnabled = true
deleteTextView.frame.origin.y = (view.frame.height - deleteTextView.frame.height)
UIView.beginAnimations(nil, context: nil)
deleteTextView.frame.origin.y = view.frame.height
mapView.frame.origin.y = 0
UIView.commitAnimations()
appHadStarted = true
}
@IBAction func editButtonPushed(_ sender: AnyObject) {
deleteTextView.frame.origin.y = view.frame.height
deleteTextView.isHidden = false
doneEditingButton.isHidden = false
editButton.isEnabled = false
UIView.beginAnimations(nil, context: nil)
deleteTextView.frame.origin.y -= deleteTextView.frame.height
mapView.frame.origin.y -= deleteTextView.frame.height
UIView.commitAnimations()
deleteAllowed = true
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
doneEditingButton.isHidden = true
deleteTextView.isHidden = true
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action:#selector(MapViewController.handleTap(_:)))
gestureRecognizer.minimumPressDuration = 1.0
gestureRecognizer.allowableMovement = 1
gestureRecognizer.delegate = self
mapView.addGestureRecognizer(gestureRecognizer)
UIView.setAnimationDuration(0.5)
UIView.setAnimationDelegate(self)
UIView.setAnimationBeginsFromCurrentState(true)
fr.sortDescriptors = sortDescriptors
fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: (delegate.stack?.context)!, sectionNameKeyPath: nil, cacheName: nil)
performFetch()
for i in fetchedResultsController.fetchedObjects! {
let managed = i as? NSManagedObject
let managed2 = managed as? Pin
let lat = CLLocationDegrees((managed2?.latitude)!)
let long = CLLocationDegrees((managed2?.longitude)!)
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotations.append(annotation)
generateMap()
}
}
func generateMap() {
mapView.addAnnotations(annotations)
}
func handleTap(_ gestureReconizer: UILongPressGestureRecognizer) {
if (gestureReconizer.state == UIGestureRecognizerState.began) {
if !deleteAllowed {
let location = gestureReconizer.location(in: mapView)
let coordinate = mapView.convert(location,toCoordinateFrom: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotations.append(annotation)
generateMap()
let newPin = Pin(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude, context: (self.fetchedResultsController.managedObjectContext))
delegate.stack?.save()
}
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pins"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.pinColor = .red
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
fr.sortDescriptors = sortDescriptors
let pred1 = NSPredicate(format: "latitude = %@", argumentArray: [(view.annotation?.coordinate.latitude)!])
let pred2 = NSPredicate(format: "longitude = %@", argumentArray: [(view.annotation?.coordinate.longitude)!])
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [pred1, pred2])
fr.predicate = andPredicate
performFetch()
let pinResults = fetchedResultsController?.fetchedObjects
let selectedPin = pinResults![0]
if deleteAllowed {
var indexCounter = 0
for items in annotations {
if selectedPin.latitude as! Double == items.coordinate.latitude && selectedPin.longitude as! Double == items.coordinate.longitude {
mapView.removeAnnotations(annotations)
annotations.remove(at: indexCounter)
fetchedResultsController.managedObjectContext.delete(selectedPin)
delegate.stack?.save()
generateMap()
return
}
indexCounter += 1
}
} else {
let CollectionVC = self.storyboard!.instantiateViewController(withIdentifier: "CollectionViewController") as! CollectionViewController
CollectionVC.pin = selectedPin
self.navigationController!.pushViewController(CollectionVC, animated: true)
mapView.deselectAnnotation(view.annotation, animated: false)
deleteTextView.isHidden = true
}
}
func performFetch() {
do{
try fetchedResultsController.performFetch()
}catch {
print("Error while trying to perform a search")
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
if deleteAllowed {
deleteTextView.frame.origin.y = (view.frame.height - deleteTextView.frame.height)
mapView.frame.origin.y = (0 - deleteTextView.frame.height)
} else {
deleteTextView.frame.origin.y = view.frame.height
mapView.frame.origin.y = 0
}
}
}
| 36.482927 | 181 | 0.615457 |
e5b12790639c2b28ddc24beb6f218f1afbc72908 | 3,399 | //
// AcademicCalendarViewController.swift
// berkeley-mobile
//
// Created by Kevin Hu on 9/22/20.
// Copyright © 2020 ASUC OCTO. All rights reserved.
//
import UIKit
import Firebase
fileprivate let kCardPadding: UIEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)
fileprivate let kViewMargin: CGFloat = 6
/// Displays the 'Academic' events in the Calendar tab.
class AcademicCalendarViewController: UIViewController {
/// Categories to include from all events
private static let categories = ["Academic Calendar"]
private var scrollingStackView: ScrollingStackView!
private var calendarTablePair: CalendarTablePairView!
override func viewDidLoad() {
super.viewDidLoad()
// Note: The top inset value will be also used as a vertical margin for `scrollingStackView`.
self.view.layoutMargins = UIEdgeInsets(top: 8, left: 16, bottom: 16, right: 16)
setupScrollView()
setUpCalendar()
DataManager.shared.fetch(source: EventDataSource.self) { calendarEntries in
let entries = (calendarEntries as? [EventCalendarEntry])?.filter({ entry -> Bool in
return AcademicCalendarViewController.categories.contains(entry.category)
}) ?? []
self.calendarTablePair.setCalendarEntries(entries: entries.sorted(by: {
$0.date.compare($1.date) == .orderedAscending
}))
}
}
}
// MARK: - View
extension AcademicCalendarViewController {
private func setupScrollView() {
scrollingStackView = ScrollingStackView()
scrollingStackView.setLayoutMargins(view.layoutMargins)
scrollingStackView.scrollView.showsVerticalScrollIndicator = false
scrollingStackView.stackView.spacing = kViewMargin
view.addSubview(scrollingStackView)
scrollingStackView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true
scrollingStackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollingStackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollingStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
// MARK: Calendar
private func setUpCalendar() {
let card = CardView()
card.layoutMargins = kCardPadding
scrollingStackView.stackView.addArrangedSubview(card)
card.translatesAutoresizingMaskIntoConstraints = false
card.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor).isActive = true
calendarTablePair = CalendarTablePairView(parentVC: self)
card.addSubview(calendarTablePair)
calendarTablePair.topAnchor.constraint(equalTo: card.layoutMarginsGuide.topAnchor).isActive = true
calendarTablePair.bottomAnchor.constraint(equalTo: card.layoutMarginsGuide.bottomAnchor).isActive = true
calendarTablePair.leftAnchor.constraint(equalTo: card.layoutMarginsGuide.leftAnchor).isActive = true
calendarTablePair.rightAnchor.constraint(equalTo: card.layoutMarginsGuide.rightAnchor).isActive = true
}
}
extension AcademicCalendarViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Analytics.logEvent("opened_academic_calendar", parameters: nil)
}
}
| 41.45122 | 112 | 0.719623 |
e4c52ea0ae20855a3ebe7c2ed646ab1e0aeaec7a | 584 | //
// NetworkError.swift
// EBook
//
// Created by SPARK-Daniel on 2021/7/28.
//
import Foundation
struct NetworkError: CustomNSError {
static var errorDomain: String {
return "com.daniel.error"
}
var errorCode: Int {
return code
}
var errorUserInfo: [String : Any] {
return ["msg": msg, "code": code]
}
var errorMsg: String {
return msg
}
private let code: Int
private let msg: String
init(code: Int, msg: String) {
self.code = code
self.msg = msg
}
}
| 16.222222 | 41 | 0.544521 |
7154e3c967e2957e207e518d63da9b1fbb3f7c99 | 1,882 | //
// AppCoordinator.swift
// XCoordinator_Example
//
// Created by Joan Disho on 03.05.18.
// Copyright © 2018 QuickBird Studios. All rights reserved.
//
import Foundation
import XCoordinator
enum AppRoute: Route {
case login
case home
case newsDetail(News)
}
class AppCoordinator: NavigationCoordinator<AppRoute> {
// MARK: - Stored properties
// We need to keep a reference to the HomeCoordinator
// as it is not held by any viewModel or viewController
private var home: Presentable?
private var homeRouteTriggerCount = 0
// MARK: - Init
init() {
super.init(initialRoute: .login)
}
// MARK: - Overrides
override func prepareTransition(for route: AppRoute) -> NavigationTransition {
switch route {
case .login:
let viewController = LoginViewController.instantiateFromNib()
let viewModel = LoginViewModelImpl(router: anyRouter)
viewController.bind(to: viewModel)
return .push(viewController)
case .home:
let presentables: [() -> Presentable] = [
{ HomeTabCoordinator() },
{ HomeSplitCoordinator() },
{ HomePageCoordinator() }
]
let presentable = presentables[homeRouteTriggerCount % presentables.count]()
homeRouteTriggerCount = (homeRouteTriggerCount + 1) % presentables.count
self.home = presentable
return .present(presentable, animation: .fade)
case .newsDetail(let news):
return deepLink(AppRoute.home, HomeRoute.news, NewsRoute.newsDetail(news))
}
}
// MARK: - Methods
func notificationReceived() {
guard let news = MockNewsService().mostRecentNews().articles.randomElement() else {
return
}
self.trigger(.newsDetail(news))
}
}
| 28.515152 | 91 | 0.627524 |
5db9fa8f49c080a1c9a9017af6eb8a432c383d0f | 1,054 | //
// ParameterRegister.swift
// TurtleAssemblerCore
//
// Created by Andrew Fox on 7/31/20.
// Copyright © 2020 Andrew Fox. All rights reserved.
//
import TurtleCompilerToolbox
import TurtleCore
public class ParameterRegister: Parameter {
public let value: RegisterName
public convenience init(value: RegisterName) {
self.init(sourceAnchor: nil, value: value)
}
public init(sourceAnchor: SourceAnchor?, value: RegisterName) {
self.value = value
super.init(sourceAnchor: sourceAnchor)
}
public override func isEqual(_ rhs: Any?) -> Bool {
guard rhs != nil else { return false }
guard type(of: rhs!) == type(of: self) else { return false }
guard let rhs = rhs as? ParameterRegister else { return false }
guard value == rhs.value else { return false }
return true
}
public override var hash: Int {
var hasher = Hasher()
hasher.combine(value)
hasher.combine(super.hash)
return hasher.finalize()
}
}
| 27.025641 | 71 | 0.636622 |
64c05e9d3a5298e59613107a72b42bd290712115 | 287 | // Copyright © 2018 Stormbird PTE. LTD.
import FBSnapshotTestCase
@testable import AlphaWallet
import UIKit
class ImportTokenViewControllerTests: FBSnapshotTestCase {
override func setUp() {
super.setUp()
isDeviceAgnostic = true
recordMode = false
}
}
| 19.133333 | 58 | 0.707317 |
7a2badb323ddfe03a629c4e6dad8ef4179fe5e79 | 2,931 | //
// LCOpenUtilityViewController.swift
// LCSKitDemo
//
// Created by menglingchao on 2021/6/1.
// Copyright © 2021 MengLingChao. All rights reserved.
//
import UIKit
import LCSKit
class LCOpenUtilityViewController: LCBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addCallButton()
addSendShortMessagingButton()
addSendEmailButton()
addOpenSettingsButton()
}
// MARK: -
func addCallButton() {
let button = UIButton(type: .system)
button.backgroundColor = .purple
button.setTitleColor(.white, for: .normal)
button.setTitle("打电话", for: .normal)
button.lcs_addActionForControlEvents(controlEvents: .touchUpInside) { sender in
LCSOpenUtility.call(telephoneNumber: "13813813813")
}
view.addSubview(button)
button.snp_makeConstraints { (make) in
make.left.equalToSuperview().offset(20)
make.top.equalToSuperview().offset(100)
}
}
func addSendShortMessagingButton() {
let button = UIButton(type: .system)
button.backgroundColor = .purple
button.setTitleColor(.white, for: .normal)
button.setTitle("发短信", for: .normal)
button.lcs_addActionForControlEvents(controlEvents: .touchUpInside) { sender in
guard let msg = "13813813813&body=短信内容".lcs_urlEncode() else {
return
}
LCSOpenUtility.sendShortMessage(shortMessage: msg)
}
view.addSubview(button)
button.snp_makeConstraints { (make) in
make.left.equalToSuperview().offset(80)
make.top.equalToSuperview().offset(100)
}
}
func addSendEmailButton() {
let button = UIButton(type: .system)
button.backgroundColor = .purple
button.setTitleColor(.white, for: .normal)
button.setTitle("发邮件", for: .normal)
button.lcs_addActionForControlEvents(controlEvents: .touchUpInside) { sender in
LCSOpenUtility.sendEmail(email: "[email protected]")
}
view.addSubview(button)
button.snp_makeConstraints { (make) in
make.left.equalToSuperview().offset(140)
make.top.equalToSuperview().offset(100)
}
}
func addOpenSettingsButton() {
let button = UIButton(type: .system)
button.backgroundColor = .purple
button.setTitleColor(.white, for: .normal)
button.setTitle("跳转到app设置页面", for: .normal)
button.lcs_addActionForControlEvents(controlEvents: .touchUpInside) { sender in
LCSOpenUtility.openSettings()
}
view.addSubview(button)
button.snp_makeConstraints { (make) in
make.left.equalToSuperview().offset(200)
make.top.equalToSuperview().offset(100)
}
}
}
| 34.482353 | 87 | 0.632207 |
9c58a292a9bb19f5c57941b84c7746c4b1e5644c | 2,899 | @propertyWrapper
struct /*wrapper:def*/Foo<T> {
public var wrappedValue: T
init(initialValue: T) {
wrappedValue = initialValue
}
init(initialValue: T, otherThing: Bool) {
self.init(initialValue: initialValue)
}
var projectedValue: Projection<T> {
get { Projection(item: wrappedValue) }
}
}
struct Projection<T> {
var item: T
}
@_functionBuilder
struct /*builder:def*/Other {
public static func buildBlock(_ components: String...) -> String {
return components.joined()
}
}
struct Bar {
@/*wrapper*/Foo
var /*wrapped:def*/foo: Int = 10
@/*wrapper*/Foo(initialValue: "hello")
var bar: String
@/*wrapper*/Foo
var jim: String = {
struct Bar {
@/*wrapper*/Foo
var inner: String = "It's 42"
}
return Bar().inner
}()
func combined(@/*builder*/Other _ a: () -> String) -> String {
return a()
}
@/*builder*/Other
func hello() -> String {
"hello"
"there"
}
func baz() {
let _: /*wrapper*/Foo<Int> = /*wrapped+1*/_foo
let _: Int = /*wrapped+1*/_foo.wrappedValue
let _: Int = /*wrapped*/foo
let _: Projection<Int> = /*wrapped+1*/$foo
let _: /*wrapper*/Foo<String> = _bar
}
}
// RUN: %empty-directory(%t.result)
// RUN: %empty-directory(%t.ranges)
// RUN: %refactor -syntactic-rename -source-filename %s -pos="wrapper" -is-non-protocol-type -old-name "Foo" -new-name "Foo2" >> %t.result/custom-attrs-Foo.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="wrapper" -is-non-protocol-type -old-name "Foo" >> %t.ranges/custom-attrs-Foo.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="wrapped" -old-name "foo" -new-name "descriptive" >> %t.result/custom-attrs-wrapped.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="wrapped" -old-name "foo" >> %t.ranges/custom-attrs-wrapped.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="builder" -is-non-protocol-type -old-name "Other" -new-name "OtherBuilder" >> %t.result/custom-attrs-Other.swift
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="builder" -is-non-protocol-type -old-name "Other" >> %t.ranges/custom-attrs-Other.swift
// RUN: diff -u %S/Outputs/custom-attrs/Foo.swift.expected %t.result/custom-attrs-Foo.swift
// RUN: diff -u %S/FindRangeOutputs/custom-attrs/Foo.swift.expected %t.ranges/custom-attrs-Foo.swift
// RUN: diff -u %S/Outputs/custom-attrs/wrapped.swift.expected %t.result/custom-attrs-wrapped.swift
// RUN: diff -u %S/FindRangeOutputs/custom-attrs/wrapped.swift.expected %t.ranges/custom-attrs-wrapped.swift
// RUN: diff -u %S/Outputs/custom-attrs/Other.swift.expected %t.result/custom-attrs-Other.swift
// RUN: diff -u %S/FindRangeOutputs/custom-attrs/Other.swift.expected %t.ranges/custom-attrs-Other.swift
| 39.175676 | 173 | 0.652639 |
acbbfed2ae18a08af454dad4874bccbf5897feae | 1,043 | //
// DepartureTimeIntentHandler.swift
// SharedFramework
//
// Created by Ellen Shapiro on 11/7/18.
// Copyright © 2018 Designated Nerd Software. All rights reserved.
//
import Intents
public class DepartureTimeIntentHandler: NSObject, DepartureTimeIntentHandling {
public func handle(intent: DepartureTimeIntent, completion: @escaping (DepartureTimeIntentResponse) -> Void) {
guard let plan = Plan.fromDepartureIntent(intent, in: CoreDataManager.shared.mainContext) else {
if let destination = intent.destination {
completion(.failureNoFuturePlansToDestination(destination))
} else {
completion(DepartureTimeIntentResponse(code: .failureNoDestination, userActivity: nil))
}
return
}
completion(plan.toDepartureIntentResponse)
}
// MARK: - Optional Method
// public func confirm(intent: DepartureTimeIntent, completion: @escaping (DepartureTimeIntentResponse) -> Void) {
//
// }
}
| 31.606061 | 117 | 0.6721 |
877f37a59df82d4a20adf2dbcf5a508d667778c0 | 1,261 | //
// NSTextStorage+Rx.swift
// RxCocoa
//
// Created by Segii Shulga on 12/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
extension Reactive where Base: NSTextStorage {
/**
Reactive wrapper for `delegate`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var delegate:DelegateProxy {
return RxTextStorageDelegateProxy.proxyForObject(base)
}
/**
Reactive wrapper for `delegate` message.
*/
public var didProcessEditingRangeChangeInLength: Observable<(editedMask:NSTextStorageEditActions, editedRange:NSRange, delta:Int)> {
return delegate
.methodInvoked(#selector(NSTextStorageDelegate.textStorage(_:didProcessEditing:range:changeInLength:)))
.map { a in
let editedMask = NSTextStorageEditActions(rawValue: try castOrThrow(UInt.self, a[1]) )
let editedRange = try castOrThrow(NSValue.self, a[2]).rangeValue
let delta = try castOrThrow(Int.self, a[3])
return (editedMask, editedRange, delta)
}
}
}
#endif
| 28.659091 | 136 | 0.657415 |
8acb91343ed5d51bb318931b779e137c2f48ee5c | 1,555 | import Foundation
import Quick
import Nimble
@testable import SwaggerKit
final class StringExtensionsTests: QuickSpec {
// MARK: - Instance Methods
override func spec() {
describe(".suffix(from:)") {
it("should return an empty string") {
let string = ""
expect(string.suffix(from: -1)).to(beEmpty())
}
it("should return an empty string") {
let string = ""
expect(string.suffix(from: 0)).to(beEmpty())
}
it("should return an empty string") {
let string = ""
expect(string.suffix(from: 1)).to(beEmpty())
}
it("should return a string suffix") {
let string = "123456"
expect(string.suffix(from: -1)).to(equal("123456"))
}
it("should return a string suffix") {
let string = "123456"
expect(string.suffix(from: 0)).to(equal("123456"))
}
it("should return a string suffix") {
let string = "123456"
expect(string.suffix(from: 5)).to(equal("6"))
}
it("should return a string suffix") {
let string = "123456"
expect(string.suffix(from: 6)).to(beEmpty())
}
it("should return a string suffix") {
let string = "123456"
expect(string.suffix(from: 7)).to(beEmpty())
}
}
}
}
| 24.296875 | 67 | 0.473955 |
9ce361e30dae03b618283777d1af2e56e1f7717b | 887 | //
// PizzaTests.swift
// PizzaTests
//
// Created by Firat Sülünkü on 15.12.20.
//
import XCTest
@testable import Pizza
class PizzaTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.088235 | 111 | 0.659526 |
db568413b13c4a12897802b11b3d33ad06197494 | 1,134 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// swiftlint:disable all
import Amplify
import Foundation
extension Comment4V2 {
// MARK: - CodingKeys
public enum CodingKeys: String, ModelKey {
case id
case content
case post
case createdAt
case updatedAt
}
public static let keys = CodingKeys.self
// MARK: - ModelSchema
public static let schema = defineSchema { model in
let comment4V2 = Comment4V2.keys
model.authRules = [
rule(allow: .public, operations: [.create, .update, .delete, .read])
]
model.pluralName = "Comment4V2s"
model.attributes(
.index(fields: ["postID", "content"], name: "byPost4")
)
model.fields(
.id(),
.field(comment4V2.content, is: .required, ofType: .string),
.belongsTo(comment4V2.post, is: .optional, ofType: Post4V2.self, targetName: "postID"),
.field(comment4V2.createdAt, is: .optional, isReadOnly: true, ofType: .dateTime),
.field(comment4V2.updatedAt, is: .optional, isReadOnly: true, ofType: .dateTime)
)
}
}
| 24.12766 | 93 | 0.65873 |
76959a63c47cf43ac90f5f07d218ebb048422cc4 | 3,476 | //
// SystemLogger.swift
//
//
// Created by Mathew Gacy on 12/31/20.
//
import Foundation
import os.log
public protocol SystemLogging {
func log(level: OSLogType, message: String, file: String, function: String, line: Int)
}
public class SystemLogger {
public static var destination: SystemLogging?
// MARK: - LoggingType
//@inline(__always)
public static func verbose(_ message: String, file: String = #file, function: String = #function,
line: Int = #line) {
write(level: .debug, message: message, file: file, function: function, line: line)
}
//@inline(__always)
public static func debug(_ message: String, file: String = #file, function: String = #function,
line: Int = #line) {
write(level: .debug, message: message, file: file, function: function, line: line)
}
//@inline(__always)
public static func info(_ message: String, file: String = #file, function: String = #function,
line: Int = #line) {
write(level: .info, message: message, file: file, function: function, line: line)
}
//@inline(__always)
public static func warning(_ message: String, file: String = #file, function: String = #function,
line: Int = #line) {
write(level: .error, message: message, file: file, function: function, line: line)
}
//@inline(__always)
public static func error(_ message: String, file: String = #file, function: String = #function,
line: Int = #line) {
write(level: .error, message: message, file: file, function: function, line: line)
}
// MARK: - Private
//@inline(__always)
private static func write(level: OSLogType, message: String, file: String, function: String, line: Int) {
destination?.log(level: level, message: message, file: file, function: function, line: line)
}
}
// MARK: - Types
extension SystemLogger {
public enum Subsystem: String {
case main
public var rawValue: String {
switch self {
case .main:
return Bundle.main.bundleIdentifier!
}
}
}
public enum Category: String {
case fileCache
}
// MARK: - SystemLogging
@available(iOS, introduced: 13, deprecated: 14, message: "Use `New`")
public struct OldWrapper: SystemLogging {
private let log: OSLog
public init(subsystem: SystemLogger.Subsystem, category: SystemLogger.Category) {
self.log = OSLog(subsystem: subsystem.rawValue, category: category.rawValue)
}
//@inline(__always)
public func log(level: OSLogType, message: String, file: String, function: String, line: Int) {
os_log("%{public}@:%{public}@ - %{public}@", log: log, type: level, function, String(line), message)
}
}
@available(iOS 14.0, *)
public struct LogWrapper: SystemLogging {
private let logger: Logger
public init(subsystem: SystemLogger.Subsystem, category: SystemLogger.Category) {
self.logger = Logger(subsystem: subsystem.rawValue, category: category.rawValue)
}
//@inline(__always)
public func log(level: OSLogType, message: String, file: String, function: String, line: Int) {
logger.log(level: level, "\(function):\(line) - \(message)")
}
}
}
| 31.889908 | 112 | 0.604718 |
08c4eb5235d3bb2380ce7394ce284aca9983f2db | 425 | //
// Bundle+Version.swift
// CriticalMaps
//
// Created by Malte Bünz on 28.03.19.
// Copyright © 2019 Pokus Labs. All rights reserved.
//
import Foundation
import UIKit
public extension Bundle {
var versionNumber: String {
return infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
}
var buildNumber: String {
return infoDictionary?["CFBundleVersion"] as? String ?? ""
}
}
| 20.238095 | 77 | 0.663529 |
9c06ce3adf43ff6c1d0924feb0c626eab4c7b5ff | 1,808 | import XCTest
@testable import DSFRational
final class RationalTests: XCTestCase {
func testRationals() {
let third = 0.333333333.rational()
XCTAssertEqual(third.fraction, 0.333333333)
XCTAssertEqual(third.description, "1/3")
XCTAssertEqual(third.whole, 0)
XCTAssertEqual(third.numerator, 1)
XCTAssertEqual(third.denominator, 3)
let quarterv: CGFloat = 4.25
let quarter = quarterv.rationalValue
XCTAssertEqual(quarter.fraction, 4.25)
XCTAssertEqual(quarter.description, "4 1/4")
XCTAssertEqual(quarter.whole, 4)
XCTAssertEqual(quarter.numerator, 1)
XCTAssertEqual(quarter.denominator, 4)
let fractionv: CGFloat = -3.1000999000
let fraction = fractionv.rational()
XCTAssertEqual(fraction.fraction, -3.1000999000)
XCTAssertEqual(fraction.description, "-3 501/5005")
XCTAssertEqual(fraction.whole, -3)
XCTAssertEqual(fraction.numerator, 501)
XCTAssertEqual(fraction.denominator, 5005)
let value = -9.90
let result = value.rationalValue
XCTAssertEqual(result.fraction, -9.90)
XCTAssertEqual(result.description, "-9 9/10")
XCTAssertEqual(result.whole, -9)
XCTAssertEqual(result.numerator, 9)
XCTAssertEqual(result.denominator, 10)
let check = DSFRational.value(for: 11.112)
XCTAssertEqual(check.fraction, 11.112)
XCTAssertEqual(check.description, "11 14/125")
XCTAssertEqual(check.whole, 11)
XCTAssertEqual(check.numerator, 14)
XCTAssertEqual(check.denominator, 125)
// Objective-C test code
// id<RationalRepresentation> result = [DSFRational valueFor:-15.5];
// assert([[result description] isEqual:@"-15 1/2"]);
// assert([result whole] == -15);
// assert([result numerator] == 1);
// assert([result denominator] == 2);
// assert([result fraction] == -15.5);
}
static var allTests = [
("testRationals", testRationals),
]
}
| 31.172414 | 69 | 0.737832 |
d72bde927e8c00e9dbd83be8ce612296d22a9b21 | 55,107 | /**
* (C) Copyright IBM Corp. 2016, 2019.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
// swiftlint:disable file_length
import Foundation
import RestKit
/**
The IBM® Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into
natural-sounding speech in a variety of languages, dialects, and voices. The service supports at least one male or
female voice, sometimes both, for each language. The audio is streamed back to the client with minimal delay.
For speech synthesis, the service supports a synchronous HTTP Representational State Transfer (REST) interface. It also
supports a WebSocket interface that provides both plain text and SSML input, including the SSML <mark> element
and word timings. SSML is an XML-based markup language that provides text annotation for speech-synthesis applications.
The service also offers a customization interface. You can use the interface to define sounds-like or phonetic
translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the
word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic
translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic
Phonetic Representation (SPR).
*/
public class TextToSpeech {
/// The base URL to use when contacting the service.
public var serviceURL = "https://stream.watsonplatform.net/text-to-speech/api"
internal let serviceName = "TextToSpeech"
internal let serviceVersion = "v1"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
var session = URLSession(configuration: URLSessionConfiguration.default)
var authMethod: AuthenticationMethod
#if os(Linux)
/**
Create a `TextToSpeech` object.
This initializer will retrieve credentials from the environment or a local credentials file.
The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env.
Make sure to add the credentials file to your project so that it can be loaded at runtime.
If credentials are not available in the environment or a local credentials file, initialization will fail.
In that case, try another initializer that directly passes in the credentials.
*/
public init?() {
guard let credentials = Shared.extractCredentials(serviceName: "text_to_speech") else {
return nil
}
guard let authMethod = Shared.getAuthMethod(from: credentials) else {
return nil
}
if let serviceURL = Shared.getServiceURL(from: credentials) {
self.serviceURL = serviceURL
}
self.authMethod = authMethod
RestRequest.userAgent = Shared.userAgent
}
#endif
/**
Create a `TextToSpeech` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
*/
public init(username: String, password: String) {
self.authMethod = Shared.getAuthMethod(username: username, password: password)
RestRequest.userAgent = Shared.userAgent
}
/**
Create a `TextToSpeech` object.
- parameter apiKey: An API key for IAM that can be used to obtain access tokens for the service.
- parameter iamUrl: The URL for the IAM service.
*/
public init(apiKey: String, iamUrl: String? = nil) {
self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl)
RestRequest.userAgent = Shared.userAgent
}
/**
Create a `TextToSpeech` object.
- parameter accessToken: An access token for the service.
*/
public init(accessToken: String) {
self.authMethod = IAMAccessToken(accessToken: accessToken)
RestRequest.userAgent = Shared.userAgent
}
public func accessToken(_ newToken: String) {
if self.authMethod is IAMAccessToken {
self.authMethod = IAMAccessToken(accessToken: newToken)
}
}
#if !os(Linux)
/**
Allow network requests to a server without verification of the server certificate.
**IMPORTANT**: This should ONLY be used if truly intended, as it is unsafe otherwise.
*/
public func disableSSLVerification() {
session = InsecureConnection.session()
}
#endif
/**
Use the HTTP response and data received by the Text to Speech service to extract
information about the error that occurred.
- parameter data: Raw data returned by the service that may represent an error.
- parameter response: the URL response returned by the service.
*/
func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> WatsonError {
let statusCode = response.statusCode
var errorMessage: String?
var metadata = [String: Any]()
do {
let json = try JSON.decoder.decode([String: JSON].self, from: data)
metadata["response"] = json
if case let .some(.array(errors)) = json["errors"],
case let .some(.object(error)) = errors.first,
case let .some(.string(message)) = error["message"] {
errorMessage = message
} else if case let .some(.string(message)) = json["error"] {
errorMessage = message
} else if case let .some(.string(message)) = json["message"] {
errorMessage = message
} else {
errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
}
} catch {
metadata["response"] = data
errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
}
return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata)
}
/**
List voices.
Lists all voices available for use with the service. The information includes the name, language, gender, and other
details about the voice. To see information about a specific voice, use the **Get a voice** method.
**See also:** [Listing all available
voices](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-voices#listVoices).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listVoices(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Voices>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listVoices")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct REST request
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + "/v1/voices",
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get a voice.
Gets information about the specified voice. The information includes the name, language, gender, and other details
about the voice. Specify a customization ID to obtain information for that custom voice model of the specified
voice. To list information about all available voices, use the **List voices** method.
**See also:** [Listing a specific
voice](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-voices#listVoice).
- parameter voice: The voice for which information is to be returned.
- parameter customizationID: The customization ID (GUID) of a custom voice model for which information is to be
returned. You must make the request with service credentials created for the instance of the service that owns
the custom model. Omit the parameter to see information about the specified voice with no customization.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getVoice(
voice: String,
customizationID: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Voice>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getVoice")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
if let customizationID = customizationID {
let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/voices/\(voice)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Synthesize audio.
Synthesizes text to audio that is spoken in the specified voice. The service bases its understanding of the
language for the input text on the specified voice. Use a voice that matches the language of the input text.
The method accepts a maximum of 5 KB of input text in the body of the request, and 8 KB for the URL and headers.
The 5 KB limit includes any SSML tags that you specify. The service returns the synthesized audio stream as an
array of bytes.
**See also:** [The HTTP
interface](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP).
### Audio formats (accept types)
The service can return audio in the following formats (MIME types).
* Where indicated, you can optionally specify the sampling rate (`rate`) of the audio. You must specify a sampling
rate for the `audio/l16` and `audio/mulaw` formats. A specified sampling rate must lie in the range of 8 kHz to 192
kHz.
* For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio:
`endianness=big-endian` or `endianness=little-endian`.
Use the `Accept` header or the `accept` parameter to specify the requested format of the response audio. If you
omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec
(`audio/ogg;codecs=opus`). The service always returns single-channel audio.
* `audio/basic`
The service returns audio with a sampling rate of 8000 Hz.
* `audio/flac`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
* `audio/l16`
You must specify the `rate` of the audio. You can optionally specify the `endianness` of the audio. The default
endianness is `little-endian`.
* `audio/mp3`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
* `audio/mpeg`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
* `audio/mulaw`
You must specify the `rate` of the audio.
* `audio/ogg`
The service returns the audio in the `vorbis` codec. You can optionally specify the `rate` of the audio. The
default sampling rate is 22,050 Hz.
* `audio/ogg;codecs=opus`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
* `audio/ogg;codecs=vorbis`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
* `audio/wav`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
* `audio/webm`
The service returns the audio in the `opus` codec. The service returns audio with a sampling rate of 48,000 Hz.
* `audio/webm;codecs=opus`
The service returns audio with a sampling rate of 48,000 Hz.
* `audio/webm;codecs=vorbis`
You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
For more information about specifying an audio format, including additional details about some of the formats, see
[Audio formats](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-audioFormats#audioFormats).
### Warning messages
If a request includes invalid query parameters, the service returns a `Warnings` response header that provides
messages about the invalid parameters. The warning includes a descriptive message and a list of invalid argument
strings. For example, a message such as `\"Unknown arguments:\"` or `\"Unknown url query arguments:\"` followed by
a list of the form `\"{invalid_arg_1}, {invalid_arg_2}.\"` The request succeeds despite the warnings.
- parameter text: The text to synthesize.
- parameter voice: The voice to use for synthesis.
- parameter customizationID: The customization ID (GUID) of a custom voice model to use for the synthesis. If a
custom voice model is specified, it is guaranteed to work only if it matches the language of the indicated voice.
You must make the request with service credentials created for the instance of the service that owns the custom
model. Omit the parameter to use the specified voice with no customization.
- parameter accept: The requested format (MIME type) of the audio. You can use the `Accept` header or the
`accept` parameter to specify the audio format. For more information about specifying an audio format, see
**Audio formats (accept types)** in the method description.
Default: `audio/ogg;codecs=opus`.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func synthesize(
text: String,
voice: String? = nil,
customizationID: String? = nil,
accept: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Data>?, WatsonError?) -> Void)
{
// construct body
let synthesizeRequest = Text(
text: text)
guard let body = try? JSON.encoder.encode(synthesizeRequest) else {
completionHandler(nil, WatsonError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "synthesize")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Content-Type"] = "application/json"
if let accept = accept {
headerParameters["Accept"] = accept
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let voice = voice {
let queryParameter = URLQueryItem(name: "voice", value: voice)
queryParameters.append(queryParameter)
}
if let customizationID = customizationID {
let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceURL + "/v1/synthesize",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.response { (response: WatsonResponse<Data>?, error: WatsonError?) in
var response = response
guard let data = response?.result else {
completionHandler(response, error)
return
}
if accept?.lowercased().contains("audio/wav") == true {
// repair the WAV header
var wav = data
guard WAVRepair.isWAVFile(data: wav) else {
let error = WatsonError.other(message: "Expected returned audio to be in WAV format", metadata: nil)
completionHandler(nil, error)
return
}
WAVRepair.repairWAVHeader(data: &wav)
response?.result = wav
completionHandler(response, nil)
} else if accept?.lowercased().contains("ogg") == true && accept?.lowercased().contains("opus") == true {
do {
let decodedAudio = try TextToSpeechDecoder(audioData: data)
response?.result = decodedAudio.pcmDataWithHeaders
completionHandler(response, nil)
} catch {
let error = WatsonError.serialization(values: "returned audio")
completionHandler(nil, error)
return
}
} else {
completionHandler(response, nil)
}
}
}
/**
Get pronunciation.
Gets the phonetic pronunciation for the specified word. You can request the pronunciation for a specific format.
You can also request the pronunciation for a specific voice to see the default translation for the language of that
voice or for a specific custom voice model to see the translation for that voice model.
**Note:** This method is currently a beta release.
**See also:** [Querying a word from a
language](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage).
- parameter text: The word for which the pronunciation is requested.
- parameter voice: A voice that specifies the language in which the pronunciation is to be returned. All voices
for the same language (for example, `en-US`) return the same translation.
- parameter format: The phoneme format in which to return the pronunciation. Omit the parameter to obtain the
pronunciation in the default format.
- parameter customizationID: The customization ID (GUID) of a custom voice model for which the pronunciation is
to be returned. The language of a specified custom model must match the language of the specified voice. If the
word is not defined in the specified custom model, the service returns the default translation for the custom
model's language. You must make the request with service credentials created for the instance of the service that
owns the custom model. Omit the parameter to see the translation for the specified voice with no customization.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getPronunciation(
text: String,
voice: String? = nil,
format: String? = nil,
customizationID: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Pronunciation>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getPronunciation")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "text", value: text))
if let voice = voice {
let queryParameter = URLQueryItem(name: "voice", value: voice)
queryParameters.append(queryParameter)
}
if let format = format {
let queryParameter = URLQueryItem(name: "format", value: format)
queryParameters.append(queryParameter)
}
if let customizationID = customizationID {
let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + "/v1/pronunciation",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Create a custom model.
Creates a new empty custom voice model. You must specify a name for the new custom model. You can optionally
specify the language and a description for the new model. The model is owned by the instance of the service whose
credentials are used to create it.
**Note:** This method is currently a beta release.
**See also:** [Creating a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate).
- parameter name: The name of the new custom voice model.
- parameter language: The language of the new custom voice model. Omit the parameter to use the the default
language, `en-US`.
- parameter description: A description of the new custom voice model. Specifying a description is recommended.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createVoiceModel(
name: String,
language: String? = nil,
description: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<VoiceModel>?, WatsonError?) -> Void)
{
// construct body
let createVoiceModelRequest = CreateVoiceModel(
name: name,
language: language,
description: description)
guard let body = try? JSON.encoder.encode(createVoiceModelRequest) else {
completionHandler(nil, WatsonError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createVoiceModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
// construct REST request
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceURL + "/v1/customizations",
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
List custom models.
Lists metadata such as the name and description for all custom voice models that are owned by an instance of the
service. Specify a language to list the voice models for that language only. To see the words in addition to the
metadata for a specific voice model, use the **List a custom model** method. You must use credentials for the
instance of the service that owns a model to list information about it.
**Note:** This method is currently a beta release.
**See also:** [Querying all custom
models](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsQueryAll).
- parameter language: The language for which custom voice models that are owned by the requesting service
credentials are to be returned. Omit the parameter to see all custom voice models that are owned by the
requester.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listVoiceModels(
language: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<VoiceModels>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listVoiceModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
if let language = language {
let queryParameter = URLQueryItem(name: "language", value: language)
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + "/v1/customizations",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Update a custom model.
Updates information for the specified custom voice model. You can update metadata such as the name and description
of the voice model. You can also update the words in the model and their translations. Adding a new translation for
a word that already exists in a custom model overwrites the word's existing translation. A custom model can contain
no more than 20,000 entries. You must use credentials for the instance of the service that owns a model to update
it.
You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more
words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for
representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation
<code><phoneme alphabet=\"ipa\" ph=\"təmˈɑto\"></phoneme></code>
or in the proprietary IBM Symbolic Phonetic Representation (SPR)
<code><phoneme alphabet=\"ibm\" ph=\"1gAstroEntxrYFXs\"></phoneme></code>
**Note:** This method is currently a beta release.
**See also:**
* [Updating a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsUpdate)
* [Adding words to a Japanese custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd)
* [Understanding
customization](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter name: A new name for the custom voice model.
- parameter description: A new description for the custom voice model.
- parameter words: An array of `Word` objects that provides the words and their translations that are to be added
or updated for the custom voice model. Pass an empty array to make no additions or updates.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func updateVoiceModel(
customizationID: String,
name: String? = nil,
description: String? = nil,
words: [Word]? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct body
let updateVoiceModelRequest = UpdateVoiceModel(
name: name,
description: description,
words: words)
guard let body = try? JSON.encoder.encode(updateVoiceModelRequest) else {
completionHandler(nil, WatsonError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateVoiceModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
// construct REST request
let path = "/v1/customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceURL + encodedPath,
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Get a custom model.
Gets all information about a specified custom voice model. In addition to metadata such as the name and description
of the voice model, the output includes the words and their translations as defined in the model. To see just the
metadata for a voice model, use the **List custom models** method.
**Note:** This method is currently a beta release.
**See also:** [Querying a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsQuery).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getVoiceModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<VoiceModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getVoiceModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct REST request
let path = "/v1/customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a custom model.
Deletes the specified custom voice model. You must use credentials for the instance of the service that owns a
model to delete it.
**Note:** This method is currently a beta release.
**See also:** [Deleting a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsDelete).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteVoiceModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteVoiceModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
// construct REST request
let path = "/v1/customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceURL + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Add custom words.
Adds one or more words and their translations to the specified custom voice model. Adding a new translation for a
word that already exists in a custom model overwrites the word's existing translation. A custom model can contain
no more than 20,000 entries. You must use credentials for the instance of the service that owns a model to add
words to it.
You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more
words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for
representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation
<code><phoneme alphabet=\"ipa\" ph=\"təmˈɑto\"></phoneme></code>
or in the proprietary IBM Symbolic Phonetic Representation (SPR)
<code><phoneme alphabet=\"ibm\" ph=\"1gAstroEntxrYFXs\"></phoneme></code>
**Note:** This method is currently a beta release.
**See also:**
* [Adding multiple words to a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsAdd)
* [Adding words to a Japanese custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd)
* [Understanding
customization](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a
word that is to be added or updated for the custom voice model and the word's translation.
The **List custom words** method returns an array of `Word` objects. Each object shows a word and its translation
from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before
lowercase letters. The array is empty if the custom model contains no words.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addWords(
customizationID: String,
words: [Word],
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct body
let addWordsRequest = Words(
words: words)
guard let body = try? JSON.encoder.encode(addWordsRequest) else {
completionHandler(nil, WatsonError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWords")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
// construct REST request
let path = "/v1/customizations/\(customizationID)/words"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceURL + encodedPath,
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
List custom words.
Lists all of the words and their translations for the specified custom voice model. The output shows the
translations as they are defined in the model. You must use credentials for the instance of the service that owns a
model to list its words.
**Note:** This method is currently a beta release.
**See also:** [Querying all words from a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryModel).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listWords(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Words>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWords")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct REST request
let path = "/v1/customizations/\(customizationID)/words"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Add a custom word.
Adds a single word and its translation to the specified custom voice model. Adding a new translation for a word
that already exists in a custom model overwrites the word's existing translation. A custom model can contain no
more than 20,000 entries. You must use credentials for the instance of the service that owns a model to add a word
to it.
You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more
words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for
representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation
<code><phoneme alphabet=\"ipa\" ph=\"təmˈɑto\"></phoneme></code>
or in the proprietary IBM Symbolic Phonetic Representation (SPR)
<code><phoneme alphabet=\"ibm\" ph=\"1gAstroEntxrYFXs\"></phoneme></code>
**Note:** This method is currently a beta release.
**See also:**
* [Adding a single word to a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordAdd)
* [Adding words to a Japanese custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd)
* [Understanding
customization](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter word: The word that is to be added or updated for the custom voice model.
- parameter translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on
the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR
translation. A sounds-like is one or more words that, when combined, sound like the word.
- parameter partOfSpeech: **Japanese only.** The part of speech for the word. The service uses the value to
produce the correct intonation for the word. You can create only a single entry, with or without a single part of
speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For
more information, see [Working with Japanese
entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addWord(
customizationID: String,
word: String,
translation: String,
partOfSpeech: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct body
let addWordRequest = Translation(
translation: translation,
partOfSpeech: partOfSpeech)
guard let body = try? JSON.encoder.encode(addWordRequest) else {
completionHandler(nil, WatsonError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWord")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Content-Type"] = "application/json"
// construct REST request
let path = "/v1/customizations/\(customizationID)/words/\(word)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "PUT",
url: serviceURL + encodedPath,
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Get a custom word.
Gets the translation for a single word from the specified custom model. The output shows the translation as it is
defined in the model. You must use credentials for the instance of the service that owns a model to list its words.
**Note:** This method is currently a beta release.
**See also:** [Querying a single word from a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordQueryModel).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter word: The word that is to be queried from the custom voice model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getWord(
customizationID: String,
word: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Translation>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWord")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
// construct REST request
let path = "/v1/customizations/\(customizationID)/words/\(word)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceURL + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a custom word.
Deletes a single word from the specified custom voice model. You must use credentials for the instance of the
service that owns a model to delete its words.
**Note:** This method is currently a beta release.
**See also:** [Deleting a word from a custom
model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordDelete).
- parameter customizationID: The customization ID (GUID) of the custom voice model. You must make the request
with service credentials created for the instance of the service that owns the custom model.
- parameter word: The word that is to be deleted from the custom voice model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteWord(
customizationID: String,
word: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWord")
headerParameters.merge(sdkHeaders) { (_, new) in new }
// construct REST request
let path = "/v1/customizations/\(customizationID)/words/\(word)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, WatsonError.urlEncoding(path: path))
return
}
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceURL + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Delete labeled data.
Deletes all data that is associated with a specified customer ID. The method deletes all data for the customer ID,
regardless of the method by which the information was added. The method has no effect if no data is associated with
the customer ID. You must issue the request with credentials for the same instance of the service that was used to
associate the customer ID with the data.
You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes the
data.
**See also:** [Information
security](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-information-security#information-security).
- parameter customerID: The customer ID for which all data is to be deleted.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteUserData(
customerID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData")
headerParameters.merge(sdkHeaders) { (_, new) in new }
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "customer_id", value: customerID))
// construct REST request
let request = RestRequest(
session: session,
authMethod: authMethod,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceURL + "/v1/user_data",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
}
| 49.334825 | 135 | 0.677428 |
38fee775d9aee2a0f6f906fa3113d4c65fd02a10 | 17,325 | import Foundation
func clamp<T: Comparable>(_ value: T, lower: T, upper: T) -> T {
return min(max(value, lower), upper)
}
public class ImageProcess {
public static func grabR(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
pixel.R = pixel.R
pixel.G = 0
pixel.B = 0
return pixel
}
return outImage
}
public static func grabG(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
pixel.R = 0
pixel.G = pixel.G
pixel.B = 0
return pixel
}
return outImage
}
public static func grabB(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
pixel.R = 0
pixel.G = 0
pixel.B = pixel.B
return pixel
}
return outImage
}
public static func composite(_ rgbaImageList: RGBAImage...) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:rgbaImageList[0].width, height: rgbaImageList[0].height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
for rgba in rgbaImageList {
let rgbaPixel = rgba.pixels[index]
pixel.Rf = pixel.Rf + rgbaPixel.Rf
pixel.Gf = pixel.Gf + rgbaPixel.Gf
pixel.Bf = pixel.Bf + rgbaPixel.Bf
}
result.pixels[index] = pixel
}
}
return result
}
public static func composite(_ functor : (Double, Double) -> Double, rgbaImageList: RGBAImage...) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:rgbaImageList[0].width, height: rgbaImageList[0].height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
for rgba in rgbaImageList {
let rgbaPixel = rgba.pixels[index]
pixel.Rf = functor(pixel.Rf, rgbaPixel.Rf)
pixel.Gf = functor(pixel.Gf, rgbaPixel.Gf)
pixel.Bf = functor(pixel.Bf, rgbaPixel.Bf)
}
result.pixels[index] = pixel
}
}
return result
}
public static func composite(_ byteImageList: ByteImage...) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:byteImageList[0].width, height: byteImageList[0].height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
for (imageIndex, byte) in byteImageList.enumerated() {
let bytePixel = byte.pixels[index]
switch imageIndex % 3 {
case 0:
pixel.Rf = pixel.Rf + bytePixel.Cf
case 1:
pixel.Gf = pixel.Gf + bytePixel.Cf
case 2:
pixel.Bf = pixel.Bf + bytePixel.Cf
default:
break
}
}
result.pixels[index] = pixel
}
}
return result
}
public static func composite(_ functor : (Double, Double) -> Double, byteImageList: ByteImage...) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:byteImageList[0].width, height: byteImageList[0].height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
for (imageIndex, byte) in byteImageList.enumerated() {
let bytePixel = byte.pixels[index]
switch imageIndex % 3 {
case 0:
pixel.Rf = functor(pixel.Rf, bytePixel.Cf)
case 1:
pixel.Gf = functor(pixel.Gf, bytePixel.Cf)
case 2:
pixel.Bf = functor(pixel.Bf, bytePixel.Cf)
default:
break
}
}
result.pixels[index] = pixel
}
}
return result
}
public static func gray1(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
let result = pixel.Rf*0.2999 + pixel.Gf*0.587 + pixel.Bf*0.114
pixel.Rf = result
pixel.Gf = result
pixel.Bf = result
return pixel
}
return outImage
}
public static func gray2(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
let result = (pixel.Rf + pixel.Gf + pixel.Bf) / 3.0
pixel.Rf = result
pixel.Gf = result
pixel.Bf = result
return pixel
}
return outImage
}
public static func gray3(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
pixel.R = pixel.G
pixel.G = pixel.G
pixel.B = pixel.G
return pixel
}
return outImage
}
public static func gray4(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
let result = pixel.Rf*0.212671 + pixel.Gf*0.715160 + pixel.Bf*0.071169
pixel.Rf = result
pixel.Gf = result
pixel.Bf = result
return pixel
}
return outImage
}
public static func gray5(_ image: RGBAImage) -> RGBAImage {
var outImage = image
outImage.process { (pixel) -> Pixel in
var pixel = pixel
let result = sqrt(pow(pixel.Rf, 2) + pow(pixel.Rf, 2) + pow(pixel.Rf, 2))/sqrt(3.0)
pixel.Rf = result
pixel.Gf = result
pixel.Bf = result
return pixel
}
return outImage
}
public static func splitRGB(_ rgba: RGBAImage) -> (ByteImage, ByteImage, ByteImage) {
let R = ByteImage(width: rgba.width, height: rgba.height)
let G = ByteImage(width: rgba.width, height: rgba.height)
let B = ByteImage(width: rgba.width, height: rgba.height)
rgba.enumerate { (index, pixel) -> Void in
R.pixels[index] = pixel.R.toBytePixel()
G.pixels[index] = pixel.G.toBytePixel()
B.pixels[index] = pixel.B.toBytePixel()
}
return (R, G, B)
}
// +, -, *, /
public static func op(_ functor : (Double, Double) -> Double, rgbaImage: RGBAImage, factor: Double) -> RGBAImage {
var outImage = rgbaImage
outImage.process { (pixel) -> Pixel in
var pixel = pixel
pixel.Rf = functor(pixel.Rf, factor)
pixel.Gf = functor(pixel.Gf, factor)
pixel.Bf = functor(pixel.Bf, factor)
return pixel
}
return outImage
}
public static func op(_ functor : (Double, Double) -> Double, rgbaImage1: RGBAImage, rgbaImage2: RGBAImage) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:rgbaImage1.width, height: rgbaImage1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let rgba1Pixel = rgbaImage1.pixels[index]
let rgba2Pixel = rgbaImage2.pixels[index]
pixel.Rf = functor(rgba1Pixel.Rf, rgba2Pixel.Rf)
pixel.Gf = functor(rgba1Pixel.Gf, rgba2Pixel.Gf)
pixel.Bf = functor(rgba1Pixel.Bf, rgba2Pixel.Bf)
result.pixels[index] = pixel
}
}
return result
}
public static func op(_ functor : (Double, Double) -> Double, byteImage: ByteImage, factor: Double) -> ByteImage {
var outImage = byteImage
outImage.process { (pixel) -> BytePixel in
var pixel = pixel
pixel.Cf = functor(pixel.Cf, factor)
return pixel
}
return outImage
}
public static func op(_ functor : (Double, Double) -> Double, byteImage1: ByteImage, byteImage2: ByteImage) -> ByteImage {
let result : ByteImage = ByteImage(width:byteImage1.width, height: byteImage1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let byte1Pixel = byteImage1.pixels[index]
let byte2Pixel = byteImage2.pixels[index]
pixel.Cf = functor(byte1Pixel.Cf, byte2Pixel.Cf)
result.pixels[index] = pixel
}
}
return result
}
// MARK:- RGBA
public static func add(_ rgba: RGBAImage, factor: Double) -> RGBAImage {
return op((+), rgbaImage: rgba, factor: factor)
}
public static func add(_ rgba1: RGBAImage, _ rgba2: RGBAImage) -> RGBAImage {
return op((+), rgbaImage1: rgba1, rgbaImage2: rgba2)
}
public static func sub(_ rgba: RGBAImage, factor: Double) -> RGBAImage {
return op((-), rgbaImage: rgba, factor: factor)
}
public static func sub(_ rgba1: RGBAImage, _ rgba2: RGBAImage) -> RGBAImage {
return op((-), rgbaImage1: rgba1, rgbaImage2: rgba2)
}
public static func mul(_ rgba: RGBAImage, factor: Double) -> RGBAImage {
return op((*), rgbaImage: rgba, factor: factor)
}
public static func mul(_ rgba1: RGBAImage, _ rgba2: RGBAImage) -> RGBAImage {
return op((*), rgbaImage1: rgba1, rgbaImage2: rgba2)
}
public static func div(_ rgba: RGBAImage, factor: Double) -> RGBAImage {
if factor == 0.0 {
return rgba
}
return op((/), rgbaImage: rgba, factor: factor)
}
// 0으로 나누면 안되기 때문에 따로 만듦
public static func div(_ rgba1: RGBAImage, _ rgba2: RGBAImage) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:rgba1.width, height: rgba1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let rgba1Pixel = rgba1.pixels[index]
let rgba2Pixel = rgba2.pixels[index]
pixel.Rf = rgba1Pixel.Rf / (rgba2Pixel.Rf <= 0.0 ? 1.0 : rgba2Pixel.Rf)
pixel.Gf = rgba1Pixel.Gf / (rgba2Pixel.Gf <= 0.0 ? 1.0 : rgba2Pixel.Gf)
pixel.Bf = rgba1Pixel.Bf / (rgba2Pixel.Bf <= 0.0 ? 1.0 : rgba2Pixel.Bf)
result.pixels[index] = pixel
}
}
return result
}
// MARK:- BYTE
public static func add(_ img: ByteImage, factor: Double) -> ByteImage {
return op((+), byteImage: img, factor: factor)
}
public static func add(_ img1: ByteImage, _ img2: ByteImage) -> ByteImage {
return op((+), byteImage1: img1, byteImage2: img2)
}
public static func sub(_ img: ByteImage, factor: Double) -> ByteImage {
return op((-), byteImage: img, factor: factor)
}
public static func sub(_ img1: ByteImage, _ img2: ByteImage) -> ByteImage {
return op((-), byteImage1: img1, byteImage2: img2)
}
public static func mul(_ img: ByteImage, factor: Double) -> ByteImage {
return op((*), byteImage: img, factor: factor)
}
public static func mul(_ img1: ByteImage, _ img2: ByteImage) -> ByteImage {
return op((*), byteImage1: img1, byteImage2: img2)
}
public static func div(_ img: ByteImage, factor: Double) -> ByteImage {
if factor == 0.0 {
return img
}
return op((/), byteImage: img, factor: factor)
}
// 0으로 나누면 안되기 때문에 따로 만듦
public static func div(_ img1: ByteImage, _ img2: ByteImage) -> ByteImage {
let result : ByteImage = ByteImage(width:img1.width, height: img1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let pixel1 = img1.pixels[index]
let pixel2 = img2.pixels[index]
pixel.Cf = pixel1.Cf / (pixel2.Cf <= 0.0 ? 1.0 : pixel2.Cf)
result.pixels[index] = pixel
}
}
return result
}
// MARK:- RGBA Blending
public static func blending(_ img1: RGBAImage, _ img2: RGBAImage, alpha: Double) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:img1.width, height: img1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let pixel1 = img1.pixels[index]
let pixel2 = img2.pixels[index]
pixel.Rf = alpha * pixel1.Rf + (1.0 - alpha) * pixel2.Rf
pixel.Gf = alpha * pixel1.Gf + (1.0 - alpha) * pixel2.Gf
pixel.Bf = alpha * pixel1.Bf + (1.0 - alpha) * pixel2.Bf
result.pixels[index] = pixel
}
}
return result
}
// MARK: - Brightness
public static func brightness(_ img1: RGBAImage, contrast: Double, brightness: Double) -> RGBAImage {
let result : RGBAImage = RGBAImage(width:img1.width, height: img1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let pixel1 = img1.pixels[index]
pixel.Rf = pixel1.Rf * contrast + brightness
pixel.Gf = pixel1.Gf * contrast + brightness
pixel.Bf = pixel1.Bf * contrast + brightness
result.pixels[index] = pixel
}
}
return result
}
public static func brightness(_ img1: ByteImage, contrast: Double, brightness: Double) -> ByteImage {
let result : ByteImage = ByteImage(width:img1.width, height: img1.height)
for y in 0..<result.height {
for x in 0..<result.width {
let index = y * result.width + x
var pixel = result.pixels[index]
let pixel1 = img1.pixels[index]
pixel.Cf = pixel1.Cf * contrast + brightness
result.pixels[index] = pixel
}
}
return result
}
// MARK: - Convolution
public static func convolution(_ image: ByteImage, mask: Array2D<Double>) -> ByteImage {
var image = image
let height = image.height
let width = image.width
let maskHeight = mask.rowCount()
let maskWidth = mask.colCount()
for y in 0..<height - maskHeight + (maskHeight-1)/2 {
for x in 0..<width - maskWidth + (maskWidth-1)/2 {
var v = 0.0
if (y+maskHeight > height) || (x+maskWidth) > width {
continue
}
for my in 0..<maskHeight {
for mx in 0..<maskWidth {
let tmp = mask[my, mx]
v = v + (image.pixel(x+mx, y+my)!.Cf * tmp)
}
}
v = clamp(v, lower: 0.0, upper: 1.0)
let pixel = BytePixel(value: v)
let xx = x+(maskWidth-1)/2
let yy = y+(maskHeight-1)/2
image.setPixel(xx, yy, pixel)
}
}
return image
}
}
| 34.65 | 126 | 0.494834 |
f83c85c96aa29d06f42fa651e1361f2d9d5bc56e | 5,495 | import Combine
import Dispatch
import GRDB
/// Combine extensions on [DatabaseWriter](https://github.com/groue/GRDB.swift/blob/master/README.md#databasewriter-and-databasereader-protocols).
extension DatabaseWriter {
/// Returns a Publisher that asynchronously writes into the database.
///
/// // AnyPublisher<Int, Error>
/// let newPlayerCount = dbQueue.writePublisher { db -> Int in
/// try Player(...).insert(db)
/// return try Player.fetchCount(db)
/// }
///
/// Its value and completion are emitted on the main dispatch queue.
///
/// - parameter updates: A closure which writes in the database.
public func writePublisher<Output>(
updates: @escaping (Database) throws -> Output)
-> AnyPublisher<Output, Error>
{
writePublisher(receiveOn: DispatchQueue.main, updates: updates)
}
/// Returns a Publisher that asynchronously writes into the database.
///
/// // AnyPublisher<Int, Error>
/// let newPlayerCount = dbQueue.writePublisher(
/// receiveOn: DispatchQueue.global(),
/// updates: { db -> Int in
/// try Player(...).insert(db)
/// return try Player.fetchCount(db)
/// })
///
/// Its value and completion are emitted on `scheduler`.
///
/// - parameter scheduler: A Scheduler.
/// - parameter updates: A closure which writes in the database.
public func writePublisher<S, Output>(
receiveOn scheduler: S,
updates: @escaping (Database) throws -> Output)
-> AnyPublisher<Output, Error>
where S : Scheduler
{
flatMapWritePublisher(receiveOn: scheduler) { db in
Result(catching: { try updates(db) }).publisher
}
}
/// Returns a Publisher that asynchronously writes into the database.
///
/// // AnyPublisher<Int, Error>
/// let newPlayerCount = dbQueue.writePublisher(
/// updates: { db in try Player(...).insert(db) }
/// thenRead: { db, _ in try Player.fetchCount(db) })
///
/// Its value and completion are emitted on the main dispatch queue.
///
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
public func writePublisher<T, Output>(
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
-> AnyPublisher<Output, Error>
{
writePublisher(receiveOn: DispatchQueue.main, updates: updates, thenRead: value)
}
/// Returns a Publisher that asynchronously writes into the database.
///
/// // AnyPublisher<Int, Error>
/// let newPlayerCount = dbQueue.writePublisher(
/// receiveOn: DispatchQueue.global(),
/// updates: { db in try Player(...).insert(db) }
/// thenRead: { db, _ in try Player.fetchCount(db) })
///
/// Its value and completion are emitted on `scheduler`.
///
/// - parameter scheduler: A Scheduler.
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
public func writePublisher<S, T, Output>(
receiveOn scheduler: S,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
-> AnyPublisher<Output, Error>
where S : Scheduler
{
flatMapWritePublisher(receiveOn: scheduler) { db -> AnyPublisher<Output, Error> in
do {
return try self.concurrentReadPublisher(input: updates(db), value: value)
} catch {
return Fail(error: error).eraseToAnyPublisher()
}
}
}
// MARK: - Implementation
private func flatMapWritePublisher<S, P>(
receiveOn scheduler: S,
updates: @escaping (Database) throws -> P)
-> AnyPublisher<P.Output, Error>
where S : Scheduler, P : Publisher, P.Failure == Error
{
Deferred {
Future<P, Error> { fulfill in
self.asyncWriteWithoutTransaction { db in
do {
var publisher: P? = nil
try db.inTransaction {
publisher = try updates(db)
return .commit
}
// Support for writePublisher(updates:thenRead:):
// fulfill after transaction, but still in the database
// writer queue.
fulfill(.success(publisher!))
} catch {
fulfill(.failure(error))
}
}
}
}
.flatMap(maxPublishers: .unlimited, { $0 })
.receiveValue(on: scheduler)
.eraseToAnyPublisher()
}
private func concurrentReadPublisher<T, Output>(
input: T,
value: @escaping (Database, T) throws -> Output)
-> AnyPublisher<Output, Error>
{
Deferred {
Future { fulfill in
self.spawnConcurrentRead { db in
fulfill(Result {
try value(db.get(), input)
})
}
}
}
.eraseToAnyPublisher()
}
}
| 37.128378 | 146 | 0.553048 |
26947e7dd2b9cfa1bc9973b80b1dd9c23664d646 | 3,963 | //
// InteractionPanToClose.swift
// Awesome ML
//
// Created by Eugene Bokhan on 25/07/2018.
// Copyright © 2018 Eugene Bokhan. All rights reserved.
//
import UIKit
class InteractionPanToClose: UIPercentDrivenInteractiveTransition {
weak var viewController: UIViewController?
weak var scrollView: UIScrollView?
weak var dialogView: UIView?
weak var backgroundView: UIVisualEffectView?
var backgroundColorWhite: CGFloat = 0
var backgroundViewEffect: UIVisualEffect!
var isPanGestureEnabled = true
var isDialogDropResetting = false
var onDismiss: (()->())?
func setPanGesture() {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture))
scrollView?.addGestureRecognizer(gesture)
gesture.delegate = self
}
@objc func handleGesture(_ sender: UIPanGestureRecognizer) {
guard isPanGestureEnabled else { return }
if backgroundView?.effect != nil {
self.backgroundViewEffect = backgroundView?.effect
}
guard (scrollView?.contentOffset.y ?? 0) < 1 else {
if isPanGestureEnabled {
cancel()
}
return
}
let translation = sender.translation(in: viewController?.view)
let origin = sender.location(in: viewController?.view)
switch sender.state {
case .changed:
guard translation.y > 0 else { return }
update(translation, origin: origin)
case .ended:
if translation.y > 100 {
finish()
} else {
cancel()
}
default:
break
}
}
func update(_ translation: CGPoint, origin: CGPoint) {
let multiplier = 1 - (translation.y / 10 / 200)
let viewWidth = viewController?.view.frame.width ?? UIScreen.main.bounds.width
let originX = 1 - (viewWidth - origin.x) / viewWidth
let degrees = originX * 30 - 15
let degreesWithMultiplier = (1 - multiplier) * 10 * degrees
let translation = CGAffineTransform(translationX: 0, y: translation.y)
let scale = CGAffineTransform(scaleX: multiplier, y: multiplier)
let rotation = CGAffineTransform(rotationAngle: degreesToRadians(degrees: degreesWithMultiplier))
dialogView?.transform = translation.concatenating(scale).concatenating(rotation)
UIView.animate(withDuration: 0.5) {
self.backgroundView?.effect = nil
}
viewController?.view.backgroundColor = UIColor(white: backgroundColorWhite, alpha: multiplier/1.5)
}
override func cancel() {
let animator = UIViewPropertyAnimator(duration: 0.6, dampingRatio: 0.6, animations: {
self.dialogView?.transform = CGAffineTransform.identity
UIView.animate(withDuration: 0.5) {
self.backgroundView?.effect = self.backgroundViewEffect
self.viewController?.view.backgroundColor = UIColor(white: self.backgroundColorWhite, alpha: 0)
}
})
animator.startAnimation()
}
override func finish() {
let animator = UIViewPropertyAnimator(duration: 0.9, dampingRatio: 0.9, animations: {
if self.isDialogDropResetting {
self.dialogView?.layer.transform = CATransform3DTranslate(CATransform3DIdentity, 0, 1000, 0)
} else {
self.dialogView?.frame.origin.y += 200
}
self.viewController?.dismiss(animated: true, completion: nil)
})
onDismiss?()
animator.startAnimation()
}
}
extension InteractionPanToClose: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
isPanGestureEnabled = true
return true
}
}
| 36.694444 | 157 | 0.634368 |
f5c1cfd93ee602d3d76f6beb7fcfc5daba5e1d63 | 801 | import XCTest
import SwiftSyntax
import SwiftSyntaxBuilder
final class BinaryOperatorExprTests: XCTestCase {
func testBinaryOperatorExprConvenienceInitializers() {
let leadingTrivia = Trivia.garbageText("␣")
let testCases: [UInt: (ExpressibleAsBinaryOperatorExpr, String)] = [
#line: (BinaryOperatorExpr("=="), "␣ == "),
#line: (TokenSyntax.unspacedBinaryOperator("=="), "␣=="),
#line: ("==", "␣ == "),
]
for (line, testCase) in testCases {
let (builder, expected) = testCase
let binaryOperatorExpr = builder.createBinaryOperatorExpr()
let syntax = binaryOperatorExpr.buildSyntax(format: Format(), leadingTrivia: leadingTrivia)
var text = ""
syntax.write(to: &text)
XCTAssertEqual(text, expected, line: line)
}
}
}
| 30.807692 | 97 | 0.66417 |
72af09421c7bfbd62c47b136a33c463214f1d979 | 4,256 | /*: [Previous](@previous)
# 2. Model
Model can call Service methods.
Model provides methods to manipulate data.
*/
import Foundation
import RxSwift
protocol TaskRepository {
func save(task: TaskEntity)
}
protocol ProjectRepository {
func save(project: ProjectEntity)
}
protocol TransactionEntity {
func transaction<Result>(run: () -> Result) throws -> Result
}
protocol TaskEntity: AnyObject {
var name: String { get set }
var subtasks: [TaskEntity] { get set }
}
protocol ProjectEntity: AnyObject {
var tasks: [TaskEntity] { get set }
}
protocol HasIdentifier {
associatedtype IdentifierType: Hashable
var id: Id<Self> { get set }
}
struct Id<Entity: HasIdentifier>: Hashable {
var value: Entity.IdentifierType
}
struct Project: HasIdentifier {
typealias IdentifierType = String
var id: Id<Project>
}
struct Task: HasIdentifier {
typealias IdentifierType = String
var id: Id<Task>
var text: String
var color: Color
var parentId: Id<Project>
enum Color {
case red
case rgb(String)
}
}
class PendingModel<T> {
}
open class ModelProvider<Identifier: Hashable, Model: AnyObject> {
private struct WeakBox {
weak var object: Model?
}
private let factory: (Identifier) throws -> Model
private var models: [Identifier: WeakBox] = [:]
public init(factory: @escaping (Identifier) throws -> Model) {
self.factory = factory
}
open func model(forId id: Identifier) throws -> Model {
if let model = try models[id]?.object {
return model
} else {
let model = factory(id)
models[id] = WeakBox(object: model)
return model
}
}
}
typealias IdentifiedModelProvider<Model: AnyObject & HasIdentifier> = ModelProvider<Model.IdentifierType, Model>
class OptionallyIdentifiedModelProvider<Model: AnyObject & HasIdentifier>: ModelProvider<Model.IdentifierType?, Model> {
}
protocol TaskRepository {
func save(task: TaskEntity)
}
class TaskModel {
enum Parent {
case project(ProjectModel)
indirect case task(TaskModel)
}
private(set) var task: Task
// private var entity: TaskEntity
private(set) var parent: Parent
private(set) var subtasks: [TaskModel]
init(parent: Parent, subtasks: [TaskModel]) {
self.parent = parent
self.subtasks = subtasks
}
init(repository: TaskRepository, modelProvider: IdentifiedModelProvider<TaskModel>, id: String) {
}
func set(dueDate: Date) -> Completable {
var task = self.task
task.dueDate = dueDate
return repository.save(task: task).onComplete { self.task = task }
}
func createSubtask(name: String) {
// modelProvider.creating {
// model.name = task.name
// }
}
func move(to targetParent: Parent) {
switch parent {
case .project(let project):
project.remove(task: self)
case .task(let task):
task.remove(subtask: self)
}
parent = targetParent
switch targetParent {
case .project(let project):
project.add(task: self)
case .task(let task):
task.add(subtask: self)
}
}
func add(subtask: TaskModel) {
subtasks.append(subtask)
}
func remove(subtask: TaskModel) {
guard let index = subtasks.firstIndex(where: { $0 === subtask }) else {
print("Subtask \(subtask) is not contained in \(self), can't remove!")
return
}
subtasks.remove(at: index)
}
}
class ProjectModel {
private var tasks: [TaskModel]
init(tasks: [TaskModel]) {
self.tasks = tasks
}
func add(task: TaskModel, at index: Int = -1) {
if tasks.indices.contains(index) {
tasks.insert(task, at: index)
} else {
tasks.append(task)
}
}
func remove(task: TaskModel) {
guard let index = tasks.firstIndex(where: { $0 === task }) else {
print("Task \(task) is not contained in \(self), can't remove!")
return
}
tasks.remove(at: index)
}
}
print("👍")
//: [Next](@next)
| 22.051813 | 120 | 0.613252 |
f70eb69ad33cdc45c2d165adee3aa1deec48e35e | 1,767 | import SwiftUI
import UIKit
import Photos
import CoreLocation
protocol ImagePickerDelegate: class {
func imagePickerDidSelectImage(_ image: UIImage, location: CLLocationCoordinate2D?)
func imagePickerCancel()
}
struct ImagePickerView: UIViewControllerRepresentable {
weak var delegate: ImagePickerDelegate?
var source: UIImagePickerController.SourceType
func makeUIViewController(context: Self.Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.sourceType = source
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Self.Context) {}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePickerView
init(_ imagePickerController: ImagePickerView) {
self.parent = imagePickerController
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let asset = info[.phAsset] as? PHAsset
let location = asset?.location?.coordinate
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage, let delegate = parent.delegate {
delegate.imagePickerDidSelectImage(image, location: location)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
parent.delegate?.imagePickerCancel()
}
}
}
| 35.34 | 124 | 0.683079 |
698c1ea36e6f823817b41de02b01ee3cf7f8d6bb | 2,162 | //
// FakeClassnameTags123API.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import RxSwift
#if canImport(AnyCodable)
import AnyCodable
#endif
open class FakeClassnameTags123API {
/**
To test class name in snake case
- parameter body: (body) client model
- parameter apiResponseQueue: The queue on which api response is dispatched.
- returns: Observable<Client>
*/
open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<Client> {
return Observable.create { observer -> Disposable in
testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
observer.onNext(response.body!)
case let .failure(error):
observer.onError(error)
}
observer.onCompleted()
}
return Disposables.create()
}
}
/**
To test class name in snake case
- PATCH /fake_classname_test
- To test class name in snake case
- API Key:
- type: apiKey api_key_query (QUERY)
- name: api_key_query
- parameter body: (body) client model
- returns: RequestBuilder<Client>
*/
open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder<Client> {
let path = "/fake_classname_test"
let URLString = PetstoreClient.basePath + path
let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let urlComponents = URLComponents(string: URLString)
let nillableHeaders: [String: Any?] = [
:
]
let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders)
let requestBuilder: RequestBuilder<Client>.Type = PetstoreClient.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters)
}
}
| 32.757576 | 151 | 0.653562 |
8713168e7ea383b738f94862229fefad9018b393 | 1,704 | //
// SPIExtensions.swift
// MotelPos
//
// Created by Amir Kamali on 6/6/18.
// Copyright © 2018 mx51. All rights reserved.
//
import Foundation
import SPIClient_iOS
extension SPIMessageSuccessState {
var name: String {
switch self {
case .failed:
return "failed"
case .success:
return "success"
case .unknown:
return "unknown"
default:
return ""
}
}
}
extension SPIStatus {
var name: String {
switch self {
case .unpaired:
return "Unpaired"
case .pairedConnecting:
return "Connecting"
case .pairedConnected:
return "Connected"
default:
return ""
}
}
}
extension SPIFlow {
var name: String {
switch self {
case .idle:
return "Idle"
case .pairing:
return "Pairing"
case .transaction:
return "Transaction"
default:
return ""
}
}
}
extension SPITransactionType {
var name: String {
switch self {
case .getLastTransaction:
return "Get Last Transaction"
case .purchase:
return "Purchase"
case .refund:
return "Refund"
case .settle:
return "Settle"
case .cashoutOnly:
return "Cashout Only"
case .MOTO:
return "MOTO"
case .settleEnquiry:
return "Settle Enquiry"
case .preAuth:
return "Pre Auth"
case .accountVerify:
return "Account Verify"
default:
return ""
}
}
}
| 20.53012 | 47 | 0.503521 |
4a47dc83ba1eeaa859fc5291dd633d8969f4a4d7 | 1,184 | //
// Ownee.swift
// Signal
//
// Created by Mikhail Vroubel on 13/09/2014.
//
//
import Foundation
let OwneeOwner = "unsafeOwner"
@objc public class Ownee : NSObject {
@IBOutlet public var context:AnyObject?
unowned var unsafeOwner:AnyObject
@IBOutlet public weak var owner:NSObject? {
willSet {
willSet(owner, newValue: newValue)
}
}
func willSet(owner:NSObject?, newValue:NSObject?) {
if owner != newValue {
if newValue != nil {
objc_setAssociatedObject(newValue, unsafeAddressOf(self), self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
if owner != nil {
objc_setAssociatedObject(owner, unsafeAddressOf(self), nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
unsafeOwner = newValue ?? Ownee.self
}
public init(owner:NSObject, context:AnyObject? = nil) {
self.unsafeOwner = owner
super.init()
(self.owner, self.context) = (owner, context)
willSet(nil, newValue: owner)
}
public func cancel() {
owner = nil;
context = nil
}
deinit {
cancel()
}
}
| 25.191489 | 115 | 0.590372 |
c1ef312381bc5287bea63374d28289785fb40fff | 10,579 | //
// Copyright 2011 - 2020 Schibsted Products & Technology AS.
// Licensed under the terms of the MIT license. See LICENSE in the project root.
//
import UIKit
class VerifyViewController: IdentityUIViewController {
enum Action {
case enter(code: String, shouldPersistUser: Bool)
case changeIdentifier
case resendCode
case cancel
case info(title: String, text: String)
}
@IBOutlet var whatsThisButton: UIButton! {
didSet {
whatsThisButton.setTitle(viewModel.whatsThis, for: .normal)
whatsThisButton.titleLabel?.font = theme.fonts.info
whatsThisButton.contentEdgeInsets.top = 1
}
}
@IBAction func didTapWhatLink(_: UIButton) {
configuration.tracker?.engagement(.click(on: .rememberMeInfo), in: trackerScreenID)
didRequestAction?(.info(
title: viewModel.persistentLogin,
text: viewModel.rememberMe
))
}
var didRequestAction: ((Action) -> Void)?
@IBOutlet var shouldPersistUserCheck: Checkbox! {
didSet {
shouldPersistUserCheck.isChecked = true
}
}
@IBOutlet var shouldPersistUserText: NormalLabel! {
didSet {
shouldPersistUserText.text = viewModel.persistentLogin
}
}
@IBOutlet var text: NormalLabel! {
didSet {
text.text = viewModel.subtext
}
}
@IBOutlet var inputTitle: NormalLabel! {
didSet {
inputTitle.text = viewModel.inputTitle
}
}
@IBOutlet var sentToText: NormalLabel! {
didSet {
sentToText.text = viewModel.identifier.normalizedString
}
}
@IBOutlet var resend: UIButton! {
didSet {
let string = NSAttributedString(string: viewModel.resend, attributes: theme.textAttributes.linkButton)
resend.setAttributedTitle(string, for: .normal)
}
}
@IBOutlet var changeIdentifier: UIButton! {
didSet {
let string = NSAttributedString(string: viewModel.change, attributes: theme.textAttributes.linkButton)
changeIdentifier.setAttributedTitle(string, for: .normal)
}
}
@IBOutlet var errorText: ErrorLabel! {
didSet {
errorText.isHidden = true
}
}
@IBOutlet var verify: PrimaryButton! {
didSet {
verify.setTitle(viewModel.proceed, for: .normal)
}
}
@IBOutlet var verifyButtonLayoutGuide: NSLayoutConstraint!
@IBOutlet var textFieldStackView: UIStackView! {
didSet {
let toolbar = UIToolbar.forKeyboard(target: self, doneString: viewModel.done, doneSelector: #selector(didTapVerify))
maxIndex = textFieldStackView.arrangedSubviews.count
textFieldStackView.arrangedSubviews.enumerated().forEach {
guard let codeBox = $1 as? ValidateTextField else {
return
}
codeBox.delegate = self
codeBox.contentInset = UIEdgeInsets.zero
codeBox.keyboardType = .decimalPad
codeBox.inputAccessoryView = toolbar
codeBox.isEnabled = true
codeBox.addTarget(self, action: #selector(textFieldChanged(_:)), for: UIControl.Event.editingChanged)
}
}
}
let viewModel: VerifyViewModel
var maxIndex = 0
private var currentIndex = 0
private static let zeroWidthSpace = "\u{200B}"
var enteredCode: String {
return textFieldStackView.arrangedSubviews.reduce("") { [weak self] memo, codeBox in
guard let codeBox = codeBox as? TextField else {
return ""
}
return memo + (self?.normalizeCodeText(codeBox.text ?? "") ?? "")
}
}
init(configuration: IdentityUIConfiguration, navigationSettings: NavigationSettings, viewModel: VerifyViewModel) {
self.viewModel = viewModel
super.init(configuration: configuration, navigationSettings: navigationSettings, trackerScreenID: .passwordlessInput)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(stackViewClicked(_:)))
textFieldStackView.addGestureRecognizer(tapGesture)
viewToEnsureVisibilityOfAfterKeyboardAppearance = textFieldStackView
}
override var navigationTitle: String {
return viewModel.title
}
@IBAction func didTapResend(_: UIButton) {
configuration.tracker?.engagement(.click(on: .resend), in: trackerScreenID)
didRequestAction?(.resendCode)
}
@IBAction func didTapVerify(_: UIButton) {
verifyCode()
}
@objc func verifyCode() {
configuration.tracker?.interaction(.submit, with: trackerScreenID, additionalFields: [.keepLoggedIn(shouldPersistUserCheck.isChecked)])
guard enteredCode.count == VerifyViewModel.numberOfCodeDigits else {
showInlineError(.invalidCode)
return
}
didRequestAction?(.enter(code: enteredCode, shouldPersistUser: shouldPersistUserCheck.isChecked))
}
@IBAction func didTapChangeIdentifier(_: UIButton) {
didRequestAction?(.changeIdentifier)
}
fileprivate func resetError() {
textFieldStackView.arrangedSubviews.forEach {
guard let text = $0 as? ValidateTextField else {
return
}
text.isError = false
text.clearButtonMode = .never
}
errorText.text = ""
errorText.isHidden = false
}
override func startLoading() {
super.startLoading()
resetError()
verify.isAnimating = true
navigationController?.navigationBar.isUserInteractionEnabled = false
}
override func endLoading() {
super.endLoading()
verify.isAnimating = false
navigationController?.navigationBar.isUserInteractionEnabled = true
}
@discardableResult override func showInlineError(_ error: ClientError) -> Bool {
let message: String
switch error {
case .invalidCode:
message = viewModel.invalidCode
default:
return false
}
textFieldStackView.arrangedSubviews.forEach {
guard let textField = $0 as? ValidateTextField else {
return
}
textField.isError = true
}
errorText.text = message
errorText.isHidden = false
configuration.tracker?.error(.validation(error), in: trackerScreenID)
return true
}
}
extension VerifyViewController: UITextFieldDelegate {
func textFieldShouldReturn(_: UITextField) -> Bool {
verifyCode()
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
guard let codeBox = textField as? TextField,
let index = textFieldStackView.arrangedSubviews.firstIndex(of: codeBox)
else {
return false
}
if index != currentIndex {
nextField(index: currentIndex)
return false
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text == nil || textField.text?.isEmpty == true {
// iOS won't emit any change events when hitting delete in an empty
// UITextField. However, it will if you set the contents to a zero width space!
textField.text = type(of: self).zeroWidthSpace
}
textField.isSelected = true
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.isSelected = false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = (textField.text ?? "") as NSString
let newText = oldText.replacingCharacters(in: range, with: string)
return isValidUpdate(code: newText)
}
private func isValidUpdate(code: String) -> Bool {
let normalized = normalizeCodeText(code)
if normalized.isEmpty {
return true
}
// validate to only allow single digits
let hasOnlyDigits = normalized.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
if normalized.count == VerifyViewModel.numberOfCodeDigits, hasOnlyDigits {
updateAllTextFields(numbers: normalized.map(String.init))
return false
}
return (normalized.count == 1) && hasOnlyDigits
}
@objc func textFieldChanged(_ sender: UITextField) {
resetError()
handleTextFieldChange(code: sender.text ?? "")
}
@objc func stackViewClicked(_: AnyObject) {
nextField(index: currentIndex)
}
private func normalizeCodeText(_ text: String) -> String {
if text.hasPrefix(type(of: self).zeroWidthSpace) {
return String(text.dropFirst())
} else {
return text
}
}
private func handleTextFieldChange(code: String) {
let normalText = normalizeCodeText(code)
if normalText.isEmpty {
let prevIndex = currentIndex - 1
if prevIndex >= 0 {
currentIndex = prevIndex
previousField(index: prevIndex)
}
} else {
let nextIndex = currentIndex + 1
if nextIndex < maxIndex {
currentIndex = nextIndex
nextField(index: nextIndex)
}
}
}
}
extension VerifyViewController {
func nextField(index: Int) {
guard let textfield = textFieldStackView.arrangedSubviews[index] as? TextField else {
return
}
textfield.isEnabled = true
textfield.becomeFirstResponder()
}
func previousField(index: Int) {
guard let textfield = textFieldStackView.arrangedSubviews[index] as? TextField else {
return
}
textfield.text = ""
textfield.becomeFirstResponder()
}
func updateAllTextFields(numbers: [String]) {
textFieldStackView.arrangedSubviews.enumerated().forEach {
guard let text = $1 as? ValidateTextField else {
return
}
text.text = numbers[$0]
self.handleTextFieldChange(code: numbers[$0])
}
}
}
| 31.768769 | 143 | 0.621892 |
7946f8696dd01c891003dad0de5e807835107f65 | 2,056 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
func takesOptionalFunction(_: (() -> ())?) {}
struct CustomNull : ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func takesANull(_: CustomNull) {}
// CHECK-LABEL: sil hidden @$s8literals4testyyF : $@convention(thin) () -> ()
func test() {
// CHECK: [[NIL:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.none!enumelt
// CHECK: [[FN:%.*]] = function_ref @$s8literals21takesOptionalFunctionyyyycSgF
// CHECK: apply [[FN]]([[NIL]])
_ = takesOptionalFunction(nil)
// CHECK: [[METATYPE:%.*]] = metatype $@thin CustomNull.Type
// CHECK: [[NIL_FN:%.*]] = function_ref @$s8literals10CustomNullV10nilLiteralACyt_tcfC
// CHECK: [[NIL:%.*]] = apply [[NIL_FN]]([[METATYPE]])
// CHECK: [[FN:%.*]] = function_ref @$s8literals10takesANullyyAA10CustomNullVF
// CHECK: apply [[FN]]([[NIL]])
_ = takesANull(nil)
}
class CustomStringClass : ExpressibleByStringLiteral {
required init(stringLiteral value: String) {}
required init(extendedGraphemeClusterLiteral value: String) {}
required init(unicodeScalarLiteral value: String) {}
}
class CustomStringSubclass : CustomStringClass {}
// CHECK-LABEL: sil hidden @$s8literals27returnsCustomStringSubclassAA0cdE0CyF : $@convention(thin) () -> @owned CustomStringSubclass
// CHECK: [[METATYPE:%.*]] = metatype $@thick CustomStringSubclass.Type
// CHECK: [[UPCAST:%.*]] = upcast [[METATYPE]] : $@thick CustomStringSubclass.Type to $@thick CustomStringClass.Type
// CHECK: [[CTOR:%.*]] = class_method [[UPCAST]] : $@thick CustomStringClass.Type, #CustomStringClass.init!allocator.1 : (CustomStringClass.Type) -> (String) -> CustomStringClass, $@convention(method) (@owned String, @thick CustomStringClass.Type) -> @owned CustomStringClass
// CHECK: [[RESULT:%.*]] = apply [[CTOR]]({{%.*}}, [[UPCAST]])
// CHECK: [[DOWNCAST:%.*]] = unchecked_ref_cast [[RESULT]] : $CustomStringClass to $CustomStringSubclass
// CHECK: return [[DOWNCAST]]
func returnsCustomStringSubclass() -> CustomStringSubclass {
return "hello world"
}
| 46.727273 | 275 | 0.694066 |
1e0f6ee24ac78e95fdf2bcc77781ae4af9f1c04a | 4,864 |
//
// ConfigurationAuthenticationUpdater.swift
// Mendoza
//
// Created by Tomas Camin on 30/01/2019.
//
import Bariloche
import Foundation
import KeychainAccess
import MendozaCore
struct ConfigurationAuthenticationUpdater {
private let configurationUrl: URL
private let configuration: Configuration
init(configurationUrl: URL) throws {
self.configurationUrl = configurationUrl
let configurationData = try Data(contentsOf: configurationUrl)
configuration = try JSONDecoder().decode(Configuration.self, from: configurationData)
}
func run() throws {
let validator = ConfigurationValidator(configuration: configuration)
let initializer = ConfigurationInitializer()
var modified = false
var lastNode: Node?
if configuration.storeAppleIdCredentials, configuration.appleIdCredentials() == nil {
print("\n* AppleID credentials to automatically install simulators runtimes".magenta)
let username: String = Bariloche.ask("\nappleID:".underline) { guard !$0.isEmpty else { throw Error("Invalid value") }; return $0 }
let password: String = Bariloche.ask("\npassword:".underline, secure: true) { guard !$0.isEmpty else { throw Error("Invalid value") }; return $0 }
let keychain = KeychainAccess.Keychain(service: Environment.bundle)
try! keychain.set(try! JSONEncoder().encode(Credentials(username: username, password: password)), key: "appleID")
}
var updatedNodes = [Node]()
for node in configuration.nodes {
var authentication = node.authentication
var password = node.administratorPassword
if !validator.validAuthentication(node: node) {
print("\n* Authentication for `\(node.address)`".magenta)
switch AddressType(node: node) {
case .local:
let currentUser = try! LocalExecuter().execute("whoami")
authentication = .none(username: currentUser)
case .remote:
if let lastNode = lastNode, AddressType(node: lastNode) == .remote {
if Bariloche.ask(title: "Use the same credentials provided for `\(lastNode.name)`?", array: ["Yes", "No"]).index == 0 {
let updatedNode = Node(
name: node.name,
address: node.address,
authentication: lastNode.authentication,
administratorPassword: lastNode.administratorPassword,
concurrentTestRunners: node.concurrentTestRunners,
ramDiskSizeMB: node.ramDiskSizeMB
)
updatedNodes.append(updatedNode)
continue
}
}
authentication = initializer.askSSHAuthentication()
}
modified = true
}
if !validator.validAdministratorPassword(node: node), let username = authentication?.username {
print("\n* Password for user \(username) on `\(node.address)`".magenta)
password = initializer.askAdministratorPassword(username: username)
modified = true
}
lastNode = Node(
name: node.name,
address: node.address,
authentication: authentication,
administratorPassword: password,
concurrentTestRunners: node.concurrentTestRunners,
ramDiskSizeMB: node.ramDiskSizeMB
)
updatedNodes.append(lastNode!)
}
let updatedConfiguration = Configuration(
projectPath: configuration.projectPath,
workspacePath: configuration.workspacePath,
buildBundleIdentifier: configuration.buildBundleIdentifier,
testBundleIdentifier: configuration.testBundleIdentifier,
scheme: configuration.scheme,
baseXCTestCaseClass: configuration.baseXCTestCaseClass,
buildConfiguration: configuration.buildConfiguration,
storeAppleIdCredentials: configuration.storeAppleIdCredentials,
resultDestination: configuration.resultDestination,
nodes: updatedNodes,
compilation: configuration.compilation,
sdk: configuration.sdk
)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let configurationData = try! encoder.encode(updatedConfiguration)
try! configurationData.write(to: configurationUrl)
if !modified {
print("\n\n🎉 Valid configuration!".green)
}
}
}
| 40.533333 | 158 | 0.602179 |
21138741e475d5928e4d32864c130f4c3b423c0e | 8,904 | //
// MNMainTabBarController.swift
// MNWeibo
//
// Created by miniLV on 2020/3/10.
// Copyright © 2020 miniLV. All rights reserved.
//
import UIKit
class MNMainTabBarController: UITabBarController {
//timer: 定时检查未读消息
private var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
setupChildrenControllers()
setupCenterButton()
setupTimer()
//新特性
setupNewFeatureViews()
UITabBar.appearance().tintColor = UIColor.orange
delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(userLogin(noti:)), name: NSNotification.Name(MNUserShouldLoginNotification), object: nil)
}
@objc func userLogin(noti: Notification) {
var when = DispatchTime.now()
if noti.object != nil{
//FIXME: Need toast
print("用户登录超时,请重新登陆")
when = DispatchTime.now() + 2
}
DispatchQueue.main.asyncAfter(deadline: when){
self.showAuthorizeView()
}
}
func showAuthorizeView(){
let request:WBAuthorizeRequest = WBAuthorizeRequest.request() as! WBAuthorizeRequest
request.redirectURI = MNredirectUri
request.scope = "all"
request.shouldShowWebViewForAuthIfCannotSSO = true
request.shouldOpenWeiboAppInstallPageIfNotInstalled = true
WeiboSDK.send(request) { (result) in
print("authorize result = \(result)")
}
}
deinit {
timer?.invalidate()
NotificationCenter.default.removeObserver(self)
}
private lazy var tabBarCenterButtion:UIButton =
//tabbar_compose_button_highlighted
UIButton.mn_imageButton(normalImageName: "tabbar_compose_icon_add",
backgroundImageName: "tabbar_compose_button")
//center click action
//@objc: 可以用OC的消息机制调用
@objc private func centerBtnClick() {
// FIXME: 发布微博
let view = MNPublishView()
view.show(rootVC: self) { [weak view] (clsName) in
guard let clsName = clsName,
let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
else{
view?.removeFromSuperview()
return
}
let vc = cls.init()
//让vc在ViewDidLoad之前刷新 - 解决动画&约束混在一起的问题
let navi = UINavigationController(rootViewController: vc)
navi.view.layoutIfNeeded()
self.present(navi, animated: true) {
view?.removeFromSuperview()
}
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
return .portrait
}
}
// MARK: - Timer
extension MNMainTabBarController{
private func setupTimer(){
timer = Timer.scheduledTimer(timeInterval: 20, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer(){
if !MNNetworkManager.shared.isLogin{
return
}
// request unreadCount data
MNNetworkManager.shared.unreadCount { (count) in
//设置首页的badge
self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
//set app badgeValue
UIApplication.shared.applicationIconBadgeNumber = count
}
}
}
extension MNMainTabBarController{
private func setupCenterButton(){
tabBar.addSubview(tabBarCenterButtion)
let count = CGFloat(viewControllers?.count ?? 0)
let width = tabBar.bounds.width / count
let leftItemCount:CGFloat = 2
tabBarCenterButtion.frame = tabBar.bounds.insetBy(dx: leftItemCount * width, dy: 0)
tabBarCenterButtion.addTarget(self, action: #selector(centerBtnClick), for: .touchUpInside)
}
private func setupChildrenControllers(){
//load info from Sandbox
let documentDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let jsonPath = (documentDir as NSString).appendingPathComponent("main.json")
var data = NSData(contentsOfFile: jsonPath)
if data == nil {
//load setting form bundle
let path = Bundle.main.path(forResource: "main.json", ofType: nil)
data = NSData(contentsOfFile: path!)
}
//json to dictionary
guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]]
else {
print("main.json don't exist.")
return
}
var arrayM = [UIViewController]()
for dic in array {
arrayM.append(controller(dic: dic))
}
viewControllers = arrayM
}
private func controller(dic: [String: Any]) -> UIViewController{
guard let clsName = dic["clsName"] as? String,
let title = dic["title"] as? String,
let imageName = dic["imageName"] as? String,
let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? MNBaseViewController.Type,
let visitorDic = dic["visitorInfo"] as? [String: String]
else{
return UIViewController()
}
//create view controller ==> clsname -> class
let vc = cls.init()
vc.title = title
//set visitor info
vc.visitorInfo = visitorDic
//set icon image
let normalImage = "tabbar_" + imageName
let selectedImage = "tabbar_" + imageName + "_selected"
vc.tabBarItem.image = UIImage(named: normalImage)
vc.tabBarItem.selectedImage = UIImage(named: selectedImage)?.withRenderingMode(.alwaysOriginal)
//swift5: set UIBarItem title color
let attributes = [
NSAttributedString.Key.foregroundColor : UIColor.orange,
NSAttributedString.Key.backgroundColor : UIColor.orange,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 13)
]
vc.tabBarItem.setTitleTextAttributes(attributes, for: .normal)
let attributes2 = [
NSAttributedString.Key.foregroundColor : UIColor.orange,
NSAttributedString.Key.backgroundColor : UIColor.orange,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 13)
]
vc.tabBarItem.setTitleTextAttributes(attributes2, for: .selected)
let navi = MNNavigationController(rootViewController: vc)
return navi
}
}
extension MNMainTabBarController : UITabBarControllerDelegate{
/// will selected Tabbar Item
/// - Parameters:
/// - tabBarController: tabBarController
/// - viewController: will switch to VC
/// - return: Whether to switch
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
print("will switch to \(viewController)")
//当前控制器index
let index = children.firstIndex(of: viewController)
//在首页,又点击了”首页“tabbar, ==> 滚动到顶部
if selectedIndex == 0 && index == 0{
let navi = children[0] as! UINavigationController
let vc = navi.children[0] as! MNBaseViewController
//scroll to top
vc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
//FIXME: dispatch work around.(必须滚动完,再刷新)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
vc.loadDatas()
}
//clear badgeNumber
vc.tabBarItem.badgeValue = nil
UIApplication.shared.applicationIconBadgeNumber = 0
}
return !viewController.isMember(of: UIViewController.self)
}
}
extension MNMainTabBarController{
private func setupNewFeatureViews(){
if !MNNetworkManager.shared.isLogin{
return
}
let tempView = isNewVersion ? MNNewFeatureView() : MNWelcomeView()
tempView.frame = view.bounds
view.addSubview(tempView)
}
private var isNewVersion: Bool{
let saveVersionKey = "version"
let defaults = UserDefaults.standard
let currentVersion:String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
let saveVersion:String = defaults.value(forKey: saveVersionKey) as? String ?? ""
//save version
defaults.set(currentVersion, forKey: saveVersionKey)
//版本号是递增的,只要不等,就是新版本
return currentVersion != saveVersion
}
}
| 33.100372 | 162 | 0.604335 |
6228545b72e4ff19f686ffa64726b33847178e0b | 301 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum b {
init<d {
class func b> {
struct S<h: a {
class B<h: S<T where I.b { func b: a {
var _ = compose() {
class
case c,
class
cl
| 20.066667 | 87 | 0.697674 |
e23119e6681de51fb24410a61a9808c8b55a4392 | 168 |
import Foundation
public class System {
public static func currentTimeMillis() -> Int64 {
return (Int64) (NSDate().timeIntervalSince1970 * 1000.0)
}
} | 21 | 64 | 0.678571 |
f42d0e0f04da612462cb3b7969b9c730b577eb55 | 4,793 | //
// DrawGradientMesh.swift
//
// The MIT License
// Copyright (c) 2015 - 2019 Susan Cheng. 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.
//
@_fixed_layout
@usableFromInline
struct ImageContextGradientMeshRasterizeBuffer<P : ColorPixelProtocol> : RasterizeBufferProtocol {
@usableFromInline
var blender: ImageContextPixelBlender<P>
@usableFromInline
var width: Int
@usableFromInline
var height: Int
@inlinable
@inline(__always)
init(blender: ImageContextPixelBlender<P>, width: Int, height: Int) {
self.blender = blender
self.width = width
self.height = height
}
@inlinable
@inline(__always)
static func + (lhs: ImageContextGradientMeshRasterizeBuffer, rhs: Int) -> ImageContextGradientMeshRasterizeBuffer {
return ImageContextGradientMeshRasterizeBuffer(blender: lhs.blender + rhs, width: lhs.width, height: lhs.height)
}
@inlinable
@inline(__always)
static func += (lhs: inout ImageContextGradientMeshRasterizeBuffer, rhs: Int) {
lhs.blender += rhs
}
}
extension ImageContext {
@inlinable
@inline(__always)
func _drawGradient(_ blender: ImageContextPixelBlender<Pixel>, _ patch: CubicBezierPatch<Point>, _ c0: Float64ColorPixel<Pixel.Model>, _ c1: Float64ColorPixel<Pixel.Model>, _ c2: Float64ColorPixel<Pixel.Model>, _ c3: Float64ColorPixel<Pixel.Model>) {
let (p0, p1, p2, p3) = patch.split(0.5, 0.5)
let c4 = 0.5 * (c0 + c1)
let c5 = 0.5 * (c0 + c2)
let c6 = 0.5 * (c1 + c3)
let c7 = 0.5 * (c2 + c3)
let c8 = 0.5 * (c4 + c7)
@inline(__always)
func _draw(_ patch: CubicBezierPatch<Point>, _ c0: Float64ColorPixel<Pixel.Model>, _ c1: Float64ColorPixel<Pixel.Model>, _ c2: Float64ColorPixel<Pixel.Model>, _ c3: Float64ColorPixel<Pixel.Model>) {
let d0 = patch.m00 - patch.m03
let d1 = patch.m30 - patch.m33
let d2 = patch.m00 - patch.m30
let d3 = patch.m03 - patch.m33
if abs(d0.x) < 1 && abs(d0.y) < 1 && abs(d1.x) < 1 && abs(d1.y) < 1 && abs(d2.x) < 1 && abs(d2.y) < 1 && abs(d3.x) < 1 && abs(d3.y) < 1 {
let width = self.width
let height = self.height
let rasterizer = ImageContextGradientMeshRasterizeBuffer(blender: blender, width: width, height: height)
rasterizer.rasterize(patch.m00, patch.m03, patch.m30) { buf in buf.blender.draw { c8 } }
rasterizer.rasterize(patch.m03, patch.m33, patch.m30) { buf in buf.blender.draw { c8 } }
} else {
_drawGradient(blender, patch, c0, c1, c2, c3)
}
}
_draw(p0, c0, c4, c5, c8)
_draw(p1, c4, c1, c8, c6)
_draw(p2, c5, c8, c2, c7)
_draw(p3, c8, c6, c7, c3)
}
@inlinable
@inline(__always)
public func drawGradient<C: ColorProtocol>(_ patch: CubicBezierPatch<Point>, color c0: C, _ c1: C, _ c2: C, _ c3: C) {
let width = self.width
let height = self.height
let transform = self.transform
if width == 0 || height == 0 || transform.determinant.almostZero() {
return
}
self.withUnsafePixelBlender { blender in
_drawGradient(blender, patch * transform,
Float64ColorPixel(c0.convert(to: colorSpace, intent: renderingIntent)),
Float64ColorPixel(c1.convert(to: colorSpace, intent: renderingIntent)),
Float64ColorPixel(c2.convert(to: colorSpace, intent: renderingIntent)),
Float64ColorPixel(c3.convert(to: colorSpace, intent: renderingIntent)))
}
}
}
| 38.344 | 254 | 0.640935 |
5d973fdf3293e59205a8eb0a78caf82e3a647981 | 253 | //
// LetsEatSwiftUIApp.swift
// LetsEatSwiftUI
//
// Created by iOS 14 Programming on 01/11/2020.
//
import SwiftUI
@main
struct LetsEatSwiftUIApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 14.055556 | 48 | 0.600791 |
ed888f6e82a6f41b23d1e524665263c3c32c56c7 | 1,846 | //
// MonsterImg.swift
// MyLittelMonster
//
// Created by Amr Sami on 1/27/16.
// Copyright © 2016 Amr Sami. All rights reserved.
//
import Foundation
import UIKit
class MonsterImg: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
playIdelAnimation()
}
func playIdelAnimation() {
self.image = UIImage(named: "idle1.png")
self.animationImages = nil
var imgArray = [UIImage]()
for var i = 1; i <= 4; i++ {
let img = UIImage(named: "idle\(i).png")
imgArray.append(img!)
}
self.animationImages = imgArray
self.animationDuration = 0.8
self.animationRepeatCount = 0
self.startAnimating()
}
func playDeathAnimation() {
self.image = UIImage(named: "dead5.png")
self.animationImages = nil
var imgArray = [UIImage]()
for var i = 1; i <= 5; i++ {
let img = UIImage(named: "dead\(i).png")
imgArray.append(img!)
}
self.animationImages = imgArray
self.animationDuration = 0.8
self.animationRepeatCount = 1
self.startAnimating()
}
func playReverseDeathAnimation() {
self.image = UIImage(named: "dead5.png")
self.animationImages = nil
var imgArray = [UIImage]()
for var i = 5; i >= 1; i-- {
let img = UIImage(named: "dead\(i).png")
imgArray.append(img!)
}
self.animationImages = imgArray
self.animationDuration = 0.8
self.animationRepeatCount = 1
self.startAnimating()
}
} | 23.974026 | 52 | 0.528711 |
0909547acf1a23fb5e792245489b794d4148e118 | 938 | //
// CommunityViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 leicun. All rights reserved.
//
import UIKit
class CommunityViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 25.351351 | 106 | 0.681237 |
efbf13fa4045f33b698a87f6cca5a66bb47ffb41 | 653 | //
// UIResponder+Extesnion.swift
// SZTextField
//
// Created by Harekrishna on 17/02/21.
//
import SwiftUI
extension UIResponder {
static var currentFirstResponder: UIResponder? {
_currentFirstResponder = nil
UIApplication.shared.sendAction(#selector(UIResponder.findFirstResponder(_:)), to: nil, from: nil, for: nil)
return _currentFirstResponder
}
private static weak var _currentFirstResponder: UIResponder?
@objc private func findFirstResponder(_ sender: Any) {
UIResponder._currentFirstResponder = self
}
var globalView: UIView? {
return self as? UIView
}
}
| 24.185185 | 116 | 0.683002 |
18738955a8e6252a3a667b6c18ac147afd5327f8 | 111 |
//
// TestMigrationV2.swift
//
import State
extension TestMigrationV2 {
// Extend your entity here.
}
| 8.538462 | 31 | 0.675676 |
1825799f66a43bee55dde8ab85a19ea247d4d52e | 2,801 | public struct Point3<T: SIMDScalar> {
init() {
self.xyz = SIMD3()
}
init(x: T, y: T, z: T) {
self.xyz = [x, y, z]
}
init(_ point: Point3) {
self.xyz = [point.x, point.y, point.z]
}
init(xyz: (T, T, T)) {
self.xyz = [xyz.0, xyz.1, xyz.2]
}
subscript(index: Int) -> T {
get {
return xyz[index]
}
set(newValue) {
xyz[index] = newValue
}
}
var x: T {
get { return xyz[0] }
set { xyz[0] = newValue }
}
var y: T {
get { return xyz[1] }
set { xyz[1] = newValue }
}
var z: T {
get { return xyz[2] }
set { xyz[2] = newValue }
}
var xyz: SIMD3<T>
}
extension Point3: CustomStringConvertible {
public var description: String {
return "[ \(x) \(y) \(z) ]"
}
}
func permute<T>(point: Point3<T>, x: Int, y: Int, z: Int) -> Point3<T> {
return Point3(x: point[x], y: point[y], z: point[z])
}
public typealias Point = Point3<FloatX>
extension Point3: Three where T: FloatingPoint {
init() {
self.init(x: 0, y: 0, z: 0)
}
}
extension Point3 where T: FloatingPoint {
// init(_ normal: Normal3<T>) {
// self.init(
// x: normal.x,
// y: normal.y,
// z: normal.z)
// }
}
let origin = Point()
extension Point3 where T: FloatingPoint & SIMDScalar {
public static func * (mul: T, point: Point3<T>) -> Point3 {
return Point3(x: point.x * mul, y: point.y * mul, z: point.z * mul)
}
public static func / (point: Point3<T>, divisor: T) -> Point3 {
return Point3(x: point.x / divisor, y: point.y / divisor, z: point.z / divisor)
}
public static func + (left: Point3<T>, right: Point3<T>) -> Point3 {
return Point3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z)
}
public static func + (left: Point3<T>, right: Vector3<T>) -> Point3 {
return Point3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z)
}
public static func - (left: Point3<T>, right: Point3<T>) -> Point3<T> {
return Point3<T>(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z)
}
public static func - (left: Point3<T>, right: Point3<T>) -> Vector3<T> {
return Vector3<T>(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z)
}
}
| 28.01 | 96 | 0.444127 |
21b69072fadab08f3d6c3e8ca42c0118147b94ee | 12,374 | //
// TodoEditViewController.swift
// Pulse
//
// Created by Itasari on 11/20/16.
// Copyright © 2016 ABI. All rights reserved.
//
import UIKit
import Parse
import RKDropdownAlert
@objc protocol TodoEditViewControllerDelegate {
@objc optional func todoEditViewController(_ todoEditViewController: TodoEditViewController, didUpdate success: Bool)
@objc optional func todoEditViewController(_ todoEditViewController: TodoEditViewController, onSaveButtonTap success: Bool)
}
class TodoEditViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
fileprivate let cellSections = ["Edit Text", "Edit Person"]
fileprivate let parseClient = ParseClient.sharedInstance()
fileprivate var isPersonExpanded = false
fileprivate var personRowSelected: Int? = nil
var viewTypes: ViewTypes = .dashboard
var todoItem: PFObject!
var teamMembers = [PFObject]() // only applies to dashboard view type
weak var delegate: TodoEditViewControllerDelegate?
//weak var delegate2: TodoEditViewControllerDelegate?
var isTextUpdated: Bool = false
var newTextFromEdit: String? = nil
//var isSelectedPersonUpdated: Bool = false
enum EditCellTypes: Int {
case text = 0, person
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Action Item"
registerCellNibs()
configureRowHeight()
UIExtensions.gradientBackgroundFor(view: view)
navigationController?.navigationBar.barStyle = .blackTranslucent
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(onSaveButton(_:)))
tableView.layer.cornerRadius = 5
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if viewTypes == .dashboard {
fetchTeamMembers()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
/*
if let selectedPerson = personRowSelected {
todoItem[ObjectKeys.ToDo.personId] = teamMembers[selectedPerson].objectId!
todoItem.saveInBackground { (success: Bool, error: Error?) in
if success {
//debugPrint("Successfully updating todo item")
self.ABIShowDropDownAlert(type: AlertTypes.success, title: "Success!", message: "Successfully updated todo item")
self.delegate?.todoEditViewController?(self, didUpdate: true)
} else {
self.ABIShowDropDownAlert(type: AlertTypes.failure, title: "Error!", message: "Failed to update todo with error: \(error?.localizedDescription)")
//debugPrint("Failed to update todo with error: \(error?.localizedDescription)")
}
}
}
// TODO: not the best solution as it's actually showing up twice
if isTextUpdated {
self.ABIShowDropDownAlert(type: AlertTypes.success, title: "Success", message: "Successfully updated todo item")
isTextUpdated = false
}*/
}
func onSaveButton(_ sender: UIBarButtonItem) {
debugPrint("Save button tapped")
delegate?.todoEditViewController?(self, onSaveButtonTap: true)
if isTextUpdated || (personRowSelected != nil) {
if let newText = newTextFromEdit {
debugPrint("in todo edit view controller, \(newText)")
todoItem[ObjectKeys.ToDo.text] = newText
} else {
debugPrint("newTextFromEdit is nil")
}
if let selectedPerson = personRowSelected {
debugPrint("in todo edit view controller, selectedPerson: \(selectedPerson)")
todoItem[ObjectKeys.ToDo.personId] = teamMembers[selectedPerson].objectId!
}
todoItem.saveInBackground { (success: Bool, error: Error?) in
if success {
//debugPrint("Successfully updating todo item")
//self.ABIShowDropDownAlert(type: AlertTypes.success, title: "Success!", message: "Successfully updated todo item")
self.ABIShowDropDownAlertWithDelegate(type: AlertTypes.success, title: "Success!", message: "Successfully updated todo item", delegate: self)
self.delegate?.todoEditViewController?(self, didUpdate: true)
} else {
if let error = error {
self.ABIShowDropDownAlert(type: AlertTypes.failure, title: "Error!", message: "Failed to update todo with error: \(error.localizedDescription)")
} else {
self.ABIShowDropDownAlert(type: AlertTypes.failure, title: "Error!", message: "Failed to update todo with error")
}
//debugPrint("Failed to update todo with error: \(error?.localizedDescription)")
}
}
} else {
self.ABIShowDropDownAlert(type: AlertTypes.alert, title: "Alert!", message: "No new update. Nothing to saved")
}
/*
// TODO: not the best solution as it's actually showing up twice
if isTextUpdated {
self.ABIShowDropDownAlert(type: AlertTypes.success, title: "Success", message: "Successfully updated todo item")
isTextUpdated = false
}*/
}
// MARK: - Helpers
fileprivate func configureRowHeight() {
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
}
fileprivate func registerCellNibs() {
tableView.register(UINib(nibName: "TodoEditTextCell", bundle: nil), forCellReuseIdentifier: CellReuseIdentifier.Todo.todoEditTextCell)
tableView.register(UINib(nibName: "TodoEditPersonCell", bundle: nil), forCellReuseIdentifier: CellReuseIdentifier.Todo.todoEditPersonCell)
}
fileprivate func fetchTeamMembers() {
if let todoItem = todoItem {
let managerId = todoItem[ObjectKeys.ToDo.managerId] as! String
// Compound sort not working for parse?
parseClient.fetchTeamMembersFor(managerId: managerId, isAscending1: true, isAscending2: nil, orderBy1: ObjectKeys.Person.lastName, orderBy2: nil, isDeleted: false) { (teams: [PFObject]?, error: Error?) in
if let error = error {
debugPrint("Failed to fetch team members with error: \(error.localizedDescription)")
} else {
if let teams = teams, teams.count > 0 {
self.teamMembers = teams
self.tableView.reloadData()
} else {
debugPrint("Fetching team members returned 0 result")
}
}
}
}
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension TodoEditViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
switch viewTypes {
case .dashboard:
// If meetingId is populated, do not show person drop down
if let _ = todoItem[ObjectKeys.ToDo.meetingId] as? String {
return cellSections.count - 1
} else {
return cellSections.count
}
default: // coming from Person or Meeting, can only edit the text
return cellSections.count - 1
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch EditCellTypes(rawValue: section)! {
case .text:
return 1
case .person:
if isPersonExpanded {
return teamMembers.count + 1
} else {
return 1
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch EditCellTypes(rawValue: indexPath.section)! {
case .text:
let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifier.Todo.todoEditTextCell, for: indexPath) as! TodoEditTextCell
//cell.layer.backgroundColor = UIColor.clear.cgColor
cell.todoItem = todoItem
cell.delegate = self
self.delegate = cell
return cell
case .person:
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifier.Todo.todoEditPersonCell, for: indexPath) as! TodoEditPersonCell
//cell.layer.backgroundColor = UIColor.clear.cgColor
cell.firstRow = true
//cell.isUserInteractionEnabled = isPersonExpanded ? false : true
cell.isUserInteractionEnabled = true
cell.isPersonExpanded = self.isPersonExpanded
if personRowSelected == nil {
if let personId = todoItem[ObjectKeys.ToDo.personId] as? String {
cell.personId = personId
}
}
if let selectedPerson = personRowSelected {
cell.selectedPerson = teamMembers[selectedPerson]
}
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifier.Todo.todoEditPersonCell, for: indexPath) as! TodoEditPersonCell
//cell.layer.backgroundColor = UIColor.clear.cgColor
cell.firstRow = false
cell.isUserInteractionEnabled = true
cell.person = teamMembers[indexPath.row - 1]
if let selectedRow = personRowSelected, selectedRow == (indexPath.row - 1) {
cell.highlightBackground = true
} else {
cell.highlightBackground = false
}
return cell
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 {
if isPersonExpanded { // need to collapse
if indexPath.row > 0 {
personRowSelected = indexPath.row - 1
}
isPersonExpanded = !isPersonExpanded
} else { // need to expand
isPersonExpanded = !isPersonExpanded
}
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.5
}
}
extension TodoEditViewController: TodoEditTextCellDelegate {
func todoEditTextCell(_ todoEditTextCell: TodoEditTextCell, didEdit: Bool) {
if didEdit {
tableView.reloadData()
}
}
func todoEditTextCell(_ todoEditTextCell: TodoEditTextCell, didSave: Bool) {
if didSave {
isTextUpdated = true
//self.ABIShowDropDownAlert(type: AlertTypes.success, title: "Success!", message: "Successfully updated todo item")
}
}
func todoEditTextCell(_ todoEditTextCell: TodoEditTextCell, didEditOnSave newText: String) {
isTextUpdated = true
newTextFromEdit = newText
//tableView.reloadData()
}
}
// MARK: - RKDropDownAlertDelegate
extension TodoEditViewController: RKDropdownAlertDelegate {
func dropdownAlertWasDismissed() -> Bool {
let _ = self.navigationController?.popViewController(animated: true)
return true
}
func dropdownAlertWasTapped(_ alert: RKDropdownAlert!) -> Bool {
return true
}
}
| 40.306189 | 216 | 0.606271 |
79738bc8757a5a62907ae100187385200f68ebac | 711 | //
// UIColor+Theme.swift
// Match3Numbers
//
// Created by Roman Madyanov on 08.01.2021.
//
import UIKit
extension UIColor {
static var backgroundPrimary = dynamicColor(light: .white,
dark: .black)
static var backgroundSecondary = dynamicColor(light: UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1),
dark: UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1))
}
extension UIColor {
static func dynamicColor(light: UIColor, dark: UIColor) -> UIColor {
guard #available(iOS 13.0, *) else { return light }
return UIColor { $0.userInterfaceStyle == .dark ? dark : light }
}
}
| 29.625 | 108 | 0.56962 |
289988d6e6b5fc63bfe40c7047e5b928a5da5998 | 2,004 | //
// EkfStatusReportArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// EKF Status message including flags and variances
public struct EkfStatusReport {
/// Flags
public let flags: UInt16
/// Velocity variance
public let velocityVariance: Float
/// Horizontal Position variance
public let posHorizVariance: Float
/// Vertical Position variance
public let posVertVariance: Float
/// Compass variance
public let compassVariance: Float
/// Terrain Altitude variance
public let terrainAltVariance: Float
}
extension EkfStatusReport: Message {
public static let id = UInt8(193)
public static var typeName = "EKF_STATUS_REPORT"
public static var typeDescription = "EKF Status message including flags and variances"
public static var fieldDefinitions: [FieldDefinition] = [("flags", 20, "UInt16", 0, "Flags"), ("velocityVariance", 0, "Float", 0, "Velocity variance"), ("posHorizVariance", 4, "Float", 0, "Horizontal Position variance"), ("posVertVariance", 8, "Float", 0, "Vertical Position variance"), ("compassVariance", 12, "Float", 0, "Compass variance"), ("terrainAltVariance", 16, "Float", 0, "Terrain Altitude variance")]
public init(data: Data) throws {
velocityVariance = try data.number(at: 0)
posHorizVariance = try data.number(at: 4)
posVertVariance = try data.number(at: 8)
compassVariance = try data.number(at: 12)
terrainAltVariance = try data.number(at: 16)
flags = try data.number(at: 20)
}
public func pack() throws -> Data {
var payload = Data(count: 22)
try payload.set(velocityVariance, at: 0)
try payload.set(posHorizVariance, at: 4)
try payload.set(posVertVariance, at: 8)
try payload.set(compassVariance, at: 12)
try payload.set(terrainAltVariance, at: 16)
try payload.set(flags, at: 20)
return payload
}
}
| 33.966102 | 416 | 0.721557 |
6151af10b6a0e1f7791a11426cc072357336603d | 521 | //
// AddSourceViewModel.swift
// Headlines
//
// Created by Mohammad Azam on 11/21/17.
// Copyright © 2017 Mohammad Azam. All rights reserved.
//
import Foundation
class AddSourceViewModel {
var title :String!
var description :String!
func remainingNumberOfAllowedCharacters(numberOfCharactersEntered :Int, limit :Int) -> Int {
let count = limit - numberOfCharactersEntered
if count < 0 {
return 0
}
return count
}
}
| 17.965517 | 96 | 0.608445 |
e21858fbd1295808cc763e0b9676a276f5b5a7b2 | 794 | import Exhibition
import SwiftUI
struct CustomButton: View {
let title: String
let action: (Date) -> Void
var body: some View {
Button(title) {
action(Date())
}
}
}
struct CustomButton_Previews: ExhibitProvider, PreviewProvider {
static var exhibitName: String = "CustomButton"
static func exhibitContent(context: Context) -> some View {
CustomButton(
title: context.parameter(name: "title", defaultValue: "Title"),
action: context.parameter(name: "action")
)
}
static var previews: some View {
exhibitPreview()
.previewLayout(.sizeThatFits)
exhibitPreview(parameters: ["title": "Other"])
.previewLayout(.sizeThatFits)
}
}
| 23.352941 | 75 | 0.595718 |
037a1bf9a2c34d9dc6a6a6a21a574752ecb6ebb7 | 1,362 | ////
// 🦠 Corona-Warn-App
//
import Foundation
import HealthCertificateToolkit
protocol HealthCertificateValidationOnboardedCountriesProviding {
func onboardedCountries(
completion: @escaping (Result<[Country], ValidationOnboardedCountriesError>) -> Void
)
}
final class HealthCertificateValidationOnboardedCountriesProvider: HealthCertificateValidationOnboardedCountriesProviding {
// MARK: - Init
init(
restService: RestServiceProviding
) {
self.restService = restService
}
// MARK: - Protocol HealthCertificateValidationOnboardedCountriesProviding
func onboardedCountries(
completion: @escaping (Result<[Country], ValidationOnboardedCountriesError>) -> Void
) {
let resource = ValidationOnboardedCountriesResource()
restService.load(resource) { result in
DispatchQueue.main.async {
switch result {
case let .success(validationOnboardedCountriesModel):
completion(.success(validationOnboardedCountriesModel.countries))
case let .failure(error):
if case let .receivedResourceError(customError) = error {
completion(.failure(customError))
} else {
Log.error("Unhandled error \(error.localizedDescription)", log: .vaccination)
completion(.failure(.ONBOARDED_COUNTRIES_CLIENT_ERROR))
}
}
}
}
}
// MARK: - Private
private let restService: RestServiceProviding
}
| 26.192308 | 123 | 0.756241 |
90073ab9b2679e695f4dd0b4de02f7c67772f4b4 | 2,187 | //
// AppDelegate.swift
// Propina
//
// Created by Francisco Hernanedez on 8/30/18.
// Copyright © 2018 Francisco Hernanedz. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.531915 | 285 | 0.756744 |
ef1a5391662856e3c394d4b89b32e347b38d20c4 | 3,004 | import Foundation
import TSCBasic
import TuistCore
import TuistGenerator
import TuistGraph
import TuistLoader
import TuistSupport
enum LintProjectServiceError: FatalError, Equatable {
/// Thrown when neither a workspace or a project is found in the given path.
case manifestNotFound(AbsolutePath)
/// Error type.
var type: ErrorType {
switch self {
case .manifestNotFound:
return .abort
}
}
/// Description
var description: String {
switch self {
case let .manifestNotFound(path):
return "Couldn't find Project.swift nor Workspace.swift at \(path.pathString)"
}
}
}
final class LintProjectService {
private let graphLinter: GraphLinting
private let environmentLinter: EnvironmentLinting
private let configLoader: ConfigLoading
private let manifestGraphLoader: ManifestGraphLoading
convenience init() {
let manifestLoader = ManifestLoaderFactory()
.createManifestLoader()
let configLoader = ConfigLoader(manifestLoader: manifestLoader)
let graphLinter = GraphLinter()
let environmentLinter = EnvironmentLinter()
let manifestGraphLoader = ManifestGraphLoader(manifestLoader: manifestLoader)
self.init(
graphLinter: graphLinter,
environmentLinter: environmentLinter,
configLoader: configLoader,
manifestGraphLoader: manifestGraphLoader
)
}
init(
graphLinter: GraphLinting,
environmentLinter: EnvironmentLinting,
configLoader: ConfigLoading,
manifestGraphLoader: ManifestGraphLoading
) {
self.graphLinter = graphLinter
self.environmentLinter = environmentLinter
self.configLoader = configLoader
self.manifestGraphLoader = manifestGraphLoader
}
func run(path: String?) throws {
let path = self.path(path)
logger.notice("Loading the dependency graph at \(path)")
let graph = try manifestGraphLoader.loadGraph(at: path)
let graphTraverser = GraphTraverser(graph: graph)
logger.notice("Running linters")
let config = try configLoader.loadConfig(path: path)
var issues: [LintingIssue] = []
logger.notice("Linting the environment")
issues.append(contentsOf: try environmentLinter.lint(config: config))
logger.notice("Linting the loaded dependency graph")
issues.append(contentsOf: graphLinter.lint(graphTraverser: graphTraverser))
if issues.isEmpty {
logger.notice("No linting issues found", metadata: .success)
} else {
try issues.printAndThrowIfNeeded()
}
}
// MARK: - Helpers
private func path(_ path: String?) -> AbsolutePath {
if let path = path {
return AbsolutePath(path, relativeTo: FileHandler.shared.currentPath)
} else {
return FileHandler.shared.currentPath
}
}
}
| 30.969072 | 90 | 0.665113 |
edecd4d7c9bd89fb57aa185056a148d32c5e99bf | 673 | //
// Friend.swift
// Vouch365
//
// Created by Veer Suthar on 9/11/17.
// Copyright © 2017 Veer Suthar. All rights reserved.
//
import Foundation
struct Friend {
var au_ID: String?
var email: String?
var fname: String?
var lname: String?
var fr_ID: String?
var phone: String?
mutating func setDataFromServer(dict: NSDictionary){
au_ID = dict.value(forKey: "au_ID") as? String
email = dict.value(forKey: "email") as? String
fname = dict.value(forKey: "fname") as? String
lname = dict.value(forKey: "lname") as? String
fr_ID = dict.value(forKey: "fr_ID") as? String
phone = dict.value(forKey: "phone") as? String
}
}
| 22.433333 | 54 | 0.653789 |
ffb57701918ce510bdd6129b96ef8538fcca4be6 | 1,683 | //
// PhraseConfig.swift
// PhraseSwift
//
// Created by Onur Torna on 18.12.19.
// Copyright © 2019 Onur Torna. All rights reserved.
//
import Foundation
public final class PhraseConfig {
public static let shared = PhraseConfig()
/// Prints debug errors when enabled
internal var isLoggingEnabled: Bool = true
/// Supported characters to use in keys
internal var supportedKeyChars: [PhraseCharacterSet] = SupportedCharSet.allCases
/// Special start character to use when defining a key
internal var keyStartChar: Character = Constant.defaultKeyStartChar
/// Special end character to use when defining a key
internal var keyEndChar: Character = Constant.defaultKeyEndChar
private init() {
// Left blank intentionally.
}
/// Configures the whole Phrase library to define logging, and key rule specification
/// - Parameter isLoggingEnabled: Enables/Disables logging
/// - Parameter supportedKeyChars: Supported characters to use it in keys
/// - Parameter keyStartChar: Special starting character of the keys
/// - Parameter keyEndChar: Special end character of the keys
public func configure(isLoggingEnabled: Bool = true,
supportedKeyChars: [PhraseCharacterSet] = SupportedCharSet.allCases,
keyStartChar: Character = Constant.defaultKeyStartChar,
keyEndChar: Character = Constant.defaultKeyEndChar) {
self.isLoggingEnabled = isLoggingEnabled
self.supportedKeyChars = supportedKeyChars
self.keyStartChar = keyStartChar
self.keyEndChar = keyEndChar
}
}
| 36.586957 | 94 | 0.687463 |
20d60eede7285a0cd689fada9ec8e2b013be03f2 | 3,446 | //
// SuperheroViewController.swift
// Flix
//
// Created by Jackson Didat on 1/20/18.
// Copyright © 2018 jdidat. All rights reserved.
//
import UIKit
class SuperheroViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var movies: [Movie] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
fetchMovies()
// Do any additional setup after loading the view.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PosterCell", for: indexPath) as! PosterCell
let movie = movies[indexPath.item]
let posterPathString = movie.posterPathString
if !posterPathString.isEmpty {
let baseURLString = "https://image.tmdb.org/t/p/w500"
let posterURL = URL(string: baseURLString + posterPathString)!
cell.posterImageView.af_setImage(withURL: posterURL)
}
return cell
}
func fetchMovies() {
//activityIndicator.startAnimating()
let url = URL(string: "https://api.themoviedb.org/3/movie/297762/similar?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
// This will run when the network request returns
if let error = error {
print(error.localizedDescription)
} else if let data = data {
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let movies = dataDictionary["results"] as! [[String: Any]]
for dictionary in movies {
let movie = Movie(dictionary: dictionary)
self.movies.append(movie)
}
self.collectionView.reloadData()
//self.refreshControl.endRefreshing()
}
}
task.resume()
//activityIndicator.stopAnimating()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UICollectionViewCell
if let indexPath = collectionView.indexPath(for: cell) {
let movie = movies[indexPath.row]
let detailViewController = segue.destination as! DetailViewController
detailViewController.movie = movie
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 38.719101 | 124 | 0.647417 |
50bb662f2abccab5ce7dcbeefa3c07b0c0446ebb | 376 | //
// Created by Michael Martinez on 19/03/2020.
// Copyright © 2020 michael-martinez. All rights reserved.
//
import Foundation
extension Bundle {
static func customSoundURL(type: CustomSoundTypes) -> URL {
let path = Bundle.main.path(forResource: type.rawValue, ofType: nil)!
let url = URL(fileURLWithPath: path)
return url
}
}
| 22.117647 | 77 | 0.656915 |
f87c2d17b643cd4598ce1fcb288fb0e4154378a9 | 109 |
import PackageDescription
let package = Package(name: "BeyovaJSON", dependencies : [], exclude: ["Tests"])
| 21.8 | 80 | 0.724771 |
752739c956e04b3a2693efae269440c9ebfd9dbe | 1,569 | //
// LoadingTableViewProvider.swift
// NiceDemo
//
// Created by Serhii Kharauzov on 1/16/19.
// Copyright © 2019 Serhii Kharauzov. All rights reserved.
//
import Foundation
import UIKit
class LoadingTableViewProvider: NSObject, TableViewProvider {
let configuration: Configuration
init(configuration: Configuration = Configuration()) {
self.configuration = configuration
}
func numberOfSections(in tableView: UITableView) -> Int {
return configuration.numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return configuration.numberOfRowsInSection
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: LoadingTableViewCell.reuseIdentifier, for: indexPath) as? LoadingTableViewCell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return configuration.heightForRow
}
}
extension LoadingTableViewProvider {
struct Configuration {
let numberOfSections: Int
let numberOfRowsInSection: Int
let heightForRow: CGFloat
init(numberOfSections: Int = 1, numberOfRowsInSection: Int = 100, heightForRow: CGFloat = 70) {
self.numberOfSections = numberOfSections
self.numberOfRowsInSection = numberOfRowsInSection
self.heightForRow = heightForRow
}
}
}
| 31.38 | 160 | 0.703633 |
e912873f465458fec4b5b3e0fd2ce3042e702c1f | 2,071 | //
// CartsModel.swift
// SexyColor.Swift
//
// Created by xiongkai on 2017/8/21.
// Copyright © 2017年 薛凯凯圆滚滚. All rights reserved.
//
import UIKit
import HandyJSON
struct ShopCartData : HandyJSON{
var code : Int?
var message: String?
var data: ShopCartModel?
static func loadCarts(completion: (_ model: ShopCartData) -> ()) {
let path = Bundle.main.path(forResource: "carts", ofType: "json")
let url = URL(fileURLWithPath: path!)
do {
let jsonData = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
let jsonDic = json as! NSDictionary
let toModel = JSONDeserializer<ShopCartData>.deserializeFrom(dict: jsonDic)!
completion(toModel)
} catch let error {
print("读取本地数据出现错误!", error)
}
}
static func plusCarts(number: Int, completion: () -> ()) {
completion()
}
static func reduceCarts(number: Int, completion: () -> ()) {
completion()
}
static func removeCarts(completion: () -> ()) {
completion()
}
}
struct ShopCartModel : HandyJSON {
var template_id : Int?
var total_amount : Int?
var rec_ids_array : [String]?
var carts_list : [CartsList]?
var bonus_info : BonusInfo?
var carts_count : Int?
}
struct CartsList : HandyJSON {
var rec_id : Int?
var goods_id : Int?
var is_special : Bool?
var is_check : Bool?
var special_type : Int?
var special_id : Int?
var goods_number : Int?
var goods_name : String?
var app_price : Double?
var user_price : Double?
var min_goods_amount : Int?
var goods_img : String?
var goods_spec_name : String?
var goods_attr_price : Double?
var expiry_at : Int?
var extension_code : String?
var is_expiry : Bool?
var expire_msg : String?
}
struct BonusInfo : HandyJSON {
var shopping_fee : Int?
var shopping_fee_description : String?
}
| 24.364706 | 97 | 0.61323 |
f98e973a8655e4c1b3b2d1a815a2999148b22e66 | 4,612 | //
// Combinators.swift
// Promissum
//
// Created by Tom Lokhorst on 2014-10-11.
// Copyright (c) 2014 Tom Lokhorst. All rights reserved.
//
import Foundation
/// Flattens a nested Promise of Promise into a single Promise.
///
/// The returned Promise resolves (or rejects) when the nested Promise resolves.
public func flatten<Value, Error>(promise: Promise<Promise<Value, Error>, Error>) -> Promise<Value, Error> {
let source = PromiseSource<Value, Error>()
promise
.trap(source.reject)
.then { p in
p.trap(source.reject).then(source.resolve)
return
}
return source.promise
}
/// Creates a Promise that resolves when both arguments to `whenBoth` resolve.
///
/// The new Promise's value is of a tuple type constructed from both argument promises.
///
/// If either of the two Promises fails, the returned Promise also fails.
public func whenBoth<A, B, Error>(promiseA: Promise<A, Error>, _ promiseB: Promise<B, Error>) -> Promise<(A, B), Error> {
return promiseA.flatMap { valueA in promiseB.map { valueB in (valueA, valueB) } }
}
/// Creates a Promise that resolves with an array of all values all provided Promises.
///
/// If any of the supplied Promises fails, the returned Promise immediately fails.
///
/// When called with an empty array of promises, this returns a Resolved Promise (with an empty array value).
public func whenAll<Value, Error>(promises: [Promise<Value, Error>]) -> Promise<[Value], Error> {
let source = PromiseSource<[Value], Error>()
var results = promises.map { $0.value }
var remaining = promises.count
if remaining == 0 {
source.resolve([])
}
for (ix, promise) in promises.enumerate() {
promise
.then { value in
results[ix] = value
remaining = remaining - 1
if remaining == 0 {
source.resolve(results.map { $0! })
}
}
promise
.trap { error in
source.reject(error)
}
}
return source.promise
}
/// Creates a Promise that resolves when either argument to `whenEither` resolves.
///
/// The new Promise's value is the value of the first promise to resolve.
/// If both argument Promises are already Resolved, the first Promise's value is used.
///
/// If both Promises fail, the returned Promise also fails.
public func whenEither<Value, Error>(promise1: Promise<Value, Error>, _ promise2: Promise<Value, Error>) -> Promise<Value, Error> {
return whenAny([promise1, promise2])
}
/// Creates a Promise that resolves when any of the argument Promises resolves.
///
/// If all of the supplied Promises fail, the returned Promise fails.
///
/// When called with an empty array of promises, this returns a Promise that will never resolve.
public func whenAny<Value, Error>(promises: [Promise<Value, Error>]) -> Promise<Value, Error> {
let source = PromiseSource<Value, Error>()
var remaining = promises.count
for promise in promises {
promise
.then { value in
source.resolve(value)
}
promise
.trap { error in
remaining = remaining - 1
if remaining == 0 {
source.reject(error)
}
}
}
return source.promise
}
/// Creates a Promise that resolves when all provided Promises finalize.
///
/// When called with an empty array of promises, this returns a Resolved Promise.
public func whenAllFinalized<Value, Error>(promises: [Promise<Value, Error>]) -> Promise<Void, NoError> {
let source = PromiseSource<Void, NoError>()
var remaining = promises.count
if remaining == 0 {
source.resolve()
}
for promise in promises {
promise
.finally {
remaining = remaining - 1
if remaining == 0 {
source.resolve()
}
}
}
return source.promise
}
/// Creates a Promise that resolves when any of the provided Promises finalize.
///
/// When called with an empty array of promises, this returns a Promise that will never resolve.
public func whenAnyFinalized<Value, Error>(promises: [Promise<Value, Error>]) -> Promise<Void, NoError> {
let source = PromiseSource<Void, NoError>()
for promise in promises {
promise
.finally {
source.resolve()
}
}
return source.promise
}
extension Promise {
/// Returns a Promise where the value information is thrown away.
public func void() -> Promise<Void, Error> {
return self.map { _ in }
}
}
extension Promise where Error : ErrorType {
/// Returns a Promise where the error is casted to an ErrorType.
public func mapErrorType() -> Promise<Value, ErrorType> {
return self.mapError { $0 }
}
}
| 26.65896 | 131 | 0.670425 |
6775eb0cd261e2e2054529137c2ecbdf2767f60b | 6,997 | //
// FlixViewController.swift
// flix
//
// Created by Auster Chen on 9/14/17.
// Copyright © 2017 Auster Chen. All rights reserved.
//
import UIKit
import AFNetworking
import VHUD
class FlixViewController: UIViewController,
UITableViewDataSource,
UITableViewDelegate,
UISearchResultsUpdating {
let refreshControl = UIRefreshControl()
let searchController = UISearchController(searchResultsController: nil)
var content = VHUDContent(.loop(3.0))
var tableViewTopToLayoutGuideConstraint: NSLayoutConstraint?
var tableViewTopToErrorViewConstraint: NSLayoutConstraint?
var errorViewHeightConstraint: NSLayoutConstraint?
var errorViewToTopLayoutGuideConstraint: NSLayoutConstraint?
var movies: [Movie] = []
var filteredMovies: [Movie] = []
var searchText: String? = ""
var endpoint: String = "now_playing"
let errorView: UIView! = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.gray
return view
}()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Setting up loader
content.loadingText = "Loading..."
content.shape = .circle
content.background = .color(#colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 0.7))
content.style = .light
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
// Setting up pull to refresh
refreshControl.layer.zPosition += 1
refreshControl.backgroundColor = UIColor.groupTableViewBackground
refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged)
tableView.insertSubview(refreshControl, at: 0)
tableView.backgroundView?.layer.zPosition -= 1;
let errorLabel = UILabel()
errorLabel.text = "Could not fetch movies"
errorView.addSubview(errorLabel)
errorLabel.translatesAutoresizingMaskIntoConstraints = false
errorLabel.leadingAnchor.constraint(equalTo: (errorLabel.superview?.leadingAnchor)!).isActive = true
errorLabel.topAnchor.constraint(equalTo: (errorLabel.superview?.topAnchor)!).isActive = true
errorLabel.bottomAnchor.constraint(equalTo: (errorLabel.superview?.bottomAnchor)!).isActive = true
errorLabel.trailingAnchor.constraint(equalTo: (errorLabel.superview?.trailingAnchor)!).isActive = true
errorLabel.textAlignment = NSTextAlignment.center
view.addSubview(errorView)
tableViewTopToErrorViewConstraint = tableView.topAnchor.constraint(equalTo: errorView.bottomAnchor)
tableViewTopToLayoutGuideConstraint = tableView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)
errorViewHeightConstraint = errorView.heightAnchor.constraint(equalToConstant: 30.0)
errorViewToTopLayoutGuideConstraint = errorView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)
errorView.leadingAnchor.constraint(equalTo: (errorView.superview?.leadingAnchor)!).isActive = true
errorView.trailingAnchor.constraint(equalTo: (errorView.superview?.trailingAnchor)!).isActive = true
// Initial movie fetch
fetchMovies()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshControlAction(_ refreshControl: UIRefreshControl) {
fetchMovies()
}
func fetchMovies() -> Void {
VHUD.show(content)
hideErrorMessage()
Movie.fetchMovies(endpoint, successCallBack: {
(movies: [Movie]) -> Void in
self.movies = movies
self.tableView.reloadData()
self.refreshControl.endRefreshing()
VHUD.dismiss(1.0)
}, {
error in
self.tableView.reloadData()
self.refreshControl.endRefreshing()
VHUD.dismiss(1.0)
self.showErrorMessage()
})
}
func showErrorMessage() -> Void {
errorView.isHidden = false
tableViewTopToLayoutGuideConstraint?.isActive = false
errorViewToTopLayoutGuideConstraint?.isActive = true
tableViewTopToErrorViewConstraint?.isActive = true
errorViewHeightConstraint?.isActive = true
}
func hideErrorMessage() -> Void {
errorViewHeightConstraint?.isActive = false
errorViewToTopLayoutGuideConstraint?.isActive = false
tableViewTopToErrorViewConstraint?.isActive = false
tableViewTopToLayoutGuideConstraint?.isActive = true
errorView.isHidden = true
view.layoutIfNeeded()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return getMoviesToDisplay().count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let moviesListToUse = getMoviesToDisplay()
let movieCell = tableView.dequeueReusableCell(withIdentifier: "MovieCell") as! MovieTableViewCell
movieCell.updateCellContentWithMovie(movie: moviesListToUse[indexPath.row])
return movieCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func updateSearchResults(for: UISearchController) {
searchText = searchController.searchBar.text
tableView.reloadData()
}
func getMoviesToDisplay() -> [Movie] {
let searchTextNSString = searchText! as NSString
if searchTextNSString.length > 0{
return movies.filter({
(movie: Movie) in
var isMatching = false
if let title = movie.title {
isMatching = title.lowercased().range(of:searchText!.lowercased()) != nil
}
if (!isMatching) {
if let overview = movie.overview {
isMatching = overview.lowercased().range(of: searchText!.lowercased()) != nil
}
}
return isMatching
})
}
return movies
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPath(for: cell)
let movie = getMoviesToDisplay()[(indexPath?.row)!]
searchController.dismiss(animated: true, completion: nil)
let moviesDetailsViewController = segue.destination as! MovieDetailsViewController
moviesDetailsViewController.movie = movie
}
}
| 38.872222 | 120 | 0.675861 |
16f95c468ed7b6eff2610d2cfc63a945a8d13a18 | 5,688 | //
// CarloudySettingViewController.swift
// CarloudyWeather
//
// Created by Zijia Zhai on 12/19/18.
// Copyright © 2018 cognitiveAI. All rights reserved.
//
import UIKit
import CarloudyiOS
class CarloudySettingViewController: UIViewController {
let carloudyBLE = CarloudyBLE.shareInstance
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.isScrollEnabled = true
sv.contentSize = CGSize(width: zjScreenWidth, height: 600)
return sv
}()
let textLabel: UILabel = {
let tl = UILabel()
tl.numberOfLines = 0
tl.text = "1. Pair your Carloudy App and Carloudy HUD\n\n2. Open Carloudy-Weather app by Carloudy App\n\nStep1 & Step2 will give Carloudy-Weather app the pair key, you only need to do them once if you do not change the pair key\n\n3. Send your WIFi to Carloudy HUD:"
tl.font = UIFont.boldSystemFont(ofSize: 15)
tl.textColor = .black
return tl
}()
lazy var sendButton: UIButton = {
let button = UIButton()
button.backgroundColor = .blue
button.layer.cornerRadius = 15
button.layer.masksToBounds = true
button.alpha = 0.5
button.setTitleColor(.white, for: .normal)
button.setTitle("Send Wifi", for: .normal)
button.addTarget(self, action: #selector(updateButtonClicked), for: .touchUpInside)
return button
}()
let textLabel2: UILabel = {
let tl = UILabel()
tl.numberOfLines = 0
tl.text = "4. Check your Carloudy HUD, after you see WIFI Connected Successfully, you can update images to Carloudy"
tl.font = UIFont.boldSystemFont(ofSize: 15)
tl.textColor = .black
return tl
}()
let textLabel3: UILabel = {
let tl = UILabel()
tl.numberOfLines = 0
tl.text = "5. Check your Carloudy HUD, after you see Image Download Successfully, you can see the image when you open the app next time."
tl.font = UIFont.boldSystemFont(ofSize: 15)
tl.textColor = .black
return tl
}()
lazy var downloadButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .blue
button.layer.cornerRadius = 15
button.layer.masksToBounds = true
button.alpha = 0.5
button.setTitleColor(.white, for: .normal)
button.setTitle("Update Images", for: .normal)
button.addTarget(self, action: #selector(downloadButtonClicked), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
if let pairkey = carloudyBlePairKey_{
carloudyBLE.newKeySendToPairAndorid_ = pairkey
}
}
fileprivate func setupUI(){
self.title = "Update Images"
navigationController?.navigationBar.prefersLargeTitles = true
self.scrollView.backgroundColor = UIColor.background
self.view.addSubview(scrollView)
scrollView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
self.scrollView.addSubview(textLabel)
textLabel.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: nil, right: nil, paddingTop: 10, paddingLeft: 15, paddingBottom: 0, paddingRight: 0, width: zjScreenWidth - 40, height: 0)
self.scrollView.addSubview(sendButton)
sendButton.anchor(top: textLabel.bottomAnchor, left: scrollView.leftAnchor, bottom: nil, right: nil, paddingTop: 20, paddingLeft: 20, paddingBottom: 0, paddingRight: 0, width: zjScreenWidth - 40, height: 50)
self.scrollView.addSubview(textLabel2)
textLabel2.anchor(top: sendButton.bottomAnchor, left: scrollView.leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 15, paddingBottom: 0, paddingRight: 0, width: zjScreenWidth - 40, height: 0)
self.scrollView.addSubview(downloadButton)
downloadButton.anchor(top: textLabel2.bottomAnchor, left: scrollView.leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 15, paddingBottom: 0, paddingRight: 0, width: zjScreenWidth - 40, height: 50)
self.scrollView.addSubview(textLabel3)
textLabel3.anchor(top: downloadButton.bottomAnchor, left: scrollView.leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 15, paddingBottom: 0, paddingRight: 0, width: zjScreenWidth - 40, height: 0)
}
@objc func updateButtonClicked(){
carloudyBLE.startANewSession(appId: carloudyAppStoreAppKey_)
carloudyBLE.alertViewToUpdateImagesFromServer()
ZJPrint(carloudyBLE)
}
@objc fileprivate func downloadButtonClicked(){
//startANewSession also let Carloudy HUD download the images
carloudyBLE.startANewSession(appId: carloudyAppStoreAppKey_)
carloudyBLE.startANewSession(appId: carloudyAppStoreAppKey_)
self.downloadButton.isEnabled = false
self.downloadButton.backgroundColor = UIColor.lightGray
self.downloadButton.setTitle("Sent, check your carloudy", for: .normal)
self.downloadButton.setTitleColor(.black, for: .normal)
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
self.downloadButton.isEnabled = true
self.downloadButton.backgroundColor = .blue
self.downloadButton.alpha = 0.5
self.downloadButton.setTitle("Update Images", for: .normal)
self.downloadButton.setTitleColor(.white, for: .normal)
}
}
}
| 43.419847 | 274 | 0.670886 |
e9c769401b52bb8d37e01b3906741dda001623d3 | 703 | //
// ResultViewController.swift
// OpenpayExample
//
// Created by Israel Grijalva Correa on 10/6/16.
// Copyright © 2016 Openpay. All rights reserved.
//
import UIKit
import Openpay
class ResultViewController: UIViewController {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var textBox: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backAction(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil);
}
}
| 19.527778 | 58 | 0.650071 |
dbd69280b7f4a81003d66ee86a3aaa594cec8648 | 518 | //
// MigrationHandler.swift
// Pods
//
// Created by 酒井篤 on 2015/09/14.
//
//
import UIKit
public class MigrationHandler: NSObject {
var targetVersion: String
var handler: () throws -> ()
public init(targetVersion: String, handler: () throws -> ()) {
self.targetVersion = targetVersion
self.handler = handler
}
public func migrate() throws {
do {
try self.handler()
} catch let error {
throw error
}
}
}
| 17.266667 | 66 | 0.546332 |
6a984a1f9af39f3057ee0ada8d862a33fb108750 | 6,725 | //
// PDFViewController.swift
// PDFTest
//
// Created by Frank Jia on 2019-05-19.
// Copyright © 2019 Frank Jia. All rights reserved.
//
import UIKit
import PDFKit
public protocol SimplePDFViewOnDismissDelegate: AnyObject {
func didDismiss(_ sender: SimplePDFViewController)
}
public class SimplePDFViewController: UIViewController {
// Views
private let pdfView: SimplePDFView = SimplePDFView()
private let topBar: SimplePDFTopBarView = SimplePDFTopBarView()
private let bottomBar: SimplePDFBottomBarView = SimplePDFBottomBarView()
// State
private var currentPage = 1
private var pdf: PDFDocument?
// Configurable properties
public var tint: UIColor? {
didSet {
pdfView.tint = tint
topBar.tint = tint
bottomBar.tint = tint
}
}
public var errorMessage: String? {
didSet {
pdfView.errorMessage = errorMessage ?? ""
}
}
public var viewTitle: String? {
didSet {
topBar.title = viewTitle ?? ""
title = viewTitle
}
}
public var exportPDFName: String = "Document"
public var dismissalDelegate: SimplePDFViewOnDismissDelegate?
// MARK: Constructors
public init(urlString: String) {
super.init(nibName:nil, bundle:nil)
pdfView.load(urlString: urlString)
}
public init (url: URL) {
super.init(nibName: nil, bundle: nil)
pdfView.load(url: url)
}
public init (data: Data) {
super.init(nibName: nil, bundle: nil)
pdfView.load(data: data)
}
public init (pdf: PDFDocument) {
super.init(nibName: nil, bundle: nil)
pdfView.load(pdf: pdf)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
initViews(withTopBar: navigationController == nil)
}
private func initViews(withTopBar: Bool) {
let superview = self.view!
superview.backgroundColor = .white
superview.addSubview(pdfView)
superview.addSubview(bottomBar)
if withTopBar {
// Add the top bar to view and add the necessary constraints
superview.addSubview(topBar)
topBar.snp.makeConstraints() { make in
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
make.left.equalToSuperview()
make.right.equalToSuperview()
}
topBar.delegate = self
// Make PDF View constrained to top bar
pdfView.snp.makeConstraints() { make in
make.top.equalTo(topBar.snp.bottom)
}
} else {
// Make PDF View constrained to navbar
pdfView.snp.makeConstraints() { make in
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
}
}
pdfView.snp.makeConstraints() { make in
make.left.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalTo(bottomBar.snp.top)
}
bottomBar.snp.makeConstraints() { make in
make.left.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
}
pdfView.delegate = self
bottomBar.delegate = self
bottomBar.enabled = false
}
}
// Delegates for different views
extension SimplePDFViewController: SimplePDFTopBarDelegate, SimplePDFBottomBarActionDelegate, SimplePDFViewerStatusDelegate {
internal func doneButtonPressed(_ sender: SimplePDFTopBarView) {
// Call delegate if it is set, else just dismiss
if let dismissalDelegate = self.dismissalDelegate {
dismissalDelegate.didDismiss(self)
} else {
self.dismiss(animated: true, completion: nil)
}
}
internal func onShareButtonPressed(_ sender: SimplePDFBottomBarView) {
guard let pdf = pdf else {
print("PDF has not loaded yet, so cannot be shared.")
return
}
// Disable bottom bar to prevent further touches
bottomBar.enabled = false
showShareSheet(for: pdf)
}
internal func onJumpToPagePressed(_ sender: SimplePDFBottomBarView) {
guard let pdf = pdf else {
print("PDF has not loaded yet.")
return
}
showJumpToPageDialog(for: pdf)
}
internal func didLoadSuccessfully(_ sender: SimplePDFView) {
self.pdf = sender.pdf
bottomBar.enabled = true
bottomBar.totalPages = pdf?.pageCount ?? 1
bottomBar.currentPage = sender.currentPageNumber
}
internal func didLoadWithError(_ sender: SimplePDFView) {
print("PDF Loaded with error")
bottomBar.enabled = false // Just to be sure
}
internal func onPageChange(_ sender: SimplePDFView) {
self.currentPage = sender.currentPageNumber
bottomBar.currentPage = sender.currentPageNumber
}
}
// Extension for presenting external VC's
extension SimplePDFViewController {
// Shows a share sheet for the PDF
private func showShareSheet(for pdf: PDFDocument) {
// A local URL that we write to
let shareURL = prepareForSharing(pdf: pdf, fileName: exportPDFName)
let shareVC = UIActivityViewController(activityItems: [shareURL], applicationActivities: nil)
present(shareVC, animated: true) {
// Re-enable bottom bar
self.bottomBar.enabled = true
}
}
// Shows a dialog to enter a page number
private func showJumpToPageDialog(for pdf: PDFDocument) {
let dialogHelper = SimplePDFJumpToPageDialog(maxPages: pdf.pageCount, tint: tint ?? self.view.tintColor)
let dialogVC = dialogHelper.getDialog(currentPage: currentPage) { newPageNum in
if let pageNum = newPageNum {
self.pdfView.jumpToPage(pageNum)
}
}
present(dialogVC, animated: true, completion: nil)
}
// Writes PDF as a file so that we can share it
private func prepareForSharing(pdf: PDFDocument, fileName: String) -> URL {
let tempPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("\(fileName).pdf")
let pdfData = pdf.dataRepresentation()
FileManager.default.createFile(atPath: tempPath, contents: pdfData, attributes: nil)
return URL(fileURLWithPath: tempPath)
}
}
| 32.965686 | 160 | 0.627658 |
ffa7816d57a5c08aff5906bb2a262f2629efb4c5 | 7,164 | //===--- ValidUTF8Buffer.swift - Bounded Collection of Valid UTF-8 --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Stores valid UTF8 inside an unsigned integer.
//
// Actually this basic type could be used to store any UInt8s that cannot be
// 0xFF
//
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct _ValidUTF8Buffer<Storage: UnsignedInteger & FixedWidthInteger> {
public typealias Element = Unicode.UTF8.CodeUnit
internal typealias _Storage = Storage
@usableFromInline
internal var _biasedBits: Storage
@inlinable // FIXME(sil-serialize-all)
internal init(_biasedBits: Storage) {
self._biasedBits = _biasedBits
}
@inlinable // FIXME(sil-serialize-all)
internal init(_containing e: Element) {
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits = Storage(truncatingIfNeeded: e &+ 1)
}
}
extension _ValidUTF8Buffer : Sequence {
public typealias SubSequence = Slice<_ValidUTF8Buffer>
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator : IteratorProtocol, Sequence {
@inlinable // FIXME(sil-serialize-all)
public init(_ x: _ValidUTF8Buffer) { _biasedBits = x._biasedBits }
@inlinable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
if _biasedBits == 0 { return nil }
defer { _biasedBits >>= 8 }
return Element(truncatingIfNeeded: _biasedBits) &- 1
}
@usableFromInline // FIXME(sil-serialize-all)
internal var _biasedBits: Storage
}
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _ValidUTF8Buffer : Collection {
@_fixed_layout // FIXME(sil-serialize-all)
public struct Index : Comparable {
@usableFromInline
internal var _biasedBits: Storage
@inlinable // FIXME(sil-serialize-all)
internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits }
@inlinable // FIXME(sil-serialize-all)
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits == rhs._biasedBits
}
@inlinable // FIXME(sil-serialize-all)
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits > rhs._biasedBits
}
}
@inlinable // FIXME(sil-serialize-all)
public var startIndex : Index {
return Index(_biasedBits: _biasedBits)
}
@inlinable // FIXME(sil-serialize-all)
public var endIndex : Index {
return Index(_biasedBits: 0)
}
@inlinable // FIXME(sil-serialize-all)
public var count : Int {
return Storage.bitWidth &>> 3 &- _biasedBits.leadingZeroBitCount &>> 3
}
@inlinable // FIXME(sil-serialize-all)
public var isEmpty : Bool {
return _biasedBits == 0
}
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
_debugPrecondition(i._biasedBits != 0)
return Index(_biasedBits: i._biasedBits >> 8)
}
@inlinable // FIXME(sil-serialize-all)
public subscript(i: Index) -> Element {
return Element(truncatingIfNeeded: i._biasedBits) &- 1
}
}
extension _ValidUTF8Buffer : BidirectionalCollection {
@inlinable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
let offset = _ValidUTF8Buffer(_biasedBits: i._biasedBits).count
_debugPrecondition(offset != 0)
return Index(_biasedBits: _biasedBits &>> (offset &<< 3 - 8))
}
}
extension _ValidUTF8Buffer : RandomAccessCollection {
public typealias Indices = DefaultIndices<_ValidUTF8Buffer>
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
_debugPrecondition(_isValid(i))
_debugPrecondition(_isValid(j))
return (
i._biasedBits.leadingZeroBitCount - j._biasedBits.leadingZeroBitCount
) &>> 3
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let startOffset = distance(from: startIndex, to: i)
let newOffset = startOffset + n
_debugPrecondition(newOffset >= 0)
_debugPrecondition(newOffset <= count)
return Index(_biasedBits: _biasedBits._fullShiftRight(newOffset &<< 3))
}
}
extension _ValidUTF8Buffer : RangeReplaceableCollection {
@inlinable // FIXME(sil-serialize-all)
public init() {
_biasedBits = 0
}
@inlinable // FIXME(sil-serialize-all)
public var capacity: Int {
return _ValidUTF8Buffer.capacity
}
@inlinable // FIXME(sil-serialize-all)
public static var capacity: Int {
return Storage.bitWidth / Element.bitWidth
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func append(_ e: Element) {
_debugPrecondition(count + 1 <= capacity)
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits |= Storage(e &+ 1) &<< (count &<< 3)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
@discardableResult
public mutating func removeFirst() -> Element {
_debugPrecondition(!isEmpty)
let result = Element(truncatingIfNeeded: _biasedBits) &- 1
_biasedBits = _biasedBits._fullShiftRight(8)
return result
}
@inlinable // FIXME(sil-serialize-all)
internal func _isValid(_ i: Index) -> Bool {
return i == endIndex || indices.contains(i)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func replaceSubrange<C: Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_debugPrecondition(_isValid(target.lowerBound))
_debugPrecondition(_isValid(target.upperBound))
var r = _ValidUTF8Buffer()
for x in self[..<target.lowerBound] { r.append(x) }
for x in replacement { r.append(x) }
for x in self[target.upperBound...] { r.append(x) }
self = r
}
}
extension _ValidUTF8Buffer {
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func append<T>(contentsOf other: _ValidUTF8Buffer<T>) {
_debugPrecondition(count + other.count <= capacity)
_biasedBits |= Storage(
truncatingIfNeeded: other._biasedBits) &<< (count &<< 3)
}
}
extension _ValidUTF8Buffer {
@inlinable // FIXME(sil-serialize-all)
public static var encodedReplacementCharacter : _ValidUTF8Buffer {
return _ValidUTF8Buffer(_biasedBits: 0xBD_BF_EF &+ 0x01_01_01)
}
@inlinable
internal var _bytes: (bytes: UInt64, count: Int) {
let count = self.count
let mask: UInt64 = 1 &<< (UInt64(truncatingIfNeeded: count) &<< 3) &- 1
let unbiased = UInt64(truncatingIfNeeded: _biasedBits) &- 0x0101010101010101
return (unbiased & mask, count)
}
}
| 31.283843 | 80 | 0.673786 |
6427d21a625b2fa1f025888781c9b1f3f4bb71a6 | 1,463 | //
// ViewController.swift
// AlertController_Additional_Exercise
//
// Created by Kas Song on 2020.04.29.
// Copyright © 2020 Kas Song. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var labelDisplay = UILabel()
var storeText: String = "" {
didSet {
labelDisplay.text = storeText
}
}
override func viewDidLoad() {
super.viewDidLoad()
homeViewUI()
}
private func homeViewUI() {
view.backgroundColor = .white
let nextButton = UIButton()
// nextButton.frame = CGRect(x: view.center.x - 50, y: 300, width: 100, height: 40)
nextButton.frame.size = CGSize(width: 100, height: 40)
nextButton.frame.origin = CGPoint(x: view.frame.midX - 50, y: 500)
nextButton.setTitle("Next", for: .normal)
nextButton.backgroundColor = .blue
nextButton.addTarget(self, action: #selector(nextButtonAction), for: .touchUpInside)
view.addSubview(nextButton)
labelDisplay.frame = CGRect(x: view.frame.midX - 100, y: 200, width: 200, height: 40)
labelDisplay.textAlignment = .center
labelDisplay.layer.borderWidth = 0.5
view.addSubview(labelDisplay)
}
@objc private func nextButtonAction() {
let vc = AlertViewController()
vc.modalPresentationStyle = .overFullScreen
present(vc, animated: true)
}
}
| 28.686275 | 93 | 0.619959 |
5d128e9d36d322917a18d43b1c80ef59340d1f7b | 2,810 | import UIKit
import AlamofireImage
class PhotosViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var posts: [[String: Any]] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
let url = URL(string: "https://api.tumblr.com/v2/blog/humansofnewyork.tumblr.com/posts/photo?api_key=Q6vHoaVm5L1u2ZAW1fqv3Jw48gFzYVg9P0vH0VHl3GVy6quoGV")!
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let task = session.dataTask(with: url) { (data, response, error) in
if let error = error {
print(error.localizedDescription)
} else if let data = data,
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let responseDictionary = dataDictionary["response"] as! [String: Any]
self.posts = responseDictionary["posts"] as! [[String: Any]]
self.tableView.reloadData()
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let post = posts[indexPath.row]
if let photos = post["photos"] as? [[String: Any]] {
let photo = photos[0]
let originalSize = photo["original_size"] as! [String: Any]
let urlString = originalSize["url"] as! String
let url = URL(string: urlString)
cell.photoView.af_setImage(withURL: url!)
self.tableView.rowHeight = 200
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
if let indexPath = tableView.indexPath(for: cell){
let photos = posts[indexPath.row]
let vc = segue.destination as! PhotoDetailsViewController
vc.photos = photos
tableView.deselectRow(at: indexPath, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 31.222222 | 162 | 0.569751 |
23fb7c428a4c69697ed5dfc4303d15804495c2bd | 2,283 | //
// Camera.swift
// SoftRenderer
//
// Created by Richard Pickup on 20/01/2022.
//
import Foundation
let PI: Double = 3.1415926535897932384626433832795;
struct Camera {
let direction: Vector
let position: Point
let nearZ: Float
let farZ: Float
let viewDistance: Float
let fieldOfView: Float
let aspectRatio: Float
let viewportWidth: Float
let viewportHeight: Float
init(position: Point,
direction: Vector,
nearDistance: Float,
farDistance: Float,
fov: Float,
width: Float,
height: Float) {
self.position = position
self.direction = direction
self.nearZ = nearDistance
self.farZ = farDistance
self.fieldOfView = Float(Double(fov) * PI / 180)
self.viewportWidth = width
self.viewportHeight = height
self.aspectRatio = width / height
let viewPlaneWidth: Float = 2.0
self.viewDistance = tanf((self.fieldOfView / 2.0) * (viewPlaneWidth * 0.5))
}
func buildCameraTransform() -> Matrix {
let translate = Matrix.translation(transX: -position.x,
transy: -position.y,
transZ: -position.z)
let rotate = Matrix.rotation(rotX: -direction.x,
rotY: -direction.y,
rotZ: -direction.z)
return translate * rotate
}
func buildPerspective() -> Matrix {
let transform = Matrix(viewDistance, 0, 0, 0,
0, viewDistance * aspectRatio, 0, 0,
0, 0, 1, 0,
0, 0, -1, 0)
return transform
}
func buildScreen() -> Matrix {
let scaleWidth = (viewportWidth * 0.5) - 0.5
let scaleHeight = (viewportHeight * 0.5) - 0.5
let transform = Matrix(scaleWidth, 0, 0, scaleWidth,
0, -scaleHeight, 0, scaleHeight,
0, 0, 1, 0,
0, 0, 0, 1)
return transform
}
}
| 30.039474 | 83 | 0.487516 |
e5e6821e638e5ea92d7c353320d75b5dc1c38074 | 2,075 | //
// NotAuthenticatedView.swift
// nbro
//
// Created by Peter Gammelgaard Poulsen on 10/03/16.
// Copyright © 2016 Bob. All rights reserved.
//
import Foundation
import UIKit
class InformationView: UIView {
fileprivate let titleBackgroundView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: 0xFFFFFF, alpha: 1)
return view
}()
let button = UIButton()
let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.titleBoldFontOfSize(44)
label.textColor = UIColor.black
label.textAlignment = .center
return label
}()
let descriptionLabel: UILabel = {
let label = UILabel()
label.font = UIFont.defaultRegularFontOfSize(14)
label.textColor = UIColor.white
label.numberOfLines = 0
return label
}()
init() {
super.init(frame: CGRect.zero)
setupSubviews()
defineLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension InformationView {
fileprivate func setupSubviews() {
[titleBackgroundView, titleLabel, descriptionLabel, button].forEach({ addSubview($0) })
}
fileprivate func defineLayout() {
titleBackgroundView.snp.makeConstraints { (make) in
make.height.equalTo(60)
make.width.equalTo(244)
make.left.top.right.equalToSuperview()
}
titleLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(titleBackgroundView)
make.centerY.equalTo(titleBackgroundView).offset(4)
}
button.snp.makeConstraints { (make) in
make.edges.equalTo(titleBackgroundView)
}
descriptionLabel.snp.makeConstraints { (make) in
make.left.right.equalTo(titleBackgroundView)
make.top.equalTo(titleBackgroundView.snp.bottom)
make.bottom.equalToSuperview()
}
}
}
| 25.9375 | 95 | 0.607229 |
878324c4aea10f841b82c9f801242d3c3875a45e | 1,232 | //
// xiaoriziUITests.swift
// xiaoriziUITests
//
// Created by zhike on 16/7/4.
// Copyright © 2016年 zhike. All rights reserved.
//
import XCTest
class xiaoriziUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.297297 | 182 | 0.660714 |
e4efa89e49df60f32421c2a71f4ecc6c700f480a | 4,396 | /*
* Copyright (c) 2017, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 AppAuth
import Vinculum
open class OktaTokenManager: NSObject, NSCoding {
open var authState: OIDAuthState
open var config: [String: String]
open var accessibility: CFString
open var validationOptions: [String: Any]
open var accessToken: String? {
// Return the known accessToken if it hasn't expired
get {
guard let tokenResponse = self.authState.lastTokenResponse,
let token = tokenResponse.accessToken,
let tokenExp = tokenResponse.accessTokenExpirationDate,
tokenExp.timeIntervalSince1970 > Date().timeIntervalSince1970 else {
return nil
}
return token
}
}
open var idToken: String? {
// Return the known idToken if it is valid
get {
guard let tokenResponse = self.authState.lastTokenResponse,
let token = tokenResponse.idToken else {
return nil
}
do {
// Attempt to validate the token
let valid = try isValidToken(idToken: token)
return valid ? token : nil
} catch let error {
// Capture the error here since we aren't throwing
print(error)
return nil
}
}
}
open var refreshToken: String? {
// Return the known refreshToken
get {
guard let token = self.authState.refreshToken else { return nil }
return token
}
}
public init(authState: OIDAuthState, config: [String: String], accessibility: CFString = kSecAttrAccessibleWhenUnlockedThisDeviceOnly, validationOptions: [String: Any]?) throws {
self.authState = authState
self.config = config
self.accessibility = accessibility
if validationOptions != nil {
// Override config options
self.validationOptions = validationOptions!
} else {
// Opinionated validation options
self.validationOptions = [
"issuer": config["issuer"] as Any,
"audience": config["clientId"] as Any,
"exp": true,
"iat": true,
"nonce": authState.lastTokenResponse?.request.additionalParameters?["nonce"] as Any
] as [String: Any]
}
super.init()
// Store the current configuration
OktaAuth.configuration = config
}
required public convenience init?(coder decoder: NSCoder) {
try? self.init(
authState: decoder.decodeObject(forKey: "authState") as! OIDAuthState,
config: decoder.decodeObject(forKey: "config") as! [String: String],
accessibility: (decoder.decodeObject(forKey: "accessibility") as! CFString),
validationOptions: (decoder.decodeObject(forKey: "validationOptions") as! [String: Any])
)
}
public func encode(with coder: NSCoder) {
coder.encode(self.authState, forKey: "authState")
coder.encode(self.config, forKey: "config")
coder.encode(self.accessibility, forKey: "accessibility")
coder.encode(self.validationOptions, forKey: "validationOptions")
}
public func isValidToken(idToken: String?) throws -> Bool {
guard let token = idToken else { return false }
do {
let isValid = try Introspect().validate(jwt: token, options: self.validationOptions)
if isValid {
return true
}
} catch let error {
throw error
}
return false
}
public func clear() {
Vinculum.removeAll()
OktaAuth.tokens = nil
}
}
| 36.032787 | 182 | 0.602821 |
4b34cea2ad89a04b269b73e522a6ebab74042316 | 366 | import Foundation
struct AppStoreSearchRequest: NetworkRequest {
var url: URL {
URL(string: "https://itunes.apple.com/us/search?term=fosdem&media=software&entity=software")!
}
func decode(_ data: Data?, response _: HTTPURLResponse?) throws -> AppStoreSearchResponse {
try JSONDecoder().decode(AppStoreSearchResponse.self, from: data ?? Data())
}
}
| 30.5 | 97 | 0.73224 |
1d3c588085d532c980602aac149e2885f4e25112 | 3,614 | //
// NewTweetViewController.swift
// Twitter
//
// Created by Weijie Chen on 4/15/17.
// Copyright © 2017 Weijie Chen. All rights reserved.
//
import UIKit
class NewTweetViewController: UIViewController,UITextViewDelegate{
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var textcount: UILabel!
@IBOutlet weak var tweettext: UITextView!
var profile : User?
var referenceTweet : Tweet?
var isReply : Bool = false
var defaultText : String = ""
let MAX_CHAR_ALLOWED = 140
override func viewDidLoad() {
super.viewDidLoad()
initProfileData(profile: self.profile)
self.profileImage.layer.cornerRadius = 9.0
self.profileImage.layer.masksToBounds = true
self.tweettext.delegate = self
// Do any additional setup after loading the view.
}
func initProfileData(profile:User?){
if let profile = profile{
if let profileUrl = profile.profileUrl{
self.profileImage.setImageWith(profileUrl)
}else{
self.profileImage.image = #imageLiteral(resourceName: "avatar")
}
self.nameLabel.text = profile.name
self.screenNameLabel.text = "@\(profile.screenname ?? "")"
}else{
self.profileImage.image = #imageLiteral(resourceName: "avatar")
}
if isReply == true{
self.tweettext.text = defaultText
}
let characteresRemaining = MAX_CHAR_ALLOWED - tweettext.text.characters.count
self.textcount.text = "\(characteresRemaining)"
self.textcount.textColor = characteresRemaining > 10 ? .darkGray : .red
}
func textViewDidChange(_ textView: UITextView) {
let characteresRemaining = MAX_CHAR_ALLOWED - tweettext.text.characters.count
self.textcount.text = "\(characteresRemaining)"
self.textcount.textColor = characteresRemaining > 10 ? .darkGray : .red
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelNewTweet(_ sender: Any) {
//performSegue(withIdentifier: "unwindSegueToNewTweet", sender: self)
dismiss(animated: true, completion: nil)
}
@IBAction func sendNewTweet(_ sender: Any) {
let newTweet = self.tweettext.text
if isReply == true{
if let refrenceId = referenceTweet?.id {
TwitterClient.sharedInstance.replyTweet(tweet: newTweet ?? "", referenceId: refrenceId)
print("post tweet: \(self.tweettext.text)")
}
performSegue(withIdentifier: "unwindSegueToTweetDetailVC", sender: self)
}else{
TwitterClient.sharedInstance.postTweet(tweet: newTweet ?? "")
print("post tweet: \(self.tweettext.text)")
performSegue(withIdentifier: "unwindSegueToNewTweet", sender: self)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 33.155963 | 107 | 0.618152 |
20a32185e9dd103ca56c2f260c80e570d286960e | 1,836 | //
// MIT License
//
// Copyright (c) 2021 Tamerlan Satualdypov
//
// 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 SwiftUI
/**
A type that represents any slider track that
can be used by `STDiscreteSlider`.
*/
public struct AnySliderTrack: SliderTrack {
public let height: CGFloat
private let _makeTrack: () -> AnyView
private let _makeFillTrack: () -> AnyView
public init<Track: SliderTrack>(track: Track) {
self.height = track.height
self._makeTrack = track.makeTrackErased
self._makeFillTrack = track.makeFillTrackErased
}
public func makeTrack() -> some View {
return self._makeTrack()
}
public func makeFillTrack() -> some View {
return self._makeFillTrack()
}
}
| 34.641509 | 82 | 0.706972 |
b93bf58d1ed7b5c6a20e39d7f951b5c21ff47b14 | 687 | //
// CharacterSet+URLQueryParameters.swift
// MemoryChainKit
//
// Created by Marc Steven on 2020/3/16.
// Copyright © 2020 Marc Steven(https://github.com/MarcSteven). All rights reserved.
//
import Foundation
public extension CharacterSet {
static var urlQueryParametersAllowed: CharacterSet {
/// Does not include "?" or "/" due to RFC 3986 - Section 3.4
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowedCharacterSet
}
}
| 29.869565 | 104 | 0.692868 |
5b39695b095b7b0372a9f89220ac5d4eab055134 | 2,484 | /**
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
public enum RoomSize: String {
case small
case medium
case large
public var displayTitle: String {
switch self {
case .small: return NSLocalizedString("Small", comment: "")
case .medium: return NSLocalizedString("Medium", comment: "")
case .large: return NSLocalizedString("Large", comment: "")
}
}
public var index: Int {
switch self {
case .small: return 0
case .medium: return 1
case .large: return 2
}
}
public init(index: Int) {
precondition(index >= RoomSize.small.index)
precondition(index <= RoomSize.large.index)
switch index {
case RoomSize.small.index: self = .small
case RoomSize.medium.index: self = .medium
case RoomSize.large.index: self = .large
default: fatalError("Unsupported RoomSize index")
}
}
}
| 38.215385 | 82 | 0.728663 |
dd01e21d212144d683d634a5ef0e0cfa7dbd0e7b | 746 | //
// NatsErorr.swift
// SwiftyNats
//
// Created by Ray Krow on 2/27/18.
//
protocol NatsError: Error {
var description: String { get set }
}
struct NatsConnectionError: NatsError {
var description: String
init(_ description: String) {
self.description = description
}
}
struct NatsSubscribeError: NatsError {
var description: String
init(_ description: String) {
self.description = description
}
}
struct NatsPublishError: NatsError {
var description: String
init(_ description: String) {
self.description = description
}
}
struct NatsTimeoutError: NatsError {
var description: String
init(_ description: String) {
self.description = description
}
}
| 18.195122 | 39 | 0.664879 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.