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
|
---|---|---|---|---|---|
8fbc1280636e7e2974b6576666bc47f5ac9ace39 | 486 | /**
Base protocol to which all proper Models should conform to for scalability and maintainance reasons.
Conformances:
- `Hashable` -> storage and equatability (`Hashable` is already `Equatable`)
- `Codable` -> coding and decoding from serial formats
- `Identifiable` -> collection diffing and mandatory in most places in SwiftUI
- `Randomable` -> easy realtime mocking eg. for `PreviewProvider`
*/
public typealias ModelProtocol = Hashable & Codable & Identifiable & Randomable
| 48.6 | 101 | 0.761317 |
149bd78c146317f5fc95e8853e36ed35c806508f | 3,699 | //
// NavigatorHelper.swift
// NavigatorHelper
//
// Created by Jeffrey hu on 2022/3/31.
//
import Foundation
protocol NavigatorProtol {
func handleNotificationLink(_ linkURL: URL?)
func handleEntry(with url: URL?) -> Bool
func dispatchPendingURLIfHave()
func clearPendingURL()
}
public final class NavigatorHelper {
public static let shared = NavigatorHelper()
private let loggerTag = "NavigatorHelper"
private var pendingHandleURL: URL?
private var pendingNotificationLinkURL: URL?
public var requirement: NavigatorHelperRequirement?
public var logPlugin: NavigatorLogPlugin? = NavigatorHelperLogPlugin()
public init() {}
}
extension NavigatorHelper: NavigatorProtol {
/// Handle the link URL form notification.
/// - Parameter linkURL: link URL
public func handleNotificationLink(_ linkURL: URL?) {
logPlugin?.handleLog(message: "Will handle notificationLink \(String(describing: linkURL))", tag: loggerTag)
guard let linkURL = linkURL else {
return
}
guard let requirement = requirement else {
logPlugin?.handleLogError(NavigatorHelperError.invalidRequirement, tag: loggerTag)
return
}
guard requirement.canHandleURL else {
pendingNotificationLinkURL = linkURL
logPlugin?.handleLog(message: "Can not handle notification link \(linkURL)", tag: loggerTag)
return
}
pendingNotificationLinkURL = nil
// handleLinkURL
requirement.handleLinkURL(url: linkURL, whiteListFilter: false)
}
@discardableResult
/// Handle entry form sourceAplication as safari or third app.
/// External incoming routes need to be whitelisted for security.
/// - Parameters:
/// - url: link URL
/// - Returns: Whether it can be handled.
public func handleEntry(with url: URL?) -> Bool {
logPlugin?.handleLog(message: "Will handleEntry \(String(describing: url))", tag: loggerTag)
guard let url = url else {
return false
}
guard let requirement = requirement else {
logPlugin?.handleLogError(NavigatorHelperError.invalidRequirement, tag: loggerTag)
return false
}
guard requirement.canHandleURL else {
logPlugin?.handleLog(message: "Can not handle entry: \(String(describing: pendingHandleURL))", tag: loggerTag)
pendingHandleURL = url
return true
}
pendingHandleURL = nil
// Resolve UniversalLink
guard let result = requirement.resolveUniversalLink(url: url) else {
logPlugin?.handleLogError(NavigatorHelperError.illegalUniversalLink, tag: loggerTag)
logPlugin?.handleLog(message: "Invalid universalLink: \(url)", tag: loggerTag)
return false
}
// Handle link with whiteListFilter
requirement.handleLinkURL(url: result, whiteListFilter: true)
return true
}
/// Dispatch pending URL if have
/// This can be called when the home page has been rendered or when the App is active.
public func dispatchPendingURLIfHave() {
logPlugin?.handleLog(message: "Will dispatch pendingURL: \(String(describing: pendingHandleURL))", tag: loggerTag)
handleEntry(with: pendingHandleURL)
handleNotificationLink(pendingNotificationLinkURL)
}
/// Clear all pending URL and sourceApplication.
public func clearPendingURL() {
pendingHandleURL = nil
pendingNotificationLinkURL = nil
}
}
class NavigatorHelperLogPlugin: NavigatorLogPlugin {
private let loggerTag = "NavigatorHelper"
func handleLogError(_ error: Error, tag: String?) {
print("[\(tag ?? loggerTag)] error is \(error)")
}
func handleLog(message: Any, tag: String?) {
print("[\(tag ?? loggerTag)] \(message)")
}
}
| 30.073171 | 118 | 0.705866 |
75191a73dcdc83f4ce7ea5d2088f5c3e7a608b22 | 3,110 | /**
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let recipeStore = RecipeStore()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
func scheduleTimerNotificationWithUserInfo(_ userInfo: [String : Any]) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in
guard granted else { return }
let message = userInfo["message"] as! String
let title = userInfo["title"] as! String
let timer = userInfo["timer"] as! Int
let content = UNMutableNotificationContent()
content.title = title
content.body = message
content.categoryIdentifier = "timer"
content.sound = UNNotificationSound.default()
content.userInfo = userInfo
var dateInfo = DateComponents()
dateInfo.minute = timer
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: false)
let request = UNNotificationRequest(identifier: "recipes", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: { (error) in
let result = (error == nil) ? "scheduled" : String(describing: error)
print("UNUserNotificationCenter: \(result)")
})
}
}
}
| 43.194444 | 149 | 0.740836 |
0891c50421d0490e3a65550318c43e79305dcd96 | 1,086 | //
// ShowAlert.swift
// Login-VIPER
//
// Created by Aashish Adhikari on 3/28/19.
// Copyright © 2019 Aashish Adhikari. All rights reserved.
//
import UIKit
func showAlertWithMessage(view: UIViewController , message: String){
let alertView: UIAlertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertController.Style.alert)
let alertAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil)
alertView.addAction(alertAction)
view.present(alertView, animated: true, completion: nil)
}
func showAlertWithMessageAndDismiss(currentView view: UIViewController , message: String){
let alertView: UIAlertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertController.Style.alert)
let alertAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel){ _ in
view.navigationController?.popViewController(animated: true)
}
alertView.addAction(alertAction)
view.present(alertView, animated: true, completion: nil)
}
| 41.769231 | 133 | 0.764273 |
795d18e810a6537c1e371f9d3f47524fefc6d577 | 2,306 | import Moya
import Foundation
extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
enum GitHub {
case Zen
case UserProfile(String)
}
extension GitHub: TargetType {
var baseURL: NSURL { return NSURL(string: "https://api.github.com")! }
var path: String {
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
return nil
}
var multipartBody: [MultipartFormData]? {
return nil
}
var sampleData: NSData {
switch self {
case .Zen:
return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)!
case .UserProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
func url(route: TargetType) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString
}
let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in
let error = NSError(domain: "com.moya.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Houston, we have a problem"])
return Endpoint<GitHub>(URL: url(target), sampleResponseClosure: {.NetworkError(error)}, method: target.method, parameters: target.parameters)
}
enum HTTPBin: TargetType {
case BasicAuth
var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! }
var path: String {
switch self {
case .BasicAuth:
return "/basic-auth/user/passwd"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
switch self {
default:
return [:]
}
}
var multipartBody: [MultipartFormData]? {
return nil
}
var sampleData: NSData {
switch self {
case .BasicAuth:
return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
| 25.622222 | 146 | 0.605377 |
e26eb37f1927a3a2b87ebc69e4bb7d896449b38f | 9,680 | import Foundation
class SettingsDetailPresenter: SettingsDetailPresenterProtocol {
var view: SettingsDetailViewProtocol?
var goalValue: Double = 2000
var selectedFavourite = 0
struct AttributionCellData {
let title: String
let url: URL?
}
let attributeCells: [AttributionCellData] = [
AttributionCellData(title: "FSCalendar",
url: URL(string: "https://github.com/WenchaoD/FSCalendar")!),
AttributionCellData(title: "Swift Confetti View",
url: URL(string: "https://github.com/ugurethemaydin/SwiftConfettiView")!),
AttributionCellData(title: "FreePik - Beverages Icon Pack",
url: URL(string: "https://www.freepik.com/")!),
AttributionCellData(title: "FreePik - Education Icon Pack",
url: URL(string: "https://www.freepik.com/")!),
AttributionCellData(title: "Flat Icon",
url: URL(string: "https://www.flaticon.com/")!),
AttributionCellData(title: "Mike Bone",
url: URL(string: "https://github.com/mikecbone")!),
AttributionCellData(title: "Marian Butnaru",
url: nil),
AttributionCellData(title: "Water Droplet Sound FX",
url: URL(string: "https://soundbible.com/")!)
]
init(view: SettingsDetailViewProtocol) {
self.view = view
}
func onViewDidLoad() {
setupView()
}
func setupView() {
switch view?.settingsType {
case .goal:
initialiseGoalView()
case .favourite:
initialiseFavView()
case .coefficient:
initialiseCoefficientView()
case .attribution:
initialiseAttributionView()
case .about:
initialiseAboutView()
case .healthKit:
initialiseHealthKitView()
case .none:
break
}
}
func initialiseGoalView() {
view?.updateTitle(title: "Change Goal")
goalValue = view?.userDefaultsController.drinkGoal ?? 2000
let headingText = "Need to update your goal?"
let bodyText = """
This number is how much you plan to drink daily. It's okay if you need to change it. \
It's normal to play around with it a few times until it feels just right.
Adjust the slider below to amend it to your liking. \
It has a minimum of 1000ml and a maximum of 4000ml.
Note: Changing the goal does not affect days that already have a drink entry.
"""
view?.setupGoalView(currentGoal: goalValue, headingText: headingText, bodyText: bodyText)
}
func initialiseFavView() {
view?.updateTitle(title: "Change Favourites")
let headingText = "Fancy a new favourite?"
let bodyText = """
To change a favourite, simply tap the one below you wish the change and choose a new drink \
and volume and we'll save it for you.
"""
view?.setupFavouritesView(headingText: headingText, bodyText: bodyText)
}
func initialiseCoefficientView() {
view?.updateTitle(title: "Drink Coefficients")
let headingText = "Drink Coefficients?"
let bodyText = """
Drink Coefficients are a representation of the percentage of water in a drink.
Milk for example has a coefficient of 0.88 so will have 88ml of water in it for each 100ml.
Note:
\u{2022} The below coefficients are estimates.
\u{2022} Changing the toggle below does not affect previous drinks.
"""
view?.setupCoefficientView(headingText: headingText, bodyText: bodyText)
}
func initialiseHealthKitView() {
view?.updateTitle(title: "Health Kit")
let headingText = "Health Kit Integration"
let bodyText = """
Enabling HealthKit integration allows us to save your drink progress in the Apple Health app.
Note:
\u{2022} Health Kit only supports water intake, therefore we recommend for accurate readings \
you enable drink coefficients.
"""
view?.setupHealthKitView(headingText: headingText, bodyText: bodyText)
}
func initialiseAttributionView() {
view?.updateTitle(title: "Thanks to")
let headingText = "Credits"
let bodyText = """
Below are links to frameworks, websites or individuals that have assisted in the creation of Drip.
"""
view?.setupAttributionView(headingText: headingText, bodyText: bodyText)
}
func initialiseAboutView() {
view?.updateTitle(title: "About")
let headingText = "About the Developer"
let bodyText = """
Hi, my name's Kaiman.
I'm the Developer of Drip. I hope you're enjoying your experience so far.
I made Drip because I wanted something simple, smooth and familiar feeling. I can only hope \
your experiences are similar and you have as much fun using this app as I had making it.
"""
view?.setupAboutView(headingText: headingText, bodyText: bodyText)
}
func creditAlertControllerForRow(row: Int) {
switch attributeCells[row].title {
case "Marian Butnaru":
let title = "Marian Butnaru"
let message = """
Marian Butnaru was the designer of the teardrop icon seen used on icon and launchscreen.
"""
view?.showAlertController(title: title, message: message)
default:
break
}
}
func updateGoalValue(newGoal: Double) {
goalValue = newGoal
}
func saveButtonTapped() {
switch view?.settingsType {
case .goal:
view?.userDefaultsController.drinkGoal = goalValue
view?.widgetUserDefaultsController.updateGoal(newGoal: goalValue)
default:
break
}
view?.popView()
}
func setCoefficientBool(isEnabled: Bool) {
view?.userDefaultsController.useDrinkCoefficients = isEnabled
}
func setHealthKitBool(isEnabled: Bool) {
view?.healthKitController.checkAuthStatus(completion: { status in
switch status {
case .notDetermined:
self.view?.healthKitController.requestAccess(completion: { success in
if success {
self.setHealthKitBool(isEnabled: isEnabled)
} else {
self.view?.userDefaultsController.enabledHealthKit = false
self.view?.setToggleStatus(isOn: false)
}
})
case .sharingAuthorized:
self.view?.userDefaultsController.enabledHealthKit = isEnabled
case .sharingDenied:
self.view?.showHealthKitDialogue()
self.view?.userDefaultsController.enabledHealthKit = false
self.view?.setToggleStatus(isOn: false)
@unknown default:
break
}
})
}
// MARK: - Favourites -
func drinkForCellAt(index: Int) -> (imageName: String, volume: Double) {
var volume: Double
var imageName: String
guard let userDefaults = view?.userDefaultsController else { return ("waterbottle.svg", 100.0)}
switch index {
case 0:
volume = userDefaults.favDrink1Volume
imageName = userDefaults.favBeverage1.imageName
case 1:
volume = userDefaults.favDrink2Volume
imageName = userDefaults.favBeverage2.imageName
case 2:
volume = userDefaults.favDrink3Volume
imageName = userDefaults.favBeverage3.imageName
case 3:
volume = userDefaults.favDrink4Volume
imageName = userDefaults.favBeverage4.imageName
default:
volume = userDefaults.favDrink1Volume
imageName = userDefaults.favBeverage1.imageName
}
return (imageName, volume)
}
func setSelectedFavourite(selected: Int) {
selectedFavourite = selected
}
func addFavourite(beverage: Beverage, volume: Double) {
guard let userDefaults = view?.userDefaultsController else { return }
switch selectedFavourite {
case 0:
userDefaults.favBeverage1 = beverage
userDefaults.favDrink1Volume = volume
case 1:
userDefaults.favBeverage2 = beverage
userDefaults.favDrink2Volume = volume
case 2:
userDefaults.favBeverage3 = beverage
userDefaults.favDrink3Volume = volume
case 3:
userDefaults.favBeverage4 = beverage
userDefaults.favDrink4Volume = volume
default:
break
}
view?.reloadCollectionView()
}
// MARK: - Table view -
func numberOfRowsInSection() -> Int {
switch view?.settingsType {
case .coefficient:
return Beverages().drinks.count
case .attribution:
return attributeCells.count
default:
return 0
}
}
func coefficientCellDataForRow(row: Int) -> Beverage {
return Beverages().drinks[row]
}
func attributionTitleForRow(row: Int) -> String {
return attributeCells[row].title
}
func getAttributionURLforRow(row: Int) -> URL? {
return attributeCells[row].url
}
}
| 34.204947 | 112 | 0.596178 |
2f784ad8066a371d227a74655366e3c08bf6a55e | 408 | import Foundation
extension DateFormatter {
static let iso8601Full: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
| 29.142857 | 62 | 0.676471 |
09fe2e1733b225e7cfd1fea3010a8802cecb8a8b | 4,276 | import RxSwift
import BigInt
protocol IBlockchain {
var delegate: IBlockchainDelegate? { get set }
var source: String { get }
func start()
func stop()
func refresh()
func syncAccountState()
var syncState: SyncState { get }
var lastBlockHeight: Int? { get }
var accountState: AccountState? { get }
func nonceSingle(defaultBlockParameter: DefaultBlockParameter) -> Single<Int>
func sendSingle(rawTransaction: RawTransaction) -> Single<Transaction>
func transactionReceiptSingle(transactionHash: Data) -> Single<RpcTransactionReceipt?>
func transactionSingle(transactionHash: Data) -> Single<RpcTransaction?>
func getStorageAt(contractAddress: Address, positionData: Data, defaultBlockParameter: DefaultBlockParameter) -> Single<Data>
func call(contractAddress: Address, data: Data, defaultBlockParameter: DefaultBlockParameter) -> Single<Data>
func estimateGas(to: Address?, amount: BigUInt?, gasLimit: Int?, gasPrice: Int?, data: Data?) -> Single<Int>
func getBlock(blockNumber: Int) -> Single<RpcBlock?>
}
protocol IBlockchainDelegate: AnyObject {
func onUpdate(lastBlockHeight: Int)
func onUpdate(syncState: SyncState)
func onUpdate(accountState: AccountState)
}
protocol ITransactionStorage {
func notSyncedTransactions(limit: Int) -> [NotSyncedTransaction]
func notSyncedInternalTransaction() -> NotSyncedInternalTransaction?
func add(notSyncedTransactions: [NotSyncedTransaction])
func save(notSyncedInternalTransaction: NotSyncedInternalTransaction)
func update(notSyncedTransaction: NotSyncedTransaction)
func remove(notSyncedTransaction: NotSyncedTransaction)
func remove(notSyncedInternalTransaction: NotSyncedInternalTransaction)
func save(transaction: Transaction)
func pendingTransactions(fromTransaction: Transaction?) -> [Transaction]
func pendingTransaction(nonce: Int) -> Transaction?
func save(transactionReceipt: TransactionReceipt)
func transactionReceipt(hash: Data) -> TransactionReceipt?
func save(logs: [TransactionLog])
func save(internalTransactions: [InternalTransaction])
func set(tags: [TransactionTag])
func remove(logs: [TransactionLog])
func hashesFromTransactions() -> [Data]
func transactionsBeforeSingle(tags: [[String]], hash: Data?, limit: Int?) -> Single<[FullTransaction]>
func pendingTransactions(tags: [[String]]) -> [FullTransaction]
func transaction(hash: Data) -> FullTransaction?
func fullTransactions(byHashes: [Data]) -> [FullTransaction]
func add(droppedTransaction: DroppedTransaction)
}
public protocol ITransactionSyncerStateStorage {
func transactionSyncerState(id: String) -> TransactionSyncerState?
func save(transactionSyncerState: TransactionSyncerState)
}
protocol ITransactionSyncerListener: AnyObject {
func onTransactionsSynced(fullTransactions: [FullTransaction])
}
public protocol ITransactionSyncer {
var id: String { get }
var state: SyncState { get }
var stateObservable: Observable<SyncState> { get }
func set(delegate: ITransactionSyncerDelegate)
func start()
func onEthereumSynced()
func onLastBlockNumber(blockNumber: Int)
func onUpdateAccountState(accountState: AccountState)
}
public protocol ITransactionSyncerDelegate {
var notSyncedTransactionsSignal: PublishSubject<Void> { get }
func transactionSyncerState(id: String) -> TransactionSyncerState?
func update(transactionSyncerState: TransactionSyncerState)
func add(notSyncedTransactions: [NotSyncedTransaction])
func notSyncedTransactions(limit: Int) -> [NotSyncedTransaction]
func remove(notSyncedTransaction: NotSyncedTransaction)
func update(notSyncedTransaction: NotSyncedTransaction)
}
protocol ITransactionManagerDelegate: AnyObject {
func onUpdate(transactionsSyncState: SyncState)
func onUpdate(transactionsWithInternal: [FullTransaction])
}
public protocol IDecorator {
func decorate(transactionData: TransactionData, fullTransaction: FullTransaction?) -> ContractMethodDecoration?
func decorate(logs: [TransactionLog]) -> [ContractEventDecoration]
}
public protocol ITransactionWatcher {
func needInternalTransactions(fullTransaction: FullTransaction) -> Bool
}
| 39.592593 | 129 | 0.769645 |
b938d464c47b22665feef73ea6fb94eafb1024a7 | 14,153 | //
// O3Client.swift
// O3
//
// Created by Apisit Toompakdee on 9/17/17.
// Copyright © 2017 drei. All rights reserved.
//
import UIKit
typealias JSONDictionary = [String: Any]
public enum O3ClientError: Error {
case invalidBodyRequest, invalidData, invalidRequest, noInternet
var localizedDescription: String {
switch self {
case .invalidBodyRequest:
return "Invalid body Request"
case .invalidData:
return "Invalid response data"
case .invalidRequest:
return "Invalid server request"
case .noInternet:
return "No Internet connection"
}
}
}
public enum O3ClientResult<T> {
case success(T)
case failure(O3ClientError)
}
public class O3Client {
enum O3Endpoints: String {
case getPriceHistory = "/v1/price/"
case getPortfolioValue = "/v1/historical"
case getAccountValue = "/v1/value"
case getNewsFeed = "/v1/feed/"
case getTokenSales = "https://platform.o3.network/api/v1/neo/tokensales"
}
enum HTTPMethod: String {
case GET
case POST
}
var baseURL = "https://api.o3.network"
public static let shared = O3Client()
func sendRequest(_ endpointURL: String, method: HTTPMethod, data: [String: Any?]?,
noBaseURL: Bool = false, completion: @escaping (O3ClientResult<JSONDictionary>) -> Void) {
var urlString = ""
if noBaseURL {
urlString = endpointURL
} else {
urlString = baseURL + endpointURL
}
let url = URL(string: urlString)
let request = NSMutableURLRequest(url: url!)
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.cachePolicy = .reloadIgnoringLocalCacheData
if data != nil {
guard let body = try? JSONSerialization.data(withJSONObject: data!, options: []) else {
completion(.failure(.invalidBodyRequest))
return
}
request.httpBody = body
}
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, _, err) in
if err != nil {
completion(.failure(.invalidRequest))
return
}
guard let dataUnwrapped = data,
let json = (try? JSONSerialization.jsonObject(with: dataUnwrapped, options: [])) as? JSONDictionary else {
completion(.failure(.invalidData))
return
}
if let code = json["code"] as? Int {
if code != 200 {
completion(.failure(.invalidData))
return
}
}
let result = O3ClientResult.success(json)
completion(result)
}
task.resume()
}
func getPriceHistory(_ symbol: String, interval: String, completion: @escaping (O3ClientResult<History>) -> Void) {
var endpoint = O3Endpoints.getPriceHistory.rawValue + symbol + String(format: "?i=%@", interval)
endpoint += String(format: "¤cy=%@", UserDefaultsManager.referenceFiatCurrency.rawValue)
sendRequest(endpoint, method: .GET, data: nil) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
guard let result = response["result"] as? JSONDictionary,
let data = result["data"] as? JSONDictionary,
let responseData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted),
let block = try? decoder.decode(History.self, from: responseData) else {
completion(.failure(.invalidData))
return
}
let clientResult = O3ClientResult.success(block)
completion(clientResult)
}
}
}
func getPortfolioValue(_ assets: [PortfolioAsset], interval: String, completion: @escaping (O3ClientResult<PortfolioValue>) -> Void) {
var queryString = String(format: "?i=%@", interval)
for asset in assets {
queryString += String(format: "&%@=%@", asset.symbol, asset.value.description)
}
queryString += String(format: "¤cy=%@", UserDefaultsManager.referenceFiatCurrency.rawValue)
let endpoint = O3Endpoints.getPortfolioValue.rawValue + queryString
print (endpoint)
sendRequest(endpoint, method: .GET, data: nil) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
guard let result = response["result"] as? JSONDictionary,
let data = result["data"] as? JSONDictionary,
let responseData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted),
let block = try? decoder.decode(PortfolioValue.self, from: responseData) else {
completion(.failure(.invalidData))
return
}
let clientResult = O3ClientResult.success(block)
completion(clientResult)
}
}
}
func getNewsFeed(completion: @escaping(O3ClientResult<FeedData>) -> Void) {
let endpoint = O3Endpoints.getNewsFeed.rawValue
sendRequest(endpoint, method: .GET, data: nil) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
guard let result = response["result"] as? JSONDictionary,
let data = result["data"] as? JSONDictionary,
let responseData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted),
let feedData = try? decoder.decode(FeedData.self, from: responseData) else {
completion(.failure(.invalidData))
return
}
let clientResult = O3ClientResult.success(feedData)
completion(clientResult)
}
}
}
func getFeatures(completion: @escaping(O3ClientResult<FeatureFeed>) -> Void) {
var endpoint = "https://platform.o3.network/api/v1/neo/news/featured"
#if TESTNET
endpoint = "https://platform.o3.network/api/v1/neo/news/featured?network=test"
#endif
#if PRIVATENET
endpoint = "https://platform.o3.network/api/v1/neo/news/featured?network=private"
#endif
sendRequest(endpoint, method: .GET, data: nil, noBaseURL: true) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let result = response["result"] as? JSONDictionary
let responseData = result!["data"] as? JSONDictionary
guard let data = try? JSONSerialization.data(withJSONObject: responseData!, options: .prettyPrinted),
let featureFeed = try? decoder.decode(FeatureFeed.self, from: data) else {
return
}
completion(.success(featureFeed))
}
}
}
func getAssetsForMarketPlace(completion: @escaping(O3ClientResult<[Asset]>) -> Void) {
var endpoint = "https://api.o3.network/v1/marketplace"
#if TESTNET
endpoint = "https://api.o3.network/v1/marketplace?network=test"
#endif
#if PRIVATENET
endpoint = "https://api.o3.network/v1/marketplace?network=private"
#endif
sendRequest(endpoint, method: .GET, data: nil, noBaseURL: true) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let result = response["result"] as? JSONDictionary
let responseData = result!["data"] as? JSONDictionary
guard let data = try? JSONSerialization.data(withJSONObject: responseData!["assets"]!, options: .prettyPrinted),
let assetList = try? decoder.decode([Asset].self, from: data) else {
return
}
guard let nep5data = try? JSONSerialization.data(withJSONObject: responseData!["nep5"]!, options: .prettyPrinted),
let nep5list = try? decoder.decode([Asset].self, from: nep5data) else {
return
}
var combinedList: [Asset] = []
for item in assetList {
combinedList.append(item)
}
for item in nep5list {
combinedList.append(item)
}
completion(.success(combinedList))
}
}
}
func getTokens(completion: @escaping(O3ClientResult<[NEP5Token]>) -> Void) {
var endpoint = "https://platform.o3.network/api/v1/neo/nep5"
#if TESTNET
endpoint = "https://platform.o3.network/api/v1/neo/nep5?network=test"
#endif
#if PRIVATENET
endpoint = "https://platform.o3.network/api/v1/neo/nep5?network=private"
#endif
sendRequest(endpoint, method: .GET, data: nil, noBaseURL: true) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let result = response["result"] as? JSONDictionary
let responseData = result!["data"] as? JSONDictionary
guard let data = try? JSONSerialization.data(withJSONObject: responseData!["nep5tokens"]!, options: .prettyPrinted),
let list = try? decoder.decode([NEP5Token].self, from: data) else {
return
}
completion(.success(list))
}
}
}
func getTokenSales(address: String, completion: @escaping(O3ClientResult<TokenSales>) -> Void) {
var endpoint = "https://platform.o3.network/api/v1/neo/" + address + "/tokensales"
#if TESTNET
endpoint = "https://platform.o3.network/api/v1/neo/" + address + "/tokensales?network=test"
#endif
#if PRIVATENET
endpoint = "https://platform.o3.network/api/v1/neo/" + address + "/tokensales?network=private"
#endif
sendRequest(endpoint, method: .GET, data: nil, noBaseURL: true) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
guard let data = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted),
let liveSales = try? decoder.decode(TokenSales.self, from: data) else {
return
}
completion(.success(liveSales))
}
}
}
func getUnboundOng(address: String, completion: @escaping(O3ClientResult<UnboundOng>) -> Void) {
var endpoint = "https://platform.o3.network/api/v1/ont/" + address + "/unboundong"
#if TESTNET
endpoint = "https://platform.o3.network/api/v1/ont/" + address + "/unboundong?network=test"
#endif
#if PRIVATENET
endpoint = "https://platform.o3.network/api/v1/ont/" + address + "/unboundong?network=private"
#endif
sendRequest(endpoint, method: .GET, data: nil, noBaseURL: true) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
let result = response["result"] as? JSONDictionary
let responseData = result!["data"] as? JSONDictionary
guard let data = try? JSONSerialization.data(withJSONObject: responseData!, options: .prettyPrinted),
let unboundong = try? decoder.decode(UnboundOng.self, from: data) else {
return
}
completion(.success(unboundong))
}
}
}
func getAccountValue(_ assets: [PortfolioAsset], completion: @escaping (O3ClientResult<AccountValue>) -> Void) {
var queryString = String(format: "?currency=%@", UserDefaultsManager.referenceFiatCurrency.rawValue)
for asset in assets {
queryString += String(format: "&%@=%@", asset.symbol, asset.value.description)
}
let endpoint = O3Endpoints.getAccountValue.rawValue + queryString
print (endpoint)
sendRequest(endpoint, method: .GET, data: nil) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let response):
let decoder = JSONDecoder()
guard let result = response["result"] as? JSONDictionary,
let data = result["data"] as? JSONDictionary,
let responseData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted),
let obj = try? decoder.decode(AccountValue.self, from: responseData) else {
completion(.failure(.invalidData))
return
}
let clientResult = O3ClientResult.success(obj)
completion(clientResult)
}
}
}
}
| 41.504399 | 138 | 0.566099 |
db0596f3bc0645bc05c333c8947e1a8b0cd2f47b | 5,665 | // 14.4 关联值
// 对实例调用area()方法来看一下实际效果,如代码清单14-27所示。
// 代码清单14-27 计算面积
import Cocoa
// 代码清单14-8 增加成员值
// 也可以不用原始值的默认行为。需要的话,可以给每个成员指定原始值,如代码清单14-13所示。
// 代码清单14-13 指定原始值
enum TextAlignment: Int {
case left = 20
case right = 30
case center = 40
case justify = 50
}
// 因为枚举会声明新类型,所以现在可以创建这个类型的实例了
// 代码清单14-2 创建TextAlignment的实例
//var alignment: TextAlignment = TextAlignment.left
// 尽管TextAlignment是自定义类型,编译器还是能够判断alignment的类型。因此可以省略alignment的显式类型声明
// 14-3 利用类型推断
//var alignment = TextAlignment.left
// 编译器对枚举的类型推断能力不仅限于变量声明。如果一个变量已经明确是某个特定的枚举类型,
// 就可以在给变量赋值时省略枚举名,如代码清单14-4所示。
// 代码清单14-4 推断枚举类型
// alignment = .right
// 注意,代码尽管还能运行,但是会输出错误的值。alignment变量设置为justify,
// 但是switch语句打印了center aligned。
var alignment = TextAlignment.justify
// 打印一些插值字符串来确认这一点,如代码清单14-12所示。
// 代码清单14-12 确认原始值
print("Left has raw value \(TextAlignment.left.rawValue)")
print("Right has raw value \(TextAlignment.right.rawValue)")
print("Center has raw value \(TextAlignment.center.rawValue)")
print("Justify has raw value \(TextAlignment.justify.rawValue)")
print("The alignment variable has raw value \(alignment.rawValue)")
// 每个带原始值的枚举类型都可以用rawValue参数创建,并返回可空枚举,如代码清单14-14所示。
// 代码清单14-14 把原始值转化回枚举类型
// 创建一个原始值
//let myRawValue = 20
// 试着把myRawValue改成不存在的原始值,看一下无法转化时的息,如代码清单14-15所示。
// 代码清单14-15 试一下不存在的值
let myRawValue = 100
// 尝试将原始值转化为TextAlignment
if let myAlignment = TextAlignment(rawValue: myRawValue) {
// 转化成功
print("successfully converted \(myRawValue) into a TextAlignment")
} else {
// 转化失败
print("\(myRawValue) has no corresponding TextAlignment case")
}
// 在传递枚举给函数或比较枚举时可以省略枚举类型
// 代码清单14-5 在比较枚举值时利用类型推断
//if alignment == .right {
// print("we should right-align the text!")
//}
// 用if语句可以比较枚举值,不过通常使用switch语句处理。
// 用switch将对齐信息用人类可读的方式打印出来
// 代码清单14-6 切换到switch
// 对枚举类型使用switch时也可以用default分支,如代码清单14-7所示。
// 代码清单14-7 把居中对齐作为默认选项
// 会产生一个编译时错误,告诉你switch语句没有被全覆盖。
// Switch must be exhaustive
switch alignment {
case .left:
print("left aligned")
case .right:
print("right aligned")
case .center:
// default:
print("center aligned")
case .justify:
print("justified")
}
// Swift支持一系列类型,包括所有的内建数值类型和字符串。
// 创建一个新的枚举,用String作为原始值类型,如代码清单14-16所示。
// 代码清单14-16 创建带字符串原始值的枚举
// 如果省略原始值,Swift会使用成员本身的名字。修改ProgrammingLanguage,删除和成员名一样的原始值,如代码清单14-17所示。
// 代码清单14-17 使用默认的字符串原始值
enum ProgrammingLanguage: String {
case swift //= "swift"
case objectiveC = "objective-c"
case c //= "c"
case cpp //= "c++"
case java //= "java"
}
let myFavoriteLanguage = ProgrammingLanguage.swift
print("My favorite programming language is \(myFavoriteLanguage.rawValue)")
// 在Swift中,方法可以和枚举关联
// 代码清单14-18 电灯泡可以开关
// 增加一个计算表面温度的方法,如代码清单14-19所示。
// 代码清单14-19 实现获取温度的方法
// 另一个有用的方法是开关电灯泡。要开关电灯泡,需要修改self的状态使之从on到off或者从off到on。
// 试着增加一个toggle()方法,这个方法不需要参数也不返回任何东西,如代码清单14-21所示。
// 代码清单14-21 尝试开关
enum Lightbulb {
case on
case off
func surfaceTemperature(forAmbientTemperature ambient: Double) -> Double {
switch self {
case .on:
return ambient + 150.0
case .off:
return ambient
}
}
// 输入这些代码后,编译器会产生错误,告诉你不能在方法内对self赋值。
// 在Swift中,枚举是值类型(value type),而值类型的方法不能对self进行修改。
// 如果希望值类型的方法能修改self,需要标记这个方法为mutating。在代码中加上这个标记,如代码清单14-22所示。
// 代码清单14-22 标记toggle()方法为mutating
mutating func toggle() {
switch self {
case .on:
self = .off
case .off:
self = .on
}
}
}
// 创建一个变量代表电灯泡,调用新实现的方法,如代码清单14-20所示。
// 代码清单14-19 实现获取温度的方法
var bulb = Lightbulb.on // 运行结果侧边栏:on
let ambientTemperature = 77.0 // 运行结果侧边栏:77
var bulbTemperature = bulb.surfaceTemperature(forAmbientTemperature: // 运行结果侧边栏:227
ambientTemperature)
print("the bulb's temperature is \(bulbTemperature)") // 运行结果侧边栏:"the bulb's temperature is 227.0\n"
// 现在可以开关电灯泡并看到关掉时的温度了,如代码清单14-23所示。
// 代码清单14-23 关掉电灯泡
bulb.toggle() // 运行结果侧边栏:off
bulbTemperature = bulb.surfaceTemperature(forAmbientTemperature: ambientTemperature) // 运行结果侧边栏:77
print("the bulb's temperature is \(bulbTemperature)") // 运行结果侧边栏:"the bulb's temperature is 77.0\n"
// Swift还提供了一种强大的枚举:带关联值的成员。关联值能让你把数据附在枚举实例上;不同的成员
// 可以有不同类型的关联值。
// 创建一个枚举用来记录一些基本图形的尺寸。每种图形有不同的属性。要表示正方形,只需
// 要一个值(边长)。要表示长方形,则需要两个值:宽和高。如代码清单14-24所示。
// 代码清单14-24 设置ShapeDimensions
enum ShapeDimensions {
// 正方形的关联值是边长
case square(side: Double)
// 长方形的关联值是宽和高
case rectangle(width: Double, height: Double)
// 在这里,switch的分支利用了Swift的模式匹配(pattern matching)把self的关联值绑定到新变量上。
func area() -> Double {
switch self {
case let .square(side: side):
return side * side
case let .rectangle(width: w, height: h):
return w * h
}
}
}
// 要创建ShapeDimensions的实例,必须指定成员和相应的关联值,如代码清单14-25所示。
// 代码清单14-25 创建图形
// 这里创建了一个边长是10单位的正方形,还有5单位×10单位的长方形。
var squareShape = ShapeDimensions.square(side: 10.0) // 运行结果侧边栏:square(side: 10.0)
var rectShape = ShapeDimensions.rectangle(width: 5.0, height: 10.0) // 运行结果侧边栏:rectangle(width: 5.0, height: 10.0)
// 对实例调用area()方法来看一下实际效果,如代码清单14-27所示。
// 代码清单14-27 计算面积
print("square's area = \(squareShape.area())")
print("rectangle's area = \(rectShape.area())")
//控制台输出:
//Left has raw value 20
//Right has raw value 30
//Center has raw value 40
//Justify has raw value 50
//The alignment variable has raw value 50
//100 has no corresponding TextAlignment case
//justified
//My favorite programming language is swift
//the bulb's temperature is 227.0
//the bulb's temperature is 77.0
//square's area = 100.0
//rectangle's area = 50.0
| 27.36715 | 114 | 0.702913 |
088e2b2e1d8abfa36cc570d4bc7fc8e5b65f2e75 | 3,829 | //
// SettingsViewController.swift
// Music2
//
// Created by 平野翔太郎 on 2021/08/05.
//
import UIKit
class SettingsViewController: UIViewController {
private let tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
return tableView
}()
private var sections = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
confugureModels()
title = "Settings"
view.backgroundColor = UIColor.viewBackground
view.addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
}
private func confugureModels() {
sections = [
Section(title: "Profile", options: [Option(title: "View Your Profile", handler: { [weak self] in
DispatchQueue.main.async {
self?.viewProfile()
}
})]),
Section(title: "Account", options: [Option(title: "Sign Out", handler: { [weak self] in
DispatchQueue.main.async {
self?.signOutTapped()
}
})])
]
}
private func viewProfile() {
let vc = ProfileViewController()
vc.navigationItem.largeTitleDisplayMode = .never
navigationController?.pushViewController(vc, animated: true)
}
private func signOutTapped() {
let alert = UIAlertController(title: "Sign Out", message: "Are you sure?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Sign Out", style: .destructive, handler: { _ in
AuthManager.shared.signOut { [weak self] success in
if success {
DispatchQueue.main.async { [weak self] in
let navVC = NavigationController(rootViewController: WelcomeViewController())
navVC.navigationBar.prefersLargeTitles = true
navVC.viewControllers.first?.navigationItem.largeTitleDisplayMode = .always
navVC.modalPresentationStyle = .fullScreen
self?.present(navVC, animated: true) {
self?.navigationController?.popToRootViewController(animated: false)
}
}
}
}
}))
self.present(alert, animated: true, completion: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView.frame = view.bounds
}
}
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = sections[indexPath.section].options[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = model.title
return cell
}
}
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = sections[indexPath.section].options[indexPath.row]
model.handler()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
}
| 35.12844 | 108 | 0.611126 |
b9fd277e55320f135214cd04276aaf2b4575f077 | 660 | //
// CustomAnnotation.swift
// Spot
//
// Created by MacBook DS on 15/02/2020.
// Copyright © 2020 Djilali Sakkar. All rights reserved.
//
import UIKit
import MapKit
class CustomAnnotation: NSObject, MKAnnotation {
@objc dynamic var coordinate: CLLocationCoordinate2D
var creationDate: Date?
var uid: String?
var ownerId: String?
var publicSpot: Bool?
var creatorName: String?
var imageID: String?
var title: String?
var subtitle: String?
var image: UIImage?
var imageURL: String?
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
}
| 20.625 | 57 | 0.663636 |
ff27d4246db33116ba2dc0c9c880bb2650e438f0 | 614 | //
// UserImageView.swift
// Animation-HW
//
// Created by Eric Golovin on 6/18/20.
// Copyright © 2020 Eric Golovin. All rights reserved.
//
import UIKit
class UserImageView: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
configure()
}
private func configure() {
layer.cornerRadius = bounds.size.width / 2
clipsToBounds = true
}
}
| 19.1875 | 55 | 0.592834 |
0141c2c0e6363dd6e22de2bd61f1c7dd004f0717 | 12,287 | //
//
// CarouselViewExample
//
// Created by Matteo Tagliafico on 03/04/16.
// Copyright © 2016 Matteo Tagliafico. All rights reserved.
//
import UIKit
public enum CarouselType {
case normal
case threeDimensional
}
open class TGLParallaxCarouselItem: UIView {
var xDisp: CGFloat = 0
var zDisp: CGFloat = 0
}
@objc public protocol TGLParallaxCarouselDelegate {
func numberOfItemsInCarouselView(_ carouselView: TGLParallaxCarousel) -> Int
func carouselView(_ carouselView: TGLParallaxCarousel, itemForRowAtIndex index: Int) -> TGLParallaxCarouselItem
func carouselView(_ carouselView: TGLParallaxCarousel, didSelectItemAtIndex index: Int)
func carouselView(_ carouselView: TGLParallaxCarousel, willDisplayItem item: TGLParallaxCarouselItem, forIndex index: Int)
}
@IBDesignable
open class TGLParallaxCarousel: UIView {
// MARK: - outlets
@IBOutlet fileprivate weak var mainView: UIView!
@IBOutlet fileprivate weak var pageControl: UIPageControl!
// MARK: - properties
open weak var delegate: TGLParallaxCarouselDelegate? {
didSet {
reloadData()
}
}
open var type: CarouselType = .threeDimensional {
didSet {
reloadData()
}
}
open var margin: CGFloat = 0 {
didSet {
reloadData()
}
}
open var bounceMargin: CGFloat = 10 {
didSet {
reloadData()
}
}
fileprivate var backingSelectedIndex = -1
open var selectedIndex: Int {
get {
return backingSelectedIndex
}
set{
backingSelectedIndex = min(delegate!.numberOfItemsInCarouselView(self) - 1, max(0, newValue))
moveToIndex(selectedIndex)
}
}
fileprivate var containerView: UIView!
fileprivate let nibName = "TGLParallaxCarousel"
open var items = [TGLParallaxCarouselItem]()
fileprivate var itemWidth: CGFloat?
fileprivate var itemHeight: CGFloat?
fileprivate var isDecelerating = false
fileprivate var parallaxFactor: CGFloat {
if let _ = itemWidth { return ((itemWidth! + margin) / xDisplacement ) }
else { return 1}
}
var xDisplacement: CGFloat {
if type == .normal {
if let _ = itemWidth { return itemWidth! }
else { return 0 }
}
else if type == .threeDimensional { return 50 } // TODO
else { return 0 }
}
var zDisplacementFactor: CGFloat {
if type == .normal { return 0 }
else if type == .threeDimensional { return 1 }
else { return 0 }
}
fileprivate var startGesturePoint: CGPoint = .zero
fileprivate var endGesturePoint: CGPoint = .zero
fileprivate var startTapGesturePoint: CGPoint = .zero
fileprivate var endTapGesturePoint: CGPoint = .zero
fileprivate var currentGestureVelocity: CGFloat = 0
fileprivate var decelerationMultiplier: CGFloat = 25
fileprivate var loopFinished = false
fileprivate var currentTargetLayer: CALayer?
fileprivate var currentItem: TGLParallaxCarouselItem?
fileprivate var currentFoundItem: TGLParallaxCarouselItem?
// MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
containerView = loadViewFromNib()
containerView.frame = bounds
containerView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(containerView)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
// MARK: - view lifecycle
override open func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
setupGestures()
}
// MARK: - setup
fileprivate func setupGestures() {
let panGesture: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action:#selector(detectPan(_:)))
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(detectTap(_:)))
mainView.addGestureRecognizer(panGesture)
mainView.addGestureRecognizer(tapGesture)
}
func reloadData() {
guard let delegate = delegate else { return }
layoutIfNeeded()
pageControl.numberOfPages = delegate.numberOfItemsInCarouselView(self)
for index in 0..<delegate.numberOfItemsInCarouselView(self) {
addItem(delegate.carouselView(self, itemForRowAtIndex: index))
}
}
func addItem(_ item: TGLParallaxCarouselItem) {
if itemWidth == nil { itemWidth = item.frame.width }
if itemHeight == nil { itemHeight = item.frame.height }
item.center = mainView.center
self.mainView.layer.insertSublayer(item.layer, at: UInt32(self.items.count))
self.items.append(item)
self.resetItemsPosition(true)
}
fileprivate func resetItemsPosition(_ animated: Bool) {
guard items.count != 0 else { return }
for (index, item) in items.enumerated() {
CATransaction.begin()
CATransaction.setDisableActions(true)
let xDispNew = xDisplacement * CGFloat(index)
let zDispNew = round(-fabs(xDispNew) * zDisplacementFactor)
let translationX = CABasicAnimation(keyPath: "transform.translation.x")
translationX.fromValue = item.xDisp
translationX.toValue = xDispNew
let translationZ = CABasicAnimation(keyPath: "transform.translation.z")
translationZ.fromValue = item.zDisp
translationZ.toValue = zDispNew
let animationGroup = CAAnimationGroup()
animationGroup.duration = animated ? 0.33 : 0
animationGroup.repeatCount = 1
animationGroup.animations = [translationX, translationZ]
animationGroup.isRemovedOnCompletion = false
animationGroup.fillMode = kCAFillModeRemoved
animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
item.layer.add(animationGroup, forKey: "myAnimation")
var t = CATransform3DIdentity
t.m34 = -(1 / 500)
t = CATransform3DTranslate(t, xDispNew, 0.0, zDispNew)
item.layer.transform = t;
item.xDisp = xDispNew
item.zDisp = zDispNew
CATransaction.commit()
}
}
// MARK: - gestures handler
func detectPan(_ recognizer:UIPanGestureRecognizer) {
let targetView = recognizer.view
switch recognizer.state {
case .began:
startGesturePoint = recognizer.location(in: targetView)
currentGestureVelocity = 0
case .changed:
currentGestureVelocity = recognizer.velocity(in: targetView).x
endGesturePoint = recognizer.location(in: targetView)
let xOffset = (startGesturePoint.x - endGesturePoint.x ) * (1 / parallaxFactor)
moveCarousel(xOffset)
startGesturePoint = endGesturePoint
case .ended, .cancelled, .failed:
startDecelerating()
case.possible:
break
}
}
func detectTap(_ recognizer:UITapGestureRecognizer) {
let targetPoint: CGPoint = recognizer.location(in: recognizer.view)
currentTargetLayer = mainView.layer.hitTest(targetPoint)!
guard let targetItem = findItemOnScreen() else { return }
let firstItemOffset = (items.first?.xDisp ?? 0) - targetItem.xDisp
let tappedIndex = -Int(round(firstItemOffset / xDisplacement))
if targetItem.xDisp == 0 {
self.delegate?.carouselView(self, didSelectItemAtIndex: tappedIndex)
}
else {
selectedIndex = tappedIndex
}
}
// MARK: - find item
fileprivate func findItemOnScreen() -> TGLParallaxCarouselItem? {
currentFoundItem = nil
for item in items {
currentItem = item
checkInSubviews(item)
}
return currentFoundItem
}
fileprivate func checkInSubviews(_ view: UIView) {
let subviews = view.subviews
if subviews.isEmpty { return }
for subview : AnyObject in subviews {
if checkView(subview as! UIView) { return }
checkInSubviews(subview as! UIView)
}
}
fileprivate func checkView(_ view: UIView) -> Bool {
if view.layer.isEqual(currentTargetLayer) {
currentFoundItem = currentItem
return true
} else {
return false
}
}
// MARK: moving logic
func moveCarousel(_ offset: CGFloat) {
guard offset != 0 else { return }
var detected = false
for (index, item) in items.enumerated() {
// check bondaries
if (items.first?.xDisp)! >= bounceMargin {
detected = true
if offset < 0 {
if loopFinished { return }
}
}
if (items.last?.xDisp)! <= -bounceMargin {
detected = true
if offset > 0 {
if loopFinished { return }
}
}
item.xDisp = item.xDisp - offset
item.zDisp = -fabs(item.xDisp) * zDisplacementFactor
let factor = factorForXDisp(item.zDisp)
DispatchQueue.main.async() {
UIView.animate(withDuration: 0.33, animations: { () -> Void in
var t = CATransform3DIdentity
t.m34 = -(1 / 500)
item.layer.transform = CATransform3DTranslate(t, item.xDisp * factor , 0.0, item.zDisp)
})
}
loopFinished = (index == items.count - 1 && detected)
}
}
fileprivate func moveToIndex(_ index: Int) {
let offsetItems = items.first?.xDisp ?? 0
let offsetToAdd = xDisplacement * -CGFloat(selectedIndex) - offsetItems
moveCarousel(-offsetToAdd)
updatePageControl(selectedIndex)
delegate?.carouselView(self, didSelectItemAtIndex: selectedIndex)
}
fileprivate func factorForXDisp(_ x: CGFloat) -> CGFloat {
let pA = CGPoint(x : xDisplacement / 2,y : parallaxFactor)
let pB = CGPoint(x : xDisplacement,y: 1)
let m = (pB.y - pA.y) / (pB.x - pA.x)
let y = (pA.y - m * pA.x) + m * fabs(x)
switch fabs(x) {
case (xDisplacement / 2)..<xDisplacement:
return y
case 0..<(xDisplacement / 2):
return parallaxFactor
default:
return 1
}
}
// MARK: - utils
func startDecelerating() {
isDecelerating = true
let distance = decelerationDistance()
let offsetItems = items.first?.xDisp ?? 0
let endOffsetItems = offsetItems + distance
selectedIndex = -Int(round(endOffsetItems / xDisplacement))
isDecelerating = false
}
fileprivate func decelerationDistance() ->CGFloat {
let acceleration = -currentGestureVelocity * decelerationMultiplier
return (acceleration == 0) ? 0 : (-pow(currentGestureVelocity, 2.0) / (2.0 * acceleration))
}
// MARK: - page control handler
func updatePageControl(_ index: Int) {
pageControl.currentPage = index
}
}
| 31.914286 | 126 | 0.590299 |
5b360bf0ab95d3ca87b55ab531d866737dfb8f96 | 2,528 | //
// ArDefine.swift
// Arumdaun
//
// Created by chanick park on 6/23/17.
// Copyright © 2017 Chanick Park. All rights reserved.
//
import Foundation
// web page links --------------------------------------------------------------
let AR_MAIN_PAGE = "https://www.arumdaunchurch.org/"
// News web page
let NEWS_WEB_PAGE = AR_MAIN_PAGE + "%EA%B3%B5%EB%8F%99%EC%B2%B4%EC%99%80%EA%B5%90%EC%9C%A1/%EA%B5%90%ED%9A%8C%EC%86%8C%EC%8B%9D/" //공동체와교육/교회소식
// church news url, xml feed
// ex. https://www.arumdaunchurch.org/category/church-news/feed/?paged=1
let AR_NEWSFEED_URL = AR_MAIN_PAGE + "category/church-news/feed/"
// Daily QT webppage, first page
let SU_DAILY_QT_URL = "http://www.su.or.kr/03bible/daily/qtView.do?qtType=QT1"
let PRIVACY_POLICY_URL = AR_MAIN_PAGE + "privacy-policy"
// Youtube API ----------------------------------------------------------------
// arumdaunweb: "AIzaSyCa7dAbw2Oai90RvbOSpjNrLbwELK78r6M"//
// arumdaunmobile: "AIzaSyDZr8crx9oB6TgLY8P6s9iHGhmz0pK1FeM"//
let YT_API_KEY = "AIzaSyDZr8crx9oB6TgLY8P6s9iHGhmz0pK1FeM"
let YT_PLAYLIST_ITEM = "https://www.googleapis.com/youtube/v3/playlistItems"
let YT_SEARCH = "https://www.googleapis.com/youtube/v3/search"
let YT_LIVEVIDEO_CHANNEL_ID = "UC_SMi4TOmGvZnVb2SLpbGyw" // test, "UCHd62-u_v4DvJ8TCFtpi4GA" (government)
let YT_LIVEVIDEO_ID = "uod4YBW9Cv0"
// ex. https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC_SMi4TOmGvZnVb2SLpbGyw&eventType=live&type=video&key=AIzaSyCa7dAbw2Oai90RvbOSpjNrLbwELK78r6M
// https://www.youtube.com/embed/live_stream?channel=UC_SMi4TOmGvZnVb2SLpbGyw&autohide=2&showsearch=0&showinfo=1&iv_load_policy=1&wmode=transparent&wmode=opaque&wmode=opaque
// google drive for morning sermons ------------------------------------------
let GOOGLE_DRIVE_FILE_URL = "https://www.googleapis.com/drive/v3/files"
let GOOGLE_DRIVE_API_KEY = "AIzaSyCsXg_HV2dxmHKE53onhPwVZh_A5r0ZVu0"
let GOOGLE_DRIVE_QT_FOLDER_ID = "0B8tfjhHvC9vdfkR2ZnF1eHRKY0JHV2tyYXY0SlhnQnk0dGZfLXN6X0E5bkNkUXRPbllhem8"
let GOOGLE_DRIVE_VIEW_URL = "https://drive.google.com/file/d/"
let GOOGLE_DRIVE_DOWNLOAD_URL = "https://drive.google.com/uc?export=download&id="
// ex. download url : https://drive.google.com/uc?export=download&id=0B8tfjhHvC9vdd3hHbTNWMHJ2M00
// hockey app ----------------------------------------------------------------
let HOCKEYAPP_ID = "5865b525e1e4461b8d7d573ca105d7bc"
// OneSignal Id --------------------------------------------------------------
let ONESIGNAL_ID = "908b6d2c-7d75-4d3d-ad24-02904d8581a0"
| 47.698113 | 173 | 0.695807 |
f8bcbe5a7e01fbc3a9aec6396fb6cc735f5c8955 | 3,839 | //
// BasicSQLiteDBManager.swift
// BasicFramework
//
// Created by Nahla Mortada on 7/5/17.
// Copyright © 2017 Nahla Mortada. All rights reserved.
//
import Foundation
import FMDB
open class BasicSQLiteDBManager: BasicManager {
// MARK: - DB File Methods
public class func copyDatabaseIntoDocumentsDirectory(databseFileName: String) {
let paths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: String = paths[0]
let destinationPath: String = "\(documentsDirectory)/\(databseFileName)"
DispatchQueue.global(qos: .background).async {
if FileManager.default.fileExists(atPath: destinationPath) == false {
let fileNameComponents = databseFileName.components(separatedBy: ".")
if let sourcePath = Bundle.main.path(forResource: fileNameComponents[0], ofType: fileNameComponents[1]){
do {
(try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath))
print("[DB]", "Move From: \(sourcePath)")
print("[DB]", "Move To: \(destinationPath)")
}
catch {
print("[DB]", "[BF] : \(error.localizedDescription)")
}
}else {
print("[DB]", "sourcePath nil")
}
}
}
}
public class func removeFile(databseFileName: String) {
let paths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: String = paths[0]
let destinationPath: String = "\(documentsDirectory)/\(databseFileName)"
DispatchQueue.global(qos: .background).async {
if FileManager.default.fileExists(atPath: destinationPath) == false {
do {
try FileManager.default.removeItem(atPath: destinationPath)
}catch {
print("[DB]", "Could not clear temp folder: \(error)")
}
}
}
}
public class func getDBHelber(dbName: String) -> FMDatabase {
//TODOO
var paths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: String = paths[0]
let databasePath: String = URL(fileURLWithPath: documentsDirectory).appendingPathComponent(dbName).absoluteString
let helper: FMDatabase = FMDatabase(path: databasePath)
if !helper.open() {
print("[DB]", "[BF] : CAAAAAN not opned")
}
return helper
}
fileprivate class func copyDatabaseIntoDocumentsDirectory(dbName: String) {
copyDatabaseIntoDocumentsDirectory(databseFileName: dbName)
}
public class func selectAll(tableName: String) -> String {
return "select * from \(tableName)"
}
// MARK: - Select Methods
public class func getQueryObject(Id: Int, InTable tableName: String, primaryKey: String) -> String {
return "select * from \(tableName) where \(primaryKey) = \(Id)"
}
public class func getQueryObjects(tableName: String) -> String {
return "select * from \(tableName)"
}
// MARK: - Delete Methods
public class func deleteQuery(tableName: String, Id itemId: Int, primaryKey: String) -> String {
let query: String = "DELETE FROM \(tableName) WHERE \(primaryKey) = \(itemId)"
return query
}
public class func deleteAllQuery(tableName: String) -> String {
let query: String = "DELETE FROM \(tableName)"
return query
}
}
| 36.561905 | 121 | 0.593123 |
1cb964ee2604ed6c4203900b64d3b26ead8a2913 | 4,704 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of BrainCore. The full BrainCore copyright notice,
// including terms governing use, modification, and redistribution, is
// contained in the file LICENSE at the root of the source code distribution
// tree.
import Foundation
import Metal
import Upsurge
public class InnerProductLayer: BackwardLayer, TrainableLayer {
struct Parameters {
let batchSize: UInt16
let inputSize: UInt16
let outputSize: UInt16
}
public let name: String?
public let id = UUID()
public let weights: Matrix<Float>
public let biases: ValueArray<Float>
public var inputSize: Int {
return weights.rows
}
public var outputSize: Int {
return weights.columns
}
var weightsBuffer: Buffer?
var weightDeltasBuffer: Buffer?
var biasesBuffer: Buffer?
var biasDeltasBuffer: Buffer?
var forwardInvocation: Invocation?
var backwardParameterUpdateInvocation: Invocation?
var backwardInputUpdateInvocation: Invocation?
public var forwardInvocations: [Invocation] {
guard let forwardInvocation = forwardInvocation else {
fatalError("initializeForward needs to be called first")
}
return [forwardInvocation]
}
public var backwardInvocations: [Invocation] {
guard let backwardParameterUpdateInvocation = backwardParameterUpdateInvocation,
let backwardInputUpdateInvocation = backwardInputUpdateInvocation else {
fatalError("initializeBackward needs to be called first")
}
return [
backwardParameterUpdateInvocation,
backwardInputUpdateInvocation
]
}
public init(weights: Matrix<Float>, biases: ValueArray<Float>, name: String? = nil) {
self.name = name
self.weights = weights
self.biases = biases
precondition(biases.count == outputSize)
}
public func initializeForward(builder: ForwardInvocationBuilder, batchSize: Int) throws {
if weightsBuffer == nil {
weightsBuffer = builder.createBuffer(name: "weights", elements: weights)
}
if biasesBuffer == nil {
biasesBuffer = builder.createBuffer(name: "biases", elements: biases)
}
let buffers = [
builder.inputBuffer,
builder.outputBuffer,
weightsBuffer!,
biasesBuffer!
]
let params = Parameters(batchSize: UInt16(batchSize), inputSize: UInt16(inputSize), outputSize: UInt16(outputSize))
forwardInvocation = try builder.createInvocation(functionName: "inner_product_forward", buffers: buffers, values: [params], width: outputSize, height: batchSize)
}
public func initializeBackward(builder: BackwardInvocationBuilder, batchSize: Int) throws {
let params = Parameters(batchSize: UInt16(batchSize), inputSize: UInt16(inputSize), outputSize: UInt16(outputSize))
if weightsBuffer == nil {
weightsBuffer = builder.createBuffer(name: "weights", elements: weights)
}
if weightDeltasBuffer == nil {
weightDeltasBuffer = builder.createBuffer(name: "weightDeltas", size: weights.count * MemoryLayout<Float>.size)
}
if biasDeltasBuffer == nil {
biasDeltasBuffer = builder.createBuffer(name: "biasDeltas", size: biases.count * MemoryLayout<Float>.size)
}
let paramUpdateBuffers = [
builder.outputDeltasBuffer,
builder.inputBuffer,
weightDeltasBuffer!,
biasDeltasBuffer!
]
backwardParameterUpdateInvocation = try builder.createInvocation(functionName: "inner_product_backward_params", buffers: paramUpdateBuffers, values: [params], width: outputSize)
let inputUpdateBuffers = [
builder.outputDeltasBuffer,
builder.inputDeltasBuffer,
weightsBuffer!,
]
backwardInputUpdateInvocation = try builder.createInvocation(functionName: "inner_product_backward_input", buffers: inputUpdateBuffers, values: [params], width: inputSize, height: batchSize)
}
public func encodeParametersUpdate(_ encodeAction: (_ values: Buffer, _ deltas: Buffer) -> Void) {
guard let weightDeltasBuffer = weightDeltasBuffer else {
fatalError("Inner Product weights were not initialized")
}
guard let biasDeltasBuffer = biasDeltasBuffer else {
fatalError("Inner Product biases were not initialized")
}
encodeAction(weightsBuffer!, weightDeltasBuffer)
encodeAction(biasesBuffer!, biasDeltasBuffer)
}
}
| 37.333333 | 198 | 0.677083 |
61167e8da218b560d845377137583f5b84aacce9 | 21,094 | //
// MessageDefinition.swift
// HealthSoftware
//
// Generated from FHIR 4.5.0-a621ed4bdc (http://hl7.org/fhir/StructureDefinition/MessageDefinition)
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
A resource that defines a type of message that can be exchanged between systems.
Defines the characteristics of a message that can be shared between systems, including the type of event that initiates
the message, the content to be transmitted and what response(s), if any, are permitted.
Interfaces:
- CanonicalResource: http://hl7.org/fhir/StructureDefinition/CanonicalResource
*/
open class MessageDefinition: DomainResource {
override open class var resourceType: ResourceType { return .messageDefinition }
/// All possible types for "event[x]"
public enum EventX: Hashable {
case coding(Coding)
case uri(FHIRPrimitive<FHIRURI>)
}
/// Business Identifier for a given MessageDefinition
public var url: FHIRPrimitive<FHIRURI>?
/// Primary key for the message definition on a given server
public var identifier: [Identifier]?
/// Business version of the message definition
public var version: FHIRPrimitive<FHIRString>?
/// Name for this message definition (computer friendly)
public var name: FHIRPrimitive<FHIRString>?
/// Name for this message definition (human friendly)
public var title: FHIRPrimitive<FHIRString>?
/// Takes the place of
public var replaces: [FHIRPrimitive<Canonical>]?
/// The status of this message definition. Enables tracking the life-cycle of the content.
public var status: FHIRPrimitive<PublicationStatus>
/// For testing purposes, not real usage
public var experimental: FHIRPrimitive<FHIRBool>?
/// Date last changed
public var date: FHIRPrimitive<DateTime>
/// Name of the publisher (organization or individual)
public var publisher: FHIRPrimitive<FHIRString>?
/// Contact details for the publisher
public var contact: [ContactDetail]?
/// Natural language description of the message definition
public var description_fhir: FHIRPrimitive<FHIRString>?
/// The context that the content is intended to support
public var useContext: [UsageContext]?
/// Intended jurisdiction for message definition (if applicable)
public var jurisdiction: [CodeableConcept]?
/// Why this message definition is defined
public var purpose: FHIRPrimitive<FHIRString>?
/// Use and/or publishing restrictions
public var copyright: FHIRPrimitive<FHIRString>?
/// Definition this one is based on
public var base: FHIRPrimitive<Canonical>?
/// Protocol/workflow this is part of
public var parent: [FHIRPrimitive<Canonical>]?
/// Event code or link to the EventDefinition
/// One of `event[x]`
public var event: EventX
/// The impact of the content of the message.
public var category: FHIRPrimitive<MessageSignificanceCategory>?
/// Resource(s) that are the subject of the event
public var focus: [MessageDefinitionFocus]?
/// Declare at a message definition level whether a response is required or only upon error or success, or never.
public var responseRequired: FHIRPrimitive<MessageheaderResponseRequest>?
/// Responses to this message
public var allowedResponse: [MessageDefinitionAllowedResponse]?
/// Canonical reference to a GraphDefinition
public var graph: [FHIRPrimitive<Canonical>]?
/// Designated initializer taking all required properties
public init(date: FHIRPrimitive<DateTime>, event: EventX, status: FHIRPrimitive<PublicationStatus>) {
self.date = date
self.event = event
self.status = status
super.init()
}
/// Convenience initializer
public convenience init(
allowedResponse: [MessageDefinitionAllowedResponse]? = nil,
base: FHIRPrimitive<Canonical>? = nil,
category: FHIRPrimitive<MessageSignificanceCategory>? = nil,
contact: [ContactDetail]? = nil,
contained: [ResourceProxy]? = nil,
copyright: FHIRPrimitive<FHIRString>? = nil,
date: FHIRPrimitive<DateTime>,
description_fhir: FHIRPrimitive<FHIRString>? = nil,
event: EventX,
experimental: FHIRPrimitive<FHIRBool>? = nil,
`extension`: [Extension]? = nil,
focus: [MessageDefinitionFocus]? = nil,
graph: [FHIRPrimitive<Canonical>]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
identifier: [Identifier]? = nil,
implicitRules: FHIRPrimitive<FHIRURI>? = nil,
jurisdiction: [CodeableConcept]? = nil,
language: FHIRPrimitive<FHIRString>? = nil,
meta: Meta? = nil,
modifierExtension: [Extension]? = nil,
name: FHIRPrimitive<FHIRString>? = nil,
parent: [FHIRPrimitive<Canonical>]? = nil,
publisher: FHIRPrimitive<FHIRString>? = nil,
purpose: FHIRPrimitive<FHIRString>? = nil,
replaces: [FHIRPrimitive<Canonical>]? = nil,
responseRequired: FHIRPrimitive<MessageheaderResponseRequest>? = nil,
status: FHIRPrimitive<PublicationStatus>,
text: Narrative? = nil,
title: FHIRPrimitive<FHIRString>? = nil,
url: FHIRPrimitive<FHIRURI>? = nil,
useContext: [UsageContext]? = nil,
version: FHIRPrimitive<FHIRString>? = nil)
{
self.init(date: date, event: event, status: status)
self.allowedResponse = allowedResponse
self.base = base
self.category = category
self.contact = contact
self.contained = contained
self.copyright = copyright
self.description_fhir = description_fhir
self.experimental = experimental
self.`extension` = `extension`
self.focus = focus
self.graph = graph
self.id = id
self.identifier = identifier
self.implicitRules = implicitRules
self.jurisdiction = jurisdiction
self.language = language
self.meta = meta
self.modifierExtension = modifierExtension
self.name = name
self.parent = parent
self.publisher = publisher
self.purpose = purpose
self.replaces = replaces
self.responseRequired = responseRequired
self.text = text
self.title = title
self.url = url
self.useContext = useContext
self.version = version
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case allowedResponse
case base; case _base
case category; case _category
case contact
case copyright; case _copyright
case date; case _date
case description_fhir = "description"; case _description_fhir = "_description"
case eventCoding
case eventUri; case _eventUri
case experimental; case _experimental
case focus
case graph; case _graph
case identifier
case jurisdiction
case name; case _name
case parent; case _parent
case publisher; case _publisher
case purpose; case _purpose
case replaces; case _replaces
case responseRequired; case _responseRequired
case status; case _status
case title; case _title
case url; case _url
case useContext
case version; case _version
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Validate that we have at least one of the mandatory properties for expanded properties
guard _container.contains(CodingKeys.eventCoding) || _container.contains(CodingKeys.eventUri) else {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: [CodingKeys.eventCoding, CodingKeys.eventUri], debugDescription: "Must have at least one value for \"event\" but have none"))
}
// Decode all our properties
self.allowedResponse = try [MessageDefinitionAllowedResponse](from: _container, forKeyIfPresent: .allowedResponse)
self.base = try FHIRPrimitive<Canonical>(from: _container, forKeyIfPresent: .base, auxiliaryKey: ._base)
self.category = try FHIRPrimitive<MessageSignificanceCategory>(from: _container, forKeyIfPresent: .category, auxiliaryKey: ._category)
self.contact = try [ContactDetail](from: _container, forKeyIfPresent: .contact)
self.copyright = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .copyright, auxiliaryKey: ._copyright)
self.date = try FHIRPrimitive<DateTime>(from: _container, forKey: .date, auxiliaryKey: ._date)
self.description_fhir = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .description_fhir, auxiliaryKey: ._description_fhir)
var _t_event: EventX? = nil
if let eventCoding = try Coding(from: _container, forKeyIfPresent: .eventCoding) {
if _t_event != nil {
throw DecodingError.dataCorruptedError(forKey: .eventCoding, in: _container, debugDescription: "More than one value provided for \"event\"")
}
_t_event = .coding(eventCoding)
}
if let eventUri = try FHIRPrimitive<FHIRURI>(from: _container, forKeyIfPresent: .eventUri, auxiliaryKey: ._eventUri) {
if _t_event != nil {
throw DecodingError.dataCorruptedError(forKey: .eventUri, in: _container, debugDescription: "More than one value provided for \"event\"")
}
_t_event = .uri(eventUri)
}
self.event = _t_event!
self.experimental = try FHIRPrimitive<FHIRBool>(from: _container, forKeyIfPresent: .experimental, auxiliaryKey: ._experimental)
self.focus = try [MessageDefinitionFocus](from: _container, forKeyIfPresent: .focus)
self.graph = try [FHIRPrimitive<Canonical>](from: _container, forKeyIfPresent: .graph, auxiliaryKey: ._graph)
self.identifier = try [Identifier](from: _container, forKeyIfPresent: .identifier)
self.jurisdiction = try [CodeableConcept](from: _container, forKeyIfPresent: .jurisdiction)
self.name = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .name, auxiliaryKey: ._name)
self.parent = try [FHIRPrimitive<Canonical>](from: _container, forKeyIfPresent: .parent, auxiliaryKey: ._parent)
self.publisher = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .publisher, auxiliaryKey: ._publisher)
self.purpose = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .purpose, auxiliaryKey: ._purpose)
self.replaces = try [FHIRPrimitive<Canonical>](from: _container, forKeyIfPresent: .replaces, auxiliaryKey: ._replaces)
self.responseRequired = try FHIRPrimitive<MessageheaderResponseRequest>(from: _container, forKeyIfPresent: .responseRequired, auxiliaryKey: ._responseRequired)
self.status = try FHIRPrimitive<PublicationStatus>(from: _container, forKey: .status, auxiliaryKey: ._status)
self.title = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .title, auxiliaryKey: ._title)
self.url = try FHIRPrimitive<FHIRURI>(from: _container, forKeyIfPresent: .url, auxiliaryKey: ._url)
self.useContext = try [UsageContext](from: _container, forKeyIfPresent: .useContext)
self.version = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .version, auxiliaryKey: ._version)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try allowedResponse?.encode(on: &_container, forKey: .allowedResponse)
try base?.encode(on: &_container, forKey: .base, auxiliaryKey: ._base)
try category?.encode(on: &_container, forKey: .category, auxiliaryKey: ._category)
try contact?.encode(on: &_container, forKey: .contact)
try copyright?.encode(on: &_container, forKey: .copyright, auxiliaryKey: ._copyright)
try date.encode(on: &_container, forKey: .date, auxiliaryKey: ._date)
try description_fhir?.encode(on: &_container, forKey: .description_fhir, auxiliaryKey: ._description_fhir)
switch event {
case .coding(let _value):
try _value.encode(on: &_container, forKey: .eventCoding)
case .uri(let _value):
try _value.encode(on: &_container, forKey: .eventUri, auxiliaryKey: ._eventUri)
}
try experimental?.encode(on: &_container, forKey: .experimental, auxiliaryKey: ._experimental)
try focus?.encode(on: &_container, forKey: .focus)
try graph?.encode(on: &_container, forKey: .graph, auxiliaryKey: ._graph)
try identifier?.encode(on: &_container, forKey: .identifier)
try jurisdiction?.encode(on: &_container, forKey: .jurisdiction)
try name?.encode(on: &_container, forKey: .name, auxiliaryKey: ._name)
try parent?.encode(on: &_container, forKey: .parent, auxiliaryKey: ._parent)
try publisher?.encode(on: &_container, forKey: .publisher, auxiliaryKey: ._publisher)
try purpose?.encode(on: &_container, forKey: .purpose, auxiliaryKey: ._purpose)
try replaces?.encode(on: &_container, forKey: .replaces, auxiliaryKey: ._replaces)
try responseRequired?.encode(on: &_container, forKey: .responseRequired, auxiliaryKey: ._responseRequired)
try status.encode(on: &_container, forKey: .status, auxiliaryKey: ._status)
try title?.encode(on: &_container, forKey: .title, auxiliaryKey: ._title)
try url?.encode(on: &_container, forKey: .url, auxiliaryKey: ._url)
try useContext?.encode(on: &_container, forKey: .useContext)
try version?.encode(on: &_container, forKey: .version, auxiliaryKey: ._version)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? MessageDefinition else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return allowedResponse == _other.allowedResponse
&& base == _other.base
&& category == _other.category
&& contact == _other.contact
&& copyright == _other.copyright
&& date == _other.date
&& description_fhir == _other.description_fhir
&& event == _other.event
&& experimental == _other.experimental
&& focus == _other.focus
&& graph == _other.graph
&& identifier == _other.identifier
&& jurisdiction == _other.jurisdiction
&& name == _other.name
&& parent == _other.parent
&& publisher == _other.publisher
&& purpose == _other.purpose
&& replaces == _other.replaces
&& responseRequired == _other.responseRequired
&& status == _other.status
&& title == _other.title
&& url == _other.url
&& useContext == _other.useContext
&& version == _other.version
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(allowedResponse)
hasher.combine(base)
hasher.combine(category)
hasher.combine(contact)
hasher.combine(copyright)
hasher.combine(date)
hasher.combine(description_fhir)
hasher.combine(event)
hasher.combine(experimental)
hasher.combine(focus)
hasher.combine(graph)
hasher.combine(identifier)
hasher.combine(jurisdiction)
hasher.combine(name)
hasher.combine(parent)
hasher.combine(publisher)
hasher.combine(purpose)
hasher.combine(replaces)
hasher.combine(responseRequired)
hasher.combine(status)
hasher.combine(title)
hasher.combine(url)
hasher.combine(useContext)
hasher.combine(version)
}
}
/**
Responses to this message.
Indicates what types of messages may be sent as an application-level response to this message.
*/
open class MessageDefinitionAllowedResponse: BackboneElement {
/// Reference to allowed message definition response
public var message: FHIRPrimitive<Canonical>
/// When should this response be used
public var situation: FHIRPrimitive<FHIRString>?
/// Designated initializer taking all required properties
public init(message: FHIRPrimitive<Canonical>) {
self.message = message
super.init()
}
/// Convenience initializer
public convenience init(
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
message: FHIRPrimitive<Canonical>,
modifierExtension: [Extension]? = nil,
situation: FHIRPrimitive<FHIRString>? = nil)
{
self.init(message: message)
self.`extension` = `extension`
self.id = id
self.modifierExtension = modifierExtension
self.situation = situation
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case message; case _message
case situation; case _situation
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.message = try FHIRPrimitive<Canonical>(from: _container, forKey: .message, auxiliaryKey: ._message)
self.situation = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .situation, auxiliaryKey: ._situation)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try message.encode(on: &_container, forKey: .message, auxiliaryKey: ._message)
try situation?.encode(on: &_container, forKey: .situation, auxiliaryKey: ._situation)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? MessageDefinitionAllowedResponse else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return message == _other.message
&& situation == _other.situation
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(message)
hasher.combine(situation)
}
}
/**
Resource(s) that are the subject of the event.
Identifies the resource (or resources) that are being addressed by the event. For example, the Encounter for an admit
message or two Account records for a merge.
*/
open class MessageDefinitionFocus: BackboneElement {
/// The kind of resource that must be the focus for this message.
public var code: FHIRPrimitive<ResourceType>
/// Profile that must be adhered to by focus
public var profile: FHIRPrimitive<Canonical>?
/// Minimum number of focuses of this type
public var min: FHIRPrimitive<FHIRUnsignedInteger>
/// Maximum number of focuses of this type
public var max: FHIRPrimitive<FHIRString>?
/// Designated initializer taking all required properties
public init(code: FHIRPrimitive<ResourceType>, min: FHIRPrimitive<FHIRUnsignedInteger>) {
self.code = code
self.min = min
super.init()
}
/// Convenience initializer
public convenience init(
code: FHIRPrimitive<ResourceType>,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
max: FHIRPrimitive<FHIRString>? = nil,
min: FHIRPrimitive<FHIRUnsignedInteger>,
modifierExtension: [Extension]? = nil,
profile: FHIRPrimitive<Canonical>? = nil)
{
self.init(code: code, min: min)
self.`extension` = `extension`
self.id = id
self.max = max
self.modifierExtension = modifierExtension
self.profile = profile
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case code; case _code
case max; case _max
case min; case _min
case profile; case _profile
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.code = try FHIRPrimitive<ResourceType>(from: _container, forKey: .code, auxiliaryKey: ._code)
self.max = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .max, auxiliaryKey: ._max)
self.min = try FHIRPrimitive<FHIRUnsignedInteger>(from: _container, forKey: .min, auxiliaryKey: ._min)
self.profile = try FHIRPrimitive<Canonical>(from: _container, forKeyIfPresent: .profile, auxiliaryKey: ._profile)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try code.encode(on: &_container, forKey: .code, auxiliaryKey: ._code)
try max?.encode(on: &_container, forKey: .max, auxiliaryKey: ._max)
try min.encode(on: &_container, forKey: .min, auxiliaryKey: ._min)
try profile?.encode(on: &_container, forKey: .profile, auxiliaryKey: ._profile)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? MessageDefinitionFocus else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return code == _other.code
&& max == _other.max
&& min == _other.min
&& profile == _other.profile
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(code)
hasher.combine(max)
hasher.combine(min)
hasher.combine(profile)
}
}
| 38.075812 | 206 | 0.733479 |
bf4d8e4669e95a1d664ee994bf522efb14275caf | 829 | //
// RsrcUnitTests.swift
// RsrcUnitTests
//
// Created by Marios Kotsiandris on 14/12/2019.
//
import XCTest
class RsrcUnitTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.121212 | 111 | 0.646562 |
280d205034f5af0b8dcb4f67d63639914c8bd156 | 243 | //
// FactoryPlaceholderCell.swift
// SimplePaginatedList
//
// Created by Kevin Dion on 2020-09-19.
// Copyright © 2020 Kevin Dion. All rights reserved.
//
import Foundation
import UIKit
class FactoryPlaceholderCell: UITableViewCell {}
| 18.692308 | 53 | 0.748971 |
ab1dd931d59f302ad4ab9f7be33bcf0c31f4f268 | 3,868 | import Foundation
/// Builds a look-up table for `sin(x)` and `cos(x)`, in the real line,
/// using *dynamic sampling* and *cubic* interpolation.
public struct CubicTrigTable <T: BinaryFloatingPoint> {
/// The lower end of the canonical interval `[0, pi/2]` for which to build the look-up table.
public let a: T = .zero
/// The upper end of the canonical interval `[0, pi/2]` for which to build the look-up table.
public let b: T = 0.5 * .pi
/// The smallest acceptable value of the increment in the independent value `x`.
/// Note that `dxMin` must satisfy the conditions `dxMax > dxMin > 0`.
public let dxMin: T
/// The largest acceptable value of the increment in the independent value `x`.
/// Note that `dxMax` must satisfy the conditions `dxMax > dxMin > 0`.
public let dxMax: T
/// The desired precision for the values of `sin(x)` and `cos(x)`.
/// Note that `df` must satisfy the condition `df > 0`.
public let df: T
/// Convenience value.
public let piOver2 = 0.5 * T.pi
/// Convenience value.
public let pi = T.pi
/// Convenience value.
public let threePiOver2 = 1.5 * T.pi
/// Convenience value.
public let twoPi = 2.0 * T.pi
/// The number of values stored in the table.
public var size: Int { sinTable.size }
/// Returns the value of `sin(x)` by retrieving it from the table, if it exists there,
/// or computes it by interpolating between the two values in the table that bracket
/// the argument `x`.
///
/// - Parameter x:
/// The value for which to retrieve or compute `sin(x)`.
///
/// - Returns:
/// The retrieved or computed value of `sin(x)`.
///
public func sin(_ x: T) -> T {
guard x >= 0 else { return -sin(-x) }
guard x != .zero && x != self.pi && x != self.twoPi else { return .zero }
guard x != self.piOver2 else { return 1 }
guard x != self.threePiOver2 else { return -1 }
if x < self.piOver2 {
return sinTable.f(x)
} else if x < self.pi {
return sin(self.pi - x)
} else if x < self.twoPi {
return -sin(x - self.pi)
} else {
return sin( x.truncatingRemainder(dividingBy: self.twoPi) )
}
}
/// Returns the value of `cos(x)` using the identity `cos(x) = sin(x + pi/2)`.
///
/// - Parameter x:
/// The value for which to retrieve or compute `cos(x)`.
///
/// - Returns:
/// The retrieved or computed value of `cos(x)`.
///
public func cos(_ x: T) -> T {
sin(x + self.piOver2)
}
/// Initialises a look-up table for `sin(x)` and `cos(x)`.
///
/// - Parameters:
///
/// - dxMin:
/// The smallest acceptable value of the increment in the independent value `x`.
/// Note that `dxMin` must satisfy the conditions `dxMax > dxMin > 0`.
///
/// - dxMax:
/// The largest acceptable value of the increment in the independent value `x`.
/// Note that `dxMax` must satisfy the conditions `dxMax > dxMin > 0`.
///
/// - df:
/// The desired precision for the values of `sin(x)` and `cos(x)`.
/// Note that `df` must satisfy the condition `df > 0`.
///
public init?(dxMin: T, dxMax: T, df: T) {
guard dxMin > 0 else { return nil }
guard dxMax > dxMin else { return nil }
guard df > 0 else { return nil }
self.dxMin = dxMin
self.dxMax = dxMax
self.df = df
self.sinTable = CubicLookupTable<T>(
a: .zero,
b: 0.5 * .pi,
dxMin: dxMin,
dxMax: dxMax,
df: df,
f: { (x: T) in T(Darwin.sin(Double(x))) },
fp: { (x: T) in T(Darwin.cos(Double(x))) }
)!
}
private let sinTable: CubicLookupTable<T>
}
| 32.233333 | 97 | 0.561789 |
5d243b07be461f0b7866a2bf4011392b2ed4b343 | 479 | //
// UserDefaultsHelper.swift
// FirebaseSDK Issues
//
// Created by Shyam Kumar on 29/06/19.
// Copyright © 2019 Shyam Kumar. All rights reserved.
//
import Foundation
extension UserDefaults {
static var lastUpdatedTime: Date? {
set {
standard.set(newValue, forKey: "LastUpdatedTime")
standard.synchronize()
}
get {
return standard.object(forKey: "LastUpdatedTime") as? Date
}
}
}
| 19.958333 | 70 | 0.592902 |
acd90001d4af9d5720d0a603ccbe83c1225645f5 | 256 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if{struct e{class a}enum S{struct S<T:T.h
| 36.571429 | 87 | 0.75 |
d6420f11cb75c8d5d63741302789e1a34ecdb2d6 | 980 | //
// CommentService.swift
// Photostream
//
// Created by Mounir Ybanez on 08/08/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import Foundation
protocol CommentService {
init(session: AuthSession)
func fetchComments(postId: String, offset: String, limit: UInt, callback: ((CommentServiceResult) -> Void)?)
func writeComment(postId: String, message: String, callback: ((CommentServiceResult) -> Void)?)
}
struct CommentServiceResult {
var comments: CommentList?
var error: CommentServiceError?
var nextOffset: String?
}
enum CommentServiceError: Error {
case authenticationNotFound(message: String)
case failedToFetch(message: String)
case failedToWrite(message: String)
var message: String {
switch self {
case .authenticationNotFound(let message),
.failedToFetch(let message),
.failedToWrite(let message):
return message
}
}
}
| 23.902439 | 112 | 0.673469 |
9156dc070a4b953b3a1da0c54949b5ff2c78eac9 | 765 | //
// MainViewController.swift
// PLPlayerDemo
//
// Created by 卢卓桓 on 2019/8/8.
// Copyright © 2019 zhineng. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
//加入子控制器
addChildVc(storyBoardName: "Live")
addChildVc(storyBoardName: "ShortVideo")
addChildVc(storyBoardName: "LongVideo")
}
/// 通过storyboard拿到控制器,并作为初始控制器的子控制器
private func addChildVc(storyBoardName: String){
//1.通过storyboard拿到控制器
let childVc = UIStoryboard(name: storyBoardName, bundle: nil)
.instantiateInitialViewController()!
//2.将拿到的控制器作为子控制器
addChild(childVc);
}
}
| 23.181818 | 69 | 0.631373 |
67318bb0dc5861c3126413c2839f9f91930ca56d | 157 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(VersionTests.allTests),
]
}
#endif
| 15.7 | 45 | 0.66879 |
290edb07010d096854dc18230bdc88c8ef77ce5b | 750 | import XCTest
import SYABasicUIKit
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.862069 | 111 | 0.602667 |
38310fb14aa9d6aa1f6f1027871f86c29773cf0c | 965 | //
// StripeLayerOptions.swift
// QSwift
//
// Created by QDong on 2021/9/26.
//
//
import UIKit
open class StripeLayerOptions: NSObject {
/// 条纹颜色
/// Color of the shapes. Defaults to gray.
open var color = UIColor.lightGray
/// 如果不倾斜,那么gapWidth 和 barWidth相同比较好看,如果倾斜,建议gapWidth是barWidth的两倍左右
/// Width of the bar
open var barWidth: CGFloat = 8
/// 间距宽度
/// Gap between bars
open var gapWidth: CGFloat = 8
/// 滚动方向
/// Direction
open var moveToRight: Bool = true
/// 滚动速度
/// Speed of the animation
open var speed: Float = 2
/// 倾斜角度, 3/4 = 45 度
/// Rotation of the shapes, 3/4 = 45 degree
open var rotation: CGFloat = CGFloat(Double.pi * 3.5 / 4)
/// 渐变透明度
/// Gradient alpha of the shapes.
open var gradientColors: [CGColor] = [UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0).cgColor]
}
| 22.97619 | 151 | 0.602073 |
67331b0ff34111fc2fcb56bb423d60be28d8b721 | 570 | //
// Created by Jim van Zummeren on 28/04/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import XCTest
@testable import markymark
class HeaderMarkDownItemTests: XCTestCase {
private var sut:HeaderMarkDownItem!
override func setUp() {
super.setUp()
sut = HeaderMarkDownItem(lines: ["Line one"], content: "Line one", level: 1)
}
func testMarkDownItemHasCorrectText(){
XCTAssertEqual(sut.content, "Line one")
}
func testMarkDownItemHasCorrectLines(){
XCTAssertEqual(sut.lines, ["Line one"])
}
} | 21.923077 | 84 | 0.666667 |
ff93310f0717f2530e1eb366b336ec1a6d4b55f4 | 2,295 | //
// SceneDelegate.swift
// The Weather App
//
// Created by Macbook_Pro on 2/9/22.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.301887 | 147 | 0.712854 |
23f7f347adb60d637c60486471ff11f322bbd5ee | 545 | //
// UIRefreshControl+Ext.swift
// Adequate
//
// Created by Mathew Gacy on 8/22/19.
// Copyright © 2019 Mathew Gacy. All rights reserved.
//
import UIKit
public extension UIRefreshControl {
/// Allow programmatic refresh
/// https://stackoverflow.com/a/14719658/4472195
func programaticallyBeginRefreshing(in tableView: UITableView) {
tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentOffset.y - frame.size.height), animated: true)
beginRefreshing()
sendActions(for: .valueChanged)
}
}
| 27.25 | 115 | 0.702752 |
bf03b9462508ae8ed2f2a047a95baf6b5dce667f | 2,686 | //
// AppDelegate.swift
// DanTang
//
// Created by 徐乐源 on 2017/3/24.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// 创建 window
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
// 检测用户是不是第一次启动
// if !UserDefaults.standard.bool(forKey: YMFirstLaunch) {
// window?.rootViewController = YMNewfeatureViewController()
// UserDefaults.standard.set(true, forKey: YMFirstLaunch)
// } else {
window?.rootViewController = YMTabBarController()
// window?.rootViewController = YMTabBarController()
// }
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:.
}
}
| 44.032787 | 285 | 0.721519 |
e57dbf02f2151e89377b45d0e7a790475c3151f4 | 3,490 | //
// YelpClient.swift
// Yelp
//
// Created by Timothy Lee on 9/19/14.
// Copyright (c) 2014 Timothy Lee. All rights reserved.
//
import UIKit
import AFNetworking
import BDBOAuth1Manager
// You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys
let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA"
let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ"
let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV"
let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y"
enum YelpSortMode: Int {
case bestMatched = 0, distance, highestRated
}
class YelpClient: BDBOAuth1RequestOperationManager {
var accessToken: String!
var accessSecret: String!
//MARK: Shared Instance
static let sharedInstance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) {
self.accessToken = accessToken
self.accessSecret = accessSecret
let baseUrl = URL(string: "https://api.yelp.com/v2/")
super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret);
let token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
func searchWithTerm(_ term: String, completion: @escaping ([Business]?, Error?) -> Void) -> AFHTTPRequestOperation {
return searchWithTerm(term, sort: nil, categories: nil, deals: nil, offset: nil, completion: completion)
}
func searchWithTerm(_ term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, offset: NSInteger?, completion: @escaping ([Business]?, Error?) -> Void) -> AFHTTPRequestOperation {
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// Default the location to San Francisco
var parameters: [String : AnyObject] = ["term": term as AnyObject, "ll": "37.785771,-122.406165" as AnyObject]
if sort != nil {
parameters["sort"] = sort!.rawValue as AnyObject?
}
if offset != nil {
parameters["offset"] = offset as AnyObject?
}
if categories != nil && categories!.count > 0 {
parameters["category_filter"] = (categories!).joined(separator: ",") as AnyObject?
}
if deals != nil {
parameters["deals_filter"] = deals! as AnyObject?
}
print(parameters)
return self.get("search", parameters: parameters,
success: { (operation: AFHTTPRequestOperation, response: Any) -> Void in
if let response = response as? [String: Any]{
let dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
}
}
},
failure: { (operation: AFHTTPRequestOperation?, error: Error) -> Void in
completion(nil, error)
})!
}
}
| 39.659091 | 198 | 0.610888 |
385835d9aba630ec240afc09567fffbb3bc8badc | 1,208 | //
// CellModelSection.swift
// CellKit-iOS
//
// Created by Petr Zvoníček on 08.06.18.
// Copyright © 2018 FUNTASTY Digital, s.r.o. All rights reserved.
//
import Foundation
public typealias CellModelSection = GenericCellModelSection<CellModel>
public struct GenericCellModelSection<Cell>: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Cell
public var cells: [Cell]
public var headerView: SupplementaryViewModel?
public var footerView: SupplementaryViewModel?
public let identifier: String
public init(cells: [Cell] = [], headerView: SupplementaryViewModel? = nil, footerView: SupplementaryViewModel? = nil, identifier: String = "") {
self.cells = cells
self.headerView = headerView
self.footerView = footerView
self.identifier = identifier
}
public init(arrayLiteral elements: Cell...) {
self.init(cells: elements)
}
public var isEmpty: Bool {
return cells.isEmpty
}
}
extension GenericCellModelSection: Equatable {
public static func == (lhs: GenericCellModelSection<Cell>, rhs: GenericCellModelSection<Cell>) -> Bool {
return lhs.identifier == rhs.identifier
}
}
| 28.761905 | 148 | 0.70447 |
7575ebc9cac98098f4987805efc0760065a08fc7 | 21,916 | //
// PasswordEditorTableViewController.swift
// pass
//
// Created by Mingshen Sun on 12/2/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import UIKit
import SafariServices
import OneTimePassword
import passKit
enum PasswordEditorCellType: Equatable {
case nameCell
case fillPasswordCell
case passwordLengthCell
case passwordUseDigitsCell
case passwordVaryCasesCell
case passwordUseSpecialSymbols
case passwordGroupsCell
case additionsCell
case deletePasswordCell
case scanQRCodeCell
case passwordFlavorCell
}
enum PasswordEditorCellKey {
case type, title, content, placeholders
}
protocol PasswordSettingSliderTableViewCellDelegate {
func generateAndCopyPassword()
}
class PasswordEditorTableViewController: UITableViewController {
var tableData = [[Dictionary<PasswordEditorCellKey, Any>]]()
var password: Password?
private var navigationItemTitle: String?
private var sectionHeaderTitles = ["Name".localize(), "Password".localize(), "Additions".localize(),""].map {$0.uppercased()}
private var sectionFooterTitles = ["", "", "UseKeyValueFormat.".localize(), ""]
private let nameSection = 0
private let passwordSection = 1
private let additionsSection = 2
private var hidePasswordSettings = true
private var passwordGenerator: PasswordGenerator = Defaults.passwordGenerator
var nameCell: TextFieldTableViewCell?
var fillPasswordCell: FillPasswordTableViewCell?
var additionsCell: TextViewTableViewCell?
private var deletePasswordCell: UITableViewCell?
private var scanQRCodeCell: UITableViewCell?
private var passwordFlavorCell: UITableViewCell?
var plainText: String {
var plainText = (fillPasswordCell?.getContent())!
if let additionsString = additionsCell?.getContent(), !additionsString.isEmpty {
plainText.append("\n")
plainText.append(additionsString)
}
if !plainText.trimmingCharacters(in: .whitespaces).hasSuffix("\n") {
plainText.append("\n")
}
return plainText
}
override func loadView() {
super.loadView()
deletePasswordCell = UITableViewCell(style: .default, reuseIdentifier: "default")
deletePasswordCell!.textLabel?.text = "DeletePassword".localize()
deletePasswordCell!.textLabel?.textColor = Colors.systemRed
deletePasswordCell?.selectionStyle = .default
scanQRCodeCell = UITableViewCell(style: .default, reuseIdentifier: "default")
scanQRCodeCell?.textLabel?.text = "AddOneTimePassword".localize()
scanQRCodeCell?.selectionStyle = .default
scanQRCodeCell?.accessoryType = .disclosureIndicator
passwordFlavorCell = UITableViewCell(style: .default, reuseIdentifier: "default")
passwordFlavorCell?.textLabel?.text = "PasswordGeneratorFlavor".localize()
passwordFlavorCell?.selectionStyle = .none
let passwordFlavorSelector = UISegmentedControl(items: PasswordGeneratorFlavor.allCases.map { $0.localized })
passwordFlavorSelector.selectedSegmentIndex = PasswordGeneratorFlavor.allCases.firstIndex(of: passwordGenerator.flavor)!
passwordFlavorSelector.addTarget(self, action: #selector(flavorChanged), for: .valueChanged)
passwordFlavorCell?.accessoryView = passwordFlavorSelector
}
override func viewDidLoad() {
super.viewDidLoad()
if navigationItemTitle != nil {
navigationItem.title = navigationItemTitle
}
tableView.register(UINib(nibName: "TextFieldTableViewCell", bundle: nil), forCellReuseIdentifier: "textFieldCell")
tableView.register(UINib(nibName: "TextViewTableViewCell", bundle: nil), forCellReuseIdentifier: "textViewCell")
tableView.register(UINib(nibName: "FillPasswordTableViewCell", bundle: nil), forCellReuseIdentifier: "fillPasswordCell")
tableView.register(UINib(nibName: "SliderTableViewCell", bundle: nil), forCellReuseIdentifier: "sliderCell")
tableView.register(UINib(nibName: "SwitchTableViewCell", bundle: nil), forCellReuseIdentifier: "switchCell")
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 48
tableView.sectionFooterHeight = UITableView.automaticDimension
tableView.estimatedSectionFooterHeight = 0
tableData = [
[
[.type: PasswordEditorCellType.nameCell, .title: "Name".localize(), .content: password?.namePath ?? ""],
],
[
[.type: PasswordEditorCellType.fillPasswordCell, .title: "Password".localize(), .content: password?.password ?? ""],
[.type: PasswordEditorCellType.passwordFlavorCell],
[.type: PasswordEditorCellType.passwordLengthCell],
[.type: PasswordEditorCellType.passwordUseDigitsCell],
[.type: PasswordEditorCellType.passwordVaryCasesCell],
[.type: PasswordEditorCellType.passwordUseSpecialSymbols],
],
[
[.type: PasswordEditorCellType.additionsCell, .title: "Additions".localize(), .content: password?.additionsPlainText ?? ""],
],
[
[.type: PasswordEditorCellType.scanQRCodeCell],
]
]
if self.password != nil {
tableData[additionsSection+1].append([.type: PasswordEditorCellType.deletePasswordCell])
}
updateTableData(withRespectTo: passwordGenerator.flavor)
}
override func viewDidLayoutSubviews() {
additionsCell?.contentTextView.setContentOffset(.zero, animated: false)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellData = tableData[indexPath.section][indexPath.row]
switch cellData[PasswordEditorCellKey.type] as! PasswordEditorCellType {
case .nameCell:
nameCell = tableView.dequeueReusableCell(withIdentifier: "textFieldCell", for: indexPath) as? TextFieldTableViewCell
nameCell?.contentTextField.delegate = self
nameCell?.setContent(content: cellData[PasswordEditorCellKey.content] as? String)
return nameCell!
case .fillPasswordCell:
fillPasswordCell = tableView.dequeueReusableCell(withIdentifier: "fillPasswordCell", for: indexPath) as? FillPasswordTableViewCell
fillPasswordCell?.delegate = self
fillPasswordCell?.contentTextField.delegate = self
fillPasswordCell?.setContent(content: cellData[PasswordEditorCellKey.content] as? String)
if tableData[passwordSection].count == 1 {
fillPasswordCell?.settingButton.isHidden = true
}
return fillPasswordCell!
case .passwordLengthCell:
return (tableView.dequeueReusableCell(withIdentifier: "sliderCell", for: indexPath) as! SliderTableViewCell)
.set(title: "Length".localize())
.configureSlider(with: passwordGenerator.flavor.lengthLimits)
.set(initialValue: passwordGenerator.limitedLength)
.checkNewValue { $0 != self.passwordGenerator.length }
.updateNewValue { self.passwordGenerator.length = $0 }
.delegate(to: self)
case .passwordUseDigitsCell:
return (tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as! SwitchTableViewCell)
.set(title: "Digits".localize())
.set(initialValue: passwordGenerator.useDigits)
.updateNewValue { self.passwordGenerator.useDigits = $0 }
.delegate(to: self)
case .passwordVaryCasesCell:
return (tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as! SwitchTableViewCell)
.set(title: "VaryCases".localize())
.set(initialValue: passwordGenerator.varyCases)
.updateNewValue { self.passwordGenerator.varyCases = $0 }
.delegate(to: self)
case .passwordUseSpecialSymbols:
return (tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as! SwitchTableViewCell)
.set(title: "SpecialSymbols".localize())
.set(initialValue: passwordGenerator.useSpecialSymbols)
.updateNewValue { self.passwordGenerator.useSpecialSymbols = $0 }
.delegate(to: self)
case .passwordGroupsCell:
return (tableView.dequeueReusableCell(withIdentifier: "sliderCell", for: indexPath) as! SliderTableViewCell)
.set(title: "Groups".localize())
.configureSlider(with: (min: 0, max: 6))
.set(initialValue: passwordGenerator.groups)
.checkNewValue { $0 != self.passwordGenerator.groups && self.passwordGenerator.isAcceptable(groups: $0) }
.updateNewValue { self.passwordGenerator.groups = $0 }
.delegate(to: self)
case .passwordFlavorCell:
return passwordFlavorCell!
case .additionsCell:
additionsCell = tableView.dequeueReusableCell(withIdentifier: "textViewCell", for: indexPath) as? TextViewTableViewCell
additionsCell?.contentTextView.delegate = self
additionsCell?.setContent(content: cellData[PasswordEditorCellKey.content] as? String)
additionsCell?.contentTextView.textColor = Colors.label
return additionsCell!
case .deletePasswordCell:
return deletePasswordCell!
case .scanQRCodeCell:
return scanQRCodeCell!
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch tableData[indexPath.section][indexPath.row][PasswordEditorCellKey.type] as! PasswordEditorCellType {
case .passwordLengthCell, .passwordGroupsCell:
return 42
case .passwordUseDigitsCell, .passwordVaryCasesCell, .passwordUseSpecialSymbols, .passwordFlavorCell:
return 42
default:
return UITableView.automaticDimension
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return tableData.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == passwordSection, hidePasswordSettings {
// hide the password section, only the password should be shown
return 1
} else {
return tableData[section].count
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionHeaderTitles[section]
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sectionFooterTitles[section]
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
tableView.deselectRow(at: indexPath, animated: true)
if selectedCell == deletePasswordCell {
let alert = UIAlertController(title: "DeletePassword?".localize(), message: nil, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Delete".localize(), style: UIAlertAction.Style.destructive, handler: {[unowned self] (action) -> Void in
self.performSegue(withIdentifier: "deletePasswordSegue", sender: self)
}))
alert.addAction(UIAlertAction.cancel())
self.present(alert, animated: true, completion: nil)
} else if selectedCell == scanQRCodeCell {
self.performSegue(withIdentifier: "showQRScannerSegue", sender: self)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Defaults.passwordGenerator = passwordGenerator
}
private func updateTableData(withRespectTo flavor: PasswordGeneratorFlavor) {
// Remove delimiter configuration for XKCD style passwords. Re-add it for random ones.
switch flavor {
case .random:
guard tableData[1].first(where: isPasswordDelimiterCellData) == nil else {
return
}
tableData[1].insert([.type: PasswordEditorCellType.passwordGroupsCell], at: tableData[1].endIndex)
case .xkcd:
tableData[1].removeAll(where: isPasswordDelimiterCellData)
}
}
private func isPasswordDelimiterCellData(data: Dictionary<PasswordEditorCellKey, Any>) -> Bool {
return (data[.type] as? PasswordEditorCellType) == .some(.passwordGroupsCell)
}
@objc func flavorChanged(_ sender: UISegmentedControl) {
let flavor = PasswordGeneratorFlavor.allCases[sender.selectedSegmentIndex]
guard passwordGenerator.flavor != flavor else {
return
}
passwordGenerator.flavor = flavor
updateTableData(withRespectTo: flavor)
tableView.reloadSections([passwordSection], with: .none)
generateAndCopyPassword()
}
// generate the password, don't care whether the original line is otp
private func generateAndCopyPasswordNoOtpCheck() {
// show password settings (e.g., the length slider)
showPasswordSettings()
let plainPassword = passwordGenerator.generate()
// update tableData so to make sure reloadData() works correctly
tableData[passwordSection][0][PasswordEditorCellKey.content] = plainPassword
// update cell manually, no need to call reloadData()
fillPasswordCell?.setContent(content: plainPassword)
}
// show password settings (e.g., the length slider)
private func showPasswordSettings() {
if hidePasswordSettings == true {
hidePasswordSettings = false
tableView.reloadSections([passwordSection], with: .fade)
}
}
private func insertScannedOTPFields(_ otpauth: String) {
// update tableData
var additionsString = ""
if let additionsPlainText = (tableData[additionsSection][0][PasswordEditorCellKey.content] as? String)?.trimmed, additionsPlainText != "" {
additionsString = additionsPlainText + "\n" + otpauth
} else {
additionsString = otpauth
}
tableData[additionsSection][0][PasswordEditorCellKey.content] = additionsString
// reload the additions cell
additionsCell?.setContent(content: additionsString)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showQRScannerSegue" {
if let navController = segue.destination as? UINavigationController {
if let viewController = navController.topViewController as? QRScannerController {
viewController.delegate = self
}
} else if let viewController = segue.destination as? QRScannerController {
viewController.delegate = self
}
}
}
func getNameURL() -> (String, URL) {
let encodedName = (nameCell?.getContent()?.stringByAddingPercentEncodingForRFC3986())!
let name = URL(string: encodedName)!.lastPathComponent
let url = URL(string: encodedName)!.appendingPathExtension("gpg")
return (name, url)
}
func checkName() -> Bool {
// the name field should not be empty
guard let name = nameCell?.getContent(), name.isEmpty == false else {
Utils.alert(title: "CannotSave".localize(), message: "FillInName.".localize(), controller: self, completion: nil)
return false
}
// the name should not start with /
guard name.hasPrefix("/") == false else {
Utils.alert(title: "CannotSave".localize(), message: "RemovePrefix.".localize(), controller: self, completion: nil)
return false
}
// the name field should be a valid url
guard let path = name.stringByAddingPercentEncodingForRFC3986(),
var passwordURL = URL(string: path) else {
Utils.alert(title: "CannotSave".localize(), message: "PasswordNameInvalid.".localize(), controller: self, completion: nil)
return false
}
// check whether we can parse the filename (be consistent with PasswordStore::addPasswordEntities)
var previousPathLength = Int.max
while passwordURL.path != "." {
passwordURL = passwordURL.deletingLastPathComponent()
if passwordURL.path != "." && passwordURL.path.count >= previousPathLength {
Utils.alert(title: "CannotSave".localize(), message: "CannotParseFilename.".localize(), controller: self, completion: nil)
return false
}
previousPathLength = passwordURL.path.count
}
return true
}
}
// MARK: - FillPasswordTableViewCellDelegate
extension PasswordEditorTableViewController: FillPasswordTableViewCellDelegate {
// generate password, copy to pasteboard, and set the cell
// check whether the current password looks like an OTP field
func generateAndCopyPassword() {
if let currentPassword = fillPasswordCell?.getContent(), Constants.isOtpRelated(line: currentPassword) {
let alert = UIAlertController(title: "Overwrite?".localize(), message: "OverwriteOtpConfiguration?".localize(), preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Yes".localize(), style: UIAlertAction.Style.destructive, handler: {_ in
self.generateAndCopyPasswordNoOtpCheck()
}))
alert.addAction(UIAlertAction.cancel())
self.present(alert, animated: true, completion: nil)
} else {
self.generateAndCopyPasswordNoOtpCheck()
}
}
// show/hide password settings (e.g., the length slider)
func showHidePasswordSettings() {
hidePasswordSettings = !hidePasswordSettings
tableView.reloadSections([passwordSection], with: .fade)
}
}
// MARK: - PasswordSettingSliderTableViewCellDelegate
extension PasswordEditorTableViewController: PasswordSettingSliderTableViewCellDelegate {}
// MARK: - QRScannerControllerDelegate
extension PasswordEditorTableViewController: QRScannerControllerDelegate {
func checkScannedOutput(line: String) -> (accept: Bool, message: String) {
if let url = URL(string: line), let _ = Token(url: url) {
return (accept: true, message: "ValidTokenUrl".localize())
} else {
return (accept: false, message: "InvalidTokenUrl".localize())
}
}
func handleScannedOutput(line: String) {
insertScannedOTPFields(line)
}
}
// MARK: - SFSafariViewControllerDelegate
extension PasswordEditorTableViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
let copiedLinesSplit = UIPasteboard.general.string?.components(separatedBy: CharacterSet.whitespacesAndNewlines).filter({ !$0.isEmpty })
if copiedLinesSplit?.count ?? 0 > 0 {
let generatedPassword = copiedLinesSplit![0]
let alert = UIAlertController(title: "WannaUseIt?".localize(), message: "", preferredStyle: UIAlertController.Style.alert)
let message = NSMutableAttributedString(string: "\("SeemsLikeYouHaveCopiedSomething.".localize()) \("FirstStringIs:".localize())\n")
message.append(Utils.attributedPassword(plainPassword: generatedPassword))
alert.setValue(message, forKey: "attributedMessage")
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {[unowned self] (action) -> Void in
// update tableData so to make sure reloadData() works correctly
self.tableData[self.passwordSection][0][PasswordEditorCellKey.content] = generatedPassword
// update cell manually, no need to call reloadData()
self.fillPasswordCell?.setContent(content: generatedPassword)
}))
alert.addAction(UIAlertAction.cancel())
self.present(alert, animated: true, completion: nil)
}
}
}
// MARK: - UITextFieldDelegate
extension PasswordEditorTableViewController: UITextFieldDelegate {
// update tableData so to make sure reloadData() works correctly
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == nameCell?.contentTextField {
tableData[nameSection][0][PasswordEditorCellKey.content] = nameCell?.getContent()
} else if textField == fillPasswordCell?.contentTextField {
if let plainPassword = fillPasswordCell?.getContent() {
tableData[passwordSection][0][PasswordEditorCellKey.content] = plainPassword
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == fillPasswordCell?.contentTextField {
// show password generation settings automatically
showPasswordSettings()
}
}
}
// MARK: - UITextViewDelegate
extension PasswordEditorTableViewController: UITextViewDelegate {
// update tableData so to make sure reloadData() works correctly
func textViewDidEndEditing(_ textView: UITextView) {
if textView == additionsCell?.contentTextView {
tableData[additionsSection][0][PasswordEditorCellKey.content] = additionsCell?.getContent()
}
}
}
| 45.374741 | 170 | 0.675899 |
29eab57a3c84fb4960a5748007f972db78abab29 | 243 | import Foundation
protocol OffsetCorrectionViewOutput {
func viewDidLoad()
func viewDidOpenCalibrateDialog()
func viewDidOpenClearDialog()
func viewDidClearOffsetValue()
func viewDidSetCorrectValue(correctValue: Double)
}
| 24.3 | 53 | 0.790123 |
3a64479dfa01fa3198401f1db8b14306a0d1050f | 2,142 | //
// ViewController.swift
// BasicAR
//
// Created by Alex Dunn on 9/18/17.
// Copyright © 2017 Alex Dunn. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// Set the scene to the view
sceneView.scene = scene
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| 26.444444 | 103 | 0.628385 |
de5593af5093e04ad8c662b1723a84ecde094851 | 994 | //
// AudioSession.swift
// SwiftAudio
//
// Created by Jørgen Henrichsen on 02/11/2018.
//
import Foundation
import AVFoundation
protocol AudioSession {
var isOtherAudioPlaying: Bool { get }
var category: AVAudioSession.Category { get }
var mode: AVAudioSession.Mode { get }
var categoryOptions: AVAudioSession.CategoryOptions { get }
var availableCategories: [AVAudioSession.Category] { get }
@available(iOS 10.0, *)
func setCategory(_ category: AVAudioSession.Category, mode: AVAudioSession.Mode, options: AVAudioSession.CategoryOptions) throws
@available(iOS 11.0, *)
func setCategory(_ category: AVAudioSession.Category, mode: AVAudioSession.Mode, policy: AVAudioSession.RouteSharingPolicy, options: AVAudioSession.CategoryOptions) throws
func setActive(_ active: Bool, options: AVAudioSession.SetActiveOptions) throws
}
extension AVAudioSession: AudioSession {}
| 28.4 | 176 | 0.700201 |
f4bd194db11056842c9122d5bab8eef87b57fcfd | 235 | //
// MessageCollectionView.swift
// MessageLib
//
// Created by Artem Vlasenko on 14.11.2019.
// Copyright © 2019 Artem Vlasenko. All rights reserved.
//
import UIKit
final class MessageCollectionView: UICollectionView {
}
| 16.785714 | 57 | 0.719149 |
e88900cdf871890626d5f0de73dc8d94488ff49d | 243 | //
// UserManagementRepository.swift
// ChatUI
//
// Created by Ryan on 11/22/19.
// Copyright © 2019 Daylighter. All rights reserved.
//
import PromiseKit
protocol UserManagementRepository {
func signOut() -> Promise<UserSession?>
}
| 18.692308 | 53 | 0.711934 |
20ae6f08357a5b86554a6823b2e724dccaca4de6 | 22,692 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// Source file update_post.proto
import Foundation
public extension Services.Post.Actions{ public struct UpdatePost { }}
public func == (lhs: Services.Post.Actions.UpdatePost.RequestV1, rhs: Services.Post.Actions.UpdatePost.RequestV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasPost == rhs.hasPost) && (!lhs.hasPost || lhs.post == rhs.post)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public func == (lhs: Services.Post.Actions.UpdatePost.ResponseV1, rhs: Services.Post.Actions.UpdatePost.ResponseV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasPost == rhs.hasPost) && (!lhs.hasPost || lhs.post == rhs.post)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public extension Services.Post.Actions.UpdatePost {
public struct UpdatePostRoot {
public static var sharedInstance : UpdatePostRoot {
struct Static {
static let instance : UpdatePostRoot = UpdatePostRoot()
}
return Static.instance
}
public var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
Services.Post.Containers.ContainersRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
public func registerAllExtensions(registry:ExtensionRegistry) {
}
}
final public class RequestV1 : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasPost:Bool = false
public private(set) var post:Services.Post.Containers.PostV1!
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasPost {
try output.writeMessage(1, value:post)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasPost {
if let varSizepost = post?.computeMessageSize(1) {
serialize_size += varSizepost
}
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Post.Actions.UpdatePost.RequestV1> {
var mergedArray = Array<Services.Post.Actions.UpdatePost.RequestV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.UpdatePost.RequestV1? {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.Post.Actions.UpdatePost.RequestV1 {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFromData(data, extensionRegistry:Services.Post.Actions.UpdatePost.UpdatePostRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.RequestV1 {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.UpdatePost.RequestV1 {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.RequestV1 {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.UpdatePost.RequestV1 {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.RequestV1 {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
return Services.Post.Actions.UpdatePost.RequestV1.classBuilder() as! Services.Post.Actions.UpdatePost.RequestV1.Builder
}
public func getBuilder() -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
return classBuilder() as! Services.Post.Actions.UpdatePost.RequestV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.Post.Actions.UpdatePost.RequestV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.Post.Actions.UpdatePost.RequestV1.Builder()
}
public func toBuilder() throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
return try Services.Post.Actions.UpdatePost.RequestV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.Post.Actions.UpdatePost.RequestV1) throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
return try Services.Post.Actions.UpdatePost.RequestV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
if hasPost {
output += "\(indent) post {\n"
try post?.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent) }\n"
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasPost {
if let hashValuepost = post?.hashValue {
hashCode = (hashCode &* 31) &+ hashValuepost
}
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.Post.Actions.UpdatePost.RequestV1"
}
override public func className() -> String {
return "Services.Post.Actions.UpdatePost.RequestV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.Post.Actions.UpdatePost.RequestV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.Post.Actions.UpdatePost.RequestV1 = Services.Post.Actions.UpdatePost.RequestV1()
public func getMessage() -> Services.Post.Actions.UpdatePost.RequestV1 {
return builderResult
}
required override public init () {
super.init()
}
public var hasPost:Bool {
get {
return builderResult.hasPost
}
}
public var post:Services.Post.Containers.PostV1! {
get {
if postBuilder_ != nil {
builderResult.post = postBuilder_.getMessage()
}
return builderResult.post
}
set (value) {
builderResult.hasPost = true
builderResult.post = value
}
}
private var postBuilder_:Services.Post.Containers.PostV1.Builder! {
didSet {
builderResult.hasPost = true
}
}
public func getPostBuilder() -> Services.Post.Containers.PostV1.Builder {
if postBuilder_ == nil {
postBuilder_ = Services.Post.Containers.PostV1.Builder()
builderResult.post = postBuilder_.getMessage()
if post != nil {
try! postBuilder_.mergeFrom(post)
}
}
return postBuilder_
}
public func setPost(value:Services.Post.Containers.PostV1!) -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
self.post = value
return self
}
public func mergePost(value:Services.Post.Containers.PostV1) throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
if builderResult.hasPost {
builderResult.post = try Services.Post.Containers.PostV1.builderWithPrototype(builderResult.post).mergeFrom(value).buildPartial()
} else {
builderResult.post = value
}
builderResult.hasPost = true
return self
}
public func clearPost() -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
postBuilder_ = nil
builderResult.hasPost = false
builderResult.post = nil
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
builderResult = Services.Post.Actions.UpdatePost.RequestV1()
return self
}
public override func clone() throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
return try Services.Post.Actions.UpdatePost.RequestV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.Post.Actions.UpdatePost.RequestV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.Post.Actions.UpdatePost.RequestV1 {
let returnMe:Services.Post.Actions.UpdatePost.RequestV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.Post.Actions.UpdatePost.RequestV1) throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
if other == Services.Post.Actions.UpdatePost.RequestV1() {
return self
}
if (other.hasPost) {
try mergePost(other.post)
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.RequestV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10 :
let subBuilder:Services.Post.Containers.PostV1.Builder = Services.Post.Containers.PostV1.Builder()
if hasPost {
try subBuilder.mergeFrom(post)
}
try input.readMessage(subBuilder, extensionRegistry:extensionRegistry)
post = subBuilder.buildPartial()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
final public class ResponseV1 : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasPost:Bool = false
public private(set) var post:Services.Post.Containers.PostV1!
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasPost {
try output.writeMessage(1, value:post)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasPost {
if let varSizepost = post?.computeMessageSize(1) {
serialize_size += varSizepost
}
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Post.Actions.UpdatePost.ResponseV1> {
var mergedArray = Array<Services.Post.Actions.UpdatePost.ResponseV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.UpdatePost.ResponseV1? {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFromData(data, extensionRegistry:Services.Post.Actions.UpdatePost.UpdatePostRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
return Services.Post.Actions.UpdatePost.ResponseV1.classBuilder() as! Services.Post.Actions.UpdatePost.ResponseV1.Builder
}
public func getBuilder() -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
return classBuilder() as! Services.Post.Actions.UpdatePost.ResponseV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.Post.Actions.UpdatePost.ResponseV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.Post.Actions.UpdatePost.ResponseV1.Builder()
}
public func toBuilder() throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
return try Services.Post.Actions.UpdatePost.ResponseV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.Post.Actions.UpdatePost.ResponseV1) throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
return try Services.Post.Actions.UpdatePost.ResponseV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
if hasPost {
output += "\(indent) post {\n"
try post?.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent) }\n"
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasPost {
if let hashValuepost = post?.hashValue {
hashCode = (hashCode &* 31) &+ hashValuepost
}
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.Post.Actions.UpdatePost.ResponseV1"
}
override public func className() -> String {
return "Services.Post.Actions.UpdatePost.ResponseV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.Post.Actions.UpdatePost.ResponseV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.Post.Actions.UpdatePost.ResponseV1 = Services.Post.Actions.UpdatePost.ResponseV1()
public func getMessage() -> Services.Post.Actions.UpdatePost.ResponseV1 {
return builderResult
}
required override public init () {
super.init()
}
public var hasPost:Bool {
get {
return builderResult.hasPost
}
}
public var post:Services.Post.Containers.PostV1! {
get {
if postBuilder_ != nil {
builderResult.post = postBuilder_.getMessage()
}
return builderResult.post
}
set (value) {
builderResult.hasPost = true
builderResult.post = value
}
}
private var postBuilder_:Services.Post.Containers.PostV1.Builder! {
didSet {
builderResult.hasPost = true
}
}
public func getPostBuilder() -> Services.Post.Containers.PostV1.Builder {
if postBuilder_ == nil {
postBuilder_ = Services.Post.Containers.PostV1.Builder()
builderResult.post = postBuilder_.getMessage()
if post != nil {
try! postBuilder_.mergeFrom(post)
}
}
return postBuilder_
}
public func setPost(value:Services.Post.Containers.PostV1!) -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
self.post = value
return self
}
public func mergePost(value:Services.Post.Containers.PostV1) throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
if builderResult.hasPost {
builderResult.post = try Services.Post.Containers.PostV1.builderWithPrototype(builderResult.post).mergeFrom(value).buildPartial()
} else {
builderResult.post = value
}
builderResult.hasPost = true
return self
}
public func clearPost() -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
postBuilder_ = nil
builderResult.hasPost = false
builderResult.post = nil
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
builderResult = Services.Post.Actions.UpdatePost.ResponseV1()
return self
}
public override func clone() throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
return try Services.Post.Actions.UpdatePost.ResponseV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.Post.Actions.UpdatePost.ResponseV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.Post.Actions.UpdatePost.ResponseV1 {
let returnMe:Services.Post.Actions.UpdatePost.ResponseV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.Post.Actions.UpdatePost.ResponseV1) throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
if other == Services.Post.Actions.UpdatePost.ResponseV1() {
return self
}
if (other.hasPost) {
try mergePost(other.post)
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.UpdatePost.ResponseV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10 :
let subBuilder:Services.Post.Containers.PostV1.Builder = Services.Post.Containers.PostV1.Builder()
if hasPost {
try subBuilder.mergeFrom(post)
}
try input.readMessage(subBuilder, extensionRegistry:extensionRegistry)
post = subBuilder.buildPartial()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
}
// @@protoc_insertion_point(global_scope)
| 43.80695 | 198 | 0.684294 |
f559974f469c1ea7cb4352dcacededc809962428 | 1,613 | //
// NSFetchResultControllerDelegateWrapper.swift
// Rates
//
// Created by Michael Henry Pantaleon on 2019/08/28.
// Copyright © 2019 Michael Henry Pantaleon. All rights reserved.
//
import Foundation
import CoreData
/// NSFetchedResultsControllerDelegateWrapper is a wrapper that will help to avoid repeatition on setting up the NSFetchResultControllerDelegate
class NSFetchedResultsControllerDelegateWrapper:NSObject, NSFetchedResultsControllerDelegate {
private var onWillChangeContent:(() -> Void)?
private var onDidChangeContent:(() -> Void)?
private var onChange:((
_ indexPath:IndexPath?,
_ type: NSFetchedResultsChangeType,
_ newIndexPath:IndexPath?) -> Void)?
init(
onWillChangeContent:(() -> Void)?,
onDidChangeContent:(() -> Void)?,
onChange:((
_ indexPath:IndexPath?,
_ type: NSFetchedResultsChangeType,
_ newIndexPath:IndexPath?) -> Void)?) {
self.onWillChangeContent = onWillChangeContent
self.onDidChangeContent = onDidChangeContent
self.onChange = onChange
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.onWillChangeContent?()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.onDidChangeContent?()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any, at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
self.onChange?(indexPath, type, newIndexPath)
}
}
| 33.604167 | 144 | 0.743335 |
f980547b3c7bb7cd74a261fc12728c6c322d2194 | 9,227 | @testable import Kickstarter_Framework
@testable import KsApi
@testable import Library
import Prelude
import XCTest
private let creator = User.template |> \.avatar.small .~ ""
private let survey = .template |> SurveyResponse.lens.project .~
(.cosmicSurgery |> Project.lens.creator .~ creator)
private let you = User.template
|> \.avatar.small .~ ""
|> \.id .~ 355
|> \.name .~ "Gina B"
internal final class ActivitiesViewControllerTests: TestCase {
override func setUp() {
super.setUp()
AppEnvironment.pushEnvironment(currentUser: you, mainBundle: Bundle.framework)
UIView.setAnimationsEnabled(false)
}
override func tearDown() {
AppEnvironment.popEnvironment()
UIView.setAnimationsEnabled(true)
super.tearDown()
}
func testActivities_All() {
let daysAgoDate = self.dateType.init().timeIntervalSince1970 - 60 * 60 * 24 * 2
let follow = .template
|> Activity.lens.id .~ 84
|> Activity.lens.user .~ (.template
|> \.name .~ "Brandon Williams"
|> \.avatar.small .~ ""
)
|> Activity.lens.category .~ .follow
let update = .template
|> Activity.lens.id .~ 51
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
)
|> Activity.lens.update .~ .template
|> Activity.lens.createdAt .~ daysAgoDate
|> Activity.lens.category .~ .update
let backing = .template
|> Activity.lens.id .~ 62
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.stats.fundingProgress .~ 0.88
|> Project.lens.category .~ .games
)
|> Activity.lens.user .~ (.template
|> \.name .~ "Judith Light"
|> \.avatar.small .~ ""
)
|> Activity.lens.category .~ .backing
let launch = .template
|> Activity.lens.id .~ 73
|> Activity.lens.project .~ .some(.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.name .~ "A Very Important Project About Kittens and Puppies"
|> Project.lens.stats.fundingProgress .~ 0
)
|> Activity.lens.category .~ .launch
let following = .template
|> Activity.lens.id .~ 0
|> Activity.lens.user .~ (.template
|> \.name .~ "David Bowie"
|> \.isFriend .~ true
|> \.avatar.small .~ ""
)
|> Activity.lens.category .~ .follow
let success = .template
|> Activity.lens.id .~ 45
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.name .~ "Help Me Transform This Pile of Wood"
|> Project.lens.stats.fundingProgress .~ 1.4
)
|> Activity.lens.category .~ .success
let failure = .template
|> Activity.lens.id .~ 36
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.name .~ "A Mildly Important Project About Arachnids and Worms"
|> Project.lens.stats.fundingProgress .~ 0.6
)
|> Activity.lens.category .~ .failure
let canceled = .template
|> Activity.lens.id .~ 27
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.name .~ "A Not Very Important Project About Pickles"
|> Project.lens.stats.fundingProgress .~ 0.1
)
|> Activity.lens.category .~ .cancellation
let suspended = .template
|> Activity.lens.id .~ 18
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.name .~ "A Questionably Important Project About Rubber Bands"
|> Project.lens.stats.fundingProgress .~ 0.04
)
|> Activity.lens.category .~ .suspension
let activities = [follow, update, backing, launch, following, success, failure, canceled, suspended]
combos(Language.allLanguages, [Device.phone4_7inch, Device.phone5_8inch, Device.pad]).forEach {
language, device in
withEnvironment(
apiService: MockService(
fetchActivitiesResponse: activities,
fetchUnansweredSurveyResponsesResponse: [survey]
),
currentUser: .template |> \.facebookConnected .~ true,
language: language,
userDefaults: MockKeyValueStore()
) {
let vc = ActivitiesViewController.instantiate()
vc.viewWillAppear(true)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = 2_360
self.scheduler.run()
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testMultipleSurveys_NotFacebookConnected_YouLaunched() {
let launch = .template
|> Activity.lens.id .~ 73
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.creator .~ you
|> Project.lens.photo.med .~ ""
|> Project.lens.photo.full .~ ""
|> Project.lens.name .~ "A Very Very Important Project About Kittens and Puppies"
|> Project.lens.stats.fundingProgress .~ 0.01
)
|> Activity.lens.user .~ you
|> Activity.lens.category .~ .launch
let survey2 = .template |> SurveyResponse.lens.project .~ (.anomalisa
|> Project.lens.creator .~ creator)
combos(Language.allLanguages, [Device.phone4_7inch]).forEach { language, device in
withEnvironment(
apiService: MockService(
fetchActivitiesResponse: [launch],
fetchUnansweredSurveyResponsesResponse: [survey, survey2]
),
currentUser: you |> \.facebookConnected .~ false |> \.needsFreshFacebookToken .~ true,
language: language,
userDefaults: MockKeyValueStore()
) {
let vc = ActivitiesViewController.instantiate()
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = 900
self.scheduler.run()
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testMultipleSurveys_NeedsFacebookReconnect() {
let launch = .template
|> Activity.lens.id .~ 73
|> Activity.lens.project .~ (.cosmicSurgery
|> Project.lens.creator .~ you
|> Project.lens.name .~ "A Very Very Important Project About Kittens and Puppies"
|> Project.lens.stats.fundingProgress .~ 0.01
)
|> Activity.lens.user .~ you
|> Activity.lens.category .~ .launch
let survey2 = .template |> SurveyResponse.lens.project .~ (.anomalisa
|> Project.lens.creator .~ creator)
combos(Language.allLanguages, [Device.phone4_7inch]).forEach { language, device in
withEnvironment(
apiService: MockService(
fetchActivitiesResponse: [launch],
fetchUnansweredSurveyResponsesResponse: [survey, survey2]
),
currentUser: you |> \.facebookConnected .~ true |> \.needsFreshFacebookToken .~ true,
language: language,
userDefaults: MockKeyValueStore()
) {
let vc = ActivitiesViewController.instantiate()
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = 900
self.scheduler.run()
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testErroredBackings() {
let date = AppEnvironment.current.calendar.date(byAdding: DateComponents(day: 4), to: MockDate().date)
let dateFormatter = ISO8601DateFormatter()
let collectionDate = dateFormatter.string(from: date ?? Date())
let project = GraphBacking.Project.template
|> \.name .~ "Awesome tabletop collection"
|> \.finalCollectionDate .~ collectionDate
let backing = GraphBacking.template
|> \.project .~ project
let backings = GraphBackingEnvelope.GraphBackingConnection(nodes: [backing, backing])
let envelope = GraphBackingEnvelope.template
|> \.backings .~ backings
let backingsResponse = UserEnvelope<GraphBackingEnvelope>(me: envelope)
combos(Language.allLanguages, [Device.phone4_7inch]).forEach { language, device in
withEnvironment(
apiService: MockService(fetchGraphUserBackingsResponse: backingsResponse),
currentUser: .template |> \.facebookConnected .~ true |> \.needsFreshFacebookToken .~ false,
language: language
) {
let vc = ActivitiesViewController.instantiate()
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = 900
self.scheduler.run()
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testScrollToTop() {
let controller = ActivitiesViewController.instantiate()
XCTAssertNotNil(controller.view as? UIScrollView)
}
}
| 35.35249 | 106 | 0.631841 |
75012cad3ed3e20159642bdef9022aaa7543a16c | 504 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func b<T
{func a
{{
class S{
var d=a<T
}}
class A{class S<T where g:P{class a{
class B<b
class B{
let f=B
| 26.526316 | 79 | 0.730159 |
fb8295ac7d5227534bd546bfd45880fa4865547d | 609 | //
// RandomAliasesView.swift
// Keyboard Extension
//
// Created by Nhon Nguyen on 29/04/2022.
//
import SwiftUI
struct RandomAliasesView: View {
@ObservedObject var viewModel: KeyboardContentViewModel
var body: some View {
VStack(spacing: 20) {
Group {
Button("Random by word") {
viewModel.random(mode: .word)
}
Button("Random by UUID") {
viewModel.random(mode: .uuid)
}
}
.foregroundColor(.slPurple)
.font(.body)
}
}
}
| 21 | 59 | 0.502463 |
283786866200ac1e52ec53560306212347301982 | 226 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
deinit {
return m(e : b { func b
class A {
class
case c,
| 22.6 | 87 | 0.738938 |
396a1c9046425f5a3442ac863e214324f8868aa6 | 3,216 | //
// ImgurLoginControllerTests.swift
// Swimgur
//
// Created by Joseph Neuman on 8/29/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import UIKit
import XCTest
import SWNetworking
class ImgurLoginControllerTests: XCTestCase {
func test1Login() {
SWNetworking.sharedInstance.logout()
var tilc = TestableImgurLoginController()
XCTAssertNotNil(tilc, "TestableImgurLoginController not loaded")
var expectation = self.expectationWithDescription("Login")
tilc.authorizeWithViewController(UIViewController()) { (success) -> () in
XCTAssertTrue(success, "Login failed")
XCTAssertNotNil(SIUserDefaults().code?, "Code does not exist")
XCTAssertNotNil(SIUserDefaults().token?.accessToken, "Token does not exist")
XCTAssertNotNil(SIUserDefaults().account?, "Account does not exist")
if let username = SIUserDefaults().account?.username {
XCTAssertEqual(username, "testthewest", "Username is incorrect")
} else {
XCTFail("Username not set")
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(10.0, handler: nil)
}
func testGetGallery() {
var expectation = self.expectationWithDescription("Get gallery")
SWNetworking.sharedInstance.getGalleryImagesWithSection(ImgurSection.Hot, sort: ImgurSort.Viral, window: ImgurWindow.Day, page: 0, showViral: true, onCompletion: { (newGalleryItems) -> () in
XCTAssertGreaterThan(newGalleryItems.count, 0, "None returned")
expectation.fulfill()
}) { (error, description) -> () in
XCTFail("Get gallery failed")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testGetAlbum() {
var expectation = self.expectationWithDescription("Get album")
SWNetworking.sharedInstance.getAlbum(albumId: "TxQjM", onCompletion: { (album) -> () in
XCTAssertEqual(album.images.count, 10, "Album image count incorrect")
expectation.fulfill()
}) { (error, description) -> () in
XCTFail("Get album failed")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testVoting() {
var expectation = self.expectationWithDescription("Get album")
SWNetworking.sharedInstance.voteOnGalleryItem(galleryItemId: "TxQjM", vote: GalleryItemVote.Down, onCompletion: { (success) -> () in
XCTAssertTrue(success, "Down vote failed")
SWNetworking.sharedInstance.voteOnGalleryItem(galleryItemId: "TxQjM", vote: GalleryItemVote.Up, onCompletion: { (success) -> () in
XCTAssertTrue(success, "Up vote failed")
expectation.fulfill()
})
})
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
}
class TestableImgurLoginController: ImgurLoginController {
func webViewDidFinishLoad(webView: UIWebView!) {
webView.stringByEvaluatingJavaScriptFromString("document.getElementById('username').value = 'testthewest'")
webView.stringByEvaluatingJavaScriptFromString("document.getElementById('password').value = 'supertesters'")
webView.stringByEvaluatingJavaScriptFromString("document.getElementById('allow').click()")
}
} | 36.965517 | 194 | 0.708955 |
4884d318f9811eceacafce1eb416f477d07e090f | 1,498 | //
// SubcategoryVieeController.swift
// TiGuia
//
// Created by Meyrillan Silva on 27/11/20.
//
//
//import SwiftUI
//
//class SubcategoryViewController: UIViewController {
//
// var subcategory: UIHostingController<SubcategoryView>?
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// // Do any additional setup after loading the view.
// subcategory = UIHostingController(rootView: SubcategoryView(index: 0))
// subcategory?.view.translatesAutoresizingMaskIntoConstraints = false
//
// self.view.addSubview(subcategory!.view)
//
// let constraints = [
// subcategory!.view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0),
// subcategory!.view.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor, constant: 0),
// subcategory!.view.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 0),
// subcategory!.view.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: 0),
// subcategory!.view.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: 0)
// ]
// NSLayoutConstraint.activate(constraints)
// }
//
//}
//
//struct SubcategoryViewController_Previews: PreviewProvider {
// static var previews: some View {
// Text("Hello, World!")
// }
//}
| 37.45 | 126 | 0.675567 |
1670ec91cee0ae8c49f38edd6c024734a8249436 | 3,784 | import UIKit
final class RepositoryTableViewCell: UITableViewCell {
private let containerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.layer.cornerRadius = 8
return view
}()
private let ownerImageView = LoadableImageView()
private let repositoryNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
private let ownerNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
private let descriptionLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureView()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureView() {
containerView.addSubview(ownerImageView)
containerView.addSubview(repositoryNameLabel)
containerView.addSubview(ownerNameLabel)
containerView.addSubview(descriptionLabel)
contentView.addSubview(containerView)
let margin: CGFloat = 12
NSLayoutConstraint.activate([
containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: margin),
containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: margin),
containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -margin),
containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -margin),
ownerImageView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: margin),
ownerImageView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: margin),
ownerImageView.heightAnchor.constraint(equalToConstant: 60),
ownerImageView.widthAnchor.constraint(equalToConstant: 60),
repositoryNameLabel.leadingAnchor.constraint(equalTo: ownerImageView.trailingAnchor, constant: margin),
repositoryNameLabel.topAnchor.constraint(equalTo: ownerImageView.topAnchor),
repositoryNameLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -margin),
ownerNameLabel.leadingAnchor.constraint(equalTo: repositoryNameLabel.leadingAnchor),
ownerNameLabel.topAnchor.constraint(equalTo: repositoryNameLabel.bottomAnchor, constant: 4),
ownerNameLabel.trailingAnchor.constraint(equalTo: repositoryNameLabel.trailingAnchor),
descriptionLabel.leadingAnchor.constraint(equalTo: repositoryNameLabel.leadingAnchor),
descriptionLabel.topAnchor.constraint(equalTo: ownerNameLabel.bottomAnchor, constant: margin),
descriptionLabel.trailingAnchor.constraint(equalTo: repositoryNameLabel.trailingAnchor),
descriptionLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -margin)
])
selectionStyle = .none
backgroundColor = .clear
}
func show(model: Repository) {
ownerImageView.setImage(from: model.owner.avatarUrl)
repositoryNameLabel.text = model.name
ownerNameLabel.text = model.owner.login
descriptionLabel.text = model.description
}
}
| 41.582418 | 116 | 0.712738 |
71fa5553408eddde863df44a632ab362db06731f | 871 | //
// EmojiButton.swift
// TestCameraDemo
//
// Created by xiudou on 2018/5/7.
// Copyright © 2018年 CoderST. All rights reserved.
//
import UIKit
class EmojiButton: UIButton {
/** 图片名字 */
var pngName : String?{
didSet{
DispatchQueue.global().async {
//耗时操作
let path = Bundle.main.path(forResource: self.pngName, ofType: "png") ?? ""
let image = UIImage(contentsOfFile: path)
DispatchQueue.main.async {
//刷新UI
if image != nil{
self.setImage(image, for: .normal)
}
self.isUserInteractionEnabled = image == nil ? false : true
}
}
}
}
/*
* 按钮的类型
* 0是表情 1是删除
*/
var btnType : Int = 0
}
| 21.775 | 91 | 0.458094 |
334e45b9038534ef7e1f3740f4dba18d6f661fcc | 300 | import XCTest
import RingBufferSingleItemTests
import RingBufferMultipleItemsTests
import RingBufferThreadsTests
var tests = [XCTestCaseEntry]()
tests += RingBufferSingleItemTests.allTests()
tests += RingBufferMultipleItemsTests.allTests()
tests += RingBufferThreadsTests.allTests()
XCTMain(tests)
| 25 | 48 | 0.846667 |
5dcf8bfaec245365fa843084607c238abbf26c5a | 763 | import UIKit
import XCTest
import GWSimpleAlert
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.433333 | 111 | 0.606815 |
ac8d1e51d896bd0959cce2c0ea1d8c757e10ccb6 | 1,034 | //
// API+Repo.swift
// CleanArchitecture
//
// Created by Tuan Truong on 6/28/18.
// Copyright © 2018 Sun Asterisk. All rights reserved.
//
import ObjectMapper
extension API {
func getRepoList(_ input: GetRepoListInput) -> Observable<GetRepoListOutput> {
return request(input)
}
}
// MARK: - GetRepoList
extension API {
final class GetRepoListInput: APIInput {
init(page: Int, perPage: Int = 10) {
let params: JSONDictionary = [
"q": "language:swift",
"per_page": perPage,
"page": page
]
super.init(urlString: API.Urls.getRepoList,
parameters: params,
requestType: .get,
requireAccessToken: true)
}
}
final class GetRepoListOutput: APIOutput {
private(set) var repos: [Repo]?
override func mapping(map: Map) {
super.mapping(map: map)
repos <- map["items"]
}
}
}
| 24.046512 | 82 | 0.535783 |
b99ac0d36dfb89a4f3c41afda0b1330487306045 | 1,638 | extension JSON {
public enum Number {
case intValue(Int)
case floatValue(Float)
case doubleValue(Double)
}
}
// MARK: - Equatable
extension JSON.Number: Equatable {
static func areEqualWithPrecision<T: BinaryFloatingPoint>(_ lhs: T, _ rhs: T, precision: T = 1e-6) -> Bool {
return abs(lhs - rhs) < precision
}
public static func ==(lhs: JSON.Number, rhs: JSON.Number) -> Bool {
switch (lhs, rhs) {
case let (.intValue(l), .intValue(r)): return l == r
case let (.intValue(l), .floatValue(r)): return areEqualWithPrecision(Float(l), r)
case let (.intValue(l), .doubleValue(r)): return areEqualWithPrecision(Double(l), r)
case let (.floatValue(l), .intValue(r)): return areEqualWithPrecision(l, Float(r))
case let (.floatValue(l), .floatValue(r)): return areEqualWithPrecision(l, r)
case let (.floatValue(l), .doubleValue(r)): return areEqualWithPrecision(Double(l), r)
case let (.doubleValue(l), .intValue(r)): return areEqualWithPrecision(l, Double(r))
case let (.doubleValue(l), .floatValue(r)): return areEqualWithPrecision(l, Double(r))
case let (.doubleValue(l), .doubleValue(r)): return areEqualWithPrecision(l, r)
}
}
}
// MARK: - Printing
extension JSON.Number: CustomStringConvertible {
public var description: String {
switch self {
case let .intValue(int): return int.description
case let .floatValue(float): return float.description
case let .doubleValue(double): return double.description
}
}
}
| 33.428571 | 112 | 0.630647 |
ffe4a4c3f5d4dfbe2dbb6cefd4c7920a79be7ae1 | 3,113 | //
// RadialMicroChart.swift
// Micro Charts
//
// Created by Xu, Sheng on 12/13/19.
// Copyright © 2019 sstadelman. All rights reserved.
//
import SwiftUI
struct RadialMicroChart: View {
enum Mode: Int, CaseIterable {
case inside
case rightSide
}
@EnvironmentObject var model: ChartModel
@State var mode: RadialMicroChart.Mode? = .inside
// the difference of outer and inner radius range from 5...20
private static let minDepth: CGFloat = 5
private static let maxDepth: CGFloat = 20
var body: some View {
GeometryReader { proxy in
self.arcView(in: proxy.size)
}
}
//swiftlint:disable force_unwrapping
func arcView(in size: CGSize) -> some View {
let percentage = model.dataItemsIn(seriesIndex: 0).last
let str = String(format: "%.1f%%", percentage?.value ?? 0)
return HStack(alignment: .center, spacing: 4) {
if percentage == nil {
NoDataView()
} else {
Spacer()
ZStack {
self.chartView(in: size)
if mode == .inside {
Text(str)
.font(Font.system(.largeTitle))
.foregroundColor(percentage!.color)
}
}
Spacer()
// if mode == .rightSide {
// Text(str)
// .font(Font.system(.largeTitle))
// .foregroundColor(model.percentage.color)
// }
}
}
}
//swiftlint:disable force_unwrapping
func chartView(in size: CGSize) -> some View {
let total = model.dataItemsIn(seriesIndex: 0).first
let percentage = model.dataItemsIn(seriesIndex: 0).last
let radius = min(size.width, size.height) / 2
var ratio: Double = 100
if total!.value != 0 {
ratio = Double(percentage!.value / max(total!.value, 1))
}
// calculate the difference of outer and inner radius
let val = radius / 10
let depth = val > RadialMicroChart.maxDepth ? RadialMicroChart.maxDepth : (val < RadialMicroChart.minDepth ? RadialMicroChart.minDepth : val)
return ZStack {
ArcShape(startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 360))
.strokeBorder(total!.color, lineWidth: depth)
ArcShape(startAngle: Angle(degrees: 0), endAngle: Angle(degrees: ratio * 360))
.strokeBorder(percentage!.color, lineWidth: depth)
}.frame(width: radius * 2, height: radius * 2, alignment: .topLeading)
}
}
struct RadialMicroChart_Previews: PreviewProvider {
static var previews: some View {
Group {
ForEach(Tests.radialModels) {
RadialMicroChart()
.environmentObject($0)
.frame(height: 200, alignment: .topLeading)
.previewLayout(.sizeThatFits)
}
}
}
}
| 33.473118 | 149 | 0.542242 |
696f760d371c2599328218e9a8f67aaab502fcb1 | 1,711 | import KsApi
import Library
import Prelude
import UIKit
internal final class ProjectNotificationsViewController: UITableViewController {
fileprivate let viewModel: ProjectNotificationsViewModelType = ProjectNotificationsViewModel()
fileprivate let dataSource = ProjectNotificationsDataSource()
internal static func instantiate() -> ProjectNotificationsViewController {
return Storyboard.Settings.instantiate(ProjectNotificationsViewController.self)
}
internal override func viewDidLoad() {
super.viewDidLoad()
self.viewModel.inputs.viewDidLoad()
self.view.backgroundColor = .ksr_grey_100
self.tableView.dataSource = self.dataSource
}
override func bindStyles() {
super.bindStyles()
_ = self |> baseControllerStyle()
}
internal override func bindViewModel() {
self.viewModel.outputs.projectNotifications
.observeForControllerAction()
.observeValues { [weak self] notifications in
self?.dataSource.load(notifications: notifications)
self?.tableView.reloadData()
}
}
internal override func tableView(_ tableView: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath) {
if let cell = cell as? ProjectNotificationCell {
cell.delegate = self
}
}
}
extension ProjectNotificationsViewController: ProjectNotificationCellDelegate {
internal func projectNotificationCell(_ cell: ProjectNotificationCell?, notificationSaveError: String) {
self.present(UIAlertController.genericError(notificationSaveError),
animated: true,
completion: nil
)
}
}
| 32.903846 | 106 | 0.711864 |
29091f141f2d279f01d85daae71bfd3839305088 | 1,308 | //
// GetWalletDetailsOperation.swift
// Upvest
//
// Created by Moin' Victor on 30/08/2019.
// Copyright © 2019 Upvest. All rights reserved.
//
import Foundation
/// Get Wallet Details Operation
internal class GetWalletDetailsOperation: BaseOperation<Wallet> {
fileprivate let resource: () -> HTTPResource<Wallet>
fileprivate var callback: UpvestCompletion<Wallet>
/// Initialize this object
///
/// - parameters:
/// - authManager: an object to store credentials, keeping track of the current Credential..
/// - api: an object that allows talking to the Upvest API
/// - clientId: Client ID
/// - walletId: Unique wallet ID.
/// - callback: UpvestCompletion (Wallet, Error?)
public init(authManager: AuthManager,
api: UpvestAPIType,
clientId: String,
walletId: String,
callback: @escaping UpvestCompletion<Wallet>) {
self.callback = callback
resource = {
APIDefinition.getWalletInfomation(walletId: walletId)
}
super.init(authManager: authManager, api: api, clientId: clientId)
}
/// Execute the operation
override func start() {
super.start()
super.execute(resource: resource, completion: callback)
}
}
| 31.142857 | 98 | 0.637615 |
8aa5a09c5b92111366f35639ccf9fd46b13e96e8 | 5,737 | //
// MomentTests.swift
// MomentTests
//
// Created by Kevin Musselman on 12/28/15.
// Copyright © 2015 Kevin Musselman. All rights reserved.
//
import XCTest
class MomentTests: XCTestCase {
let today = NSDate()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// let finalTime = parseDateTimeString(("today" as NSString).UTF8String)
let d = getDate("today")
let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let components1 = NSCalendar.currentCalendar().components(unitFlags, fromDate: d)
let components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: today)
XCTAssertEqual(components1, components2, "today is right")
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testTomorrow(){
let d = getDate("tomorrow")
let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let components1 = NSCalendar.currentCalendar().components(unitFlags, fromDate: d)
var components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: today)
components2.day += 1
let date = NSCalendar.currentCalendar().dateFromComponents(components2)
components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: date!)
// print("components1 & 2 = \(components1) and \(components2)")
XCTAssertEqual(components1, components2, "tomorrow is right")
}
func testYesterday(){
let d = getDate("yesterday")
let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let components1 = NSCalendar.currentCalendar().components(unitFlags, fromDate: d)
var components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: today)
components2.day -= 1
let date = NSCalendar.currentCalendar().dateFromComponents(components2)
components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: date!)
// print("components1 & 2 = \(components1) and \(components2)")
XCTAssertEqual(components1, components2, "tomorrow is right")
// let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
//
// let components = NSDateComponents()
// components.year = 1987
// components.month = 3
// components.day = 17
// components.hour = 14
// components.minute = 20
// components.second = 0
//
// let date = calendar?.dateFromComponents(components)
}
func testDaysAgo(){
let d = getDate("3 days ago")
let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let components1 = NSCalendar.currentCalendar().components(unitFlags, fromDate: d)
var components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: today)
components2.day -= 3
let date = NSCalendar.currentCalendar().dateFromComponents(components2)
components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: date!)
// print("components1 & 2 = \(components1) and \(components2)")
XCTAssertEqual(components1, components2, "tomorrow is right")
}
func testDayAfterTomorrow(){
let d = getDate("day after tomorrow")
let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let components1 = NSCalendar.currentCalendar().components(unitFlags, fromDate: d)
var components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: today)
components2.day += 2
let date = NSCalendar.currentCalendar().dateFromComponents(components2)
components2 = NSCalendar.currentCalendar().components(unitFlags, fromDate: date!)
// print("components1 & 2 = \(components1) and \(components2)")
XCTAssertEqual(components1, components2, "day after tomorrow correct")
}
func testParsePerformance() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
_ = self.getDate("day after tomorrow")
}
}
func testParsePerformance2() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
_ = self.getDate("2 years from now at 1500")
}
}
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measureBlock {
// // Put the code you want to measure the time of here.
// let d = NSDate()
// let unitFlags: NSCalendarUnit = [.Minute, .Hour, .Day, .Month, .Year]
// let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: d)
// components.year += 2
// components.hour = 15
// components.minute = 0
//
// _ = NSCalendar.currentCalendar().dateFromComponents(components)
// }
// }
func getDate(str:String)->NSDate {
let when = (str as NSString).UTF8String
let finalTime:Double = parseDateTimeString(when)
let d = NSDate(timeIntervalSince1970: finalTime)
return d
}
}
| 39.027211 | 111 | 0.630643 |
d52ec868089070e9f1e7adcea4da7ee511f20069 | 225 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A:a{protocol a{}class C<T where h:a{typealias e=c | 45 | 87 | 0.768889 |
33e4aa4a72c7b885fd99673eaa0ab851b77315a9 | 4,163 | //
// CustomLabels.swift
// Poplur
//
// Created by Mark Meritt on 2016-11-13.
// Copyright © 2016 Apptist. All rights reserved.
//
import UIKit
import AVFoundation
class CircleButton: UIButton {
var audioPlayer: AVAudioPlayer!
required override init(frame: CGRect) {
super.init(frame: frame)
let radius = self.frame.width/2
self.layer.cornerRadius = radius
self.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// fatalError("init(coder:) has not been implemented")
let radius = self.frame.width/2
self.layer.cornerRadius = radius
self.clipsToBounds = true
}
func animateRadius(scale: CGFloat, soundOn: Bool) {
UIView.animate(withDuration: 0.5, animations: {
if(soundOn) {
self.playSound()
}
self.transform = CGAffineTransform.identity.scaledBy(x: scale, y: scale)
}, completion: { (finish) in
UIView.animate(withDuration: 0.5, animations: {
self.transform = CGAffineTransform.identity
})
})
}
func animateWithNewImage(scale: CGFloat, soundOn: Bool, image: UIImage) {
UIView.animate(withDuration: 0.5, animations: {
if(soundOn) {
self.playSound()
}
self.transform = CGAffineTransform.identity.scaledBy(x: scale, y: scale)
}, completion: { (finish) in
UIView.animate(withDuration: 0.5, animations: {
self.transform = CGAffineTransform.identity
self.setImage(image, for: .normal)
})
})
}
func setColorRed() {
self.backgroundColor = UIColor.init(red: 212/255, green: 107/255, blue: 107/255, alpha: 1.0)
}
func setColorBlue() {
self.backgroundColor = UIColor.init(red: 58/255, green: 93/255, blue: 131/255, alpha: 1.0)
}
func setColorGreen() {
self.backgroundColor = UIColor.init(red: 58/255, green: 131/255, blue: 108/255, alpha: 1.0)
}
func setColorOrange() {
self.backgroundColor = UIColor.init(red: 211/255, green: 115/255, blue: 76/255, alpha: 1.0)
}
func setColorClear() {
self.backgroundColor = UIColor.init(red: 216/255, green: 216/255, blue: 216/255, alpha: 0.80)
}
func setColourWhite() {
self.backgroundColor = UIColor.init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
}
func setColourVerifiedGreen() {
self.backgroundColor = UIColor.init(red: 0/255, green: 203/255, blue: 9/255, alpha: 1.0)
}
func addText(string: String, color: Int) {
self.titleLabel?.font = UIFont(name: "MyriadPro-Semibold", size: 20.5)
self.setTitle(string, for: UIControlState.normal)
self.setSpacing(space: 0.1)
if(color == 0) {
self.setTitleColor(UIColor.black, for: UIControlState.normal)
} else {
self.setTitleColor(UIColor.init(red: 134/255, green: 69/255, blue: 69/255, alpha: 1.0), for: UIControlState.normal)
}
}
func addBorder() {
self.layer.borderWidth = 2.88
self.layer.borderColor = UIColor.black.cgColor
}
func turnOff() {
UIView.animate(withDuration: 0.5) {
self.alpha = 0.1
self.isUserInteractionEnabled = false
}
}
func turnOn() {
UIView.animate(withDuration: 0.5) {
self.alpha = 1.0
self.isUserInteractionEnabled = true
}
}
private func playSound(){
let poppingSound = URL(fileURLWithPath: Bundle.main.path(forResource: "pop", ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: poppingSound)
audioPlayer.prepareToPlay()
audioPlayer.setVolume(0.1, fadeDuration: 0.1)
audioPlayer.play()
} catch {
print("Error getting the audio file")
}
}
}
| 28.710345 | 127 | 0.570022 |
e900d8c875adc258aa6075169a735cdb3ba4f9de | 11,342 | //
// LegacyConstructorRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 29/11/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct LegacyConstructorRule: ASTRule, CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "legacy_constructor",
name: "Legacy Constructor",
description: "Swift constructors are preferred over legacy convenience functions.",
kind: .idiomatic,
nonTriggeringExamples: [
"CGPoint(x: 10, y: 10)",
"CGPoint(x: xValue, y: yValue)",
"CGSize(width: 10, height: 10)",
"CGSize(width: aWidth, height: aHeight)",
"CGRect(x: 0, y: 0, width: 10, height: 10)",
"CGRect(x: xVal, y: yVal, width: aWidth, height: aHeight)",
"CGVector(dx: 10, dy: 10)",
"CGVector(dx: deltaX, dy: deltaY)",
"NSPoint(x: 10, y: 10)",
"NSPoint(x: xValue, y: yValue)",
"NSSize(width: 10, height: 10)",
"NSSize(width: aWidth, height: aHeight)",
"NSRect(x: 0, y: 0, width: 10, height: 10)",
"NSRect(x: xVal, y: yVal, width: aWidth, height: aHeight)",
"NSRange(location: 10, length: 1)",
"NSRange(location: loc, length: len)",
"UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)",
"UIEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)",
"NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)",
"NSEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)"
],
triggeringExamples: [
"↓CGPointMake(10, 10)",
"↓CGPointMake(xVal, yVal)",
"↓CGPointMake(calculateX(), 10)\n",
"↓CGSizeMake(10, 10)",
"↓CGSizeMake(aWidth, aHeight)",
"↓CGRectMake(0, 0, 10, 10)",
"↓CGRectMake(xVal, yVal, width, height)",
"↓CGVectorMake(10, 10)",
"↓CGVectorMake(deltaX, deltaY)",
"↓NSMakePoint(10, 10)",
"↓NSMakePoint(xVal, yVal)",
"↓NSMakeSize(10, 10)",
"↓NSMakeSize(aWidth, aHeight)",
"↓NSMakeRect(0, 0, 10, 10)",
"↓NSMakeRect(xVal, yVal, width, height)",
"↓NSMakeRange(10, 1)",
"↓NSMakeRange(loc, len)",
"↓UIEdgeInsetsMake(0, 0, 10, 10)",
"↓UIEdgeInsetsMake(top, left, bottom, right)",
"↓NSEdgeInsetsMake(0, 0, 10, 10)",
"↓NSEdgeInsetsMake(top, left, bottom, right)",
"↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)"
],
corrections: [
"↓CGPointMake(10, 10 )\n": "CGPoint(x: 10, y: 10)\n",
"↓CGPointMake(xPos, yPos )\n": "CGPoint(x: xPos, y: yPos)\n",
"↓CGSizeMake(10, 10)\n": "CGSize(width: 10, height: 10)\n",
"↓CGSizeMake( aWidth, aHeight )\n": "CGSize(width: aWidth, height: aHeight)\n",
"↓CGRectMake(0, 0, 10, 10)\n": "CGRect(x: 0, y: 0, width: 10, height: 10)\n",
"↓CGRectMake(xPos, yPos , width, height)\n":
"CGRect(x: xPos, y: yPos, width: width, height: height)\n",
"↓CGVectorMake(10, 10)\n": "CGVector(dx: 10, dy: 10)\n",
"↓CGVectorMake(deltaX, deltaY)\n": "CGVector(dx: deltaX, dy: deltaY)\n",
"↓NSMakePoint(10, 10 )\n": "NSPoint(x: 10, y: 10)\n",
"↓NSMakePoint(xPos, yPos )\n": "NSPoint(x: xPos, y: yPos)\n",
"↓NSMakeSize(10, 10)\n": "NSSize(width: 10, height: 10)\n",
"↓NSMakeSize( aWidth, aHeight )\n": "NSSize(width: aWidth, height: aHeight)\n",
"↓NSMakeRect(0, 0, 10, 10)\n": "NSRect(x: 0, y: 0, width: 10, height: 10)\n",
"↓NSMakeRect(xPos, yPos , width, height)\n":
"NSRect(x: xPos, y: yPos, width: width, height: height)\n",
"↓NSMakeRange(10, 1)\n": "NSRange(location: 10, length: 1)\n",
"↓NSMakeRange(loc, len)\n": "NSRange(location: loc, length: len)\n",
"↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)\n": "CGVector(dx: 10, dy: 10)\n" +
"NSRange(location: 10, length: 1)\n",
"↓CGVectorMake(dx, dy)\n↓NSMakeRange(loc, len)\n": "CGVector(dx: dx, dy: dy)\n" +
"NSRange(location: loc, length: len)\n",
"↓UIEdgeInsetsMake(0, 0, 10, 10)\n":
"UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)\n",
"↓UIEdgeInsetsMake(top, left, bottom, right)\n":
"UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)\n",
"↓NSEdgeInsetsMake(0, 0, 10, 10)\n":
"NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)\n",
"↓NSEdgeInsetsMake(top, left, bottom, right)\n":
"NSEdgeInsets(top: top, left: left, bottom: bottom, right: right)\n",
"↓NSMakeRange(0, attributedString.length)\n":
"NSRange(location: 0, length: attributedString.length)\n",
"↓CGPointMake(calculateX(), 10)\n": "CGPoint(x: calculateX(), y: 10)\n"
]
)
private static let constructorsToArguments = ["CGRectMake": ["x", "y", "width", "height"],
"CGPointMake": ["x", "y"],
"CGSizeMake": ["width", "height"],
"CGVectorMake": ["dx", "dy"],
"NSMakePoint": ["x", "y"],
"NSMakeSize": ["width", "height"],
"NSMakeRect": ["x", "y", "width", "height"],
"NSMakeRange": ["location", "length"],
"UIEdgeInsetsMake": ["top", "left", "bottom", "right"],
"NSEdgeInsetsMake": ["top", "left", "bottom", "right"]]
private static let constructorsToCorrectedNames = ["CGRectMake": "CGRect",
"CGPointMake": "CGPoint",
"CGSizeMake": "CGSize",
"CGVectorMake": "CGVector",
"NSMakePoint": "NSPoint",
"NSMakeSize": "NSSize",
"NSMakeRect": "NSRect",
"NSMakeRange": "NSRange",
"UIEdgeInsetsMake": "UIEdgeInsets",
"NSEdgeInsetsMake": "NSEdgeInsets"]
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard containsViolation(kind: kind, dictionary: dictionary),
let offset = dictionary.offset else {
return []
}
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))
]
}
private func violations(in file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [[String: SourceKitRepresentable]] {
guard containsViolation(kind: kind, dictionary: dictionary) else {
return []
}
return [dictionary]
}
private func containsViolation(kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> Bool {
guard kind == .call,
let name = dictionary.name,
dictionary.offset != nil,
let expectedArguments = type(of: self).constructorsToArguments[name],
dictionary.enclosedArguments.count == expectedArguments.count else {
return false
}
return true
}
private func violations(in file: File,
dictionary: [String: SourceKitRepresentable]) -> [[String: SourceKitRepresentable]] {
return dictionary.substructure.flatMap { subDict -> [[String: SourceKitRepresentable]] in
var dictionaries = violations(in: file, dictionary: subDict)
if let kind = subDict.kind.flatMap(SwiftExpressionKind.init(rawValue:)) {
dictionaries += violations(in: file, kind: kind, dictionary: subDict)
}
return dictionaries
}
}
private func violations(in file: File) -> [[String: SourceKitRepresentable]] {
return violations(in: file, dictionary: file.structure.dictionary).sorted { lhs, rhs in
(lhs.offset ?? 0) < (rhs.offset ?? 0)
}
}
public func correct(file: File) -> [Correction] {
let violatingDictionaries = violations(in: file)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for dictionary in violatingDictionaries.reversed() {
guard let offset = dictionary.offset, let length = dictionary.length,
let range = file.contents.bridge().byteRangeToNSRange(start: offset, length: length),
let name = dictionary.name,
let correctedName = type(of: self).constructorsToCorrectedNames[name],
file.ruleEnabled(violatingRanges: [range], for: self) == [range],
case let arguments = argumentsContents(file: file, arguments: dictionary.enclosedArguments),
let expectedArguments = type(of: self).constructorsToArguments[name],
arguments.count == expectedArguments.count else {
continue
}
if let indexRange = correctedContents.nsrangeToIndexRange(range) {
let joinedArguments = zip(expectedArguments, arguments).map { "\($0): \($1)" }.joined(separator: ", ")
let replacement = correctedName + "(" + joinedArguments + ")"
correctedContents = correctedContents.replacingCharacters(in: indexRange, with: replacement)
adjustedLocations.insert(range.location, at: 0)
}
}
let corrections = adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
file.write(correctedContents)
return corrections
}
private func argumentsContents(file: File, arguments: [[String: SourceKitRepresentable]]) -> [String] {
let contents = file.contents.bridge()
return arguments.flatMap { argument -> String? in
guard argument.name == nil,
let offset = argument.offset,
let length = argument.length else {
return nil
}
return contents.substringWithByteRange(start: offset, length: length)
}
}
}
| 49.313043 | 118 | 0.523893 |
1cbf8c088bc6bd46283624e978f247ad508574dd | 260 | // @copyright Trollwerks Inc.
@testable import MTP
import XCTest
final class MyCountsPageVCTests: TestCase {
func testInitWithCoder() {
// when
let sut = MyCountsPageVC(coder: NSCoder())
// then
XCTAssertNil(sut)
}
}
| 17.333333 | 50 | 0.630769 |
f9a54e9a9816ac70d3e3246b3ff2fe309b529115 | 339 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a{{{{{}}}}typealias d:d
{
}
}a( : :
([
{
((((([ { a :{{ {{{{
a :{
{ {a(
{{ { { {
{
{ b { {{ {
a{{{{ d {
}
() {
}
}}}
} a
{
{
}
}aga
{{ {
{
{{
} b{ {{
a= = "
}
t
| 9.970588 | 87 | 0.486726 |
76af493b70b810320baa58206c713b03936b0c1f | 3,401 | // RUN: not %target-swift-frontend -color-diagnostics -diagnostic-style=llvm -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace
// RUN: not %target-swift-frontend -no-color-diagnostics -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace --check-prefix=NO-COLOR
// RUN: not %target-swift-frontend -diagnostic-style=swift -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --check-prefix=CHECK-DESCRIPTIVE
// A diagnostic with no educational notes
let x = 1 +
// CHECK:{{.*}}[0m[0;1;31merror: [0m[1mexpected expression after operator
// CHECK-NOT: {{-+$}}
// NO-COLOR:{{.*}}error: expected expression after operator
// NO-COLOR-NOT: {{-+$}}
// A diagnostic with an educational note using supported markdown features
extension (Int, Int) {}
// CHECK:{{.*}}[0m[0;1;31merror: [0m[1mnon-nominal type '(Int, Int)' cannot be extended
// CHECK-NEXT:[0mextension (Int, Int) {}
// CHECK-NEXT:[0;1;32m^ ~~~~~~~~~~
// CHECK-NEXT:[0m[0m[1mNominal Types[0m
// CHECK-NEXT:--------------
// CHECK-EMPTY:
// CHECK-NEXT:Nominal types documentation content. This is a paragraph
// CHECK-EMPTY:
// CHECK-NEXT: blockquote
// CHECK-NEXT: {{$}}
// CHECK-NEXT: - item 1
// CHECK-NEXT: - item 2
// CHECK-NEXT: - item 3
// CHECK-NEXT: {{$}}
// CHECK-NEXT: let x = 42
// CHECK-NEXT: if x > 0 {
// CHECK-NEXT: print("positive")
// CHECK-NEXT: }
// CHECK-NEXT: {{$}}
// CHECK-NEXT:Type 'MyClass'
// CHECK-EMPTY:
// CHECK-NEXT:[Swift](swift.org)
// CHECK-EMPTY:
// CHECK-NEXT:[0m[1mbold[0m italics
// CHECK-NEXT:--------------
// CHECK-NEXT:[0m[1mHeader 1[0m
// CHECK-NEXT:[0m[1mHeader 3[0m
// NO-COLOR:{{.*}}error: non-nominal type '(Int, Int)' cannot be extended
// NO-COLOR-NEXT:extension (Int, Int) {}
// NO-COLOR-NEXT:^ ~~~~~~~~~~
// NO-COLOR-NEXT:Nominal Types
// NO-COLOR-NEXT:--------------
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT:Nominal types documentation content. This is a paragraph
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT: blockquote
// NO-COLOR-NEXT: {{$}}
// NO-COLOR-NEXT: - item 1
// NO-COLOR-NEXT: - item 2
// NO-COLOR-NEXT: - item 3
// NO-COLOR-NEXT: {{$}}
// NO-COLOR-NEXT: let x = 42
// NO-COLOR-NEXT: if x > 0 {
// NO-COLOR-NEXT: print("positive")
// NO-COLOR-NEXT: }
// NO-COLOR-NEXT: {{$}}
// NO-COLOR-NEXT:Type 'MyClass'
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT:[Swift](swift.org)
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT:bold italics
// NO-COLOR-NEXT:--------------
// NO-COLOR-NEXT:Header 1
// NO-COLOR-NEXT:Header 3
// CHECK-DESCRIPTIVE: educational-notes.swift
// CHECK-DESCRIPTIVE-NEXT: | // A diagnostic with an educational note
// CHECK-DESCRIPTIVE-NEXT: | extension (Int, Int) {}
// CHECK-DESCRIPTIVE-NEXT: | ^ error: expected expression after operator
// CHECK-DESCRIPTIVE-NEXT: |
// CHECK-DESCRIPTIVE: educational-notes.swift
// CHECK-DESCRIPTIVE-NEXT: | // A diagnostic with an educational note
// CHECK-DESCRIPTIVE-NEXT: | extension (Int, Int) {}
// CHECK-DESCRIPTIVE-NEXT: | ~~~~~~~~~~
// CHECK-DESCRIPTIVE-NEXT: | ^ error: non-nominal type '(Int, Int)' cannot be extended
// CHECK-DESCRIPTIVE-NEXT: |
// CHECK-DESCRIPTIVE-NEXT: Nominal Types
// CHECK-DESCRIPTIVE-NEXT: -------------
| 40.011765 | 224 | 0.648339 |
e639a17fb5f7b030794cbe905c5cee0c5dc22483 | 1,427 | ///
/// GenericActionContainer.swift
///
/// Copyright 2017 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 1/19/17.
///
import Foundation
import TraceLog
class GenericActionContainer<ActionType: GenericAction>: ActionContainer {
private let genericAction: ActionType
internal init(action: ActionType, notificationService: NotificationService, completionBlock: ((_ actionProxy: ActionProxy) -> Void)?) {
self.genericAction = action
super.init(action: action, notificationService: notificationService, completionBlock: completionBlock)
logTrace(Log.tag, level: 4) { "Proxy \(self) created for action \(self.action)." }
}
internal override func execute() throws {
try self.genericAction.execute()
}
override func cancel() {
self.genericAction.cancel()
super.cancel()
}
}
| 31.711111 | 139 | 0.704275 |
e432278ffb54856628d17616688b09c7adeadb87 | 1,596 | //
// CPFunnyLabViewController.swift
// BeeFun
//
// Created by WengHengcong on 3/25/16.
// Copyright © 2016 JungleSong. All rights reserved.
//
import UIKit
class BFFunnyLabViewController: BFBaseViewController {
@IBOutlet weak var lab_awardNameTf: UITextField!
override func viewDidLoad() {
self.title = "Funny Lab"
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func leftItemAction(_ sender: UIButton?) {
_ = self.navigationController?.popViewController(animated: true)
}
@IBAction func lag_getAward(_ sender: AnyObject) {
let userDefault = UserDefaults.standard
var awardUrl = ""
// auth url: github-awards.com/auth/github
if let username = lab_awardNameTf.text {
let firstNeedAuth = userDefault.object(forKey: "\(username)needauth")
if firstNeedAuth == nil {
awardUrl = "http://github-awards.com/auth/github"
} else {
awardUrl = "http://github-awards.com/users/search?login=\(username)"
}
// let awardVC = CPFunnyAwardViewController()
// awardVC.username = username
// awardVC.url = awardUrl
// self.navigationController?.pushViewController(awardVC, animated: true)
} else {
JSMBHUDBridge.showText("Input your github username", view: self.view)
return
}
}
// FIXME: 网络重连
override func reconnect() {
super.reconnect()
}
}
| 25.741935 | 84 | 0.615915 |
bb0c76339fd648d2286c95985601ee9091ea9c12 | 3,470 | // Copyright 2017-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
//
// Buffer.swift
// GoldenGate
//
// Created by Marcel Jackwerth on 4/25/18.
//
import BluetoothConnection
import Foundation
import GoldenGateXP
public typealias Port = BluetoothConnection.Port
extension Buffer {
/// Returns an `UnsafeBuffer` for this `DataSink`.
var gg: UnsafeBuffer {
if let unsafe = self as? UnsafeBuffer {
return unsafe
} else {
return ManagedBuffer(self)
}
}
}
/// A `Buffer` that can be passed to C or comes from C.
protocol UnsafeBuffer: Buffer {
/// The pointer type to a `Buffer`.
typealias Ref = UnsafeMutablePointer<GG_Buffer>
/// A pointer to this object.
var ref: Ref { get }
}
internal final class UnmanagedBuffer: UnsafeBuffer {
typealias Ref = UnsafeMutablePointer<GG_Buffer>
let ref: Ref
init(_ ref: Ref!) {
self.ref = ref
GG_Buffer_Retain(ref)
}
///
convenience init(_ ref: UnsafeMutablePointer<GG_StaticBuffer>) {
// NOTE: GG_StaticBuffer_AsBuffer is a macro that uses GG_Cast
self.init(ref.withMemoryRebound(to: GG_Buffer.self, capacity: 1) { $0 })
}
deinit {
GG_Buffer_Release(ref)
}
var count: Int {
return GG_Buffer_GetDataSize(ref)
}
var data: Data {
return Data(bytes: GG_Buffer_GetData(ref)!, count: count)
}
func getRawData() -> UnsafePointer<UInt8> {
return GG_Buffer_GetData(ref)!
}
func useRawData() -> UnsafeMutablePointer<UInt8>! {
return GG_Buffer_UseData(ref)
}
}
/// Wraps buffers that are implemented in Swift so that
/// they can be used in C.
final class ManagedBuffer: GGAdaptable, UnsafeBuffer {
typealias GGObject = GG_Buffer
typealias GGInterface = GG_BufferInterface
private let instance: Buffer
let adapter: Adapter
private static var interface = GG_BufferInterface(
Retain: { ref in
return Adapter.takeUnretained(ref).passRetained()
},
Release: { ref in
let instance = Adapter.takeUnretained(ref)
Unmanaged.passUnretained(instance).release()
},
GetData: { ref in
return Adapter.takeUnretained(ref).getRawData()
},
UseData: { ref in
return Adapter.takeUnretained(ref).useRawData()
},
GetDataSize: { ref in
return Adapter.takeUnretained(ref).count
}
)
fileprivate init(_ instance: Buffer) {
assert(!(instance is UnsafeBuffer))
self.instance = instance
self.adapter = Adapter(iface: &type(of: self).interface)
adapter.bind(to: self)
}
/// Creates a new managed buffer backed by the given data.
public convenience init(data: Data) {
self.init(NSDataBuffer(data as NSData))
}
var count: Int {
return instance.count
}
var data: Data {
return instance.data
}
func getRawData() -> UnsafePointer<UInt8> {
return instance.getRawData()
}
func useRawData() -> UnsafeMutablePointer<UInt8>! {
return instance.useRawData()
}
/// Increments the retain counter by one.
///
/// Useful when returning a buffer to C.
///
/// - Note: In ARC, this would normally be solved via autorelease
func passRetained() -> Ref {
_ = Unmanaged.passRetained(self)
return ref
}
}
| 25.144928 | 80 | 0.62536 |
e5c863eda65981336494955f79ec5ff7e1357656 | 462 | //
// Album+Mapping.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Domain
import ObjectMapper
extension Album: ImmutableMappable {
// JSON -> Object
public init(map: Map) throws {
title = try map.value("title")
uid = try map.value("id", using: UidTransform())
userId = try map.value("userId", using: UidTransform())
}
}
| 22 | 63 | 0.645022 |
ab8e47727f4a95255d0044e073717d1c575a2ada | 822 | // swift-tools-version:5.3
import PackageDescription
// Version is technically not required here, SPM doesn't check
let version = "2.0.0-beta.5"
// Tag is required to point towards the right asset. SPM requires the tag to follow semantic versioning to be able to resolve it.
let tag = "2.0.0-beta.5"
let checksum = "a53a83db87a5e705d58227f6d9088c76425ddb00e0a9eded87ae845ce5903529"
let url = "https://github.com/sparkle-project/Sparkle/releases/download/\(tag)/Sparkle-for-Swift-Package-Manager.zip"
let package = Package(
name: "Sparkle",
platforms: [.macOS(.v10_11)],
products: [
.library(
name: "Sparkle",
targets: ["Sparkle"])
],
targets: [
.binaryTarget(
name: "Sparkle",
url: url,
checksum: checksum
)
]
)
| 30.444444 | 129 | 0.648418 |
e4fbba9937736b01ab4dc7f64d90a8c2ad3f6106 | 3,980 | //
// QRCodeVC.swift
// Libralize-iOS
//
// Created by Libralize on 13/10/2021.
//
import UIKit
import WebKit
import Liberalize_Frontend_iOS_SDK
class QRCodeVC: ViewController {
private let provider = ApiProvider()
private let qrData: String
private let source: String
private let paymentId: String
private lazy var cancelButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancel))
return button
}()
// 3.1.a Init QRCode Component
private lazy var qrCodeView = QRCodeView(size: 256)
// 3.1.b Init Pay With OCBC Button
private lazy var ocbcButton = PayWithOCBCButton()
// Use timer to check payment status every 3 seconds
private lazy var timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] timer in
guard let self = self else { return }
self.checkQRCodePaymentStatus()
}
init(qrData: String, source: String, paymentId: String) {
self.qrData = qrData
self.source = source
self.paymentId = paymentId
super.init(nibName: nil, bundle: nil)
self.title = "QR Code"
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func makeUI() {
super.makeUI()
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
navigationController?.overrideUserInterfaceStyle = .light
}
self.navigationController?.setNavigationBarHidden(false, animated: true)
navigationItem.title = title
view.backgroundColor = .white
navigationItem.setLeftBarButton(cancelButton, animated: false)
view.addSubViews([qrCodeView, ocbcButton])
ocbcButton.isHidden = true
qrCodeView.makeConstraint(
centerXAnchor: view.centerXAnchor,
centerYAnchor: view.centerYAnchor
)
ocbcButton.makeConstraint(
topAnchor: qrCodeView.bottomAnchor, topConstant: 8,
leftAnchor: qrCodeView.leftAnchor,
rightAnchor: qrCodeView.rightAnchor
)
loadData()
}
// 3.2 Display QRCode data and OCBC button
private func loadData() {
// 3.2.a Display QRCode data
qrCodeView.loadQR(qrData: qrData, source: source)
// 3.2.b Show "Paywith OCBC" button when source is "paynow"
// 3.2.c Config qrData and paymentId for OCBC button
ocbcButton.isHidden = source != "paynow"
ocbcButton.set(qrString: qrData, paymentId: paymentId)
// 3.3 Start loop to check payment status
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
self.timer.fire()
}
}
@objc private func cancel() {
self.navigationController?.dismiss(animated: true, completion: nil)
}
// 3.3.a Check payment status
@objc private func checkQRCodePaymentStatus() {
provider.getPayment(paymentId: paymentId) { error, payment in
print("Payment status: \(String(describing: payment?.state))")
// 3.3.a Close this screen when payment state is "SUCCESS"
if payment?.state == "SUCCESS" {
self.dismiss(animated: true, completion: nil)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer.invalidate()
}
}
extension QRCodeVC: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
loading(show: false)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
loading(show: false)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
loading(show: false)
}
}
| 32.357724 | 120 | 0.637437 |
4bf32d2831cb7d9eb08ae5374daac43776698faa | 1,905 | //
// MainViewUITests.swift
// NYTimes ArticlesUITests
//
// Created by Shahul Hamed Shaik (HLB) on 13/03/2022.
//
import XCTest
class MainViewUITests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
}
override func tearDown() {
super.tearDown()
}
func testMainView() {
let app = XCUIApplication()
app.launch()
let mainScreen = MainScreen(app: app)
XCTAssertTrue(mainScreen.isAllDataExists())
}
func testSearchAricles() {
let app = XCUIApplication()
app.launch()
let mainScreen = MainScreen(app: app)
mainScreen.openSearchAritcles()
let searchArticlesScreen = SearchArticlesScreen(app: app)
XCTAssertTrue(searchArticlesScreen.isAllElementsExists())
}
func testMostViewedArticles() {
let app = XCUIApplication()
app.launch()
let mainScreen = MainScreen(app: app)
mainScreen.openMostViewed()
let articlesScreen = ArticlesListScreen(app: app)
XCTAssertTrue(articlesScreen.isArticlesScreenExists())
}
func testMostSharedArticles() {
let app = XCUIApplication()
app.launch()
let mainScreen = MainScreen(app: app)
mainScreen.openMostShared()
let articlesScreen = ArticlesListScreen(app: app)
XCTAssertTrue(articlesScreen.isArticlesScreenExists())
}
func testMostEmailedArticles() {
let app = XCUIApplication()
app.launch()
let mainScreen = MainScreen(app: app)
mainScreen.openMostEmailed()
let articlesScreen = ArticlesListScreen(app: app)
XCTAssertTrue(articlesScreen.isArticlesScreenExists())
}
}
| 23.8125 | 65 | 0.592126 |
670a59cfea6cc5631fb9eecc1dd03f0a465cf687 | 2,736 | import UIKit
extension UITableView {
/**
Mimic a user taking an edit action on the cell at the given index path in
the table view.
- parameters:
- title: The title of the edit action to take
- at: The index path at which to attempt to take this action
- throws:
A `FleetError` is there is no cell at the given index path, if the data source
does not allow editing of the given index path, or if there is no edit action with the
given title on the cell.
*/
public func selectCellAction(withTitle title: String, at indexPath: IndexPath) {
guard let dataSource = dataSource else {
FleetError(Fleet.TableViewError.dataSourceRequired(userAction: "select cell action")).raise()
return
}
guard let delegate = delegate else {
FleetError(Fleet.TableViewError.delegateRequired(userAction: "select cell action")).raise()
return
}
if !delegate.responds(to: #selector(UITableViewDelegate.tableView(_:editActionsForRowAt:))) {
FleetError(Fleet.TableViewError.incompleteDelegate(required: "UITableViewDelegate.tableView(_:editActionsForRowAt:)", userAction: "select cell action")).raise()
return
}
let sectionCount = numberOfSections
if indexPath.section >= sectionCount {
FleetError(Fleet.TableViewError.sectionDoesNotExist(sectionNumber: indexPath.section)).raise()
return
}
let rowCount = numberOfRows(inSection: indexPath.section)
if indexPath.row >= rowCount {
FleetError(Fleet.TableViewError.rowDoesNotExist(at: indexPath)).raise()
return
}
let doesDataSourceImplementCanEditRow = dataSource.responds(to: #selector(UITableViewDataSource.tableView(_:canEditRowAt:)))
let canEditCell = doesDataSourceImplementCanEditRow && dataSource.tableView!(self, canEditRowAt: indexPath)
if !canEditCell {
FleetError(Fleet.TableViewError.rejectedAction(at: indexPath, reason: "Table view data source does not allow editing of that row.")).raise()
return
}
let editActions = delegate.tableView!(self, editActionsForRowAt: indexPath)
let actionOpt = editActions?.first() { element in
return element.title == title
}
guard let action = actionOpt else {
FleetError(Fleet.TableViewError.cellActionDoesNotExist(at: indexPath, title: title)).raise()
return
}
delegate.tableView?(self, willBeginEditingRowAt: indexPath)
action.handler!(action, indexPath)
delegate.tableView?(self, didEndEditingRowAt: indexPath)
}
}
| 40.835821 | 172 | 0.667398 |
e6a062eb13028dac2ac2f671451192f1ea005f9c | 3,037 | //
// GeneralSettingsViewController.swift
// Yippy
//
// Created by Matthew Davidson on 12/4/20.
// Copyright © 2020 MatthewDavidson. All rights reserved.
//
import Foundation
import Cocoa
import RxSwift
class GeneralSettingsViewController: NSViewController {
@IBOutlet var maxHistoryItemsPopUpButton: NSPopUpButton!
@IBOutlet var showsRichTextButton: NSButton!
@IBOutlet var pastesRichTextButton: NSButton!
private var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setupMaxHistoryItemsPopUpButton()
setupShowsRichTextButton()
setupPastesRichTextButton()
}
// MARK: Setup view
private func setupMaxHistoryItemsPopUpButton() {
maxHistoryItemsPopUpButton.removeAllItems()
for val in Constants.settings.maxHistoryItemsOptions {
maxHistoryItemsPopUpButton.addItem(withTitle: "\(val)")
}
State.main.history.maxItems.subscribe(onNext: onMaxHistoryItems).disposed(by: disposeBag)
maxHistoryItemsPopUpButton.target = self
maxHistoryItemsPopUpButton.action = #selector(onMaxItemsSelected)
maxHistoryItemsPopUpButton.isEnabled = true
maxHistoryItemsPopUpButton.autoenablesItems = true
}
private func setupShowsRichTextButton() {
State.main.showsRichText.subscribe(onNext: onShowsRichText).disposed(by: disposeBag)
showsRichTextButton.target = self
showsRichTextButton.action = #selector(onShowsRichTextButtonClicked)
}
private func setupPastesRichTextButton() {
State.main.pastesRichText.subscribe(onNext: onPastesRichText).disposed(by: disposeBag)
pastesRichTextButton.target = self
pastesRichTextButton.action = #selector(onPastesRichTextButtonClicked)
}
// MARK: Bind to settings
private func onMaxHistoryItems(_ maxItems: Int) {
let newIndex = Constants.settings.maxHistoryItemsOptions.firstIndex(of: maxItems) ?? Constants.settings.maxHistoryItemsDefaultIndex
if newIndex != maxHistoryItemsPopUpButton.indexOfSelectedItem {
maxHistoryItemsPopUpButton.selectItem(at: newIndex)
}
}
private func onShowsRichText(_ showsRichText: Bool) {
showsRichTextButton.state = showsRichText ? .on : .off
}
private func onPastesRichText(_ pastesRichText: Bool) {
pastesRichTextButton.state = pastesRichText ? .on : .off
}
// MARK: Handle Actions
@objc private func onMaxItemsSelected() {
State.main.history.setMaxItems(Constants.settings.maxHistoryItemsOptions[maxHistoryItemsPopUpButton.indexOfSelectedItem])
}
@objc private func onShowsRichTextButtonClicked() {
State.main.showsRichText.accept(showsRichTextButton.state == .on)
}
@objc private func onPastesRichTextButtonClicked() {
State.main.pastesRichText.accept(pastesRichTextButton.state == .on)
}
}
| 33.373626 | 139 | 0.70135 |
e84ef2e41cd19dc3105cc829251a1a31626a6064 | 910 | //
// SwitchCell.swift
// Yelp
//
// Created by Stephen Chudleigh on 10/21/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
@objc protocol SwitchCellDelegate {
@objc optional func switchCell(switchCell: SwitchCell, didChangeValue value: Bool)
}
class SwitchCell: UITableViewCell {
@IBOutlet weak var switchLabel: UILabel!
@IBOutlet weak var onSwitch: UISwitch!
weak var delegate: SwitchCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
onSwitch.addTarget(self, action: #selector(onSwitchChanged), for: .valueChanged)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func onSwitchChanged() {
delegate?.switchCell?(switchCell: self, didChangeValue: true)
}
}
| 23.947368 | 88 | 0.689011 |
fe4ef91155842ce3371833e730760d72eff0fef0 | 6,546 | //
// CodeEditorTextView.swift
// CodeEdit
//
// Created by Marco Carnevali on 19/03/22.
//
import Cocoa
import SwiftUI
import AppPreferences
public class CodeEditorTextView: NSTextView {
@StateObject
private var prefs: AppPreferencesModel = .shared
init(
textContainer container: NSTextContainer?
) {
super.init(frame: .zero, textContainer: container)
drawsBackground = true
isEditable = true
isHorizontallyResizable = false
isVerticallyResizable = true
allowsUndo = true
isRichText = false
isGrammarCheckingEnabled = false
isContinuousSpellCheckingEnabled = false
isAutomaticQuoteSubstitutionEnabled = false
isAutomaticDashSubstitutionEnabled = false
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private var swiftSelectedRange: Range<String.Index> {
let string = self.string
guard !string.isEmpty else { return string.startIndex..<string.startIndex }
guard let selectedRange = Range(self.selectedRange(), in: string) else {
assertionFailure("Could not convert the selectedRange")
return string.startIndex..<string.startIndex
}
return selectedRange
}
private var currentLine: String {
let string = self.string
return String(string[string.lineRange(for: swiftSelectedRange)])
}
public override func insertNewline(_ sender: Any?) {
// get line before newline
let currentLine = self.currentLine
let prefix = currentLine.prefix {
guard let scalar = $0.unicodeScalars.first else {
return false
}
return CharacterSet.whitespaces.contains(scalar)
}
super.insertNewline(sender)
if !prefix.isEmpty {
insertText(String(prefix), replacementRange: selectedRange())
}
}
let autoPairs = [
"(": ")",
"{": "}",
"[": "]",
"\"": "\"",
]
public override func insertText(_ string: Any, replacementRange: NSRange) {
super.insertText(string, replacementRange: replacementRange)
guard let string = string as? String,
let end = autoPairs[string]
else { return }
super.insertText(end, replacementRange: selectedRange())
super.moveBackward(self)
}
public override func insertTab(_ sender: Any?) {
super.insertText(
String(
repeating: " ",
count: prefs.preferences.textEditing.defaultTabWidth
),
replacementRange: selectedRange()
)
}
/// input a backslash (\\)
@IBAction func inputBackSlash(_ sender: Any?) {
super.insertText(
"\\",
replacementRange: selectedRange()
)
}
/// Override of the default context menu in the editor...
///
/// This is a basic view without any functionality, once we have most the items built
/// we will start connecting the menu items to their respective actions.
public override func menu(for event: NSEvent) -> NSMenu? {
guard var menu = super.menu(for: event) else { return nil }
menu = helpMenu(menu)
menu = codeMenu(menu)
menu = gitMenu(menu)
menu = removeMenus(menu)
return menu
}
func helpMenu(_ menu: NSMenu) -> NSMenu {
menu.insertItem(withTitle: "Jump To Definition",
action: nil,
keyEquivalent: "",
at: 0)
menu.insertItem(withTitle: "Show Code Actions",
action: nil,
keyEquivalent: "",
at: 1)
menu.insertItem(withTitle: "Show Quick Help",
action: nil,
keyEquivalent: "",
at: 2)
menu.insertItem(.separator(), at: 3)
return menu
}
func codeMenu(_ menu: NSMenu) -> NSMenu {
menu.insertItem(withTitle: "Refactor",
action: nil,
keyEquivalent: "",
at: 4)
menu.insertItem(withTitle: "Find",
action: nil,
keyEquivalent: "",
at: 5)
menu.insertItem(withTitle: "Navigate",
action: nil,
keyEquivalent: "",
at: 6)
menu.insertItem(.separator(), at: 7)
return menu
}
func gitMenu(_ menu: NSMenu) -> NSMenu {
menu.insertItem(withTitle: "Show Last Change For Line",
action: nil,
keyEquivalent: "",
at: 8)
menu.insertItem(withTitle: "Create Code Snippet...",
action: nil,
keyEquivalent: "",
at: 9)
menu.insertItem(withTitle: "Add Pull Request Discussion to Current Line",
action: nil,
keyEquivalent: "",
at: 10)
menu.insertItem(.separator(), at: 11)
return menu
}
/// This removes the default menu items in the context menu based on their name..
///
/// The only problem currently is how well it would work with other languages.
func removeMenus(_ menu: NSMenu) -> NSMenu {
let removeItemsContaining = [
// Learn Spelling
"_learnSpellingFromMenu:",
// Ignore Spelling
"_ignoreSpellingFromMenu:",
// Spelling suggestion
"_changeSpellingFromMenu:",
// Search with Google
"_searchWithGoogleFromMenu:",
// Share, Font, Spelling and Grammar, Substitutions, Transformations
// Speech, Layout Orientation
"submenuAction:",
// Lookup, Translate
"_rvMenuItemAction"
]
for item in menu.items {
if let itemAction = item.action {
if removeItemsContaining.contains(String(describing: itemAction)) {
// Get localized item name, and remove it.
let index = menu.indexOfItem(withTitle: item.title)
if index >= 0 {
menu.removeItem(at: index)
}
}
}
}
return menu
}
}
| 29.486486 | 89 | 0.536358 |
62e270f046cd611345693ddf4bdcad13bf54cc78 | 1,406 | //
// TipAppUITests.swift
// TipAppUITests
//
// Created by Mike Neri on 12/30/20.
//
import XCTest
class TipAppUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.697674 | 182 | 0.653627 |
8f1c5129fbb95c7673dac288c331c35762117a3f | 183 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(DoubleTests.allTests),
testCase(FloatTests.allTests),
]
}
#endif
| 16.636364 | 45 | 0.710383 |
2f489c30a42e495a121e62a7e0be587313166344 | 1,220 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// MockReceiptFetcher.swift
//
@testable import RevenueCat
class MockReceiptFetcher: ReceiptFetcher {
var receiptDataCalled = false
var shouldReturnReceipt = true
var shouldReturnZeroBytesReceipt = false
var receiptDataTimesCalled = 0
var receiptDataReceivedRefreshPolicy: ReceiptRefreshPolicy?
convenience init(requestFetcher: StoreKitRequestFetcher) {
self.init(requestFetcher: requestFetcher, bundle: .main)
}
override func receiptData(refreshPolicy: ReceiptRefreshPolicy, completion: @escaping ((Data?) -> Void)) {
receiptDataReceivedRefreshPolicy = refreshPolicy
receiptDataCalled = true
receiptDataTimesCalled += 1
if (shouldReturnReceipt) {
if (shouldReturnZeroBytesReceipt) {
completion(Data())
} else {
completion(Data(1...3))
}
} else {
completion(nil)
}
}
}
| 28.372093 | 109 | 0.663115 |
71189c19cb531c7e49d32a5b52de917ebdd82a46 | 509 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func g<T>() {
S(AnyObject) {
}
convenience init(array: U -> : Int
b: A? = {
func a(")
class C<H : C<T>(b<T>](f
| 31.8125 | 79 | 0.707269 |
9b9599cd3753e9c1e76db789649e814301486bb4 | 670 | //: [Previous](@previous)
//: ### Ingredients calculated! What if...?
struct Dough {
let yield: Double
let hydration: Double
var flour: Double {
return 100 * yield / (100 + hydration)
}
var water: Double {
return yield - flour
}
var yeast: Double {
return flour * 1%
}
var salt: Double {
return flour * 1.9%
}
init(yield: Double, hydrationPercentage hydration: Double = 70.0) {
self.yield = yield
self.hydration = hydration
}
}
let dough = Dough(yield: 1700)
dough.yield
dough.flour
dough.water
dough.yeast
dough.salt
//: [Next](@next)
| 16.75 | 71 | 0.559701 |
e6f25a9ce8c128924860ddfa440211161401ebe2 | 13,249 | //
// AppDelegate.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import RSCore
import RSWeb
import Account
import BackgroundTasks
import os.log
var appDelegate: AppDelegate!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UnreadCountProvider {
private var bgTaskDispatchQueue = DispatchQueue.init(label: "BGTaskScheduler")
private var waitBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
private var syncBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
var syncTimer: ArticleStatusSyncTimer?
var shuttingDown = false {
didSet {
if shuttingDown {
syncTimer?.shuttingDown = shuttingDown
syncTimer?.invalidate()
}
}
}
var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Application")
var userNotificationManager: UserNotificationManager!
var faviconDownloader: FaviconDownloader!
var imageDownloader: ImageDownloader!
var authorAvatarDownloader: AuthorAvatarDownloader!
var webFeedIconDownloader: WebFeedIconDownloader!
var extensionContainersFile: ExtensionContainersFile!
var extensionFeedAddRequestFile: ExtensionFeedAddRequestFile!
var unreadCount = 0 {
didSet {
if unreadCount != oldValue {
postUnreadCountDidChangeNotification()
UIApplication.shared.applicationIconBadgeNumber = unreadCount
}
}
}
var isSyncArticleStatusRunning = false
var isWaitingForSyncTasks = false
override init() {
super.init()
appDelegate = self
let documentAccountURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let documentAccountsFolder = documentAccountURL.appendingPathComponent("Accounts").absoluteString
let documentAccountsFolderPath = String(documentAccountsFolder.suffix(from: documentAccountsFolder.index(documentAccountsFolder.startIndex, offsetBy: 7)))
AccountManager.shared = AccountManager(accountsFolder: documentAccountsFolderPath)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountRefreshDidFinish(_:)), name: .AccountRefreshDidFinish, object: nil)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AppDefaults.registerDefaults()
let isFirstRun = AppDefaults.isFirstRun
if isFirstRun {
os_log("Is first run.", log: log, type: .info)
}
if isFirstRun && !AccountManager.shared.anyAccountHasAtLeastOneFeed() {
let localAccount = AccountManager.shared.defaultAccount
DefaultFeedsImporter.importDefaultFeeds(account: localAccount)
}
registerBackgroundTasks()
CacheCleaner.purgeIfNecessary()
initializeDownloaders()
initializeHomeScreenQuickActions()
DispatchQueue.main.async {
self.unreadCount = AccountManager.shared.unreadCount
}
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .sound, .alert]) { (granted, error) in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
UNUserNotificationCenter.current().delegate = self
userNotificationManager = UserNotificationManager()
extensionContainersFile = ExtensionContainersFile()
extensionFeedAddRequestFile = ExtensionFeedAddRequestFile()
syncTimer = ArticleStatusSyncTimer()
#if DEBUG
syncTimer!.update()
#endif
return true
}
func applicationWillTerminate(_ application: UIApplication) {
shuttingDown = true
}
// MARK: Notifications
@objc func unreadCountDidChange(_ note: Notification) {
if note.object is AccountManager {
unreadCount = AccountManager.shared.unreadCount
}
}
@objc func accountRefreshDidFinish(_ note: Notification) {
AppDefaults.lastRefresh = Date()
}
// MARK: - API
func manualRefresh(errorHandler: @escaping (Error) -> ()) {
UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate } ).forEach {
$0.cleanUp(conditional: true)
}
AccountManager.shared.refreshAll(errorHandler: errorHandler)
}
func resumeDatabaseProcessingIfNecessary() {
if AccountManager.shared.isSuspended {
AccountManager.shared.resumeAll()
os_log("Application processing resumed.", log: self.log, type: .info)
}
}
func prepareAccountsForBackground() {
extensionFeedAddRequestFile.suspend()
syncTimer?.invalidate()
scheduleBackgroundFeedRefresh()
syncArticleStatus()
waitForSyncTasksToFinish()
}
func prepareAccountsForForeground() {
extensionFeedAddRequestFile.resume()
if let lastRefresh = AppDefaults.lastRefresh {
if Date() > lastRefresh.addingTimeInterval(15 * 60) {
AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log)
} else {
AccountManager.shared.syncArticleStatusAll()
syncTimer?.update()
}
} else {
AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log)
}
}
func logMessage(_ message: String, type: LogItem.ItemType) {
print("logMessage: \(message) - \(type)")
}
func logDebugMessage(_ message: String) {
logMessage(message, type: .debug)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
defer { completionHandler() }
if let sceneDelegate = response.targetScene?.delegate as? SceneDelegate {
sceneDelegate.handle(response)
}
}
}
// MARK: App Initialization
private extension AppDelegate {
private func initializeDownloaders() {
let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let faviconsFolderURL = tempDir.appendingPathComponent("Favicons")
let imagesFolderURL = tempDir.appendingPathComponent("Images")
try! FileManager.default.createDirectory(at: faviconsFolderURL, withIntermediateDirectories: true, attributes: nil)
let faviconsFolder = faviconsFolderURL.absoluteString
let faviconsFolderPath = faviconsFolder.suffix(from: faviconsFolder.index(faviconsFolder.startIndex, offsetBy: 7))
faviconDownloader = FaviconDownloader(folder: String(faviconsFolderPath))
let imagesFolder = imagesFolderURL.absoluteString
let imagesFolderPath = imagesFolder.suffix(from: imagesFolder.index(imagesFolder.startIndex, offsetBy: 7))
try! FileManager.default.createDirectory(at: imagesFolderURL, withIntermediateDirectories: true, attributes: nil)
imageDownloader = ImageDownloader(folder: String(imagesFolderPath))
authorAvatarDownloader = AuthorAvatarDownloader(imageDownloader: imageDownloader)
let tempFolder = tempDir.absoluteString
let tempFolderPath = tempFolder.suffix(from: tempFolder.index(tempFolder.startIndex, offsetBy: 7))
webFeedIconDownloader = WebFeedIconDownloader(imageDownloader: imageDownloader, folder: String(tempFolderPath))
}
private func initializeHomeScreenQuickActions() {
let unreadTitle = NSLocalizedString("First Unread", comment: "First Unread")
let unreadIcon = UIApplicationShortcutIcon(systemImageName: "chevron.down.circle")
let unreadItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.FirstUnread", localizedTitle: unreadTitle, localizedSubtitle: nil, icon: unreadIcon, userInfo: nil)
let searchTitle = NSLocalizedString("Search", comment: "Search")
let searchIcon = UIApplicationShortcutIcon(systemImageName: "magnifyingglass")
let searchItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.ShowSearch", localizedTitle: searchTitle, localizedSubtitle: nil, icon: searchIcon, userInfo: nil)
let addTitle = NSLocalizedString("Add Feed", comment: "Add Feed")
let addIcon = UIApplicationShortcutIcon(systemImageName: "plus")
let addItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.ShowAdd", localizedTitle: addTitle, localizedSubtitle: nil, icon: addIcon, userInfo: nil)
UIApplication.shared.shortcutItems = [addItem, searchItem, unreadItem]
}
}
// MARK: Go To Background
private extension AppDelegate {
func waitForSyncTasksToFinish() {
guard !isWaitingForSyncTasks && UIApplication.shared.applicationState == .background else { return }
isWaitingForSyncTasks = true
self.waitBackgroundUpdateTask = UIApplication.shared.beginBackgroundTask { [weak self] in
guard let self = self else { return }
self.completeProcessing(true)
os_log("Accounts wait for progress terminated for running too long.", log: self.log, type: .info)
}
DispatchQueue.main.async { [weak self] in
self?.waitToComplete() { [weak self] suspend in
self?.completeProcessing(suspend)
}
}
}
func waitToComplete(completion: @escaping (Bool) -> Void) {
guard UIApplication.shared.applicationState == .background else {
os_log("App came back to forground, no longer waiting.", log: self.log, type: .info)
completion(false)
return
}
if AccountManager.shared.refreshInProgress || isSyncArticleStatusRunning {
os_log("Waiting for sync to finish...", log: self.log, type: .info)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
self?.waitToComplete(completion: completion)
}
} else {
os_log("Refresh progress complete.", log: self.log, type: .info)
completion(true)
}
}
func completeProcessing(_ suspend: Bool) {
if suspend {
suspendApplication()
}
UIApplication.shared.endBackgroundTask(self.waitBackgroundUpdateTask)
self.waitBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
isWaitingForSyncTasks = false
}
func syncArticleStatus() {
guard !isSyncArticleStatusRunning else { return }
isSyncArticleStatusRunning = true
let completeProcessing = { [unowned self] in
self.isSyncArticleStatusRunning = false
UIApplication.shared.endBackgroundTask(self.syncBackgroundUpdateTask)
self.syncBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
}
self.syncBackgroundUpdateTask = UIApplication.shared.beginBackgroundTask {
completeProcessing()
os_log("Accounts sync processing terminated for running too long.", log: self.log, type: .info)
}
DispatchQueue.main.async {
AccountManager.shared.syncArticleStatusAll() {
completeProcessing()
}
}
}
func suspendApplication() {
guard UIApplication.shared.applicationState == .background else { return }
AccountManager.shared.suspendNetworkAll()
AccountManager.shared.suspendDatabaseAll()
CoalescingQueue.standard.performCallsImmediately()
for scene in UIApplication.shared.connectedScenes {
if let sceneDelegate = scene.delegate as? SceneDelegate {
sceneDelegate.suspend()
}
}
os_log("Application processing suspended.", log: self.log, type: .info)
}
}
// MARK: Background Tasks
private extension AppDelegate {
/// Register all background tasks.
func registerBackgroundTasks() {
// Register background feed refresh.
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.ranchero.NetNewsWire.FeedRefresh", using: nil) { (task) in
self.performBackgroundFeedRefresh(with: task as! BGAppRefreshTask)
}
}
/// Schedules a background app refresh based on `AppDefaults.refreshInterval`.
func scheduleBackgroundFeedRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.ranchero.NetNewsWire.FeedRefresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
// We send this to a dedicated serial queue because as of 11/05/19 on iOS 13.2 the call to the
// task scheduler can hang indefinitely.
bgTaskDispatchQueue.async {
do {
try BGTaskScheduler.shared.submit(request)
} catch {
os_log(.error, log: self.log, "Could not schedule app refresh: %@", error.localizedDescription)
}
}
}
/// Performs background feed refresh.
/// - Parameter task: `BGAppRefreshTask`
/// - Warning: As of Xcode 11 beta 2, when triggered from the debugger this doesn't work.
func performBackgroundFeedRefresh(with task: BGAppRefreshTask) {
scheduleBackgroundFeedRefresh() // schedule next refresh
os_log("Woken to perform account refresh.", log: self.log, type: .info)
DispatchQueue.main.async {
if AccountManager.shared.isSuspended {
AccountManager.shared.resumeAll()
}
AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) { [unowned self] in
if !AccountManager.shared.isSuspended {
self.suspendApplication()
os_log("Account refresh operation completed.", log: self.log, type: .info)
task.setTaskCompleted(success: true)
}
}
}
// set expiration handler
task.expirationHandler = { [weak task] in
DispatchQueue.main.sync {
self.suspendApplication()
}
os_log("Accounts refresh processing terminated for running too long.", log: self.log, type: .info)
task?.setTaskCompleted(success: false)
}
}
}
| 33.798469 | 207 | 0.763605 |
fe7bc29cda2d4cb87c70736b34c1d9ba365bcf23 | 221 | //
// Track.swift
// DiscoverThatSong
//
// Created by Mohammed Abdullatif on 2021-01-02.
//
struct Track: Codable, Equatable {
let album: Album
let artists: [Artist]
let id: String
let name: String
}
| 15.785714 | 49 | 0.647059 |
202b846d883c16299732bda3a171d90eb761494d | 1,298 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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.
*/
@frozen
public enum HorizontalAlignment {
case left
case center
case right
}
@frozen
public enum VerticalAlignment {
case top
case center
case bottom
}
| 34.157895 | 78 | 0.773498 |
22da8fd4238dab7689554d10bd103672d09c7337 | 482 | //
// SectionHeaderCell.swift
// SNAdapter_Example
//
// Created by Macbook Pro on 5/25/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import SNAdapter
class SectionHeaderCell: UITableViewCell, SNCellable {
func configure(_ object: SNCellableModel?) {
guard let basicModel = object as? SectionModel else { return }
self.backgroundColor = UIColor.gray
self.textLabel?.text = basicModel.title
}
}
| 21.909091 | 70 | 0.678423 |
7a32e2e784749f311febfb7ad19b95a01fc4912d | 16,222 | //
// Tests.swift
// Tests
//
// Created by phimage on 06/04/2017.
// Copyright © 2017 phimage (Eric Marchand). All rights reserved.
//
import XCTest
@testable import ValueTransformerKit
class Tests: XCTestCase {
var count: Int {
return ValueTransformer.valueTransformerNames().count
}
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testRegister() {
var expected = count
StringTransformers.register()
expected = expected + StringTransformers.transformers.count
XCTAssertEqual(expected, count)
ImageRepresentationTransformers.register()
expected = expected + ImageRepresentationTransformers.transformers.count * 2
XCTAssertEqual(expected, count)
NSLocale.Key.register()
expected = expected + NSLocale.Key.transformers.count
XCTAssertEqual(expected, count)
NumberTransformers.register()
expected = expected + NumberTransformers.transformers.count * 2
XCTAssertEqual(expected, count)
DateTransformers.register()
expected = expected + DateTransformers.transformers.count * 2
XCTAssertEqual(expected, count)
TimeTransformers.register()
expected = expected + TimeTransformers.transformers.count * 2
XCTAssertEqual(expected, count)
String.Encoding.register()
expected = expected + String.Encoding.transformers.count /* 2, no reverse, auto reverse */
XCTAssertEqual(expected, count)
// Singleton
ArrayToStringTransformer.register()
expected = expected + 2
XCTAssertEqual(expected, count)
OrderedSetToArrayValueTransformer.register()
expected = expected + 2
XCTAssertEqual(expected, count)
IdentityTransformer.register()
expected = expected + 1
XCTAssertEqual(expected, count)
IsEmptyTransformer.register()
expected = expected + 1
XCTAssertEqual(expected, count)
IsNotEmptyTransformer.register()
expected = expected + 1
XCTAssertEqual(expected, count)
ArrayStringJSONValueTransformer().register()
expected = expected + 1
XCTAssertEqual(expected, count)
JSONValueTransformer<TestObject>().register()
expected = expected + 1
XCTAssertEqual(expected, count)
PropertyListTransformer<TestObject>().register()
expected = expected + 1
XCTAssertEqual(expected, count)
testValueTransformerByName()
}
func testValueTransformerByName() {
// Try to get all value transformers using names
for name in ValueTransformer.valueTransformerNames() {
print(name.rawValue)
XCTAssertNotNil(ValueTransformer(forName: name))
}
}
func testIdentityTransformer() {
let tranformer = ValueTransformer.identity
var transformed = tranformer.transformedValue(nil)
XCTAssertNil(transformed)
var value: String? = nil
transformed = tranformer.transformedValue(value)
XCTAssertNil(value)
XCTAssertEqual(transformed as? String, value)
value = " value"
transformed = tranformer.transformedValue(value)
XCTAssertNotNil(value)
XCTAssertEqual(transformed as? String, value)
XCTAssertEqual(tranformer.transformedValue(true) as? Bool, true)
XCTAssertEqual(tranformer.transformedValue(false) as? Bool, false)
}
func testStringCapitalizedTransformer() {
let transformerType = StringTransformers.capitalized
let transformer = transformerType.transformer
XCTAssertNil(transformerType.transformedValue(nil))
XCTAssertNil(transformer.transformedValue(nil))
XCTAssertEqual(transformerType.transformedValue("") as? String, "")
XCTAssertEqual(transformer.transformedValue("") as? String, "")
XCTAssertEqual(transformerType.transformedValue("qwerty") as? String, "Qwerty")
XCTAssertEqual(transformer.transformedValue("qwerty") as? String, "Qwerty")
XCTAssertEqual(transformerType.transformedValue("qwerTy") as? String, "Qwerty")
XCTAssertEqual(transformer.transformedValue("qwerTy") as? String, "Qwerty")
XCTAssertEqual(transformerType.transformedValue("QwerTy") as? String, "Qwerty")
XCTAssertEqual(transformer.transformedValue("QwerTy") as? String, "Qwerty")
XCTAssertEqual(transformerType.transformedValue("Qwer Ty") as? String, "Qwer Ty")
XCTAssertEqual(transformer.transformedValue("Qwer Ty") as? String, "Qwer Ty")
XCTAssertEqual(transformerType.transformedValue("Qwer ty") as? String, "Qwer Ty")
XCTAssertEqual(transformer.transformedValue("Qwer ty") as? String, "Qwer Ty")
}
func testStringUppercasedTransformer() {
let transformerType = StringTransformers.uppercased
let transformer = transformerType.transformer
XCTAssertNil(transformerType.transformedValue(nil))
XCTAssertNil(transformer.transformedValue(nil))
XCTAssertEqual(transformerType.transformedValue("") as? String, "")
XCTAssertEqual(transformer.transformedValue("") as? String, "")
XCTAssertEqual(transformerType.transformedValue("qwerty") as? String, "QWERTY")
XCTAssertEqual(transformer.transformedValue("qwerty") as? String, "QWERTY")
XCTAssertEqual(transformerType.transformedValue("qwerTy") as? String, "QWERTY")
XCTAssertEqual(transformer.transformedValue("qwerTy") as? String, "QWERTY")
XCTAssertEqual(transformerType.transformedValue("QWERTY") as? String, "QWERTY")
XCTAssertEqual(transformer.transformedValue("QWERTY") as? String, "QWERTY")
}
func testStringLowercasedTransformer() {
let transformerType = StringTransformers.lowercased
let transformer = transformerType.transformer
XCTAssertNil(transformerType.transformedValue(nil))
XCTAssertNil(transformer.transformedValue(nil))
XCTAssertEqual(transformerType.transformedValue("") as? String, "")
XCTAssertEqual(transformer.transformedValue("") as? String, "")
XCTAssertEqual(transformerType.transformedValue("qwerty") as? String, "qwerty")
XCTAssertEqual(transformer.transformedValue("qwerty") as? String, "qwerty")
XCTAssertEqual(transformerType.transformedValue("qwerTy") as? String, "qwerty")
XCTAssertEqual(transformer.transformedValue("qwerTy") as? String, "qwerty")
XCTAssertEqual(transformerType.transformedValue("QWERTY") as? String, "qwerty")
XCTAssertEqual(transformer.transformedValue("QWERTY") as? String, "qwerty")
}
func testClosure() {
let dico = ["ewrwer": "value", "aeae": nil, true: "test"] as [AnyHashable : String?]
let valueForNil = "test"
let transformer = ValueTransformer.closure { object in
guard let object = object as? AnyHashable else {
return valueForNil
}
return dico[object] ?? nil
}
for (key, value) in dico {
let transformed = transformer.transformedValue(key)
XCTAssertEqual(transformed as? String, value)
}
let transformed = transformer.transformedValue(nil)
XCTAssertEqual(transformed as? String, valueForNil)
}
func testReverseClosure() {
let dico = ["ewrwer": "value", "aeae": nil, true: "test"] as [AnyHashable : String?]
let valueForNil = "test"
let transformer = ValueTransformer.closure(forwardTransformer: { object in
guard let object = object as? AnyHashable else {
return valueForNil
}
return dico[object] ?? nil
}) { object in
for (key, value) in dico {
if value == object as? String {
return key
}
}
/*if object == valueForNil {
return nil
}*/
return nil
}
for (key, value) in dico {
let transformed = transformer.transformedValue(key)
XCTAssertEqual(transformed as? String, value)
let reverse = transformer.reverseTransformedValue(transformed)
XCTAssertEqual(reverse as? AnyHashable, key)
}
let transformed = transformer.transformedValue(nil)
XCTAssertEqual(transformed as? String, valueForNil)
}
func testJSONStringArray() {
let array = ["ewrwer", "value", "aeae", "test"]
let transformer = ArrayStringJSONValueTransformer()
let data = transformer.transformedValue(array)
XCTAssertNotNil(data)
XCTAssertNotNil(data as? Data)
var value = transformer.reverseTransformedValue(data)
XCTAssertNotNil(value)
XCTAssertNotNil(value as? [String])
if let va = value as? [String] {
XCTAssertEqual(va, array)
}
let stringTransformer = transformer.with(encoding: .utf8)
let string = stringTransformer.transformedValue(array)
XCTAssertNotNil(string)
XCTAssertNotNil(string as? String)
value = stringTransformer.reverseTransformedValue(string)
XCTAssertNotNil(value)
XCTAssertNotNil(value as? [String])
if let va = value as? [String] {
XCTAssertEqual(va, array)
}
}
func testJSONStruc() {
let object = TestObject(string: "string", integer: 5)
let transformer = JSONValueTransformer<TestObject>()
let data = transformer.transformedValue(object)
XCTAssertNotNil(data)
XCTAssertNotNil(data as? Data)
var value = transformer.reverseTransformedValue(data)
XCTAssertNotNil(value)
XCTAssertNotNil(value as? TestObject)
if let va = value as? TestObject {
XCTAssertEqual(va, object)
}
let stringTransformer = transformer.with(encoding: .utf8)
let string = stringTransformer.transformedValue(object)
XCTAssertNotNil(string)
XCTAssertNotNil(string as? String)
value = stringTransformer.reverseTransformedValue(string)
XCTAssertNotNil(value)
XCTAssertNotNil(value as? TestObject)
if let va = value as? TestObject {
XCTAssertEqual(va, object)
}
}
func testCoumpound() {
let stringTransformer: CompoundValueTransformer = [ArrayStringJSONValueTransformer(), String.Encoding.utf8.transformer]
let array = ["ewrwer", "value", "aeae", "test"]
let string = stringTransformer.transformedValue(array)
let value = stringTransformer.reverseTransformedValue(string)
if let va = value as? [String] {
XCTAssertEqual(va, array)
} else {
XCTFail()
}
}
func testOperator() {
let stringTransformer = ArrayStringJSONValueTransformer() + String.Encoding.utf8.transformer
let array: [String] = ["ewrwer", "value", "aeae", "test"]
let string = stringTransformer.transformedValue(array) as? String
let value = stringTransformer.reverseTransformedValue(string)
if let value = value as? [String] {
XCTAssertEqual(value, array)
} else {
XCTFail()
}
let newString: String? = array *> stringTransformer
XCTAssertEqual(newString, string)
let newArray: [String]? = stringTransformer <* newString
if let newArray = newArray {
XCTAssertEqual(newArray, array)
} else {
XCTFail()
}
}
func testURLTransformer() {
let transformer = URLToStringTransformer()
let urlStrings = ["http://www.exemple.com", "tel:0105050", "file://path/to/a/file"]
for urlString in urlStrings {
if let url = URL(string: urlString) {
if let string = transformer.transformedValue(url) as? String {
XCTAssertEqual(urlString, string)
} else {
XCTFail("Faield to convert to string from url created with \(urlString)")
}
XCTAssertEqual(url, transformer.reverse.transformedValue(urlString) as? URL)
} else {
XCTFail("Faield to convert to url \(urlString)")
}
}
}
func testIsEmpty() {
let isEmpty = IsEmptyTransformer()
var result = isEmpty.transformedValue([]) as? Bool ?? false
XCTAssertTrue(result, "is empty fail on array")
result = isEmpty.transformedValue([:]) as? Bool ?? false
XCTAssertTrue(result, "is empty fail on dictionary")
result = isEmpty.transformedValue("") as? Bool ?? false
XCTAssertTrue(result, "is empty fail on string")
result = isEmpty.transformedValue("test") as? Bool ?? true
XCTAssertFalse(result, "not is empty fail on string")
result = isEmpty.transformedValue(NSArray()) as? Bool ?? false
XCTAssertTrue(result, "is empty fail on NSArray")
result = isEmpty.transformedValue(NSDictionary()) as? Bool ?? false
XCTAssertTrue(result, "is empty fail on NSDictionary")
result = isEmpty.transformedValue(NSSet()) as? Bool ?? false
XCTAssertTrue(result, "is empty fail on NSSet")
result = isEmpty.transformedValue(NSString()) as? Bool ?? false
XCTAssertTrue(result, "is empty fail on NSString")
result = isEmpty.transformedValue(NSString("test")) as? Bool ?? true
XCTAssertFalse(result, "not is empty fail on NSString")
}
func testIsNotEmpty() {
let isNotEmpty = IsNotEmptyTransformer()
var result = isNotEmpty.transformedValue([]) as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on array")
result = isNotEmpty.transformedValue(["azeaze"]) as? Bool ?? false
XCTAssertTrue(result, "is not empty fail on array")
result = isNotEmpty.transformedValue([:]) as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on dictionary")
result = isNotEmpty.transformedValue(["azeae":"azeae"]) as? Bool ?? false
XCTAssertTrue(result, "is not empty fail on dictionary")
result = isNotEmpty.transformedValue("") as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on string")
result = isNotEmpty.transformedValue("test") as? Bool ?? false
XCTAssertTrue(result, "not is not empty fail on string")
result = isNotEmpty.transformedValue(NSArray()) as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on NSArray")
result = isNotEmpty.transformedValue(NSDictionary()) as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on NSDictionary")
result = isNotEmpty.transformedValue(NSSet()) as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on NSSet")
result = isNotEmpty.transformedValue(NSString()) as? Bool ?? true
XCTAssertFalse(result, "not is not empty fail on NSString")
result = isNotEmpty.transformedValue(NSString("test")) as? Bool ?? false
XCTAssertTrue(result, "is not empty fail on NSString")
}
func _testImageRepresentationTransformers() {
XCTFail("not implemented")
}
func _testNumberTransformers() {
XCTFail("not implemented")
}
func _testDateTransformers() {
XCTFail("not implemented")
}
func _testTimeTransformers() {
XCTFail("not implemented")
}
}
struct TestObject: Codable, Equatable {
var string: String
var integer: Int
public static func ==(lhs: TestObject, rhs: TestObject) -> Bool {
return lhs.string == rhs.string && lhs.integer == rhs.integer
}
}
| 37.638051 | 127 | 0.635248 |
4a4f19e5342e5e1329636cdf4fd489aa141682b4 | 5,023 | import UIKit
open class FSPagerViewCell: UICollectionViewCell {
/// Returns the label used for the main textual content of the pager view cell.
@objc
open var textLabel: UILabel? {
if let _ = _textLabel {
return _textLabel
}
let view = UIView(frame: .zero)
view.isUserInteractionEnabled = false
view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
let textLabel = UILabel(frame: .zero)
textLabel.textColor = .white
textLabel.font = UIFont.preferredFont(forTextStyle: .body)
self.contentView.addSubview(view)
view.addSubview(textLabel)
textLabel.addObserver(self, forKeyPath: "font", options: [.old, .new], context: kvoContext)
_textLabel = textLabel
return textLabel
}
/// Returns the image view of the pager view cell. Default is nil.
@objc
open var imageView: UIImageView? {
if let _ = _imageView {
return _imageView
}
let imageView = UIImageView(frame: .zero)
self.contentView.addSubview(imageView)
_imageView = imageView
return imageView
}
fileprivate weak var _textLabel: UILabel?
fileprivate weak var _imageView: UIImageView?
private var accessibilityMessage: String = ""
fileprivate let kvoContext = UnsafeMutableRawPointer(bitPattern: 0)
fileprivate let selectionColor = UIColor(white: 0.2, alpha: 0.2)
fileprivate weak var _selectedForegroundView: UIView?
fileprivate var selectedForegroundView: UIView? {
guard _selectedForegroundView == nil else {
return _selectedForegroundView
}
guard let imageView = _imageView else {
return nil
}
let view = UIView(frame: imageView.bounds)
imageView.addSubview(view)
_selectedForegroundView = view
return view
}
open override var isHighlighted: Bool {
set {
super.isHighlighted = newValue
if newValue {
self.selectedForegroundView?.layer.backgroundColor = self.selectionColor.cgColor
} else if !super.isSelected {
self.selectedForegroundView?.layer.backgroundColor = UIColor.clear.cgColor
}
}
get {
return super.isHighlighted
}
}
open override var isSelected: Bool {
set {
super.isSelected = newValue
self.selectedForegroundView?.layer.backgroundColor = newValue ? self.selectionColor.cgColor : UIColor.clear.cgColor
}
get {
return super.isSelected
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
self.contentView.backgroundColor = UIColor.clear
self.backgroundColor = UIColor.clear
self.contentView.layer.shadowColor = UIColor.black.cgColor
self.contentView.layer.shadowRadius = 3
self.contentView.layer.shadowOpacity = 0.25
self.contentView.layer.shadowOffset = CGSize(width: 0.3, height: 0.3)
}
deinit {
if let textLabel = _textLabel {
textLabel.removeObserver(self, forKeyPath: "font", context: kvoContext)
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if let imageView = _imageView {
imageView.frame = self.contentView.bounds
}
if let textLabel = _textLabel {
textLabel.superview!.frame = {
var rect = self.contentView.bounds
let height = textLabel.font.pointSize * 1.5
rect.size.height = height
rect.origin.y = self.contentView.frame.height - height
return rect
}()
textLabel.frame = {
var rect = textLabel.superview!.bounds
rect = rect.insetBy(dx: 8, dy: 0)
rect.size.height -= 1
rect.origin.y += 1
return rect
}()
}
if let selectedForegroundView = _selectedForegroundView {
selectedForegroundView.frame = self.contentView.bounds
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if context == kvoContext {
if keyPath == "font" {
self.setNeedsLayout()
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
// MARK: Accessibility
extension FSPagerViewCell {
func setAccessibilityMessage(_ message: String) {
self.accessibilityMessage = message
}
func getAccessibilityMessage() -> String {
return accessibilityMessage
}
}
| 31.993631 | 155 | 0.611388 |
acab50b6472e53bd5015b2a649ccecbf76f818f1 | 723 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
/// Holds all the data necessary to create the views for the overflow menu.
@objcMembers public class OverflowMenuModel: NSObject, ObservableObject {
/// The destinations for the overflow menu.
public var destinations: [OverflowMenuDestination]
/// The action groups for the overflow menu.
public var actionGroups: [OverflowMenuActionGroup]
public init(
destinations: [OverflowMenuDestination],
actionGroups: [OverflowMenuActionGroup]
) {
self.destinations = destinations
self.actionGroups = actionGroups
}
}
| 31.434783 | 75 | 0.759336 |
210b382572b13211a9cb58374860542c7040d5b6 | 2,819 | import Foundation
import azureSwiftRuntime
public protocol WebAppsGetMSDeployLogSlot {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var name : String { get set }
var slot : String { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (MSDeployLogProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.WebApps {
// GetMSDeployLogSlot get the MSDeploy Log for the last MSDeploy operation.
internal class GetMSDeployLogSlotCommand : BaseCommand, WebAppsGetMSDeployLogSlot {
public var resourceGroupName : String
public var name : String
public var slot : String
public var subscriptionId : String
public var apiVersion = "2016-08-01"
public init(resourceGroupName: String, name: String, slot: String, subscriptionId: String) {
self.resourceGroupName = resourceGroupName
self.name = name
self.slot = slot
self.subscriptionId = subscriptionId
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/extensions/MSDeploy/log"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{name}"] = String(describing: self.name)
self.pathParameters["{slot}"] = String(describing: self.slot)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(MSDeployLogData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (MSDeployLogProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: MSDeployLogData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 45.467742 | 167 | 0.629656 |
f91375da918cc001b55734198c5dcdd2456d1453 | 6,967 | //
// DataExtension.swift
// WiggleSDK
//
// Created by mykim on 2017. 11. 21..
// Copyright © 2017년 leejaejin. All rights reserved.
//
import Foundation
import CommonCrypto
extension Data {
/**
enum AESError: Error {
case KeyError((String, Int))
case IVError((String, Int))
case CryptorError((String, Int))
}
// The iv is prefixed to the encrypted data
func AES256EncryptWithKey(_ key:String) throws -> Data? {
guard let keyData = key.data(using: String.Encoding.utf8) else { return nil }
let keyLength = keyData.count
let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256]
if (validKeyLengths.contains(keyLength) == false) {
throw AESError.KeyError(("Invalid key length", keyLength))
}
let ivSize = kCCBlockSizeAES128;
let cryptLength = size_t(ivSize + self.count + kCCBlockSizeAES128)
var cryptData = Data(count:cryptLength)
let status = cryptData.withUnsafeMutableBytes {ivBytes in
SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, ivBytes)
}
if (status != 0) {
throw AESError.IVError(("IV generation failed", Int(status)))
}
var numBytesEncrypted :size_t = 0
let options = CCOptions(kCCOptionPKCS7Padding)
let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
self.withUnsafeBytes {dataBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES),
options,
keyBytes, keyLength,
cryptBytes,
dataBytes, self.count,
cryptBytes+kCCBlockSizeAES128, cryptLength,
&numBytesEncrypted)
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.count = numBytesEncrypted + ivSize
}
else {
throw AESError.CryptorError(("Encryption failed", Int(cryptStatus)))
}
return cryptData;
}
// The iv is prefixed to the encrypted data
func AES256DecryptWithKey(_ key:String) throws -> Data? {
guard let keyData = key.data(using: String.Encoding.utf8) else { return nil }
let keyLength = keyData.count
let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256]
if (validKeyLengths.contains(keyLength) == false) {
throw AESError.KeyError(("Invalid key length", keyLength))
}
let ivSize = kCCBlockSizeAES128;
let clearLength = size_t(self.count - ivSize)
var clearData = Data(count:clearLength)
var numBytesDecrypted :size_t = 0
let options = CCOptions(kCCOptionPKCS7Padding)
let cryptStatus = clearData.withUnsafeMutableBytes {cryptBytes in
self.withUnsafeBytes {dataBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES128),
options,
keyBytes, keyLength,
dataBytes,
dataBytes+kCCBlockSizeAES128, clearLength,
cryptBytes, clearLength,
&numBytesDecrypted)
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
clearData.count = numBytesDecrypted
}
else {
throw AESError.CryptorError(("Decryption failed", Int(cryptStatus)))
}
return clearData;
}
*/
}
extension String {
func aesEncrypt(key: String, iv: String, options: Int = kCCOptionPKCS7Padding) -> String? {
if let keyData: Data = key.data(using: String.Encoding.utf8),
let data: Data = self.data(using: String.Encoding.utf8),
let cryptData: NSMutableData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {
let keyLength: size_t = size_t(kCCKeySizeAES256)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted: size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyLength,
nil,
(data as NSData).bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString
}
else {
return nil
}
}
return nil
}
func aesDecrypt(key: String, iv: String, options: Int = kCCOptionPKCS7Padding) -> String? {
if let keyData: Data = key.data(using: String.Encoding.utf8),
let data: NSData = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
let cryptData: NSMutableData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
let keyLength: size_t = size_t(kCCKeySizeAES256)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted: size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
(keyData as NSData).bytes, keyLength,
nil,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let unencryptedMessage = String(data: cryptData as Data, encoding: String.Encoding.utf8)
return unencryptedMessage
}
else {
return nil
}
}
return nil
}
}
| 38.491713 | 107 | 0.538395 |
87ddd835c563064522a125f17271a3e25f909ed4 | 946 | //
// HabitInfo.swift
// Habits
//
// Created by RAJ RAVAL on 10/03/20.
// Copyright © 2020 Buck. All rights reserved.
//
import Foundation
struct HabitInfo: Identifiable, Codable {
let id = UUID()
let habitName: String
let habitDescription: String
let habitCategory: String
}
class Habits: ObservableObject {
@Published var habitItems = [HabitInfo]() {
didSet {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(habitItems) {
UserDefaults.standard.set(encoded, forKey: "Habits")
}
}
}
init() {
if let habitItems = UserDefaults.standard.data(forKey: "Habits") {
let decoder = JSONDecoder()
if let decoded = try? decoder.decode([HabitInfo].self, from: habitItems) {
self.habitItems = decoded
return
}
}
self.habitItems = []
}
}
| 24.25641 | 86 | 0.570825 |
bb37435bb7b19836fd5dabb93cc2d2e643346542 | 796 | //
// ResponseMD.swift
// Cinema
//
// Created by Alex on 2/28/19.
// Copyright © 2019 Alex. All rights reserved.
//
import Foundation
class ResponseTilesBatch: Codable {
let page: Int?
let totalResults: Int?
let totalPages: Int?
let results: [AbstractDecodedTile]?
let id: Int?
enum CodingKeys: String, CodingKey {
case page = "page"
case totalResults = "total_results"
case totalPages = "total_pages"
case results = "results"
case id = "id"
}
init(page: Int?, totalResults: Int?, totalPages: Int?, results: [AbstractDecodedTile]?, id: Int?) {
self.page = page
self.totalResults = totalResults
self.totalPages = totalPages
self.results = results
self.id = id
}
}
| 23.411765 | 103 | 0.606784 |
de20f0c6ec7e9ffa525d51c26dc034ad0a7c04a5 | 25,330 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import class Foundation.ProcessInfo
#if os(Windows)
import Foundation
#endif
import TSCLibc
import Dispatch
/// Process result data which is available after process termination.
public struct ProcessResult: CustomStringConvertible {
public enum Error: Swift.Error {
/// The output is not a valid UTF8 sequence.
case illegalUTF8Sequence
/// The process had a non zero exit.
case nonZeroExit(ProcessResult)
}
public enum ExitStatus: Equatable {
/// The process was terminated normally with a exit code.
case terminated(code: Int32)
/// The process was terminated due to a signal.
case signalled(signal: Int32)
}
/// The arguments with which the process was launched.
public let arguments: [String]
/// The environment with which the process was launched.
public let environment: [String: String]
/// The exit status of the process.
public let exitStatus: ExitStatus
/// The output bytes of the process. Available only if the process was
/// asked to redirect its output and no stdout output closure was set.
public let output: Result<[UInt8], Swift.Error>
/// The output bytes of the process. Available only if the process was
/// asked to redirect its output and no stderr output closure was set.
public let stderrOutput: Result<[UInt8], Swift.Error>
/// Create an instance using a POSIX process exit status code and output result.
///
/// See `waitpid(2)` for information on the exit status code.
public init(
arguments: [String],
environment: [String: String],
exitStatusCode: Int32,
output: Result<[UInt8], Swift.Error>,
stderrOutput: Result<[UInt8], Swift.Error>
) {
let exitStatus: ExitStatus
#if os(Windows)
exitStatus = .terminated(code: exitStatusCode)
#else
if WIFSIGNALED(exitStatusCode) {
exitStatus = .signalled(signal: WTERMSIG(exitStatusCode))
} else {
precondition(WIFEXITED(exitStatusCode), "unexpected exit status \(exitStatusCode)")
exitStatus = .terminated(code: WEXITSTATUS(exitStatusCode))
}
#endif
self.init(arguments: arguments, environment: environment, exitStatus: exitStatus, output: output,
stderrOutput: stderrOutput)
}
/// Create an instance using an exit status and output result.
public init(
arguments: [String],
environment: [String: String],
exitStatus: ExitStatus,
output: Result<[UInt8], Swift.Error>,
stderrOutput: Result<[UInt8], Swift.Error>
) {
self.arguments = arguments
self.environment = environment
self.output = output
self.stderrOutput = stderrOutput
self.exitStatus = exitStatus
}
/// Converts stdout output bytes to string, assuming they're UTF8.
public func utf8Output() throws -> String {
return String(decoding: try output.get(), as: Unicode.UTF8.self)
}
/// Converts stderr output bytes to string, assuming they're UTF8.
public func utf8stderrOutput() throws -> String {
return String(decoding: try stderrOutput.get(), as: Unicode.UTF8.self)
}
public var description: String {
return """
<ProcessResult: exit: \(exitStatus), output:
\((try? utf8Output()) ?? "")
>
"""
}
}
/// Process allows spawning new subprocesses and working with them.
///
/// Note: This class is thread safe.
public final class Process: ObjectIdentifierProtocol {
/// Errors when attempting to invoke a process
public enum Error: Swift.Error {
/// The program requested to be executed cannot be found on the existing search paths, or is not executable.
case missingExecutableProgram(program: String)
}
public enum OutputRedirection {
/// Do not redirect the output
case none
/// Collect stdout and stderr output and provide it back via ProcessResult object
case collect
/// Stream stdout and stderr via the corresponding closures
case stream(stdout: OutputClosure, stderr: OutputClosure)
public var redirectsOutput: Bool {
switch self {
case .none:
return false
case .collect, .stream:
return true
}
}
public var outputClosures: (stdoutClosure: OutputClosure, stderrClosure: OutputClosure)? {
switch self {
case .stream(let stdoutClosure, let stderrClosure):
return (stdoutClosure: stdoutClosure, stderrClosure: stderrClosure)
case .collect, .none:
return nil
}
}
}
/// Typealias for process id type.
#if !os(Windows)
public typealias ProcessID = pid_t
#endif
/// Typealias for stdout/stderr output closure.
public typealias OutputClosure = ([UInt8]) -> Void
/// Global default setting for verbose.
public static var verbose = false
/// If true, prints the subprocess arguments before launching it.
public let verbose: Bool
/// The current environment.
@available(*, deprecated, message: "use ProcessEnv.vars instead")
static public var env: [String: String] {
return ProcessInfo.processInfo.environment
}
/// The arguments to execute.
public let arguments: [String]
/// The environment with which the process was executed.
public let environment: [String: String]
/// The process id of the spawned process, available after the process is launched.
#if os(Windows)
private var _process: Foundation.Process?
#else
public private(set) var processID = ProcessID()
#endif
/// If the subprocess has launched.
/// Note: This property is not protected by the serial queue because it is only mutated in `launch()`, which will be
/// called only once.
public private(set) var launched = false
/// The result of the process execution. Available after process is terminated.
public var result: ProcessResult? {
return self.serialQueue.sync {
self._result
}
}
/// How process redirects its output.
public let outputRedirection: OutputRedirection
/// The result of the process execution. Available after process is terminated.
private var _result: ProcessResult?
/// If redirected, stdout result and reference to the thread reading the output.
private var stdout: (result: Result<[UInt8], Swift.Error>, thread: Thread?) = (.success([]), nil)
/// If redirected, stderr result and reference to the thread reading the output.
private var stderr: (result: Result<[UInt8], Swift.Error>, thread: Thread?) = (.success([]), nil)
/// Queue to protect concurrent reads.
private let serialQueue = DispatchQueue(label: "org.swift.swiftpm.process")
/// Queue to protect reading/writing on map of validated executables.
private static let executablesQueue = DispatchQueue(
label: "org.swift.swiftpm.process.findExecutable")
/// Indicates if a new progress group is created for the child process.
private let startNewProcessGroup: Bool
/// Cache of validated executables.
///
/// Key: Executable name or path.
/// Value: Path to the executable, if found.
static private var validatedExecutablesMap = [String: AbsolutePath?]()
/// Create a new process instance.
///
/// - Parameters:
/// - arguments: The arguments for the subprocess.
/// - environment: The environment to pass to subprocess. By default the current process environment
/// will be inherited.
/// - outputRedirection: How process redirects its output. Default value is .collect.
/// - verbose: If true, launch() will print the arguments of the subprocess before launching it.
/// - startNewProcessGroup: If true, a new progress group is created for the child making it
/// continue running even if the parent is killed or interrupted. Default value is true.
public init(
arguments: [String],
environment: [String: String] = ProcessEnv.vars,
outputRedirection: OutputRedirection = .collect,
verbose: Bool = Process.verbose,
startNewProcessGroup: Bool = true
) {
self.arguments = arguments
self.environment = environment
self.outputRedirection = outputRedirection
self.verbose = verbose
self.startNewProcessGroup = startNewProcessGroup
}
/// Returns the path of the the given program if found in the search paths.
///
/// The program can be executable name, relative path or absolute path.
public static func findExecutable(_ program: String) -> AbsolutePath? {
return Process.executablesQueue.sync {
// Check if we already have a value for the program.
if let value = Process.validatedExecutablesMap[program] {
return value
}
// FIXME: This can be cached.
let envSearchPaths = getEnvSearchPaths(
pathString: ProcessEnv.vars["PATH"],
currentWorkingDirectory: localFileSystem.currentWorkingDirectory
)
// Lookup and cache the executable path.
let value = lookupExecutablePath(
filename: program, searchPaths: envSearchPaths)
Process.validatedExecutablesMap[program] = value
return value
}
}
/// Launch the subprocess.
public func launch() throws {
precondition(arguments.count > 0 && !arguments[0].isEmpty, "Need at least one argument to launch the process.")
precondition(!launched, "It is not allowed to launch the same process object again.")
// Set the launch bool to true.
launched = true
// Print the arguments if we are verbose.
if self.verbose {
stdoutStream <<< arguments.map({ $0.spm_shellEscaped() }).joined(separator: " ") <<< "\n"
stdoutStream.flush()
}
// Look for executable.
guard Process.findExecutable(arguments[0]) != nil else {
throw Process.Error.missingExecutableProgram(program: arguments[0])
}
#if os(Windows)
_process = Foundation.Process()
_process?.arguments = arguments
_process?.executableURL = URL(fileURLWithPath: arguments[0])
if outputRedirection.redirectsOutput {
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
stdoutPipe.fileHandleForReading.readabilityHandler = { (fh : FileHandle) -> Void in
let contents = fh.readDataToEndOfFile()
self.outputRedirection.outputClosures?.stdoutClosure([UInt8](contents))
if case .success(let data) = self.stdout.result {
self.stdout.result = .success(data + contents)
}
}
stderrPipe.fileHandleForReading.readabilityHandler = { (fh : FileHandle) -> Void in
let contents = fh.readDataToEndOfFile()
self.outputRedirection.outputClosures?.stderrClosure([UInt8](contents))
if case .success(let data) = self.stderr.result {
self.stderr.result = .success(data + contents)
}
}
_process?.standardOutput = stdoutPipe
_process?.standardError = stderrPipe
}
try _process?.run()
#else
// Initialize the spawn attributes.
#if canImport(Darwin) || os(Android)
var attributes: posix_spawnattr_t? = nil
#else
var attributes = posix_spawnattr_t()
#endif
posix_spawnattr_init(&attributes)
defer { posix_spawnattr_destroy(&attributes) }
// Unmask all signals.
var noSignals = sigset_t()
sigemptyset(&noSignals)
posix_spawnattr_setsigmask(&attributes, &noSignals)
// Reset all signals to default behavior.
#if os(macOS)
var mostSignals = sigset_t()
sigfillset(&mostSignals)
sigdelset(&mostSignals, SIGKILL)
sigdelset(&mostSignals, SIGSTOP)
posix_spawnattr_setsigdefault(&attributes, &mostSignals)
#else
// On Linux, this can only be used to reset signals that are legal to
// modify, so we have to take care about the set we use.
var mostSignals = sigset_t()
sigemptyset(&mostSignals)
for i in 1 ..< SIGSYS {
if i == SIGKILL || i == SIGSTOP {
continue
}
sigaddset(&mostSignals, i)
}
posix_spawnattr_setsigdefault(&attributes, &mostSignals)
#endif
// Set the attribute flags.
var flags = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF
if startNewProcessGroup {
// Establish a separate process group.
flags |= POSIX_SPAWN_SETPGROUP
posix_spawnattr_setpgroup(&attributes, 0)
}
posix_spawnattr_setflags(&attributes, Int16(flags))
// Setup the file actions.
#if canImport(Darwin) || os(Android)
var fileActions: posix_spawn_file_actions_t? = nil
#else
var fileActions = posix_spawn_file_actions_t()
#endif
posix_spawn_file_actions_init(&fileActions)
defer { posix_spawn_file_actions_destroy(&fileActions) }
// Workaround for https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=89e435f3559c53084498e9baad22172b64429362
// Change allowing for newer version of glibc
guard let devNull = strdup("/dev/null") else {
throw SystemError.posix_spawn(0, arguments)
}
defer { free(devNull) }
// Open /dev/null as stdin.
posix_spawn_file_actions_addopen(&fileActions, 0, devNull, O_RDONLY, 0)
var outputPipe: [Int32] = [0, 0]
var stderrPipe: [Int32] = [0, 0]
if outputRedirection.redirectsOutput {
// Open the pipes.
try open(pipe: &outputPipe)
try open(pipe: &stderrPipe)
// Open the write end of the pipe as stdout and stderr, if desired.
posix_spawn_file_actions_adddup2(&fileActions, outputPipe[1], 1)
posix_spawn_file_actions_adddup2(&fileActions, stderrPipe[1], 2)
// Close the other ends of the pipe.
for pipe in [outputPipe, stderrPipe] {
posix_spawn_file_actions_addclose(&fileActions, pipe[0])
posix_spawn_file_actions_addclose(&fileActions, pipe[1])
}
} else {
posix_spawn_file_actions_adddup2(&fileActions, 1, 1)
posix_spawn_file_actions_adddup2(&fileActions, 2, 2)
}
let argv = CStringArray(arguments)
let env = CStringArray(environment.map({ "\($0.0)=\($0.1)" }))
let rv = posix_spawnp(&processID, argv.cArray[0]!, &fileActions, &attributes, argv.cArray, env.cArray)
guard rv == 0 else {
throw SystemError.posix_spawn(rv, arguments)
}
if outputRedirection.redirectsOutput {
let outputClosures = outputRedirection.outputClosures
// Close the write end of the output pipe.
try close(fd: &outputPipe[1])
// Create a thread and start reading the output on it.
var thread = Thread { [weak self] in
if let readResult = self?.readOutput(onFD: outputPipe[0], outputClosure: outputClosures?.stdoutClosure) {
self?.stdout.result = readResult
}
}
thread.start()
self.stdout.thread = thread
// Close the write end of the stderr pipe.
try close(fd: &stderrPipe[1])
// Create a thread and start reading the stderr output on it.
thread = Thread { [weak self] in
if let readResult = self?.readOutput(onFD: stderrPipe[0], outputClosure: outputClosures?.stderrClosure) {
self?.stderr.result = readResult
}
}
thread.start()
self.stderr.thread = thread
}
#endif // POSIX implementation
}
/// Blocks the calling process until the subprocess finishes execution.
@discardableResult
public func waitUntilExit() throws -> ProcessResult {
#if os(Windows)
precondition(_process != nil, "The process is not yet launched.")
let p = _process!
p.waitUntilExit()
stdout.thread?.join()
stderr.thread?.join()
let executionResult = ProcessResult(
arguments: arguments,
environment: environment,
exitStatusCode: p.terminationStatus,
output: stdout.result,
stderrOutput: stderr.result
)
return executionResult
#else
return try serialQueue.sync {
precondition(launched, "The process is not yet launched.")
// If the process has already finsihed, return it.
if let existingResult = _result {
return existingResult
}
// If we're reading output, make sure that is finished.
stdout.thread?.join()
stderr.thread?.join()
// Wait until process finishes execution.
var exitStatusCode: Int32 = 0
var result = waitpid(processID, &exitStatusCode, 0)
while result == -1 && errno == EINTR {
result = waitpid(processID, &exitStatusCode, 0)
}
if result == -1 {
throw SystemError.waitpid(errno)
}
// Construct the result.
let executionResult = ProcessResult(
arguments: arguments,
environment: environment,
exitStatusCode: exitStatusCode,
output: stdout.result,
stderrOutput: stderr.result
)
self._result = executionResult
return executionResult
}
#endif
}
#if !os(Windows)
/// Reads the given fd and returns its result.
///
/// Closes the fd before returning.
private func readOutput(onFD fd: Int32, outputClosure: OutputClosure?) -> Result<[UInt8], Swift.Error> {
// Read all of the data from the output pipe.
let N = 4096
var buf = [UInt8](repeating: 0, count: N + 1)
var out = [UInt8]()
var error: Swift.Error? = nil
loop: while true {
let n = read(fd, &buf, N)
switch n {
case -1:
if errno == EINTR {
continue
} else {
error = SystemError.read(errno)
break loop
}
case 0:
break loop
default:
let data = buf[0..<n]
if let outputClosure = outputClosure {
outputClosure(Array(data))
} else {
out += data
}
}
}
// Close the read end of the output pipe.
close(fd)
// Construct the output result.
return error.map(Result.failure) ?? .success(out)
}
#endif
/// Send a signal to the process.
///
/// Note: This will signal all processes in the process group.
public func signal(_ signal: Int32) {
#if os(Windows)
if signal == SIGINT {
_process?.interrupt()
} else {
_process?.terminate()
}
#else
assert(launched, "The process is not yet launched.")
_ = TSCLibc.kill(startNewProcessGroup ? -processID : processID, signal)
#endif
}
}
extension Process {
/// Execute a subprocess and block until it finishes execution
///
/// - Parameters:
/// - arguments: The arguments for the subprocess.
/// - environment: The environment to pass to subprocess. By default the current process environment
/// will be inherited.
/// - Returns: The process result.
@discardableResult
static public func popen(arguments: [String], environment: [String: String] = ProcessEnv.vars) throws -> ProcessResult {
let process = Process(arguments: arguments, environment: environment, outputRedirection: .collect)
try process.launch()
return try process.waitUntilExit()
}
@discardableResult
static public func popen(args: String..., environment: [String: String] = ProcessEnv.vars) throws -> ProcessResult {
return try Process.popen(arguments: args, environment: environment)
}
/// Execute a subprocess and get its (UTF-8) output if it has a non zero exit.
///
/// - Parameters:
/// - arguments: The arguments for the subprocess.
/// - environment: The environment to pass to subprocess. By default the current process environment
/// will be inherited.
/// - Returns: The process output (stdout + stderr).
@discardableResult
static public func checkNonZeroExit(arguments: [String], environment: [String: String] = ProcessEnv.vars) throws -> String {
let process = Process(arguments: arguments, environment: environment, outputRedirection: .collect)
try process.launch()
let result = try process.waitUntilExit()
// Throw if there was a non zero termination.
guard result.exitStatus == .terminated(code: 0) else {
throw ProcessResult.Error.nonZeroExit(result)
}
return try result.utf8Output()
}
@discardableResult
static public func checkNonZeroExit(args: String..., environment: [String: String] = ProcessEnv.vars) throws -> String {
return try checkNonZeroExit(arguments: args, environment: environment)
}
public convenience init(args: String..., environment: [String: String] = ProcessEnv.vars, outputRedirection: OutputRedirection = .collect) {
self.init(arguments: args, environment: environment, outputRedirection: outputRedirection)
}
}
// MARK: - Private helpers
#if !os(Windows)
#if os(macOS)
private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#else
private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t
#endif
private func WIFEXITED(_ status: Int32) -> Bool {
return _WSTATUS(status) == 0
}
private func _WSTATUS(_ status: Int32) -> Int32 {
return status & 0x7f
}
private func WIFSIGNALED(_ status: Int32) -> Bool {
return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)
}
private func WEXITSTATUS(_ status: Int32) -> Int32 {
return (status >> 8) & 0xff
}
private func WTERMSIG(_ status: Int32) -> Int32 {
return status & 0x7f
}
/// Open the given pipe.
private func open(pipe: inout [Int32]) throws {
let rv = TSCLibc.pipe(&pipe)
guard rv == 0 else {
throw SystemError.pipe(rv)
}
}
/// Close the given fd.
private func close(fd: inout Int32) throws {
let rv = TSCLibc.close(fd)
guard rv == 0 else {
throw SystemError.close(rv)
}
}
extension Process.Error: CustomStringConvertible {
public var description: String {
switch self {
case .missingExecutableProgram(let program):
return "could not find executable for '\(program)'"
}
}
}
extension ProcessResult.Error: CustomStringConvertible {
public var description: String {
switch self {
case .illegalUTF8Sequence:
return "illegal UTF8 sequence output"
case .nonZeroExit(let result):
let stream = BufferedOutputByteStream()
switch result.exitStatus {
case .terminated(let code):
stream <<< "terminated(\(code)): "
case .signalled(let signal):
stream <<< "signalled(\(signal)): "
}
// Strip sandbox information from arguments to keep things pretty.
var args = result.arguments
// This seems a little fragile.
if args.first == "sandbox-exec", args.count > 3 {
args = args.suffix(from: 3).map({$0})
}
stream <<< args.map({ $0.spm_shellEscaped() }).joined(separator: " ")
// Include the output, if present.
if let output = try? result.utf8Output() + result.utf8stderrOutput() {
// We indent the output to keep it visually separated from everything else.
let indentation = " "
stream <<< " output:\n" <<< indentation <<< output.replacingOccurrences(of: "\n", with: "\n" + indentation)
if !output.hasSuffix("\n") {
stream <<< "\n"
}
}
return stream.bytes.description
}
}
}
#endif
| 36.657019 | 144 | 0.616818 |
693f43e3f17de061ba621cd98a0f0204c1376233 | 1,240 | //
// PivotalProjectMembership.swift
// bugTrap
//
// Created by Colby L Williams on 11/10/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class PivotalProjectMembership : JsonSerializable {
var id = 0
var personId = 0
var person = PivotalPerson()
var kind = ""
init (id: Int, person: PivotalPerson, kind: String) {
self.id = id
self.person = person
self.personId = person.id
self.kind = kind
}
class func deserialize (json: JSON) -> PivotalProjectMembership? {
var person = PivotalPerson()
let id = json["id"].intValue
if let personW = PivotalPerson.deserialize(json["person"]) {
person = personW
} else {
person.id = json["person_id"].intValue
}
let kind = json["kind"].stringValue
return PivotalProjectMembership (id: id, person: person, kind: kind)
}
class func deserializeAll(json: JSON) -> [PivotalProjectMembership] {
var items = [PivotalProjectMembership]()
if let jsonArray = json.array {
for item: JSON in jsonArray {
if let pivotalProjectMembership = deserialize(item) {
items.append(pivotalProjectMembership)
}
}
}
return items
}
func serialize () -> NSMutableDictionary {
return NSMutableDictionary()
}
} | 18.787879 | 70 | 0.68629 |
896910d8503b7c09ac04743973323422143a3ecd | 9,939 | //
// PrivateDatabaseManager.swift
// IceCream
//
// Created by caiyue on 2019/4/22.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
import CloudKit
final class PrivateDatabaseManager: DatabaseManager {
let container: CKContainer
let database: CKDatabase
let syncObjects: [Syncable]
public init(objects: [Syncable], container: CKContainer) {
self.syncObjects = objects
self.container = container
self.database = container.privateCloudDatabase
}
func fetchChangesInDatabase(_ callback: (() -> Void)?) {
let changesOperation = CKFetchDatabaseChangesOperation(previousServerChangeToken: databaseChangeToken)
/// Only update the changeToken when fetch process completes
changesOperation.changeTokenUpdatedBlock = { [weak self] newToken in
self?.databaseChangeToken = newToken
}
changesOperation.fetchDatabaseChangesCompletionBlock = {
[weak self]
newToken, _, error in
guard let self = self else { return }
switch ErrorHandler.shared.resultType(with: error) {
case .success:
self.databaseChangeToken = newToken
// Fetch the changes in zone level
self.fetchChangesInZones(callback)
case .retry(let timeToWait, _):
ErrorHandler.shared.retryOperationIfPossible(retryAfter: timeToWait, block: {
self.fetchChangesInDatabase(callback)
})
case .recoverableError(let reason, _):
switch reason {
case .changeTokenExpired:
/// The previousServerChangeToken value is too old and the client must re-sync from scratch
self.databaseChangeToken = nil
self.fetchChangesInDatabase(callback)
default:
return
}
default:
return
}
}
database.add(changesOperation)
}
func createCustomZonesIfAllowed() {
let zonesToCreate = syncObjects.filter { !$0.isCustomZoneCreated }.map { CKRecordZone(zoneID: $0.zoneID) }
guard zonesToCreate.count > 0 else { return }
let modifyOp = CKModifyRecordZonesOperation(recordZonesToSave: zonesToCreate, recordZoneIDsToDelete: nil)
modifyOp.modifyRecordZonesCompletionBlock = { [weak self](_, _, error) in
guard let self = self else { return }
switch ErrorHandler.shared.resultType(with: error) {
case .success:
self.syncObjects.forEach { object in
object.isCustomZoneCreated = true
// As we register local database in the first step, we have to force push local objects which
// have not been caught to CloudKit to make data in sync
DispatchQueue.main.async {
object.pushLocalObjectsToCloudKit()
}
}
case .retry(let timeToWait, _):
ErrorHandler.shared.retryOperationIfPossible(retryAfter: timeToWait, block: {
self.createCustomZonesIfAllowed()
})
default:
return
}
}
database.add(modifyOp)
}
func createDatabaseSubscriptionIfHaveNot() {
#if os(iOS) || os(tvOS) || os(macOS)
guard !subscriptionIsLocallyCached else { return }
let subscription = CKDatabaseSubscription(subscriptionID: IceCreamSubscription.cloudKitPrivateDatabaseSubscriptionID.id)
let notificationInfo = CKSubscription.NotificationInfo()
notificationInfo.shouldSendContentAvailable = true // Silent Push
subscription.notificationInfo = notificationInfo
let createOp = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: [])
createOp.modifySubscriptionsCompletionBlock = { _, _, error in
guard error == nil else { return }
self.subscriptionIsLocallyCached = true
}
createOp.qualityOfService = .utility
database.add(createOp)
#endif
}
func startObservingTermination() {
#if os(iOS) || os(tvOS)
NotificationCenter.default.addObserver(self, selector: #selector(self.cleanUp), name: UIApplication.willTerminateNotification, object: nil)
#elseif os(macOS)
NotificationCenter.default.addObserver(self, selector: #selector(self.cleanUp), name: NSApplication.willTerminateNotification, object: nil)
#endif
}
func registerLocalDatabase() {
self.syncObjects.forEach { object in
DispatchQueue.main.async {
object.registerLocalDatabase()
}
}
}
private func fetchChangesInZones(_ callback: (() -> Void)? = nil) {
let changesOp = CKFetchRecordZoneChangesOperation(recordZoneIDs: zoneIds, optionsByRecordZoneID: zoneIdOptions)
changesOp.fetchAllChanges = true
changesOp.recordZoneChangeTokensUpdatedBlock = { [weak self] zoneId, token, _ in
guard let self = self else { return }
guard let syncObject = self.syncObjects.first(where: { $0.zoneID == zoneId }) else { return }
syncObject.zoneChangesToken = token
}
changesOp.recordChangedBlock = { [weak self] record in
/// The Cloud will return the modified record since the last zoneChangesToken, we need to do local cache here.
/// Handle the record:
guard let self = self else { return }
guard let syncObject = self.syncObjects.first(where: { $0.recordType == record.recordType }) else { return }
syncObject.add(record: record)
}
changesOp.recordWithIDWasDeletedBlock = { [weak self] recordId, _ in
guard let self = self else { return }
guard let syncObject = self.syncObjects.first(where: { $0.zoneID == recordId.zoneID }) else { return }
syncObject.delete(recordID: recordId)
}
changesOp.recordZoneFetchCompletionBlock = { [weak self](zoneId ,token, _, _, error) in
guard let self = self else { return }
switch ErrorHandler.shared.resultType(with: error) {
case .success:
guard let syncObject = self.syncObjects.first(where: { $0.zoneID == zoneId }) else { return }
syncObject.zoneChangesToken = token
callback?()
print("Fetch records successfully in zone: \(zoneId))")
case .retry(let timeToWait, _):
ErrorHandler.shared.retryOperationIfPossible(retryAfter: timeToWait, block: {
self.fetchChangesInZones(callback)
})
case .recoverableError(let reason, _):
switch reason {
case .changeTokenExpired:
/// The previousServerChangeToken value is too old and the client must re-sync from scratch
guard let syncObject = self.syncObjects.first(where: { $0.zoneID == zoneId }) else { return }
syncObject.zoneChangesToken = nil
self.fetchChangesInZones(callback)
default:
return
}
default:
return
}
}
database.add(changesOp)
}
}
extension PrivateDatabaseManager {
/// The changes token, for more please reference to https://developer.apple.com/videos/play/wwdc2016/231/
var databaseChangeToken: CKServerChangeToken? {
get {
/// For the very first time when launching, the token will be nil and the server will be giving everything on the Cloud to client
/// In other situation just get the unarchive the data object
guard let tokenData = UserDefaults.standard.object(forKey: IceCreamKey.databaseChangesTokenKey.value) as? Data else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: tokenData) as? CKServerChangeToken
}
set {
guard let n = newValue else {
UserDefaults.standard.removeObject(forKey: IceCreamKey.databaseChangesTokenKey.value)
return
}
let data = NSKeyedArchiver.archivedData(withRootObject: n)
UserDefaults.standard.set(data, forKey: IceCreamKey.databaseChangesTokenKey.value)
}
}
var subscriptionIsLocallyCached: Bool {
get {
guard let flag = UserDefaults.standard.object(forKey: IceCreamKey.subscriptionIsLocallyCachedKey.value) as? Bool else { return false }
return flag
}
set {
UserDefaults.standard.set(newValue, forKey: IceCreamKey.subscriptionIsLocallyCachedKey.value)
}
}
private var zoneIds: [CKRecordZone.ID] {
return syncObjects.map { $0.zoneID }
}
private var zoneIdOptions: [CKRecordZone.ID: CKFetchRecordZoneChangesOperation.ZoneOptions] {
return syncObjects.reduce([CKRecordZone.ID: CKFetchRecordZoneChangesOperation.ZoneOptions]()) { (dict, syncObject) -> [CKRecordZone.ID: CKFetchRecordZoneChangesOperation.ZoneOptions] in
var dict = dict
let zoneChangesOptions = CKFetchRecordZoneChangesOperation.ZoneOptions()
zoneChangesOptions.previousServerChangeToken = syncObject.zoneChangesToken
dict[syncObject.zoneID] = zoneChangesOptions
return dict
}
}
@objc func cleanUp() {
for syncObject in syncObjects {
syncObject.cleanUp()
}
}
}
| 41.240664 | 193 | 0.610625 |
fc43da7106b1f34195b60c224ed0b74a06f14f0b | 633 | //
// Weekend.swift
// Timetables
//
// Created by JiaChen(: on 6/7/20.
// Copyright © 2020 SST Inc. All rights reserved.
//
import Foundation
import SwiftUI
import WidgetKit
extension Screens {
struct WeekendView: View {
var family: WidgetFamily
@ViewBuilder
var body: some View {
if family == .systemSmall {
WeekendViews.Small()
} else {
WeekendViews.Medium()
}
}
}
}
struct Weekend_Previews: PreviewProvider {
static var previews: some View {
Screens.WeekendView(family: .systemMedium)
}
}
| 19.181818 | 50 | 0.575039 |
1631f23a615ca1f9678b1ed7a4b1efe953c5b5a5 | 2,776 | //
// AverageCollection.swift
// Ents
//
// Created by Georges Boumis on 25/08/2017.
// Copyright © 2016-2017 Georges Boumis.
// Licensed under MIT (https://github.com/averello/Ents/blob/master/LICENSE)
//
import Foundation
public struct AverageCollection<E>: RangeReplaceableCollection, RandomAccessCollection where E: BinaryInteger {
private let storage: [E]
public init() {
self.init([] as [E])
}
public init(_ storage: [E]) {
self.storage = storage
}
public var startIndex: Array<E>.Index { return self.storage.startIndex }
public var endIndex: Array<E>.Index { return self.storage.endIndex }
public subscript(i: Array<E>.Index) -> E { return self.storage[i] }
public func index(after i: Array<E>.Index) -> Array<E>.Index { return self.storage.index(after: i) }
enum Error: Swift.Error {
case empty
}
public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, C.Iterator.Element == E {
var array = self.storage
array.replaceSubrange(subrange, with: newElements)
self = AverageCollection(array)
}
}
extension AverageCollection {
public func average<F>() throws -> F where F: FloatingPoint {
guard self.hasElements else { throw AverageCollection.Error.empty }
if E.isSigned {
return self.reduce(F(numericCast(0) as Int64), { (res, next) -> F in
return res + F(numericCast(next) as Int64)
}) / F(numericCast(self.count) as Int64)
}
else {
return self.reduce(F(numericCast(0) as UInt64), { (res, next) -> F in
return res + F(numericCast(next) as UInt64)
}) / F(numericCast(self.count) as UInt64)
}
}
public func average<I>() throws -> I where I: SignedInteger {
guard self.hasElements else { throw AverageCollection.Error.empty }
return self.reduce(I(0), { (res, next) -> I in
return res + I(next)
}) / I(self.count)
}
public func median<F>() throws -> F where F: FloatingPoint {
guard self.hasElements else { throw AverageCollection.Error.empty }
let odd = self.count % 2 != 0
if E.isSigned {
if odd {
return F(numericCast(self.middle!) as Int64)
}
else {
return F(numericCast(self.lowerMiddle! + self.upperMiddle!) as Int64) / F(2)
}
}
else {
if odd {
return F(numericCast(self.middle!) as UInt64)
}
else {
return F(numericCast(self.lowerMiddle! + self.upperMiddle!) as UInt64) / F(2)
}
}
}
}
| 33.047619 | 136 | 0.584294 |
f9bfce1252cfa61c0f29e29271b00555251cc83c | 1,102 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "SailthruMobile",
platforms: [
.iOS(.v10)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "SailthruMobile",
targets: ["SailthruMobile"]),
.library(
name: "SailthruMobileExtension",
targets: ["SailthruMobileExtension"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.binaryTarget(
name: "SailthruMobile",
path: "SailthruMobile.xcframework"
),
.binaryTarget(
name: "SailthruMobileExtension",
path: "SailthruMobileExtension.xcframework"
)
]
)
| 32.411765 | 117 | 0.611615 |
db145fb621c8b6cdd3cbd2bb5f0a83a6784ffcd5 | 14,587 | //
// Garage+Codable.swift
// GarageStorage
//
// Created by Brian Arnold on 10/3/19.
// Copyright © 2015-2020 Wellframe. All rights reserved.
//
import Foundation
extension Garage {
// MARK: - Core Data
static let userInfoKey = CodingUserInfoKey(rawValue: "Garage")!
internal func decodeData<T: Decodable>(_ string: String) throws -> T {
let data: Data = try decrypt(string)
let decoder = JSONDecoder()
decoder.userInfo[Garage.userInfoKey] = self
decoder.dateDecodingStrategy = .custom(decodeTransformableDate)
return try decoder.decode(T.self, from: data)
}
internal func encodeData<T: Encodable>(_ object: T) throws -> String {
let encoder = JSONEncoder()
encoder.userInfo[Garage.userInfoKey] = self
encoder.dateEncodingStrategy = .formatted(Date.isoFormatter)
let data = try encoder.encode(object)
return try encrypt(data)
}
// MARK: - Parking
@discardableResult
internal func makeCoreDataObject<T: Encodable>(from object: T, identifier: String) throws -> CoreDataObject {
let className = String(describing: type(of: object))
let coreDataObject = retrieveCoreDataObject(for: className, identifier: identifier)
coreDataObject.data = try encodeData(object)
return coreDataObject
}
@discardableResult
internal func makeSyncingCoreDataObject<T: Encodable & Syncable>(from object: T, identifier: String) throws -> CoreDataObject {
let coreDataObject = try makeCoreDataObject(from: object, identifier: identifier)
coreDataObject.syncStatus = object.syncStatus
return coreDataObject
}
/// Add an object to the Garage.
///
/// - parameter object: An object of type T that conforms to Mappable.
public func park<T: Mappable>(_ object: T) throws {
try makeCoreDataObject(from: object, identifier: object.id)
autosave()
}
/// Add an object to the Garage.
///
/// - parameter object: An object of type T that conforms to Mappable and Syncable.
public func park<T: Mappable & Syncable>(_ object: T) throws {
try makeSyncingCoreDataObject(from: object, identifier: object.id)
autosave()
}
/// Add an object to the Garage.
///
/// - parameter object: An object of type T that conforms to Encodable and Hashable.
public func park<T: Encodable & Hashable>(_ object: T) throws {
try makeCoreDataObject(from: object, identifier: "\(object.hashValue)")
autosave()
}
/// Add an object to the Garage.
///
/// - parameter object: An object of type T that conforms to Encodable, Hashable and Syncable.
public func park<T: Encodable & Hashable & Syncable>(_ object: T) throws {
try makeSyncingCoreDataObject(from: object, identifier: "\(object.hashValue)")
autosave()
}
/// Adds an array of objects to the garage.
///
/// - parameter objects: An array of objects of the same type T, that conform to Mappable.
public func parkAll<T: Mappable>(_ objects: [T]) throws {
for object in objects {
try makeCoreDataObject(from: object, identifier: object.id)
}
autosave()
}
/// Adds an array of objects to the garage.
///
/// - parameter objects: An array of objects of the same type T, that conform to Mappable and Syncable.
public func parkAll<T: Mappable & Syncable>(_ objects: [T]) throws {
for object in objects {
try makeSyncingCoreDataObject(from: object, identifier: object.id)
}
autosave()
}
/// Adds an array of objects to the garage.
///
/// - parameter objects: An array of objects of the same type T, that conform to Encodable and Hashable.
public func parkAll<T: Encodable & Hashable>(_ objects: [T]) throws {
for object in objects {
try makeCoreDataObject(from: object, identifier: "\(object.hashValue)")
}
autosave()
}
/// Adds an array of objects to the garage.
///
/// - parameter objects: An array of objects of the same type T, that conform to Encodable, Hashable and Syncable.
public func parkAll<T: Encodable & Hashable & Syncable>(_ objects: [T]) throws {
for object in objects {
try makeSyncingCoreDataObject(from: object, identifier: "\(object.hashValue)")
}
autosave()
}
// MARK: - Retrieving
private func makeCodable<T: Decodable>(from coreDataObject: CoreDataObject) throws -> T {
let codable: T = try decodeData(coreDataObject.data)
return codable
}
private func makeSyncable<T: Decodable & Syncable>(from coreDataObject: CoreDataObject) throws -> T {
var syncable: T = try makeCodable(from: coreDataObject)
syncable.syncStatus = coreDataObject.syncStatus
return syncable
}
/// Fetches an object of a given class with a given identifier from the Garage.
///
/// - parameter objectClass: The type of the object to retrieve. This class must conform to Decodable.
/// - parameter identifier: The identifier of the object to retrieve. This is the identifier specified by that object's mapping.
///
/// - returns: An object conforming to the specified class, or nil if it was not found.
public func retrieve<T: Decodable>(_ objectClass: T.Type, identifier: String) throws -> T? {
let className = String(describing: T.self)
let coreDataObject = try fetchCoreDataObject(for: className, identifier: identifier)
return try makeCodable(from: coreDataObject)
}
/// Fetches an object of a given class with a given identifier from the Garage.
///
/// - parameter objectClass: The type of the object to retrieve. This class must conform to Decodable.
/// - parameter identifier: The identifier of the object to retrieve. This is the identifier specified by that object's mapping.
///
/// - returns: An object conforming to the specified class, or nil if it was not found.
public func retrieve<T: Decodable & Syncable>(_ objectClass: T.Type, identifier: String) throws -> T? {
let className = String(describing: T.self)
let coreDataObject = try fetchCoreDataObject(for: className, identifier: identifier)
return try makeSyncable(from: coreDataObject)
}
private func makeCodableObjects<T: Decodable>(from coreDataObjects: [CoreDataObject]) throws -> [T] {
var objects = [T]()
for coreDataObject in coreDataObjects {
let codable: T = try makeCodable(from: coreDataObject)
objects.append(codable)
}
return objects
}
private func makeSyncableObjects<T: Decodable & Syncable>(from coreDataObjects: [CoreDataObject]) throws -> [T] {
var objects = [T]()
for coreDataObject in coreDataObjects {
let codable: T = try makeSyncable(from: coreDataObject)
objects.append(codable)
}
return objects
}
/// Fetches all objects of a given class from the Garage.
///
/// - parameter objectClass: The class of the objects to retrieve
///
/// - returns: An array of objects, all of which conform to the specified class. If no objects are found, an empty array is returned.
public func retrieveAll<T: Decodable>(_ objectClass: T.Type) throws -> [T] {
let className = String(describing: T.self)
let coreDataObjects = fetchObjects(for: className, identifier: nil)
return try makeCodableObjects(from: coreDataObjects)
}
/// Fetches all objects of a given class from the Garage.
///
/// - parameter objectClass: The class of the objects to retrieve
///
/// - returns: An array of objects, all of which conform to the specified class. If no objects are found, an empty array is returned.
public func retrieveAll<T: Decodable & Syncable>(_ objectClass: T.Type) throws -> [T] {
let className = String(describing: T.self)
let coreDataObjects = fetchObjects(for: className, identifier: nil)
return try makeSyncableObjects(from: coreDataObjects)
}
// MARK: - Sync Status
private func updateCoreDataSyncStatus(_ syncStatus: SyncStatus, for className: String, identifier: String) throws {
let coreDataObject = try fetchCoreDataObject(for: className, identifier: identifier)
coreDataObject.syncStatus = syncStatus
}
/// Sets the sync status for a given object of type T that conforms to Mappable and Syncable.
///
/// - parameter syncStatus: The SyncStatus of the object
/// - parameter object: An object of type T that conforms to Mappable and Syncable
///
/// - throws: if not successful
public func setSyncStatus<T: Mappable & Syncable>(_ syncStatus: SyncStatus, for object: T) throws {
let className = String(describing: T.self)
let identifier = object.id
try updateCoreDataSyncStatus(syncStatus, for: className, identifier: identifier)
autosave()
}
/// Sets the sync status for a given object of type T that conforms to Hashable and Syncable.
///
/// - parameter syncStatus: The SyncStatus of the object
/// - parameter object: An object of type T that conforms to Hashable and Syncable
///
/// - throws: if not successful
public func setSyncStatus<T: Hashable & Syncable>(_ syncStatus: SyncStatus, for object: T) throws {
let className = String(describing: T.self)
let identifier = "\(object.hashValue)"
try updateCoreDataSyncStatus(syncStatus, for: className, identifier: identifier)
autosave()
}
/// Sets the sync status for an array of objects of the same type T conforming to Mappable and Syncable.
///
/// - parameter syncStatus: The SyncStatus of the objects
/// - parameter objects: An array of objects of the same type T conforming to Mappable and Syncable.
///
/// - throws: if there was a problem setting the sync status for an object. Note: Even if this throws, there still could be objects with their syncStatus was set successfully. A false repsonse simply indicates at least one failure.
public func setSyncStatus<T: Mappable & Syncable>(_ syncStatus: SyncStatus, for objects: [T]) throws {
let className = String(describing: T.self)
for object in objects {
let identifier = object.id
try updateCoreDataSyncStatus(syncStatus, for: className, identifier: identifier)
}
autosave()
}
/// Sets the sync status for an array of objects of the same type T conforming to Hashable and Syncable.
///
/// - parameter syncStatus: The SyncStatus of the objects
/// - parameter objects: An array of objects of the same type T conforming to Hashable and Syncable.
///
/// - throws: if there was a problem setting the sync status for an object. Note: Even if this throws, there still could be objects with their syncStatus was set successfully. A false repsonse simply indicates at least one failure.
public func setSyncStatus<T: Hashable & Syncable>(_ syncStatus: SyncStatus, for objects: [T]) throws {
let className = String(describing: T.self)
for object in objects {
let identifier = "\(object.hashValue)"
try updateCoreDataSyncStatus(syncStatus, for: className, identifier: identifier)
}
autosave()
}
private func syncStatus<T>(for object: T, identifier: String) throws -> SyncStatus {
let className = String(describing: T.self)
let coreDataObject = try fetchCoreDataObject(for: className, identifier: identifier)
return coreDataObject.syncStatus
}
/// Returns the sync status for an object.
///
/// - parameter object: An object conforming to Mappable and Syncable
///
/// - returns: The Sync Status
public func syncStatus<T: Mappable & Syncable>(for object: T) throws -> SyncStatus {
let identifier = object.id
return try syncStatus(for: object, identifier: identifier)
}
/// Returns the sync status for an object.
///
/// - parameter object: An object conforming to Hashable and Syncable
///
/// - returns: The Sync Status
public func syncStatus<T: Hashable & Syncable>(for object: T) throws -> SyncStatus {
let identifier = "\(object.hashValue)"
return try syncStatus(for: object, identifier: identifier)
}
/// Returns all the objects of type T conforming to Codable that have a given sync status
///
/// - parameter syncStatus: The Sync Status
///
/// - returns: An array of objects of type T conforming to Codable. If no objects are found, an empty array is returned.
public func retrieveAll<T: Decodable & Syncable>(withStatus syncStatus: SyncStatus) throws -> [T] {
let coreDataObjects = try fetchObjects(with: syncStatus, type: nil)
return try makeSyncableObjects(from: coreDataObjects)
}
// MARK: - Deleting
private func deleteCoreDataObject<T>(_ object: T, identifier: String) throws {
let className = String(describing: T.self)
let coreDataObject = try fetchCoreDataObject(for: className, identifier: identifier)
try delete(coreDataObject)
}
/// Deletes an object of a given type from the Garage
///
/// - parameter object: A type conforming to Codable
public func delete<T: Mappable>(_ object: T) throws {
let identifier = object.id
try deleteCoreDataObject(object, identifier: identifier)
}
/// Deletes an object of a given type from the Garage
///
/// - parameter object: A type conforming to Codable
public func delete<T: Hashable>(_ object: T) throws {
let identifier = "\(object.hashValue)"
try deleteCoreDataObject(object, identifier: identifier)
}
/// Deletes all objects of a given type from the Garage
///
/// - parameter objectClass: A type conforming to Codable
public func deleteAll<T>(_ objectClass: T.Type) {
let className = String(describing: T.self)
let coreDataObjects = fetchObjects(for: className, identifier: nil)
deleteAll(coreDataObjects)
}
}
| 41.677143 | 235 | 0.656338 |
9cc2be12dabec1f469233fff945610164bc1800a | 8,476 | //
// ViewController.swift
// RxMapKit
//
// Created by [email protected] on 01/31/2021.
// Copyright (c) 2021 [email protected]. All rights reserved.
//
import UIKit
import MapKit
import RxMapKit
import RxCocoa
import RxSwift
class Annotation: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String? = nil
let reusableIdentifier: String = "MapAnnotationView"
init(coordinate: CLLocationCoordinate2D, title: String) {
self.coordinate = coordinate
self.title = title
}
}
prefix func !(b: Bool?) -> Bool? { return b != nil ? !b! : nil }
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var actionButton0: UIButton!
@IBOutlet weak var actionButton1: UIButton!
@IBOutlet weak var locationButton: UIButton!
let disposeBag = DisposeBag()
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
bindViewModel()
locationButton.rx.tap
.map { [weak self] in !self?.locationButton.isSelected ?? false }
.bind(to: locationButton.rx.isSelected)
.disposed(by: disposeBag)
let track = locationButton.rx.observe(Bool.self, "selected")
.filter { $0 != nil }
.map { $0! }
.publish()
_ = track.filter { $0 }
.take(1)
.subscribe(onNext: { [weak self] _ in
self?.locationManager.requestWhenInUseAuthorization()
})
_ = track.bind(to: mapView.rx.showsUserLocation.asObserver())
_ = track.map { $0 ? .follow : .none }
.bind(to: mapView.rx.userTrackingModeToAnimate)
track.connect()
.disposed(by: disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.addMapObjects()
}
}
private func addMapObjects() {
let center = CLLocationCoordinate2D(latitude: 23.16, longitude: 113.23)
let place0 = CLLocationCoordinate2D(latitude: 22.95, longitude: 113.36)
mapView.register(MapAnnotationView.self, forAnnotationViewWithReuseIdentifier: "MapAnnotationView")
do {
mapView.rx.handleViewForAnnotation { (mapView, annotation) in
guard let anotation = annotation as? Annotation,
let view = mapView.dequeueReusableAnnotationView(withIdentifier: anotation.reusableIdentifier) as? MapAnnotationView else { return nil }
view.image = UIImage(named: "map_markNormal")
view.canShowCallout = true
view.isDraggable = true
return view
}
mapView.addAnnotations([
Annotation(coordinate: center, title: "1"),
Annotation(coordinate: place0, title: "2")
])
}
do {
mapView.rx.handleRendererForOverlay { (mapView, overlay) in
if overlay is MKCircle {
let renderer = MKCircleRenderer(overlay: overlay)
renderer.strokeColor = UIColor.green.withAlphaComponent(0.8)
renderer.lineWidth = 4
renderer.fillColor = UIColor.green.withAlphaComponent(0.3)
return renderer
} else {
return MKOverlayRenderer(overlay: overlay)
}
}
let circle = MKCircle(center: center, radius: 2000)
circle.title = "Circle"
mapView.addOverlays([circle])
}
Observable.just(MKMapCamera(lookingAtCenter: center, fromDistance: 50000, pitch: 30, heading: 45))
.bind(to: mapView.rx.cameraToAnimate)
.disposed(by: disposeBag)
//actionButton0.rx.tap.map { .satellite }.bind(to: mapView.rx.mapType).disposed(by: disposeBag)
actionButton1.rx.tap.map { false }
.bind(to: mapView.rx.isZoomEnabled)
.disposed(by: disposeBag)
}
}
extension ViewController {
func bindViewModel() {
mapView.rx.regionWillChange
.subscribe(onNext: {
print("Will region change: isAnimated \($0.isAnimated)")
})
.disposed(by: disposeBag)
mapView.rx.regionDidChange
.subscribe(onNext: { print("Did region change: \($0.region) isAnimated \($0.isAnimated)") })
.disposed(by: disposeBag)
mapView.rx.willStartLoadingMap
.subscribe(onNext: { print("Will start loading map") })
.disposed(by: disposeBag)
mapView.rx.didFinishLoadingMap
.subscribe(onNext: { print("Did finish loading map") })
.disposed(by: disposeBag)
mapView.rx.didFailLoadingMap
.subscribe(onNext: { print("Did fail loading map with error: \($0)") })
.disposed(by: disposeBag)
mapView.rx.willStartRenderingMap
.subscribe(onNext: { print("Will start rendering map") })
.disposed(by: disposeBag)
mapView.rx.didFinishRenderingMap
.subscribe(onNext: { print("Did finish rendering map: fully rendered \($0.isFullyRendered)") })
.disposed(by: disposeBag)
mapView.rx.didAddAnnotationViews
.subscribe(onNext: { views in
// for v in views {
// print("Did add annotation views: \(v.annotation!.title! ?? "unknown")")
// v.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
// UIView.animate(withDuration: 0.4) { v.transform = CGAffineTransform.identity }
// }
})
.disposed(by: disposeBag)
mapView.rx.didSelectAnnotationView
.subscribe(onNext: { view in
print("Did selected: \(view.annotation!.title! ?? "")")
// view.image = #imageLiteral(resourceName: "marker_selected")
// view.backgroundColor = .purple
})
.disposed(by: disposeBag)
mapView.rx.didDeselectAnnotationView
.subscribe(onNext: { view in
print("Did deselected: \(view.annotation!.title! ?? "")")
//// view.image = #imageLiteral(resourceName: "marker_normal")
// view.backgroundColor = .clear
})
.disposed(by: disposeBag)
mapView.rx.willStartLocatingUser
.subscribe(onNext: { print("Will start locating user") })
.disposed(by: disposeBag)
mapView.rx.didStopLocatingUser.asDriver()
.drive(onNext: { print("Did stop locating user") })
.disposed(by: disposeBag)
mapView.rx.didUpdateUserLocation
.subscribe(onNext: { location in
print("Did update user location \(location)")
})
.disposed(by: disposeBag)
mapView.rx.userLocation
.subscribe(onNext: { print("Did update user location: \($0.location?.description ?? "")") })
.disposed(by: disposeBag)
mapView.rx.showsUserLocation.asObservable()
.subscribe(onNext: { print("Shows user location: \($0)") })
.disposed(by: disposeBag)
mapView.rx.didFailToLocateUser.asDriver()
.drive(onNext: { print("Did fail to locate user: \($0)") })
.disposed(by: disposeBag)
mapView.rx.didFailToLocateUser
.subscribe(onNext: { error in
print("Did fail to locate user: \(error.localizedDescription)")
})
.disposed(by: disposeBag)
mapView.rx.dragStateOfAnnotationView
.subscribe(onNext: { (view, newState, oldState) in
print("Drag state did changed: \(view.annotation!.title! ?? "unknown"), \(newState.rawValue) <- \(oldState.rawValue)")
})
.disposed(by: disposeBag)
mapView.rx.didAddRenderers.subscribe(onNext: { renderers in
for r in renderers { print("Did add renderer: \(r.overlay.title! ?? "unknown")") }
})
.disposed(by: disposeBag)
}
}
| 36.534483 | 158 | 0.568664 |
388d0637760388605466856c0d434c2fc8c2bb99 | 3,043 | //
// Router.swift
// movver-ios
//
// Created by Pablo Romeu on 15/9/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import Movver
class Router: MOVVER_RT{
var unwrappedController:ViewController{
return self.movver_currentController as! ViewController
}
override func movver_VM_Call(event: Any) {
let eventViewModel = event as! ViewModelToRouterEvents
switch eventViewModel {
case .showAlert(let alertString):
print("Alert \(alertString)")
let alert = UIAlertController(title: "alert", message: alertString, preferredStyle: .alert);
let button = UIAlertAction(title: "OK", style: .cancel, handler: { (_) in
self.unwrappedController.dismiss(animated: true, completion: {
})
})
alert.addAction(button)
self.unwrappedController.present(alert, animated: true, completion: {
self.movver_tellViewModel(event: RouterToViewModelEvents.didShowAlert)
})
case .goToCollectionView:
print("Go to collection")
let newRouter = CollectionRouter()
self.unwrappedController.navigationController?.pushViewController(newRouter.movver_VC_Instantiate(model: nil,
viewModelClass:CollectionViewModel.self,
storyboard: UIStoryboard(name: "Main", bundle: Bundle.main),
identifier: "CollectionViewController",
previousRouter: self),
animated: true)
case .goToTableView:
print("Go to tableView")
let newRouter = TableRouter()
self.unwrappedController.navigationController?.pushViewController(newRouter.movver_VC_Instantiate(model: nil,
viewModelClass:TableViewModel.self,
storyboard: UIStoryboard(name: "Main", bundle: Bundle.main),
identifier: "TableViewController",
previousRouter: self),
animated: true)
}
}
}
class subRouter: Router {
}
| 47.546875 | 170 | 0.42951 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.