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
|
---|---|---|---|---|---|
225806b109ceecdbe5edda1ece7f2570c32a9411 | 2,071 | //
// FileDownloadOperation.swift
// Rebekka
//
// Created by Constantine Fry on 25/05/15.
// Copyright (c) 2015 Constantine Fry. All rights reserved.
//
import Foundation
/** Operation for downloading a file from FTP server. */
internal class FileDownloadOperation: ReadStreamOperation {
private var fileHandle: NSFileHandle?
var fileURL: NSURL?
override func start() {
let filePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(NSUUID().UUIDString)
self.fileURL = NSURL(fileURLWithPath: filePath)
do {
try NSData().writeToURL(self.fileURL!, options: NSDataWritingOptions.DataWritingAtomic)
self.fileHandle = try NSFileHandle(forWritingToURL: self.fileURL!)
self.startOperationWithStream(self.readStream)
} catch let error as NSError {
self.error = error
self.finishOperation()
}
}
override func streamEventEnd(aStream: NSStream) -> (Bool, NSError?) {
self.fileHandle?.closeFile()
return (true, nil)
}
override func streamEventError(aStream: NSStream) {
super.streamEventError(aStream)
self.fileHandle?.closeFile()
if self.fileURL != nil {
do {
try NSFileManager.defaultManager().removeItemAtURL(self.fileURL!)
} catch _ {
}
}
self.fileURL = nil
}
override func streamEventHasBytes(aStream: NSStream) -> (Bool, NSError?) {
if let inputStream = aStream as? NSInputStream {
var parsetBytes: Int = 0
repeat {
parsetBytes = inputStream.read(self.temporaryBuffer, maxLength: 1024)
if parsetBytes > 0 {
autoreleasepool {
let data = NSData(bytes: self.temporaryBuffer, length: parsetBytes)
self.fileHandle!.writeData(data)
}
}
} while (parsetBytes > 0)
}
return (true, nil)
}
}
| 32.873016 | 111 | 0.593916 |
61a27defe2273a1139538f70c3fc13076490810e | 12,433 | //
// MediaRemoteWrapper.swift
// Accord
//
// Created by evelyn on 2021-12-28.
//
import Combine
import Foundation
// MARK: - SpotifyResponse
struct SpotifyResponse: Codable {
let tracks: Tracks
}
// MARK: - Tracks
struct Tracks: Codable {
let href: String
let items: [SpotifyItem]
let limit: Int
let offset: Int
let total: Int
}
// MARK: - Item
struct SpotifyItem: Codable {
let album: Album
let artists: [Artist]
let availableMarkets: [String]
let discNumber, durationMS: Int
let explicit: Bool
let externalUrls: ExternalUrls
let href: String
let id: String
let isLocal: Bool
let name: String
let popularity: Int
let trackNumber: Int
let type, uri: String
enum CodingKeys: String, CodingKey {
case album, artists
case availableMarkets = "available_markets"
case discNumber = "disc_number"
case durationMS = "duration_ms"
case explicit
case externalUrls = "external_urls"
case href, id
case isLocal = "is_local"
case name, popularity
case trackNumber = "track_number"
case type, uri
}
}
// MARK: - Album
struct Album: Codable {
let albumType: String
let artists: [Artist]
let availableMarkets: [String]
let externalUrls: ExternalUrls
let href: String
let id: String
let images: [SpotifyImage]
let name, releaseDate, releaseDatePrecision: String
let totalTracks: Int
let type, uri: String
enum CodingKeys: String, CodingKey {
case albumType = "album_type"
case artists
case availableMarkets = "available_markets"
case externalUrls = "external_urls"
case href, id, images, name
case releaseDate = "release_date"
case releaseDatePrecision = "release_date_precision"
case totalTracks = "total_tracks"
case type, uri
}
}
// MARK: - Artist
struct Artist: Codable {
let externalUrls: ExternalUrls
let href: String
let id, name, type, uri: String
enum CodingKeys: String, CodingKey {
case externalUrls = "external_urls"
case href, id, name, type, uri
}
}
// MARK: - ExternalUrls
struct ExternalUrls: Codable {
let spotify: String
}
// MARK: - Image
struct SpotifyImage: Codable {
let height: Int
let url: String
let width: Int
}
final class MediaRemoteWrapper {
typealias MRMediaRemoteGetNowPlayingInfoFunction = @convention(c) (DispatchQueue, @escaping ([String: Any]) -> Void) -> Void
static var MRMediaRemoteGetNowPlayingInfo: MRMediaRemoteGetNowPlayingInfoFunction = {
// Load framework
let bundle = CFBundleCreate(kCFAllocatorDefault, NSURL(fileURLWithPath: "/System/Library/PrivateFrameworks/MediaRemote.framework"))
// Get a Swift function for MRMediaRemoteGetNowPlayingInfo
guard let MRMediaRemoteGetNowPlayingInfoPointer = CFBundleGetFunctionPointerForName(bundle, "MRMediaRemoteGetNowPlayingInfo" as CFString) else { fatalError("Could not find symbol in MediaRemote image") }
typealias MRMediaRemoteGetNowPlayingInfoFunction = @convention(c) (DispatchQueue, @escaping ([String: Any]) -> Void) -> Void
return unsafeBitCast(MRMediaRemoteGetNowPlayingInfoPointer, to: MRMediaRemoteGetNowPlayingInfoFunction.self)
}()
static var useSpotifyRPC: Bool = UserDefaults.standard.value(forKey: "SpotifyRPC") as? Bool ?? true
final class Song {
internal init(name: String, artist: String? = nil, duration: Double? = nil, albumName: String? = nil, elapsed: Double? = nil, isMusic: Bool, artworkURL: String?) {
self.name = name
self.artist = artist
self.duration = duration
self.albumName = albumName
self.elapsed = elapsed
self.isMusic = isMusic
self.artworkURL = artworkURL
}
var name: String
var artist: String?
var duration: Double?
var albumName: String?
var elapsed: Double?
var isMusic: Bool
var artworkURL: String?
}
enum NowPlayingErrors: Error {
case errorGettingNowInfoPtr
case noName
}
class func getCurrentlyPlayingSong() -> Future<Song, Error> {
Future { promise in
// Get song info
MRMediaRemoteGetNowPlayingInfo(DispatchQueue.global()) { information in
guard let name = information["kMRMediaRemoteNowPlayingInfoTitle"] as? String else { return promise(.failure(NowPlayingErrors.noName)) }
let isMusic = information["kMRMediaRemoteNowPlayingInfoIsMusicApp"] as? Bool ?? false
let timestamp = information["kMRMediaRemoteNowPlayingInfoTimestamp"] as? String
let formatted = Date().timeIntervalSince1970 - (ISO8601DateFormatter().date(from: timestamp ?? "")?.timeIntervalSince1970 ?? 0)
let progress = (information["kMRMediaRemoteNowPlayingInfoElapsedTime"] as? Double) ?? formatted
if let id = (information["kMRMediaRemoteNowPlayingInfoAlbumiTunesStoreAdamIdentifier"] as? Int) ?? (information["kMRMediaRemoteNowPlayingInfoiTunesStoreIdentifier"] as? Int) {
print("Song has iTunes Store ID")
Request.fetch(url: URL(string: "https://itunes.apple.com/lookup?id=\(String(id))"), completion: { completion in
switch completion {
case let .success(data):
print("Success fetching iTunes Store ID")
if let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let results = dict["results"] as? [[String: Any]]
{
let artworkURL = results.first?["artworkUrl100"] as? String
let song = Song(
name: name,
artist: information["kMRMediaRemoteNowPlayingInfoArtist"] as? String,
duration: information["kMRMediaRemoteNowPlayingInfoDuration"] as? Double,
albumName: information["kMRMediaRemoteNowPlayingInfoAlbum"] as? String,
elapsed: progress,
isMusic: isMusic,
artworkURL: artworkURL
)
promise(.success(song))
}
case let .failure(error):
print(error)
}
})
} else {
print("where is da adam id??", information.keys)
let song = Song(
name: name,
artist: information["kMRMediaRemoteNowPlayingInfoArtist"] as? String,
duration: information["kMRMediaRemoteNowPlayingInfoDuration"] as? Double,
albumName: information["kMRMediaRemoteNowPlayingInfoAlbum"] as? String,
elapsed: progress,
isMusic: isMusic,
artworkURL: nil
)
promise(.success(song))
}
}
}
}
static var bag = Set<AnyCancellable>()
static var rateLimit: Bool = false
static var status: String?
private class func updateWithSong(_ song: Song) {
try? wss.updatePresence(status: status ?? Self.status ?? "dnd", since: 0) {
Activity.current!
Activity(
applicationID: musicRPCAppID,
flags: 1,
name: "Apple Music",
type: 2,
timestamp: Int(Date().timeIntervalSince1970) * 1000,
state: "In \(song.albumName ?? song.name) by \(song.artist ?? "someone")",
details: song.name
)
}
}
private class func updateWithArtworkURL(_ song: Song, artworkURL: String) {
ExternalImages.proxiedURL(appID: musicRPCAppID, url: artworkURL)
.replaceError(with: [])
.sink { out in
guard let url = out.first?.external_asset_path else { return }
try? wss.updatePresence(status: status ?? Self.status ?? "dnd", since: 0) {
Activity.current!
Activity(
flags: 1,
name: "Apple Music",
type: 2,
timestamp: Int(Date().timeIntervalSince1970) * 1000,
endTimestamp: song.duration != nil ? Int(Date().timeIntervalSince1970 + (song.duration!)) * 1000 : nil,
state: song.albumName ?? song.name + " (Single)",
details: song.name,
assets: [
"large_image": "mp:\(url)",
"large_text": song.albumName ?? "Unknown album",
]
)
}
}
.store(in: &bag)
}
class func updatePresence(status: String? = nil) {
guard !Self.rateLimit else { return }
rateLimit = true
MediaRemoteWrapper.getCurrentlyPlayingSong()
.sink(receiveCompletion: {
switch $0 {
case .finished: break
case let .failure(error): print(error)
}
}, receiveValue: { song in
guard song.isMusic else { return }
if let spotifyToken = spotifyToken, Self.useSpotifyRPC {
Request.fetch(SpotifyResponse.self, url: URL(string: "https://api.spotify.com/v1/search?type=track&q=" + ((song.artist ?? "") + "+" + song.name).replacingOccurrences(of: " ", with: "+")), headers: Headers(
contentType: "application/json",
token: "Bearer " + spotifyToken,
type: .GET
)) {
switch $0 {
case let .success(packet):
if let track = packet.tracks.items.first, let imageURL = track.album.images.first?.url.components(separatedBy: "/").last {
try? wss.updatePresence(status: status ?? Self.status ?? "dnd", since: 0) {
Activity.current!
Activity(
flags: 48,
name: "Spotify",
type: 2,
metadata: ["album_id": track.album.id, "artist_ids": track.artists.map(\.id)],
timestamp: Int(Date().timeIntervalSince1970 - (song.elapsed ?? 0)) * 1000,
endTimestamp: Int(Date().timeIntervalSince1970 + (song.duration ?? Double(track.durationMS / 1000))) * 1000,
state: song.artist ?? "Unknown artist",
details: track.name,
assets: [
"large_image": "spotify:" + imageURL,
"large_text": track.album.name,
]
)
}
} else if let url = song.artworkURL {
Self.updateWithArtworkURL(song, artworkURL: url)
} else {
Self.updateWithSong(song)
}
case let .failure(error):
print(error)
}
}
} else if let url = song.artworkURL {
Self.updateWithArtworkURL(song, artworkURL: url)
} else {
Self.updateWithSong(song)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
rateLimit = false
}
})
.store(in: &Self.bag)
}
}
| 40.630719 | 225 | 0.525537 |
8780b17fa565f133826e5665558c70594e1fad1c | 275 | //
// Image.swift
//
//
// Created by hengyu on 2020/10/7.
//
#if canImport(UIKit)
import UIKit
public typealias OBImage = UIKit.UIImage
#elseif canImport(AppKit)
import AppKit
public typealias OBImage = AppKit.NSImage
#else
public typealias OBImage = Data
#endif
| 11.956522 | 41 | 0.72 |
cc6969eef91a382a5bf036970c56a1105f05a9e3 | 547 | //
// ViewController.swift
// PHQRCode
//
// Created by NFDGIT on 04/09/2021.
// Copyright (c) 2021 NFDGIT. All rights reserved.
//
import UIKit
import PHQRCode
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
PHQRCode.init()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.535714 | 80 | 0.654479 |
16b43d5e2dd1deda391bab1eef9b43dd8c5461b7 | 1,413 | //
// SettingsPageRow.swift
// Volume
//
// Created by Cameron Russell on 4/15/21.
// Copyright © 2021 Cornell AppDev. All rights reserved.
//
import SwiftUI
struct SettingsPageRow: View {
let page: SettingsPage
private var row: some View {
HStack {
Image(page.imageName)
.resizable()
.renderingMode(.template)
.foregroundColor(.volume.lightGray)
.frame(width: 24, height: 24)
.padding()
Text(page.info)
.font(.helveticaRegular(size: 16))
.foregroundColor(.black)
Spacer()
Image.volume.backArrow
.foregroundColor(.black)
.rotationEffect(Angle(degrees: 180))
.padding()
}
.padding([.leading, .trailing])
}
var body: some View {
switch page.destination {
case .externalLink(let urlString):
if let url = URL(string: urlString) {
Link(destination: url) {
row
}
}
case .internalView(let view):
NavigationLink(destination: SettingsView.getView(for: view)) {
row
}
}
}
}
//struct SettingsPageRow_Previews: PreviewProvider {
// static var previews: some View {
// SettingsPageRow()
// }
//}
| 25.690909 | 74 | 0.511677 |
2243af51da8182db8c29d92980c8ce5a51cc6545 | 27,360 | //
// StreamCryptor.swift
// Cryptor
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import CommonCrypto
#elseif os(Linux)
import OpenSSL
#endif
///
/// Encrypts or decrypts return results as they become available.
///
/// - Note: The underlying cipher may be a block or a stream cipher.
///
/// Use for large files or network streams.
///
/// For small, in-memory buffers Cryptor may be easier to use.
///
public class StreamCryptor {
#if os(Linux)
//
// Key sizes
//
static let kCCKeySizeAES128 = 16
static let kCCKeySizeAES192 = 24
static let kCCKeySizeAES256 = 32
static let kCCKeySizeDES = 8
static let kCCKeySize3DES = 24
static let kCCKeySizeMinCAST = 5
static let kCCKeySizeMaxCAST = 16
static let kCCKeySizeMinRC2 = 1
static let kCCKeySizeMaxRC2 = 128
static let kCCKeySizeMinBlowfish = 8
static let kCCKeySizeMaxBlowfish = 56
//
// Block sizes
//
static let kCCBlockSizeAES128 = 16
static let kCCBlockSizeDES = 8
static let kCCBlockSize3DES = 8
static let kCCBlockSizeCAST = 8
static let kCCBlockSizeRC2 = 8
static let kCCBlockSizeBlowfish = 8
#endif
///
/// Enumerates Cryptor operations
///
public enum Operation {
/// Encrypting
case encrypt
/// Decrypting
case decrypt
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Convert to native `CCOperation`
func nativeValue() -> CCOperation {
switch self {
case .encrypt:
return CCOperation(kCCEncrypt)
case .decrypt:
return CCOperation(kCCDecrypt)
}
}
#elseif os(Linux)
/// Convert to native value
func nativeValue() -> UInt32 {
switch self {
case .encrypt:
return 0
case .decrypt:
return 1
}
}
#endif
}
///
/// Enumerates valid key sizes.
///
public enum ValidKeySize {
case fixed(Int)
case discrete([Int])
case range(Int, Int)
///
/// Determines if a given `keySize` is valid for this algorithm.
///
/// - Parameter keySize: The size to test for validity.
///
/// - Returns: True if valid, false otherwise.
///
func isValidKeySize(keySize: Int) -> Bool {
switch self {
case .fixed(let fixed):
return (fixed == keySize)
case .range(let min, let max):
return ((keySize >= min) && (keySize <= max))
case .discrete(let values):
return values.contains(keySize)
}
}
///
/// Determines the next valid key size; that is, the first valid key size larger
/// than the given value.
///
/// - Parameter keySize: The size for which the `next` size is desired.
///
/// - Returns: Will return `nil` if the passed in `keySize` is greater than the max.
///
func paddedKeySize(keySize: Int) -> Int? {
switch self {
case .fixed(let fixed):
return (keySize <= fixed) ? fixed : nil
case .range(let min, let max):
return (keySize > max) ? nil : ((keySize < min) ? min : keySize)
case .discrete(let values):
return values.sorted().reduce(nil) { answer, current in
return answer ?? ((current >= keySize) ? current : nil)
}
}
}
}
///
/// Maps CommonCryptoOptions onto a Swift struct.
///
public struct Options: OptionSet {
public typealias RawValue = Int
public let rawValue: RawValue
/// Convert from a native value (i.e. `0`, `kCCOptionpkcs7Padding`, `kCCOptionECBMode`)
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
/// Convert from a native value (i.e. `0`, `kCCOptionpkcs7Padding`, `kCCOptionECBMode`)
public init(_ rawValue: RawValue) {
self.init(rawValue: rawValue)
}
/// No options
public static let none = Options(rawValue: 0)
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Use padding. Needed unless the input is a integral number of blocks long.
public static var pkcs7Padding = Options(rawValue:kCCOptionPKCS7Padding)
/// Electronic Code Book Mode. Don't use this.
public static var ecbMode = Options(rawValue:kCCOptionECBMode)
#elseif os(Linux)
/// Use padding. Needed unless the input is a integral number of blocks long.
public static var pkcs7Padding = Options(rawValue:0x0001)
/// Electronic Code Book Mode. Don't use this.
public static var ecbMode = Options(rawValue:0x0002)
#endif
}
///
/// Enumerates available algorithms
///
public enum Algorithm {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Advanced Encryption Standard
/// - Note: aes and aes128 are equivalent.
case aes, aes128, aes192, aes256
/// Data Encryption Standard
case des
/// Triple des
case tripleDes
/// cast
case cast
/// rc2
case rc2
/// blowfish
case blowfish
#elseif os(Linux)
/// Advanced Encryption Standard
/// - Note: aes and aes128 are equivalent.
case aes, aes128, aes192, aes256
/// Data Encryption Standard
case des
/// Triple des
case tripleDes
/// cast
case cast
/// rc2
case rc2
/// blowfish
case blowfish
#endif
/// Blocksize, in bytes, of algorithm.
public var blockSize: Int {
switch self {
case .aes, .aes128, .aes192, .aes256:
return kCCBlockSizeAES128
case .des:
return kCCBlockSizeDES
case .tripleDes:
return kCCBlockSize3DES
case .cast:
return kCCBlockSizeCAST
case .rc2:
return kCCBlockSizeRC2
case .blowfish:
return kCCBlockSizeBlowfish
}
}
public var defaultKeySize: Int {
switch self {
case .aes, .aes128:
return kCCKeySizeAES128
case .aes192:
return kCCKeySizeAES192
case .aes256:
return kCCKeySizeAES256
case .des:
return kCCKeySizeDES
case .tripleDes:
return kCCKeySize3DES
case .cast:
return kCCKeySizeMinCAST
case .rc2:
return kCCKeySizeMinRC2
case .blowfish:
return kCCKeySizeMinBlowfish
}
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Native, CommonCrypto constant for algorithm.
func nativeValue() -> CCAlgorithm {
switch self {
case .aes, .aes128, .aes192, .aes256:
return CCAlgorithm(kCCAlgorithmAES)
case .des:
return CCAlgorithm(kCCAlgorithmDES)
case .tripleDes:
return CCAlgorithm(kCCAlgorithm3DES)
case .cast:
return CCAlgorithm(kCCAlgorithmCAST)
case .rc2:
return CCAlgorithm(kCCAlgorithmRC2)
case .blowfish:
return CCAlgorithm(kCCAlgorithmBlowfish)
}
}
#elseif os(Linux)
#if swift(>=4.2)
/// Native, OpenSSL function for algorithm.
func nativeValue(options: Options) -> OpaquePointer? {
if options == .pkcs7Padding || options == .none {
switch self {
case .aes, .aes128:
return .init(EVP_aes_128_cbc())
case .aes192:
return .init(EVP_aes_192_cbc())
case .aes256:
return .init(EVP_aes_256_cbc())
case .des:
return .init(EVP_des_cbc())
case .tripleDes:
return .init(EVP_des_ede3_cbc())
case .cast:
return .init(EVP_cast5_cbc())
case .rc2:
return .init(EVP_rc2_cbc())
case .blowfish:
return .init(EVP_bf_cbc())
}
}
if options == .ecbMode {
switch self {
case .aes, .aes128:
return .init(EVP_aes_128_ecb())
case .aes192:
return .init(EVP_aes_192_ecb())
case .aes256:
return .init(EVP_aes_256_ecb())
case .des:
return .init(EVP_des_ecb())
case .tripleDes:
return .init(EVP_des_ede3_ecb())
case .cast:
return .init(EVP_cast5_ecb())
case .rc2:
return .init(EVP_rc2_ecb())
case .blowfish:
return .init(EVP_bf_ecb())
}
}
fatalError("Unsupported options and/or algorithm.")
}
#else
/// Native, OpenSSL function for algorithm.
func nativeValue(options: Options) -> UnsafePointer<EVP_CIPHER> {
if options == .pkcs7Padding || options == .none {
switch self {
case .aes, .aes128:
return EVP_aes_128_cbc()
case .aes192:
return EVP_aes_192_cbc()
case .aes256:
return EVP_aes_256_cbc()
case .des:
return EVP_des_cbc()
case .tripleDes:
return EVP_des_ede3_cbc()
case .cast:
return EVP_cast5_cbc()
case .rc2:
return EVP_rc2_cbc()
case .blowfish:
return EVP_bf_cbc()
}
}
if options == .ecbMode {
switch self {
case .aes, .aes128:
return EVP_aes_128_ecb()
case .aes192:
return EVP_aes_192_ecb()
case .aes256:
return EVP_aes_256_ecb()
case .des:
return EVP_des_ecb()
case .tripleDes:
return EVP_des_ede3_ecb()
case .cast:
return EVP_cast5_ecb()
case .rc2:
return EVP_rc2_ecb()
case .blowfish:
return EVP_bf_ecb()
}
}
fatalError("Unsupported options and/or algorithm.")
}
#endif
#endif
///
/// Determines the valid key size for this algorithm
///
/// - Returns: Valid key size for this algorithm.
///
func validKeySize() -> ValidKeySize {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
switch self {
case .aes, .aes128, .aes192, .aes256:
return .discrete([kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256])
case .des:
return .fixed(kCCKeySizeDES)
case .tripleDes:
return .fixed(kCCKeySize3DES)
case .cast:
return .range(kCCKeySizeMinCAST, kCCKeySizeMaxCAST)
case .rc2:
return .range(kCCKeySizeMinRC2, kCCKeySizeMaxRC2)
case .blowfish:
return .range(kCCKeySizeMinBlowfish, kCCKeySizeMaxBlowfish)
}
#elseif os(Linux)
switch self {
case .aes, .aes128:
return .fixed(kCCKeySizeAES128)
case .aes192:
return .fixed(kCCKeySizeAES192)
case .aes256:
return .fixed(kCCKeySizeAES256)
case .des:
return .fixed(kCCKeySizeDES)
case .tripleDes:
return .fixed(kCCKeySize3DES)
case .cast:
return .range(kCCKeySizeMinCAST, kCCKeySizeMaxCAST)
case .rc2:
return .range(kCCKeySizeMinRC2, kCCKeySizeMaxRC2)
case .blowfish:
return .range(kCCKeySizeMinBlowfish, kCCKeySizeMaxBlowfish)
}
#endif
}
///
/// Tests if a given keySize is valid for this algorithm
///
/// - Parameter keySize: The key size to be validated.
///
/// - Returns: True if valid, false otherwise.
///
func isValidKeySize(keySize: Int) -> Bool {
return self.validKeySize().isValidKeySize(keySize: keySize)
}
///
/// Calculates the next, if any, valid keySize greater or equal to a given `keySize` for this algorithm
///
/// - Parameter keySize: Key size for which the next size is requested.
///
/// - Returns: Next key size or nil
///
func paddedKeySize(keySize: Int) -> Int? {
return self.validKeySize().paddedKeySize(keySize: keySize)
}
}
///
/// The status code resulting from the last method call to this Cryptor.
/// Used to get additional information when optional chaining collapes.
///
public internal(set) var status: Status = .success
///
/// Context obtained. True if we have it, false otherwise.
///
private var haveContext: Bool = false
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// CommonCrypto Context
private var context = UnsafeMutablePointer<CCCryptorRef?>.allocate(capacity: 1)
#elseif os(Linux)
#if swift(>=4.2)
/// OpenSSL Cipher Context
private let context: OpaquePointer? = .init(EVP_CIPHER_CTX_new())
#else
/// OpenSSL Cipher Context
private let context: UnsafeMutablePointer<EVP_CIPHER_CTX> = EVP_CIPHER_CTX_new()
#endif
/// Operation
private var operation: Operation = .encrypt
/// The algorithm
private var algorithm: Algorithm
#endif
// MARK: Lifecycle Methods
///
/// Default Initializer
///
/// - Parameters:
/// - operation: The operation to perform see Operation (Encrypt, Decrypt)
/// - algorithm: The algorithm to use see Algorithm (AES, des, tripleDes, cast, rc2, blowfish)
/// - keyBuffer: Pointer to key buffer
/// - keyByteCount: Number of bytes in the key
/// - ivBuffer: Initialization vector buffer
/// - ivLength: Length of the ivBuffer
///
/// - Returns: New StreamCryptor instance.
///
public init(operation: Operation, algorithm: Algorithm, options: Options, keyBuffer: [UInt8], keyByteCount: Int, ivBuffer: UnsafePointer<UInt8>, ivLength: Int = 0) throws {
guard algorithm.isValidKeySize(keySize: keyByteCount) else {
throw CryptorError.invalidKeySize
}
guard options.contains(.ecbMode) || ivLength == algorithm.blockSize else {
throw CryptorError.invalidIVSizeOrLength
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let rawStatus = CCCryptorCreate(operation.nativeValue(), algorithm.nativeValue(), CCOptions(options.rawValue), keyBuffer, keyByteCount, ivBuffer, self.context)
if let status = Status.fromRaw(status: rawStatus) {
self.status = status
} else {
throw CryptorError.fail(rawStatus, "Cryptor init returned unexpected status.")
}
self.haveContext = true
#elseif os(Linux)
self.algorithm = algorithm
self.operation = operation
var rawStatus: Int32
switch self.operation {
case .encrypt:
rawStatus = EVP_EncryptInit_ex(.make(optional: self.context), .make(optional: algorithm.nativeValue(options: options)), nil, keyBuffer, ivBuffer)
case .decrypt:
rawStatus = EVP_DecryptInit(.make(optional: self.context), .make(optional: algorithm.nativeValue(options: options)), keyBuffer, ivBuffer)
}
if rawStatus == 0 {
let errorCode = ERR_get_error()
if let status = Status.fromRaw(status: errorCode) {
self.status = status
} else {
throw CryptorError.fail(Int32(errorCode), "Cryptor init returned unexpected status.")
}
}
self.haveContext = true
// Default to no padding...
var needPadding: Int32 = 0
if options == .pkcs7Padding {
needPadding = 1
}
// Note: This call must be AFTER the init call above...
EVP_CIPHER_CTX_set_padding(.make(optional: self.context), needPadding)
self.status = Status.success
#endif
}
///
/// Creates a new StreamCryptor
///
/// - Parameters:
/// - operation: The operation to perform see Operation (Encrypt, Decrypt)
/// - algorithm: The algorithm to use see Algorithm (AES, des, tripleDes, cast, rc2, blowfish)
/// - key: A byte array containing key data
/// - iv: A byte array containing initialization vector
///
/// - Returns: New StreamCryptor instance.
///
public convenience init(operation: Operation, algorithm: Algorithm, options: Options, key: [UInt8], iv: [UInt8]) throws {
guard let paddedKeySize = algorithm.paddedKeySize(keySize: key.count) else {
throw CryptorError.invalidKeySize
}
try self.init(operation:operation,
algorithm:algorithm,
options:options,
keyBuffer:CryptoUtils.zeroPad(byteArray:key, blockSize: paddedKeySize),
keyByteCount:paddedKeySize,
ivBuffer:iv,
ivLength:iv.count)
}
///
/// Creates a new StreamCryptor
///
/// - Parameters:
/// - operation: The operation to perform see Operation (Encrypt, Decrypt)
/// - algorithm: The algorithm to use see Algorithm (AES, des, tripleDes, cast, rc2, blowfish)
/// - key: A string containing key data (will be interpreted as UTF8)
/// - iv: A string containing initialization vector data (will be interpreted as UTF8)
///
/// - Returns: New StreamCryptor instance.
///
public convenience init(operation: Operation, algorithm: Algorithm, options: Options, key: String, iv: String) throws {
let keySize = key.utf8.count
guard let paddedKeySize = algorithm.paddedKeySize(keySize: keySize) else {
throw CryptorError.invalidKeySize
}
try self.init(operation:operation,
algorithm:algorithm,
options:options,
keyBuffer:CryptoUtils.zeroPad(string: key, blockSize: paddedKeySize),
keyByteCount:paddedKeySize,
ivBuffer:iv,
ivLength:iv.utf8.count)
}
///
/// Cleanup
///
deinit {
// Ensure we've got a context before attempting to get rid of it...
if self.haveContext == false {
return
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
// Ensure we've got a context before attempting to get rid of it...
if self.context.pointee == nil {
return
}
let rawStatus = CCCryptorRelease(self.context.pointee)
if let status = Status.fromRaw(status: rawStatus) {
if status != .success {
NSLog("WARNING: CCCryptoRelease failed with status \(rawStatus).")
}
} else {
fatalError("CCCryptorUpdate returned unexpected status.")
}
#if swift(>=4.1)
context.deallocate()
#else
context.deallocate(capacity: 1)
#endif
self.haveContext = false
#elseif os(Linux)
EVP_CIPHER_CTX_free(.make(optional: self.context))
self.haveContext = false
#endif
}
// MARK: Public Methods
///
/// Add the contents of an Data buffer to the current encryption/decryption operation.
///
/// - Parameters:
/// - dataIn: The input data
/// - byteArrayOut: Output data
///
/// - Returns: A tuple containing the number of output bytes produced and the status (see Status)
///
public func update(dataIn: Data, byteArrayOut: inout [UInt8]) -> (Int, Status) {
let dataOutAvailable = byteArrayOut.count
var dataOutMoved = 0
dataIn.withUnsafeBytes() { (buffer: UnsafePointer<UInt8>) in
_ = update(bufferIn: buffer, byteCountIn: dataIn.count, bufferOut: &byteArrayOut, byteCapacityOut: dataOutAvailable, byteCountOut: &dataOutMoved)
}
return (dataOutMoved, self.status)
}
///
/// Add the contents of an NSData buffer to the current encryption/decryption operation.
///
/// - Parameters:
/// - dataIn: The input data
/// - byteArrayOut: Output data
///
/// - Returns: A tuple containing the number of output bytes produced and the status (see Status)
///
public func update(dataIn: NSData, byteArrayOut: inout [UInt8]) -> (Int, Status) {
let dataOutAvailable = byteArrayOut.count
var dataOutMoved = 0
var ptr = dataIn.bytes.assumingMemoryBound(to: UInt8.self).pointee
_ = update(bufferIn: &ptr, byteCountIn: dataIn.length, bufferOut: &byteArrayOut, byteCapacityOut: dataOutAvailable, byteCountOut: &dataOutMoved)
return (dataOutMoved, self.status)
}
///
/// Add the contents of a byte array to the current encryption/decryption operation.
///
/// - Parameters:
/// - byteArrayIn: The input data
/// - byteArrayOut: Output data
///
/// - Returns: A tuple containing the number of output bytes produced and the status (see Status)
///
public func update(byteArrayIn: [UInt8], byteArrayOut: inout [UInt8]) -> (Int, Status) {
let dataOutAvailable = byteArrayOut.count
var dataOutMoved = 0
_ = update(bufferIn: byteArrayIn, byteCountIn: byteArrayIn.count, bufferOut: &byteArrayOut, byteCapacityOut: dataOutAvailable, byteCountOut: &dataOutMoved)
return (dataOutMoved, self.status)
}
///
/// Add the contents of a string (interpreted as UTF8) to the current encryption/decryption operation.
///
/// - Parameters:
/// - byteArrayIn: The input data
/// - byteArrayOut: Output data
///
/// - Returns: A tuple containing the number of output bytes produced and the status (see Status)
///
public func update(stringIn: String, byteArrayOut: inout [UInt8]) -> (Int, Status) {
let dataOutAvailable = byteArrayOut.count
var dataOutMoved = 0
_ = update(bufferIn: stringIn, byteCountIn: stringIn.utf8.count, bufferOut: &byteArrayOut, byteCapacityOut: dataOutAvailable, byteCountOut: &dataOutMoved)
return (dataOutMoved, self.status)
}
///
/// Retrieves all remaining encrypted or decrypted data from this cryptor.
///
/// - Note: If the underlying algorithm is an block cipher and the padding option has
/// not been specified and the cumulative input to the cryptor has not been an integral
/// multiple of the block length this will fail with an alignment error.
///
/// - Note: This method updates the status property
///
/// - Parameter byteArrayOut: The output bffer
///
/// - Returns: a tuple containing the number of output bytes produced and the status (see Status)
///
public func final(byteArrayOut: inout [UInt8]) -> (Int, Status) {
let dataOutAvailable = byteArrayOut.count
var dataOutMoved = 0
_ = final(bufferOut: &byteArrayOut, byteCapacityOut: dataOutAvailable, byteCountOut: &dataOutMoved)
return (dataOutMoved, self.status)
}
// MARK: - Low-level interface
///
/// Update the buffer
///
/// - Parameters:
/// - bufferIn: Pointer to input buffer
/// - inByteCount: Number of bytes contained in input buffer
/// - bufferOut: Pointer to output buffer
/// - outByteCapacity: Capacity of the output buffer in bytes
/// - outByteCount: On successful completion, the number of bytes written to the output buffer
///
/// - Returns: Status of the update
///
public func update(bufferIn: UnsafeRawPointer, byteCountIn: Int, bufferOut: UnsafeMutablePointer<UInt8>, byteCapacityOut: Int, byteCountOut: inout Int) -> Status {
if self.status == .success {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let rawStatus = CCCryptorUpdate(self.context.pointee, bufferIn, byteCountIn, bufferOut, byteCapacityOut, &byteCountOut)
if let status = Status.fromRaw(status: rawStatus) {
self.status = status
} else {
fatalError("CCCryptorUpdate returned unexpected status.")
}
#elseif os(Linux)
var rawStatus: Int32
var outLength: Int32 = 0
switch self.operation {
case .encrypt:
rawStatus = EVP_EncryptUpdate(.make(optional: self.context), bufferOut, &outLength, bufferIn.assumingMemoryBound(to: UInt8.self), Int32(byteCountIn))
case .decrypt:
rawStatus = EVP_DecryptUpdate(.make(optional: self.context), bufferOut, &outLength, bufferIn.assumingMemoryBound(to: UInt8.self), Int32(byteCountIn))
}
byteCountOut = Int(outLength)
if rawStatus == 0 {
let errorCode = ERR_get_error()
if let status = Status.fromRaw(status: errorCode) {
self.status = status
} else {
fatalError("Cryptor update returned unexpected status.")
}
} else {
self.status = Status.success
}
#endif
}
return self.status
}
///
/// Retrieves all remaining encrypted or decrypted data from this cryptor.
///
/// - Note: If the underlying algorithm is an block cipher and the padding option has
/// not been specified and the cumulative input to the cryptor has not been an integral
/// multiple of the block length this will fail with an alignment error.
///
/// - Note: This method updates the status property
///
/// - Parameters:
/// - bufferOut: Pointer to output buffer
/// - outByteCapacity: Capacity of the output buffer in bytes
/// - outByteCount: On successful completion, the number of bytes written to the output buffer
///
/// - Returns: Status of the update
///
public func final(bufferOut: UnsafeMutablePointer<UInt8>, byteCapacityOut: Int, byteCountOut: inout Int) -> Status {
if self.status == Status.success {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let rawStatus = CCCryptorFinal(self.context.pointee, bufferOut, byteCapacityOut, &byteCountOut)
if let status = Status.fromRaw(status: rawStatus) {
self.status = status
} else {
fatalError("CCCryptorUpdate returned unexpected status.")
}
#elseif os(Linux)
var rawStatus: Int32
var outLength: Int32 = Int32(byteCapacityOut)
switch self.operation {
case .encrypt:
rawStatus = EVP_EncryptFinal(.make(optional: self.context), bufferOut, &outLength)
case .decrypt:
rawStatus = EVP_DecryptFinal(.make(optional: self.context), bufferOut, &outLength)
}
byteCountOut = Int(outLength)
if rawStatus == 0 {
let errorCode = ERR_get_error()
if let status = Status.fromRaw(status: errorCode) {
self.status = status
} else {
fatalError("Cryptor final returned unexpected status.")
}
} else {
self.status = Status.success
}
#endif
}
return self.status
}
///
/// Determines the number of bytes that will be output by this Cryptor if inputBytes of additional
/// data is input.
///
/// - Parameters:
/// - inputByteCount: Number of bytes that will be input.
/// - isFinal: True if buffer to be input will be the last input buffer, false otherwise.
///
/// - Returns: The final output length
///
public func getOutputLength(inputByteCount: Int, isFinal: Bool = false) -> Int {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
return CCCryptorGetOutputLength(self.context.pointee, inputByteCount, isFinal)
#elseif os(Linux)
if inputByteCount == 0 {
return self.algorithm.blockSize
}
return (inputByteCount + self.algorithm.blockSize - (inputByteCount % self.algorithm.blockSize))
#endif
}
}
| 26.282421 | 173 | 0.622588 |
71cc1f39e94a84929df4e203d1ade818a05e6a37 | 748 | //
// Race.swift
// HSTracker
//
// Created by Benjamin Michotte on 13/07/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
enum Race: String, CaseIterable {
case invalid,
bloodelf,
draenei,
dwarf,
gnome,
goblin,
human,
nightelf,
orc,
tauren,
troll,
undead,
worgen,
goblin2,
murloc,
demon,
scourge,
mechanical,
elemental,
ogre,
beast,
totem,
nerubian,
pirate,
dragon,
blank,
all,
race_27,
race_28,
race_29,
race_30,
race_31,
race_32,
race_33,
race_34,
race_35,
race_36,
race_37,
egg,
race_39,
race_40,
race_41,
race_42,
quilboar
}
| 13.122807 | 60 | 0.564171 |
0e76336c87d683877adaa2e99a6ea91f3be08daa | 2,982 | import CoreBluetooth
/**
* @class BluetoothManager
* @since 0.5.0
* @hidden
*/
open class BluetoothManager : JavaScriptClass, CBPeripheralManagerDelegate {
//--------------------------------------------------------------------------
// MARK: Properties
//--------------------------------------------------------------------------
/**
* Whether bluetooth services are enabled.
* @property enabled
* @since 0.5.0
*/
private(set) public var enabled: Bool = false
/**
* Whether bluetooth services were requested.
* @property requested
* @since 0.5.0
*/
private(set) public var requested: Bool = false
/**
* Whether bluetooth services were authorized.
* @property authorized
* @since 0.5.0
*/
private(set) public var authorized: Bool = false
/**
* @property peripheralManager
* @since 0.5.0
* @hidden
*/
private(set) public var peripheralManager: CBPeripheralManager!
//--------------------------------------------------------------------------
// MARK: Peripheral Manager Delegate
//--------------------------------------------------------------------------
/**
* @method peripheralManagerDidUpdateState
* @since 0.5.0
* @hidden
*/
open func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
let enabled = peripheral.state == .poweredOn
if (self.enabled != enabled) {
self.enabled = enabled
self.property("enabled", boolean: enabled)
if (enabled) {
self.holder.callMethod("nativeEnable")
} else {
self.holder.callMethod("nativeDisable")
}
}
}
//--------------------------------------------------------------------------
// MARK: JS Functions
//--------------------------------------------------------------------------
/**
* @method jsFunction_init
* @since 0.5.0
* @hidden
*/
@objc open func jsFunction_init(callback: JavaScriptFunctionCallback) {
self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: 0])
self.enabled = self.isServiceEnabled()
self.requested = self.isServiceRequested()
self.authorized = self.isServiceAuthorized()
self.property("enabled", boolean: self.enabled)
self.property("requested", boolean: self.requested)
self.property("authorized", boolean: self.authorized)
}
//--------------------------------------------------------------------------
// MARK: Private API
//--------------------------------------------------------------------------
/**
* @method isServiceEnabled
* @since 0.1.0
* @hidden
*/
private func isServiceEnabled() -> Bool {
return self.peripheralManager.state == .poweredOn
}
/**
* @method isServiceRequested
* @since 0.5.0
* @hidden
*/
private func isServiceRequested() -> Bool {
return true // TODO
}
/**
* @method isServiceAuthorized
* @since 0.5.0
* @hidden
*/
private func isServiceAuthorized() -> Bool {
return true // TODO
}
}
| 24.442623 | 129 | 0.533199 |
293f7800f7cbc851fc829f45b5a2276ad1cb7426 | 1,541 | //
// AppDelegate.swift
// iRCON
//
// Created by Jack Bruienne on 10/25/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillEnterForeground(_ application: UIApplication) {
application.windows.forEach {($0.rootViewController as? ServersViewController)?.tableView.reloadData()}
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.585366 | 179 | 0.744971 |
bf012bf8a3aabb60312e0267e98727ad6cc997d3 | 105 | public protocol SKSelectable: SKNode {}
public protocol SKSelectableShape: SKShapeNode, SKSelectable {}
| 26.25 | 63 | 0.819048 |
9022acbfd26659c0f9af9ca60eefa00b43b4ceb5 | 8,205 | //
// UISearchS.swift
// Saily
//
// Created by Lakr Aream on 2019/7/14.
// Copyright © 2019 Lakr Aream. All rights reserved.
//
class UISearchS: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
var table_view: UITableView = UITableView()
var header_view: UIView?
var timer : Timer?
var contentView = UIScrollView()
// 控制 NAV
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// 防止导航抽风
let dummy = UIView()
view.addSubview(dummy)
dummy.snp.makeConstraints { (x) in
x.edges.equalTo(self.view.snp.edges)
}
table_view.separatorColor = .clear
table_view.clipsToBounds = false
table_view.delegate = self
table_view.dataSource = self
table_view.allowsSelection = false
table_view.backgroundView?.backgroundColor = .clear
table_view.backgroundColor = .clear
self.view.backgroundColor = LKRoot.ins_color_manager.read_a_color("main_background")
contentView.contentSize.height = sum_the_height() + 80
contentView.contentSize.width = UIScreen.main.bounds.width
table_view.isScrollEnabled = false
table_view.bounces = false
contentView.delegate = self
contentView.showsVerticalScrollIndicator = false
contentView.showsHorizontalScrollIndicator = false
contentView.decelerationRate = .fast
view.addSubview(contentView)
contentView.addSubview(table_view)
contentView.snp.makeConstraints { (x) in
x.edges.equalTo(self.view.snp.edges)
}
table_view.snp.makeConstraints { (x) in
x.edges.equalTo(self.contentView.snp.edges)
}
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timer_call), userInfo: nil, repeats: true)
timer?.fire()
DispatchQueue.main.async {
self.timer_call()
}
}
var last_size = CGFloat(0)
@objc func timer_call() {
if last_size != sum_the_height() {
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
self.contentView.contentSize.height = self.sum_the_height()
self.table_view.snp.remakeConstraints({ (x) in
x.edges.equalTo(self.contentView)
x.width.equalTo(UIScreen.main.bounds.width)
x.height.equalTo(self.sum_the_height())
})
}, completion: nil)
}
}
func sum_the_height() -> CGFloat {
var ret = CGFloat(0)
for i in 0...5 {
ret += do_the_height_math(indexPath: IndexPath(row: i, section: 0))
}
ret += 38
return ret - 999
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return do_the_height_math(indexPath: indexPath)
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return do_the_height_math(indexPath: indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
table_view.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let ret = UITableViewCell()
switch indexPath.row {
case 0: // 处理一下头条
let header = LKRoot.ins_view_manager.create_AS_home_header_view(title_str: "搜索中心".localized(),
sub_str: "在这里,寻找可能".localized(),
image_str: "NAMED:SearchIcon",
sep_enabled: false)
ret.contentView.addSubview(header)
header.snp.makeConstraints { (x) in
x.edges.equalTo(ret.contentView.snp.edges).inset(UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0))
}
ret.backgroundColor = .clear
case 1:
let fake_search = common_views.LKNonWorkSearchBar()
fake_search.apart_init(txt: "查找插件/文章".localized())
let real_search = UIButton()
ret.addSubview(fake_search)
ret.addSubview(real_search)
real_search.addTarget(self, action: #selector(real_search_call), for: .touchUpInside)
fake_search.snp.makeConstraints { (x) in
x.left.equalTo(ret.snp.left).offset(24)
x.right.equalTo(ret.snp.right).offset(-24)
x.top.equalTo(ret.snp.top) // .offset(2)
x.bottom.equalTo(ret.snp.bottom) // .offset(-2)
}
real_search.snp.makeConstraints { (x) in
x.edges.equalTo(ret.snp.edges)
}
ret.backgroundColor = .clear
case 2:
let sep = UIView()
sep.backgroundColor = LKRoot.ins_color_manager.read_a_color("tabbar_untint")
sep.alpha = 0.3
ret.addSubview(sep)
sep.snp.makeConstraints { (x) in
x.bottom.equalTo(ret.snp.bottom).offset(-2)
x.height.equalTo(0.5)
x.left.equalTo(ret.snp.left)
x.right.equalTo(ret.snp.right)
}
ret.backgroundColor = .clear
case 3:
let package_repo_manager = LKRoot.manager_reg.rp
package_repo_manager.apart_init(father: tableView)
ret.contentView.addSubview(package_repo_manager)
package_repo_manager.snp.makeConstraints { (x) in
x.edges.equalTo(ret.contentView.snp.edges)
}
ret.backgroundView?.backgroundColor = .clear
ret.backgroundColor = .clear
case 4:
let sep = UIView()
sep.backgroundColor = LKRoot.ins_color_manager.read_a_color("tabbar_untint")
sep.alpha = 0.3
ret.addSubview(sep)
sep.snp.makeConstraints { (x) in
x.centerY.equalTo(ret.snp.centerY)
x.height.equalTo(0.5)
x.left.equalTo(ret.snp.left)
x.right.equalTo(ret.snp.right)
}
ret.backgroundColor = .clear
case 5:
let package_repo_manager = LKRoot.manager_reg.ru
package_repo_manager.apart_init(father: tableView)
ret.contentView.addSubview(package_repo_manager)
package_repo_manager.snp.makeConstraints { (x) in
x.edges.equalTo(ret.contentView.snp.edges)
}
ret.backgroundView?.backgroundColor = .clear
ret.backgroundColor = .clear
default:
ret.backgroundColor = .clear
}
return ret
}
func do_the_height_math(indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0: return 150
case 1: return 35
case 2: return 28
case 3:
if LKRoot.container_manage_cell_status["RP_IS_COLLAPSED"] ?? true {
return 127
} else {
return 127 + CGFloat(LKRoot.container_packages_randomfun_DBSync.count) * 62
}
case 4: return 18
case 5:
var count = LKRoot.container_recent_update.count
if count > LKRoot.manager_reg.ru.limit {
count = LKRoot.manager_reg.ru.limit
}
count += 1
return CGFloat(count) * 62 + 1024
default: return 0
}
}
@objc func real_search_call() {
let new = LKPackageSearch()
presentViewController(some: new)
}
}
| 38.886256 | 145 | 0.582572 |
2294b2ab17e551a08a7bbac7d9467b08cc2feded | 276 | //
// QLipaApp.swift
// QLipa
//
// Created by user on 2021/05/09.
//
import SwiftUI
@main
struct QLipaApp: App {
var body: some Scene {
DocumentGroup(newDocument: QLipaDocument()) { file in
ContentView(document: file.$document)
}
}
}
| 15.333333 | 61 | 0.597826 |
f4175dd3e54fc251562346cbb8d1266b3361ee71 | 2,174 | //
// AppDelegate.swift
// GCDExample
//
// Created by Jon Hoffman on 3/16/19.
// Copyright © 2019 Jon Hoffman. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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.255319 | 285 | 0.75483 |
fb9ddb7265495e9a3e69ad8ecda1d37ba9a6cded | 1,357 | //
// RoomRepository.swift
// chat
//
// Created by admin on 15.02.2022.
//
import Foundation
class RoomRepository : RoomRepositoryProtocol {
private let roomApiService: RoomApiServiceProtocol
private let messageCache: MessageCache
init(roomApiService: RoomApiServiceProtocol, messageCache: MessageCache) {
self.roomApiService = roomApiService
self.messageCache = messageCache
}
func getRoomHistory(room: String, completion: @escaping ([MessageModel], Error?) -> Void) {
self.roomApiService.getRoomHistory(roomName: room, completion: {response, error in
var messageModels = [MessageModel]()
let cachedMessageModels = self.messageCache.getCachedMessages(room: room)
if (response != nil) {
messageModels = response?.result?.map({result in MessageModel(roomHistoryResult: result)}) ?? [MessageModel]()
let unsentLetters = cachedMessageModels.filter { !($0.wasSent ?? true) }
messageModels.append(contentsOf: unsentLetters)
self.messageCache.rewriteAllCachedMessages(messages: messageModels)
} else {
messageModels = cachedMessageModels
}
completion(messageModels, error)
})
}
}
| 35.710526 | 126 | 0.628592 |
7ae1eb9abb08bd869aa198f80f5f66c1cd1d21eb | 652 | //
// LocationTableViewCell.swift
// Everything Rick and Morty
//
// Created by Gareth Harte on 13/05/2018.
// Copyright © 2018 gharte. All rights reserved.
//
import UIKit
class LocationTableViewCell: UITableViewCell {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var typeLabel: UILabel!
@IBOutlet var dimensionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
}
func setUpWith(locationModel location: Location) {
nameLabel.text = location.name
typeLabel.text = location.type
dimensionLabel.text = location.dimension
}
}
| 22.482759 | 54 | 0.671779 |
d6ff199c71b8b524cfad43de0ed8c05abead852a | 547 | //
// TitleToggleCell+Theme.swift
// HFoundation
//
// Created by Vlad Z. on 2/18/20.
// Copyright © 2020 Vlad Z. All rights reserved.
//
import HUIKit
import ThemeManager
import UIKit
public extension TitleToggleCell {
func applyTheme(usingTheme theme: ThemeProtocol = ThemeContainer.defaultTheme) {
titleLabel.applyLabelStyle(.title(attribute: .regular), customizing: { label, _ in
label.textColor = .color(forPalette: .grey300)
})
toggle.onTintColor = .color(forPalette: .primary)
}
}
| 24.863636 | 90 | 0.678245 |
e527474f6ba98abc51275eae340872c2403683f2 | 1,071 | //
// Array+InsertionSort.swift
// Demo
//
// Created by yu on 2021/1/18.
//
extension Array where Element: Comparable {
public mutating func insertionSort() {
insertionSort(by: <)
}
public mutating func insertionSort(by areInIncreasingOrder: (Element, Element) -> Bool) {
guard self.count > 1 else { return }
for i in 1...self.count - 1 {
let current = self[i]
var preIndex = i - 1
while preIndex >= 0 && areInIncreasingOrder(current, self[preIndex]) {
self[preIndex + 1] = self[preIndex]
preIndex -= 1
}
self[preIndex + 1] = current
}
}
}
public func insertionSort(_ nums: inout [Int]) {
guard nums.count > 1 else { return }
for i in 1..<nums.count {
let current = nums[i]
var preIndex = i - 1
while preIndex >= 0 && nums[preIndex] > current {
nums[preIndex + 1] = nums[preIndex]
preIndex -= 1
}
nums[preIndex + 1] = current
}
}
| 26.121951 | 93 | 0.531279 |
621741046975016b522d3261e9fec37badddfad3 | 172 | //
// Actions+ResendRestoreLink.swift
// Core
//
// Created by Ihor Yarovyi on 1/3/22.
//
import Foundation
public extension Actions {
enum ResendRestoreLink {}
}
| 13.230769 | 38 | 0.686047 |
39b0539d412bbf93984f0297c698e8bfad3fa5a2 | 2,455 | //
// SimpleVisualization.swift
// swiftled-2
//
// Created by Michael Lewis on 7/29/16.
//
//
import Foundation
import RxSwift
import Cleanse
import OPC
class SimpleVisualization : Visualization {
let timeMultiplier = SliderControl<Float>(bounds: -10.0..<10.0, defaultValue: 1, name: "Time Multiplier")
let ledCount: Int
let segmentLength: Int
public var controls: Observable<[Control]> {
return Observable.just([
timeMultiplier,
])
}
init(
ledCount: TaggedProvider<LedCount>,
segmentLength: TaggedProvider<SegmentLength>) {
self.ledCount = ledCount.get()
self.segmentLength = segmentLength.get()
}
public static func configureRoot(binder bind: ReceiptBinder<BaseVisualization>) -> BindingReceipt<BaseVisualization> {
return bind.to(factory: SimpleVisualization.init)
}
public let name = "Simple"
public func bind(_ ticker: Observable<WriteContext>) -> Disposable {
let ledCount = self.ledCount
let segmentLength = self.segmentLength
var offset = 0.0
return ticker.subscribe(onNext: {[weak self] context in
guard let `self` = self else {
return
}
let writeBuffer = context.writeBuffer
offset += context.tickContext.timeDelta * Double(self.timeMultiplier.value)
let now = offset
applyOverRange(writeBuffer.startIndex..<writeBuffer.endIndex) { bounds in
for i in bounds {
var hueNumerator = -((Float(now / -30) - Float(i) * 0.25 / Float(ledCount)))
if hueNumerator < 0 {
hueNumerator += -floor(hueNumerator)
precondition(hueNumerator >= 0)
}
let hue: Float = hueNumerator.truncatingRemainder(dividingBy: 1.0)
let portion = Float(i % segmentLength) / Float(segmentLength)
let value = 0.5 + 0.5 * sin(Float(now * 2) + Float(Float.pi * 2) * portion)
writeBuffer[i] = HSV(
h: hue,
s: 1,
v: value
)
.rgbFloat
}
}
})
}
}
| 31.075949 | 122 | 0.523422 |
1e3a3ee3863bb0fc5cf847d7485d3e8eacff8509 | 2,089 | // -------------------------------------------------------------------------------------------------
// Copyright (C) 2016-2019 HERE Europe B.V.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
// License-Filename: LICENSE
//
// -------------------------------------------------------------------------------------------------
import XCTest
import hello
class ListenerRoundtripTests: XCTestCase {
var providerImplWasCalled = false
var route: Route?
var routeImpl: RouteImpl?
class RouteImpl: Route {
}
class RouteProviderImpl: RouteProvider {
var parent: ListenerRoundtripTests
init(_ parent: ListenerRoundtripTests) {
self.parent = parent
}
public func setRoute(route: Route) {
parent.providerImplWasCalled = true
parent.route = route
parent.routeImpl = route as? RouteImpl
}
}
func testListenerRoundTripPreservesType() {
Nlp.setRoute(routeProvider: RouteProviderImpl(self), route: RouteImpl())
XCTAssertTrue(providerImplWasCalled)
XCTAssertNotNil(route)
XCTAssertNotNil(routeImpl)
}
func testOriginalSwiftObjectIsReturnedBack() {
let route = RouteImpl()
RouteStorage.route = route
XCTAssertTrue(RouteStorage.route === route)
}
static var allTests = [
("testListenerRoundTripPreservesType", testListenerRoundTripPreservesType),
("testOriginalSwiftObjectIsReturnedBack", testOriginalSwiftObjectIsReturnedBack)
]
}
| 31.179104 | 100 | 0.626616 |
618349acc1588e81bd38c06d7f97fe39887aea41 | 925 | //
// StringParsers.swift
// StringsToCSV
//
// Created by John Morgan on 02/12/2016.
// Copyright © 2016 John Morgan. All rights reserved.
//
import Foundation
public func string(_ string: String) -> Parser<String> {
return string.characters.reduce(pure(String())) { (parser, char) -> Parser<String> in
return parser.then(character(char)).map { $0.0.appending(String($0.1)) }
}.named(string)
}
public func string(of character: Parser<Character>) -> Parser<String> {
return many(character).asString()
}
public func anyString() -> Parser<String> {
return string(of: anyCharacter())
}
// TODO: When Swift supports conditional conformance
//extension Parser: ExpressibleByStringLiteral where Output == String.CharacterView {
//
// public init(stringLiteral value: String) {
//
// self.name = value
// self.parse = string(value).parse
// }
//}
| 24.342105 | 89 | 0.652973 |
db3e8c721111b0e1d3d8030ce11f4dcce907c062 | 1,299 | //
// DeleteAUserFollowingResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 UIKit
class DeleteAUserFollowingResponseHandler: ErrorResponseHandler {
}
| 41.903226 | 81 | 0.760585 |
08e2c118de3c791266ec1db9c554c6ad776a2e2d | 1,940 | // BNRequest_SendSharedElement.swift
// biin
// Created by Alison Padilla on 9/7/15.
// Copyright (c) 2015 Esteban Padilla. All rights reserved.
import Foundation
class BNRequest_SendSharedElement: BNRequest {
override init(){
super.init()
}
deinit{
}
convenience init(requestString:String, errorManager:BNErrorManager, networkManager:BNNetworkManager, element:BNElement? ){
self.init()
self.requestString = requestString
self.dataIdentifier = dataIdentifier
self.requestType = BNRequestType.SendSharedElement
self.errorManager = errorManager
self.networkManager = networkManager
self.element = element
}
override func run() {
isRunning = true
attemps += 1
var model = Dictionary<String, Dictionary <String, String>>()
var modelContent = Dictionary<String, String>()
modelContent["identifier"] = self.element!.identifier!
modelContent["type"] = "element"
model["model"] = modelContent
var htttpBody:NSData?
do {
htttpBody = try NSJSONSerialization.dataWithJSONObject(model, options:[])
} catch _ as NSError {
htttpBody = nil
}
self.networkManager!.epsNetwork!.put(self.identifier, url:self.requestString, htttpBody:htttpBody, callback: {
(data: Dictionary<String, AnyObject>, error: NSError?) -> Void in
if (error != nil) {
if self.attemps == self.attempsLimit { self.requestError = BNRequestError.Internet_Failed }
self.networkManager!.requestManager!.processFailedRequest(self, error: error)
} else {
self.isCompleted = true
self.networkManager!.requestManager!.processCompletedRequest(self)
}
})
}
}
| 31.290323 | 126 | 0.606701 |
ef753c7e3d8f56e2683f0e199d3681b3acf5ffd8 | 994 | import SwiftUI
struct ContentView: View {
// MARK: - PROPERTIES
@State private var isShowingSettings:Bool = false
var fruits: [Fruit] = fruitsData
// MARK: - BODY
var body: some View {
NavigationView{
List{
ForEach(fruits.shuffled()){ item in
NavigationLink(destination: FruitDetailView(fruit: item)){
FruitListView(fruit: item)
.padding(.vertical, 4)
}
}//: FOREACH
}//: LIST
.navigationTitle("Fruits")
.navigationBarItems(trailing: Button(action: {
isShowingSettings = true
}, label: {
Image(systemName: "slider.horizontal.3")
}))//: BUTTON
.sheet(isPresented: $isShowingSettings){
SettingsView()
}
}//: NAVIGATION
.navigationViewStyle(StackNavigationViewStyle())
}
}
// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(fruits: fruitsData)
.previewDevice("iPhone 11")
.environment(\.locale, .init(identifier: "pt"))
}
}
| 24.243902 | 63 | 0.661972 |
761459bc906f4398dfa4b4291f3d2addaac2ac74 | 5,819 | //
// LiveStreamingAPI.swift
// YTLiveStreaming
//
// Created by Sergey Krotkih on 10/28/16.
// Copyright © 2016 Sergey Krotkih. All rights reserved.
//
import Foundation
import Moya
import Result
private func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data, options: [])
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
return prettyData
} catch {
return data //fallback to original data if it cant be serialized
}
}
let requestClosure = { (endpoint: Moya.Endpoint<LiveStreamingAPI>, done: @escaping MoyaProvider<LiveStreamingAPI>.RequestResultClosure) in
GoogleOAuth2.sharedInstance.requestToken() { token in
if let token = token {
do {
var request = try endpoint.urlRequest() as URLRequest
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.addValue(Bundle.main.bundleIdentifier!, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
var nserror: NSError! = NSError(domain: "LiveStreamingAPIHttp", code: 0, userInfo: nil)
let error = MoyaError.underlying(nserror, nil)
done(Result(request, failWith: error))
}
catch {
}
} else {
do {
let request = try endpoint.urlRequest() as URLRequest
var nserror: NSError! = NSError(domain: "LiveStreamingAPIHttp", code: 4000, userInfo: ["NSLocalizedDescriptionKey": "Failed Google OAuth2 request token"])
let error = MoyaError.underlying(nserror, nil)
done(Result(request, failWith: error))
}
catch {
}
}
}
}
let YouTubeLiveVideoProvider = MoyaProvider<LiveStreamingAPI>(requestClosure: requestClosure, plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)])
enum LiveStreamingAPI {
case listBroadcasts([String: AnyObject])
case liveBroadcast([String: AnyObject])
case transitionLiveBroadcast([String: AnyObject])
case deleteLiveBroadcast([String: AnyObject])
case bindLiveBroadcast([String: AnyObject])
case liveStream([String: AnyObject])
case deleteLiveStream([String: AnyObject])
}
extension LiveStreamingAPI: TargetType {
public var baseURL: URL { return URL(string: LiveAPI.BaseURL)! }
public var path: String {
switch self {
case .listBroadcasts(_):
return "/liveBroadcasts"
case .liveBroadcast(_):
return "/liveBroadcasts"
case .transitionLiveBroadcast(_):
return "/liveBroadcasts/transition"
case .deleteLiveBroadcast(_):
return "/liveBroadcasts"
case .bindLiveBroadcast(_):
return "/liveBroadcasts/bind"
case .liveStream(_):
return "/liveStreams"
case .deleteLiveStream(_):
return "/liveStreams"
}
}
public var method: Moya.Method {
switch self {
case .listBroadcasts:
return .get
case .liveBroadcast:
return .get
case .transitionLiveBroadcast:
return .post
case .deleteLiveBroadcast:
return .delete
case .bindLiveBroadcast:
return .post
case .liveStream:
return .get
case .deleteLiveStream:
return .delete
}
}
public var task: Task {
switch self {
case .listBroadcasts(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .liveBroadcast(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .transitionLiveBroadcast(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .deleteLiveBroadcast(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .bindLiveBroadcast(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .liveStream(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .deleteLiveStream(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
}
}
public var parameters: [String: Any]? {
switch self {
case .listBroadcasts(let parameters):
return parameters
case .liveBroadcast(let parameters):
return parameters
case .transitionLiveBroadcast(let parameters):
return parameters
case .deleteLiveBroadcast(let parameters):
return parameters
case .bindLiveBroadcast(let parameters):
return parameters
case .liveStream(let parameters):
return parameters
case .deleteLiveStream(let parameters):
return parameters
}
}
public var sampleData: Data {
switch self {
case .listBroadcasts(_):
return Data()
case .liveBroadcast(_):
return Data()
case .transitionLiveBroadcast(_):
return Data()
case .deleteLiveBroadcast(_):
return Data()
case .bindLiveBroadcast(_):
return Data()
case .liveStream(_):
return Data()
case .deleteLiveStream(_):
return Data()
}
}
public var multipartBody: [MultipartFormData]? {
return []
}
var headers: [String : String]? {
return ["Content-type": "application/json"]
}
}
public func url(_ route: TargetType) -> String {
return route.baseURL.appendingPathComponent(route.path).absoluteString
}
| 33.251429 | 190 | 0.657673 |
9cc3b5f7b4184cb3006002eadd0c6e3cb4ca1530 | 412 | //
// ShowErrorStatusBar.swift
// Freetime
//
// Created by Ryan Nystrom on 7/15/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import Squawk
func ShowErrorStatusBar(graphQLErrors: [Error]?, networkError: Error?) {
if networkError != nil {
Squawk.showNetworkError()
} else if let graphQL = graphQLErrors?.first {
Squawk.show(error: graphQL)
}
}
| 21.684211 | 72 | 0.677184 |
110273fe2cb33143466e21b93a108fd084c2e4c2 | 3,420 | // 350. Intersection of Two Arrays II
// https://leetcode.com/problems/intersection-of-two-arrays-ii/
//
// Given two arrays, write a function to compute their intersection.
// Example:
// Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
//
// Note:
// Each element in the result should appear as many times as it shows in both arrays.
// The result can be in any order.
// Follow up:
// What if the given array is already sorted? How would you optimize your algorithm?
// What if nums1's size is small compared to nums2's size? Which algorithm is better?
// What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
// 求两个array相交的数字,重复的数字也要算
import Foundation
class Num350_IntersectionOfTwoArraysII: Solution {
// MARK: - Sort and use two pointers
// O(nlogn + mlogm)
// O(1)
func sorted(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
let nums1 = nums1.sorted()
let nums2 = nums2.sorted()
var i = 0
var j = 0
var res: [Int] = []
while i < nums1.count, j < nums2.count {
if nums1[i] < nums2[j] {
i += 1
continue
} else if nums1[i] > nums2[j] {
j += 1
continue
} else {
res.append(nums1[i])
i += 1
j += 1
}
}
return res
}
// MARK: - Record nums1 frequency, check nums2 and record result.
// O(n + m)
// O(min(n, m))
func dict(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var nums1Dict: [Int: Int] = [:]
for n in nums1 {
if let count = nums1Dict[n] {
nums1Dict[n] = count + 1
} else {
nums1Dict[n] = 1
}
}
var res: [Int] = []
for n in nums2 {
if let count = nums1Dict[n] {
res.append(n)
if count - 1 == 0 {
nums1Dict.removeValue(forKey: n)
} else {
nums1Dict[n] = count - 1
}
}
}
return res
}
// MARK: - Straightforward solution, two loops, if equal, record and remove.
// O(n^2)
func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var mutableNums1 = nums1
var mutableNums2 = nums2
var results: [Int] = []
var i = 0
while i < mutableNums1.count {
for j in 0 ..< mutableNums2.count {
if mutableNums1[i] == mutableNums2[j] {
results.append(mutableNums1[i])
mutableNums1.remove(at: i)
mutableNums2.remove(at: j)
i -= 1
break
}
}
i += 1
}
return results
}
func test() {
// [], [] -> []
assert(intersection([], []) == [])
// [], [1] -> []
assert(intersection([], [1]) == [])
// [1], [2] -> []
assert(intersection([1], [2]) == [])
// [1], [1] -> [1]
assert(intersection([1], [1]) == [1])
// [1, 2], [2] -> [2]
assert(intersection([1, 2], [2]) == [2])
// [1, 2, 2, 1], [2, 2] -> [2]
assert(intersection([1, 2, 2, 1], [2, 2]) == [2, 2])
// [], [] -> []
// assert(intersection2([], []) == [])
// // [], [1] -> []
// assert(intersection2([], [1]) == [])
// // [1], [2] -> []
// assert(intersection2([1], [2]) == [])
// // [1], [1] -> [1]
// assert(intersection2([1], [1]) == [1])
// // [1, 2], [2] -> [2]
// assert(intersection2([1, 2], [2]) == [2])
// // [1, 2, 2, 1], [2, 2] -> [2]
// assert(intersection2([1, 2, 2, 1], [2, 2]) == [2])
}
}
| 27.580645 | 138 | 0.505263 |
d63d59365109fac40509a89a12d3ea48e60e4544 | 705 | //
// main.swift
// Error
//
// Created by zainguo on 2020/6/29.
// Copyright © 2020 zainguo. All rights reserved.
//
import Foundation
struct MyError: Error {
var msg: String
}
enum SomeError: Error {
case illegalArg(String)
case outOfBounds(Int, Int)
case outOfMemory
}
func divide(_ num1: Int, _ num2: Int) throws -> Int {
if num2 == 0 {
// throw MyError(msg: "0不能作为除数")
throw SomeError.illegalArg("0不能作为除数")
}
return num1 / num2
}
print(try? divide(20, 10))
func test() {
do {
print(try divide(20, 0))
} catch let SomeError.illegalArg(msg) {
print("参数异常:", msg)
} catch {
print("其他错误")
}
}
test()
| 16.395349 | 53 | 0.58156 |
c1313f80dd7ba156282c576be566d858cdaf46f2 | 2,507 | //
// RoundLabel.swift
//
// Created by Tibor Leon Hahne on 23.10.18.
// Copyright © 2018 Tibor Leon Hahne. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable open class EssentialLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
override open func prepareForInterfaceBuilder() {
sharedInit()
}
func sharedInit() {
self.updateCornerRadius()
}
override open func layoutSubviews() {
super.layoutSubviews()
self.updateCornerRadius()
}
@IBInspectable var rounded: Bool = false {
didSet {
updateCornerRadius()
}
}
@IBInspectable var borderWidth: Float = 0 {
didSet {
self.layer.borderWidth = CGFloat(self.borderWidth)
}
}
@IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
self.layer.borderColor = self.borderColor.cgColor
}
}
@IBInspectable var cornerRadiusFactor: CGFloat = 2 {
didSet {
self.layer.cornerRadius = self.cornerRadiusFactor
}
}
@IBInspectable var lshadowColor: UIColor = UIColor.clear {
didSet {
self.layer.shadowColor = self.lshadowColor.cgColor
}
}
@IBInspectable var lshadowOffset: CGSize = CGSize.zero {
didSet {
self.layer.shadowOffset = self.shadowOffset
}
}
@IBInspectable var lshadowOpacity: Float = 0 {
didSet {
self.layer.shadowOpacity = self.lshadowOpacity
}
}
@IBInspectable var lshadowRadius: Float = 0 {
didSet {
self.layer.shadowRadius = CGFloat(self.lshadowRadius)
}
}
@IBInspectable var maskToBounds: Bool = true {
didSet {
self.layer.masksToBounds = self.maskToBounds
}
}
func updateCornerRadius() {
let width = self.frame.size.width
let height = self.frame.size.height
let size = width > height ? height : width
self.layer.cornerRadius = self.rounded ? size / self.cornerRadiusFactor : 0
self.layer.borderWidth = CGFloat(self.borderWidth)
self.layer.borderColor = self.borderColor.cgColor
self.layer.masksToBounds = self.maskToBounds
}
}
| 24.578431 | 83 | 0.590347 |
5611b5b752f710dc7fffad8076c077233cbcabbc | 11,406 | //
// Spica for iOS (Spica)
// File created by Lea Baumgart on 07.10.20.
//
// Licensed under the MIT License
// Copyright © 2020 Lea Baumgart. All rights reserved.
//
// https://github.com/SpicaApp/Spica-iOS
//
import SwiftKeychainWrapper
import UIKit
import SwiftUI
import Kingfisher
@available(iOS 14.0, *)
class SidebarViewController: UIViewController {
private var dataSource: UICollectionViewDiffableDataSource<SidebarSection, Item>!
private var collectionView: UICollectionView!
private var accountViewController: UserProfileViewController!
private var secondaryViewControllers = [UINavigationController]()
var previouslySelectedIndex: IndexPath?
var mentionsTimer = Timer()
var mentions = [String]()
var viewControllerToNavigateTo: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Spica"
navigationController?.navigationBar.prefersLargeTitles = true
accountViewController = UserProfileViewController(style: .insetGrouped)
let id = KeychainWrapper.standard.string(forKey: "dev.abmgrt.spica.user.id")
accountViewController!.user = User(id: id ?? "")
let settingsViewController = UINavigationController(rootViewController: UIHostingController(rootView: SettingsView(controller: .init(delegate: self, colorDelegate: self))))
settingsViewController.navigationBar.prefersLargeTitles = true
secondaryViewControllers = [UINavigationController(rootViewController: FeedViewController(style: .insetGrouped)),
UINavigationController(rootViewController: MentionsViewController(style: .insetGrouped)),
UINavigationController(rootViewController: BookmarksViewController(style: .insetGrouped)),
UINavigationController(rootViewController: SearchViewController(style: .insetGrouped)),
UINavigationController(rootViewController: accountViewController!),
settingsViewController]
configureHierarchy()
configureDataSource()
setInitialSecondaryView()
}
override func viewWillAppear(_: Bool) {
loadMentionsCount()
mentionsTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(loadMentionsCount), userInfo: nil, repeats: true)
NotificationCenter.default.addObserver(self, selector: #selector(loadMentionsCount), name: Notification.Name("loadMentionsCount"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(openUniversalLink(_:)), name: Notification.Name("openUniversalLink"), object: nil)
}
override func viewDidAppear(_ animated: Bool) {
}
@objc func openUniversalLink(_ notification: NSNotification) {
if let path = notification.userInfo?["path"] as? String {
switch path {
case "feed":
previouslySelectedIndex = IndexPath(row: 0, section: 0)
collectionView.selectItem(at: IndexPath(row: 0, section: 0),
animated: false,
scrollPosition: UICollectionView.ScrollPosition.centeredVertically)
splitViewController?.setViewController(secondaryViewControllers[0], for: .secondary)
case "mentions":
previouslySelectedIndex = IndexPath(row: 1, section: 0)
collectionView.selectItem(at: IndexPath(row: 1, section: 0),
animated: false,
scrollPosition: UICollectionView.ScrollPosition.centeredVertically)
splitViewController?.setViewController(secondaryViewControllers[1], for: .secondary)
default: break
}
}
}
func setViewController(_ vc: UIViewController) {
viewControllerToNavigateTo = vc
}
private func setInitialSecondaryView() {
previouslySelectedIndex = IndexPath(row: 0, section: 0)
collectionView.selectItem(at: IndexPath(row: 0, section: 0),
animated: false,
scrollPosition: UICollectionView.ScrollPosition.centeredVertically)
splitViewController?.setViewController(secondaryViewControllers[0], for: .secondary)
if viewControllerToNavigateTo != nil {
(splitViewController?.viewControllers.last as? UINavigationController)?.pushViewController(viewControllerToNavigateTo!, animated: true)
}
}
@objc func loadMentionsCount() {
MicroAPI.default.getUnreadMentions(allowError: false) { [self] result in
switch result {
case .failure:
break
case let .success(loadedMentions):
DispatchQueue.main.async {
UIApplication.shared.applicationIconBadgeNumber = loadedMentions.count
if mentions.count != loadedMentions.count {
mentions = loadedMentions
if mentions.count > 0 {
guard let index = tabsItems.firstIndex(where: { $0.item == .mentions }) else { return }
tabsItems[index].image = UIImage(systemName: "bell.badge.fill")
configureDataSource()
} else {
guard let index = tabsItems.firstIndex(where: { $0.item == .mentions }) else { return }
tabsItems[index].image = UIImage(systemName: "bell")
configureDataSource()
}
}
}
}
}
}
}
@available(iOS 14.0, *)
extension SidebarViewController: ColorPickerControllerDelegate, SettingsDelegate {
func changedColor(_ color: UIColor) {
UserDefaults.standard.setColor(color: color, forKey: "globalTintColor")
guard let sceneDelegate = view.window?.windowScene?.delegate as? SceneDelegate else { return }
sceneDelegate.window?.tintColor = color
}
func overrideUIInterfaceStyle(_ style: UIUserInterfaceStyle) {
let sceneDelegate = self.view.window!.windowScene!.delegate as! SceneDelegate
sceneDelegate.window?.overrideUserInterfaceStyle = style
}
func signedOut() {
let sceneDelegate = self.view.window!.windowScene!.delegate as! SceneDelegate
sceneDelegate.window?.rootViewController = sceneDelegate.loadInitialViewController()
sceneDelegate.window?.makeKeyAndVisible()
}
func setBiomicSessionToAuthorized() {
let sceneDelegate = view.window!.windowScene!.delegate as! SceneDelegate
sceneDelegate.sessionAuthorized = true
}
}
@available(iOS 14.0, *)
extension SidebarViewController {
private func createLayout() -> UICollectionViewLayout {
return UICollectionViewCompositionalLayout { section, layoutEnvironment in
var config = UICollectionLayoutListConfiguration(appearance: .sidebar)
config.headerMode = section == 0 ? .none : .firstItemInSection
return NSCollectionLayoutSection.list(using: config, layoutEnvironment: layoutEnvironment)
}
}
}
@available(iOS 14.0, *)
extension SidebarViewController {
private func configureHierarchy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.delegate = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
private func configureDataSource() {
let headerRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, _, item in
var content = cell.defaultContentConfiguration()
content.text = item.title
cell.contentConfiguration = content
cell.accessories = [.outlineDisclosure()]
}
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { [self] cell, index, item in
var content = cell.defaultContentConfiguration()
content.text = item.title
content.image = item.image
content.imageProperties.cornerRadius = (item.image?.size.height)! / 2
if item.item == .mentions, mentions.count > 0 {
content.secondaryText = "\(mentions.count)"
content.prefersSideBySideTextAndSecondaryText = true
}
cell.contentConfiguration = content
cell.accessories = []
}
dataSource = UICollectionViewDiffableDataSource<SidebarSection, Item>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, item: Item) -> UICollectionViewCell? in
if indexPath.item == 0, indexPath.section != 0 {
return collectionView.dequeueConfiguredReusableCell(using: headerRegistration, for: indexPath, item: item)
} else {
return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item)
}
}
let sections: [SidebarSection] = [.tabs]
var snapshot = NSDiffableDataSourceSnapshot<SidebarSection, Item>()
snapshot.appendSections(sections)
dataSource.apply(snapshot, animatingDifferences: false)
for section in sections {
switch section {
case .tabs:
var sectionSnapshot = NSDiffableDataSourceSectionSnapshot<Item>()
sectionSnapshot.append(tabsItems)
dataSource.apply(sectionSnapshot, to: section)
}
}
}
}
@available(iOS 14.0, *)
extension SidebarViewController: UICollectionViewDelegate {
func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath == previouslySelectedIndex ?? IndexPath(row: 99, section: 99) {
if indexPath.section == 0 && indexPath.row == 0 && secondaryViewControllers[0].viewControllers.count == 1 {
let vc = (secondaryViewControllers[0].viewControllers.first as! FeedViewController)
vc.tableView.setContentOffset(.init(x: 0, y: -116), animated: true)
}
else {
secondaryViewControllers[indexPath.row].popToRootViewController(animated: true)
}
}
else {
guard indexPath.section == 0 else { return }
splitViewController?.setViewController(secondaryViewControllers[indexPath.row], for: .secondary)
}
previouslySelectedIndex = indexPath
}
}
struct Item: Hashable {
let title: String?
var image: UIImage?
var item: TabItem!
private let identifier = UUID()
}
var tabsItems = [
Item(title: "Feed", image: UIImage(systemName: "house"), item: .feed),
Item(title: "Mentions", image: UIImage(systemName: "bell"), item: .mentions),
Item(title: "Bookmarks", image: UIImage(systemName: "bookmark"), item: .bookmarks),
Item(title: "Search", image: UIImage(systemName: "magnifyingglass"), item: .search),
Item(title: "Account", image: UIImage(systemName: "person.circle"), item: .account),
Item(title: "Settings", image: UIImage(systemName: "gear"), item: .settings),
]
enum TabItem {
case feed, mentions, bookmarks, search, account, settings
}
enum SidebarSection: String {
case tabs
}
| 43.041509 | 174 | 0.6835 |
569fe44cddad42b71b1c37e5d605e586cf01c201 | 3,832 | import Foundation
import SwiftDate
import Swinject
protocol TempTargetsObserver {
func tempTargetsDidUpdate(_ targers: [TempTarget])
}
protocol TempTargetsStorage {
func storeTempTargets(_ targets: [TempTarget])
func syncDate() -> Date
func recent() -> [TempTarget]
func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment]
func storePresets(_ targets: [TempTarget])
func presets() -> [TempTarget]
func current() -> TempTarget?
}
final class BaseTempTargetsStorage: TempTargetsStorage, Injectable {
private let processQueue = DispatchQueue(label: "BaseTempTargetsStorage.processQueue")
@Injected() private var storage: FileStorage!
@Injected() private var broadcaster: Broadcaster!
init(resolver: Resolver) {
injectServices(resolver)
}
func storeTempTargets(_ targets: [TempTarget]) {
storeTempTargets(targets, isPresets: false)
}
private func storeTempTargets(_ targets: [TempTarget], isPresets: Bool) {
processQueue.sync {
let file = isPresets ? OpenAPS.FreeAPS.tempTargetsPresets : OpenAPS.Settings.tempTargets
var uniqEvents: [TempTarget] = []
self.storage.transaction { storage in
storage.append(targets, to: file, uniqBy: \.createdAt)
uniqEvents = storage.retrieve(file, as: [TempTarget].self)?
.filter {
guard !isPresets else { return true }
return $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date()
}
.sorted { $0.createdAt > $1.createdAt } ?? []
storage.save(Array(uniqEvents), as: file)
}
broadcaster.notify(TempTargetsObserver.self, on: processQueue) {
$0.tempTargetsDidUpdate(uniqEvents)
}
}
}
func syncDate() -> Date {
Date().addingTimeInterval(-1.days.timeInterval)
}
func recent() -> [TempTarget] {
storage.retrieve(OpenAPS.Settings.tempTargets, as: [TempTarget].self)?.reversed() ?? []
}
func current() -> TempTarget? {
guard let currentTarget = recent()
.last(where: {
$0.createdAt.addingTimeInterval(Int($0.duration).minutes.timeInterval) > Date()
&& $0.createdAt <= Date()
})
else {
return nil
}
if let cancel = recent().last(where: { $0.createdAt <= Date() }), cancel.duration == 0 {
return nil
}
return currentTarget
}
func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment] {
let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedTempTargets, as: [NigtscoutTreatment].self) ?? []
let eventsManual = recent().filter { $0.enteredBy == TempTarget.manual }
let treatments = eventsManual.map {
NigtscoutTreatment(
duration: Int($0.duration),
rawDuration: nil,
rawRate: nil,
absolute: nil,
rate: nil,
eventType: .nsTempTarget,
createdAt: $0.createdAt,
enteredBy: TempTarget.manual,
bolus: nil,
insulin: nil,
notes: nil,
carbs: nil,
targetTop: $0.targetTop,
targetBottom: $0.targetBottom
)
}
return Array(Set(treatments).subtracting(Set(uploaded)))
}
func storePresets(_ targets: [TempTarget]) {
storage.remove(OpenAPS.FreeAPS.tempTargetsPresets)
storeTempTargets(targets, isPresets: true)
}
func presets() -> [TempTarget] {
storage.retrieve(OpenAPS.FreeAPS.tempTargetsPresets, as: [TempTarget].self)?.reversed() ?? []
}
}
| 34.214286 | 116 | 0.588205 |
fbe438ab616878d434dbd47908d8e6d579bfab7d | 1,653 | //
// Session.swift
// TeamupKit
//
// Created by Merrick Sapsford on 20/06/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import Foundation
/// A session that is occurring or has occurred.
public struct Session: Codable {
enum CodingKeys: String, CodingKey {
case id
case name
case description
case venue
case business
case detailUrl = "detail_url"
case registrationUrl = "registration_url"
case occupancy
case attendanceCount = "attendance_count"
case type
case registrationDetails = "registration_details"
case isActive = "active"
}
/// The identifier of the session.
public let id: Int
/// The name of the session.
public let name: String
/// The description of the session.
public let description: String
/// The venue that the session is occuring at.
public let venue: Venue
/// The business that is hosting the session.
public let business: Business
/// Web URL for the session details.
public let detailUrl: URL
/// Web URL for the session registration.
public let registrationUrl: URL
/// Details on registering the current user for the session.
public let registrationDetails: RegistrationDetails?
/// The total amount of registrations allowed for the session.
public let occupancy: Int?
/// The current attendance count for the session.
public let attendanceCount: Int
/// The type of the session.
public let type: SessionType
/// Whether the session is active.
public let isActive: Bool
}
| 29 | 66 | 0.663037 |
f4b892ebfd5e8f22ef006c63431cec3bbd37e090 | 2,527 | //
// FloatingBar.swift
// Identity Crisis
//
// Created by Lucas Wang on 2020-10-17.
//
import SwiftUI
import Combine
struct CurrentEmotionView: View {
let session: String
private let id = UUID()
@ObservedObject var camera = CameraInput()
var mainView: some View {
VStack {
Spacer()
HStack {
Text("Your current emotion:")
.font(.system(size: 20))
.fontWeight(.semibold)
Text(camera.emotion.description)
.font(.system(size: 60))
.onAppear {
startReporting()
}
.onDisappear {
stopReporting()
}
.onReceive(NotificationCenter.default.publisher(for: .emotionalWindowOpen)) { _ in
startReporting()
}
.onReceive(NotificationCenter.default.publisher(for: .emotionalWindowClose)) { _ in
stopReporting()
}
// if let image = camera.image {
// Image(nsImage: image)
// }
}
Spacer()
}
.padding()
.frame(idealWidth: 350, idealHeight: 120)
}
var body: some View {
if #available(OSX 11.0, *) {
mainView
.ignoresSafeArea()
} else {
mainView
.edgesIgnoringSafeArea(.all)
}
}
@State var tokens: [AnyCancellable] = []
func startReporting() {
guard tokens.isEmpty else { return }
camera.start()
tokens.append(camera.$emotion.collect(10).sink { (output) in
Dictionary(grouping: output) { $0 }
.mapValues { $0.count }
.max { $0.value < $1.value }
.map {
database.child(session).child(id.uuidString)
.setValue($0.key.rawValue)
History.shared.record($0.key)
}
})
}
func stopReporting() {
camera.stop()
tokens.forEach { $0.cancel() }
tokens.removeAll()
database.child(session).child(id.uuidString).removeValue()
}
}
struct FloatingBar_Previews: PreviewProvider {
static var previews: some View {
Group {
CurrentEmotionView(session: "test")
CurrentEmotionView(session: "test")
}
}
}
| 28.393258 | 103 | 0.477641 |
e68dbdc120bb44e3be56ff72cabe3e4723532059 | 5,675 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// A DFA state represents a set of possible ATN configurations.
/// As Aho, Sethi, Ullman p. 117 says "The DFA uses its state
/// to keep track of all possible states the ATN can be in after
/// reading each input symbol. That is to say, after reading
/// input a1a2..an, the DFA is in a state that represents the
/// subset T of the states of the ATN that are reachable from the
/// ATN's start state along some path labeled a1a2..an."
/// In conventional NFA→DFA conversion, therefore, the subset T
/// would be a bitset representing the set of states the
/// ATN could be in. We need to track the alt predicted by each
/// state as well, however. More importantly, we need to maintain
/// a stack of states, tracking the closure operations as they
/// jump from rule to rule, emulating rule invocations (method calls).
/// I have to add a stack to simulate the proper lookahead sequences for
/// the underlying LL grammar from which the ATN was derived.
///
/// I use a set of ATNConfig objects not simple states. An ATNConfig
/// is both a state (ala normal conversion) and a RuleContext describing
/// the chain of rules (if any) followed to arrive at that state.
///
/// A DFA state may have multiple references to a particular state,
/// but with different ATN contexts (with same or different alts)
/// meaning that state was reached via a different set of rule invocations.
///
public final class DFAState: Hashable, CustomStringConvertible {
public internal(set) var stateNumber = -1
public internal(set) var configs: ATNConfigSet
///
/// `edges[symbol]` points to target of symbol. Shift up by 1 so (-1)
/// _org.antlr.v4.runtime.Token#EOF_ maps to `edges[0]`.
///
public internal(set) var edges: [DFAState?]!
public internal(set) var isAcceptState = false
///
/// if accept state, what ttype do we match or alt do we predict?
/// This is set to _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_ when _#predicates_`!=null` or
/// _#requiresFullContext_.
///
public internal(set) var prediction = 0
public internal(set) var lexerActionExecutor: LexerActionExecutor?
///
/// Indicates that this state was created during SLL prediction that
/// discovered a conflict between the configurations in the state. Future
/// _org.antlr.v4.runtime.atn.ParserATNSimulator#execATN_ invocations immediately jumped doing
/// full context prediction if this field is true.
///
public internal(set) var requiresFullContext = false
///
/// During SLL parsing, this is a list of predicates associated with the
/// ATN configurations of the DFA state. When we have predicates,
/// _#requiresFullContext_ is `false` since full context prediction evaluates predicates
/// on-the-fly. If this is not null, then _#prediction_ is
/// _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_.
///
/// We only use these for non-_#requiresFullContext_ but conflicting states. That
/// means we know from the context (it's $ or we don't dip into outer
/// context) that it's an ambiguity not a conflict.
///
/// This list is computed by _org.antlr.v4.runtime.atn.ParserATNSimulator#predicateDFAState_.
///
public internal(set) var predicates: [PredPrediction]?
///
/// Map a predicate to a predicted alternative.
///
public final class PredPrediction: CustomStringConvertible {
public let pred: SemanticContext
// never null; at least SemanticContext.NONE
public let alt: Int
public init(_ pred: SemanticContext, _ alt: Int) {
self.alt = alt
self.pred = pred
}
public var description: String {
return "(\(pred),\(alt))"
}
}
public init(_ configs: ATNConfigSet) {
self.configs = configs
}
///
/// Get the set of all alts mentioned by all ATN configurations in this
/// DFA state.
///
public func getAltSet() -> Set<Int>? {
return configs.getAltSet()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(configs)
}
public var description: String {
var buf = "\(stateNumber):\(configs)"
if isAcceptState {
buf += "=>"
if let predicates = predicates {
buf += String(describing: predicates)
}
else {
buf += String(prediction)
}
}
return buf
}
}
///
/// Two _org.antlr.v4.runtime.dfa.DFAState_ instances are equal if their ATN configuration sets
/// are the same. This method is used to see if a state already exists.
///
/// Because the number of alternatives and number of ATN configurations are
/// finite, there is a finite number of DFA states that can be processed.
/// This is necessary to show that the algorithm terminates.
///
/// Cannot test the DFA state numbers here because in
/// _org.antlr.v4.runtime.atn.ParserATNSimulator#addDFAState_ we need to know if any other state
/// exists that has this exact set of ATN configurations. The
/// _#stateNumber_ is irrelevant.
///
public func ==(lhs: DFAState, rhs: DFAState) -> Bool {
if lhs === rhs {
return true
}
return (lhs.configs == rhs.configs)
}
| 37.833333 | 103 | 0.650749 |
39b6877ef3e4f659a738368df13b8329b72fdaa5 | 457 | //
// MMBaseNavigationController.swift
// Swift_SweetSugar
//
// Created by 杨杰 on 2021/9/3.
// Copyright © 2021 Mumu. All rights reserved.
//
import UIKit
class MMBaseNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var childForStatusBarStyle: UIViewController? {
return topViewController
}
}
| 19.041667 | 60 | 0.68709 |
3ae432cb738cf6f16489153ec3dd87747eed4030 | 533 | //
// ViewController.swift
// bus-stop-cafe-2.0
//
// Created by Christian Cmehil-Warn on 6/16/18.
// Copyright © 2018 Christian Cmehil-Warn. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.5 | 80 | 0.673546 |
67bcea34d17a99219dcf153b998358d656be7108 | 2,599 | //
// AppDelegate.swift
// AmazonChimeSDKMessagingDemo
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
//
import UIKit
import Amplify
import AmplifyPlugins
import UserNotifications
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var deviceToken: String?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try Amplify.add(plugin: AWSCognitoAuthPlugin())
try Amplify.add(plugin: AWSS3StoragePlugin())
try Amplify.configure()
} catch {
print("An error occurred setting up Amplify: \(error)")
}
registerForPushNotifications()
return true
}
// handler - registerForRemoteNotifications() succeed
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
self.deviceToken = tokenParts.joined()
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("AppDelegate Failed to registerForRemoteNotifications: \(error)")
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
// Request for the permission to receive push notifications within this app
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
guard granted else { return }
self?.getNotificationSettings()
}
}
// If push notifications are authorized, call registerForRemoteNotifications to register this device
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
| 38.791045 | 179 | 0.711043 |
8f52177fc69648acba8478fe07d59f36768e2efd | 1,801 | //
// MHNavigationController.swift
// MHSinaWeiboExample
//
// Created by CoderMikeHe on 17/3/3.
// Copyright © 2017年 CoderMikeHe. All rights reserved.
//
/**
1. 系统的导航条左侧或右侧item不能高亮。 利用customView 或者 配置 [UIBarButtonItem appearance]
2. 导航条融合,用户体验不好。 自定义navigationBar,或者设置导航条的颜色很重,解决高亮闪动的bug
3.
*/
import UIKit
class MHNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// 隐藏系统自带的navigationBar
navigationBar.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/// 监听控制器的push操作 所有的 push 操作都会调用这个方法
// viewController 是被 push进来,再次可以设置其返回按钮
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
// 如果不是栈底控制器就需要隐藏,根控制器不需要处理
if childViewControllers.count>0 {
// 隐藏底部tabBar
viewController.hidesBottomBarWhenPushed = true
// 判断控制器的类型
if let vc = viewController as? MHBaseViewController{
var title = "返回"
// 判断如果是栈底控制器 即只有一个子控制器 显示栈底控制器的主题
if childViewControllers.count==1 {
title = childViewControllers.first?.title ?? "返回"
}
// 设置控制器左侧栏的按钮 取出 navItem
vc.navItem.leftBarButtonItem = UIBarButtonItem(title: title, target: self, action: #selector(popToParent) , isBack : true)
}
}
super.pushViewController(viewController, animated: animated)
}
@objc private func popToParent() {
popViewController(animated: true)
}
}
| 25.366197 | 138 | 0.582454 |
08fa8b188a9f94a3cd72dd7ea7a236527714ddbd | 213 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
p(
{
for {
struct S {
func d {
class
case ,
| 17.75 | 87 | 0.732394 |
b9641b7c50d31db1bd30c876c99c9ce6fe6c54eb | 1,748 | //
// ArgumentFactory.swift
// InstantMock
//
// Created by Patrick on 13/05/2017.
// Copyright © 2017 pirishd. All rights reserved.
//
/** Protocol for argument factory that aims at creating arguments */
public protocol ArgumentFactory {
associatedtype Value
/// Create a new argument value
func argument(value: Value?) -> ArgumentValue
/// Create a new any argument
func argumentAny(_ typeDescription: String) -> ArgumentAny
// Create a new argument closure
func argumentClosure(_ typeDescription: String) -> ArgumentClosure
// Create a new argument that must verify provided condition
func argument(condition: @escaping (Value) -> Bool) -> ArgumentVerify
func argument(condition: @escaping (Value?) -> Bool) -> ArgumentVerify
// Create a new argument capture
func argumentCapture(_ typeDescription: String) -> ArgumentCapture
}
/** Implementation of argument factory */
final class ArgumentFactoryImpl<T>: ArgumentFactory {
func argument(value: T?) -> ArgumentValue {
return ArgumentValueImpl<T>(value)
}
func argumentAny(_ typeDescription: String) -> ArgumentAny {
return ArgumentAnyImpl(typeDescription)
}
func argumentClosure(_ typeDescription: String) -> ArgumentClosure {
return ArgumentClosureImpl(typeDescription)
}
func argument(condition: @escaping (T) -> Bool) -> ArgumentVerify {
return ArgumentVerifyMandatoryImpl<T>(condition)
}
func argument(condition: @escaping (T?) -> Bool) -> ArgumentVerify {
return ArgumentVerifyOptionalImpl<T>(condition)
}
func argumentCapture(_ typeDescription: String) -> ArgumentCapture {
return ArgumentCaptureImpl<T>(typeDescription)
}
}
| 29.133333 | 74 | 0.704233 |
91143b55632438caa7a0eb6a9c4c4b003c09d4b8 | 2,262 | //
// ARContentView.swift
// ARHeadsetKit
//
// Created by Philip Turner on 9/25/21.
//
#if !os(macOS)
import SwiftUI
import MetalKit
public struct ARContentView<CustomSettingsView: CustomRenderingSettingsView> {
@inlinable public init() { }
public func environmentObject(_ coordinator: CustomSettingsView.Coordinator) -> some View {
InternalView(coordinator: coordinator)
}
private struct InternalView: View {
var coordinator: CustomSettingsView.Coordinator
var body: some View {
ZStack {
ARDisplayView<CustomSettingsView.Coordinator>(coordinator: coordinator)
TouchscreenInterfaceView<CustomSettingsView>(coordinator: coordinator)
}
.ignoresSafeArea(.all)
}
}
}
struct ARDisplayView<Coordinator: AppCoordinator>: View {
@ObservedObject var coordinator: Coordinator
var body: some View {
ZStack {
let bounds = UIScreen.main.bounds
MetalView(coordinator: coordinator)
.disabled(false)
.frame(width: bounds.height, height: bounds.width)
.rotationEffect(.degrees(90))
.position(x: bounds.width * 0.5, y: bounds.height * 0.5)
HeadsetViewSeparator<Coordinator>(coordinator: coordinator)
}
}
private struct MetalView: UIViewRepresentable {
@ObservedObject var coordinator: Coordinator
func makeCoordinator() -> Coordinator { coordinator }
func makeUIView(context: Context) -> MTKView { context.coordinator.view }
func updateUIView(_ uiView: MTKView, context: Context) { }
}
}
struct TouchscreenInterfaceView<CustomSettingsView: CustomRenderingSettingsView>: View {
typealias Coordinator = CustomSettingsView.Coordinator
@ObservedObject var coordinator: Coordinator
var body: some View {
ZStack {
SettingsIconView<Coordinator>(coordinator: coordinator)
MainSettingsView<CustomSettingsView>(coordinator: coordinator)
AppTutorialView<Coordinator>(coordinator: coordinator)
}
}
}
#endif
| 30.16 | 95 | 0.632626 |
26f74dbd68ff6b345eed00288c2325521c140502 | 1,034 | //
// ID3RecordingTimesFrameCreatorsFactory.swift
// ID3TagEditor
//
// Created by Fabrizio Duroni on 29.10.20.
// 2020 Fabrizio Duroni.
//
// swiftlint:disable line_length
import Foundation
class ID3RecordingTimesFrameCreatorsFactory {
static func make() -> [ID3FrameCreator] {
let frameFromStringISO88591ContentCreator = ID3FrameFromStringContentCreatorWithISO88591EncodingFactory.make()
return [
ID3FrameContentCreator(
frameCreator: FrameFromIntegerContentAdapter(frameCreator: frameFromStringISO88591ContentCreator),
frameName: .recordingYear,
frameType: .recordingYear
),
ID3RecordingDayMonthFrameCreator(frameCreator: frameFromStringISO88591ContentCreator),
ID3RecordingHourMinuteFrameCreator(frameCreator: frameFromStringISO88591ContentCreator),
ID3RecordingDateTimeFrameCreator(frameCreator: frameFromStringISO88591ContentCreator, timestampCreator: ID3TimestampCreator())
]
}
}
| 36.928571 | 138 | 0.737911 |
d7214f9f3404969706dd6bf75151ffd006337c69 | 8,614 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
enum XMLParserDelegateEvent {
case startDocument
case endDocument
case didStartElement(String, String?, String?, [String: String])
case didEndElement(String, String?, String?)
case foundCharacters(String)
}
extension XMLParserDelegateEvent: Equatable {
public static func ==(lhs: XMLParserDelegateEvent, rhs: XMLParserDelegateEvent) -> Bool {
switch (lhs, rhs) {
case (.startDocument, startDocument):
return true
case (.endDocument, endDocument):
return true
case let (.didStartElement(lhsElement, lhsNamespace, lhsQname, lhsAttr),
didStartElement(rhsElement, rhsNamespace, rhsQname, rhsAttr)):
return lhsElement == rhsElement && lhsNamespace == rhsNamespace && lhsQname == rhsQname && lhsAttr == rhsAttr
case let (.didEndElement(lhsElement, lhsNamespace, lhsQname),
.didEndElement(rhsElement, rhsNamespace, rhsQname)):
return lhsElement == rhsElement && lhsNamespace == rhsNamespace && lhsQname == rhsQname
case let (.foundCharacters(lhsChar), .foundCharacters(rhsChar)):
return lhsChar == rhsChar
default:
return false
}
}
}
class XMLParserDelegateEventStream: NSObject, XMLParserDelegate {
var events: [XMLParserDelegateEvent] = []
func parserDidStartDocument(_ parser: XMLParser) {
events.append(.startDocument)
}
func parserDidEndDocument(_ parser: XMLParser) {
events.append(.endDocument)
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
events.append(.didStartElement(elementName, namespaceURI, qName, attributeDict))
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
events.append(.didEndElement(elementName, namespaceURI, qName))
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
events.append(.foundCharacters(string))
}
}
class TestXMLParser : XCTestCase {
static var allTests: [(String, (TestXMLParser) -> () throws -> Void)] {
return [
("test_withData", test_withData),
("test_withDataEncodings", test_withDataEncodings),
("test_withDataOptions", test_withDataOptions),
("test_sr9758_abortParsing", test_sr9758_abortParsing),
("test_sr10157_swappedElementNames", test_sr10157_swappedElementNames),
]
}
// Helper method to embed the correct encoding in the XML header
static func xmlUnderTest(encoding: String.Encoding? = nil) -> String {
let xmlUnderTest = "<test attribute='value'><foo>bar</foo></test>"
guard var encoding = encoding?.description else {
return xmlUnderTest
}
if let open = encoding.range(of: "(") {
let range: Range<String.Index> = open.upperBound..<encoding.endIndex
encoding = String(encoding[range])
}
if let close = encoding.range(of: ")") {
encoding = String(encoding[..<close.lowerBound])
}
return "<?xml version='1.0' encoding='\(encoding.uppercased())' standalone='no'?>\n\(xmlUnderTest)\n"
}
static func xmlUnderTestExpectedEvents(namespaces: Bool = false) -> [XMLParserDelegateEvent] {
let uri: String? = namespaces ? "" : nil
return [
.startDocument,
.didStartElement("test", uri, namespaces ? "test" : nil, ["attribute": "value"]),
.didStartElement("foo", uri, namespaces ? "foo" : nil, [:]),
.foundCharacters("bar"),
.didEndElement("foo", uri, namespaces ? "foo" : nil),
.didEndElement("test", uri, namespaces ? "test" : nil),
]
}
func test_withData() {
let xml = Array(TestXMLParser.xmlUnderTest().utf8CString)
let data = xml.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<CChar>) -> Data in
return buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout<CChar>.stride) {
return Data(bytes: $0, count: buffer.count)
}
}
let parser = XMLParser(data: data)
let stream = XMLParserDelegateEventStream()
parser.delegate = stream
let res = parser.parse()
XCTAssertEqual(stream.events, TestXMLParser.xmlUnderTestExpectedEvents())
XCTAssertTrue(res)
}
func test_withDataEncodings() {
// If th <?xml header isn't present, any non-UTF8 encodings fail. This appears to be libxml2 behavior.
// These don't work, it may just be an issue with the `encoding=xxx`.
// - .nextstep, .utf32LittleEndian
let encodings: [String.Encoding] = [.utf16LittleEndian, .utf16BigEndian, .utf32BigEndian, .ascii]
for encoding in encodings {
let xml = TestXMLParser.xmlUnderTest(encoding: encoding)
let parser = XMLParser(data: xml.data(using: encoding)!)
let stream = XMLParserDelegateEventStream()
parser.delegate = stream
let res = parser.parse()
XCTAssertEqual(stream.events, TestXMLParser.xmlUnderTestExpectedEvents())
XCTAssertTrue(res)
}
}
func test_withDataOptions() {
let xml = TestXMLParser.xmlUnderTest()
let parser = XMLParser(data: xml.data(using: .utf8)!)
parser.shouldProcessNamespaces = true
parser.shouldReportNamespacePrefixes = true
parser.shouldResolveExternalEntities = true
let stream = XMLParserDelegateEventStream()
parser.delegate = stream
let res = parser.parse()
XCTAssertEqual(stream.events, TestXMLParser.xmlUnderTestExpectedEvents(namespaces: true) )
XCTAssertTrue(res)
}
func test_sr9758_abortParsing() {
class Delegate: NSObject, XMLParserDelegate {
func parserDidStartDocument(_ parser: XMLParser) { parser.abortParsing() }
}
let xml = TestXMLParser.xmlUnderTest(encoding: .utf8)
let parser = XMLParser(data: xml.data(using: .utf8)!)
let delegate = Delegate()
parser.delegate = delegate
XCTAssertFalse(parser.parse())
XCTAssertNotNil(parser.parserError)
}
func test_sr10157_swappedElementNames() {
class ElementNameChecker: NSObject, XMLParserDelegate {
let name: String
init(_ name: String) { self.name = name }
func parser(_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String] = [:])
{
if parser.shouldProcessNamespaces {
XCTAssertEqual(self.name, qName)
} else {
XCTAssertEqual(self.name, elementName)
}
}
func parser(_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?)
{
if parser.shouldProcessNamespaces {
XCTAssertEqual(self.name, qName)
} else {
XCTAssertEqual(self.name, elementName)
}
}
func check() {
let elementString = "<\(self.name) />"
var parser = XMLParser(data: elementString.data(using: .utf8)!)
parser.delegate = self
XCTAssertTrue(parser.parse())
// Confirm that the parts of QName is also not swapped.
parser = XMLParser(data: elementString.data(using: .utf8)!)
parser.delegate = self
parser.shouldProcessNamespaces = true
XCTAssertTrue(parser.parse())
}
}
ElementNameChecker("noPrefix").check()
ElementNameChecker("myPrefix:myLocalName").check()
}
}
| 42.22549 | 173 | 0.617019 |
56bb34d63ad191dba22dfd5aa207ebfd6bef6b5c | 2,377 | //
// EpisodeDetailView.swift
// MortyUI
//
// Created by Thomas Ricouard on 21/12/2020.
//
import SwiftUI
import Apollo
import KingfisherSwiftUI
struct EpisodeDetailView: View {
@StateObject private var query: SingleQuery<GetEpisodeQuery>
init(id: GraphQLID) {
_query = StateObject(wrappedValue: SingleQuery(query: GetEpisodeQuery(id: id)))
}
var episode: EpisodeDetail? {
query.data?.episode?.fragments.episodeDetail
}
var body: some View {
List {
Section(header: Text("Info")) {
InfoRowView(label: "Name",
icon: "info",
value: episode?.name ?? "loading...")
InfoRowView(label: "Air date",
icon: "calendar",
value: episode?.airDate ?? "loading...")
InfoRowView(label: "Code",
icon: "barcode",
value: episode?.episode ?? "loading...")
}.redacted(reason: episode == nil ? .placeholder : [])
if let characters = episode?.characters?.compactMap{ $0 } {
Section(header: Text("Characters")) {
ForEach(characters, id: \.id) { character in
NavigationLink(
destination: CharacterDetailView(id: character.id!),
label: {
HStack {
if let image = character.image,
let url = URL(string: image) {
KFImage(url)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 28, height: 28)
.cornerRadius(14)
}
Text(character.name!)
}
})
}
}
}
}
.listStyle(GroupedListStyle())
}
}
struct EpisodeDetailView_Previews: PreviewProvider {
static var previews: some View {
EpisodeDetailView(id: GraphQLID(0))
}
}
| 34.955882 | 87 | 0.424064 |
16037d150f9291cd2a5d2ccd3cf3d34f39e8377d | 628 | //
// GQLOperationTypeSpec.swift
// ChartyTests
//
// Created by Philip Niedertscheider on 25.11.20.
// Copyright © 2020 Philip Niedertscheider. All rights reserved.
//
import Quick
import Nimble
@testable import Charty
class GQLOperationTypeSpec: QuickSpec {
override func spec() {
describe("GQLOperationType") {
it("should have a operation for querying") {
expect(GQLOperationType.query.rawValue) == "query"
}
it("should have a operation for mutation") {
expect(GQLOperationType.query.rawValue) == "query"
}
}
}
}
| 23.259259 | 66 | 0.617834 |
8fa4c5771a934a5c00f77effa2b74d0f01bb4e57 | 672 | //
// SendModuleBuilder.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 10/15/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
struct SendModuleBuilder: ModuleBuilder {
func build(input: Send.DTO.InputModel) -> UIViewController {
let interactor: SendInteractorProtocol = SendInteractor()
var presenter: SendPresenterProtocol = SendPresenter()
presenter.interactor = interactor
let vc = StoryboardScene.Send.sendViewController.instantiate()
vc.inputModel = input
vc.presenter = presenter
return vc
}
}
| 23.172414 | 70 | 0.651786 |
8a2522723185947efa4641a53d8075043b30b5a7 | 4,963 | //
// PermisssionAuthorizationTests.swift
//
//
// Copyright © 2021 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
@testable import MobilePassiveData
import JsonModel
import NSLocaleSwizzle
import Foundation
import SharedResourcesTests
class CodableMotionRecorderTests: XCTestCase {
var decoder: JSONDecoder {
return SerializationFactory.defaultFactory.createJSONDecoder()
}
var encoder: JSONEncoder {
return SerializationFactory.defaultFactory.createJSONEncoder()
}
override func setUp() {
super.setUp()
NSLocale.setCurrentTest(Locale(identifier: "en_US"))
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testStandardPermission_DefaultMessage() {
let permission = StandardPermission(permissionType: .motion)
XCTAssertEqual(permission.deniedMessage, "You have not given this app permission to use the motion and fitness sensors. You can enable access by turning on 'Motion & Fitness' in the Privacy Settings.")
XCTAssertTrue(permission.requestIfNeeded)
XCTAssertFalse(permission.isOptional)
}
func testStandardPermission_DefaultCodable() {
let permission = StandardPermission(permissionType: .motion)
do {
let encodedObject = try encoder.encode(permission)
let jsonObject = try JSONSerialization.jsonObject(with: encodedObject, options: [])
if let dictionary = jsonObject as? [String : Any] {
XCTAssertEqual("motion", dictionary["permissionType"] as? String)
}
else {
XCTFail("Failed to encode as a dictionary.")
}
let decodedObject = try decoder.decode(StandardPermission.self, from: encodedObject)
XCTAssertEqual(.motion, decodedObject.permissionType)
} catch let err {
XCTFail("Failed to decode/encode object: \(err)")
return
}
}
func testStandardPermission_CustomCodable() {
let filename = "StandardPermission_Camera"
guard let url = Bundle.testResources.url(forResource: filename, withExtension: "json")
else {
XCTFail("Could not find resource in the `Bundle.testResources`: \(filename).json")
return
}
do {
let data = try Data(contentsOf: url)
let decodedObject = try decoder.decode(StandardPermission.self, from: data)
XCTAssertEqual(.camera, decodedObject.permissionType)
XCTAssertEqual("Camera Permission", decodedObject.title)
XCTAssertEqual("A picture tells a thousand words.", decodedObject.reason)
XCTAssertEqual("Your access to the camera is restricted.", decodedObject.restrictedMessage)
XCTAssertEqual("You have previously denied permission for this app to use the camera.", decodedObject.deniedMessage)
XCTAssertFalse(decodedObject.requestIfNeeded)
XCTAssertTrue(decodedObject.isOptional)
} catch let err {
XCTFail("Failed to decode/encode object: \(err)")
return
}
}
}
| 42.418803 | 209 | 0.693129 |
f79f02df0c0bc8f3e85913e730b728b19eacd303 | 898 | //
// PreworkTests.swift
// PreworkTests
//
// Created by Hieu Ngan Nguyen on 12/20/21.
//
import XCTest
@testable import Prework
class PreworkTests: 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.411765 | 111 | 0.662584 |
fb0156ef52a7fea0bb77b0be38086e1bcde3e0b3 | 1,176 | //
// TxContentUtxoOutputs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public final class TxContentUtxoOutputs: Codable, Hashable {
/** Output address */
public var address: String
public var amount: [TxContentUtxoAmount]
public init(address: String, amount: [TxContentUtxoAmount]) {
self.address = address
self.amount = amount
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case address
case amount
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(address, forKey: .address)
try container.encode(amount, forKey: .amount)
}
public static func == (lhs: TxContentUtxoOutputs, rhs: TxContentUtxoOutputs) -> Bool {
lhs.address == rhs.address &&
lhs.amount == rhs.amount
}
public func hash(into hasher: inout Hasher) {
hasher.combine(address.hashValue)
hasher.combine(amount.hashValue)
}
}
| 25.565217 | 90 | 0.668367 |
5b5decaee6b69b2608b350854d963e261a159984 | 5,713 | //
// LNTopScrollView2_1.swift
// TaoKeThird
//
// Created by 付耀辉 on 2018/11/19.
// Copyright © 2018年 付耀辉. All rights reserved.
//
import UIKit
class LNTopScrollView2_1: UIView {
// 回调
typealias swiftBlock = (_ message:NSInteger, _ model:LNTopListModel) -> Void
var willClick : swiftBlock? = nil
func callBackBlock(block: @escaping ( _ message:NSInteger, _ model:LNTopListModel) -> Void ) {
willClick = block
}
// 下划线
fileprivate var underLine = UIView()
// 当前选择的下标
fileprivate var currentIndex = NSInteger()
fileprivate var scrollView = UIScrollView()
fileprivate var scrollHeight:CGFloat = 40
fileprivate var isOut = false
fileprivate var lineView = UIView()
fileprivate var showMore = UIButton()
fileprivate var selectFont = UIFont.systemFont(ofSize: 15)
fileprivate var normalFont = UIFont.systemFont(ofSize: 14)
var lineColor = UIColor.white
var textColor = kGaryColor(num: 255)
var datas = [LNTopListModel]()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setTopView(titles:[LNTopListModel], selectIndex:NSInteger) -> Void {
datas = titles
let model = LNTopListModel()
model.name = "全部"
datas.insert(model, at: 0)
_ = self.subviews.map {
$0.removeFromSuperview()
}
currentIndex = selectIndex
let moreWidth = CGFloat(45)
scrollView = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH-moreWidth, height: scrollHeight))
scrollView.showsHorizontalScrollIndicator = false
let kHeight = CGFloat(scrollHeight)
let kSpace = CGFloat(8)
var totalWidth = CGFloat()
for index in 0..<datas.count{
let kWidth = getLabWidth(labelStr: datas[index].name, font: selectFont, height: kHeight) + 10
let markBtn = UIButton.init(frame: CGRect(x: kSpace + totalWidth , y: 1, width: kWidth, height: kHeight))
markBtn.setTitle(datas[index].name, for: .normal)
markBtn.setTitleColor(textColor, for: .normal)
markBtn.titleLabel?.font = normalFont
markBtn.addTarget(self, action: #selector(goodAtProject(sender:)), for: .touchUpInside)
markBtn.tag = 130 + index
totalWidth += (kWidth+kSpace)
scrollView.addSubview(markBtn)
}
scrollView.contentSize = CGSize(width: totalWidth, height: scrollHeight)
if datas.count>0 {
let selectButton = scrollView.viewWithTag(130+selectIndex) as! UIButton
selectButton.titleLabel?.font = selectFont
underLine = UIView.init(frame: CGRect(x: 0, y: scrollHeight-4, width: getLabWidth(labelStr: datas[selectIndex].name, font: selectFont, height: 1) - 7, height: 2))
underLine.center.x = selectButton.center.x
}
underLine.backgroundColor = lineColor
underLine.layer.cornerRadius = 1
underLine.clipsToBounds = true
scrollView.addSubview(underLine)
self.addSubview(scrollView)
showMore = UIButton.init(frame: CGRect(x: self.width-moreWidth, y: 0, width: moreWidth, height: self.height))
showMore.addTarget(self, action: #selector(showAllOptions(sender:)), for: .touchUpInside)
showMore.setImage(UIImage.init(named: "Sizer_white_icon"), for: .normal)
showMore.backgroundColor = UIColor.clear
showMore.tag = 10086
self.addSubview(showMore)
lineView = UIView.init(frame: CGRect(x: self.width-moreWidth, y: 10, width: 0.5, height: scrollHeight-20))
lineView.backgroundColor = lineColor
self.addSubview(lineView)
}
@objc func changeStyle() {
showMore.setImage(UIImage.init(named: "Sizer_black_icon"), for: .normal)
}
@objc fileprivate func showAllOptions(sender: UIButton) {
if nil != willClick {
willClick!(10086,LNTopListModel())
}
}
//MARK: 顶部选择栏选择事件
@objc func goodAtProject(sender:UIButton) {
let lastButton = self.viewWithTag(currentIndex+130) as! UIButton
if lastButton == sender {
return
}
sender.titleLabel?.font = selectFont
lastButton.titleLabel?.font = normalFont
weak var weakSelf = self
UIView.animate(withDuration: 0.3, animations: {
weakSelf?.underLine.bounds.size.width = getLabWidth(labelStr: (sender.titleLabel?.text)!, font: self.selectFont, height: 2)-5
weakSelf?.underLine.center = CGPoint(x: sender.center.x, y: (weakSelf?.underLine.center.y)!)
if sender.centerX > self.scrollView.width/2 && (weakSelf?.scrollView.contentSize.width)!-sender.centerX > self.scrollView.width/2{
weakSelf?.scrollView.contentOffset = CGPoint(x: sender.centerX-self.scrollView.width/2, y: 0)
}else{
if sender.centerX < self.scrollView.width/2 {
weakSelf?.scrollView.contentOffset = CGPoint(x: 0, y: 0)
}else{
weakSelf?.scrollView.contentOffset = CGPoint(x: (weakSelf?.scrollView.contentSize.width)!-self.scrollView.width, y: 0)
}
}
})
currentIndex = sender.tag - 130
if nil != willClick {
willClick!(currentIndex,datas[sender.tag-130])
}
}
}
| 35.930818 | 174 | 0.613513 |
4a40412818502f9a5ca9a669f91b3c5b618adc06 | 3,803 | //
// MapViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// 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 UIKit
import MapKit
class MapAnnotation : NSObject, MKAnnotation {
@objc var coordinate : CLLocationCoordinate2D
override init() {
coordinate = CLLocationCoordinate2D(latitude: -33.0, longitude: -56.0)
super.init()
}
}
@objc(MapViewController)
class MapViewController : UIViewController, XLFormRowDescriptorViewController, MKMapViewDelegate {
var rowDescriptor: XLFormRowDescriptor?
lazy var mapView : MKMapView = { [unowned self] in
let mapView = MKMapView(frame: self.view.frame)
mapView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
return mapView
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(mapView)
mapView.delegate = self
if let value = rowDescriptor?.value as? CLLocation {
mapView.setCenter(value.coordinate, animated: false)
title = String(format: "%0.4f, %0.4f", mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude)
let annotation = MapAnnotation()
annotation.coordinate = value.coordinate
self.mapView.addAnnotation(annotation)
}
}
//MARK - - MKMapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotation")
pinAnnotationView.pinColor = MKPinAnnotationColor.red
pinAnnotationView.isDraggable = true
pinAnnotationView.animatesDrop = true
return pinAnnotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
if (newState == .ending){
if let rowDescriptor = rowDescriptor, let annotation = view.annotation {
rowDescriptor.value = CLLocation(latitude:annotation.coordinate.latitude, longitude:annotation.coordinate.longitude)
self.title = String(format: "%0.4f, %0.4f", annotation.coordinate.latitude, annotation.coordinate.longitude)
}
}
}
}
| 39.206186 | 176 | 0.707073 |
bfbf3ae07844a7846b8672953914d825fb734ee3 | 10,423 | //
// AssetCell.swift
// AnyImageKit
//
// Created by 刘栋 on 2019/9/17.
// Copyright © 2019 AnyImageProject.org. All rights reserved.
//
import UIKit
final class AssetCell: UICollectionViewCell {
private lazy var imageView: UIImageView = {
let view = UIImageView(frame: .zero)
view.contentMode = .scaleAspectFill
view.layer.masksToBounds = true
return view
}()
private lazy var gifView: GIFView = {
let view = GIFView()
view.isHidden = true
return view
}()
private lazy var videoView: VideoView = {
let view = VideoView()
view.isHidden = true
return view
}()
private lazy var editedView: EditedView = {
let view = EditedView()
view.isHidden = true
return view
}()
private lazy var selectdCoverView: UIView = {
let view = UIView(frame: .zero)
view.isHidden = true
view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
return view
}()
private lazy var disableCoverView: UIView = {
let view = UIView(frame: .zero)
view.isHidden = true
view.backgroundColor = UIColor.white.withAlphaComponent(0.5)
return view
}()
private(set) lazy var boxCoverView: UIView = {
let view = UIView(frame: .zero)
view.isHidden = true
view.layer.borderWidth = 4
return view
}()
private(set) lazy var selectButton: NumberCircleButton = {
let view = NumberCircleButton(frame: .zero, style: .default)
return view
}()
private var identifier: String = ""
override func prepareForReuse() {
super.prepareForReuse()
identifier = ""
selectdCoverView.isHidden = true
gifView.isHidden = true
videoView.isHidden = true
editedView.isHidden = true
disableCoverView.isHidden = true
boxCoverView.isHidden = true
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
addSubview(imageView)
addSubview(selectdCoverView)
addSubview(gifView)
addSubview(videoView)
addSubview(editedView)
addSubview(disableCoverView)
addSubview(boxCoverView)
addSubview(selectButton)
imageView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
selectdCoverView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
gifView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
videoView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
editedView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
disableCoverView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
boxCoverView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
selectButton.snp.makeConstraints { maker in
maker.top.right.equalToSuperview().inset(0)
maker.width.height.equalTo(40)
}
}
}
extension AssetCell {
var image: UIImage? {
return imageView.image
}
}
extension AssetCell {
private func setConfig(_ config: ImagePickerController.Config) {
boxCoverView.layer.borderColor = config.theme.mainColor.cgColor
selectButton.setTheme(config.theme)
}
func setContent(_ asset: Asset, manager: PickerManager, animated: Bool = false, isPreview: Bool = false) {
setConfig(manager.config)
let options = PhotoFetchOptions(sizeMode: .thumbnail(100*UIScreen.main.nativeScale), needCache: false)
identifier = asset.phAsset.localIdentifier
manager.requestPhoto(for: asset.phAsset, options: options, completion: { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let response):
guard self.identifier == asset.phAsset.localIdentifier else { return }
self.imageView.image = asset._image ?? response.image
if asset.mediaType == .video && !isPreview {
self.videoView.setVideoTime(asset.videoDuration)
}
case .failure(let error):
_print(error)
}
})
updateState(asset, manager: manager, animated: animated, isPreview: isPreview)
}
func updateState(_ asset: Asset, manager: PickerManager, animated: Bool = false, isPreview: Bool = false) {
if asset._images[.edited] != nil {
editedView.isHidden = false
} else {
switch asset.mediaType {
case .photoGIF:
gifView.isHidden = false
case .video:
videoView.isHidden = false
default:
break
}
}
if !isPreview {
selectButton.setNum(asset.selectedNum, isSelected: asset.isSelected, animated: animated)
selectdCoverView.isHidden = !asset.isSelected
disableCoverView.isHidden = !(manager.isUpToLimit && !asset.isSelected)
}
}
}
// MARK: - VideoView
private class VideoView: UIView {
private lazy var videoImageView: UIImageView = {
let view = UIImageView(frame: .zero)
view.image = BundleHelper.image(named: "Video")
return view
}()
private lazy var videoLabel: UILabel = {
let view = UILabel(frame: .zero)
view.isHidden = true
view.textColor = UIColor.white
view.font = UIFont.systemFont(ofSize: 12)
return view
}()
private lazy var videoCoverLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.frame = CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)
layer.colors = [
UIColor.black.withAlphaComponent(0.4).cgColor,
UIColor.black.withAlphaComponent(0).cgColor]
layer.locations = [0, 1]
layer.startPoint = CGPoint(x: 0.5, y: 1)
layer.endPoint = CGPoint(x: 0.5, y: 0)
return layer
}()
override func layoutSubviews() {
super.layoutSubviews()
videoCoverLayer.frame = CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
layer.addSublayer(videoCoverLayer)
addSubview(videoImageView)
addSubview(videoLabel)
videoImageView.snp.makeConstraints { maker in
maker.left.bottom.equalToSuperview().inset(8)
maker.width.equalTo(24)
maker.height.equalTo(15)
}
videoLabel.snp.makeConstraints { maker in
maker.left.equalTo(videoImageView.snp.right).offset(3)
maker.centerY.equalTo(videoImageView)
}
}
}
extension VideoView {
/// 设置视频时间,单位:秒
func setVideoTime(_ time: String) {
videoLabel.isHidden = false
videoLabel.text = time
}
}
// MARK: - GIF View
private class GIFView: UIView {
private lazy var gifLabel: UILabel = {
let view = UILabel(frame: .zero)
view.text = "GIF"
view.textColor = UIColor.white
view.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
return view
}()
private lazy var gifCoverLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.frame = CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)
layer.colors = [
UIColor.black.withAlphaComponent(0.4).cgColor,
UIColor.black.withAlphaComponent(0).cgColor]
layer.locations = [0, 1]
layer.startPoint = CGPoint(x: 0.5, y: 1)
layer.endPoint = CGPoint(x: 0.5, y: 0)
return layer
}()
override func layoutSubviews() {
super.layoutSubviews()
gifCoverLayer.frame = CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
layer.addSublayer(gifCoverLayer)
addSubview(gifLabel)
gifLabel.snp.makeConstraints { maker in
maker.left.bottom.equalToSuperview().inset(8)
maker.height.equalTo(15)
}
}
}
// MARK: - Edited View
private class EditedView: UIView {
private lazy var imageView: UIImageView = {
let view = UIImageView(frame: .zero)
view.image = BundleHelper.image(named: "PhotoEdited")
return view
}()
private lazy var coverLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.frame = CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)
layer.colors = [
UIColor.black.withAlphaComponent(0.4).cgColor,
UIColor.black.withAlphaComponent(0).cgColor]
layer.locations = [0, 1]
layer.startPoint = CGPoint(x: 0.5, y: 1)
layer.endPoint = CGPoint(x: 0.5, y: 0)
return layer
}()
override func layoutSubviews() {
super.layoutSubviews()
coverLayer.frame = CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
layer.addSublayer(coverLayer)
addSubview(imageView)
imageView.snp.makeConstraints { maker in
maker.left.bottom.equalToSuperview().inset(6)
maker.width.height.equalTo(15)
}
}
}
| 31.020833 | 111 | 0.598964 |
fcc0a5b4be4dbfc7f6e1d70c543fdf7e83cfe877 | 903 | //
// SwiftUIDemoTests.swift
// SwiftUIDemoTests
//
// Created by mac on 2020/11/27.
//
import XCTest
@testable import SwiftUIDemo
class SwiftUIDemoTests: 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.558824 | 111 | 0.666667 |
621138f5c0f5dc1fe179c75dbb09087822d33434 | 5,611 | //
// ViewController.swift
// Siri
//
// Created by Marin Todorov on 6/23/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var meterLabel: UILabel!
@IBOutlet weak var speakButton: UIButton!
let monitor = MicMonitor()
let assistant = Assistant()
var lastTransformScale: CGFloat = 0.0
let replicator = CAReplicatorLayer()
let dot = CALayer()
let dotLength = CGFloat(6.0)
let dotOffset = CGFloat(8.0)
let animationDuration = 0.33
override func viewDidLoad() {
super.viewDidLoad()
replicator.frame = view.bounds
view.layer.addSublayer(replicator)
dot.frame = CGRect(x: replicator.frame.size.width - dotLength, y: replicator.position.y, width: dotLength, height: dotLength)
dot.backgroundColor = UIColor.lightGrayColor().CGColor
dot.borderColor = UIColor.whiteColor().CGColor
dot.borderWidth = 0.5
dot.cornerRadius = 1.5
replicator.addSublayer(dot)
replicator.instanceCount = Int(view.frame.size.width / dotOffset)
replicator.instanceTransform = CATransform3DMakeTranslation(-dotOffset, 0.0, 0.0)
replicator.instanceDelay = 0.02
// //曲线不够平滑
// let move = CABasicAnimation(keyPath: "position.y")
// move.fromValue = dot.position.y
// move.toValue = dot.position.y + 250.0
// move.duration = 1.0
// move.repeatCount = Float.infinity
// move.autoreverses = true
// move.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// dot.addAnimation(move, forKey: nil)
// replicator.instanceDelay = 0.03
}
@IBAction func actionStartMonitoring(sender: AnyObject) {
monitor.stopMonitoring()
dot.removeAllAnimations()
}
@IBAction func actionEndMonitoring(sender: AnyObject) {
//speak after 1 second
delay(seconds: 1.0, completion: {
self.startSpeaking()
})
}
func startSpeaking() {
print("speak back")
let scale = CABasicAnimation(keyPath: "transform")
scale.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
scale.toValue = NSValue(CATransform3D:CATransform3DMakeScale(1.4, 15, 1.0))
scale.duration = animationDuration
scale.repeatCount = Float.infinity
scale.autoreverses = true
scale.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseOut)
dot.addAnimation(scale, forKey: "dotScale")
let fade = CABasicAnimation(keyPath: "opacity")
fade.fromValue = 1.0
fade.toValue = 0.2
fade.duration = animationDuration
fade.beginTime = CACurrentMediaTime() + animationDuration
fade.repeatCount = Float.infinity
fade.autoreverses = true
fade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
dot.addAnimation(fade, forKey: "dotOpacity")
let tint = CABasicAnimation(keyPath: "backgroundColor")
tint.fromValue = UIColor.magentaColor().CGColor
tint.toValue = UIColor.cyanColor().CGColor
tint.duration = 2 * animationDuration
tint.beginTime = CACurrentMediaTime() + 0.28
tint.fillMode = kCAFillModeBackwards
tint.repeatCount = Float.infinity
tint.autoreverses = true
tint.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
dot.addAnimation(tint, forKey: "dotColor")
let initialRotation = CABasicAnimation(keyPath: "instanceTransform.rotation")
initialRotation.fromValue = 0.0
initialRotation.toValue = 0.01
initialRotation.duration = 0.33
initialRotation.removedOnCompletion = false
initialRotation.fillMode = kCAFillModeForwards
initialRotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
replicator.addAnimation(initialRotation, forKey:"initialRotation")
let rotation = CABasicAnimation(keyPath: "instanceTransform.rotation")
rotation.fromValue = 0.01
rotation.toValue = -0.01
rotation.duration = 0.99
rotation.beginTime = CACurrentMediaTime() + 0.33
rotation.repeatCount = Float.infinity
rotation.autoreverses = true
rotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
replicator.addAnimation(rotation, forKey: "replicatorRotation")
meterLabel.text = assistant.randomAnswer()
assistant.speak(meterLabel.text!, completion: endSpeaking)
speakButton.hidden = true
dot.backgroundColor = UIColor.greenColor().CGColor
monitor.startMonitoringWithHandler { level in
self.meterLabel.text = String(format: "%.2f db", level)
let scaleFactor = max(0.2, CGFloat(level) + 50) / 2
let scale = CABasicAnimation(keyPath: "transform.scale.y")
scale.fromValue = self.lastTransformScale
scale.toValue = scaleFactor
scale.duration = 0.1
scale.removedOnCompletion = false
scale.fillMode = kCAFillModeForwards
self.dot.addAnimation(scale, forKey: nil)
self.lastTransformScale = scaleFactor
}
}
func endSpeaking() {
replicator.removeAllAnimations()
let scale = CABasicAnimation(keyPath: "transform")
scale.toValue = NSValue(CATransform3D: CATransform3DIdentity)
scale.duration = 0.33
scale.removedOnCompletion = false
scale.fillMode = kCAFillModeForwards
dot.addAnimation(scale, forKey: nil)
dot.removeAnimationForKey("dotColor")
dot.removeAnimationForKey("dotOpacity")
dot.backgroundColor = UIColor.lightGrayColor().CGColor
speakButton.hidden = false
}
}
| 30.82967 | 129 | 0.713955 |
39865c930e8c20d29801e3b9592755bde528d068 | 4,325 | //
// HamButton.swift
// BoomMenuButton
//
// Created by Nightonke on 2017/5/4.
// Copyright © 2017 Nightonke. All rights reserved.
//
class HamButton: BoomButtonWithText {
// MARK: Initialize
override init(builder: BoomButtonBuilder) {
super.init(builder: builder)
if let hamButtonBuilder = builder as? HamButtonBuilder {
containsSubText = hamButtonBuilder.containsSubText
normalSubText = hamButtonBuilder.normalSubText
highlightedSubText = hamButtonBuilder.highlightedSubText
unableSubText = hamButtonBuilder.unableSubText
normalAttributedText = hamButtonBuilder.normalAttributedSubText
highlightedAttributedSubText = hamButtonBuilder.highlightedAttributedSubText
unableAttributedSubText = hamButtonBuilder.unableAttributedSubText
normalSubTextColor = hamButtonBuilder.normalSubTextColor
highlightedSubTextColor = hamButtonBuilder.highlightedSubTextColor
unableSubTextColor = hamButtonBuilder.unableSubTextColor
subTextFrame = hamButtonBuilder.subTextFrame
subTextFont = hamButtonBuilder.subTextFont
subTextAlignment = hamButtonBuilder.subTextAlignment
subTextLineBreakMode = hamButtonBuilder.subTextLineBreakMode
subTextLines = hamButtonBuilder.subTextLines
subTextShadowColor = hamButtonBuilder.subTextShadowColor
subTextShadowOffsetX = hamButtonBuilder.subTextShadowOffsetX
subTextShadowOffsetY = hamButtonBuilder.subTextShadowOffsetY
width = hamButtonBuilder.width
height = hamButtonBuilder.height
shadowPathRect = builder.shadowPathRect
frame = CGRect.init(x: 0, y: 0, width: width, height: height)
resetButtonLayer()
resetNormalImage(builder: builder)
resetHighlightedImage(builder: builder)
resetUnableImage(builder: builder)
resetImageView()
resetLabel()
resetSubLabel()
if builder.unable {
toUnable()
} else {
toNormal()
}
round = false
} else {
fatalError("The builder used to initialize ham-button should be ham-button-builder")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("BoomButton does not support NSCoding")
}
// MARK: - Override Methods
override func toNormal() {
toNormalImage()
toNormalText()
toNormalSubText()
toNormalButton()
}
override func toHighlighted() {
toHighlightedImage()
toHighlightedText()
toHighlightedSubText()
toHighlightedButton()
}
override func toUnable() {
toUnableImage()
toUnableText()
toUnableSubText()
toUnableButton()
}
override func type() -> ButtonEnum {
return .ham
}
override func goneViews() -> [UIView] {
var goneViews = [UIView]()
if imageView != nil {
goneViews.append(imageView!)
}
if label != nil {
goneViews.append(label!)
}
if subLabel != nil {
goneViews.append(subLabel!)
}
return goneViews
}
override func rotateViews() -> [UIView] {
var rotateViews = [UIView]()
if imageView != nil && rotateImage {
rotateViews.append(imageView!)
}
return rotateViews
}
override func buttonWidth() -> CGFloat {
return width
}
override func buttonHeight() -> CGFloat {
return height
}
override func setAnchorPointOfLayer() {
Utils.setAnchorPoint(CGPoint.init(x: 0.5, y: 0.5), layer: layer)
}
override func rotateAnchorPoint() -> CGPoint {
return CGPoint.init(x: imageFrame.origin.x + imageFrame.size.width / 2, y: imageFrame.origin.y + imageFrame.size.height / 2)
}
override func centerPoint() -> CGPoint {
return CGPoint.init(x: width / 2, y: height / 2)
}
}
| 30.457746 | 132 | 0.596069 |
5613d7c63a3dfe3b9a701bd7cf2d6cba1e00b787 | 2,089 | //
// HTTPMessage.swift
// Telegraph
//
// Created by Yvo van Beek on 1/30/17.
// Copyright © 2017 Building42. All rights reserved.
//
import Foundation
open class HTTPMessage {
public var headers = HTTPHeaders()
public var body = Data()
public var version = HTTPVersion(1, 1)
internal var firstLine: String { return "" }
internal var stripBody = false
/// Performs last minute changes to the message, just before writing it to the stream.
open func prepareForWrite() {
// Set the keep alive connection header
if version.minor == 0 {
keepAlive = false
} else if headers.connection == nil {
keepAlive = true
}
}
/// Writes the HTTP message to the provided stream.
public func write(to stream: WriteStream, headerTimeout: TimeInterval, bodyTimeout: TimeInterval) {
writeHeader(to: stream, timeout: headerTimeout)
writeBody(to: stream, timeout: bodyTimeout)
stream.flush()
}
/// Writes the first line and headers to the provided stream.
open func writeHeader(to stream: WriteStream, timeout: TimeInterval) {
// Write the first line
stream.write(data: firstLine.utf8Data, timeout: timeout)
stream.write(data: .crlf, timeout: timeout)
// Write the headers
headers.forEach { key, value in
stream.write(data: "\(key): \(value)".utf8Data, timeout: timeout)
stream.write(data: .crlf, timeout: timeout)
}
// Signal the end of the headers with another crlf
stream.write(data: .crlf, timeout: timeout)
}
/// Writes the body to the provided stream.
open func writeBody(to stream: WriteStream, timeout: TimeInterval) {
if !stripBody {
stream.write(data: body, timeout: timeout)
}
}
}
// MARK: Helper methods
extension HTTPMessage {
var keepAlive: Bool {
get { return headers.connection?.lowercased() != "close" }
set { headers.connection = newValue ? "keep-alive" : "close" }
}
var isConnectionUpgrade: Bool {
get { return headers.connection?.lowercased() == "upgrade" }
set { headers.connection = newValue ? "upgrade" : nil }
}
}
| 28.616438 | 101 | 0.677358 |
200d9f348ea1722aec77ff9016e2567b917996fa | 3,941 | //
// UIViewController+Alert.swift
// iReader
//
// Created by WillZh on 2018/7/11.
// Copyright © 2018年 NoOrg. All rights reserved.
//
import Foundation
import UIKit
public extension UIViewController {
/// 显示一个 UIAlertController
///
/// - Parameters:
/// - title: 标题
/// - msg: 提示内容
/// - cancelTitle: 取消键标题,默认为 '取消'
/// - buttons: 其他按钮标题
/// - handle: 点击按钮回调,可以根据按钮标题名称来判断具体事件
func zs_showSystemAlert(title: String?, msg: String?, cancelTitle: String? = "取消", buttons: [String], handle: ((_ title: String) -> Void)?) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
// 添加取消按钮
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: nil))
// 添加自定义按钮
for bt in buttons {
let action = UIAlertAction(title: bt, style: .default) { (alertAction) in
guard let block = handle else {
return
}
block(bt) // 调用 block 返回
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
}
self.present(alert, animated: true, completion: nil)
}
}
public extension UIViewController {
/// 从 storyboard 中初始化 ViewController,storyboard Id 必须和类名相同
///
/// - Parameter sbname: storyboard 名称
/// - Returns: UIViewController 实例
class func zs_loadFromSB(_ sbname: String) -> UIViewController {
let sb = UIStoryboard.init(name: sbname, bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: NSStringFromClass(self).components(separatedBy: ".").last!)
return vc
}
/// 初始化。若 sbname 有值,从 storyboard 加载。若没有值,调用 init 方法
class func zs_instance(_ sbname: String = "") -> UIViewController {
if sbname == "" {
return self.init()
}
return zs_loadFromSB(sbname)
}
}
public extension UIViewController {
/// 导航 push 到一个 ViewController
func zs_pushTo(_ vc: UIViewController, animated: Bool = true) {
self.navigationController?.pushViewController(vc, animated: animated)
}
/// 导航 pop 到上一个 ViewController
@discardableResult
func zs_pop(_ animated: Bool = true) -> UIViewController? {
return self.navigationController?.popViewController(animated: animated)
}
/// 导航 pop 到根 ViewController
@discardableResult
func zs_popToRoot(_ animated: Bool = true) -> [UIViewController]? {
return self.navigationController?.popToRootViewController(animated: animated)
}
/// 导航 pop 到指定的 vc
@discardableResult
func zs_popTo(_ vc: UIViewController, animated: Bool = true) -> [UIViewController]? {
return self.navigationController?.popToViewController(vc, animated: animated)
}
/// 导航 pop 指定数量的层级。比如有 A,B,C 3个VC,当 length == 2 时,将返回到 A
func zs_popStack(_ length: Int, animated: Bool = true) {
if length == 1 {
_ = self.zs_pop()
return
}
let arr = self.navigationController?.viewControllers
guard let vcs = arr else {
return
}
if length >= vcs.count {
return
}
let level = vcs.count - length
if level == 1{
_ = self.zs_popToRoot()
return
}
var tempVCs = [UIViewController]()
for i in 0 ..< level {
tempVCs.append(vcs[i])
}
self.navigationController?.setViewControllers(tempVCs, animated: animated)
}
/// present 到一个 ViewController
func zs_presentTo(_ vc: UIViewController, animated: Bool = true) {
self.present(vc, animated: animated, completion: nil)
}
/// dismiss
func zs_dismiss() {
self.dismiss(animated: true, completion: nil)
}
}
| 27.753521 | 145 | 0.589952 |
67516dee8e2acf96f490c60b6b23e651975323d2 | 4,930 | import oneHookLibrary
import UIKit
private class SimpleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
}
private class SimpleDialogViewController: UIViewController {
override func loadView() {
view = FrameLayout()
view.backgroundColor = .clear
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(FrameLayout().apply {
$0.backgroundColor = .red
$0.layer.cornerRadius = Dimens.standardCornerRadius
$0.layer.masksToBounds = true
$0.layoutGravity = .center
$0.layoutSize = CGSize(width: dp(150), height: dp(150))
})
}
}
class ControllerHostDemoViewController: BaseScrollableDemoViewController {
private var controllerHost: ControllerHostView!
private var topMarginSlider = EDSlider().apply {
$0.value = 0
$0.minimumValue = 0
$0.maximumValue = 500
}
private let outsideDismissSwitch = SwitchView().apply {
$0.isOn = true
}
private let dragDismissSwitch = SwitchView().apply {
$0.isOn = true
}
private let blurBackgroundSwitch = SwitchView().apply {
$0.isOn = true
}
override func viewDidLoad() {
super.viewDidLoad()
toolbarTitle = "ControllerHost"
controllerHost = ControllerHostView(parentController: self)
controllerHost.delegate = self
controllerHost.contentTopMargin = dp(200)
view.addSubview(controllerHost)
contentLinearLayout.addSubview(StackLayout().apply {
$0.padding = Dimens.marginMedium
$0.orientation = .vertical
$0.spacing = Dimens.marginMedium
$0.addSubview(EDLabel().apply {
$0.font = UIFont.boldSystemFont(ofSize: 16)
$0.text = "Top Margin"
})
$0.addSubview(topMarginSlider.apply {
$0.layoutGravity = [.fillHorizontal]
})
$0.addSubview(EDLabel().apply {
$0.font = UIFont.boldSystemFont(ofSize: 16)
$0.text = "Allow Tap Outside to Dismiss"
})
$0.addSubview(outsideDismissSwitch)
$0.addSubview(EDLabel().apply {
$0.font = UIFont.boldSystemFont(ofSize: 16)
$0.text = "Allow Drag to Dismiss"
})
$0.addSubview(dragDismissSwitch)
$0.addSubview(EDLabel().apply {
$0.font = UIFont.boldSystemFont(ofSize: 16)
$0.text = "Show blurred background"
})
$0.addSubview(blurBackgroundSwitch)
})
contentLinearLayout.addSubview(EDButton().apply {
$0.layoutGravity = [.fillHorizontal]
$0.marginTop = Dimens.marginMedium
$0.tag = 1
$0.setTitleColor(.primaryTextColor, for: .normal)
$0.setTitle("Present Dialog", for: .normal)
$0.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)
})
contentLinearLayout.addSubview(EDButton().apply {
$0.layoutGravity = [.fillHorizontal]
$0.tag = 0
$0.setTitleColor(.primaryTextColor, for: .normal)
$0.setTitle("Present View Controller", for: .normal)
$0.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)
})
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
controllerHost.matchParent()
}
@objc private func buttonPressed(sender: UIControl) {
switch sender.tag {
case 0:
controllerHost.contentTopMargin = CGFloat(topMarginSlider.value)
if blurBackgroundSwitch.isOn {
controllerHost.present(
SimpleViewController(),
style: .init(blurEffect: .init(style: .regular))
)
} else {
controllerHost.present(SimpleViewController())
}
case 1:
controllerHost.contentTopMargin = 0
if blurBackgroundSwitch.isOn {
controllerHost.present(
SimpleDialogViewController(),
style: .init(blurEffect: .init(style: .regular))
)
} else {
controllerHost.present(SimpleDialogViewController())
}
default:
break
}
}
}
extension ControllerHostDemoViewController: ControllerHostViewDelegate {
func controllerStackDidChange() {
}
func controllerShouldDismissTapOutside(controller: UIViewController) -> Bool {
outsideDismissSwitch.isOn
}
func controllerShouldDismissByDrag(controller: UIViewController, location: CGPoint) -> Bool {
dragDismissSwitch.isOn
}
}
| 31.806452 | 97 | 0.587424 |
0ef10ef8007acae1eeaf1c1d6325f473851fa0ee | 223 | import Plot
extension Node where Context: HTMLContext {
/// Adds the raw values of the passed elements as classes.
static func `classes`(_ classes: String...) -> Self {
.class(classes.joined(separator: " "))
}
}
| 24.777778 | 60 | 0.681614 |
ccac01cf181b28e18f52ea786df2853e381c18d8 | 165 | //
// SetupFile.swift
// BangleCompanionApp
//
// Created by Adam Cotter on 31/01/2020.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
| 16.5 | 51 | 0.69697 |
d9794d7a3b5c194c546f763a97e38740247a7667 | 3,379 | // The MIT License (MIT)
//
// Copyright (c) 2018 ByungKook Hwang (https://magi82.github.io)
//
// 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 UIKit
import RxSwift
public protocol BindView: class {
associatedtype ViewBinder
var disposeBag: DisposeBag { get set }
var viewBinder: ViewBinder? { get set }
func state(viewBinder: ViewBinder)
func command(viewBinder: ViewBinder)
func binding(viewBinder: ViewBinder?)
}
// MARK: - disposeBag
private var disposeBagKey: String = "disposeBag"
extension BindView {
public var disposeBag: DisposeBag {
get {
if let value = objc_getAssociatedObject(self,
&disposeBagKey) as? DisposeBag {
return value
}
let disposeBag = DisposeBag()
objc_setAssociatedObject(self,
&disposeBagKey,
disposeBag,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposeBag
}
set {
objc_setAssociatedObject(self,
&disposeBagKey,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - viewBinder
private var viewBinderKey: String = "viewBinder"
extension BindView {
public var viewBinder: ViewBinder? {
get {
if let value = objc_getAssociatedObject(self,
&viewBinderKey) as? ViewBinder {
return value
}
return nil
}
set {
objc_setAssociatedObject(self,
&viewBinderKey,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let viewController = self as? UIViewController
viewController?.rx.methodInvoked(#selector(UIViewController.loadView))
.asObservable()
.map { _ in newValue }
.subscribe(onNext: { [weak self] in
self?.binding(viewBinder: $0)
})
.disposed(by: self.disposeBag)
}
}
public func binding(viewBinder: ViewBinder?) {
if let viewBinder = viewBinder {
state(viewBinder: viewBinder)
command(viewBinder: viewBinder)
}
}
}
| 31.877358 | 88 | 0.634507 |
7275ca36765258a97aaee26f1e4eb1e135ad43a7 | 1,271 | import Cocoa
public class BaseRenderer {
static let colors: [NSColor] = [
#colorLiteral(red: 0.1921568662, green: 0.007843137719, blue: 0.09019608051, alpha: 1),
#colorLiteral(red: 0.3176470697, green: 0.07450980693, blue: 0.02745098062, alpha: 1),
#colorLiteral(red: 0.3098039329, green: 0.01568627544, blue: 0.1294117719, alpha: 1),
#colorLiteral(red: 0.521568656, green: 0.1098039225, blue: 0.05098039284, alpha: 1),
#colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1),
#colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1),
#colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1),
#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1),
]
static func text(for node: CallGraphNode) -> String {
return "\(node.symbol.name), \(node.symbol.weight)"
}
}
extension NSColor {
var hex: String {
let red = Int(round(redComponent * 0xFF))
let green = Int(round(greenComponent * 0xFF))
let blue = Int(round(blueComponent * 0xFF))
let hexString = NSString(format: "#%02X%02X%02X", red, green, blue)
return hexString as String
}
}
| 43.827586 | 95 | 0.651456 |
26445c60c7d742b9daf79d7a96c4b11e52783124 | 12,355 | //
// UIScrollViewExtension.swift
// WiggleSDK
//
// Created by pkh on 2018. 5. 23..
// Copyright © 2018년 mykim. All rights reserved.
//
import Foundation
import UIKit
public enum Direction: Int {
case Up
case Down
case Left
case Right
public var isX: Bool { return self == .Left || self == .Right }
public var isY: Bool { return !isX }
}
public extension UIPanGestureRecognizer {
var direction: Direction? {
let velo = velocity(in: view)
let vertical = abs(velo.y) > abs(velo.x)
switch (vertical, velo.x, velo.y) {
case (true, _, let y) where y < 0: return .Up
case (true, _, let y) where y > 0: return .Down
case (false, let x, _) where x > 0: return .Right
case (false, let x, _) where x < 0: return .Left
default: return nil
}
}
}
public typealias ScrollViewClosure = (_ obj: UIScrollView, _ newValue: CGPoint, _ oldValue: CGPoint) -> Void
extension UIScrollView {
private struct AssociatedKeys {
static var headerView: UInt8 = 0
static var footerView: UInt8 = 0
static var topInsetView: UInt8 = 0
static var headerViewIsSticky: UInt8 = 0
static var kvoOffsetCallback: UInt8 = 0
static var offsetObserver: UInt8 = 0
static var insetObserver: UInt8 = 0
static var contentSizeObserver: UInt8 = 0
static var headerViewFrameObserver: UInt8 = 0
}
// MARK:- Observer를 중복으로 Add하는 방지를 위한 Bool 값들
public var offsetObserver: NSKeyValueObservation? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.offsetObserver) as? NSKeyValueObservation
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.offsetObserver, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var insetObserver: NSKeyValueObservation? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.insetObserver) as? NSKeyValueObservation
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.insetObserver, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var contentSizeObserver: NSKeyValueObservation? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.contentSizeObserver) as? NSKeyValueObservation
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.contentSizeObserver, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var headerViewFrameObserver: NSKeyValueObservation? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.headerViewFrameObserver) as? NSKeyValueObservation
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.headerViewFrameObserver, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK:- Sticky Header
public var headerViewIsSticky: Bool {
get {
if let result = objc_getAssociatedObject(self, &AssociatedKeys.headerViewIsSticky) as? Bool {
return result
}
return false
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.headerViewIsSticky, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK:- Custom Header & Mall Footer
public var customHeaderView: UIView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.headerView) as? UIView
}
set {
addObserverOffset()
addObserverInset()
var beforeViewHeight: CGFloat = 0
if let customHeaderView: UIView = self.customHeaderView {
self.headerViewFrameObserver = nil
beforeViewHeight = customHeaderView.frame.size.height
customHeaderView.removeFromSuperview()
}
objc_setAssociatedObject(self, &AssociatedKeys.headerView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
guard let view: UIView = newValue else { return }
view.autoresizingMask = .flexibleWidth
view.frame.size.width = self.frame.size.width
self.addSubview(view)
let top: CGFloat = floor(self.contentInset.top + view.frame.size.height - beforeViewHeight)
self.contentInset = UIEdgeInsets(top: top, left: self.contentInset.left, bottom: self.contentInset.bottom, right: self.contentInset.right)
addObserverHeaderViewFrame()
}
}
public var customFooterView: UIView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.footerView) as? UIView
}
set {
addObserverInset()
addObserverContentSize()
var beforeViewHeight: CGFloat = 0
if let customFooterView: UIView = self.customFooterView {
beforeViewHeight = customFooterView.frame.size.height
customFooterView.removeFromSuperview()
}
objc_setAssociatedObject(self, &AssociatedKeys.footerView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
guard let view: UIView = newValue else { return }
view.frame.origin.x = 0
view.frame.origin.y = self.contentSize.height
view.frame.size.width = self.frame.size.width
view.autoresizingMask = .flexibleWidth
self.addSubview(view)
let bottom: CGFloat = floor(self.contentInset.bottom + view.frame.size.height - beforeViewHeight)
self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: bottom, right: self.contentInset.right)
}
}
// MARK:- Add Top Inset View
public var topInsetView: UIView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.topInsetView) as? UIView
}
set {
if let topInsetView: UIView = self.topInsetView, newValue == nil {
self.contentInset = UIEdgeInsets(top: self.contentInset.top - topInsetView.frame.size.height, left: self.contentInset.left, bottom: self.contentInset.bottom, right: self.contentInset.right)
topInsetView.removeFromSuperview()
}
objc_setAssociatedObject(self, &AssociatedKeys.topInsetView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public func addTopInset(color: UIColor, height: CGFloat) {
addObserverInset()
if let topInsetView: UIView = self.topInsetView {
topInsetView.frame.size.height = height
topInsetView.backgroundColor = color
}
else {
topInsetView = UIView(frame: CGRect(x: 0, y: -self.contentInset.top, width: self.frame.size.width, height: height))
topInsetView?.autoresizingMask = .flexibleWidth
topInsetView!.backgroundColor = color
self.addSubview(topInsetView!)
}
self.contentInset = UIEdgeInsets(top: height + self.contentInset.top, left: self.contentInset.left, bottom: self.contentInset.bottom, right: self.contentInset.bottom)
}
public func removeTopInset() {
topInsetView = nil
}
// MARK:- Refresh Callback (Offset 값의 변화를 받은 뒤 처리)
public func addKvoOffsetCallback(_ clousre: @escaping ScrollViewClosure) {
self.addObserverOffset()
if var clouserArray = objc_getAssociatedObject(self, &AssociatedKeys.kvoOffsetCallback) as? [ScrollViewClosure] {
clouserArray.append(clousre)
objc_setAssociatedObject(self, &AssociatedKeys.kvoOffsetCallback, clouserArray, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
else {
var clouserArray: [ScrollViewClosure] = [ScrollViewClosure]()
clouserArray.append(clousre)
objc_setAssociatedObject(self, &AssociatedKeys.kvoOffsetCallback, clouserArray, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK:- Refresh Callback (Offset 값의 변화를 받은 뒤 처리)
public var kvoOffsetCallbacks: [ScrollViewClosure]? {
return objc_getAssociatedObject(self, &AssociatedKeys.kvoOffsetCallback) as? [ScrollViewClosure]
}
// MARK:- Inset Observer
private func addObserverInset() {
guard self.insetObserver == nil else { return }
self.insetObserver = self.observe(\.contentInset, options: [.old, .new]) { [weak self] _, _ in
guard let `self` = self else { return }
if let headerView: UIView = self.customHeaderView {
headerView.frame.origin.y = -headerView.frame.size.height
}
if let topInsetView: UIView = self.topInsetView {
topInsetView.frame.origin.y = -self.contentInset.top
}
if let footerView: UIView = self.customFooterView {
footerView.frame.origin.y = self.contentSize.height
}
}
}
// MARK:- Content Offset Observer
private func addObserverOffset() {
guard self.offsetObserver == nil else { return }
self.offsetObserver = self.observe(\.contentOffset, options: [.old, .new]) { [weak self] obj, change in
guard let `self` = self else { return }
guard let newValue: CGPoint = change.newValue, let oldValue: CGPoint = change.oldValue else { return }
if floor(newValue.y) != floor(oldValue.y) {
if let kvoOffsetCallbacks = self.kvoOffsetCallbacks {
for clousre in kvoOffsetCallbacks {
clousre(obj, newValue, oldValue)
}
}
}
guard let headerView: UIView = self.customHeaderView else { return }
if self.headerViewIsSticky {
let new = newValue.y
// let old = oldValue.cgPointValue.y
if new > -self.contentInset.top {
headerView.frame.origin.y = new // sticky
}
else {
headerView.frame.origin.y = -headerView.frame.size.height
}
}
else {
headerView.frame.origin.y = -headerView.frame.size.height
}
}
}
// MARK:- Content Size Observer
private func addObserverContentSize() {
guard self.contentSizeObserver == nil else { return }
self.contentSizeObserver = self.observe(\.contentSize, options: [.old, .new]) { [weak self] _, change in
guard let `self` = self else { return }
guard let newValue: CGSize = change.newValue, let oldValue: CGSize = change.oldValue else { return }
guard newValue != oldValue else { return }
if let footerView = self.customFooterView {
footerView.frame.origin.y = self.contentSize.height
// print("self.contentSize.height: \(self.contentSize.height)")
}
}
}
// MARK:- HeaderView Frame Observer
private func addObserverHeaderViewFrame() {
guard let headerView = self.customHeaderView else { return }
guard self.headerViewFrameObserver == nil else { return }
self.headerViewFrameObserver = headerView.observe(\.frame, options: [.old, .new]) { [weak self] _, change in
guard let `self` = self else { return }
guard let newValue: CGRect = change.newValue, let oldValue: CGRect = change.oldValue else { return }
guard floor(newValue.size.height) != floor(oldValue.size.height) else { return }
let top: CGFloat = floor(self.contentInset.top + newValue.size.height - oldValue.size.height)
self.contentInset = UIEdgeInsets(top: top, left: self.contentInset.left, bottom: self.contentInset.bottom, right: self.contentInset.right)
}
}
public func removeObserverAll() {
self.insetObserver = nil
self.offsetObserver = nil
self.contentSizeObserver = nil
self.headerViewFrameObserver = nil
}
public func setTabTouchContentOffset(_ contentOffset: CGPoint, animated: Bool) {
self.scrollsToTop = false
self.setContentOffset(contentOffset, animated: animated)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.scrollsToTop = true
}
}
}
| 39.983819 | 205 | 0.631 |
3a0ad0f300f8e68d4f89916bd29ec22a962c17a2 | 1,824 | //
// PasteTextField.swift
// GerritJarvis
//
// Created by Chuanren Shang on 2019/5/15.
// Copyright © 2019 Chuanren Shang. All rights reserved.
//
import Cocoa
class PasteTextField: NSSecureTextField {
private let commandKey = NSEvent.ModifierFlags.command.rawValue
private let commandShiftKey = NSEvent.ModifierFlags.command.rawValue | NSEvent.ModifierFlags.shift.rawValue
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if event.type == NSEvent.EventType.keyDown {
if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
switch event.charactersIgnoringModifiers! {
case "x":
if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true }
case "c":
if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true }
case "v":
if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true }
case "z":
if NSApp.sendAction(Selector(("undo:")), to:nil, from:self) { return true }
case "a":
if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to:nil, from:self) { return true }
default:
break
}
}
else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey {
if event.charactersIgnoringModifiers == "Z" {
if NSApp.sendAction(Selector(("redo:")), to:nil, from:self) { return true }
}
}
}
return super.performKeyEquivalent(with: event)
}
}
| 41.454545 | 131 | 0.591557 |
1d8ca67b8ca6efbea36f14e382175dcfedcfbbfc | 1,284 | //
// SwitchTVC.swift
// UtilityKit
//
// Created by Vivek Kumar on 07/09/19.
//
import UIKit
public class SwitchTVC: BaseTVC {
public static let nibName = "SwitchTVC"
public static let identifier = "SwitchTVC"
public static let nib = SwitchTVC.getNib()
class func getNib() -> UINib {
return UINib(nibName: SwitchTVC.nibName, bundle: Bundle(for: SwitchTVC.self))
}
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var formSwitch: UISwitch!
@IBAction func toggleSwitch(_ sender: UISwitch) {
self.field.value = sender.isOn
}
var formField : Field!{
didSet{
self.titleLbl.text = self.field.title
self.formSwitch.isOn = self.field.value as? Bool ?? false
}
}
public override var field: Field!{
get{
return self.formField
}
set{
self.formField = newValue
}
}
override public func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override public func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.928571 | 85 | 0.590343 |
89407f47262eb166617d26cc953dbcf42998c8c2 | 1,066 | //
// SettingsViewController.swift
// fake-dropbox
//
// Created by Ed Chao on 2/4/15.
// Copyright (c) 2015 codepath. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var settingsScrollView: UIScrollView!
@IBOutlet weak var settingsImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
settingsScrollView.contentSize = settingsImageView.frame.size
}
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.
}
*/
}
| 26.65 | 106 | 0.69137 |
1a133d97147201844d408ae328a05346ffa5c17b | 14,442 | //
// DiscussionAPI.swift
// edX
//
// Created by Tang, Jeff on 6/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public enum DiscussionPostsFilter {
case AllPosts
case Unread
case Unanswered
fileprivate var apiRepresentation : String? {
switch self {
case .AllPosts: return nil // default
case .Unread: return "unread"
case .Unanswered: return "unanswered"
}
}
}
public enum DiscussionPostsSort {
case RecentActivity
case MostActivity
case VoteCount
fileprivate var apiRepresentation : String? {
switch self {
case .RecentActivity: return "last_activity_at"
case .MostActivity: return "comment_count"
case .VoteCount: return "vote_count"
}
}
}
public class DiscussionAPI {
private static func threadDeserializer(response : HTTPURLResponse, json : JSON) -> Result<DiscussionThread> {
return DiscussionThread(json : json).toResult(NSError.oex_courseContentLoadError())
}
private static func commentDeserializer(response : HTTPURLResponse, json : JSON) -> Result<DiscussionComment> {
return DiscussionComment(json : json).toResult(NSError.oex_courseContentLoadError())
}
private static func listDeserializer<A>(response : HTTPURLResponse, items : [JSON]?, constructor : ((JSON) -> A?)) -> Result<[A]> {
if let items = items {
var result: [A] = []
for itemJSON in items {
if let item = constructor(itemJSON) {
result.append(item)
}
}
return Success(v: result)
}
else {
return Failure(e: NSError.oex_courseContentLoadError())
}
}
private static func threadListDeserializer(response : HTTPURLResponse, json : JSON) -> Result<[DiscussionThread]> {
return listDeserializer(response: response, items: json.array, constructor: { DiscussionThread(json : $0) } )
}
private static func commentListDeserializer(response : HTTPURLResponse, json : JSON) -> Result<[DiscussionComment]> {
return listDeserializer(response: response, items: json.array, constructor: { DiscussionComment(json : $0) } )
}
private static func topicListDeserializer(response : HTTPURLResponse, json : JSON) -> Result<[DiscussionTopic]> {
if let coursewareTopics = json["courseware_topics"].array,
let nonCoursewareTopics = json["non_courseware_topics"].array
{
var result: [DiscussionTopic] = []
for topics in [nonCoursewareTopics, coursewareTopics] {
for json in topics {
if let topic = DiscussionTopic(json: json) {
result.append(topic)
}
}
}
return Success(v: result)
}
else {
return Failure(e: NSError.oex_courseContentLoadError())
}
}
private static func discussionInfoDeserializer(response : HTTPURLResponse, json : JSON) -> Result<DiscussionInfo> {
return DiscussionInfo(json : json).toResult(NSError.oex_courseContentLoadError())
}
//MA-1378 - Automatically follow posts when creating a new post
static func createNewThread(newThread: DiscussionNewThread, follow : Bool = true) -> NetworkRequest<DiscussionThread> {
let json = JSON([
"course_id" : newThread.courseID,
"topic_id" : newThread.topicID,
"type" : newThread.type.rawValue,
"title" : newThread.title,
"raw_body" : newThread.rawBody,
"following" : follow
])
return NetworkRequest(
method : HTTPMethod.POST,
path : "/api/discussion/v1/threads/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
deserializer : .jsonResponse(threadDeserializer)
)
}
// when parent id is nil, counts as a new post
static func createNewComment(threadID : String, text : String, parentID : String? = nil) -> NetworkRequest<DiscussionComment> {
var json = JSON([
"thread_id" : threadID,
"raw_body" : text,
])
if let parentID = parentID {
json["parent_id"] = JSON(parentID)
}
return NetworkRequest(
method : HTTPMethod.POST,
path : "/api/discussion/v1/comments/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
deserializer : .jsonResponse(commentDeserializer)
)
}
// User can only vote on post and response not on comment.
// thread is the same as post
static func voteThread(voted: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["voted" : !voted])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .jsonResponse(threadDeserializer)
)
}
static func voteResponse(voted: Bool, responseID: String) -> NetworkRequest<DiscussionComment> {
let json = JSON(["voted" : !voted])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/comments/\(responseID)/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .jsonResponse(commentDeserializer)
)
}
// User can flag (report) on post, response, or comment
static func flagThread(abuseFlagged: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["abuse_flagged" : abuseFlagged])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .jsonResponse(threadDeserializer)
)
}
static func flagComment(abuseFlagged: Bool, commentID: String) -> NetworkRequest<DiscussionComment> {
let json = JSON(["abuse_flagged" : abuseFlagged])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/comments/\(commentID)/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .jsonResponse(commentDeserializer)
)
}
// User can only follow original post, not response or comment.
static func followThread(following: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["following" : !following])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .jsonResponse(threadDeserializer)
)
}
// mark thread as read
static func readThread(read: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["read" : read])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.jsonBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .jsonResponse(threadDeserializer)
)
}
// Pass nil in place of topicIDs if we need to fetch all threads
static func getThreads(environment: RouterEnvironment?, courseID: String, topicIDs: [String]?, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort, pageNumber : Int) -> NetworkRequest<Paginated<[DiscussionThread]>> {
var query = ["course_id" : JSON(courseID)]
addRequestedFields(environment: environment, query: &query)
if let identifiers = topicIDs {
//TODO: Replace the comma separated strings when the API improves
query["topic_id"] = JSON(identifiers.joined(separator: ","))
}
if let view = filter.apiRepresentation {
query["view"] = JSON(view)
}
if let order = orderBy.apiRepresentation {
query["order_by"] = JSON(order)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
requiresAuth : true,
query: query,
deserializer : .jsonResponse(threadListDeserializer)
).paginated(page: pageNumber)
}
static func getFollowedThreads(environment: RouterEnvironment?, courseID : String, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort, pageNumber : Int = 1) -> NetworkRequest<Paginated<[DiscussionThread]>> {
var query = ["course_id" : JSON(courseID), "following" : JSON(true)]
addRequestedFields(environment: environment, query: &query)
if let view = filter.apiRepresentation {
query["view"] = JSON(view)
}
if let order = orderBy.apiRepresentation {
query["order_by"] = JSON(order)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
requiresAuth : true,
query: query,
deserializer : .jsonResponse(threadListDeserializer)
).paginated(page: pageNumber)
}
static func searchThreads(environment: RouterEnvironment?, courseID: String, searchText: String, pageNumber : Int = 1) -> NetworkRequest<Paginated<[DiscussionThread]>> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
requiresAuth : true,
query: [
"course_id" : JSON(courseID),
"text_search": JSON(searchText)
],
deserializer : .jsonResponse(threadListDeserializer)
).paginated(page: pageNumber)
}
//TODO: Yet to decide the semantics for the *endorsed* field. Setting false by default to fetch all questions.
//Questions can not be fetched if the endorsed field isn't populated
static func getResponses(environment:RouterEnvironment?, threadID: String, threadType : DiscussionThreadType, endorsedOnly endorsed : Bool = false,pageNumber : Int = 1) -> NetworkRequest<Paginated<[DiscussionComment]>> {
var query = ["thread_id": JSON(threadID)]
if let environment = environment, environment.config.discussionsEnabledProfilePictureParam {
query["requested_fields"] = JSON("profile_image")
}
//Only set the endorsed flag if the post is a question
if threadType == .Question {
query["endorsed"] = JSON(endorsed)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/comments/", // responses are treated similarly as comments
requiresAuth : true,
query: query,
deserializer : .jsonResponse(commentListDeserializer)
).paginated(page: pageNumber)
}
private static func addRequestedFields(environment: RouterEnvironment?, query: inout [String : JSON]) {
if let environment = environment, environment.config.discussionsEnabledProfilePictureParam {
query["requested_fields"] = JSON("profile_image")
}
}
static func getCourseTopics(courseID: String) -> NetworkRequest<[DiscussionTopic]> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/course_topics/\(courseID)",
requiresAuth : true,
deserializer : .jsonResponse(topicListDeserializer)
)
}
static func getTopicByID(courseID: String, topicID : String) -> NetworkRequest<[DiscussionTopic]> {
let query = ["topic_id" : JSON(topicID)]
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/course_topics/\(courseID)",
requiresAuth : true,
query: query,
deserializer : .jsonResponse(topicListDeserializer)
)
}
// get response comments
static func getComments(environment:RouterEnvironment?, commentID: String, pageNumber: Int) -> NetworkRequest<Paginated<[DiscussionComment]>> {
var query: [String: JSON] = [:]
if let environment = environment, environment.config.discussionsEnabledProfilePictureParam {
query["requested_fields"] = JSON("profile_image")
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/comments/\(commentID)/",
requiresAuth : true,
query: query,
deserializer : .jsonResponse(commentListDeserializer)
).paginated(page: pageNumber)
}
static func getDiscussionInfo(courseID: String) -> NetworkRequest<(DiscussionInfo)> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/courses/\(courseID)",
requiresAuth : true,
query: [:],
deserializer : .jsonResponse(discussionInfoDeserializer)
)
}
}
| 41.5 | 228 | 0.616189 |
f89dc8e67be7aa068d26d313d4393fa2eebe7ea4 | 520 | //
// PollPredefinedAnswer.swift
// AirLockSDK
//
// Created by Yoav Ben Yair on 06/10/2021.
//
import Foundation
public class PollPredefinedAnswer : PollAnswer {
public let correctAnswer: Bool?
override init?(answerObject: AnyObject){
if let correctAnswer = answerObject["correctAnswer"] as? Bool {
self.correctAnswer = correctAnswer
} else {
self.correctAnswer = nil
}
super.init(answerObject: answerObject)
}
}
| 20 | 71 | 0.609615 |
d96b8dae4624c7e49b13808d03cdd18007aafc86 | 1,046 | //
// SourceCodeLine.swift
// ModelCompiler
//
// Created by Egor Taflanidi on 14.06.28.
// Copyright © 28 Heisei RedMadRobot LLC. All rights reserved.
//
import Foundation
open class SourceCodeLine: CustomDebugStringConvertible, Equatable {
open let absoluteFilePath: String
open let lineNumber: Int
open let line: String
open var debugDescription: String
{
get {
return "Source Code Line: filename: \(self.absoluteFilePath); line number: \(self.lineNumber); line: \(self.line)"
}
}
public init(absoluteFilePath: String, lineNumber: Int, line: String)
{
self.absoluteFilePath = absoluteFilePath
self.lineNumber = lineNumber
self.line = line
}
}
public func ==(left: SourceCodeLine, right: SourceCodeLine) -> Bool
{
return
left.lineNumber == right.lineNumber
&& left.line == right.line
&& left.absoluteFilePath == right.absoluteFilePath
}
| 25.512195 | 126 | 0.610899 |
bf76dd01f4c1964db351c5c734a22ce60cede4a2 | 776 | //
// UIHelper.swift
// GithubFinder
//
// Created by Diego Oruna on 6/08/20.
//
import UIKit
struct UIHelper {
static func createThreeColumnFlowLayout(in view:UIView) -> UICollectionViewFlowLayout{
let width = view.bounds.width
let padding:CGFloat = 12
let minimumItemSpacing:CGFloat = 10
let availableWidth = width - (padding * 2) - (minimumItemSpacing * 2)
let itemWidth = availableWidth / 3
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = .init(top: padding, left: padding, bottom: padding, right: padding)
flowLayout.itemSize = .init(width: itemWidth, height: itemWidth + 40)
return flowLayout
}
}
| 25.032258 | 101 | 0.617268 |
8af2b4be492c63d30fb8ba06888862deae40894a | 4,458 | //
// AppDelegate.swift
// SwipeToDeleteInsidePageVC
//
// Created by Andrey Filipenkov on 18/04/2019.
// Copyright © 2019 kambala. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let centralVc = UIViewController()
let leftTable = ViewController("left", isRightToLeft: false)
let rightTable = ViewController("right", isRightToLeft: true)
weak var gestureRecognizerShouldBeginCustomHandler: ViewController?
weak var pageVcScrollViewPanRecognizerOriginalDelegate: UIGestureRecognizerDelegate!
typealias ObjcGestureRecognizerShouldBeginFn = @convention(c) (AnyObject, Selector, UIGestureRecognizer) -> Bool
var gestureRecognizerShouldBeginOriginalImp: ObjcGestureRecognizerShouldBeginFn!
let gestureRecognizerShouldBeginSelector = #selector(UIGestureRecognizerDelegate.gestureRecognizerShouldBegin(_:))
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = {
let pageVc = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal)
pageVc.dataSource = self
pageVc.delegate = self
pageVc.setViewControllers([self.centralVc], direction: .forward, animated: false, completion: nil)
pageVcScrollViewPanRecognizerOriginalDelegate = (pageVc.view.subviews.first as! UIScrollView).panGestureRecognizer.delegate
return pageVc
}()
window!.makeKeyAndVisible()
// swizzle -gestureRecognizerShouldBegin: of pan's delegate
let gestureRecognizerShouldBeginBlock: @convention(block) (AnyObject?, UIGestureRecognizer) -> Bool = { (this: AnyObject?, gestureRecognizer: UIGestureRecognizer) in
// only perform custom handling if the handler is set and it's pan's delegate that is called
guard let handler = self.gestureRecognizerShouldBeginCustomHandler, (this as? UIGestureRecognizerDelegate) === self.pageVcScrollViewPanRecognizerOriginalDelegate else {
return self.gestureRecognizerShouldBeginOriginalImp(this!, self.gestureRecognizerShouldBeginSelector, gestureRecognizer)
}
return !handler.shouldAllowTableSwipeWithRecognizer(gestureRecognizer)
}
let protocolSelector = protocol_getMethodDescription(UIGestureRecognizerDelegate.self, gestureRecognizerShouldBeginSelector, false, true).name
let imp = method_setImplementation(class_getInstanceMethod(type(of: pageVcScrollViewPanRecognizerOriginalDelegate), protocolSelector!)!,
imp_implementationWithBlock(unsafeBitCast(gestureRecognizerShouldBeginBlock, to: AnyObject.self)))
gestureRecognizerShouldBeginOriginalImp = unsafeBitCast(imp, to: ObjcGestureRecognizerShouldBeginFn.self)
centralVc.view.backgroundColor = UIColor.lightGray
return true
}
}
// MARK: - UIPageViewControllerDataSource
extension AppDelegate: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
switch viewController {
case leftTable:
return centralVc
case centralVc:
return rightTable
default:
return nil
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
switch viewController {
case rightTable:
return centralVc
case centralVc:
return leftTable
default:
return nil
}
}
}
// MARK: - UIPageViewControllerDataSource
extension AppDelegate: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
guard completed, let currentVc = pageViewController.viewControllers?.first, currentVc != previousViewControllers.first else {
return
}
gestureRecognizerShouldBeginCustomHandler = currentVc != centralVc ? (currentVc as! ViewController) : nil
}
}
| 48.456522 | 190 | 0.738672 |
d5d034c1f09f15eb393365e56c89c27773cf3de5 | 2,336 | //
// BigBoxViewController + TableCellTodoTodayBoxDelegate.swift
// What to-do today?
//
// Created by Jayson Chen on 2019/7/31.
// Copyright © 2019 Jayson Chen. All rights reserved.
//
import UIKit
extension BigBoxViewController : TableCellTodoTodayBoxDelegate {
@IBAction func checkCheckBox(_ sender: UIButton) {
Constants.heavyHaptic.impactOccurred()
let index = sender.tag
list[todayIndexList[index]].done! = !list[todayIndexList[index]].done!
saveData()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadSmallBox"), object: nil)
}
// edit the text in the today box
func doneEdittingTodayCell(_ newText: String, _ sender : TodayTupleTableViewCell) {
let index = tableView.indexPath(for: sender)?.row
if newText.isEmpty {
todayList.remove(at: index!)
tableView.deleteRows(at: [IndexPath(row: index!, section: 0)], with: .fade)
let uuid = list[todayIndexList[index!]].uuid!
list.remove(at: todayIndexList[index!])
todayOrdersList.remove(at: todayOrdersList.index(of: uuid)!)
// here
} else {
list[todayIndexList[index!]].content = newText
}
saveData()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadSmallBox"), object: nil)
}
func moveOutToday(_ sender : TodayTupleTableViewCell) {
Constants.mediumHaptic.impactOccurred()
let index = tableView.indexPath(for: sender)?.row
sender.textView.resignFirstResponder()
list[todayIndexList[index!]].isToday = !list[todayIndexList[index!]].isToday
let uuid = list[todayIndexList[index!]].uuid!
todayOrdersList.remove(at: todayOrdersList.index(of: uuid)!)
todayList.remove(at: index!)
todayIndexList.remove(at: index!)
saveData()
}
func todayEnterEdit(_ indexPath : IndexPath) {
todayIsEditting = true
scrollTarget = indexPath.row
}
func saveData() {
user?.todoList! = []
user?.todayOrdersList = []
PersistenceService.saveContext()
user?.todoList! = list
user?.todayOrdersList = todayOrdersList
PersistenceService.saveContext()
reloadToday()
}
}
| 35.393939 | 107 | 0.644692 |
61addbfeb9bdb6d0c82701470982cb644bcab484 | 41,303 | /* ***********
* Project : Esp-App-Mobile-iOS - App to connect a Esp32 device by BLE
* Programmer: Joao Lopes
* Module : MainController - main controller and main code in app
* Comments : Uses a singleton pattern to share instance to all app
* Versions :
* ------- -------- -------------------------
* 0.1.0 08/08/18 First version
* 0.1.1 17.08.18 Adjusts in send repeat echoes
* 0.1.2 17/08/18 Adjusts in Terminal BLE and Debug
* 0.2.0 20/08/18 Option to disable logging br BLE (used during repeated sends)
* 0.3.0 23/08/18 Changed name of github repos to Esp-App-Mobile-Apps-*
* Few adjustments
* 0.3.1 24/08/18 Alert for BLE device low battery
**/
/*
// TODO:
*/
import Foundation
import UIKit
public class MainController: NSObject, BLEDelegate {
/////// Singleton
static private var instance : MainController {
return sharedInstance
}
private static let sharedInstance = MainController()
// Singleton pattern method
static func getInstance() -> MainController {
return self.instance
}
////// BLE instance
#if !targetEnvironment(simulator) // Real device ? (not for simulator)
private let ble = BLE.getInstance ()
#endif
////// Objects
var navigationController: UINavigationController? = nil // Navegation
var storyBoardMain: UIStoryboard? = nil // Story board Main
@objc var timerSeconds: Timer? = nil // Timer in seconds
var imageBattery: UIImage? = nil // Battery
///// Variables
public let versionApp:String = "0.3.1" // Version of this APP
private (set) var versionDevice: String = "?" // Version of BLE device
private (set) var timeFeedback: Int = 0 // Time to send feedbacks
private (set) var sendFeedback: Bool = false // Send feedbacks ?
private (set) var timeActive: Int = 0 // Time of last activity
private var exiting: Bool = false
private (set) var deviceHaveBattery: Bool = false // Device connected have a battery
private (set) var deviceHaveSenCharging: Bool = false // Device connected have a sensor of charging of battery
private (set) var poweredExternal: Bool = false // Powered by external (USB or power supply)?
private (set) var chargingBattery: Bool = false // Charging battery ?
private (set) var statusBattery:String = "100%" // Battery status
private (set) var voltageBattery: Float = 0.0 // Voltage calculated of battery
private (set) var readADCBattery: Int = 0 // Value of ADC read of battery
private (set) var debugging: Bool = true // Debugging ?
// Global exception treatment // TODO: make it in future
// private let mExceptionHandler: ExceptionHandler
// BLE
private var bleStatusActive: Bool = false // Active BLE status in the panel?
private var bleTimeout: Int = 0 // BLE Timeout
private var bleVerifyTimeout: Bool = true // Check timeout?
private var bleAbortingConnection: Bool = false // Aborting connection ?
private (set) var bleDebugs: [BLEDebug] = [] // Array for BLE debugs
public var bleDebugEnabled: Bool =
AppSettings.TERMINAL_BLE // It is enabled ?
/////////////////// Init
// Init
override init() {
super.init()
// Initialize App
initializeApp ()
}
/////////////////// Methods
private func activateTimer (activate: Bool) {
// Timer of seconds
debugV("activate:", activate)
// Zera veriaveis
timeFeedback = 0
// active?
if activate {
if timerSeconds != nil {
// Disable before the previous one
timerSeconds?.invalidate()
}
// Activate the timer
self.timerSeconds = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerTickSeconds), userInfo: nil, repeats: true)
} else {
// Cancel timer
if timerSeconds != nil {
self.timerSeconds?.invalidate()
}
}
}
@objc private func timerTickSeconds() {
// Timer every second - only when connected
#if !targetEnvironment (simulator) // Real device ? (not for simulator)
if ble.connected == false {
// Timer - deactivate
activateTimer (activate: false)
return
}
if self.bleStatusActive {
showStatusBle (active: false)
}
// Send Timeout
if bleVerifyTimeout == true && !debugging {
bleTimeout -= 1
if bleTimeout <= 0 {
debugE("*** Timeout")
bleAbortConnection (message: "No response from BLE device (code B2)")
return
}
}
#endif
// Check inactivity
if let _:MainMenuViewController = navigationController?.topViewController
as? MainMenuViewController { // In main menu ?
// Remaining time to go into inactivity
timeActive -= 1
// debugV ("Active time =" + mTimeActive)
if timeActive <= 0 {
// Abort connection
bleAbortConnection (message: "The connection and device was shutdown, due to having reached maximum time of inactivity (\(AppSettings.TIME_MAX_INACTITIVY)s.)")
return
}
} else { // For others - set it as active
timeActive = AppSettings.TIME_MAX_INACTITIVY
}
#if !targetEnvironment (simulator) // Real device
if ble.sendingNow == false && sendFeedback == true {
// Send feedback periodically
timeFeedback += 1
if timeFeedback == AppSettings.TIME_SEND_FEEDBACK {
bleSendFeedback()
timeFeedback = 0
}
}
#endif
// Terminal BLE
if AppSettings.TERMINAL_BLE {
if let terminalBLEVC:TerminalBLEViewController = navigationController?.topViewController as? TerminalBLEViewController {
// Is to send repeated (only for echoes) ?
if terminalBLEVC.repeatSend {
// Show a debug with the total per second
if terminalBLEVC.bleTotRepeatPSec > 0 {
bleAddDebug(type: "O", message: "*** Repeats(send/receive) p/sec.: \(terminalBLEVC.bleTotRepeatPSec)", extra: "", forced: true)
} else { // Send again, if no responses received
terminalBLEVC.send(repeated: true)
}
// Clear the total
terminalBLEVC.bleTotRepeatPSec = 0
}
}
}
}
public func initializeVariables () {
// Initialize control variables
bleVerifyTimeout = false
bleTimeout = 0
sendFeedback = false
timeActive = AppSettings.TIME_MAX_INACTITIVY
}
func showVCMainMenu () {
// Show the main menu view controller
if storyBoardMain == nil {
storyBoardMain = UIStoryboard(name: "Main", bundle: nil)
}
// Update the UI
DispatchQueue.main.async {
let mainMenuVC = self.storyBoardMain?.instantiateViewController(withIdentifier: "Main menu") as? MainMenuViewController
self.navigationController?.pushViewController(mainMenuVC!, animated: true)
}
}
func showVCDisconnected (message: String) {
// Show disconnected view controller
if storyBoardMain == nil {
storyBoardMain = UIStoryboard(name: "Main", bundle: nil)
}
// Update the UI
DispatchQueue.main.async {
// Returns to VC root
self.navigationController?.popToRootViewController(animated:false)
//Show disconnected view controller
if self.storyBoardMain == nil {
self.storyBoardMain = UIStoryboard(name: "Main", bundle: nil)
}
if let disconnectedVC = self.storyBoardMain?.instantiateViewController(withIdentifier: "Disconnected") as? DisconnectedViewController {
self.navigationController?.pushViewController(disconnectedVC, animated: false)
disconnectedVC.message = message
}
}
}
// Show status of battery
func showStatusBattery () {
// Show data saved before
var imageViewBattery: UIImageView!
var labelPercentBattery: UILabel!
// Process VC // TODO: see it! put here all VC that have a statusbar
if let mainMenu = navigationController?.topViewController as? MainMenuViewController {
labelPercentBattery = mainMenu.labelPercentBattery
imageViewBattery = mainMenu.imageViewBattery
} else if let infoVC = navigationController?.topViewController as? InformationsViewController {
labelPercentBattery = infoVC.labelPercentBattery
imageViewBattery = infoVC.imageViewBattery
} else if let terminalBLEVC = navigationController?.topViewController as? TerminalBLEViewController {
labelPercentBattery = terminalBLEVC.labelPercentBattery
imageViewBattery = terminalBLEVC.imageViewBattery
// } else if let settingsVC = navigationController?.topViewController as? SettingsViewController {
// labelPercentBattery = mainMenu.labelPercentBattery
// imageViewBattery = mainMenu.imageViewBattery
}
// Show status of battery
if labelPercentBattery != nil {
// Update UI
DispatchQueue.main.async {
if self.deviceHaveBattery {
imageViewBattery.isHidden = false
labelPercentBattery.isHidden = false
imageViewBattery.image = self.imageBattery
labelPercentBattery.text = self.statusBattery
} else {
imageViewBattery.isHidden = true
labelPercentBattery.isHidden = true
}
}
}
}
// Show status of BLE (icon)
func showStatusBle (active:Bool) {
var imageViewBluetooth: UIImageView!
// TODO: see it! need put all VC that have a statusbar here
if let mainMenuVC = navigationController?.topViewController as? MainMenuViewController {
imageViewBluetooth = mainMenuVC.imageViewBluetooth
} else if let infoVC = navigationController?.topViewController as? InformationsViewController {
imageViewBluetooth = infoVC.imageViewBluetooth
} else if let terminalBLEVC = navigationController?.topViewController as? TerminalBLEViewController {
imageViewBluetooth = terminalBLEVC.imageViewBluetooth
// } else if let terminalVC = navigationController?.topViewController as? TerminalViewController {
// } else if let settingsVC = navigationController?.topViewController as? SettingsViewController {
// imageViewBluetooth = settingsVC.imageViewBluetooth
}
// Update UI
if imageViewBluetooth != nil {
DispatchQueue.main.async {
imageViewBluetooth.image = (active) ? #imageLiteral(resourceName: "bt_icon") : #imageLiteral(resourceName: "bt_icon_inactive")
}
}
self.bleStatusActive = true
}
////// BLE
// Scan a device
public func bleScanDevice() {
// Starting the scanning ...
debugV("Scanning device ...")
// Is on screen of connection ?
if let connectingVC:ConnectingViewController = navigationController?.topViewController as? ConnectingViewController {
connectingVC.labelScanning.text = "Scanning now ..."
}
#if !targetEnvironment(simulator) // Real device
ble.startScan(AppSettings.BLE_DEVICE_NAME)
#endif
}
// Connected
private func bleConnected () {
// Connection OK
// Activate the timer
activateTimer(activate: true)
// Message initial
bleSendMessage(MessagesBLE.MESSAGE_INITIAL, verifyResponse: true, debugExtra: "Initial")
// Send feedbacks
sendFeedback = true
}
// Abort the connection
func bleAbortConnection(message:String) {
// Only if not still running, to avoid loops
if bleAbortingConnection {
return
}
// On disconnected VC ?
if let _ = navigationController?.topViewController as? DisconnectedViewController {
return
}
// Abort
bleAbortingConnection = true
debugV("msg=" + message)
// Message to device enter in standby or reinitialize
#if !targetEnvironment(simulator) // Real device
if ble.connected {
if !poweredExternal {
bleSendMessage(MessagesBLE.MESSAGE_STANDBY, verifyResponse: false, debugExtra: "Standby")
} else {
bleSendMessage(MessagesBLE.MESSAGE_RESTART, verifyResponse: false, debugExtra: "Restart")
}
}
#endif
// Abort timers
activateTimer(activate: false)
// Ends connection BLE
#if !targetEnvironment(simulator) // Real device
ble.disconnectPeripheral()
#endif
// Init variables
initializeVariables()
// Debug
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
self.bleAddDebug(type: "O", message: "Connection aborted: \(message)") // Add debug
}
// Shom message on disconnected VC
showVCDisconnected(message: message)
// Abort processed
bleAbortingConnection = false
}
// Send a message by BLE
func bleSendMessage(_ message:String, verifyResponse:Bool=false, debugExtra: String = "") {
#if !targetEnvironment(simulator) // Real device
// If not connected or just sending now, returns
// To avoid problems
if !ble.connected || ble.sendingNow {
return
}
// Multithreading
DispatchQueue.global().async {
// Debug
debugV("send menssage \(message)")
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
self.bleAddDebug(type: "S", message: message, extra: debugExtra) // Add debug
}
// Reinitializes the time for feedbacks
self.timeFeedback = 0
// Show status
self.showStatusBle(active: true)
self.showMessageStatus("Sending data to device ...")
// Send a message by BLE
self.ble.send(message)
// Verify response ? (timeout)
if verifyResponse {
self.bleTimeout = AppSettings.BLE_TIMEOUT
self.bleVerifyTimeout = true
self.showMessageStatus("Waiting response ...")
} else { // Not waiting a response
self.bleTimeout = 0
self.bleVerifyTimeout = false
self.showMessageStatus("")
}
}
#endif
}
// Send a feedback message
func bleSendFeedback() {
#if !targetEnvironment(simulator) // Real device
debugV("")
// Is is just sending now, ignore
if ble.sendingNow {
return
}
// Send a message
bleSendMessage(MessagesBLE.MESSAGE_FEEDBACK, verifyResponse: true, debugExtra: "Feedback")
#endif
}
// Process the message received by BLE
func bleProcessMessageRecv(_ message: String) {
#if !targetEnvironment(simulator) // Real device
// Process the message
if message.count < 3 {
debugE("invalid msg (<3):", message)
return
}
// Extract the delimited fields
let fields: Fields = Fields(message, delim:":")
// Extract code
let codMsg:Int = Int(fields.getField(1)) ?? -1
// Process the message by code
switch codMsg {
case MessagesBLE.CODE_OK: // OK
// Receive OK response, generally no process need
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "OK")
}
break
case MessagesBLE.CODE_INITIAL: // Initial message response
// Format O1:Version:HaveBattery:HaveSensorCharging
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Initial")
}
bleProcessInitial(fields: fields)
case MessagesBLE.CODE_ENERGY: // Status of energy: USB ou Battery
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Energy")
}
debugV("Messagem of energy")
bleProcessEnergy(fields: fields)
// Note: example of call subroutine to update the VC
if let infoVC:InformationsViewController = navigationController?.topViewController as? InformationsViewController {
infoVC.updateEnergyInfo()
}
case MessagesBLE.CODE_INFO: // Status of energy: USB ou Battery
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Info")
}
debugV("Message of info")
bleProcessInfo(fields: fields)
case MessagesBLE.CODE_ECHO: // Echo -> receives the same message sended
// Echo received
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Echo")
}
if let terminalBLEVC:TerminalBLEViewController = navigationController?.topViewController as? TerminalBLEViewController {
// Is to send repeated (only for echoes) ??
if terminalBLEVC.repeatSend {
terminalBLEVC.bleTotRepeatPSec += 1
bleSendMessage(message, verifyResponse: true, debugExtra: "Echo")
}
}
break
case MessagesBLE.CODE_FEEDBACK: // Feedback
// Feedback received
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Feedback")
}
break
case MessagesBLE.CODE_STANDBY: // Entrou em standby
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Standby")
}
bleAbortConnection(message: "The device is turn off")
default: // Invalid code
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleUpdateDebug(extra: "Invalid")
}
debugE("invalid msg code", message)
}
#endif
}
// Process initial message
private func bleProcessInitial(fields: Fields) {
// Note: this is a example how this app discovery device hardware
// This usefull to works with versions or models of hardware
// For example: if device have a battery, the app show status of this
// Format of message: 01:FIRWARE VERSION:HAVE BATTERY:HAVE SENSOR CHARGING
debugV("initial msg")
// Version
versionDevice = fields.getField(2)
debugV("version of device ", versionDevice)
// Have a battery
deviceHaveBattery = ( fields.getField(3) == "Y")
// Have a battery charging sensor
deviceHaveSenCharging = ( fields.getField(4) == "Y")
// Show the main menu
showVCMainMenu()
}
// Process energy message
private func bleProcessEnergy(fields: Fields) {
// Format of message: 10:POWERED:CHARGING:ADC_BATTERY
poweredExternal = (fields.getField(2) == "EXT")
chargingBattery = (fields.getField(3) == "Y")
readADCBattery = fields.getFieldInt(4)
debugD("usb=", poweredExternal, "charging=", chargingBattery, "vbat=", readADCBattery)
// Calculate the voltage (done here note in firmware - due more easy to update)
// TODO: see it! please caliber it first !
// To caliber:
// - A charged battery plugged
// - Unplug the USB cable (or energy cable)
// - Meter the voltage of battery with multimeter
// - See the value of ADC read in monitor serial or in App informations
let voltageCaliber: Float = 3.942
let readADCCaliber: Float = 3168
let factorCaliber: Float = (voltageCaliber / readADCCaliber)
// Voltage readed from ADC
let oldVoltage = voltageBattery
voltageBattery = Util.round((Float(readADCBattery) * factorCaliber), 2)
debugV("vbat ->", voltageBattery, "v")
// Calculate the %
var percent:Int = 0
var voltage:Float = voltageBattery
if voltage >= 2.5 {
voltage -= 2.5 // Limit // TODO: see it!
percent = Int(Util.round(((voltage * 100.0) / 1.7), 0))
if percent > 100 {
percent = 100
}
} else {
percent = 0
}
// Show o icon of battery and percent of this
// TODO: see it! Experimental code, please verify this works ok
statusBattery = ""
imageBattery = nil
if deviceHaveSenCharging { // With sensor of charging
if poweredExternal { // Powered by USB or external
statusBattery = "Ext"
} else {
statusBattery = "Bat"
}
if poweredExternal && chargingBattery { // Charging by USB or external
imageBattery = #imageLiteral(resourceName: "charging")
statusBattery += "|Chg"
} else { // Not charging, process a voltage
statusBattery += "|\(percent)%"
}
} else { //without sensor
if (poweredExternal) { // Powered by USB or external
imageBattery = #imageLiteral(resourceName: "battery7")
statusBattery = "Ext"
} else { // Not charging, process a voltage
statusBattery = "\(percent)%"
}
}
// show image of battery by voltage ?
if imageBattery == nil {
if voltageBattery >= 4.2 {
imageBattery = #imageLiteral(resourceName: "battery6")
} else if voltageBattery >= 3.9 {
imageBattery = #imageLiteral(resourceName: "battery6")
} else if voltageBattery >= 3.7 {
imageBattery = #imageLiteral(resourceName: "battery5")
} else if voltageBattery >= 3.5 {
imageBattery = #imageLiteral(resourceName: "battery4")
} else if voltageBattery >= 3.3 {
imageBattery = #imageLiteral(resourceName: "battery3")
} else if voltageBattery >= 3.0 {
imageBattery = #imageLiteral(resourceName: "battery2")
} else {
imageBattery = #imageLiteral(resourceName: "battery1")
}
}
// Show it
showStatusBattery()
// Battery low ?
let low: Float = 3.1 // Experimental // TODO do setting
if voltageBattery <= low &&
(oldVoltage == 0.0 || oldVoltage > low) {
Alert.alert("Attention: low battery on BLE device!", viewController: UtilUI.getRootViewController()!)
}
}
// Process info messages
func bleProcessInfo(fields: Fields) {
// Example of process content delimited of message
// Note: field 1 is a code of message
// Is on informations screen ?
// Note: example of show data in specific view controller
guard let infoVC:InformationsViewController = navigationController?.topViewController as? InformationsViewController else {
return
}
// Extract data
let type: String = fields.getField(2)
var info: String = fields.getField(3)
debugV("type: \(type) info \(debugEscapedStr(info))")
// Update UI
DispatchQueue.main.async {
// Process information by type
switch type {
case "ESP32":
// About ESP32
// Works with info (\n (message separator) and : (field separator) cannot be send by device
info = info.replacingOccurrences(of: "#", with: "\n") // replace it
info = info.replacingOccurrences(of: ";", with: ":") // replace it
#if !targetEnvironment(simulator) // Device real
info.append("* RSSI of connection: ")
info.append(String(self.ble.maxRSSIFound))
info.append("\n")
#endif
info.append("*** Device hardware")
info.append("\n")
info.append("* Have a battery ?: ")
info.append(((self.deviceHaveBattery) ? "Yes" : "No"))
info.append("\n")
info.append("* Have sensor charging ?: ")
info.append(((self.deviceHaveSenCharging) ? "Yes" : "No"))
info.append("\n")
infoVC.textViewAboutEsp32.text = info
case "VDD33":
// Voltage reading of ESP32 - Experimental code!
// Calculate the voltage (done here note in firmware - due more easy to update)
// TODO: see it! please caliber it first !
// To caliber:
// - Unplug the USB cable (or energy cable)
// - Meter the voltage of 3V3 pin (or 2 pin of ESP32)
// - See the value of rom_phy_get_vdd33 read in monitor serial or in App informations
let voltageCaliber: Float = 3.317
let readPhyCaliber: Float = 6742
let factorCaliber: Float = (voltageCaliber / readPhyCaliber)
// Voltage readed from ADC
let voltageEsp32: Float = Util.round((Float(info)! * factorCaliber), 2)
infoVC.labelVoltageEsp32.text = "\(info) (\(voltageEsp32)v)"
case "FMEM":
// Free memory of ESP32
infoVC.labelFreeMemory.text = info
// VUSB and VBAT is by energy type message
default:
debugE("Invalid type: \(type)")
}
}
}
// Name of device connected
func bleNameDeviceConnected () -> String {
#if !targetEnvironment(simulator) // Real device
return (ble.connected) ? " Connected a \(ble.peripheralConnected?.name ?? "")" : "Not connected"
#else // Simulator
return "simulator (not connected)"
#endif
}
///////// BLE delegates
func bleDidUpdateState(_ state: BLECentralManagerState) {
#if !targetEnvironment(simulator) // Real device
// Verify status
if state == BLECentralManagerState.poweredOn {
let message = "Bluetooth is enable"
debugW(message)
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleAddDebug(type: "O", message: message) // Add debug
}
// Search devive
bleScanDevice()
} else {
let message = "Bluetooth is disabled"
debugW(message)
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleAddDebug(type: "O", message: message) // Add debug
}
bleAbortConnection(message: "Please turn on the Bluetooth")
// On connecting VC ?
if let connectingVC:ConnectingViewController = navigationController?.topViewController as? ConnectingViewController {
Alert.alert("Please turn on the Bluetooth", title:"Bluetooth is disabled", viewController: connectingVC)
}
}
#endif
}
// Timeout of BLE scan
func bleDidTimeoutScan() {
#if !targetEnvironment(simulator) // Real device
let message = "Could not connect to device"
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleAddDebug(type: "O", message: message) // Add debug
}
bleAbortConnection(message: message)
#endif
}
// Connecting
func bleDidConnectingToPeripheral(_ name: String) {
#if !targetEnvironment(simulator) // Real device
let message = "Found: \(name)"
// On connecting VC ?
if let connectingVC:ConnectingViewController = navigationController?.topViewController as? ConnectingViewController {
connectingVC.labelMessage.text = message
}
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleAddDebug(type: "C", message: message) // Add debug
}
#endif
}
// Connection successfully (after discoveries)
func bleDidConnectToPeripheral(_ name: String) {
#if !targetEnvironment(simulator) // Real device
let message = "Connected a \(name)"
// On connecting VC ?
if let connectingVC:ConnectingViewController = navigationController?.topViewController as? ConnectingViewController {
connectingVC.labelMessage.text = message
}
// Successful connection
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleAddDebug(type: "C", message: message) // Add debug
}
bleConnected()
#endif
}
// Received a data from device - not used
func bleDidReceiveData(data: String) {
}
// Received a line from device
func bleDidReceiveLine(line: String) {
#if !targetEnvironment(simulator) // Real device
// Multithreading
DispatchQueue.global().async {
// Process the message
// Is waiting a response ?
if self.bleVerifyTimeout {
self.showMessageStatus("")
self.bleVerifyTimeout = false
self.bleTimeout = AppSettings.BLE_TIMEOUT
}
// Restart time of feedback
self.timeFeedback = 0
// Occurs an error in device ?
if line.starts(with: MessagesBLE.MESSAGE_ERROR) {
self.bleUpdateDebug(extra: "Error")
debugE("occurs error: \(line)")
// Can abort or only show a message
//bleAbortConnection(message: "Occurs a exception on device: " + line)
// TODO: show a message
return
}
// Process the message
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
self.bleAddDebug(type: "R", message: line) // Add debug
}
self.bleProcessMessageRecv(line)
}
#endif
}
// Disconnect
func bleDidDisconnectFromPeripheral() {
#if !targetEnvironment(simulator) // Real device
let message = "Device disconnected (code B1)"
if AppSettings.TERMINAL_BLE && self.bleDebugEnabled { // App have a Terminal BLE (debug) and it is enabled ?
bleAddDebug(type: "D", message: message) // Add debug
}
bleAbortConnection(message: message) // Abort
#endif
}
// Add Debug BLE
func bleAddDebug (type: Character, message: String, extra: String = "", forced: Bool = false) {
// App have a Terminal BLE (debug)
if !(AppSettings.TERMINAL_BLE && (self.bleDebugEnabled || forced)) { // App have a Terminal BLE (debug) and it is enabled ?
return
}
// Add debug
let bleDebug = BLEDebug()
// Time
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
bleDebug.time = "\(String(format: "%02d",hour)):\(String(format: "%02d",minutes)):\(String(format: "%02d",seconds))"
// Type
bleDebug.type = type
// Message
bleDebug.message = message
// Extra
bleDebug.extra = extra
// Add it
if AppSettings.TERMINAL_BLE_ORDER_DESC { // Top
bleDebugs.insert(bleDebug, at: 0)
} else { // Bottom
bleDebugs.append(bleDebug)
}
// In Terminal BLE VC ?
if let terminalBLEVC:TerminalBLEViewController = navigationController?.topViewController
as? TerminalBLEViewController {
// Not for repeated sends - due can crash the app - in this case use refresh button
if !terminalBLEVC.repeatSend || forced {
// Insert row - reloadData is very slow and much CPU
terminalBLEVC.insertRow()
}
}
}
// Update last Debug BLE
func bleUpdateDebug (extra: String) {
// App have a Terminal BLE (debug)
if !(AppSettings.TERMINAL_BLE && self.bleDebugEnabled) { // App have a Terminal BLE (debug) and it is enabled ?
return
}
// Update last debug
if bleDebugs.count == 0 {
return
}
let pos: Int = (AppSettings.TERMINAL_BLE_ORDER_DESC) ? 0 : bleDebugs.count-1
let item = bleDebugs[pos]
item.extra = extra
// In Terminal BLE VC ?
if let terminalBLEVC:TerminalBLEViewController = navigationController?.topViewController
as? TerminalBLEViewController {
// Update last row - reloadData is very slow and much CPU
terminalBLEVC.updateLastRow()
}
}
/////// Utilitarias
func showMessageStatus(_ message:String) {
// Show a message on statusbar
var label:UILabel!
// TODO: see it: Put all VC with statusbar here
if let connectingVC = navigationController?.topViewController as? ConnectingViewController {
label = connectingVC.labelMessage
} else if let mainMenuVC = navigationController?.topViewController as? MainMenuViewController {
label = mainMenuVC.labelStatus
} else if let infoVC = navigationController?.topViewController as? InformationsViewController {
label = infoVC.labelStatus
} else if let terminalVC = navigationController?.topViewController as? TerminalBLEViewController {
label = terminalVC.labelStatus
// } else if let settingsVC = navigationController?.topViewController as? SettingsViewController {
// label = settingsVC.labelStatus
}
if label != nil {
// Update UI
DispatchQueue.main.async {
label.text = message
}
} else {
debugV(message)
}
}
// Initialize APP
private func initializeApp () {
// Initialize the app
// Debug - set level
debugSetLevel(.verbose)
debugV("Initilializing ...")
// BLE
#if !targetEnvironment(simulator) // Real device
ble.delegate = self
// See it! please left only of 2 below lines uncommented
ble.showDebug(.debug) // Less debug of BLE, only essential
//ble.showDebug(.verbose) // More debug
#else // Simulador
self.versionDevice = "Simul."
#endif
// Inicializa variaveis
initializeVariables()
// Debug
debugV("Initialized")
}
// Finish App
func finishApp() {
debugD("")
#if !targetEnvironment(simulator) // Device real
// Send a message to device - to turn off or restart
if ble.connected {
var message: String = ""
if AppSettings.TURN_OFF_DEVICE_ON_EXIT {
message = MessagesBLE.MESSAGE_STANDBY
} else {
message = MessagesBLE.MESSAGE_RESTART
}
ble.send(message)
sleep(1)
}
#endif
// Exit
debugD("Exiting ...")
exit (0)
}
}
////// END
| 29.800144 | 171 | 0.526499 |
1a628db4d7e5d9733f156152006437c181d7b6d1 | 510 | //
// ContentView.swift
// SwiftUIPasscode
//
// Created by luongvinh on 25/09/2021.
//
import SwiftUI
struct ContentView: View {
var body: some View {
SwiftUIPasscode(
input: PasscodeInput(
passcodeLength: 6,
completeHandler: { passcode in
print(passcode)
})
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 16.451613 | 46 | 0.531373 |
ed22fb789f00b8a4b7f924f14cd715c093e001c5 | 653 | //
// DevicesViewCell.swift
// Blue-Falcon
//
// Created by Andrew Reed on 31/08/2019.
// Copyright © 2019 Andrew Reed. All rights reserved.
//
import SwiftUI
import Combine
struct DevicesViewCell : View {
let name: String
let deviceId: String
var body: some View {
VStack(alignment: .leading) {
if !name.isEmpty {
HStack {
Text("Name:")
.bold()
Text(name)
.italic()
}.padding(EdgeInsets(top: 5, leading: 0, bottom: 0, trailing: 0))
}
Text(deviceId)
}
}
}
| 20.40625 | 81 | 0.488515 |
20cc6bd25d32409ffaf96812a04d1d7caaac3347 | 5,565 | //
// AudioLoader.swift
// Pods
//
// Created by RYOKATO on 2015/12/05.
//
//
import AVFoundation
import MobileCoreServices
class AudioLoader: NSObject, AVAssetResourceLoaderDelegate, NSURLConnectionDataDelegate {
var pendingRequests = [AVAssetResourceLoadingRequest]()
var songData = NSMutableData()
var response: URLResponse?
var connections = [String: NSURLConnection]()
var audioCache: Cache<NSData>
init(cache: Cache<NSData>) {
audioCache = cache
}
func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
self.songData = NSMutableData() // Reset the songData
self.response = response
self.processPendingRequests()
}
func connection(_ connection: NSURLConnection, didReceive data: Data) {
self.songData.append(data as Data)
self.processPendingRequests()
}
func connectionDidFinishLoading(_ connection: NSURLConnection) {
self.processPendingRequests()
let tmpUrl = NSURL(string: (connection.currentRequest.url?.absoluteString)!)!
let actualUrl = getActualURL(url: tmpUrl)
let urlString = actualUrl.absoluteString
if (audioCache.objectForKey(key: urlString!) != nil) {
return
}
audioCache[urlString!] = songData
}
func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
print(error)
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
let url = loadingRequest.request.url!
let actualURL = getActualURL(url: url as NSURL)
let urlString = actualURL.absoluteString
if (connections[urlString!] == nil) {
let request = NSURLRequest(url: actualURL as URL)
let connection = NSURLConnection(request: request as URLRequest, delegate: self, startImmediately: false)!
connection.setDelegateQueue(OperationQueue.main)
connection.start()
connections[actualURL.absoluteString!] = connection
}
self.pendingRequests.append(loadingRequest)
return true
}
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
pendingRequests = pendingRequests.filter({ $0 != loadingRequest })
}
private func processPendingRequests() {
var requestsCompleted = [AVAssetResourceLoadingRequest]()
for loadingRequest in pendingRequests {
fillInContentInformation(contentInformationRequest: loadingRequest.contentInformationRequest)
let didRespondCompletely = respondWithDataForRequest(dataRequest: loadingRequest.dataRequest!)
if didRespondCompletely == true {
requestsCompleted.append(loadingRequest)
loadingRequest.finishLoading()
}
}
for requestCompleted in requestsCompleted {
for (i, pendingRequest) in pendingRequests.enumerated() {
if requestCompleted == pendingRequest {
pendingRequests.remove(at: i)
}
}
}
}
private func fillInContentInformation(contentInformationRequest: AVAssetResourceLoadingContentInformationRequest?) {
if(contentInformationRequest == nil) {
return
}
if (self.response == nil) {
return
}
let mimeType = self.response!.mimeType
let unmanagedContentType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, mimeType! as CFString, nil)
let cfContentType = unmanagedContentType!.takeRetainedValue()
contentInformationRequest!.contentType = String(cfContentType)
contentInformationRequest!.isByteRangeAccessSupported = true
contentInformationRequest!.contentLength = self.response!.expectedContentLength
}
private func respondWithDataForRequest(dataRequest: AVAssetResourceLoadingDataRequest) -> Bool {
var startOffset: Int64 = dataRequest.requestedOffset
if dataRequest.currentOffset != 0 {
startOffset = dataRequest.currentOffset
}
let songDataLength = Int64(self.songData.length)
if songDataLength < startOffset {
return false
}
let unreadBytes = songDataLength - startOffset
let numberOfBytesToRespondWith: Int64
if Int64(dataRequest.requestedLength) > unreadBytes {
numberOfBytesToRespondWith = unreadBytes
} else {
numberOfBytesToRespondWith = Int64(dataRequest.requestedLength)
}
dataRequest.respond(with: self.songData.subdata(with: NSMakeRange(Int(startOffset), Int(numberOfBytesToRespondWith))))
let endOffset = startOffset + Int64(dataRequest.requestedLength)
let didRespondFully = songDataLength >= endOffset
return didRespondFully
}
private func getActualURL(url: NSURL) -> NSURL {
let actualURLComponents = NSURLComponents(url: url as URL, resolvingAgainstBaseURL: false)
if url.scheme == "httpstreaming" {
actualURLComponents!.scheme = "http"
} else if url.scheme == "httpsstreaming" {
actualURLComponents!.scheme = "https"
}
print("actualURLCoponents:" + actualURLComponents!.url!.absoluteString)
return actualURLComponents!.url! as NSURL
}
}
| 40.326087 | 161 | 0.675292 |
1eb1329d1972ab120bfcf208aef14ef5d64d01cf | 25,960 | //
// ExtendedLocalFileProvider.swift
// FileProvider
//
// Created by Amir Abbas Mousavian.
// Copyright © 2017 Mousavian. Distributed under MIT license.
//
#if os(macOS) || os(iOS) || os(tvOS)
import Foundation
import ImageIO
import CoreGraphics
import AVFoundation
extension LocalFileProvider: ExtendedFileProvider {
open func thumbnailOfFileSupported(path: String) -> Bool {
switch path.pathExtension.lowercased() {
case LocalFileInformationGenerator.imageThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.audioThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.videoThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.pdfThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.officeThumbnailExtensions.contains:
return true
case LocalFileInformationGenerator.customThumbnailExtensions.contains:
return true
default:
return false
}
}
open func propertiesOfFileSupported(path: String) -> Bool {
let fileExt = path.pathExtension.lowercased()
switch fileExt {
case LocalFileInformationGenerator.imagePropertiesExtensions.contains:
return LocalFileInformationGenerator.imageProperties != nil
case LocalFileInformationGenerator.audioPropertiesExtensions.contains:
return LocalFileInformationGenerator.audioProperties != nil
case LocalFileInformationGenerator.videoPropertiesExtensions.contains:
return LocalFileInformationGenerator.videoProperties != nil
case LocalFileInformationGenerator.pdfPropertiesExtensions.contains:
return LocalFileInformationGenerator.pdfProperties != nil
case LocalFileInformationGenerator.archivePropertiesExtensions.contains:
return LocalFileInformationGenerator.archiveProperties != nil
case LocalFileInformationGenerator.officePropertiesExtensions.contains:
return LocalFileInformationGenerator.officeProperties != nil
case LocalFileInformationGenerator.customPropertiesExtensions.contains:
return LocalFileInformationGenerator.customProperties != nil
default:
return false
}
}
@discardableResult
open func thumbnailOfFile(path: String, dimension: CGSize? = nil, completionHandler: @escaping ((_ image: ImageClass?, _ error: Error?) -> Void)) -> Progress? {
let dimension = dimension ?? CGSize(width: 64, height: 64)
(dispatch_queue).async {
var thumbnailImage: ImageClass? = nil
// Check cache
let fileURL = self.url(of: path)
// Create Thumbnail and cache
switch fileURL.pathExtension.lowercased() {
case LocalFileInformationGenerator.videoThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.videoThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.audioThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.audioThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.imageThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.imageThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.pdfThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.pdfThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.officeThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.officeThumbnail(fileURL, dimension)
case LocalFileInformationGenerator.customThumbnailExtensions.contains:
thumbnailImage = LocalFileInformationGenerator.customThumbnail(fileURL, dimension)
default:
completionHandler(nil, nil)
return
}
completionHandler(thumbnailImage, nil)
}
return nil
}
@discardableResult
open func propertiesOfFile(path: String, completionHandler: @escaping ((_ propertiesDictionary: [String: Any], _ keys: [String], _ error: Error?) -> Void)) -> Progress? {
(dispatch_queue).async {
let fileExt = path.pathExtension.lowercased()
var getter: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))?
switch fileExt {
case LocalFileInformationGenerator.imagePropertiesExtensions.contains:
getter = LocalFileInformationGenerator.imageProperties
case LocalFileInformationGenerator.audioPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.audioProperties
case LocalFileInformationGenerator.videoPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.videoProperties
case LocalFileInformationGenerator.pdfPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.pdfProperties
case LocalFileInformationGenerator.archivePropertiesExtensions.contains:
getter = LocalFileInformationGenerator.archiveProperties
case LocalFileInformationGenerator.officePropertiesExtensions.contains:
getter = LocalFileInformationGenerator.officeProperties
case LocalFileInformationGenerator.customPropertiesExtensions.contains:
getter = LocalFileInformationGenerator.customProperties
default:
break
}
var dic = [String: Any]()
var keys = [String]()
if let getterMethod = getter {
(dic, keys) = getterMethod(self.url(of: path))
}
completionHandler(dic, keys, nil)
}
return nil
}
}
/// Holds supported file types and thumbnail/properties generator for specefied type of file
public struct LocalFileInformationGenerator {
/// Image extensions supportes for thumbnail.
///
/// Default: `["jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff", "ico"]`
static public var imageThumbnailExtensions: [String] = ["heic", "jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff", "ico"]
/// Audio and music extensions supportes for thumbnail.
///
/// Default: `["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]`
static public var audioThumbnailExtensions: [String] = ["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]
/// Video extensions supportes for thumbnail.
///
/// Default: `["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]`
static public var videoThumbnailExtensions: [String] = ["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]
/// Portable document file extensions supportes for thumbnail.
///
/// Default: `["pdf"]`
static public var pdfThumbnailExtensions: [String] = ["pdf"]
/// Office document extensions supportes for thumbnail.
///
/// Default: `empty`
static public var officeThumbnailExtensions: [String] = []
/// Custom document extensions supportes for thumbnail.
///
/// Default: `empty`
static public var customThumbnailExtensions: [String] = []
/// Image extensions supportes for properties.
///
/// Default: `["jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff"]`
static public var imagePropertiesExtensions: [String] = ["heic", "jpg", "jpeg", "bmp", "gif", "png", "tif", "tiff"]
/// Audio and music extensions supportes for properties.
///
/// Default: `["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]`
static public var audioPropertiesExtensions: [String] = ["mp1", "mp2", "mp3", "mpa", "mpga", "m1a", "m2a", "m4a", "m4b", "m4p", "m4r", "aac", "snd", "caf", "aa", "aax", "adts", "aif", "aifc", "aiff", "au", "flac", "amr", "wav", "wave", "bwf", "ac3", "eac3", "ec3", "cdda"]
/// Video extensions supportes for properties.
///
/// Default: `["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]`
static public var videoPropertiesExtensions: [String] = ["mov", "mp4", "mpg4", "m4v", "mqv", "mpg", "mpeg", "avi", "vfw", "3g2", "3gp", "3gp2", "3gpp", "qt"]
/// Portable document file extensions supportes for properties.
///
/// Default: `["pdf"]`
static public var pdfPropertiesExtensions: [String] = ["pdf"]
/// Archive extensions (like zip) supportes for properties.
///
/// Default: `empty`
static public var archivePropertiesExtensions: [String] = []
/// Office document extensions supportes for properties.
///
/// Default: `empty`
static public var officePropertiesExtensions: [String] = []
/// Custom document extensions supportes for properties.
///
/// Default: `empty`
static public var customPropertiesExtensions: [String] = []
/// Thumbnail generator closure for image files.
static public var imageThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return LocalFileProvider.scaleDown(fileURL: fileURL, toSize: dimension)
}
/// Thumbnail generator closure for audio and music files.
static public var audioThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
let playerItem = AVPlayerItem(url: fileURL)
let metadataList = playerItem.asset.commonMetadata
#if swift(>=4.0)
let commonKeyArtwork = AVMetadataKey.commonKeyArtwork
#else
let commonKeyArtwork = AVMetadataCommonKeyArtwork
#endif
for item in metadataList {
if item.commonKey == commonKeyArtwork {
if let data = item.dataValue {
return LocalFileProvider.scaleDown(data: data, toSize: dimension)
}
}
}
return nil
}
/// Thumbnail generator closure for video files.
static public var videoThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
let asset = AVAsset(url: fileURL)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.maximumSize = dimension ?? .zero
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTime(value: asset.duration.value / 3, timescale: asset.duration.timescale)
if let cgImage = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil) {
#if os(macOS)
return ImageClass(cgImage: cgImage, size: .zero)
#else
return ImageClass(cgImage: cgImage)
#endif
}
return nil
}
/// Thumbnail generator closure for portable document files files.
static public var pdfThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return LocalFileProvider.convertToImage(pdfURL: fileURL, maxSize: dimension)
}
/// Thumbnail generator closure for office document files.
/// - Note: No default implementation is avaiable
static public var officeThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return nil
}
/// Thumbnail generator closure for custom type of files.
/// - Note: No default implementation is avaiable
static public var customThumbnail: (_ fileURL: URL, _ dimension: CGSize?) -> ImageClass? = { fileURL, dimension in
return nil
}
/// Properties generator closure for image files.
static public var imageProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value, !((value as? String)?.isEmpty ?? false) {
keys.append(key)
dic[key] = value
}
}
func simplify(_ top:Int64, _ bottom:Int64) -> (newTop:Int, newBottom:Int) {
var x = top
var y = bottom
while (y != 0) {
let buffer = y
y = x % y
x = buffer
}
let hcfVal = x
let newTopVal = top/hcfVal
let newBottomVal = bottom/hcfVal
return(Int(newTopVal), Int(newBottomVal))
}
guard let source = CGImageSourceCreateWithURL(fileURL as CFURL, nil), let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as NSDictionary? else {
return (dic, keys)
}
let tiffDict = properties[kCGImagePropertyTIFFDictionary as String] as? NSDictionary ?? [:]
let exifDict = properties[kCGImagePropertyExifDictionary as String] as? NSDictionary ?? [:]
let gpsDict = properties[kCGImagePropertyGPSDictionary as String] as? NSDictionary ?? [:]
if let pixelWidth = properties.object(forKey: kCGImagePropertyPixelWidth) as? NSNumber, let pixelHeight = properties.object(forKey: kCGImagePropertyPixelHeight) as? NSNumber {
add(key: "Dimensions", value: "\(pixelWidth)x\(pixelHeight)")
}
add(key: "DPI", value: properties[kCGImagePropertyDPIWidth as String])
add(key: "Device maker", value: tiffDict[kCGImagePropertyTIFFMake as String])
add(key: "Device model", value: tiffDict[kCGImagePropertyTIFFModel as String])
add(key: "Lens model", value: exifDict[kCGImagePropertyExifLensModel as String])
add(key: "Artist", value: tiffDict[kCGImagePropertyTIFFArtist as String] as? String)
add(key: "Copyright", value: tiffDict[kCGImagePropertyTIFFCopyright as String] as? String)
add(key: "Date taken", value: tiffDict[kCGImagePropertyTIFFDateTime as String] as? String)
if let latitude = gpsDict[kCGImagePropertyGPSLatitude as String] as? NSNumber,
let longitude = gpsDict[kCGImagePropertyGPSLongitude as String] as? NSNumber {
let altitudeDesc = (gpsDict[kCGImagePropertyGPSAltitude as String] as? NSNumber).map({ " at \($0.format(precision: 0))m" }) ?? ""
add(key: "Location", value: "\(latitude.format()), \(longitude.format())\(altitudeDesc)")
}
add(key: "Area", value: gpsDict[kCGImagePropertyGPSAreaInformation as String])
add(key: "Color space", value: properties[kCGImagePropertyColorModel as String])
add(key: "Color depth", value: (properties[kCGImagePropertyDepth as String] as? NSNumber).map({ "\($0) bits" }))
add(key: "Color profile", value: properties[kCGImagePropertyProfileName as String])
add(key: "Focal length", value: exifDict[kCGImagePropertyExifFocalLength as String])
add(key: "White banance", value: exifDict[kCGImagePropertyExifWhiteBalance as String])
add(key: "F number", value: exifDict[kCGImagePropertyExifFNumber as String])
add(key: "Exposure program", value: exifDict[kCGImagePropertyExifExposureProgram as String])
if let exp = exifDict[kCGImagePropertyExifExposureTime as String] as? NSNumber {
let expfrac = simplify(Int64(exp.doubleValue * 1_163_962_800_000), 1_163_962_800_000)
add(key: "Exposure time", value: "\(expfrac.newTop)/\(expfrac.newBottom)")
}
add(key: "ISO speed", value: (exifDict[kCGImagePropertyExifISOSpeedRatings as String] as? [NSNumber])?.first)
return (dic, keys)
}
/// Properties generator closure for audio and music files.
static var audioProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value {
keys.append(key)
dic[key] = value
}
}
func makeKeyDescription(_ key: String?) -> String? {
guard let key = key else {
return nil
}
guard let regex = try? NSRegularExpression(pattern: "([a-z])([A-Z])" , options: []) else {
return nil
}
let newKey = regex.stringByReplacingMatches(in: key, options: [], range: NSRange(location: 0, length: (key as NSString).length) , withTemplate: "$1 $2")
return newKey.capitalized
}
func parseLocationData(_ value: String) -> (latitude: Double, longitude: Double, height: Double?)? {
let scanner = Scanner.init(string: value)
var latitude: Double = 0.0, longitude: Double = 0.0, height: Double = 0
if scanner.scanDouble(&latitude), scanner.scanDouble(&longitude) {
scanner.scanDouble(&height)
return (latitude, longitude, height)
} else {
return nil
}
}
guard fileURL.fileExists else {
return (dic, keys)
}
let playerItem = AVPlayerItem(url: fileURL)
let metadataList = playerItem.asset.commonMetadata
for item in metadataList {
#if swift(>=4.0)
let commonKey = item.commonKey?.rawValue
#else
let commonKey = item.commonKey
#endif
if let key = makeKeyDescription(commonKey) {
if commonKey == "location", let value = item.stringValue, let loc = parseLocationData(value) {
keys.append(key)
let heightStr: String = (loc.height as NSNumber?).map({ ", \($0.format(precision: 0))m" }) ?? ""
dic[key] = "\((loc.latitude as NSNumber).format())°, \((loc.longitude as NSNumber).format())°\(heightStr)"
} else if let value = item.dateValue {
keys.append(key)
dic[key] = value
} else if let value = item.numberValue {
keys.append(key)
dic[key] = value
} else if let value = item.stringValue {
keys.append(key)
dic[key] = value
}
}
}
if let ap = try? AVAudioPlayer(contentsOf: fileURL) {
add(key: "Duration", value: ap.duration.formatshort)
add(key: "Bitrate", value: ap.settings[AVSampleRateKey] as? Int)
}
return (dic, keys)
}
/// Properties generator closure for video files.
static public var videoProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value {
keys.append(key)
dic[key] = value
}
}
if let audioprops = LocalFileInformationGenerator.audioProperties?(fileURL) {
dic = audioprops.prop
keys = audioprops.keys
dic.removeValue(forKey: "Duration")
if let index = keys.firstIndex(of: "Duration") {
keys.remove(at: index)
}
}
let asset = AVURLAsset(url: fileURL, options: nil)
#if swift(>=4.0)
let videoTracks = asset.tracks(withMediaType: AVMediaType.video)
#else
let videoTracks = asset.tracks(withMediaType: AVMediaTypeVideo)
#endif
if let videoTrack = videoTracks.first {
var bitrate: Float = 0
let width = Int(videoTrack.naturalSize.width)
let height = Int(videoTrack.naturalSize.height)
add(key: "Dimensions", value: "\(width)x\(height)")
var duration: Int64 = 0
for track in videoTracks {
duration += track.timeRange.duration.timescale > 0 ? track.timeRange.duration.value / Int64(track.timeRange.duration.timescale) : 0
bitrate += track.estimatedDataRate
}
add(key: "Duration", value: TimeInterval(duration).formatshort)
add(key: "Video Bitrate", value: "\(Int(ceil(bitrate / 1000))) kbps")
}
#if swift(>=4.0)
let audioTracks = asset.tracks(withMediaType: AVMediaType.audio)
#else
let audioTracks = asset.tracks(withMediaType: AVMediaTypeAudio)
#endif
// dic["Audio channels"] = audioTracks.count
var bitrate: Float = 0
for track in audioTracks {
bitrate += track.estimatedDataRate
}
add(key: "Audio Bitrate", value: "\(Int(ceil(bitrate / 1000))) kbps")
return (dic, keys)
}
/// Properties generator closure for protable documents files.
static public var pdfProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = { fileURL in
var dic = [String: Any]()
var keys = [String]()
func add(key: String, value: Any?) {
if let value = value, !((value as? String)?.isEmpty ?? false) {
keys.append(key)
dic[key] = value
}
}
func getKey(_ key: String, from dict: CGPDFDictionaryRef) -> String? {
var cfStrValue: CGPDFStringRef?
if (CGPDFDictionaryGetString(dict, key, &cfStrValue)), let value = cfStrValue.flatMap({ CGPDFStringCopyTextString($0) }) {
return value as String
}
var cfArrayValue: CGPDFArrayRef?
if (CGPDFDictionaryGetArray(dict, key, &cfArrayValue)), let cfArray = cfArrayValue {
var array = [String]()
for i in 0..<CGPDFArrayGetCount(cfArray) {
var cfItemValue: CGPDFStringRef?
if CGPDFArrayGetString(cfArray, i, &cfItemValue), let item = cfItemValue.flatMap({ CGPDFStringCopyTextString($0) }) {
array.append(item as String)
}
}
return array.joined(separator: ", ")
}
return nil
}
func convertDate(_ date: String?) -> Date? {
guard let date = date else { return nil }
let dateStr = date.replacingOccurrences(of: "'", with: "").replacingOccurrences(of: "D:", with: "", options: .anchored)
let dateFormatter = DateFormatter()
let formats: [String] = ["yyyyMMddHHmmssTZ", "yyyyMMddHHmmssZZZZZ", "yyyyMMddHHmmssZ", "yyyyMMddHHmmss"]
for format in formats {
dateFormatter.dateFormat = format
if let result = dateFormatter.date(from: dateStr) {
return result
}
}
return nil
}
guard let provider = CGDataProvider(url: fileURL as CFURL), let reference = CGPDFDocument(provider), let dict = reference.info else {
return (dic, keys)
}
add(key: "Title", value: getKey("Title", from: dict))
add(key: "Author", value: getKey("Author", from: dict))
add(key: "Subject", value: getKey("Subject", from: dict))
add(key: "Producer", value: getKey("Producer", from: dict))
add(key: "Keywords", value: getKey("Keywords", from: dict))
var majorVersion: Int32 = 0
var minorVersion: Int32 = 0
reference.getVersion(majorVersion: &majorVersion, minorVersion: &minorVersion)
if majorVersion > 0 {
add(key: "Version", value: String(majorVersion) + "." + String(minorVersion))
}
add(key: "Pages", value: reference.numberOfPages)
if reference.numberOfPages > 0, let pageRef = reference.page(at: 1) {
let size = pageRef.getBoxRect(CGPDFBox.mediaBox).size
add(key: "Resolution", value: "\(Int(size.width))x\(Int(size.height))")
}
add(key: "Content creator", value: getKey("Creator", from: dict))
add(key: "Creation date", value: convertDate(getKey("CreationDate", from: dict)))
add(key: "Modified date", value: convertDate(getKey("ModDate", from: dict)))
add(key: "Security", value: reference.isEncrypted ? (reference.isUnlocked ? "Present" : "Password Protected") : "None")
add(key: "Allows printing", value: reference.allowsPrinting)
add(key: "Allows copying", value: reference.allowsCopying)
return (dic, keys)
}
/// Properties generator closure for video files.
/// - Note: No default implementation is avaiable
static public var archiveProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = nil
/// Properties generator closure for office doument files.
/// - Note: No default implementation is avaiable
static public var officeProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = nil
/// Properties generator closure for custom type of files.
/// - Note: No default implementation is avaiable
static public var customProperties: ((_ fileURL: URL) -> (prop: [String: Any], keys: [String]))? = nil
}
#endif
| 49.166667 | 278 | 0.609707 |
d9fc84202c8b98af8ced4f5aa6e0507148afa572 | 1,697 | //
// CollectionsTests.swift
// RecipeAppTests
//
// Created by Emre on 30.01.2022.
//
import XCTest
import RxSwift
import RxCocoa
@testable import RecipeApp
class CollectionsTests: XCTestCase {
private var localCollectionsRepository: LocalCollectionsRepository!
private var collectionsViewModel: CollectionsViewModel!
private var disposeBag: DisposeBag!
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
try super.setUpWithError()
localCollectionsRepository = LocalCollectionsRepository()
collectionsViewModel = CollectionsViewModel(collectionsProtocol: localCollectionsRepository)
disposeBag = DisposeBag()
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
localCollectionsRepository = nil
collectionsViewModel = nil
disposeBag = nil
try super.tearDownWithError()
}
func testFirstCollectionDecoding() throws {
let expectation = expectation(description: "Service Call")
defer {
collectionsViewModel.requestData()
wait(for: [expectation], timeout: 1)
}
collectionsViewModel
.collections
.observe(on: MainScheduler.instance)
.subscribe(onNext: { collections in
let firstCollection = collections.first
XCTAssertEqual(firstCollection?.title, "Taste of Japan 🇯🇵")
expectation.fulfill()
})
.disposed(by: disposeBag)
}
}
| 31.425926 | 111 | 0.672363 |
9066882f6d0e55520671c932bc2d036976e055e6 | 4,546 | import Foundation
import Postbox
import SwiftSignalKit
import SyncCore
import TelegramApi
import MtProtoKit
public enum CreateChannelError {
case generic
case restricted
case tooMuchJoined
case tooMuchLocationBasedGroups
case serverProvided(String)
}
private func createChannel(account: Account, title: String, description: String?, isSupergroup:Bool, location: (latitude: Double, longitude: Double, address: String)? = nil, isForHistoryImport: Bool = false) -> Signal<PeerId, CreateChannelError> {
return account.postbox.transaction { transaction -> Signal<PeerId, CreateChannelError> in
var flags: Int32 = 0
if isSupergroup {
flags |= (1 << 1)
} else {
flags |= (1 << 0)
}
if isForHistoryImport {
flags |= (1 << 3)
}
var geoPoint: Api.InputGeoPoint?
var address: String?
if let location = location {
flags |= (1 << 2)
geoPoint = .inputGeoPoint(flags: 0, lat: location.latitude, long: location.longitude, accuracyRadius: nil)
address = location.address
}
transaction.clearItemCacheCollection(collectionId: Namespaces.CachedItemCollection.cachedGroupCallDisplayAsPeers)
return account.network.request(Api.functions.channels.createChannel(flags: flags, title: title, about: description ?? "", geoPoint: geoPoint, address: address), automaticFloodWait: false)
|> mapError { error -> CreateChannelError in
if error.errorCode == 406 {
return .serverProvided(error.errorDescription)
} else if error.errorDescription == "CHANNELS_TOO_MUCH" {
return .tooMuchJoined
} else if error.errorDescription == "CHANNELS_ADMIN_LOCATED_TOO_MUCH" {
return .tooMuchLocationBasedGroups
} else if error.errorDescription == "USER_RESTRICTED" {
return .restricted
} else {
return .generic
}
}
|> mapToSignal { updates -> Signal<PeerId, CreateChannelError> in
account.stateManager.addUpdates(updates)
if let message = updates.messages.first, let peerId = apiMessagePeerId(message) {
return account.postbox.multiplePeersView([peerId])
|> filter { view in
return view.peers[peerId] != nil
}
|> take(1)
|> map { _ in
return peerId
}
|> castError(CreateChannelError.self)
|> timeout(5.0, queue: Queue.concurrentDefaultQueue(), alternate: .fail(.generic))
} else {
return .fail(.generic)
}
}
}
|> castError(CreateChannelError.self)
|> switchToLatest
}
public func createChannel(account: Account, title: String, description: String?) -> Signal<PeerId, CreateChannelError> {
return createChannel(account: account, title: title, description: description, isSupergroup: false)
}
public func createSupergroup(account: Account, title: String, description: String?, location: (latitude: Double, longitude: Double, address: String)? = nil, isForHistoryImport: Bool = false) -> Signal<PeerId, CreateChannelError> {
return createChannel(account: account, title: title, description: description, isSupergroup: true, location: location, isForHistoryImport: isForHistoryImport)
}
public enum DeleteChannelError {
case generic
}
public func deleteChannel(account: Account, peerId: PeerId) -> Signal<Void, DeleteChannelError> {
return account.postbox.transaction { transaction -> Api.InputChannel? in
return transaction.getPeer(peerId).flatMap(apiInputChannel)
}
|> mapError { _ -> DeleteChannelError in }
|> mapToSignal { inputChannel -> Signal<Void, DeleteChannelError> in
if let inputChannel = inputChannel {
return account.network.request(Api.functions.channels.deleteChannel(channel: inputChannel))
|> map(Optional.init)
|> `catch` { _ -> Signal<Api.Updates?, DeleteChannelError> in
return .fail(.generic)
}
|> mapToSignal { updates -> Signal<Void, DeleteChannelError> in
if let updates = updates {
account.stateManager.addUpdates(updates)
}
return .complete()
}
} else {
return .fail(.generic)
}
}
}
| 41.706422 | 247 | 0.624505 |
9c092b71aa33647310d015ec4cd2cb8fc558cbab | 5,314 | //
// Wallet.swift
// WalletKit
//
// Created by yuzushioh on 2018/01/01.
// Copyright © 2018 yuzushioh. All rights reserved.
//
import Foundation
@objc public final class Wallet :NSObject {
public let privateKey: PrivateKey
public let coin: Coin
public init(seed: Data, coin: Coin) {
self.coin = coin
privateKey = PrivateKey(seed: seed, coin: coin)
}
//MARK: - Public
public func generateAddress(at index: UInt32) -> String {
let derivedKey = bip44PrivateKey.derived(at: .notHardened(index))
return derivedKey.publicKey.address
}
public func generateAccount(at derivationPath: [DerivationNode]) -> Account {
let privateKey = generatePrivateKey(at: derivationPath)
return Account(privateKey: privateKey)
}
public func generateAccount(at index: UInt32 = 0) -> Account {
let address = bip44PrivateKey.derived(at: .notHardened(index))
return Account(privateKey: address)
}
public func generateAccounts(count: UInt32) -> [Account] {
var accounts:[Account] = []
for index in 0..<count {
accounts.append(generateAccount(at: index))
}
return accounts
}
public func sign(rawTransaction: EthereumRawTransaction) throws -> String {
let signer = EIP155Signer(chainId: 1)
let rawData = try signer.sign(rawTransaction, privateKey: privateKey)
let hash = rawData.toHexString().addHexPrefix()
return hash
}
@objc class public func generateBitcoinAccount() -> [String:String] {
let mnemonic = Mnemonic.create()
let seed = Mnemonic.createSeed(mnemonic: mnemonic)
let wallet = Wallet(seed: seed, coin: .bitcoin)
let account = wallet.generateAccount()
return ["mnemonicKey":mnemonic,"addressKey":account.address,"privateKey":account.rawPrivateKey]
}
@objc class public func generateETHAccount() -> [String:String] {
let mnemonic = Mnemonic.create()
let seed = Mnemonic.createSeed(mnemonic: mnemonic)
let wallet = Wallet(seed: seed, coin: .ethereum)
let account = wallet.generateAccount()
return ["mnemonicKey":mnemonic,"addressKey":account.address,"privateKey":account.rawPrivateKey]
}
@objc class public func importETHAccountWithPriateKey(at privateKeyStr:String) -> [String:String] {
if privateKeyStr.count < 40 {
return ["error":"私钥长度不够"];
}
let privateKey = PrivateKey(pk: privateKeyStr, coin: .ethereum)
return ["mnemonicKey":"","addressKey":privateKey!.publicKey.address,"privateKey":privateKeyStr]
}
@objc class public func importBitcoinAccountWithPriateKey(at privateKeyStr:String) -> [String:String] {
if privateKeyStr.count < 40 {
return ["error":"私钥长度不够"];
}
let privateKey = PrivateKey(pk: privateKeyStr, coin: .bitcoin)
return ["mnemonicKey":"","addressKey":privateKey!.publicKey.address,"privateKey":privateKeyStr]
}
@objc class public func importETHAccountWithMnemonic(at mnemonic:String) -> [String:String] {
let mnemonicCount = mnemonic.components(separatedBy: " ")
if mnemonicCount.count < 12 {
return ["error":"助记词个数不够"];
}
for (index) in mnemonicCount.enumerated() {
let word:String = index.element
if word.count == 0 {
return ["error":"助记词长度不对"];
}
}
let seed = Mnemonic.createSeed(mnemonic: mnemonic)
let wallet = Wallet(seed: seed, coin: .ethereum)
let account = wallet.generateAccount()
return ["mnemonicKey":mnemonic,"addressKey":account.address,"privateKey":account.rawPrivateKey]
}
@objc class public func importBitcoinAccountWithMnemonic(at mnemonic:String) -> [String:String] {
let mnemonicCount = mnemonic.components(separatedBy: " ")
if mnemonicCount.count < 12 {
return ["error":"助记词个数不够"];
}
for (index) in mnemonicCount.enumerated() {
let word:String = index.element
if word.count == 0 {
return ["error":"助记词长度不对"];
}
}
let seed = Mnemonic.createSeed(mnemonic: mnemonic)
let wallet = Wallet(seed: seed, coin: .bitcoin)
let account = wallet.generateAccount()
return ["mnemonicKey":mnemonic,"addressKey":account.address,"privateKey":account.rawPrivateKey]
}
//MARK: - Private
//https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
private var bip44PrivateKey:PrivateKey {
let bip44Purpose:UInt32 = 44
let purpose = privateKey.derived(at: .hardened(bip44Purpose))
let coinType = purpose.derived(at: .hardened(coin.coinType))
let account = coinType.derived(at: .hardened(0))
let receive = account.derived(at: .notHardened(0))
return receive
}
private func generatePrivateKey(at nodes:[DerivationNode]) -> PrivateKey {
return privateKey(at: nodes)
}
private func privateKey(at nodes: [DerivationNode]) -> PrivateKey {
var key: PrivateKey = privateKey
for node in nodes {
key = key.derived(at:node)
}
return key
}
}
| 38.230216 | 107 | 0.636432 |
7962d6b84c85866e897416992bab0545fd0b4d4a | 1,087 | //
// GameTableViewCell.swift
// MyGames
//
// Created by Douglas Frari on 4/27/21.
//
import UIKit
// GAME no singular representa nossa CELULA
class GameTableViewCell: UITableViewCell {
@IBOutlet weak var ivCover: UIImageView!
@IBOutlet weak var lbTitle: UILabel!
@IBOutlet weak var lbConsole: UILabel!
@IBOutlet weak var ivConsoleCover: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func prepare(with game: Game) {
lbTitle.text = game.title ?? ""
lbConsole.text = game.console?.name ?? ""
if let image = game.cover as? UIImage {
ivCover.image = image
} else {
ivCover.image = UIImage(named: "noCover")
}
self.ivConsoleCover.image = (game.console?.cover as? UIImage) ?? #imageLiteral(resourceName: "noCover")
}
}
| 25.880952 | 111 | 0.630175 |
14552fc62b288690b931f2825efeb4e5440107fc | 5,313 | //
// ArrayLibRosaExtensions.swift
// RosaKit
//
// Created by Hrebeniuk Dmytro on 23.12.2019.
// Copyright © 2019 Dmytro Hrebeniuk. All rights reserved.
//
import Foundation
public extension Array where Iterator.Element: FloatingPoint {
static func createFFTFrequencies(sampleRate: Int, FTTCount: Int) -> [Element] {
return [Element].linespace(start: 0, stop: Element(sampleRate)/Element(2), num: Element(1 + FTTCount/2))
}
static func createMELFrequencies(MELCount: Int, fmin: Element, fmax: Element) -> [Element] {
let minMEL = Element.MEL(fromHZ: fmin)
let maxMEL = Element.MEL(fromHZ: fmax)
let mels = [Element].linespace(start: minMEL, stop: maxMEL, num: Element(MELCount))
return mels.map { Element.HZ(fromMEL: $0) }
}
static func createMelFilter(sampleRate: Int, FTTCount: Int, melsCount: Int = 128) -> [[Element]] {
let fmin = Element(0)
let fmax = Element(sampleRate) / 2
var weights = [Element].empty(width: melsCount, height: 1 + FTTCount/2, defaultValue: Element(0))
let FFTFreqs = [Element].createFFTFrequencies(sampleRate: sampleRate, FTTCount: FTTCount)
let MELFreqs = [Element].createMELFrequencies(MELCount: melsCount + 2, fmin: fmin, fmax: fmax)
let diff = MELFreqs.diff
let ramps = MELFreqs.outerSubstract(array: FFTFreqs)
for index in 0..<melsCount {
let lower = ramps[index].map { -$0 / diff[index] }
let upper = ramps[index+2].map { $0 / diff[index+1] }
weights[index] = [Element].minimumFlatVector(matrix1: lower, matrix2: upper).map { Swift.max(Element(0), $0) }
}
for index in 0..<melsCount {
let enorm = Element(2) / (MELFreqs[index+2] - MELFreqs[index])
weights[index] = weights[index].map { $0*enorm }
}
return weights
}
func powerToDB(ref: Element = Element(1), amin: Element = Element(1)/Element(10000000000), topDB: Element = Element(80)) -> [Element] {
let ten = Element(10)
let logSpec = map { ten * (Swift.max(amin, $0)).logarithm10() - ten * (Swift.max(amin, abs(ref))).logarithm10() }
let maximum = (logSpec.max() ?? Element(0))
return logSpec.map { Swift.max($0, maximum - topDB) }
}
func normalizeAudioPower() -> [Element] {
var dbValues = powerToDB()
let minimum = (dbValues.min() ?? Element(0))
dbValues = dbValues.map { $0 - minimum}
let maximun = (dbValues.map { abs($0) }.max() ?? Element(0))
dbValues = dbValues.map { $0/(maximun + Element(1)) }
return dbValues
}
}
public extension Array where Element == Double {
func stft(nFFT: Int = 256, hopLength: Int = 1024) -> [[Double]] {
let FFTWindow = [Double].getHannWindow(frameLength: Double(nFFT)).map { [$0] }
let centered = self.reflectPad(fftSize: nFFT/2)
let yFrames = centered.frame(frameLength: nFFT, hopLength: hopLength)
let matrix = FFTWindow.multiplyVector(matrix: yFrames)
let rfftMatrix = matrix.rfft
let itemLength = matrix.count/2 + 1
let result = rfftMatrix
return result
}
func melspectrogram(nFFT: Int = 2048, hopLength: Int = 512, sampleRate: Int = 22050, melsCount: Int = 128) -> [[Double]] {
let spectrogram = self.stft(nFFT: nFFT, hopLength: hopLength).map { $0.map { pow($0, 2.0) } }
let melBasis = [Double].createMelFilter(sampleRate: sampleRate, FTTCount: nFFT, melsCount: melsCount)
return melBasis.dot(matrix: spectrogram)
}
}
extension Array where Element == [Double] {
var rfft: [[Double]] {
let transposed = self.transposed
let cols = transposed.count
let rows = transposed.first?.count ?? 1
let rfftRows = rows/2 + 1
let flatMatrix = transposed.flatMap { $0 }
let rfftCount = rfftRows*cols
var resultComplexMatrix = [Double](repeating: 0.0, count: (rfftCount + cols + 1)*2)
resultComplexMatrix.withUnsafeMutableBytes { destinationData -> Void in
let destinationDoubleData = destinationData.bindMemory(to: Double.self).baseAddress
flatMatrix.withUnsafeBytes { (flatData) -> Void in
let sourceDoubleData = flatData.bindMemory(to: Double.self).baseAddress
execute_real_forward(sourceDoubleData, destinationDoubleData, Int32(cols), Int32(rows), 1)
}
}
var realMatrix = [Double](repeating: 0.0, count: rfftCount)
for index in 0..<rfftCount {
let real = resultComplexMatrix[index*2]
let imagine = resultComplexMatrix[index*2+1]
realMatrix[index] = sqrt(pow(real, 2) + pow(imagine, 2))
}
let result = realMatrix.chunked(into: rfftRows).transposed
return result
}
public func normalizeAudioPowerArray() -> [[Double]] {
let chunkSize = self.first?.count ?? 0
let dbValues = self.flatMap { $0 }.normalizeAudioPower().chunked(into: chunkSize)
return dbValues
}
}
| 37.153846 | 139 | 0.600414 |
38d50f6f07ea4094b00938977ec92fed0dff77db | 845 | //
// KissXMLSwiftTests.swift
// KissXMLSwiftTests
//
// Created by Chris Ballinger on 1/26/16.
//
//
import XCTest
import KissXML
class KissXMLSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testXMLNode() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let node = DDXMLNode()
let apple = NSXMLNode()
XCTAssertNotNil(node)
XCTAssertNotNil(apple)
}
}
| 24.852941 | 111 | 0.640237 |
ef45f3269bd42ef0a3de75ac1303787be86aae5e | 984 | import UIKit
public class STSectionBuilder {
public var height: CGFloat = 0
public var title: String?
public var viewBuilder: STSectionViewBuilder?
public var builders = [STBuilderProtocol]()
public var sectionId: String?
public func isTable() -> Bool {
if builders.isEmpty {
return false
}
if let builder = builders.first {
if builder.isTable() {
return true
}
}
return false
}
public func getTable() -> STBuilderProtocol? {
if isTable() {
return builders[0]
}
return nil
}
public func getNumberOfRows() -> Int {
var count = 0
for builder in builders {
count += builder.getCount()
}
return count
}
public func hasBuilders() -> Bool {
return builders.isEmpty == false
}
}
| 20.5 | 50 | 0.505081 |
1d98709e13d7610e74b4aaad11575461a8769496 | 774 | //
// FlightResponse.swift
// kiwiTest
//
// Created by Pavle Mijatovic on 17.4.21..
//
import Foundation
struct FlightResponse: Decodable {
struct FlightRouteResponse: Decodable {
let cityFrom: String
let cityCodeFrom: String
let cityTo: String
let cityCodeTo: String
}
let cityFrom: String
let cityCodeFrom: String
let cityTo: String
let cityCodeTo: String
let deepLink: String
let mapIdto: String
let dTimeUTC: Double
let price: Int
let route: [FlightRouteResponse]
let distance: Double
enum CodingKeys: String, CodingKey {
case cityFrom, cityCodeFrom, cityTo, cityCodeTo, mapIdto, dTimeUTC, price, route, distance
case deepLink = "deep_link"
}
}
| 22.114286 | 98 | 0.656331 |
4b29d61ad58a1dfc1fde4cfda0eb0abe8d737b83 | 1,787 | //
// MainViewController.swift
// Bankey
//
// Created by Shaleen on 17/01/22.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupTabBar()
}
private func setupViews() {
let summaryVC = AccountSummaryViewController()
let moneyVC = MoveMoneyViewController()
let moreVC = MoreViewController()
summaryVC.setTabBarImage(imageName: "list.dash.header.rectangle", title: "Summary")
moneyVC.setTabBarImage(imageName: "arrow.left.arrow.right", title: "Move Money")
moreVC.setTabBarImage(imageName: "ellipsis.circle", title: "More")
let summaryNC = UINavigationController(rootViewController: summaryVC)
let moneyNC = UINavigationController(rootViewController: moneyVC)
let moreNC = UINavigationController(rootViewController: moreVC)
summaryNC.navigationBar.barTintColor = appColor
hideNavigationBarLine(summaryNC.navigationBar)
let tabBarList = [summaryNC, moneyNC, moreNC]
viewControllers = tabBarList
}
private func hideNavigationBarLine(_ navigationBar: UINavigationBar) {
let img = UIImage()
navigationBar.shadowImage = img
navigationBar.setBackgroundImage(img, for: .default)
navigationBar.isTranslucent = false
}
private func setupTabBar() {
tabBar.tintColor = appColor
tabBar.isTranslucent = false
}
}
class MoveMoneyViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .systemOrange
}
}
class MoreViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .systemPurple
}
}
| 28.365079 | 91 | 0.683828 |
e538bd659907db4dc9e5787668a4b9384d8f2557 | 27,805 | // Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public class GridMaze: GameProtocol {
// Maximum set of possible actions in any grid position in the maze
public enum Action: Int, CustomStringConvertible, CaseIterable, Hashable {
case LEFT
case UP
case DOWN
case RIGHT
public var description: String {
switch self {
case .LEFT: return "<"
case .UP: return "A"
case .DOWN: return "V"
case .RIGHT: return ">"
}
}
}
public struct BoardState: StateProtocol {
public let game: GridMaze
public var history = [GridMaze.Action]()
public var currentPlayer: Player { return isTerminal ? .terminal : .player(0) }
public var isTerminal: Bool { return gridCell.isTerminal }
public var isGoal: Bool { return gridCell.isGoal }
public var gridCell: GridCell // Cell in the maze where we are currently positioned
var utility = 0.0
}
// *** Section 1: Required by GameProtocol
// Many of the things could instead of fatalError return nil if that was supported by GameProtocol
// Crashing or -Double.infinity are only current alteratives
public var minUtility: Double { fatalError("Cannot be calcuated for GridMaze") }
/// TODO: Ok? It is not known
public var maxUtility: Double { fatalError("Cannot be calcuated for GridMaze") }
/// TODO: Ok? It is not known
public var utilitySum: Double? { return nil } // Only known for very specific (and trivial) mazes
public var playerCount: Int { return 1 } // Only one player navigating (and terminal player does not count)
public var maxGameLength: Int { fatalError("Cannot be calcuated for GridMaze") }
/// TODO: Ok? It is not known
public static var info: GameInfo {
fatalError("Cannot be (easily) caluated for GridMaze")
// TODO
// return GameInfo(
// shortName: "grid_maze",
// longName: "Grid Maze",
// dynamics: .simultaneous, /// TODO: "Every player acts at each stage." Equivalent to .sequential as there is only one player
// chanceMode: TODO, /// TODO: Can change dynamically (even after init) with JumpSpecifications != 1
// information: .perfect, /// TODO: Depends on API user probes environment
// utility: .generalSum,
// rewardModel: .rewards, /// TODO: Can change dynamically (even after init)
// maxPlayers: 1,
// minPlayers: 1,
// providesInformationStateString: true,
// providesInformationStateTensor: true
// )
}
public var initialState: BoardState {
let slist = maze.flatMap({ $0 }).filter({ $0.isInitial })
if slist.count == 1 {
return BoardState(gridCell: slist[0])
} else {
fatalError(
"GridMaze misconfigured: One (and only one) initial state is required and supported")
}
}
public var allActions: [Action] { return GridMaze.Action.allCases }
// TODO
// Spiel docs refer to ImperfectInformationState.informationStateTensor`
// cannot find ImperfectInformationState so
// "see the documentation of that function for details of the data layout." not possible
// Full inforation state is position (of robot) in maze, either [1] if we
// flatMap maze and use position index, alt [1, 1] if we use (row,col)?
// What should we return, TicTacToe returns [3*boardSize*boardSize]
public var informationStateTensorShape: [Int] { [1] }
// *** Section 2: Native things for GridMaze
public var maze: [[GridCell]] = [[GridCell]]()
public var rowCount: Int
public var columnCount: Int
//----
public init(
rowCount: Int,
columnCount: Int,
borderCell: GridCell = GridCell.wall,
innerCell: GridCell = GridCell.space(reward: -1.0)
) {
precondition(rowCount > 0 && columnCount > 0, "Row and column count must be larger than 0")
self.rowCount = rowCount
self.columnCount = columnCount
// Allocate and assign innerCell entries for each cell in grid
// TODO: Can we use init(repeating: ..., count: ...) with [[GridCell]] in an elegant way?
maze.reserveCapacity(rowCount)
for ridx in 0..<rowCount {
maze.append([GridCell]())
for cidx in 0..<columnCount {
maze[ridx].append(innerCell)
self[ridx, cidx] = innerCell // Sets state in cell element
}
}
for i in 0..<rowCount {
self[i, 0] = borderCell
self[i, columnCount - 1] = borderCell
}
for i in 0..<columnCount {
self[0, i] = borderCell
self[rowCount - 1, i] = borderCell
}
}
//---
public subscript(row: Int, col: Int) -> GridCell {
get { return self.maze[row][col] }
set {
self.maze[row][col] = newValue
self.maze[row][col].game = self
self.maze[row][col].row = row
self.maze[row][col].col = col
// TODO: Do full maze validation, e.g. to avoid chained JumpSpecifications or landing at !isVisitable cells
}
}
}
/// Extensions required by Spiel framework
extension GridMaze.BoardState {
init(gridCell: GridCell) {
self.gridCell = gridCell
self.game = gridCell.game!
}
public var legalActionsMask: [Bool] {
if gridCell.isTerminal { // No actions available from terminal states
return [Bool]()
}
var mask: [Bool] = Array(repeating: false, count: GridMaze.Action.allCases.count)
mask = zip(mask, GridMaze.Action.allCases).map {
gridCell.getTargetWOJumpSpecification(takingAction: $0.1).canAttemptToBeEntered
}
return mask
}
public func utility(for player: Player) -> Double { return utility }
public mutating func apply(_ action: GridMaze.Action) {
let gridCell2 = gridCell.getTargetWJumpSpecification(takingAction: action)
gridCell = gridCell2
precondition(
gridCell.canAttemptToBeEntered && gridCell.canBeEntered,
"Action: \(action) is illegal from position: [\(gridCell.row!),\(gridCell.col!)]")
utility += gridCell.rewardOnEnter
history.append(action)
}
// TODO: How do we work with this and JumpSpecification? Is that what we're supposed to do?
public var chanceOutcomes: [GridMaze.Action: Double] {
/// From Spiel:
/// Note: what is returned here depending on the game's chanceMode (in
/// its GameInfo):
/// - Option 1. `.explicitStochastic`. All chance node outcomes are returned along
/// with their respective probabilities. Then State.apply(...) is deterministic.
/// - Option 2. `.sampledStochastic`. Return a dummy single action here with
/// probability 1, and then `State.apply(_:)` does the real sampling. In this
/// case, the game has to maintain its own RNG.
fatalError("Method not implemented")
}
// TODO: Correct understanding?
public func informationStateTensor(for player: Player) -> [Double] {
return [Double(game.columnCount * gridCell.row! + gridCell.col!)] // Each position is a unique info state
}
// TODO: Correct understanding?
public func informationStateString(for player: Player) -> String {
return GridMaze.BoardState.informationStateImpl(gridCell: gridCell)
}
fileprivate static func informationStateImpl(gridCell: GridCell) -> String {
return String(format: "%d:%d", gridCell.row!, gridCell.col!) // Do this so developer gets a readable position
}
}
/// ********************************************************************
//----
// JumpSpecification allows stochastic behavior configuration for grid cells
public typealias JumpSpecificationProbability = (js: JumpSpecification, prob: Double)
public enum JumpSpecification: Equatable, CustomStringConvertible {
case Welcome // I am happy to welcome you to my space
case BounceBack // You cannot enter my space, bounce back (e.g. Wall)
case Relative(Int, Int) // Teleport(row,col) (extend to also support a function argument)
case Absolute(Int, Int) // Teleport(row,col) (extend to also support a function argument)
public var description: String {
switch self {
case .Welcome: return "Welcome"
case .BounceBack: return "BounceBack"
case let .Relative(row, col): return String(format: "Relative (%d,%d)", row, col)
case let .Absolute(row, col): return String(format: "Absolute (%d,%d)", row, col)
}
}
}
//----
// Defines behavior for a cell in the GridMaze
public struct GridCell {
var oneWordDescription: String
var game: GridMaze? // Set by GridMaze.subscript
var row, col: Int? // Position of GridCell, set by GridMaze.subscript (optional because not assigned in init)
var rewardOnEnter: Double // If you enter, if went elsewhere due to JumpSpecification then that target cells R is used
// TODO: Need to read these from public scope, can we statically limit write to private scope?
public var canAttemptToBeEntered: Bool // True if it is legal to take an action towards entering this cell
public var canBeEntered: Bool { // False if you can never actually arrive at this cell, i.e. does not have a welcoming JS)
return canAttemptToBeEntered
&& (
entryJumpProbabilities.count == 0
|| entryJumpProbabilities.contains { $0.js == .Welcome && $0.prob > 0 }
)
}
public var isInitial: Bool
public var isTerminal: Bool
public var isGoal: Bool
// Stoachstic behavior for cell
// When attempting to enter cell, this specification can specify alternative behavior than just entering cell
// (i.e compare to the the wind in Frozen Lake environment)
public var entryJumpProbabilities = [JumpSpecificationProbability]() {
willSet {
let probSum = newValue.reduce(0) { $0 + $1.prob }
guard newValue.count == 0 || probSum == 1.0
else { // All probabilities must sum to 1.0
fatalError("Jump probabilities don't sum to 1.0")
}
}
}
public var hasProbabilisticTarget: Bool {
return entryJumpProbabilities.filter { $0.js != .Welcome }.count > 0
}
init(
oneWordDescription: String,
reward: Double,
entryJumpProbabilities: [JumpSpecificationProbability] = [],
isInitial: Bool,
isTerminal: Bool,
isGoal: Bool,
canAttemptToBeEntered: Bool
) {
self.oneWordDescription = oneWordDescription
self.rewardOnEnter = reward
self.isInitial = isInitial
self.isTerminal = isTerminal
self.isGoal = isGoal
self.canAttemptToBeEntered = canAttemptToBeEntered
self.entryJumpProbabilities = entryJumpProbabilities
}
// Not considering JumpSpecifications, which cell would takaingAction lead to
// (used to find out the JS that might be applied)
func getTargetWOJumpSpecification(takingAction: GridMaze.Action) -> GridCell {
// Find new co-ordinates wrapping if needed
var newRow = row!
var newCol = col!
switch takingAction {
case .LEFT:
newCol -= 1
if col == 0 {
newCol = game!.columnCount - 1
}
case .UP:
newRow -= 1
if row == 0 {
newRow = game!.rowCount - 1
}
case .DOWN:
newRow += 1
if row == game!.rowCount - 1 {
newRow = 0
}
case .RIGHT:
newCol += 1
if col == game!.columnCount - 1 {
newCol = 0
}
}
// Returned state may !isVisitable, needs to checked by caller
return game![newRow, newCol]
}
// Find target cell takaingAction, applying any stochastic JumpSpecification behavior
func getTargetWJumpSpecification(takingAction: GridMaze.Action) -> GridCell {
let targetCell = getTargetWOJumpSpecification(takingAction: takingAction)
if !targetCell.hasProbabilisticTarget {
return targetCell
}
let probabilities = targetCell.entryJumpProbabilities.map { $0.prob }
let probabilityIndex = randomIndexFromProbabilities(probabilityList: probabilities)
let targetCell2 = calculateTargeCellJumpSpecification(
originCell: self,
targetCell: targetCell,
js: targetCell.entryJumpProbabilities[probabilityIndex].js)
return targetCell2
}
// If js is stocahstically selected, return target cell js could end up in
func calculateTargeCellJumpSpecification(
originCell: GridCell, // Neeeded for bounce-back
targetCell: GridCell,
js: JumpSpecification
) -> GridCell {
var rv = targetCell
switch js {
case .Welcome:
rv = targetCell
case .BounceBack:
rv = originCell
case let .Absolute(row, col):
rv = game![row, col]
case let .Relative(row, col):
rv = game![targetCell.row! + row, targetCell.col! + col]
}
// Only support 1-step jumps. I.e, cannot jump to a state having JSs specifying additional jumps
precondition(
js == .Welcome || !rv.hasProbabilisticTarget,
"At cell (\(originCell.row!),\(originCell.col!)). Target cell (\(rv.row!),\(rv.col!)) was not purely welcoming"
)
return rv
}
public typealias ProbRewardCell = (prob: Double, reward: Double, cell: GridCell)
public func probeActionTargets(takingAction: GridMaze.Action) -> [(ProbRewardCell)] {
precondition(
canBeEntered && canAttemptToBeEntered && !isTerminal,
"Cannot probeActionWithProbabilities from this cell (\(row!),\(col!))")
let targetCell = getTargetWOJumpSpecification(takingAction: takingAction)
precondition(
targetCell.canAttemptToBeEntered,
"Target cell from (\(row!),\(col!)) taking action: \(takingAction) is not visitable")
if targetCell.entryJumpProbabilities.count == 0 {
return [(1.0, targetCell.rewardOnEnter, targetCell)]
}
let result: [ProbRewardCell] = targetCell.entryJumpProbabilities.map {
let tc = calculateTargeCellJumpSpecification(
originCell: self,
targetCell: targetCell,
js: $0.js)
return ($0.prob, tc.rewardOnEnter, tc) // TODO: Swift question, is single element () implicitly type convertible to [()]
}
return result
}
}
// ***************************************************************************
// Create factory functions for common Cell Types to use in GridMazes
extension GridCell {
/// Creates a start cell with the given reward.
public static func start(reward: Double = -1) -> GridCell {
return GridCell(
oneWordDescription: "START", reward: reward,
isInitial: true, isTerminal: false, isGoal: false,
canAttemptToBeEntered: true)
}
/// Creates a goal cell with the given reward.
public static func goal(reward: Double) -> GridCell {
return GridCell(
oneWordDescription: "GOAL", reward: reward,
isInitial: false, isTerminal: true, isGoal: true,
canAttemptToBeEntered: true)
}
/// Creates a start cell with the given reward.
public static func space(reward: Double) -> GridCell {
return GridCell(
oneWordDescription: "SPACE", reward: reward,
isInitial: false, isTerminal: false, isGoal: false,
canAttemptToBeEntered: true)
}
/// Creates a hole cell with the given reward.
public static func hole(reward: Double) -> GridCell {
return GridCell(
oneWordDescription: "HOLE", reward: reward,
isInitial: false, isTerminal: true, isGoal: false,
canAttemptToBeEntered: true)
}
/// Creates a wall cell with the given reward.
public static var wall: GridCell {
return GridCell(
oneWordDescription: "WALL", reward: -1.0, // Reward is no-op because !canAttemptToBeEntered
isInitial: false, isTerminal: false, isGoal: false,
canAttemptToBeEntered: false)
}
/// A bounce cell.
public static var bounce: GridCell {
return GridCell(
oneWordDescription: "BOUNCE", reward: -1.0, // Reward is irrelevant, you receive reward of cell you bounce back to
entryJumpProbabilities: [(js: .BounceBack, prob: 1.0)],
isInitial: false, isTerminal: false, isGoal: false,
canAttemptToBeEntered: true)
}
}
// ***************************************************************************
// GridMaze printing functions
extension GridMaze {
public typealias QTableType = [String: [(action: GridMaze.Action, qvalue: Double)]]
public typealias VTableType = [String: Double]
public typealias PTableType = [String: [GridMaze.Action]]
public func printMazeAndTable(
header: String, // header string
vtable: VTableType? = nil,
qtable: QTableType? = nil,
ptable: PTableType? = nil,
printFullFloat: Bool = false
) {
// Print header
if header.count > 0 { print(header) }
// Print transition probabilities (JumpSpecifications) in top section (i.e. not as part of cell in grid)
var transitionProbabilitiesFound = false
for (ri, r) in maze.enumerated() {
for (ci, cell) in r.enumerated() {
let jsps: [JumpSpecificationProbability] = cell.entryJumpProbabilities
if jsps.count > 0 {
if (jsps.count == 1 && jsps[0].js == JumpSpecification.Welcome) {
break
}
if !transitionProbabilitiesFound { // Print header
print(
"\nTransition probabilities (non-stochastic transitions are not printed (i.e as expected based on action)"
)
}
print("[\(ri),\(ci)]: ", terminator: "")
for (i, jsp) in jsps.enumerated() {
if (i > 0) { print(" ", terminator: "") }
print("\(String(format: "Probability: %0.2f", jsp.prob)), Type: \(jsp.js.description)")
transitionProbabilitiesFound = true
}
}
}
}
if transitionProbabilitiesFound {
print()
}
// Get cell definitions strings
let cellStrs = getCellDefinitionStrs(printFullFloat: printFullFloat)
// Get v-, q-, and policy-value strings
let (vtableStrs, qtableStrs, ptableStrs) = getTableAndPolicyStrs(
vtable: vtable,
qtable: qtable,
ptable: ptable,
printFullFloat: printFullFloat)
// Get the maximum column width needed to support maze def, q-/v-/policy-table printing
let colCount = cellStrs[0].count
var colMaxWidth = 2
for i in 0..<colCount {
let maxWidth = getLargestColSize(
col: i, maze: cellStrs, vtable: vtableStrs, qtable: qtableStrs, policy: ptableStrs)
if maxWidth > colMaxWidth {
colMaxWidth = maxWidth
}
}
// Print the columns on first row
print(" ", terminator: "") // Row index pre-space
for i in 0..<colCount {
print(strCenter(str: String(format: "%02d", i), len: colMaxWidth), terminator: "")
print(" ", terminator: "")
}
print()
// Print grid cell rows with maze definition, tables, and policy parts
for (ri, r) in cellStrs.enumerated() {
print(String(format: "%02d ", ri), terminator: "") // row index
// Print cell definition
for c in r {
let ccenter = strCenter(str: c, len: colMaxWidth)
print("\(ccenter) ", terminator: "")
}
print()
// Potentially print vtable
if let vts = vtableStrs?[ri] {
for (ci, c) in vts.enumerated() {
let ccenter = strCenter(str: c, len: colMaxWidth)
if (ci == 0) {
print("VTable ", terminator: "")
}
print("\(ccenter) ", terminator: "")
}
print()
}
// Potentially print qtable
if let qts = qtableStrs?[ri] {
for (ci, c) in qts.enumerated() {
let ccenter1 = strCenter(str: c[0], len: colMaxWidth)
if ci == 0 {
print("QTable ", terminator: "")
}
print("\(ccenter1) ", terminator: "")
}
print()
for (ci, c) in qts.enumerated() {
let ccenter1 = strCenter(str: c[1], len: colMaxWidth)
if ci == 0 {
print(" ", terminator: "")
}
print("\(ccenter1) ", terminator: "")
}
print()
}
// Potentially print policy
if let ps = ptableStrs?[ri] {
for (ci, c) in ps.enumerated() {
let ccenter = strCenter(str: c, len: colMaxWidth)
if (ci == 0) {
print("Policy ", terminator: "")
}
print("\(ccenter) ", terminator: "")
}
print()
}
print()
}
}
func getCellDefinitionStrs(printFullFloat: Bool) -> [[String]] {
var cellDescriptions: [[String]] = []
for row in maze {
var rowStrs = [String]()
var str = ""
for cell in row {
var jsStr = "" // Add a note about the existance of a JS if one exists
if cell.entryJumpProbabilities.count > 1
|| (
cell.entryJumpProbabilities.count == 1 && cell.entryJumpProbabilities[0].js != .Welcome
)
{
jsStr = "(JS)"
}
str = "\(cell.oneWordDescription)\(jsStr)"
if cell.canBeEntered {
str = "\(str):\(double2Str(printFullFloat: printFullFloat, value: cell.rewardOnEnter))"
}
if cell.isTerminal {
str += ":T"
} else if cell.isInitial {
str += ":I"
}
rowStrs.append(str)
}
cellDescriptions.append(rowStrs)
}
return cellDescriptions
}
func getTableAndPolicyStrs(
vtable: VTableType? = nil,
qtable: QTableType? = nil,
ptable: PTableType? = nil,
printFullFloat: Bool
) -> ([[String]]?, [[[String]]]?, [[String]]?) {
var vtableResult: [[String]]? = nil
if vtable != nil {
vtableResult = []
}
var qtableResult: [[[String]]]? = nil
if qtable != nil {
qtableResult = []
}
var ptableResult: [[String]]? = nil
if ptable != nil {
ptableResult = []
}
for (ri, r) in maze.enumerated() {
var vtableStrs = [String]()
var qtableStrs = [[String]]()
var ptableStrs = [String]()
for ci in 0..<r.count {
let informationState = GridMaze.BoardState.informationStateImpl(gridCell: maze[ri][ci])
// QTable
// TODO: This is ugly, what is the beatiful Swift way to write this?
var qs1 = "*"
var qs2 = "*"
if maze[ri][ci].canAttemptToBeEntered && maze[ri][ci].canBeEntered
&& !maze[ri][ci].isTerminal
{
qs1 = ""
qs2 = ""
var q = [(action: GridMaze.Action, qvalue: Double)]()
if let qtmp = qtable?[informationState] {
q = qtmp
} else {
let gs = BoardState(gridCell: maze[ri][ci])
let qvaluePart = 1.0 / Double(gs.legalActions.count)
q = gs.legalActions.map { ($0, qvaluePart) }
}
_ = q.map {
if $0 == .UP || $0 == .DOWN {
if qs1.count > 0 { qs1 += " " }
qs1 += "\($0.description):\(double2Str(printFullFloat: printFullFloat, value: $1))"
} else {
if qs2.count > 0 { qs2 += " " }
qs2 += "\($0.description):\(double2Str(printFullFloat: printFullFloat, value: $1))"
}
}
}
if qtable != nil {
qtableStrs.append([qs1, qs2])
}
// VTable
var vs = "*"
if maze[ri][ci].canAttemptToBeEntered && maze[ri][ci].canBeEntered {
vs = "0"
if let v = vtable?[informationState] {
vs = double2Str(printFullFloat: printFullFloat, value: v)
}
}
if vtable != nil {
vtableStrs.append(vs)
}
// PTable
var ps = "*"
if maze[ri][ci].canAttemptToBeEntered && maze[ri][ci].canBeEntered
&& !maze[ri][ci].isTerminal
{
ps = "?"
if let list = ptable?[informationState] {
ps = list.reduce("?") { str, elem in "\(str)\(elem)," }
if ps.suffix(1) == "," {
ps = String("\(ps.dropFirst().dropLast())")
}
}
}
if ptable != nil {
ptableStrs.append(ps)
}
} // End-for iterating through GridCells in maze
qtableResult?.append(qtableStrs)
vtableResult?.append(vtableStrs)
ptableResult?.append(ptableStrs)
}
return (vtableResult, qtableResult, ptableResult)
}
// Format value to print nicely in tables
func double2Str(printFullFloat: Bool, value: Double) -> String {
if printFullFloat {
return String(format: "%f", value)
}
// Print as an integer
if value.truncatingRemainder(dividingBy: 1) == 0 {
return String(format: "%d", Int(value.rounded(.toNearestOrAwayFromZero)))
}
// Deal with inifinity (may very well exist, for rewards of cells that can never be entered)
if value == Double.infinity {
return "inf"
}
if value == -Double.infinity {
return "-inf"
}
// Value is >=10 or <=-10, then skip the decimals
if value >= 10.0 || value <= -10.0 {
return String(format: "%d", Int(value.rounded(.toNearestOrAwayFromZero)))
}
// Print 1 decimal if >=5 or <=5, otherwise limit to 2
var r = ""
if value >= 5.0 || value <= -5.0 {
r = String(format: "%0.1f", value) // Drop second decimal, it's 0 or neglectible
} else {
r = String(format: "%0.2f", value)
}
// If a decimal point exist, remove all trailig 0s
if r.contains(".") {
while r.suffix(1) == "0" {
r = String(r.dropLast(1))
}
if r.suffix(1) == "." { // If trimming leaved '.' as trailer then remove that also
r = String(r.dropLast(1))
}
}
// Remove a leading zero
if r.starts(with: "0") {
return String(r.dropFirst(1))
}
// Remove a leading zero after '-'
if r.starts(with: "-0") {
return "-" + r.dropFirst(2)
}
return r
}
// Given all values, what is the longest string
// This value is used to pad all other values to get symmetric table
func getLargestColSize(
col: Int, maze: [[String]], vtable: [[String]]?, qtable: [[[String]]]?, policy: [[String]]?
) -> Int {
let mcols = maze.map { $0[col] }
let vcols = vtable?.map { $0[col] } ?? []
let qcols1 = qtable?.map { $0[col][0] } ?? []
let qcols2 = qtable?.map { $0[col][1] } ?? []
let pcols = policy?.map { $0[col] } ?? []
return (mcols + vcols + qcols1 + qcols2 + pcols).max { $0.count < $1.count }!.count // at least maze is non-empty
}
}
// **************************************************************************
// Miscellaneous functions needed
//----
// TODO: Does a function like this existin in Swift library
fileprivate func randomIndexFromProbabilities(probabilityList: [Double]) -> Int {
let sum = probabilityList.reduce(0, +)
let randomNumber = Double.random(in: 0.0..<sum)
var ladder = 0.0
for (idx, probability) in probabilityList.enumerated() {
ladder += probability
if randomNumber < ladder {
return idx
}
}
// If everything falls through, then pick last one
return (probabilityList.count - 1)
}
//----
// TODO: Does a function like this existin in Swift library
// (i.e shift content of str to the center of len (and pad with " ")
fileprivate func strCenter(str: String, len: Int) -> String {
precondition(len >= str.count, "Cannot center text if it's larger than space")
var r = str
let space = len - r.count
let even = space / 2
let rem = space % 2
if rem > 0 {
r = " \(r)"
}
for _ in 0..<even {
r = " \(r) "
}
return r
}
| 34.369592 | 138 | 0.61996 |
218f1e990cb04ccb4536478d2802a9df3b224f8d | 3,213 | // Copyright © 2021 Stormbird PTE. LTD.
import Foundation
import UIKit
import BigInt
struct TransactionRowViewModel {
private let transactionRow: TransactionRow
private let chainState: ChainState
private let wallet: Wallet
private let shortFormatter = EtherNumberFormatter.short
private let fullFormatter = EtherNumberFormatter.full
private var server: RPCServer {
return transactionRow.server
}
init(
transactionRow: TransactionRow,
chainState: ChainState,
wallet: Wallet
) {
self.transactionRow = transactionRow
self.chainState = chainState
self.wallet = wallet
}
var direction: TransactionDirection {
if wallet.address.sameContract(as: transactionRow.from) {
return .outgoing
} else {
return .incoming
}
}
var confirmations: Int? {
return chainState.confirmations(fromBlock: transactionRow.blockNumber)
}
var amountTextColor: UIColor {
switch direction {
case .incoming: return Colors.appHighlightGreen
case .outgoing: return Colors.appRed
}
}
var shortValue: TransactionValue {
return transactionValue(for: shortFormatter)
}
var fullValue: TransactionValue {
return transactionValue(for: fullFormatter)
}
var fullAmountAttributedString: NSAttributedString {
return amountAttributedString(for: fullValue)
}
func amountAttributedString(for value: TransactionValue) -> NSAttributedString {
let amount = NSAttributedString(
string: amountWithSign(for: value.amount),
attributes: [
.font: Fonts.regular(size: 24) as Any,
.foregroundColor: amountTextColor,
]
)
let currency = NSAttributedString(
string: " " + value.symbol,
attributes: [
.font: Fonts.regular(size: 16) as Any
]
)
return amount + currency
}
func amountWithSign(for amount: String) -> String {
guard amount != "0" else { return amount }
switch direction {
case .incoming: return "+\(amount)"
case .outgoing: return "-\(amount)"
}
}
private func transactionValue(for formatter: EtherNumberFormatter) -> TransactionValue {
if let operation = transactionRow.operation, let symbol = operation.symbol {
if operation.operationType == .erc721TokenTransfer || operation.operationType == .erc875TokenTransfer {
return TransactionValue(
amount: operation.value,
symbol: symbol
)
} else {
return TransactionValue(
amount: formatter.string(from: BigInt(operation.value) ?? BigInt(), decimals: operation.decimals),
symbol: symbol
)
}
} else {
return TransactionValue(
amount: formatter.string(from: BigInt(transactionRow.value) ?? BigInt()),
symbol: server.symbol
)
}
}
}
| 30.028037 | 122 | 0.594771 |
5087939fc36757b0bc4da07b656209b9a1b2e580 | 1,629 | import UIKit
import RealmSwift
import ZeroKit
class AccountViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var zeroKitIdLabel: UILabel!
@IBOutlet weak var realmIdLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.title = "Account"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.usernameLabel.text = nil
self.zeroKitIdLabel.text = nil
ZeroKitManager.shared.backend.getProfile { profile, _ in
if let profile = profile,
let profileData = profile.data(using: .utf8),
let json = (try? JSONSerialization.jsonObject(with: profileData, options: [])) as? [String: Any] {
self.usernameLabel.text = json[ProfileField.alias.rawValue] as? String
} else {
self.usernameLabel.text = nil
}
}
ZeroKitManager.shared.zeroKit.whoAmI { (userId, _) in
self.zeroKitIdLabel.text = userId
}
realmIdLabel.text = SyncUser.current?.identity
}
@IBAction func logoutButtonTapped(sender: UIButton) {
let alert = UIAlertController(title: "Log out?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Log out", style: .default, handler: { _ in
(UIApplication.shared.delegate as! AppDelegate).logOut()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| 33.9375 | 114 | 0.637815 |
879a6ee512324a16b7fafb6200c4b36cd65a4c3c | 6,682 | //
// Util.swift
// IngenicoConnectKit
//
// Created for Ingenico ePayments on 15/12/2016.
// Copyright © 2016 Global Collect Services. All rights reserved.
//
import UIKit
public class Util {
static let shared = Util()
public var metaInfo: [String: String]? = nil
public var platformIdentifier: String {
let OSName = UIDevice.current.systemName
let OSVersion = UIDevice.current.systemVersion
return "\(OSName)/\(OSVersion)"
}
public var screenSize: String {
let screenBounds = UIScreen.main.bounds
let screenScale = UIScreen.main.scale
let screenSize = CGSize(width: CGFloat(screenBounds.size.width * screenScale), height: CGFloat(screenBounds.size.height * screenScale))
return "\(Int(screenSize.width))\(Int(screenSize.height))"
}
public var deviceType: String {
var size = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine)
}
public init() {
metaInfo = [
"platformIdentifier": platformIdentifier,
"sdkIdentifier": "SwiftClientSDK/v3.0.0",
"sdkCreator": "Ingenico",
"screenSize": screenSize,
"deviceBrand": "Apple",
"deviceType": deviceType
]
}
public var base64EncodedClientMetaInfo: String? {
return base64EncodedClientMetaInfo(withAppIdentifier: nil)
}
public func base64EncodedClientMetaInfo(withAddedData addedData: [String: String]) -> String? {
return base64EncodedClientMetaInfo(withAppIdentifier: nil, ipAddress: nil, addedData: addedData)
}
public func base64EncodedClientMetaInfo(withAppIdentifier appIdentifier: String?) -> String? {
return base64EncodedClientMetaInfo(withAppIdentifier: appIdentifier, ipAddress: nil, addedData: nil)
}
public func base64EncodedClientMetaInfo(withAppIdentifier appIdentifier: String?, ipAddress: String?) -> String? {
return base64EncodedClientMetaInfo(withAppIdentifier: appIdentifier, ipAddress: ipAddress, addedData: nil)
}
public func base64EncodedClientMetaInfo(withAppIdentifier appIdentifier: String?, ipAddress: String?, addedData: [String: String]?) -> String? {
if let addedData = addedData {
for (k, v) in addedData {
metaInfo!.updateValue(v, forKey: k)
}
}
if let appIdentifier = appIdentifier, !appIdentifier.isEmpty {
metaInfo!["appIdentifier"] = appIdentifier
} else {
metaInfo!["appIdentifier"] = "UNKNOWN"
}
if let ipAddress = ipAddress, !ipAddress.isEmpty {
metaInfo!["ipAddress"] = ipAddress
}
return base64EncodedString(fromDictionary: metaInfo!)
}
public func C2SBaseURL(by region: Region, environment: Environment) -> String {
switch region {
case .EU:
switch environment {
case .production:
return "https://ams1.api-ingenico.com/client/v1"
case .preProduction:
return "https://ams1.preprod.api-ingenico.com/client/v1"
case .sandbox:
return "https://ams1.sandbox.api-ingenico.com/client/v1"
}
case .US:
switch environment {
case .production:
return "https://us.api-ingenico.com/client/v1"
case .preProduction:
return "https://us.preprod.api-ingenico.com/client/v1"
case .sandbox:
return "https://us.sandbox.api-ingenico.com/client/v1"
}
case .AMS:
switch environment {
case .production:
return "https://ams2.api-ingenico.com/client/v1"
case .preProduction:
return "https://ams2.preprod.api-ingenico.com/client/v1"
case .sandbox:
return "https://ams2.sandbox.api-ingenico.com/client/v1"
}
case .PAR:
switch environment {
case .production:
return "https://par.api-ingenico.com/client/v1"
case .preProduction:
return "https://par-preprod.api-ingenico.com/client/v1"
case .sandbox:
return "https://par.sandbox.api-ingenico.com/client/v1"
}
}
}
public func assetsBaseURL(by region: Region, environment: Environment) -> String {
switch region {
case .EU:
switch environment {
case .production:
return "https://assets.pay1.secured-by-ingenico.com"
case .preProduction:
return "https://assets.pay1.preprod.secured-by-ingenico.com"
case .sandbox:
return "https://assets.pay1.sandbox.secured-by-ingenico.com"
}
case .US:
switch environment {
case .production:
return "https://assets.pay2.secured-by-ingenico.com"
case .preProduction:
return "https://assets.pay2.preprod.secured-by-ingenico.com"
case .sandbox:
return "https://assets.pay2.sandbox.secured-by-ingenico.com"
}
case .AMS:
switch environment {
case .production:
return "https://assets.pay3.secured-by-ingenico.com"
case .preProduction:
return "https://assets.pay3.preprod.secured-by-ingenico.com"
case .sandbox:
return "https://assets.pay3.sandbox.secured-by-ingenico.com"
}
case .PAR:
switch environment {
case .production:
return "https://assets.pay4.secured-by-ingenico.com"
case .preProduction:
return "https://assets.pay4.preprod.secured-by-ingenico.com"
case .sandbox:
return "https://assets.pay4.sandbox.secured-by-ingenico.com"
}
}
}
//TODO: move to Base64 class
public func base64EncodedString(fromDictionary dictionary: [AnyHashable: Any]) -> String? {
guard let json = try? JSONSerialization.data(withJSONObject: dictionary, options: []) else {
Macros.DLog(message: "Unable to serialize dictionary")
return nil
}
return json.encode()
}
}
| 36.118919 | 148 | 0.575726 |
0ed5c43d2bfcc4e5d12ca41b5a540666c610740f | 1,613 | //
// KSAlbum.swift
// KeysocTest
//
// Created by Steve Lai on 5/12/2020.
//
import Foundation
struct KSAlbum: Decodable {
var wrapperType: String //"collection",
var collectionType: String //"Album",
var artistId: Int //909253,
var collectionId: Int //1440857781,
var amgArtistId: Int? //468749,
var artistName: String //"Jack Johnson",
var collectionName: String //"In Between Dreams (Bonus Track Version)",
var collectionCensoredName: String //"In Between Dreams (Bonus Track Version)",
var artistViewUrl: String //"https://music.apple.com/us/artist/jack-johnson/909253?uo=4",
var collectionViewUrl: String //"https://music.apple.com/us/album/in-between-dreams-bonus-track-version/1440857781?uo=4",
var artworkUrl60: String //"https://is2-ssl.mzstatic.com/image/thumb/Music118/v4/24/46/97/24469731-f56f-29f6-67bd-53438f59ebcb/source/60x60bb.jpg",
var artworkUrl100: String //"https://is2-ssl.mzstatic.com/image/thumb/Music118/v4/24/46/97/24469731-f56f-29f6-67bd-53438f59ebcb/source/100x100bb.jpg",
var collectionPrice: Float //6.99,
var collectionExplicitness: String //"notExplicit",
var trackCount: Int //16,
var copyright: String //"℗ 2013 Jack Johnson",
var country: String //"USA",
var currency: String //"USD",
var releaseDate: String //"2005-03-01T08:00:00Z",
var primaryGenreName: String //"Rock"
}
| 50.40625 | 164 | 0.611903 |
33700ef88ed024426236d7e866d421313ef926db | 1,110 | //
// PieChart.swift
// Money Flow
//
// Created by Алия Гиниятова on 07.07.2021.
//
import Foundation
import UIKit
extension CGFloat {
func radians() -> CGFloat {
let b = CGFloat(Float.pi) * (self/180)
return b
}
}
extension UIBezierPath {
convenience init(circleSegmentCenter center:CGPoint, radius:CGFloat, startAngle:CGFloat, endAngle:CGFloat)
{
self.init()
self.move(to: CGPoint(x: center.x, y: center.y))
self.addArc(withCenter: center, radius:radius, startAngle:startAngle.radians(), endAngle: endAngle.radians(), clockwise:true)
self.close()
}
}
func pieChart(pieces:[(UIBezierPath, UIColor)], viewRect:CGRect) -> UIView {
var layers = [CAShapeLayer]()
for p in pieces {
let layer = CAShapeLayer()
layer.path = p.0.cgPath
layer.fillColor = p.1.cgColor
layer.strokeColor = UIColor.white.cgColor
layers.append(layer)
}
let view = UIView(frame: viewRect)
for l in layers {
view.layer.addSublayer(l)
}
return view
}
| 20.555556 | 133 | 0.614414 |
1a5234384a3ad5d846a49733d77905cd19499950 | 2,398 | //
// Service2ViewController.swift
// Swimediator_Example
import UIKit
import SnapKit
import Swimediator
class Service2ViewController: BaseViewController {
var serviceId: String
required init(serviceId: String) {
self.serviceId = serviceId
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
label.text = "serviceId:" + serviceId
view.addSubview(label)
label.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
}
lazy var label: UILabel = {
let label = UILabel()
return label
}()
override func injector1Action() {
let vc = MediatorManager.getObject(aProtocol: Service1Protocol.self)
self.navigationController?.pushViewController(vc as! UIViewController, animated: true)
}
override func injector2Action() {
let vc = MediatorManager.getObject(aProtocol: Service2Protocol.self, arg1: "Service2ToService2")
self.navigationController?.pushViewController(vc as! UIViewController, animated: true)
}
override func injector3Action() {
let vc = MediatorManager.getObject(aProtocol: Service3Protocol.self, arg1: "service2", arg2: "service3")
self.navigationController?.pushViewController(vc as! UIViewController, animated: true)
}
override func router1Action() {
let obj = try? MediatorManager.routerURL(route: "swi://service1")
guard let vc = obj as? UIViewController else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
override func router2Action() {
let obj = try? MediatorManager.routerURL(route: "swi://service2/router_Service2ToService2")
guard let vc = obj as? UIViewController else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
override func router3Action() {
let obj = try? MediatorManager.routerURL(route: "swi://service3?from=router_Service2&to=router_Service3")
guard let vc = obj as? UIViewController else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 32.405405 | 113 | 0.655963 |
69f7083d37f5c678266c669c7bf64a33bd703b92 | 6,610 | import ComposableArchitecture
import Foundation
import SwiftUI
private let readMe = """
This screen demonstrates how one can share system-wide dependencies across many features with \
very little work. The idea is to create a `SystemEnvironment` generic type that wraps an \
environment, and then implement dynamic member lookup so that you can seamlessly use the \
dependencies in both environments.
Then, throughout your application you can wrap your environments in the `SystemEnvironment` \
to get instant access to all of the shared dependencies. Some good candidates for dependencies \
to share are things like date initializers, schedulers (especially `DispatchQueue.main`), `UUID` \
initializers, and any other dependency in your application that you want every reducer to have \
access to.
"""
struct MultipleDependenciesState: Equatable {
var alert: AlertState<MultipleDependenciesAction>?
var dateString: String?
var fetchedNumberString: String?
var isFetchInFlight = false
var uuidString: String?
}
enum MultipleDependenciesAction: Equatable {
case alertButtonTapped
case alertDelayReceived
case alertDismissed
case dateButtonTapped
case fetchNumberButtonTapped
case fetchNumberResponse(Int)
case uuidButtonTapped
}
struct MultipleDependenciesEnvironment {
var fetchNumber: () -> Effect<Int, Never>
}
let multipleDependenciesReducer = Reducer<
MultipleDependenciesState,
MultipleDependenciesAction,
SystemEnvironment<MultipleDependenciesEnvironment>
> { state, action, environment in
switch action {
case .alertButtonTapped:
return Effect(value: .alertDelayReceived)
.delay(for: 1, scheduler: environment.mainQueue())
.eraseToEffect()
case .alertDelayReceived:
state.alert = .init(title: "Here's an alert after a delay!")
return .none
case .alertDismissed:
state.alert = nil
return .none
case .dateButtonTapped:
state.dateString = "\(environment.date())"
return .none
case .fetchNumberButtonTapped:
state.isFetchInFlight = true
return environment.fetchNumber()
.map(MultipleDependenciesAction.fetchNumberResponse)
case let .fetchNumberResponse(number):
state.isFetchInFlight = false
state.fetchedNumberString = "\(number)"
return .none
case .uuidButtonTapped:
state.uuidString = "\(environment.uuid())"
return .none
}
}
struct MultipleDependenciesView: View {
let store: Store<MultipleDependenciesState, MultipleDependenciesAction>
var body: some View {
WithViewStore(self.store) { viewStore in
Form {
Section(
header: Text(template: readMe, .caption)
) {
EmptyView()
}
Section(
header: Text(
template: """
The actions below make use of the dependencies in the `SystemEnvironment`.
""", .caption)
) {
HStack {
Button("Date") { viewStore.send(.dateButtonTapped) }
viewStore.dateString.map(Text.init)
}
HStack {
Button("UUID") { viewStore.send(.uuidButtonTapped) }
viewStore.uuidString.map(Text.init)
}
Button("Delayed Alert") { viewStore.send(.alertButtonTapped) }
.alert(self.store.scope(state: { $0.alert }), dismiss: .alertDismissed)
}
Section(
header: Text(
template: """
The actions below make use of the custom environment for this screen, which holds a \
dependency for fetching a random number.
""", .caption)
) {
HStack {
Button("Fetch Number") { viewStore.send(.fetchNumberButtonTapped) }
viewStore.fetchedNumberString.map(Text.init)
Spacer()
if viewStore.isFetchInFlight {
ActivityIndicator()
}
}
}
}
.buttonStyle(BorderlessButtonStyle())
}
.navigationBarTitle("System Environment")
}
}
struct MultipleDependenciesView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
MultipleDependenciesView(
store: Store(
initialState: .init(),
reducer: multipleDependenciesReducer,
environment: .live(
environment: MultipleDependenciesEnvironment(
fetchNumber: {
Effect(value: Int.random(in: 1...1_000))
.delay(for: 1, scheduler: DispatchQueue.main)
.eraseToEffect()
})
)
)
)
}
}
}
@dynamicMemberLookup
struct SystemEnvironment<Environment> {
var date: () -> Date
var environment: Environment
var mainQueue: () -> AnySchedulerOf<DispatchQueue>
var uuid: () -> UUID
subscript<Dependency>(
dynamicMember keyPath: WritableKeyPath<Environment, Dependency>
) -> Dependency {
get { self.environment[keyPath: keyPath] }
set { self.environment[keyPath: keyPath] = newValue }
}
/// Creates a live system environment with the wrapped environment provided.
///
/// - Parameter environment: An environment to be wrapped in the system environment.
/// - Returns: A new system environment.
static func live(environment: Environment) -> Self {
Self(
date: Date.init,
environment: environment,
mainQueue: { DispatchQueue.main.eraseToAnyScheduler() },
uuid: UUID.init
)
}
/// Transforms the underlying wrapped environment.
func map<NewEnvironment>(
_ transform: @escaping (Environment) -> NewEnvironment
) -> SystemEnvironment<NewEnvironment> {
.init(
date: self.date,
environment: transform(self.environment),
mainQueue: self.mainQueue,
uuid: self.uuid
)
}
}
#if DEBUG
extension SystemEnvironment {
static func mock(
date: @escaping () -> Date = { fatalError("date dependency is unimplemented.") },
environment: Environment,
mainQueue: @escaping () -> AnySchedulerOf<DispatchQueue> = { fatalError() },
uuid: @escaping () -> UUID = { fatalError("UUID dependency is unimplemented.") }
) -> Self {
Self(
date: date,
environment: environment,
mainQueue: { mainQueue().eraseToAnyScheduler() },
uuid: uuid
)
}
}
#endif
extension UUID {
/// A deterministic, auto-incrementing "UUID" generator for testing.
static var incrementing: () -> UUID {
var uuid = 0
return {
defer { uuid += 1 }
return UUID(uuidString: "00000000-0000-0000-0000-\(String(format: "%012x", uuid))")!
}
}
}
| 29.247788 | 100 | 0.654917 |
db0f610a18b58aee5f9a7212f8c105d5f3be46c6 | 341 | //
// NSObject+KyoSubscript.swift
// KyoDynamicProperty
//
// Created by 王建星 on 2020/11/1.
//
import Foundation
public extension NSObject {
/// 获取或设置动态属性
subscript(dynamicProperty key: String) -> AnyObject? {
set {self.addProperty(name: key, value: newValue)}
get {self.getProperty(name: key)}
}
}
| 17.947368 | 58 | 0.636364 |
6ad0afd4d33ac0a686a14b043cfad4d79d6b9290 | 7,215 | //
// SecondMenuViewController.swift
// FinalProject
//
// Created by Лада on 27/11/2019.
// Copyright © 2019 Лада. All rights reserved.
//
import UIKit
protocol UpdateGamePoints {
func addPointsToGamer(gamerNumber: Int)
}
// здесь идет сама игра
// из предыдущего контроллера передается коллекция карточек
// здесь ведется подсчет очков и изменяются параметры у вью
final class GameMenuViewController: UIViewController, UpdateGamePoints {
var cardCollection: [ImageModel]!
// var gameMenuModel: GameModelInput!
private var cardCollectionView: UICollectionView!
private let dataSource = CardsCollectionViewDataSource()
private let delegate = CardCollectionViewDelegate()
private let layout = CardCollectionViewFlowLayout()
// параметры игры: очки первого игрока, второго игрока и количество оставшихся очков, по которым определяется, завершена ли игра
private var pointsGamer1 = 0
private var pointsGamer2 = 0
private var gameCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
delegate.gameMenuViewController = self
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: view.frame.width, height: 700)
cardCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height), collectionViewLayout: layout)
cardCollectionView.register(CardCell.self, forCellWithReuseIdentifier: "CardCell")
dataSource.cardCollection = cardCollection
cardCollectionView.dataSource = dataSource
cardCollectionView.delegate = delegate
cardCollectionView.isScrollEnabled = false
cardCollectionView.frame = CGRect(x: 0, y: 2*(navigationController?.navigationBar.frame.height ?? 0), width: view.frame.width, height:view.frame.width + 6)
cardCollectionView.backgroundColor = .blue
view.backgroundColor = UIColor.red
// устанавливаем количество очков, равных количеству карточек
gameCount = cardCollection.count
// настраиваем расположение объектов
let height = view.frame.height
let width = view.frame.width
textGamer1.frame = CGRect(x: view.frame.width/10, y: height/8*6, width: width/4*1, height: height/16)
textGamer2.frame = CGRect(x: view.frame.width/10 + width/2*1, y: height/8*6, width: width/4*1, height: height/16)
textPointGamer1.frame = CGRect(x: view.frame.width/10, y: height/8*7, width: width/4*1, height: height/16)
textPointGamer2.frame = CGRect(x: view.frame.width/10 + width/2*1, y: height/8*7, width: width/4*1, height: height/16)
textPointGamer1.text = String(pointsGamer1)
textPointGamer2.text = String(pointsGamer2)
}
// добавляем наши объекты
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
view.backgroundColor = .blue
view.addSubview(cardCollectionView)
view.addSubview(textGamer1)
view.addSubview(textGamer2)
view.addSubview(textPointGamer1)
view.addSubview(textPointGamer2)
}
// функция, отвечающая за добавление очков игроку, чей номер передается в gamerNumber
// так же ведет подсчет количества оставшихся очков, удаляя по 2 очка при правильном ответе (неправильный ответ не передается)
func addPointsToGamer(gamerNumber: Int) {
switch gamerNumber {
case 1:
do {
self.pointsGamer1 += 1
self.textPointGamer1.text = String(self.pointsGamer1)
gameCount -= 2
}
case 2:
do {
self.pointsGamer2 += 1
self.textPointGamer2.text = String(self.pointsGamer2)
gameCount -= 2
}
default:
errorMessage(error: "Такого игрока нет")
}
// когда количество карточек доходит до 0, тогда и количество очков становится 0
// и появляется сообщение об окончании игры, а так же выдаются результаты игры
if gameCount == 0 {
if pointsGamer1 > pointsGamer2 {
textGameOver.text = "Игра закончена!\nПобедил игрок \(String( textGamer1.text))"
}
if pointsGamer1 < pointsGamer2 {
textGameOver.text = "Игра закончена!\nПобедил игрок \(String(textGamer2.text))"
}
if pointsGamer1 == pointsGamer2{
textGameOver.text = "Игра закончена!\nНичья"
}
textGameOver.frame = CGRect(x: view.frame.width/3, y: view.frame.height/2, width: view.frame.width/3, height: 100)
view.addSubview(textGameOver)
}
}
private let textGameOver: UITextView = {
let text = UITextView()
text.isUserInteractionEnabled = false
text.textAlignment = .center
text.font = UIFont.systemFont(ofSize: 16)
text.backgroundColor = .white
text.layer.cornerRadius = 15
return text
}()
private let textGamer1: UITextView = {
let text = UITextView()
text.isUserInteractionEnabled = false
text.text = "Игрок 1"
text.textAlignment = .center
text.contentInset = UIEdgeInsets(top: 120, left:0, bottom: 10, right:0)
text.font = UIFont.systemFont(ofSize: 16)
text.backgroundColor = .white
text.layer.cornerRadius = 15
return text
}()
private let textGamer2: UITextView = {
let text = UITextView()
text.isUserInteractionEnabled = false
text.text = "Игрок 2"
text.textAlignment = .center
text.contentInset = UIEdgeInsets(top: 120, left:0, bottom: 10, right:0)
text.font = UIFont.systemFont(ofSize: 16)
text.backgroundColor = .white
text.layer.cornerRadius = 15
return text
}()
private let textPointGamer1: UITextView = {
let text = UITextView()
text.isUserInteractionEnabled = false
text.text = ""
text.textAlignment = .center
text.contentInset = UIEdgeInsets(top: 120, left:0, bottom: 10, right:0)
text.font = UIFont.systemFont(ofSize: 16)
text.backgroundColor = .white
text.layer.cornerRadius = 15
return text
}()
private let textPointGamer2: UITextView = {
let text = UITextView()
text.isUserInteractionEnabled = false
text.text = ""
text.textAlignment = .center
text.contentInset = UIEdgeInsets(top: 120, left:0, bottom: 10, right:0)
text.font = UIFont.systemFont(ofSize: 16)
text.backgroundColor = .white
text.layer.cornerRadius = 15
return text
}()
func errorMessage(error: String){
let errorMessage = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
errorMessage.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
self.present(errorMessage, animated: true)
}
}
| 39.861878 | 166 | 0.635897 |
ac625fe1ab8588c5910e44f28d02fe504f48b0e7 | 19,718 | import ChangeCases
import Foundation
public struct APIDefinition {
public var name: String
public var returnType: String
public var parameters: [(name: String, type: String)]
public var comment: String?
public init(
name: String, returnType: String, parameters: [(name: String, type: String)], comment: String?
) {
self.name = name
self.returnType = returnType
self.parameters = parameters
self.comment = comment
}
}
// We have 3 ways to handle Mj* types. These are either value like MjvCamera, itself is a final
// class / struct, and contains the struct of mjvCamera. Or ref, like MjModel, itself is a final
// class / struct, and contains the UnsafeMutablePointer to mjModel. The other is the alias like
// MjrRect, it is the same as mjrRect.
enum MjType {
case value
case ref
case alias
}
let MjTypes: [String: MjType] = [
"MjContact": .value,
"MjData": .ref,
"MjLROpt": .value,
"MjModel": .ref,
"MjOption": .value,
"MjrContext": .ref,
"MjrRect": .alias,
"MjSolverStat": .alias,
"MjStatistic": .alias,
"MjTimerStat": .alias,
"MjuiDef": .value,
"MjuiItemEdit": .ref,
"MjuiItemMulti": .ref,
"MjuiItemSingle": .ref,
"MjuiItemSlider": .ref,
"MjuiItem": .ref,
"MjuiSection": .ref,
"MjuiState": .value,
"MjUI": .ref,
"MjuiThemeColor": .value,
"MjuiThemeSpacing": .value,
"MjvCamera": .value,
"MjvFigure": .ref,
"MjVFS": .ref,
"MjvGeom": .value,
"MjvGLCamera": .value,
"MjVisual": .value,
"MjvLight": .alias,
"MjvOption": .value,
"MjvPerturb": .value,
"MjvScene": .ref,
"MjWarningStat": .alias,
]
public func mjObjectExtensions() -> String {
let mjTypes = MjTypes.map({ $0 }).sorted { $0.key < $1.key }
var code = "import C_mujoco\n\n"
for (key, value) in mjTypes {
code += "extension \(key): MjObject {\n"
let cType = key.firstLowercased() + "_"
code += " public typealias CType = \(cType)\n"
code +=
" public static func withCTypeUnsafeMutablePointer<R>(to value: inout Self, _ body: (UnsafeMutablePointer<CType>) throws -> R) rethrows -> R {\n"
let varName = varName(key)
switch value {
case .value:
code += " try withUnsafeMutablePointer(to: &value.\(varName), body)\n"
case .alias:
code += " try withUnsafeMutablePointer(to: &value, body)\n"
case .ref:
code += " try body(value.\(varName))\n"
}
code += " }\n"
code += "}\n"
}
return code
}
let MjTypeConversionSuffixPatch: [String: String] = [
"MjuiItem": ", object: _storage"
]
enum SwiftParameterType {
case plain(String, Bool, Bool) // name, isPointer, isConst
case string
case tuple(String, Bool, Int) // name, isConst, Repeat
case array(String, Bool) // name, isConst
case `enum`(String) // name
var isPointer: Bool {
switch self {
case .plain(_, let isPointer, _):
return isPointer
case .array, .tuple, .string:
return true
case .enum:
return false
}
}
var isConst: Bool {
switch self {
case .plain(_, _, let isConst), .array(_, let isConst), .tuple(_, let isConst, _):
return isConst
case .string, .enum:
return true
}
}
var isInout: Bool {
// Otherwise, if it is a pointer, it needs to be inout.
switch self {
case let .plain(_, isPointer, _):
// If it is const pointer, we don't need this to be inout, just a local copy would be
// sufficient.
if isConst {
return false
}
return isPointer
case let .tuple(_, isConst, _), let .array(_, isConst):
return !isConst
case .string, .enum:
return false
}
}
var isArrayOrTuple: Bool {
switch self {
case .array, .tuple:
return true
case .plain, .string, .enum:
return false
}
}
var swiftType: String {
switch self {
case let .plain(name, _, _), let .enum(name):
return name
case let .tuple(name, isConst, _), let .array(name, isConst):
return isConst ? "Mj\(name)BufferPointer" : "Mj\(name)MutableBufferPointer"
case .string:
return "String"
}
}
}
extension SwiftParameterType: CustomStringConvertible {
var description: String {
switch self {
case let .plain(name, _, _), let .enum(name):
return name
case let .tuple(name, _, count):
return "(" + [String](repeating: name, count: count).joined(separator: ", ") + ")"
case let .array(name, _):
return "[" + name + "]"
case .string:
return "String"
}
}
}
func swiftParameterType(name: String, type: String, comment: String?) -> SwiftParameterType {
if type == "const char *" || type == "const char*" { return .string }
let matched = type.split(separator: " ", maxSplits: 1)
let isConst = matched.count > 1 && matched[0] == "const"
let nakedType = isConst ? String(matched.last!) : type
var mainType = nakedType
let isPointer = (mainType.last == "*")
var isEnum = false
if isPointer {
mainType = String(mainType.dropLast().trimmingCharacters(in: .whitespaces))
} else if let comment = comment {
// If it is not pointer, we need to explore the possibility this is an enum type.
// In MuJoCo, all enum types are int, but they are annotated in comment as "x is mjtY"
let parts = comment.split(separator: " ")
for (i, part) in parts.enumerated() where i < parts.count - 2 {
if part == name && parts[i + 1] == "is" && parts[i + 2].hasPrefix("mjt") {
mainType =
"Mjt"
+ String(
parts[i + 2].suffix(from: parts[i + 2].index(parts[i + 2].startIndex, offsetBy: 3)))
if mainType.hasSuffix(".") || mainType.hasSuffix(";") {
mainType = String(mainType.dropLast())
}
isEnum = true
break
}
}
}
mainType = (SwiftType[mainType] ?? mainType).firstUppercased()
if let range = name.range(of: #"\[\w+\]"#, options: .regularExpression) {
let matched = name[range].dropFirst().dropLast()
let count = Int(matched)!
precondition(!isPointer) // We cannot handle static array with pointer.
precondition(!isEnum)
return .tuple(mainType, isConst, count)
}
if mainType.hasPrefix("Mj") || !isPointer {
if isEnum {
return .enum(mainType)
} else {
return .plain(mainType, isPointer, isConst)
}
} else {
return .array(mainType, isConst)
}
}
enum SwiftReturnType {
case plain(String, Bool, Bool) // name, isPointer, isConst
case string
case void
var isMjType: Bool {
if case .plain(let name, _, _) = self {
return name.hasPrefix("Mj")
}
return false
}
func isBoolReturn(apiName: String) -> Bool {
// This is pure C, bool is int, is Int32.
guard case let .plain(name, _, _) = self, name == "Int32" else {
return false
}
// If name contains _is, it is a boolean
return apiName.contains("_is")
}
}
extension SwiftReturnType: CustomStringConvertible {
var description: String {
switch self {
case let .plain(name, _, _):
return name
case .string:
return "String"
case .void:
return "Void"
}
}
}
func swiftReturnType(_ type: String) -> SwiftReturnType {
if type == "void" { return .void }
if type == "const char *" || type == "const char*" { return .string }
let matched = type.split(separator: " ", maxSplits: 1)
let isConst = matched.count > 1 && matched[0] == "const"
let nakedType = isConst ? String(matched.last!) : type
var mainType = nakedType
let isPointer = (mainType.last == "*")
if isPointer {
mainType = String(mainType.dropLast().trimmingCharacters(in: .whitespaces))
}
mainType = (SwiftType[mainType] ?? mainType).firstUppercased()
return .plain(mainType, isPointer, isConst)
}
func varName(_ name: String) -> String {
precondition(name.hasPrefix("Mj"))
let internalProperty = name.dropFirst()
let varName = internalProperty.suffix(from: internalProperty.firstIndex(where: \.isUppercase)!)
.lowercased()
return "_" + varName
}
public func functionExtension(
_ apiDefinition: APIDefinition, deny: [String] = [], nameMapping: [String: [String]] = [:]
) -> (mainType: String?, sourceCode: String) {
// First, identify primary owner of the function.
// Rule:
// 1. Only look at first or last parameter (excluding mjt* or ordinary C types) as the primary owner, if cannot find any, fatal.
// 2. Identify parameter corresponding to the function signature, if the function starts with mjv_
// find the parameter has type mjv*.
let prefix = apiDefinition.name.prefix(while: { $0 != "_" })
var mainInd: Int? = nil
var mainType: String? = nil
for (i, last) in apiDefinition.parameters.enumerated().reversed() {
guard !last.type.hasPrefix("mjt") else { continue }
let matched = last.type.split(separator: " ", maxSplits: 1)
let nakedType = String(matched.last!)
guard nakedType.hasPrefix("mj") else { continue }
guard !deny.contains(nakedType) else { continue }
if nakedType.lowercased().hasPrefix(prefix) {
mainType = nakedType
mainInd = i
break
}
}
if let first = apiDefinition.parameters.first {
let matched = first.type.split(separator: " ", maxSplits: 1)
let nakedType = String(matched.last!)
if !deny.contains(nakedType) {
if nakedType.lowercased().hasPrefix(prefix) {
mainType = nakedType
mainInd = 0
} else if mainType == nil {
mainType = nakedType
mainInd = 0
}
}
}
if var unwrappedMainType = mainType {
if !(unwrappedMainType.hasPrefix("mj") && !unwrappedMainType.hasPrefix("mjt")) {
mainType = nil
mainInd = nil
} else {
// Now we have main type, we can create functions for them.
if unwrappedMainType.last == "*" {
unwrappedMainType = String(
unwrappedMainType.dropLast().trimmingCharacters(in: .whitespaces))
}
mainType = unwrappedMainType.firstUppercased()
}
}
var positionedNamedParameters = [Int: (name: String, type: String)]()
for (i, parameter) in apiDefinition.parameters.enumerated() {
guard i != mainInd else { continue }
// First, matching parameter name.
let possibleNames = nameMapping[parameter.name]
let name: String
if let possibleNames = possibleNames {
if possibleNames.count > 1 {
var matched: String? = nil
let lowercasedType = parameter.type.lowercased()
for possibleName in possibleNames {
if lowercasedType.contains(possibleName.lowercased()) {
matched = possibleName
break
}
}
name = matched!
} else {
name = possibleNames.first!
}
} else {
name = parameter.name
}
positionedNamedParameters[i] = (name: name, type: parameter.type)
}
// Remove the prefix from the name.
var funcName = apiDefinition.name.suffix(
from: apiDefinition.name.index(
apiDefinition.name.firstIndex(where: { $0 == "_" })!, offsetBy: 1))
let lowercasedName = funcName.lowercased()
var parameterSuffix = ""
var suffixIndexes = Set<Int>()
for i in 0..<apiDefinition.parameters.count {
guard i != mainInd, let namedParameter = positionedNamedParameters[i] else { continue }
if lowercasedName.contains(namedParameter.name.lowercased()) {
parameterSuffix += namedParameter.name.lowercased()
suffixIndexes.insert(i)
} else {
break
}
}
var anonymousIndexes = Set<Int>()
if lowercasedName.hasSuffix(parameterSuffix) {
// We have a problem, we cannot have function that has no name. In this case, make function name
// whatever it is, and make the parameters not named.
if lowercasedName.hasPrefix(parameterSuffix) {
// Now these matching suffix indexes should be anonymous.
anonymousIndexes = suffixIndexes
} else {
// Other, remove these suffixes.
funcName = funcName.prefix(
upTo: funcName.index(
funcName.startIndex, offsetBy: lowercasedName.count - parameterSuffix.count))
}
}
var parameterPairs = [String]()
var numberedGenerics = [String]()
var parameterParsedTypes = [Int: SwiftParameterType]()
for i in 0..<apiDefinition.parameters.count {
guard i != mainInd, let namedParameter = positionedNamedParameters[i] else { continue }
let parsedType = swiftParameterType(
name: namedParameter.name, type: namedParameter.type, comment: apiDefinition.comment)
parameterParsedTypes[i] = parsedType
// For inout parameters, we need to make this as generics, otherwise the API requires you first cast to the protocol, which could be messed up.
let swiftType: String
if parsedType.isInout && parsedType.isArrayOrTuple {
swiftType = "T\(numberedGenerics.count)"
numberedGenerics.append(parsedType.swiftType)
} else {
swiftType = parsedType.swiftType
}
if anonymousIndexes.contains(i) {
parameterPairs.append(
"_ \(cleanupFieldName(name: namedParameter.name).camelCase()): \(parsedType.isInout ? "inout ": "")\(swiftType)"
)
} else {
parameterPairs.append(
"\(cleanupFieldName(name: namedParameter.name).camelCase()): \(parsedType.isInout ? "inout ": "")\(swiftType)"
)
}
}
let mainParsedType = mainInd.map {
swiftParameterType(
name: apiDefinition.parameters[$0].name, type: apiDefinition.parameters[$0].type,
comment: apiDefinition.comment)
}
var code = ""
if let comment = apiDefinition.comment {
code += " /// \(comment)\n"
}
code += " @inlinable\n"
let mutatingPrefix: String
if let mainParsedType = mainParsedType, mainParsedType.isInout {
mutatingPrefix = " mutating"
} else {
mutatingPrefix = ""
}
let parsedReturnType = swiftReturnType(apiDefinition.returnType)
let isBoolReturn = parsedReturnType.isBoolReturn(apiName: apiDefinition.name)
let hasReturnValue: Bool
if case .void = parsedReturnType {
hasReturnValue = false
} else {
hasReturnValue = true
}
let genericsList =
numberedGenerics.count > 0
? "<\(numberedGenerics.enumerated().map({ "T\($0): \($1)" }).joined(separator: ", "))>" : ""
switch parsedReturnType {
case .string:
code +=
" public\(mutatingPrefix) func \(funcName)\(genericsList)(\(parameterPairs.joined(separator: ", "))) -> String? {\n"
case .void:
code +=
" public\(mutatingPrefix) func \(funcName)\(genericsList)(\(parameterPairs.joined(separator: ", "))) {\n"
case .plain(let name, _, _):
code +=
" public\(mutatingPrefix) func \(funcName)\(genericsList)(\(parameterPairs.joined(separator: ", "))) -> \(isBoolReturn ? "Bool" : name) {\n"
}
var localCopyPairs = [String]()
var callingPairs = [String]()
var enclosings = 0
for (i, _) in apiDefinition.parameters.enumerated() {
guard i != mainInd, let namedParameter = positionedNamedParameters[i] else {
let mainType = mainType! // We can unwrapped because mainInd != nil.
let mainParsedType = mainParsedType! // Therefore, we can unwrap mainParsedType too.
switch MjTypes[mainType]! {
case .value:
if mainParsedType.isPointer {
if mainParsedType.isConst {
localCopyPairs.append(
"var _\(varName(mainParsedType.swiftType)) = self.\(varName(mainParsedType.swiftType))"
)
callingPairs.append("&_\(varName(mainType))")
} else {
callingPairs.append("&self.\(varName(mainType))")
}
} else {
callingPairs.append("self.\(varName(mainType))")
}
case .ref:
precondition(mainParsedType.isPointer)
callingPairs.append("self.\(varName(mainType))")
case .alias:
if mainParsedType.isPointer {
callingPairs.append("self")
} else {
callingPairs.append("&self")
}
}
continue
}
let parsedType = parameterParsedTypes[i]!
let paramName = cleanupFieldName(name: namedParameter.name).camelCase()
if case let .plain(typeName, isPointer, isConst) = parsedType, typeName.hasPrefix("Mj") {
switch MjTypes[parsedType.swiftType]! {
case .value:
if isPointer {
if isConst { // This is const pointer, we need to make a local copy and then pass the pointer.
localCopyPairs.append(
String(repeating: " ", count: enclosings)
+ "var \(paramName)_\(varName(parsedType.swiftType)) = \(paramName).\(varName(parsedType.swiftType))"
)
callingPairs.append("&\(paramName)_\(varName(parsedType.swiftType))")
} else {
callingPairs.append("&\(paramName).\(varName(parsedType.swiftType))")
}
} else {
callingPairs.append("\(paramName).\(varName(parsedType.swiftType))")
}
case .ref:
precondition(isPointer)
callingPairs.append("\(paramName).\(varName(parsedType.swiftType))")
case .alias:
if isPointer {
callingPairs.append("&\(paramName)")
} else {
callingPairs.append(paramName)
}
}
} else if case let .array(_, isConst) = parsedType {
if isConst {
localCopyPairs.append(
String(repeating: " ", count: enclosings) + (hasReturnValue ? "return " : "")
+ "\(paramName).withUnsafeBufferPointer { \(paramName)__p in")
} else {
localCopyPairs.append(
String(repeating: " ", count: enclosings) + (hasReturnValue ? "return " : "")
+ "\(paramName).withUnsafeMutableBufferPointer { \(paramName)__p in")
}
enclosings += 1
callingPairs.append("\(paramName)__p.baseAddress")
} else if case let .tuple(_, isConst, count) = parsedType {
localCopyPairs.append(
String(repeating: " ", count: enclosings) + "precondition(\(paramName).count == \(count))")
if isConst {
localCopyPairs.append(
String(repeating: " ", count: enclosings) + (hasReturnValue ? "return " : "")
+ "\(paramName).withUnsafeBufferPointer { \(paramName)__p in")
} else {
localCopyPairs.append(
String(repeating: " ", count: enclosings) + (hasReturnValue ? "return " : "")
+ "\(paramName).withUnsafeMutableBufferPointer { \(paramName)__p in")
}
enclosings += 1
callingPairs.append("\(paramName)__p.baseAddress")
} else if case .enum(_) = parsedType {
callingPairs.append("\(paramName).rawValue")
} else {
callingPairs.append("\(paramName)")
}
}
code += localCopyPairs.map({ " \($0)\n" }).joined()
let extraPadding = String(repeating: " ", count: enclosings)
switch parsedReturnType {
case .string:
code +=
" \(extraPadding)return String(cString: \(apiDefinition.name)(\(callingPairs.joined(separator: ", "))), encoding: .utf8)\n"
case .void:
code += " \(extraPadding)\(apiDefinition.name)(\(callingPairs.joined(separator: ", ")))\n"
case .plain(let name, _, _):
if isBoolReturn {
code +=
" \(extraPadding)return (0 != \(apiDefinition.name)(\(callingPairs.joined(separator: ", "))))\n"
} else {
if parsedReturnType.isMjType && MjTypes[name] != .alias {
code +=
" \(extraPadding)return \(name)(\(apiDefinition.name)(\(callingPairs.joined(separator: ", ")))\(MjTypeConversionSuffixPatch[name] ?? ""))\n"
} else {
code +=
" \(extraPadding)return \(apiDefinition.name)(\(callingPairs.joined(separator: ", ")))\n"
}
}
}
for i in (0..<enclosings).reversed() {
code += " \(String(repeating: " ", count: i))}\n"
}
code += " }\n"
return (mainType: mainType, sourceCode: code)
}
| 34.837456 | 153 | 0.630135 |
3921d37fcd77e895015d2e020b19f2853ff0b558 | 1,017 | //: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
import UIKit
let graph = Graph()
let node5 = graph.addNode("5")
let node7 = graph.addNode("7")
let node3 = graph.addNode("3")
let node11 = graph.addNode("11")
let node8 = graph.addNode("8")
let node2 = graph.addNode("2")
let node9 = graph.addNode("9")
let node10 = graph.addNode("10")
graph.addEdge(fromNode: node5, toNode: node11)
graph.addEdge(fromNode: node7, toNode: node11)
graph.addEdge(fromNode: node7, toNode: node8)
graph.addEdge(fromNode: node3, toNode: node8)
graph.addEdge(fromNode: node3, toNode: node10)
graph.addEdge(fromNode: node11, toNode: node2)
graph.addEdge(fromNode: node11, toNode: node9)
graph.addEdge(fromNode: node11, toNode: node10)
graph.addEdge(fromNode: node8, toNode: node9)
// using depth-first search
graph.topologicalSort()
// also using depth-first search
graph.topologicalSortAlternative()
// Kahn's algorithm
graph.topologicalSortKahn()
| 26.076923 | 52 | 0.741396 |
891f7df1ceb4dfdeeac841d6473571a7024ed8be | 6,289 | //
// TRLDefaultsManager.swift
// Trolley
//
// Created by Harry Wright on 17.09.17.
// Copyright © 2017 Off-Piste.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// MARK: Struct Helpers
/// Workaround for:
///
/// Protocol 'IntegerType' can only be used as a generic constraint because it has
/// Self or associated type requirements
///
/// :nodoc:
public protocol _trl_encodable {
func encode() -> Data
func decode(for data: Data) throws -> Self
}
/// Workaround for:
///
/// Protocol 'IntegerType' can only be used as a generic constraint because it has
/// Self or associated type requirements
///
/// :nodoc:
public protocol _trl_encodable_associated_type {
associatedtype EncodingHelper: TRLEncodableHelper
}
/// :nodoc:
public protocol TRLEncodableHelper: NSCoding, NSKeyedUnarchiverDelegate {
var structType: _trl_encodable { get }
}
/// If you wish to save your custom structs to the NSUserDefaults this Protocol is what you need.
///
/// - Note:
/// Workaround for:
/// *Protocol 'IntegerType' can only be used as a generic constraint because it has
/// Self or associated type requirements*
///
/// :nodoc:
public typealias TRLEncodable = _trl_encodable & _trl_encodable_associated_type
// MARK: TRLDefaultsManager
/// A wrapper for UserDefaults
///
/// This allows for eaiser handling of items into and out
/// of NSUserDefaults with just a key and object been needed
/// and we do the rest.
@objc public final class TRLDefaultsManager: NSObject {
private var defaults: UserDefaults {
return UserDefaults.standard
}
private var _key: String
/// Initaliser to set up the key
///
/// - Parameter key: The string key for UD
@nonobjc
public init(withKey key: String) {
self._key = key
}
/// Initaliser to set up the key
///
/// - Parameter key: The string key for UD
@available(swift, introduced: 1.0, obsoleted: 1.0)
@objc(managerForKey:)
public static func __managerForKey(_ key: String) -> TRLDefaultsManager {
return TRLDefaultsManager(withKey: key)
}
/// Method to retrive an object from persistance storage
///
/// - Returns: The object for the key
/// - Throws: A Trolley.Error.nsudNilReturnValue if the object is nil
@objc(retriveObject:)
public final func retrieveObject() throws -> Any {
guard let data = defaults.data(forKey: _key) else {
throw TRLMakeError(.defaultsManagerNilReturnValue, "Could not retrive value for: \(_key)")
}
return try Encoder.decode(data: data, forKey: _key)
}
/// Method to set the object
///
/// - Parameter object: The object you wish to store
@objc(setObject:error:)
public func set(_ object: Any) throws {
let data = try Encoder(withObject: object).data
self.defaults.set(data, forKey: self._key)
}
/// The method to remove objects for the key
@objc(clearObject)
public func clear() {
defaults.removeObject(forKey: _key)
}
}
fileprivate class Encoder {
/// The data of the object.
///
/// # NOTE
/// Custom classes must conform to `NSCoding`.
let data: Data
/// Initalsier to set the object and encode it as data
///
/// - Parameter object: Any object, please confom custom objects to `NSCoding`
init(withObject object: Any) throws {
guard let displayStyle = Mirror(reflecting: object).displayStyle else {
let msg: String = "Could not find displayStyle for \(Mirror(reflecting: object))"
throw TRLMakeError(.mirrorCouldNotFindDisplayStyle, msg)
}
// No need to rerchive???
if object is Data || object is NSData {
self.data = object as! Data
} else {
switch displayStyle {
case .class:
self.data = NSKeyedArchiver.archivedData(withRootObject: object)
case .struct:
if let value = object as? _trl_encodable {
self.data = value.encode()
} else {
throw TRLMakeError(.defaultsManagerInvalidStruct, "\(object) does not conform to _trl_encodable")
}
default:
throw TRLMakeError(.defaultsManagerInvalidValueType, "\(displayStyle) is not valid")
}
}
}
/// The method for whichh objects are attemped to be decoded
///
/// Checks for `Basket.Helper` due to the struct having its down decode methods built in
///
/// - Parameters:
/// - data: The retrived data
/// - key: The key for the object, used in the throw
/// - Returns: An Any object that can be used and converted by the user
/// - Throws: An `ManagerError` if the object cannot be unarchived
class func decode(data: Data, forKey key: String) throws -> Any {
guard let object = NSKeyedUnarchiver.unarchiveObject(with: data) else {
throw TRLMakeError(.defaultsManagerCouldNotUnarchive, "Could not unarchiveObject for key: \(key)")
}
if let value = object as? TRLEncodableHelper {
return try value.structType.decode(for: data)
}
return object
}
}
| 32.926702 | 117 | 0.663062 |
fcc8a4615048b2d59ee6aad4a6c3b28d96aead1a | 2,437 | //
// User.swift
// TwitterClient
//
// Created by Dhiman on 2/14/16.
// Copyright © 2016 Dhiman. All rights reserved.
//
import UIKit
var _currentUser: User?
var currentUserKey = "kCurrentKey"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject {
var name: String?
var screenname: String?
var profileImageUrl: String?
var tagline: String?
var dictionary: NSDictionary
var tweet_count: Int?
var followers_count: Int?
var following_count: Int?
var backgroundImageUrl: String?
init(dictionary: NSDictionary) {
self.dictionary = dictionary
// pull user from persistance
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
profileImageUrl = dictionary["profile_image_url"] as? String
tagline = dictionary["description"] as? String
tweet_count = dictionary["statuses_count"] as? Int
followers_count = dictionary["followers_count"] as? Int
following_count = dictionary["friends_count"] as? Int
backgroundImageUrl = dictionary["profile_background_image_url"] as? String
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
let dictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: [])
_currentUser = User(dictionary: dictionary as! NSDictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
let data = try! NSJSONSerialization.dataWithJSONObject(user!.dictionary, options: [])
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize() // save
}
}
}
| 30.08642 | 105 | 0.651211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.