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
|
---|---|---|---|---|---|
6aaf8ea265ba3deb17ef3aa66c8b358df1b4f1dd | 8,010 | //
// AamojiInserter.swift
// aamoji
//
// Created by Nate Parrott on 5/19/15.
// Copyright (c) 2015 Nate Parrott. All rights reserved.
//
import Cocoa
import SQLite
let ReplacementsKey = "NSUserDictionaryReplacementItems"
let ReplacementOnKey = "on"
let ReplacementShortcutKey = "replace"
let ReplacementReplaceWithKey = "with"
class AamojiInserter: NSObject {
var inserted: Bool? {
get {
if let replacements = _defaults.arrayForKey(ReplacementsKey) as? [[NSObject: NSObject]] {
for replacement in replacements {
if let shortcut = replacement[ReplacementShortcutKey] as? String {
if _allShortcuts.contains(shortcut) {
return true
}
}
}
return false
} else {
return nil
}
}
set(insertOpt) {
if let insert = insertOpt {
if let replacements = _defaults.arrayForKey(ReplacementsKey) as? [[NSObject: NSObject]] {
if insert {
_insertReplacements()
} else {
_deleteReplacements()
}
/*let withoutAamoji = replacements.filter({ !self._replacementBelongsToAamoji($0) })
let newReplacements: [[NSObject: NSObject]] = insert ? (withoutAamoji + aamojiEntries()) : withoutAamoji
var globalDomain = _defaults.persistentDomainForName(NSGlobalDomain)!
globalDomain[ReplacementsKey] = newReplacements
_defaults.setPersistentDomain(globalDomain, forName: NSGlobalDomain)
_defaults.synchronize()*/
}
}
}
}
private func _insertReplacements() {
// make the change in sqlite:
let db = Database(_pathForDatabase())
var pk = db.scalar("SELECT max(Z_PK) FROM 'ZUSERDICTIONARYENTRY'") as? Int ?? 0
let timestamp = Int64(NSDate().timeIntervalSince1970)
for entry in aamojiEntries() {
// key, timestamp, with, replace
let replace = entry[ReplacementShortcutKey] as! String
let with = entry[ReplacementReplaceWithKey] as! String
db.run("INSERT INTO 'ZUSERDICTIONARYENTRY' VALUES(?,1,1,0,0,0,0,?,NULL,NULL,NULL,NULL,NULL,?,?,NULL)", [pk, timestamp, with, replace])
pk++
}
// make the change in nsuserdefaults:
let existingReplacementEntries = _defaults.arrayForKey(ReplacementsKey) as! [[NSObject: NSObject]]
_setReplacementsInUserDefaults(existingReplacementEntries + aamojiEntries())
}
private func _deleteReplacements() {
// make the change in sqlite:
let db = Database(_pathForDatabase())
for entry in aamojiEntries() {
let shortcut = entry[ReplacementShortcutKey] as! String
db.run("DELETE FROM 'ZUSERDICTIONARYENTRY' WHERE ZSHORTCUT = ?", [shortcut])
}
// make the change in nsuserdefaults:
let existingReplacementEntries = _defaults.arrayForKey(ReplacementsKey) as! [[NSObject: NSObject]]
let withoutAamojiEntries = existingReplacementEntries.filter({ !self._allShortcuts.contains($0[ReplacementShortcutKey] as! String) })
_setReplacementsInUserDefaults(withoutAamojiEntries)
}
private func _pathForDatabase() -> String {
let library = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true).first as! String
let container1 = library.stringByAppendingPathComponent("Dictionaries/CoreDataUbiquitySupport")
let contents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(container1, error: nil) as! [String]
let userName = NSUserName()
let matchingDirname = contents.filter({ $0.startsWith(userName) }).first!
let container2 = container1.stringByAppendingPathComponent(matchingDirname).stringByAppendingPathComponent("UserDictionary")
// find the active icloud directory first, then fall back to local:
var subdir = "local"
for child in NSFileManager.defaultManager().contentsOfDirectoryAtPath(container2, error: nil) as! [String] {
let containerDir = container2.stringByAppendingPathComponent(child).stringByAppendingPathComponent("container")
if NSFileManager.defaultManager().fileExistsAtPath(containerDir) {
subdir = child
}
}
let path = container2.stringByAppendingPathComponent(subdir).stringByAppendingPathComponent("store/UserDictionary.db")
return path
}
private func _setReplacementsInUserDefaults(replacements: [[NSObject: NSObject]]) {
var globalDomain = _defaults.persistentDomainForName(NSGlobalDomain)!
globalDomain[ReplacementsKey] = replacements
_defaults.setPersistentDomain(globalDomain, forName: NSGlobalDomain)
_defaults.synchronize()
}
private lazy var _allShortcuts: Set<String> = {
let entries = self.aamojiEntries()
return Set(entries.map({ $0[ReplacementShortcutKey] as! String }))
}()
func aamojiEntries() -> [[NSObject: NSObject]] {
let emojiInfoJson = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("emoji", ofType: "json")!)!
let emojiInfo = NSJSONSerialization.JSONObjectWithData(emojiInfoJson, options: nil, error: nil) as! [[String: AnyObject]]
var emojiByShortcut = [String: String]()
var emojiShortcutPrecendences = [String: Double]()
for emojiDict in emojiInfo {
if let emoji = emojiDict["emoji"] as? String {
for (shortcutUnprocessed, precedence) in _shortcutsAndPrecedencesForEmojiInfoEntry(emojiDict) {
if let shortcut = _processShortcutIfAllowed(shortcutUnprocessed) {
let existingPrecedence = emojiShortcutPrecendences[shortcut] ?? 0
if precedence > existingPrecedence {
emojiByShortcut[shortcut] = emoji
emojiShortcutPrecendences[shortcut] = precedence
}
}
}
}
}
let entries = Array(emojiByShortcut.keys).map() {
(shortcut) -> [NSObject: NSObject] in
let emoji = emojiByShortcut[shortcut]!
return [ReplacementOnKey: 1, ReplacementShortcutKey: "aa" + shortcut, ReplacementReplaceWithKey: emoji]
}
return entries
}
private func _shortcutsAndPrecedencesForEmojiInfoEntry(entry: [String: AnyObject]) -> [(String, Double)] {
var results = [(String, Double)]()
if let aliases = entry["aliases"] as? [String] {
for alias in aliases {
results.append((alias, 3))
}
}
if let description = entry["description"] as? String {
let words = description.componentsSeparatedByString(" ")
if let firstWord = words.first {
results.append((firstWord, 2))
}
for word in words {
results.append((word, 1))
}
}
if let tags = entry["tags"] as? [String] {
for tag in tags {
results.append((tag, 1.5))
}
}
return results
}
private var _allowedCharsInShortcutStrings = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyz0123456789_:")
private func _processShortcutIfAllowed(var shortcut: String) -> String? {
shortcut = shortcut.lowercaseString
if shortcut.containsOnlyCharactersFromSet(_allowedCharsInShortcutStrings) {
return shortcut
} else {
return nil
}
}
private var _defaults = NSUserDefaults()
}
| 44.010989 | 146 | 0.613483 |
e92a18bed57bb02c69de0e483291c59d743324bc | 990 | /*********************************************
*
* This code is under the MIT License (MIT)
*
* Copyright (c) 2021 AliSoftware
*
*********************************************/
import Foundation
/// A few of the protocols' (i.e. `StoryboardBased`, `NibLoadable` and `NibOwnerLoadable` described below) default
/// implementations attempt to load resources from the bundle containing the resource.
/// It does this through the `Bundled` protocol. Each time you declare conformance to
/// `StoryboardBased`, `NibLoadable` or `NibOwnerLoadable`, you will have
/// to provide access to the appropriate bundle.
///
/// This can be achieved through one of the following methods...
/// 1) Declare your `Reusable` based classes to conform to `BundledSelf`
/// 2) Declare your `Reusable` based classes to conform to `BundledModule`
/// 3) Provide you own implementation of the `static var bundle: Bundle` property directly
public protocol Bundled {
static var bundle: Bundle { get }
}
| 39.6 | 116 | 0.666667 |
11048eeda2a360d42a576687787daeb8c543ff39 | 2,141 | /**
* BulletinBoard
* Copyright (c) 2017 Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* An item that can be displayed inside a bulletin card.
*/
@objc public protocol BulletinItem: class {
// MARK: - Configuration
/**
* The current object managing the item.
*
* This property is set when the item is currently being displayed. It will be set to `nil` when
* the item is removed from view.
*
* When implementing `BulletinItem`, you should mark this property `weak` to avoid retain cycles.
*/
var manager: BulletinManager? { get set }
/**
* Whether the page can be dismissed.
*
* If you set this value to `true`, the user will be able to dismiss the bulletin by tapping outside
* of the card or by swiping down.
*
* You should set it to `true` for the last item you want to display.
*/
var isDismissable: Bool { get set }
/**
* The block of code to execute when the bulletin item is dismissed. This is called when the bulletin
* is moved out of view.
*
* You can set it to `nil` if `isDismissable` is set to false.
*
* - parameter item: The item that is being dismissed. When calling `dismissalHandler`, the manager
* passes a reference to `self` so you don't have to manage weak references yourself.
*/
var dismissalHandler: ((_ item: BulletinItem) -> Void)? { get set }
/**
* The item to display after this one.
*
* If you set this value, you'll be able to call `displayNextItem()` to push the next item to
* the stack.
*/
var nextItem: BulletinItem? { get set }
/**
* Creates the list of views to display in the bulletin.
*
* The views will be arranged vertically in the order they are stored in the array returned by
* this function.
*/
func makeArrangedSubviews() -> [UIView]
/**
* Called by the manager when the item was removed from the bulletin. Use this function to
* remove any button target or gesture recognizers from your managed views.
*/
func tearDown()
}
| 28.171053 | 105 | 0.641289 |
de92187fe6abbe5cc6a6b44939213b4005d7e5a8 | 3,163 | //
// Copyright (c) 2019 Google 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 MLKitCommon
import MLKitImageClassificationAutoML
class ModelManagementSnippets {
func setupRemoteModel() {
// [START setup_remote_model]
let downloadConditions = ModelDownloadConditions(allowsCellularAccess: true,
allowsBackgroundDownloading: true)
// Instantiate a concrete subclass of RemoteModel.
let remoteModel = AutoMLRemoteModel(name: "your_remote_model" // The name you assigned in the console.
)
// [END setup_remote_model]
// [START start_download]
let downloadProgress = ModelManager.modelManager().download(remoteModel, conditions: downloadConditions)
// ...
if downloadProgress.isFinished {
// The model is available on the device
}
// [END start_download]
}
func setupModelDownloadNotifications() {
// [START setup_notifications]
NotificationCenter.default.addObserver(
forName: .mlkitModelDownloadDidSucceed,
object: nil,
queue: nil
) { [weak self] notification in
guard let strongSelf = self,
let userInfo = notification.userInfo,
let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as? RemoteModel,
model.name == "your_remote_model"
else { return }
// The model was downloaded and is available on the device
}
NotificationCenter.default.addObserver(
forName: .mlkitModelDownloadDidFail,
object: nil,
queue: nil
) { [weak self] notification in
guard let strongSelf = self,
let userInfo = notification.userInfo,
let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as? RemoteModel
else { return }
let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
// ...
}
// [END setup_notifications]
}
func setupLocalModel() {
// [START setup_local_model]
guard let manifestPath = Bundle.main.path(forResource: "manifest",
ofType: "json",
inDirectory: "my_model") else { return }
// Instantiate a concrete subclass of LocalModel.
let localModel = AutoMLLocalModel(manifestPath: manifestPath)
// [END setup_local_model]
}
}
| 38.108434 | 112 | 0.609864 |
e938a64fcd306069cbbfadbba1e48018b0afd8ac | 1,530 | //
// Change.swift
// FireStore-iOS
//
// Created by José Donor on 27/12/2018.
//
import FirebaseFirestore
import SwiftXtend
public enum Change<T: Identifiable & Decodable> where T.Identifier == String {
case delete(T, at: Int)
case insert(T, at: Int)
case move(T, from: Int, to: Int)
case update(T, at: Int)
// MARK: - Initialize
public init?(change: DocumentChange,
ofType type: T.Type) throws {
let document = change.document
let either = document.map(type)
if let error = either.b { throw error }
guard let _value = either.a,
let value = _value else { return nil }
switch change.type {
case .removed:
self = .delete(value, at: Int(change.oldIndex))
case .added:
self = .insert(value, at: Int(change.newIndex))
case .modified:
if change.oldIndex != change.newIndex {
self = .move(value, from: Int(change.oldIndex), to: Int(change.newIndex))
}
else {
self = .update(value, at: Int(change.newIndex))
}
}
}
public var value: T {
switch self {
case let .delete(value, _),
let .insert(value, _),
let .move(value, _, _),
let .update(value, _):
return value
}
}
public var oldIndex: Int? {
switch self {
case let .delete(_, index),
let .move(_, index, _),
let .update(_, index):
return index
case .insert:
return nil
}
}
public var newIndex: Int? {
switch self {
case let .insert(_, index),
let .move(_, _, index),
let .update(_, index):
return index
case .delete:
return nil
}
}
}
| 18 | 78 | 0.627451 |
7a87ac8e0a32b750e93f93281b3893cb514a7ed0 | 2,077 | //
// InfoViewController.swift
// Keyman
//
// Created by Gabriel Wong on 2017-09-05.
// Copyright © 2017 SIL International. All rights reserved.
//
import KeymanEngine
import UIKit
import Reachability
class InfoViewController: UIViewController, UIWebViewDelegate {
@IBOutlet var webView: UIWebView!
private var networkReachable: Reachability?
convenience init() {
if UIDevice.current.userInterfaceIdiom == .phone {
self.init(nibName: "InfoViewController_iPhone", bundle: nil)
} else {
self.init(nibName: "InfoViewController_iPad", bundle: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
extendedLayoutIncludesOpaqueBars = true
webView?.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(self.networkStatusChanged),
name: NSNotification.Name.reachabilityChanged, object: nil)
do {
try networkReachable = Reachability(hostname: "keyman.com")
try networkReachable?.startNotifier()
} catch {
SentryManager.captureAndLog(error, message: "error starting Reachability notifier: \(error)")
}
}
@objc func networkStatusChanged(_ notification: Notification) {
reloadKeymanHelp()
}
func reloadKeymanHelp() {
loadFromLocal()
}
private func loadFromLocal() {
let offlineHelpBundle = Bundle(path: Bundle.main.path(forResource: "OfflineHelp", ofType: "bundle")!)!
// Safari won't recognize the contents without the .html ending.
let filePath = offlineHelpBundle.path(forResource: "index", ofType: "html", inDirectory: nil)
webView.loadRequest(URLRequest(url: URL.init(fileURLWithPath: filePath!)))
}
// Currently unused, as we haven't yet added a toggle to allow users to choose online
// over the default of offline.
private func loadFromServer() {
let appVersion = Version.current.majorMinor
let url = "\(KeymanHosts.HELP_KEYMAN_COM)/products/iphone-and-ipad/\(appVersion.plainString)/"
webView.loadRequest(URLRequest(url: URL(string: url)!))
log.debug("Info page URL: \(url)")
}
}
| 31.469697 | 106 | 0.718344 |
cc060d2b7f1b2ff213baf9acf0991b71aa052433 | 872 | //
// NotificationsViewModelTests.swift
// fujikoTests
//
// Created by Charlie Cai on 23/3/20.
// Copyright © 2020 tickboxs. All rights reserved.
//
import Foundation
import UIKit
import XCTest
import RxSwift
import RxCocoa
import RxBlocking
import RxTest
@testable import fujiko
class NotificationsViewModelTests: XCTestCase {
var vm: NotificationsViewModel!
var scheduler: TestScheduler!
var disposeBag: DisposeBag!
override func setUp() {
vm = NotificationsViewModel()
scheduler = TestScheduler(initialClock: 0)
disposeBag = DisposeBag()
}
override func tearDown() {
}
func testNotificationsNotEmptyWhenPagePresent() {
scheduler.start()
XCTAssert(vm.output.notifications.value.count == 8,
"Could not Get notifications")
}
}
| 20.27907 | 59 | 0.66055 |
bf03529f5c2d2de3a3f52cbe9152b3f7cd92185c | 480 | //
// SwifQLable+Join.swift
// SwifQL
//
// Created by Mihael Isaev on 14/02/2019.
//
import Foundation
//MARK: JOIN
extension SwifQLable {
public func join(_ mode: JoinMode, _ table: SwifQLable, on predicates: SwifQLable) -> SwifQLable {
var parts = self.parts
parts.appendSpaceIfNeeded()
let join = SwifQLJoinBuilder(mode, table, on: predicates)
parts.append(contentsOf: join.parts)
return SwifQLableParts(parts: parts)
}
}
| 22.857143 | 102 | 0.666667 |
500358ab2d35aab740496db5824532eba4b6d53a | 1,196 | import BuildDsl
import SingletonHell
import RunGrayBoxTestsTask
import Foundation
import CiFoundation
import Destinations
BuildDsl.teamcity.main { di in
let environmentProvider: EnvironmentProvider = try di.resolve()
return try RunGrayBoxTestsTask(
bashExecutor: di.resolve(),
grayBoxTestRunner: EmceeGrayBoxTestRunner(
emceeProvider: di.resolve(),
temporaryFileProvider: di.resolve(),
bashExecutor: di.resolve(),
queueServerRunConfigurationUrl: environmentProvider.getUrlOrThrow(
env: Env.MIXBOX_CI_EMCEE_QUEUE_SERVER_RUN_CONFIGURATION_URL
),
sharedQueueDeploymentDestinationsUrl: environmentProvider.getUrlOrThrow(
env: Env.MIXBOX_CI_EMCEE_SHARED_QUEUE_DEPLOYMENT_DESTINATIONS_URL
),
testArgFileJsonGenerator: di.resolve(),
fileDownloader: di.resolve(),
environmentProvider: di.resolve()
),
mixboxTestDestinationConfigurationsProvider: di.resolve(),
iosProjectBuilder: di.resolve(),
bundlerBashCommandGenerator: di.resolve(),
bashEscapedCommandMaker: di.resolve()
)
}
| 36.242424 | 84 | 0.690635 |
2030b606286959d06a317f15fcf32de31d13892f | 1,864 | import Foundation
public struct AppPreviewSet: Codable {
public struct Attributes: Codable {
public let previewType: String?
}
public struct Relationships: Codable {
public let appPreviews: AppPreviewSet.Relationships.AppPreviews?
public let appStoreVersionLocalization: AppPreviewSet.Relationships.AppStoreVersionLocalization?
}
public let attributes: AppScreenshot.Attributes?
public let id: String
public let relationships: AppScreenshot.Relationships?
public private(set) var type: String = "appPreviewSets"
public let links: ResourceLinks<AppScreenshotResponse>
}
public extension AppPreviewSet.Relationships {
struct AppPreviews: Codable {
public let data: AppPreviewSet.Relationships.AppPreviews.Data?
public let links: AppPreviewSet.Relationships.AppPreviews.Links?
public let meta: PagingInformation?
}
struct AppStoreVersionLocalization: Codable {
public let data: AppPreviewSet.Relationships.AppStoreVersionLocalization.Data?
public let links: AppPreviewSet.Relationships.AppStoreVersionLocalization.Links?
}
}
public extension AppPreviewSet.Relationships.AppPreviews {
struct Data: Codable {
public let id: String
public private(set) var type: String = "appPreviews"
}
struct Links: Codable {
/// uri-reference
public let related: URL?
/// uri-reference
public let `self`: URL?
}
}
public extension AppPreviewSet.Relationships.AppStoreVersionLocalization {
struct Data: Codable {
public let id: String
public private(set) var type: String = "appStoreVersionLocalizations"
}
struct Links: Codable {
/// uri-reference
public let related: URL?
/// uri-reference
public let `self`: URL?
}
}
| 25.888889 | 104 | 0.700107 |
678cc3f3b85c85f0a56a9f3f28881cbc56579fad | 6,877 | //
// HomeViewController.swift
// YuDou
//
// Created by Bemagine on 2017/1/4.
// Copyright © 2017年 bemagine. All rights reserved.
//
import UIKit
private let kTitleH : CGFloat = 40
class HomeViewController: BaseViewController {
fileprivate lazy var homeCateArray : [HomeCateModel] = [HomeCateModel]()
fileprivate var pageTitleView : PageTitleView!
/*
fileprivate lazy var pageTitleView : PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kNavitagionBarH+kStatusBarH, width: kScreenW, height: kTitleH)
// let pageTitleView = PageTitleView(frame: titleFrame, titles: ["推荐", "手游", "娱乐","游戏", "趣玩"])
let pageTitleView = PageTitleView(frame: titleFrame, titles: ["推荐"])
pageTitleView.delegate = self
return pageTitleView
}()
*/
fileprivate var pageContentView : PageContentView!
/*
fileprivate lazy var pageContentView : PageContentView = {[weak self] in
let contentViewFrame = CGRect(x: 0, y: kTitleH+kNavitagionBarH+kStatusBarH, width: kScreenW, height: kScreenH - kNavitagionBarH - kStatusBarH - kTitleH)
var childVCs = [UIViewController]()
childVCs.append(RecommendViewController())
// childVCs.append(PhoneGameViewController())
// childVCs.append(AmuseViewController())
// childVCs.append(GameViewController())
// childVCs.append(FunnyViewController())
let pcontentView = PageContentView(frame: contentViewFrame, childVCs: childVCs, parentViewContnroller: self)
pcontentView.delegate = self
return pcontentView
}()
*/
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI
setupUI()
// 获取数据
loadHomeCateData()
NotificationCenter.default.addObserver(self, selector: #selector(self.transformView(notification:)), name: NSNotification.Name(rawValue: NotificationNavigationBarTransform), object: nil)
}
deinit {
// 移除通知
NotificationCenter.default.removeObserver(self)
}
@objc fileprivate func transformView(notification: Notification) {
let objc = notification.object as! ScrollDirection
if objc == .ScrollUp {
if self.pageTitleView.frame.origin.y == kNavitagionBarH+kStatusBarH {
return
}
UIView.animate(withDuration: 0.2, animations: {
self.pageTitleView.frame = CGRect(x: 0, y: kNavitagionBarH+kStatusBarH, width: kScreenW, height: kTitleH)
self.pageContentView.frame = CGRect(x: 0, y: kTitleH+kNavitagionBarH+kStatusBarH, width: kScreenW, height: kScreenH - kNavitagionBarH - kStatusBarH - kTitleH)
})
} else {
if self.pageTitleView.frame.origin.y == kStatusBarH {
return
}
UIView.animate(withDuration: 0.2, animations: {
self.pageTitleView.frame = CGRect(x: 0, y: kStatusBarH, width: kScreenW, height: kTitleH)
self.pageContentView.frame = CGRect(x: 0, y: kTitleH + kStatusBarH, width: kScreenW, height: kScreenH - kTitleH - kStatusBarH)
})
}
super.navigationBarTransform(direction: objc)
}
}
// MARK: - 设置UI
extension HomeViewController {
override func setupUI() {
// 不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
// 设置导航栏
setupNavigationItem()
// 设置内容
// setupContentView()
super.setupUI()
}
private func setupNavigationItem() {
// 设置导航栏背景
// 设置左边的Item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName:"homeLogoIcon")
// 设置右边的Item
let size = CGSize(width: 40, height: 40);
let historyItem = UIBarButtonItem(imageName: "viewHistoryIcon", highImageName: "viewHistoryIconHL", size: size)
let searchItem = UIBarButtonItem(imageName: "searchBtnIcon", highImageName: "searchBtnIconHL", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "scanIcon", highImageName: "scanIconHL", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
fileprivate func setupContentView() {
let titleFrame = CGRect(x: 0, y: kNavitagionBarH+kStatusBarH, width: kScreenW, height: kTitleH)
var titles = ["推荐"]
for item in homeCateArray {
titles.append(item.title)
}
pageTitleView = PageTitleView(frame: titleFrame, titles: titles)
pageTitleView.delegate = self
view.addSubview(pageTitleView)
let contentViewFrame = CGRect(x: 0, y: kTitleH+kNavitagionBarH+kStatusBarH, width: kScreenW, height: kScreenH - kNavitagionBarH - kStatusBarH - kTitleH)
var childVCs = [UIViewController]()
childVCs.append(RecommendViewController())
for item in homeCateArray {
let anchorVC = AmuseViewController()
anchorVC.cateModel = item
childVCs.append(anchorVC)
}
pageContentView = PageContentView(frame: contentViewFrame, childVCs: childVCs, parentViewContnroller: self)
pageContentView.delegate = self
view.addSubview(pageContentView)
}
}
// MARK: - 获取数据
extension HomeViewController {
fileprivate func loadHomeCateData() {
let urlString = "api/homeCate/getCateList?client_sys=ios"
NetWorkTools.loadData(URLString: urlString, params: nil) { (response) in
guard let result = response as? [String : Any] , let resultData = result["data"] as? [[String : Any]] else {
self.loadFiled()
return
}
for dict in resultData {
let cateModel = HomeCateModel(dict: dict)
self.homeCateArray.append(cateModel)
}
// 设置contentView
self.setupContentView()
self.loadDataFinished()
}
}
}
// MARK: - PageTitleViewDelegate, PageContentViewDelegate
extension HomeViewController: PageTitleViewDelegate, PageContentViewDelegate {
func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) {
// 让collectionView滚动到指定位置
pageContentView.setCurrentIndex(index: index)
}
func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| 33.546341 | 194 | 0.61742 |
69daff8f171591f9244ad6e81c7589aabc3b854d | 243 | //
// Array+Extension.swift
// Tests iOS
//
// Created by Vidhyadharan on 05/01/21.
//
import Foundation
extension Array {
func dropAllButLast() -> ArraySlice<Element> {
return self.dropFirst(self.count - 1)
}
}
| 14.294118 | 50 | 0.617284 |
61efbd48d1086d51abff1027a9fcbbbc7f8ab703 | 720 | //
// BooksService.swift
// Example
//
// Created by Anton Glezman on 18.06.2020.
// Copyright © 2020 RedMadRobot. All rights reserved.
//
import Apexy
import ExampleAPI
typealias Book = ExampleAPI.Book
protocol BookService {
@discardableResult
func fetchBooks(completion: @escaping (Result<[Book], Error>) -> Void) -> Progress
}
final class BookServiceImpl: BookService {
let apiClient: Client
init(apiClient: Client) {
self.apiClient = apiClient
}
func fetchBooks(completion: @escaping (Result<[Book], Error>) -> Void) -> Progress {
let endpoint = BookListEndpoint()
return apiClient.request(endpoint, completionHandler: completion)
}
}
| 21.176471 | 88 | 0.670833 |
901d6e0cc410bb36462677edfc30d76acdeabae4 | 5,676 | //===--- Join.swift - Protocol and Algorithm for concatenation ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
internal enum _JoinGeneratorState {
case Start
case GeneratingElements
case GeneratingSeparator
case End
}
/// A generator that presents the elements of the sequences generated
/// by `Base`, concatenated using a given separator.
public struct JoinGenerator<
Base : GeneratorType where Base.Element : SequenceType
> : GeneratorType {
/// Creates a generator that presents the elements of the sequences
/// generated by `base`, concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
public init<
Separator : SequenceType
where
Separator.Generator.Element == Base.Element.Generator.Element
>(base: Base, separator: Separator) {
self._base = base
self._separatorData = ContiguousArray(separator)
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
public mutating func next() -> Base.Element.Generator.Element? {
repeat {
switch _state {
case .Start:
if let nextSubSequence = _base.next() {
_inner = nextSubSequence.generate()
_state = .GeneratingElements
} else {
_state = .End
return nil
}
case .GeneratingElements:
let result = _inner!.next()
if _fastPath(result != nil) {
return result
}
if _separatorData.isEmpty {
_inner = _base.next()?.generate()
if _inner == nil {
_state = .End
return nil
}
} else {
_inner = _base.next()?.generate()
if _inner == nil {
_state = .End
return nil
}
_separator = _separatorData.generate()
_state = .GeneratingSeparator
}
case .GeneratingSeparator:
let result = _separator!.next()
if _fastPath(result != nil) {
return result
}
_state = .GeneratingElements
case .End:
return nil
}
}
while true
}
internal var _base: Base
internal var _inner: Base.Element.Generator? = nil
internal var _separatorData: ContiguousArray<Base.Element.Generator.Element>
internal var _separator: ContiguousArray<Base.Element.Generator.Element>.Generator?
internal var _state: _JoinGeneratorState = .Start
}
/// A sequence that presents the elements of the `Base` sequences
/// concatenated using a given separator.
public struct JoinSequence<
Base : SequenceType where Base.Generator.Element : SequenceType
> : SequenceType {
/// Creates a sequence that presents the elements of `base` sequences
/// concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
public init<
Separator : SequenceType
where
Separator.Generator.Element ==
Base.Generator.Element.Generator.Element
>(base: Base, separator: Separator) {
self._base = base
self._separator = ContiguousArray(separator)
}
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> JoinGenerator<Base.Generator> {
return JoinGenerator(
base: _base.generate(),
separator: _separator)
}
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Generator.Element.Generator.Element> {
var result = ContiguousArray<Generator.Element>()
let separatorSize: Int = numericCast(_separator.count)
let reservation = _base._preprocessingPass {
(s: Base) -> Int in
var r = 0
for chunk in s {
r += separatorSize + chunk.underestimateCount()
}
return r - separatorSize
}
if let n = reservation {
result.reserveCapacity(numericCast(n))
}
if separatorSize != 0 {
var gen = _base.generate()
if let first = gen.next() {
result.appendContentsOf(first)
while let next = gen.next() {
result.appendContentsOf(_separator)
result.appendContentsOf(next)
}
}
} else {
for x in _base {
result.appendContentsOf(x)
}
}
return result._buffer
}
internal var _base: Base
internal var _separator:
ContiguousArray<Base.Generator.Element.Generator.Element>
}
extension SequenceType where Generator.Element : SequenceType {
/// Returns a view, whose elements are the result of interposing a given
/// `separator` between the elements of the sequence `self`.
///
/// For example,
/// `[[1, 2, 3], [4, 5, 6], [7, 8, 9]].joinWithSeparator([-1, -2])`
/// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]`.
@warn_unused_result
public func joinWithSeparator<
Separator : SequenceType
where
Separator.Generator.Element == Generator.Element.Generator.Element
>(separator: Separator) -> JoinSequence<Self> {
return JoinSequence(base: self, separator: separator)
}
}
@available(*, unavailable, message="call the 'joinWithSeparator()' method on the sequence of elements")
public func join<
C : RangeReplaceableCollectionType, S : SequenceType
where S.Generator.Element == C
>(
separator: C, _ elements: S
) -> C {
fatalError("unavailable function can't be called")
}
| 29.409326 | 103 | 0.640063 |
0a6e5cff30e9537583b85142a99d29f6a2c5ca29 | 850 | //
// Speaker+JSON.swift
// talker
//
// Created by Mathias Aichinger on 23/11/2016.
// Copyright © 2016 Easysolutions. All rights reserved.
//
import Foundation
import SwiftyJSON
import TalkerFramework
import Kakapo
class ClientSpeaker: Speaker, JSONInitializable, Serializable {
public required init(json: JSON) {
let serverId: String? = json["serverId"].stringValue
let speakerName: String = json["speakerName"].stringValue
let speakerImageURL: String? = json["speakerImageURL"].stringValue
super.init(serverId: serverId, speakerName: speakerName, speakerImageURL: speakerImageURL)
}
public override init(serverId: String?, speakerName: String, speakerImageURL: String? = nil) {
super.init(serverId: serverId, speakerName: speakerName, speakerImageURL: speakerImageURL)
}
}
| 30.357143 | 98 | 0.72 |
16c99fc7b8f381f2642d185ac33410c156d54234 | 1,274 | //
// RowView.swift
// CustomViewsSolution
//
// Created by Jonathan Rasmusson Work Pro on 2019-10-17.
// Copyright © 2019 Rasmusson Software Consulting. All rights reserved.
//
import UIKit
class RowView: UIView {
var title: String
var isOn: Bool
init(title: String, isOn: Bool) {
self.title = title
self.isOn = isOn
super.init(frame: .zero)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
let titleLabel = makeLabel(withText: title)
let onOffSwith = makeSwitch(isOn: isOn)
addSubview(titleLabel)
addSubview(onOffSwith)
// Everything flush to edges...
titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
onOffSwith.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
onOffSwith.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor).isActive = true
}
// A suggestion about size. But one that can be overridden.
override var intrinsicContentSize: CGSize {
return CGSize(width: 200, height: 31)
}
}
| 25.48 | 94 | 0.66719 |
2903275b51790d772cf922a3791d156bdd0f8d80 | 1,478 | // Copyright 2019 Algorand, 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.
//
// BannerViewInfoStyleSheet.swift
import Foundation
import Macaroon
import UIKit
struct BannerViewInfoStyleSheet: BannerViewStyleSheet {
let title: TextStyle
let background: ViewStyle
let backgroundShadow: Macaroon.Shadow?
private let textColor = Colors.Text.primary
init() {
self.title = [
.font(UIFont.font(withWeight: .semiBold(size: 16.0))),
.textAlignment(.left),
.textOverflow(.fitting),
.textColor(textColor)
]
self.background = []
self.backgroundShadow =
Macaroon.Shadow(
color: rgba(0.0, 0.0, 0.0, 0.1),
opacity: 1.0,
offset: (0, 8),
radius: 6,
fillColor: Colors.Background.secondary,
cornerRadii: (12, 12),
corners: .allCorners
)
}
}
| 30.163265 | 75 | 0.628552 |
6a6df2fd50ed31612430b80de06c593d0d819e31 | 928 | //
// FollowingDataManager.swift
// Recipe-CICCC
//
// Created by 北島 志帆美 on 2020-04-16.
// Copyright © 2020 Argus Chen. All rights reserved.
//
import Foundation
import Firebase
class FollowingDataManager {
weak var delegate: FollowingDelegate?
func getImageOfRecipesFollowing(uid: String, rid: String, indexOfImage: Int, orderFollowing: Int) {
var image = UIImage()
let storage = Storage.storage()
let storageRef = storage.reference()
let imageRef = storageRef.child("user/\(uid)/RecipePhoto/\(rid)/\(rid)")
imageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in //
if error != nil {
print(error?.localizedDescription as Any)
} else {
image = UIImage(data: data!)!
self.delegate?.appendRecipeImage(imgs: image, indexOfImage: indexOfImage, orderFollowing: orderFollowing)
}
}
}
}
| 23.2 | 117 | 0.630388 |
2065880a733ba25a8b1299cc40d13ca1acd86396 | 2,521 | //
// MenuTableViewController.swift
// ZLSwipeableViewSwiftDemo
//
// Created by Zhixuan Lai on 5/25/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
let demoViewControllers = [("Default", ZLSwipeableViewController.self),
("Custom Animation", CustomAnimationDemoViewController.self),
("Custom Swipe", CustomSwipeDemoViewController.self),
("Allowed Direction", CustomDirectionDemoViewController.self),
("History", HistoryDemoViewController.self),
("Previous View", PreviousViewDemoViewController.self),
("Should Swipe", ShouldSwipeDemoViewController.self),
("Always Swipe", AlwaysSwipeDemoViewController.self)]
override func viewDidLoad() {
super.viewDidLoad()
title = "ZLSwipeableView"
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demoViewControllers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = String(format: "s%li-r%li", indexPath.section, indexPath.row)
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
cell.textLabel?.text = titleForRowAtIndexPath(indexPath)
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let title = titleForRowAtIndexPath(indexPath)
let vc = viewControllerForRowAtIndexPath(indexPath)
vc.title = title
navigationController?.pushViewController(vc, animated: true)
}
func titleForRowAtIndexPath(_ indexPath: IndexPath) -> String {
let (title, _) = demoViewControllers[indexPath.row]
return title
}
func viewControllerForRowAtIndexPath(_ indexPath: IndexPath) -> ZLSwipeableViewController {
let (_, vc) = demoViewControllers[indexPath.row]
return vc.init()
}
}
| 38.784615 | 109 | 0.646569 |
d5988499653c38f1b1860d0732b10ad96d7f25e2 | 26,214 | import Foundation
import UIKit
import AVFoundation
import Display
import TelegramCore
import SyncCore
import SwiftSignalKit
import Photos
import CoreLocation
import Contacts
import AddressBook
import UserNotifications
import CoreTelephony
import TelegramPresentationData
import LegacyComponents
import AccountContext
public enum DeviceAccessCameraSubject {
case video
case videoCall
}
public enum DeviceAccessMicrophoneSubject {
case audio
case video
case voiceCall
}
public enum DeviceAccessMediaLibrarySubject {
case send
case save
case wallpaper
}
public enum DeviceAccessLocationSubject {
case send
case live
case tracking
}
public enum DeviceAccessSubject {
case camera(DeviceAccessCameraSubject)
case microphone(DeviceAccessMicrophoneSubject)
case mediaLibrary(DeviceAccessMediaLibrarySubject)
case location(DeviceAccessLocationSubject)
case contacts
case notifications
case siri
case cellularData
}
private let cachedMediaLibraryAccessStatus = Atomic<Bool?>(value: nil)
public func shouldDisplayNotificationsPermissionWarning(status: AccessType, suppressed: Bool) -> Bool {
switch (status, suppressed) {
case (.allowed, _), (.unreachable, true), (.notDetermined, true):
return false
default:
return true
}
}
public final class DeviceAccess {
private static let contactsPromise = Promise<Bool?>(nil)
static var contacts: Signal<Bool?, NoError> {
return self.contactsPromise.get()
|> distinctUntilChanged
}
private static let notificationsPromise = Promise<Bool?>(nil)
static var notifications: Signal<Bool?, NoError> {
return self.notificationsPromise.get()
}
private static let siriPromise = Promise<Bool?>(nil)
static var siri: Signal<Bool?, NoError> {
return self.siriPromise.get()
}
private static let locationPromise = Promise<Bool?>(nil)
static var location: Signal<Bool?, NoError> {
return self.locationPromise.get()
}
public static func isMicrophoneAccessAuthorized() -> Bool? {
return AVAudioSession.sharedInstance().recordPermission == .granted
}
public static func authorizationStatus(applicationInForeground: Signal<Bool, NoError>? = nil, siriAuthorization: (() -> AccessType)? = nil, subject: DeviceAccessSubject) -> Signal<AccessType, NoError> {
switch subject {
case .notifications:
let status = (Signal<AccessType, NoError> { subscriber in
if #available(iOSApplicationExtension 10.0, iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in
switch settings.authorizationStatus {
case .authorized:
if settings.alertSetting == .disabled {
subscriber.putNext(.unreachable)
} else {
subscriber.putNext(.allowed)
}
case .denied:
subscriber.putNext(.denied)
case .notDetermined:
subscriber.putNext(.notDetermined)
default:
subscriber.putNext(.notDetermined)
}
subscriber.putCompletion()
})
} else {
subscriber.putNext(.notDetermined)
subscriber.putCompletion()
}
return EmptyDisposable
} |> afterNext { status in
switch status {
case .allowed, .unreachable:
DeviceAccess.notificationsPromise.set(.single(nil))
default:
break
}
} )
|> then(self.notifications
|> mapToSignal { authorized -> Signal<AccessType, NoError> in
if let authorized = authorized {
return .single(authorized ? .allowed : .denied)
} else {
return .complete()
}
})
if let applicationInForeground = applicationInForeground {
return applicationInForeground
|> distinctUntilChanged
|> mapToSignal { inForeground -> Signal<AccessType, NoError> in
return status
}
} else {
return status
}
case .contacts:
let status = Signal<AccessType, NoError> { subscriber in
if #available(iOSApplicationExtension 9.0, iOS 9.0, *) {
switch CNContactStore.authorizationStatus(for: .contacts) {
case .notDetermined:
subscriber.putNext(.notDetermined)
case .authorized:
subscriber.putNext(.allowed)
default:
subscriber.putNext(.denied)
}
subscriber.putCompletion()
} else {
switch ABAddressBookGetAuthorizationStatus() {
case .notDetermined:
subscriber.putNext(.notDetermined)
case .authorized:
subscriber.putNext(.allowed)
default:
subscriber.putNext(.denied)
}
subscriber.putCompletion()
}
return EmptyDisposable
}
return status
|> then(self.contacts
|> mapToSignal { authorized -> Signal<AccessType, NoError> in
if let authorized = authorized {
return .single(authorized ? .allowed : .denied)
} else {
return .complete()
}
})
case .cellularData:
return Signal { subscriber in
if #available(iOSApplicationExtension 9.0, iOS 9.0, *) {
func statusForCellularState(_ state: CTCellularDataRestrictedState) -> AccessType? {
switch state {
case .restricted:
return .denied
case .notRestricted:
return .allowed
default:
return .allowed
}
}
let cellState = CTCellularData.init()
if let status = statusForCellularState(cellState.restrictedState) {
subscriber.putNext(status)
}
cellState.cellularDataRestrictionDidUpdateNotifier = { restrictedState in
if let status = statusForCellularState(restrictedState) {
subscriber.putNext(status)
}
}
} else {
subscriber.putNext(.allowed)
subscriber.putCompletion()
}
return EmptyDisposable
}
case .siri:
if let siriAuthorization = siriAuthorization {
return Signal { subscriber in
let status = siriAuthorization()
subscriber.putNext(status)
subscriber.putCompletion()
return EmptyDisposable
}
|> then(self.siri
|> mapToSignal { authorized -> Signal<AccessType, NoError> in
if let authorized = authorized {
return .single(authorized ? .allowed : .denied)
} else {
return .complete()
}
})
} else {
return .single(.denied)
}
case .location:
return Signal { subscriber in
let status = CLLocationManager.authorizationStatus()
switch status {
case .authorizedAlways, .authorizedWhenInUse:
subscriber.putNext(.allowed)
case .denied, .restricted:
subscriber.putNext(.denied)
case .notDetermined:
subscriber.putNext(.notDetermined)
@unknown default:
fatalError()
}
subscriber.putCompletion()
return EmptyDisposable
}
|> then(self.location
|> mapToSignal { authorized -> Signal<AccessType, NoError> in
if let authorized = authorized {
return .single(authorized ? .allowed : .denied)
} else {
return .complete()
}
}
)
default:
return .single(.notDetermined)
}
}
public static func authorizeAccess(to subject: DeviceAccessSubject, registerForNotifications: ((@escaping (Bool) -> Void) -> Void)? = nil, requestSiriAuthorization: ((@escaping (Bool) -> Void) -> Void)? = nil, locationManager: LocationManager? = nil, presentationData: PresentationData? = nil, present: @escaping (ViewController, Any?) -> Void = { _, _ in }, openSettings: @escaping () -> Void = { }, displayNotificationFromBackground: @escaping (String) -> Void = { _ in }, _ completion: @escaping (Bool) -> Void = { _ in }) {
switch subject {
case let .camera(cameraSubject):
let status = PGCamera.cameraAuthorizationStatus()
if status == PGCameraAuthorizationStatusNotDetermined {
AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
Queue.mainQueue().async {
completion(response)
if !response, let presentationData = presentationData {
let text: String
switch cameraSubject {
case .video:
text = presentationData.strings.AccessDenied_Camera
case .videoCall:
text = presentationData.strings.AccessDenied_VideoCallCamera
}
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.AccessDenied_Title, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
}
}
}
} else if status == PGCameraAuthorizationStatusRestricted || status == PGCameraAuthorizationStatusDenied, let presentationData = presentationData {
let text: String
if status == PGCameraAuthorizationStatusRestricted {
text = presentationData.strings.AccessDenied_CameraRestricted
} else {
switch cameraSubject {
case .video:
text = presentationData.strings.AccessDenied_Camera
case .videoCall:
text = presentationData.strings.AccessDenied_VideoCallCamera
}
}
completion(false)
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.AccessDenied_Title, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
} else if status == PGCameraAuthorizationStatusAuthorized {
completion(true)
} else {
assertionFailure()
completion(true)
}
case let .microphone(microphoneSubject):
if AVAudioSession.sharedInstance().recordPermission == .granted {
completion(true)
} else {
AVAudioSession.sharedInstance().requestRecordPermission({ granted in
Queue.mainQueue().async {
if granted {
completion(true)
} else if let presentationData = presentationData {
completion(false)
let text: String
switch microphoneSubject {
case .audio:
text = presentationData.strings.AccessDenied_VoiceMicrophone
case .video:
text = presentationData.strings.AccessDenied_VideoMicrophone
case .voiceCall:
text = presentationData.strings.AccessDenied_CallMicrophone
}
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.AccessDenied_Title, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
if case .voiceCall = microphoneSubject {
displayNotificationFromBackground(text)
}
}
}
})
}
case let .mediaLibrary(mediaLibrarySubject):
let continueWithValue: (Bool) -> Void = { value in
Queue.mainQueue().async {
if value {
completion(true)
} else if let presentationData = presentationData {
completion(false)
let text: String
switch mediaLibrarySubject {
case .send:
text = presentationData.strings.AccessDenied_PhotosAndVideos
case .save:
text = presentationData.strings.AccessDenied_SaveMedia
case .wallpaper:
text = presentationData.strings.AccessDenied_Wallpapers
}
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.AccessDenied_Title, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
}
}
}
if let value = cachedMediaLibraryAccessStatus.with({ $0 }) {
continueWithValue(value)
} else {
PHPhotoLibrary.requestAuthorization({ status in
let value: Bool
switch status {
case .restricted, .denied, .notDetermined:
value = false
case .authorized:
value = true
@unknown default:
fatalError()
}
let _ = cachedMediaLibraryAccessStatus.swap(value)
continueWithValue(value)
})
}
case let .location(locationSubject):
let status = CLLocationManager.authorizationStatus()
switch status {
case .authorizedAlways:
completion(true)
case .authorizedWhenInUse:
switch locationSubject {
case .send, .tracking:
completion(true)
case .live:
completion(false)
if let presentationData = presentationData {
let text = presentationData.strings.AccessDenied_LocationAlwaysDenied
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.AccessDenied_Title, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
}
}
case .denied, .restricted:
completion(false)
if let presentationData = presentationData {
let text: String
if status == .denied {
switch locationSubject {
case .send, .live:
text = presentationData.strings.AccessDenied_LocationDenied
case .tracking:
text = presentationData.strings.AccessDenied_LocationTracking
}
} else {
text = presentationData.strings.AccessDenied_LocationDisabled
}
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.AccessDenied_Title, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
}
case .notDetermined:
switch locationSubject {
case .send, .tracking:
locationManager?.requestWhenInUseAuthorization(completion: { status in
completion(status == .authorizedWhenInUse || status == .authorizedAlways)
})
case .live:
locationManager?.requestAlwaysAuthorization(completion: { status in
completion(status == .authorizedAlways)
})
default:
break
}
@unknown default:
fatalError()
}
case .contacts:
let _ = (self.contactsPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { value in
if let value = value {
completion(value)
} else {
if #available(iOSApplicationExtension 9.0, iOS 9.0, *) {
switch CNContactStore.authorizationStatus(for: .contacts) {
case .notDetermined:
let store = CNContactStore()
store.requestAccess(for: .contacts, completionHandler: { authorized, _ in
self.contactsPromise.set(.single(authorized))
completion(authorized)
})
case .authorized:
self.contactsPromise.set(.single(true))
completion(true)
default:
self.contactsPromise.set(.single(false))
completion(false)
}
} else {
switch ABAddressBookGetAuthorizationStatus() {
case .notDetermined:
var error: Unmanaged<CFError>?
let addressBook = ABAddressBookCreateWithOptions(nil, &error)
if let addressBook = addressBook?.takeUnretainedValue() {
ABAddressBookRequestAccessWithCompletion(addressBook, { authorized, _ in
Queue.mainQueue().async {
self.contactsPromise.set(.single(authorized))
completion(authorized)
}
})
} else {
self.contactsPromise.set(.single(false))
completion(false)
}
case .authorized:
self.contactsPromise.set(.single(true))
completion(true)
default:
self.contactsPromise.set(.single(false))
completion(false)
}
}
}
})
case .notifications:
if let registerForNotifications = registerForNotifications {
registerForNotifications { result in
self.notificationsPromise.set(.single(result))
completion(result)
}
}
case .siri:
if let requestSiriAuthorization = requestSiriAuthorization {
requestSiriAuthorization { result in
self.siriPromise.set(.single(result))
completion(result)
}
}
case .cellularData:
if let presentationData = presentationData {
present(standardTextAlertController(theme: AlertControllerTheme(presentationData: presentationData), title: presentationData.strings.Permissions_CellularDataTitle_v0, text: presentationData.strings.Permissions_CellularDataText_v0, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_NotNow, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.AccessDenied_Settings, action: {
openSettings()
})]), nil)
}
}
}
}
| 53.717213 | 531 | 0.455406 |
6999866f9a3ab60edc83294f128c97c796e7fbb1 | 1,041 | //
// ArticalsDetailsVC.swift
// NY TimesMostPopularArticles
//
// Created by SaFaa Mohamed on 04/03/2022.
//
import UIKit
class ArticalsDetailsVC: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var abstractLabel: UILabel!
lazy var viewModel : ArticlesDetailsVM = {
return ArticlesDetailsVM()
}()
var articleModel: ArticleModel!
override func viewDidLoad() {
super.viewDidLoad()
imageView.load(withImageUrl: articleModel.imageUrlString)
titleLabel.text = articleModel.title
abstractLabel.text = articleModel.abstract
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 26.025 | 106 | 0.680115 |
bf85deb5699ae3a2be6bdaaaccbb783fc3dbe4a4 | 1,135 | //
// OrderCollectionViewCell.swift
// Label
//
// Created by Anthony Gordon on 18/11/2016.
// Copyright © 2016 Anthony Gordon. All rights reserved.
//
// 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.
import UIKit
class OrderCollectionViewCell: UICollectionViewCell {
// MARK: IB
@IBOutlet weak var lblProdTitle: UILabel!
@IBOutlet weak var lblProdStyle: UILabel!
@IBOutlet weak var lblProdPrice: UILabel!
@IBOutlet weak var lblProdQuantity: UILabel!
@IBOutlet weak var lblOrderRef: UILabel!
@IBOutlet weak var lblOrderDate: UILabel!
@IBOutlet weak var lblOrderTotal: UILabel!
@IBOutlet weak var lblBillingName: UILabel!
@IBOutlet weak var lblBillingAddress: UILabel!
@IBOutlet weak var viewContainer: UIView!
@IBOutlet weak var viewContainerHeader: UIView!
@IBOutlet weak var viewContainerFooter: UIView!
@IBOutlet weak var btnRemoveProd: UIButton!
@IBOutlet weak var lblSubtotal: UILabel!
}
| 34.393939 | 76 | 0.740088 |
26c5e70f9410a201ef9680c0db88a0591f79087e | 230 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class c : T {
var e: j { func j>() {
if true {
class
case c,
| 23 | 87 | 0.713043 |
08c73a421e8bfe78d8eb3a49b9a25da0d44fde70 | 762 | //
// showFollowersViewController.swift
// Recipe-CICCC
//
// Created by 北島 志帆美 on 2020-02-21.
// Copyright © 2020 Argus Chen. All rights reserved.
//
import UIKit
class showFollowingViewController: UIViewController {
// @IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 23.090909 | 106 | 0.665354 |
e489ed25d392a29e4e4a8a24e7c9997c8cc0bd36 | 2,980 | //
// AppDelegate.swift
// PushNotificationManagerExample-Swift
//
// Created by BANYAN on 2017/10/25.
// Copyright © 2017年 GREENBANYAN. All rights reserved.
//
import UIKit
import UserNotificationsUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
let types = UNAuthorizationOptions([.alert,.badge,.sound])
notificationCenter.requestAuthorization(options: types, completionHandler: { (flag, error) in
if flag {
print("注册成功")
} else {
print("注册失败:\(error.debugDescription)")
}
})
} else {
let setting = UIUserNotificationSettings.init(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(setting)
}
UIApplication.shared.registerForRemoteNotifications()
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:.
}
}
| 45.846154 | 285 | 0.711409 |
1a80273834c06fc585aa0a90d73a8367ef33ecf3 | 3,941 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
/// Error enum for PinpointEmail
public enum PinpointEmailErrorType: AWSErrorType {
case accountSuspendedException(message: String?)
case alreadyExistsException(message: String?)
case badRequestException(message: String?)
case concurrentModificationException(message: String?)
case limitExceededException(message: String?)
case mailFromDomainNotVerifiedException(message: String?)
case messageRejected(message: String?)
case notFoundException(message: String?)
case sendingPausedException(message: String?)
case tooManyRequestsException(message: String?)
}
extension PinpointEmailErrorType {
public init?(errorCode: String, message: String?) {
var errorCode = errorCode
if let index = errorCode.firstIndex(of: "#") {
errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...])
}
switch errorCode {
case "AccountSuspendedException":
self = .accountSuspendedException(message: message)
case "AlreadyExistsException":
self = .alreadyExistsException(message: message)
case "BadRequestException":
self = .badRequestException(message: message)
case "ConcurrentModificationException":
self = .concurrentModificationException(message: message)
case "LimitExceededException":
self = .limitExceededException(message: message)
case "MailFromDomainNotVerifiedException":
self = .mailFromDomainNotVerifiedException(message: message)
case "MessageRejected":
self = .messageRejected(message: message)
case "NotFoundException":
self = .notFoundException(message: message)
case "SendingPausedException":
self = .sendingPausedException(message: message)
case "TooManyRequestsException":
self = .tooManyRequestsException(message: message)
default:
return nil
}
}
}
extension PinpointEmailErrorType: CustomStringConvertible {
public var description: String {
switch self {
case .accountSuspendedException(let message):
return "AccountSuspendedException: \(message ?? "")"
case .alreadyExistsException(let message):
return "AlreadyExistsException: \(message ?? "")"
case .badRequestException(let message):
return "BadRequestException: \(message ?? "")"
case .concurrentModificationException(let message):
return "ConcurrentModificationException: \(message ?? "")"
case .limitExceededException(let message):
return "LimitExceededException: \(message ?? "")"
case .mailFromDomainNotVerifiedException(let message):
return "MailFromDomainNotVerifiedException: \(message ?? "")"
case .messageRejected(let message):
return "MessageRejected: \(message ?? "")"
case .notFoundException(let message):
return "NotFoundException: \(message ?? "")"
case .sendingPausedException(let message):
return "SendingPausedException: \(message ?? "")"
case .tooManyRequestsException(let message):
return "TooManyRequestsException: \(message ?? "")"
}
}
}
| 42.836957 | 156 | 0.652372 |
7280cff7c5471e61956ebea6c5cd07377a4b160e | 1,284 | //
// UTicketTCell.swift
// U17
//
// Created by dongjiawang on 2021/12/20.
//
import UIKit
class UTicketTCell: UBaseTableViewCell {
var model: DetailRealtimeModel? {
didSet {
guard let model = model else {
return
}
let text = NSMutableAttributedString(string: "本月月票 | 累计月票 ",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)])
text.append(NSAttributedString(string: "\(model.comic?.total_ticket ?? "")",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]))
text.insert(NSAttributedString(string: "\(model.comic?.monthly_ticket ?? "")",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]),
at: 6)
textLabel?.attributedText = text
textLabel?.textAlignment = .center
}
}
}
| 38.909091 | 122 | 0.546729 |
211156e229be2c78c5be6e755950e5bcd876f303 | 1,639 | //
// AppDelegate.swift
// ContactsApp
//
// Created by Fereizqo Sulaiman on 06/02/20.
// Copyright © 2020 Fereizqo Sulaiman. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Remove nav bar shadow and background
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 38.116279 | 179 | 0.735815 |
e9ee696cb0766e6443fc90662f16ec382347fd2b | 399 | import UIKit
var appCoordinator: AppCoordinator!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
appCoordinator = AppCoordinator(dataSource: DataSource(), appNavigator: AppNavigator())
return true
}
}
| 28.5 | 146 | 0.769424 |
dbbc28d9a96f1e09c538a614a5ac632313eda01d | 2,895 | /// Copyright (c) 2019 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 RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet private var searchCityName: UITextField!
@IBOutlet private var tempLabel: UILabel!
@IBOutlet private var humidityLabel: UILabel!
@IBOutlet private var iconLabel: UILabel!
@IBOutlet private var cityNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
style()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
Appearance.applyBottomLine(to: searchCityName)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Style
private func style() {
view.backgroundColor = UIColor.aztec
searchCityName.textColor = UIColor.ufoGreen
tempLabel.textColor = UIColor.cream
humidityLabel.textColor = UIColor.cream
iconLabel.textColor = UIColor.cream
cityNameLabel.textColor = UIColor.cream
}
}
| 37.597403 | 83 | 0.751295 |
29178a9c3fa70b47d3ef368a7234ffa12da05f47 | 11,284 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CareKitStore
import CareKitUI
import Combine
import Contacts
import ContactsUI
import MapKit
import MessageUI
import UIKit
/// A superclass to all view controllers that are synchronized with a contact. Actions in the view sent through the
/// `OCKContactViewDelegate` protocol will be automatically hooked up to controller logic.
///
/// Alternatively, subclass and use your custom view by specializing the `View` generic and overriding the `makeView()` method. Override the
/// `updateView(view:context)` method to hook up the contact to the view. This method will be called any time the contact is added, updated, or
/// deleted.
open class OCKContactViewController<View: UIView & OCKContactDisplayable, Store: OCKStoreProtocol>:
OCKSynchronizedViewController<View, Store.Contact>,
OCKContactDisplayer, OCKContactViewDelegate, MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate {
/// An `Error` subclass detailing errors specific to a contact.
private enum ContactError: Error, LocalizedError {
case invalidAddress
/// `number` is the invalid phone number in context.
case invalidPhoneNumber(number: String)
case cannotSendMessage
case cannotSendMail
var errorDescription: String? {
switch self {
case .invalidAddress: return "Invalid address"
case .invalidPhoneNumber(let number): return "Invalid number: \(number)"
case .cannotSendMessage: return "Unable to compose a message"
case .cannotSendMail: return "Unable to compose an email"
}
}
}
// MARK: - Properties
/// The view displayed by this view controller.
public var contactView: UIView & OCKContactDisplayable { synchronizedView }
/// The store manager used to provide synchronization.
public let storeManager: OCKSynchronizedStoreManager<Store>
/// If set, the delegate will receive callbacks when important events happen.
public weak var delegate: OCKContactViewControllerDelegate?
private let query: OCKContactQuery?
private let contactIdentifier: String
// MARK: - Initializers
/// Create a view controller with a contact to display.
/// - Parameter storeManager: A store manager that will be used to provide synchronization.
/// - Parameter contact: Contact to use as the view model.
public init(storeManager: OCKSynchronizedStoreManager<Store>, contact: Store.Contact) {
self.storeManager = storeManager
query = nil
contactIdentifier = contact.identifier
super.init()
setViewModel(contact, animated: false)
}
/// Create a view controller by querying for a contact to display.
/// - Parameter storeManager: A store manager that will be used to provide synchronization.
/// - Parameter contactIdentifier: The identifier of the contact for which to query.
/// - Parameter query: The query used to find the contact.
public init(storeManager: OCKSynchronizedStoreManager<Store>, contactIdentifier: String, query: OCKContactQuery?) {
self.storeManager = storeManager
self.contactIdentifier = contactIdentifier
self.query = query
super.init()
}
// MARK: - Life cycle
override open func viewDidLoad() {
super.viewDidLoad()
contactView.delegate = self
if viewModel == nil {
fetchContact(withIdentifier: contactIdentifier, query: query)
}
}
// MARK: - Methods
private func fetchContact(withIdentifier id: String, query: OCKContactQuery?) {
let anchor = OCKContactAnchor.contactIdentifier([id])
storeManager.store.fetchContacts(anchor, query: query, queue: .main) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let contacts):
self.setViewModel(contacts.first, animated: self.viewModel != nil)
self.subscribe()
self.delegate?.contactViewController(self, didFinishQuerying: self.viewModel)
case .failure(let error):
self.delegate?.contactViewController(self, didFailWithError: error)
}
}
}
/// Subscribe to update and delete notifications for the contact.
override open func makeSubscription() -> AnyCancellable? {
guard let contact = viewModel else { return nil }
let changedSubscription = storeManager.publisher(forContact: contact, categories: [.update]).sink { [weak self] updatedContact in
guard let self = self else { return }
self.setViewModel(updatedContact, animated: self.viewModel != nil)
}
let deletedSubscription = storeManager.publisher(forContact: contact, categories: [.delete], fetchImmediately: false)
.sink { [weak self] _ in
guard let self = self else { return }
self.setViewModel(nil, animated: self.viewModel != nil)
}
return AnyCancellable {
changedSubscription.cancel()
deletedSubscription.cancel()
}
}
// MARK: - OCKContactViewDelegate
/// Present an alert to call the contact. By default, calls the first phone number in the contact's list of phone numbers.
/// - Parameter contactView: The view that displays the contact.
/// - Parameter sender: The sender that is initiating the call process.
open func contactView(_ contactView: UIView & OCKContactDisplayable, senderDidInitiateCall sender: Any?) {
guard let phoneNumber = viewModel?.convert().phoneNumbers?.first?.value else { return }
let filteredNumber = phoneNumber.filter("0123456789".contains) // remove non-numeric characters to provide to calling API
guard let url = URL(string: "tel://" + filteredNumber) else {
delegate?.contactViewController(self, didFailWithError: ContactError.invalidPhoneNumber(number: phoneNumber))
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
/// Present the UI to message the contact. By default, the first messaging number will be used.
/// - Parameter contactView: The view that displays the contact.
/// - Parameter sender: The sender that is initiating the messaging process.
open func contactView(_ contactView: UIView & OCKContactDisplayable, senderDidInitiateMessage sender: Any?) {
guard let messagesNumber = viewModel?.convert().messagingNumbers?.first?.value else { return }
guard MFMessageComposeViewController.canSendText() else {
self.delegate?.contactViewController(self, didFailWithError: ContactError.cannotSendMessage)
return
}
let filteredNumber = messagesNumber.filter("0123456789".contains) // remove non-numeric characters to provide to message API
let composeViewController = MFMessageComposeViewController()
composeViewController.messageComposeDelegate = self
composeViewController.recipients = [filteredNumber]
self.present(composeViewController, animated: true, completion: nil)
}
/// Present the UI to email the contact. By default, the first email address will be used.
/// - Parameter contactView: The view that displays the contact.
/// - Parameter sender: The sender that is initiating the email process.
open func contactView(_ contactView: UIView & OCKContactDisplayable, senderDidInitiateEmail sender: Any?) {
guard let firstEmail = viewModel?.convert().emailAddresses?.first?.value else { return }
guard MFMailComposeViewController.canSendMail() else {
self.delegate?.contactViewController(self, didFailWithError: ContactError.cannotSendMail)
return
}
let mailViewController = MFMailComposeViewController()
mailViewController.mailComposeDelegate = self
mailViewController.setToRecipients([firstEmail])
self.present(mailViewController, animated: true, completion: nil)
}
/// Present a map with a marker on the contact's address.
/// - Parameter contactView: The view that displays the contact.
/// - Parameter sender: The sender that is initiating the address lookup process.
open func contactView(_ contactView: UIView & OCKContactDisplayable, senderDidInitiateAddressLookup sender: Any?) {
guard let address = viewModel?.convert().address else { return }
let geoloc = CLGeocoder()
geoloc.geocodePostalAddress(address) { [weak self] placemarks, _ in
guard let self = self else { return }
guard let placemark = placemarks?.first else {
self.delegate?.contactViewController(self, didFailWithError: ContactError.invalidAddress)
return
}
let mkPlacemark = MKPlacemark(placemark: placemark)
let mapItem = MKMapItem(placemark: mkPlacemark)
mapItem.openInMaps(launchOptions: nil)
}
}
open func didSelectContactView(_ contactView: UIView & OCKContactDisplayable) { }
// MARK: - MFMessageComposeViewControllerDelegate
open func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: nil)
}
// MARK: - MFMailComposeViewControllerDelegate
open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
| 48.222222 | 143 | 0.712425 |
fc7fba7a7035d9fe371169ed7ea503da90c62565 | 602 | //
// GetPokemonDetail.swift
// ios-base-architecture
//
// Created by Felipe Silva Lima on 11/26/20.
//
import Foundation
protocol IGetPokemonDetail {
func getPokemonDetail(name: String, _ completion: @escaping (PokemonEntity) -> Void, _ failure: @escaping (ServerError) -> Void)
}
struct GetPokemonDetailImpl: IGetPokemonDetail {
let repository: IPokemonDetailRepository
func getPokemonDetail(name: String, _ completion: @escaping (PokemonEntity) -> Void, _ failure: @escaping (ServerError) -> Void) {
repository.getPokemonDetail(name: name, completion, failure)
}
}
| 26.173913 | 134 | 0.727575 |
ed548f91174b3bcfa97b8406711f5a117f33608e | 1,095 | import XCTest
@testable import FramesIos
class DetailsInputViewTests: XCTestCase {
var detailsInputView = DetailsInputView()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
detailsInputView = DetailsInputView()
}
func testEmptyInitialization() {
_ = DetailsInputView()
}
func testCoderInitialization() {
let coder = NSKeyedUnarchiver(forReadingWith: Data())
_ = DetailsInputView(coder: coder)
}
func testFrameInitialization() {
_ = DetailsInputView(frame: CGRect(x: 0, y: 0, width: 400, height: 48))
}
func testSetText() {
detailsInputView.text = "Text"
XCTAssertEqual(detailsInputView.label.text, "Text")
}
func testSetLabelAndBackgroundColor() {
detailsInputView.set(label: "addressLine1", backgroundColor: .white)
XCTAssertEqual(detailsInputView.label.text, "Address line 1*")
XCTAssertEqual(detailsInputView.backgroundColor, UIColor.white)
}
}
| 29.594595 | 109 | 0.675799 |
d6c1074e0736139ddd1972abe6abd1dcaefd680e | 5,805 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// Extend a protocol with a property.
extension Sequence {
final var myCount: Int {
var result = 0
for _ in self {
result += 1
}
return result
}
}
// CHECK: 4
print(["a", "b", "c", "d"].myCount)
// Extend a protocol with a function.
extension Collection {
final var myIndices: Range<Index> {
return startIndex..<endIndex
}
func clone() -> Self {
return self
}
}
// CHECK: 4
print(["a", "b", "c", "d"].clone().myCount)
extension Collection {
final func indexMatching(fn: Iterator.Element -> Bool) -> Index? {
for i in myIndices {
if fn(self[i]) { return i }
}
return nil
}
}
// CHECK: 2
print(["a", "b", "c", "d"].indexMatching({$0 == "c"})!)
// Extend certain instances of a collection (those that have equatable
// element types) with another algorithm.
extension Collection where Self.Iterator.Element : Equatable {
final func myIndexOf(element: Iterator.Element) -> Index? {
for i in self.indices {
if self[i] == element { return i }
}
return nil
}
}
// CHECK: 3
print(["a", "b", "c", "d", "e"].myIndexOf("d")!)
extension Sequence {
final public func myEnumerated() -> EnumeratedSequence<Self> {
return self.enumerated()
}
}
// CHECK: (0, a)
// CHECK-NEXT: (1, b)
// CHECK-NEXT: (2, c)
for (index, element) in ["a", "b", "c"].myEnumerated() {
print("(\(index), \(element))")
}
extension Sequence {
final public func myReduce<T>(
initial: T, @noescape combine: (T, Self.Iterator.Element) -> T
) -> T {
var result = initial
for value in self {
result = combine(result, value)
}
return result
}
}
// CHECK: 15
print([1, 2, 3, 4, 5].myReduce(0, combine: +))
extension Sequence {
final public func myZip<S : Sequence>(s: S) -> Zip2Sequence<Self, S> {
return Zip2Sequence(_sequence1: self, _sequence2: s)
}
}
// CHECK: (1, a)
// CHECK-NEXT: (2, b)
// CHECK-NEXT: (3, c)
for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) {
print("(\(a), \(b))")
}
// Mutating algorithms.
extension MutableCollection
where Self.Index: RandomAccessIndex, Self.Iterator.Element : Comparable {
public final mutating func myPartition() -> Index {
return self.partition()
}
}
// CHECK: 4 3 1 2 | 5 9 8 6 7 6
var evenOdd = [5, 3, 6, 2, 4, 9, 8, 1, 7, 6]
var evenOddSplit = evenOdd.myPartition()
for i in evenOdd.myIndices {
if i == evenOddSplit { print(" |", terminator: "") }
if i > 0 { print(" ", terminator: "") }
print(evenOdd[i], terminator: "")
}
print("")
extension RangeReplaceableCollection {
public final func myJoin<S : Sequence where S.Iterator.Element == Self>(
elements: S
) -> Self {
var result = Self()
var iter = elements.makeIterator()
if let first = iter.next() {
result.append(contentsOf: first)
while let next = iter.next() {
result.append(contentsOf: self)
result.append(contentsOf: next)
}
}
return result
}
}
// CHECK: a,b,c
print(
String(
",".characters.myJoin(["a".characters, "b".characters, "c".characters])
)
)
// Constrained extensions for specific types.
extension Collection where Self.Iterator.Element == String {
final var myCommaSeparatedList: String {
if startIndex == endIndex { return "" }
var result = ""
var first = true
for x in self {
if first { first = false }
else { result += ", " }
result += x
}
return result
}
}
// CHECK: x, y, z
print(["x", "y", "z"].myCommaSeparatedList)
// CHECK: {{[tuv], [tuv], [tuv]}}
print((["t", "u", "v"] as Set).myCommaSeparatedList)
// Existentials
protocol ExistP1 {
func existP1()
}
extension ExistP1 {
final func runExistP1() {
print("runExistP1")
self.existP1()
}
}
struct ExistP1_Struct : ExistP1 {
func existP1() {
print(" - ExistP1_Struct")
}
}
class ExistP1_Class : ExistP1 {
func existP1() {
print(" - ExistP1_Class")
}
}
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Struct
var existP1: ExistP1 = ExistP1_Struct()
existP1.runExistP1()
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Class
existP1 = ExistP1_Class()
existP1.runExistP1()
protocol P {
mutating func setValue(b: Bool)
func getValue() -> Bool
}
extension P {
final var extValue: Bool {
get { return getValue() }
set(newValue) { setValue(newValue) }
}
}
extension Bool : P {
mutating func setValue(b: Bool) { self = b }
func getValue() -> Bool { return self }
}
class C : P {
var theValue: Bool = false
func setValue(b: Bool) { theValue = b }
func getValue() -> Bool { return theValue }
}
func toggle(value: inout Bool) {
value = !value
}
var p: P = true
// CHECK: Bool
print("Bool")
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// CHECK: C
print("C")
p = C()
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// Logical lvalues of existential type.
struct HasP {
var _p: P
var p: P {
get { return _p }
set { _p = newValue }
}
}
var hasP = HasP(_p: false)
// CHECK: true
hasP.p.extValue = true
print(hasP.p.extValue)
// CHECK: false
toggle(&hasP.p.extValue)
print(hasP.p.extValue)
// rdar://problem/20739719
class Super: Init {
required init(x: Int) { print("\(x) \(self.dynamicType)") }
}
class Sub: Super {}
protocol Init { init(x: Int) }
extension Init { init() { self.init(x: 17) } }
// CHECK: 17 Super
_ = Super()
// CHECK: 17 Sub
_ = Sub()
// CHECK: 17 Super
var sup: Super.Type = Super.self
_ = sup.init()
// CHECK: 17 Sub
sup = Sub.self
_ = sup.init()
// CHECK: DONE
print("DONE")
| 19.095395 | 75 | 0.619121 |
260e92a26b6106b61b4c4888a8e85e0cc1169aea | 1,964 | import PackageDescription
let package = Package(
name: "Vapor",
targets: [
// Framework
Target(name: "Vapor", dependencies: [
"Auth",
"Cache",
"Cookies",
"Sessions",
"Settings"
]),
// Misc
Target(name: "Auth", dependencies: ["Cookies", "Cache"]),
Target(name: "Cache"),
Target(name: "Cookies"),
Target(name: "Sessions", dependencies: ["Cookies"]),
Target(name: "Settings"),
// Development and Testing
// Target(name: "Development", dependencies: ["Vapor"]),
// Target(name: "Performance", dependencies: ["Vapor"]),
],
dependencies: [
// SHA2 + HMAC hashing. Used by the core to create session identifiers.
.Package(url: "https://github.com/vapor/crypto.git", majorVersion: 1),
// ORM for interacting with databases
.Package(url: "https://github.com/vapor/fluent.git", majorVersion: 1),
// Core vapor transport layer
.Package(url: "https://github.com/vapor/engine.git", majorVersion: 1),
// Console protocol and implementation for powering command line interface.
.Package(url: "https://github.com/vapor/console.git", majorVersion: 1),
// JSON enum wrapper around Foundation JSON
.Package(url: "https://github.com/vapor/json.git", majorVersion: 1),
// A security framework for Swift.
.Package(url: "https://github.com/stormpath/Turnstile.git", majorVersion: 1),
// An extensible templating language built for Vapor. 🍃
.Package(url: "https://github.com/vapor/leaf.git", majorVersion: 1),
// A type safe routing package including HTTP and TypeSafe routers.
.Package(url: "https://github.com/vapor/routing.git", majorVersion: 1),
],
exclude: [
"Sources/Development",
"Sources/Performance",
"Sources/TypeSafeGenerator"
]
)
| 34.45614 | 85 | 0.596232 |
d53d8b59fc7a9b00e17fedaace98a814bc706f99 | 986 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// swiftlint:disable all
import Amplify
import Foundation
extension Todo {
// MARK: - CodingKeys
public enum CodingKeys: String, ModelKey {
case id
case name
case description
case categories
case section
case stickies
}
public static let keys = CodingKeys.self
// MARK: - ModelSchema
public static let schema = defineSchema { model in
let todo = Todo.keys
model.pluralName = "Todos"
model.fields(
.id(),
.field(todo.name, is: .required, ofType: .string),
.field(todo.description, is: .optional, ofType: .string),
.field(todo.categories, is: .optional, ofType: .embeddedCollection(of: Category.self)),
.field(todo.section, is: .optional, ofType: .embedded(type: Section.self)),
.field(todo.stickies, is: .optional, ofType: .embeddedCollection(of: String.self))
)
}
}
| 24.04878 | 93 | 0.6643 |
4a68fba878d80e638b7413fcc20b294d43c7442f | 2,654 | //
// StoriesController.swift
// Nimbus
//
// Created by Pirush Prechathavanich on 6/15/18.
// Copyright © 2018 Nimbl3. All rights reserved.
//
import Cocoa
import ReactiveSwift
final class StoriesController: MenuController {
private let manager: RequestManager
private var disposable: Disposable?
private let projectItem = NSMenuItem(title: "No project selected")
private let helpItem = NSMenuItem(title: "- Select a story and use CMD + SHIFT + C.")
private var storyItems: [NSMenuItem] = []
private(set) var stories: [Story] = [] {
didSet { update(with: stories) }
}
// MARK: - selected properties
private var selectedStoryItem: NSMenuItem? {
didSet { selectedStory = stories.first { $0.name == selectedStoryItem?.title } }
}
private(set) var selectedStory: Story? {
didSet {
guard let story = selectedStory else { return }
onSelectStory?(story)
}
}
var onUpdateStories: (([Story]) -> Void)?
var onSelectStory: ((Story) -> Void)?
init(with requestManager: RequestManager) {
manager = requestManager
}
// MARK: - menu controller
var items: [NSMenuItem] {
var items = [projectItem]
if !storyItems.isEmpty { items.append(helpItem) }
items.append(contentsOf: storyItems)
return items
}
func configure(with project: Project) {
projectItem.title = project.projectName
fetchStories(of: project)
}
private func fetchStories(of project: Project) {
let request = Requests.PivotalTracker.stories(ofProjectId: project.projectId,
withState: .started)
disposable?.dispose()
disposable = manager.perform(request)
.startWithResult { [weak self] result in
switch result {
case .success(let stories): self?.stories = stories
case .failure(let error): debugPrint(error)
}
}
}
private func update(with stories: [Story]) {
storyItems = stories.map {
let item = createItem(title: $0.name, action: #selector(selectStory))
item.representedObject = $0
if $0.id == selectedStory?.id { item.state = .on }
return item
}
onUpdateStories?(stories)
}
// MARK: - action
@objc private func selectStory(_ item: NSMenuItem) {
item.state = .on
selectedStoryItem?.state = .off
selectedStoryItem = item
}
}
| 28.847826 | 89 | 0.58214 |
9c97ffba95ff6481a77528e117f8c2ba06ee9b21 | 1,356 | import Foundation
struct Grid {
private(set) var items: [[Cell]]
init(size: Int) {
items = .init(repeating: .init(repeating: .dead(), count: size), count: size)
}
func contact(_ at: Point) -> [Automaton] {
(at.x - 1 ... at.x + 1).flatMap { x in
(at.y - 1 ... at.y + 1).reduce(into: []) {
$0.append(Point(x, $1))
}
}.filter { $0 != at }.reduce(into: []) {
guard $1.x >= 0 && $1.x < items.count && $1.y >= 0 && $1.y < items.count, let automaton = self[$1].automaton else { return }
$0.append(automaton)
}
}
func percent(_ of: Automaton) -> Double {
.init(items.map { $0.filter { $0.automaton == of }.count }.reduce(0, +)) / .init(items.count * items.count)
}
func oldest(_ of: Automaton) -> Int {
items.flatMap { $0.filter { $0.automaton == of }.map(\.age) }.max() ?? 0
}
var random: Point {
var point: Point
repeat {
point = .init(.random(in: 0 ..< items.count), .random(in: 0 ..< items.count))
} while self[point].automaton != nil
return point
}
subscript(_ point: Point) -> Cell {
get {
items[point.x][point.y]
}
set {
items[point.x][point.y] = newValue
}
}
}
| 29.478261 | 136 | 0.477139 |
c12bda4a7065e09c193708e2552bc1e0cdb2e2fd | 543 | //
// Data+Pressure.swift
// DataKit
//
// Created by Eric Lewis on 6/21/19.
// Copyright © 2019 Eric Lewis, Inc. All rights reserved.
//
import Foundation
public struct Pressure : MeasurementCategory {
public var title = "Pressure"
public var description = ""
public var icon: String? = "rectangle.compress.vertical"
public var measurements: [MeasurementData] = [
MeasurementData(title: "bars", unit: UnitPressure.bars),
MeasurementData(title: "gigapascals", unit: UnitPressure.gigapascals),
]
public init() {}
}
| 24.681818 | 74 | 0.699816 |
ffd8410bd753fe24f4c70aa64f0128aa72856bef | 1,324 | import SwiftUI
struct WeatherItems: View {
let rain: Double?
let snow: Double?
let windSpeed : Double
let pressure: Int
let humidity: Int
let uvi: Double
let dewPoint: Double
let visibility: Double?
var body: some View {
VStack(alignment: .leading) {
HStack(spacing: 20) {
if let rain = rain {
Label(rain.toString(maximumFractionDigits: 2) + "mm", systemImage: "cloud.rain")
}
if let snow = snow {
Label(snow.toString(maximumFractionDigits: 2) + "mm", systemImage: "cloud.snow")
}
Label(windSpeed.toString(maximumFractionDigits: 1) + "m/s", systemImage: "wind")
Label("\(pressure)hPa", systemImage: "barometer")
}
HStack(spacing: 20) {
Text("Humidity: \(humidity)%")
Text("UV: \(uvi.toString)")
}
HStack(spacing: 20) {
Text("Dew point: \(dewPoint.celsius)")
if let visibility = visibility {
Text("Visibility: \((visibility / 1000).toString(maximumFractionDigits: 1))km")
}
}
}
}
}
| 30.790698 | 100 | 0.476586 |
ef8a966ade80115ef5c0a7f3f8b032bcb33afe68 | 20,556 | //
// MZCardCell.swift
// Muzzley-iOS
//
// Created by Ana Figueira on 11/10/2018.
// Copyright © 2018 Muzzley. All rights reserved.
//
import UIKit
@objc protocol MZCardCellDelegate: NSObjectProtocol {
func removeCard(_ card : MZCardViewModel)
func showPullToRefresh()
func showCardInfo(cardVM: MZCardViewModel, action: MZActionViewModel, stage: MZStageViewModel)
func exitCardInfo()
func cardContentDidChange(indexPath : IndexPath)
}
class MZCardCell: UITableViewCell,
UITableViewDelegate,
UITableViewDataSource,
MZCardTitleViewDelegate,
MZCardActionsDelegate,
MZCardLocationPickerDelegate,
MZCardDevicesPickerDelegate,
MZCardDatePickerDelegate,
MZCardAdsScrollDelegate,
MZCardAdCellDelegate,
MZCardLocationPickerViewControllerDelegate,
MZAddDevicePopupViewControllerDelegate
{
// This sets the order in which the card fields should appear.
let CARD_IMAGE_INDEX = 0
let CARD_TITLE_INDEX = 1
let CARD_TEXT_INDEX = 2
let CARD_FIELDS_INDEX = 3
let CARD_ACTIONS_INDEX = 4
// Time that the action feedback should stay visible (success/error)
let DELAY_FEEDBACK = 2
@IBOutlet weak var uiBackgroundView: UIView!
// UI Outlets
@IBOutlet weak var uiOverlayView: UIView!
@IBOutlet weak var uiCardStackView: UIStackView!
// Class variables
var card : MZCardViewModel?
var indexPath : IndexPath?
var currentStageIndex : Int = 0
var delegate : MZCardCellDelegate?
var parentViewController : UIViewController?
var cardsInteractor : MZCardsInteractor?
var cellsOrder: Array<Int> = []
// Tableview that displays the menu with the card options on ...
var tableViewPopup = UITableView()
var tableViewPopupItems : Array<String> = []
var isFirstRender = true
func setCardViewModel(viewModel : MZCardViewModel, parentViewController: UIViewController, indexPath : IndexPath)
{
self.card = viewModel
self.parentViewController = parentViewController
self.indexPath = indexPath
self.cardsInteractor = MZCardsInteractor()
self.isFirstRender = true
updateCard()
}
/// Returns an array with the order in which the fields of the card should be displayed
func getFieldsOrder(card: MZCardViewModel, stage: MZStageViewModel) -> [Int]
{
var arrayOrder = [Int]()
if stage.imageUrl != nil
{
arrayOrder.append(self.CARD_IMAGE_INDEX)
}
if (stage.title != nil && !stage.title!.isEmpty) || (card.title != nil && !card.title!.isEmpty) || !card.feedback.isEmpty
{
arrayOrder.append(self.CARD_TITLE_INDEX)
}
if stage.text != nil && !stage.text.content.isEmpty
{
arrayOrder.append(self.CARD_TEXT_INDEX)
}
if stage.fields != nil && stage.fields.count > 0
{
for i in 0...stage.unfoldedFieldsIndex
{
arrayOrder.append(self.CARD_FIELDS_INDEX)
}
}
if stage.actions != nil && stage.actions.count > 0
{
arrayOrder.append(self.CARD_ACTIONS_INDEX)
}
return arrayOrder
}
// Updates the card according the viewmodel state
func updateCard()
{
for item in self.uiCardStackView.arrangedSubviews
{
self.uiCardStackView.removeArrangedSubview(item)
item.removeFromSuperview()
}
self.contentView.backgroundColor = UIColor.muzzleyDarkWhiteColor(withAlpha: 1)
self.currentStageIndex = self.card!.unfoldedStagesIndex
let cellsOrder = getFieldsOrder(card: card!, stage: card!.stages[currentStageIndex])
let firstFieldIndex = cellsOrder.index(of: self.CARD_FIELDS_INDEX)
for index in 0...cellsOrder.count-1
{
switch cellsOrder[index]
{
case self.CARD_IMAGE_INDEX:
if card!.stages[currentStageIndex].imageUrl != nil
{
let cardImageView = MZCardImageView()
cardImageView.setCardViewModel(card!)
self.parentViewController!.addChildViewController(cardImageView)
self.uiCardStackView.addArrangedSubview(cardImageView.view)
}
break
case self.CARD_TITLE_INDEX:
let cardTitleView = MZCardTitleView()
cardTitleView.setCardViewModel(card!)
cardTitleView.delegate = self
self.parentViewController!.addChildViewController(cardTitleView)
self.uiCardStackView.addArrangedSubview(cardTitleView.view)
break
case self.CARD_TEXT_INDEX:
let cardTextView = MZCardTextView()
cardTextView.setCardViewModel(card!)
self.parentViewController!.addChildViewController(cardTextView)
self.uiCardStackView.addArrangedSubview(cardTextView.view)
break
case self.CARD_ACTIONS_INDEX:
let cardActionsView = MZCardActions()
cardActionsView.setCardViewModel(card!)
cardActionsView.delegate = self
self.parentViewController!.addChildViewController(cardActionsView)
self.uiCardStackView.addArrangedSubview(cardActionsView.view)
break
case self.CARD_FIELDS_INDEX:
let field = card!.stages[currentStageIndex].fields[index-firstFieldIndex!]
switch(field.type)
{
case MZFieldViewModel.key_location:
let picker = MZCardLocationPicker()
picker.setViewModel(card!, fieldViewModel: field)
picker.delegate = self
self.parentViewController!.addChildViewController(picker)
self.uiCardStackView.addArrangedSubview(picker.view)
break
case MZFieldViewModel.key_time:
let picker = MZCardDatePicker()
picker.setViewModel(card!, fieldViewModel: field)
picker.delegate = self
self.parentViewController!.addChildViewController(picker)
self.uiCardStackView.addArrangedSubview(picker.view)
break
case MZFieldViewModel.key_deviceChoice:
let picker = MZCardDevicesPicker()
picker.setViewModel(card!, fieldViewModel: field)
picker.delegate = self
self.parentViewController!.addChildViewController(picker)
self.uiCardStackView.addArrangedSubview(picker.view)
break
case MZFieldViewModel.key_text:
let picker = MZCardTextField()
picker.setViewModel(card!, fieldViewModel: field)
// picker.delegate = self
self.parentViewController!.addChildViewController(picker)
self.uiCardStackView.addArrangedSubview(picker.view)
break
case MZFieldViewModel.key_singleChoice,
MZFieldViewModel.key_multiChoice:
let picker = MZCardChoicePicker()
picker.setViewModel(card!, fieldViewModel: field)
// picker.delegate = self
self.parentViewController!.addChildViewController(picker)
self.uiCardStackView.addArrangedSubview(picker.view)
break
case MZFieldViewModel.key_adsList:
let picker = MZCardAdsScroll()
picker.setViewModel(card!, fieldViewModel: field, indexPath : self.indexPath!)
picker.delegate = self
self.parentViewController!.addChildViewController(picker)
self.uiCardStackView.addArrangedSubview(picker.view)
break
default:
break
}
break
default:
break
}
}
if !self.isFirstRender
{
self.delegate?.cardContentDidChange(indexPath: self.indexPath!)
}
self.isFirstRender = false
}
// UIStackView event for tapping an element. Commented here because we do not want selection to occur
override func setSelected(_ selected: Bool, animated: Bool)
{
// super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// Calls CardsViewController delegate to remove the card from the list
func hideCard()
{
self.delegate?.removeCard(card!)
}
//
func hideFeedback()
{
self.hideOverlay()
self.card!.state = MZCardViewModel.CardState.none
self.updateCard()
}
/// Overlay
func showOverlay()
{
self.uiOverlayView!.backgroundColor = UIColor.muzzleyBlackColor(withAlpha: 0.6)
self.uiOverlayView!.alpha = 0
self.uiOverlayView.isHidden = false
let tap = UITapGestureRecognizer(target: self, action: #selector(hideFeedback))
tap.delegate = self
self.uiOverlayView!.addGestureRecognizer(tap)
UIView.animate(withDuration: 0.3)
{
self.uiOverlayView!.alpha = 1
self.tableViewPopup.frame = CGRect(x: 0.0, y: CGFloat(self.uiCardStackView.frame.size.height) - 40 * CGFloat(self.tableViewPopupItems.count), width: self.uiCardStackView.frame.size.width, height: 40.0 * CGFloat(self.tableViewPopupItems.count))
}
}
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: self.tableViewPopup) == true {
return false
}
return true
}
func hideOverlay()
{
if self.tableViewPopup != nil
{
self.tableViewPopup.removeFromSuperview()
}
if self.uiOverlayView.alpha == 1
{
UIView.animate(withDuration: 0.3, animations: {
self.uiOverlayView.alpha = 0
}, completion: { (finished) in
self.uiOverlayView.isHidden = true
})
}
}
/// Card states
func showSuccess()
{
self.card!.state = MZCardViewModel.CardState.success
self.updateCard()
self.perform(#selector(hideCard), with: nil, afterDelay: TimeInterval(DELAY_FEEDBACK))
}
func showError()
{
self.card!.state = MZCardViewModel.CardState.error
self.updateCard()
self.perform(#selector(hideFeedback), with: nil, afterDelay: TimeInterval(DELAY_FEEDBACK))
// Hide feedback?
}
/// DELEGATES
// MZCardTitleViewDelegate
func feedbackButtonTappedWithCard(_ card: MZCardViewModel)
{
self.tableViewPopupItems = card.feedback
self.showOverlay()
let height : CGFloat = 40.0 * CGFloat(self.tableViewPopupItems.count)
self.tableViewPopup = UITableView(frame: CGRect(x: 0, y: 0, width: self.uiCardStackView.frame.width, height: height))
self.tableViewPopup.allowsSelection = true
self.tableViewPopup.allowsMultipleSelection = false
self.tableViewPopup.register(UITableViewCell, forCellReuseIdentifier: "Cell")
self.tableViewPopup.backgroundColor = UIColor.white
self.tableViewPopup.delegate = self
self.tableViewPopup.dataSource = self
let feedbackHeight = self.uiCardStackView.arrangedSubviews[0].frame.origin.y
self.tableViewPopup.frame = CGRect(x: 40, y: feedbackHeight + 30, width: self.uiCardStackView.frame.size.width - 48, height: height)
self.tableViewPopup.layer.masksToBounds = false
self.tableViewPopup.layer.shadowOffset = CGSize(width: 0, height: 0)
self.tableViewPopup.layer.shadowColor = UIColor.muzzleyGray2Color(withAlpha: 1).cgColor
self.tableViewPopup.layer.shadowOpacity = 0.4
self.tableViewPopup.layer.shadowRadius = 4
self.uiOverlayView.addSubview(self.tableViewPopup)
}
// MZCardActionsDelegate
func gotoStageTapped(_ card: MZCardViewModel, action: MZActionViewModel) {
var currentStage = card.stages[card.unfoldedStagesIndex]
currentStage.unfoldedFieldsIndex = 0
self.currentStageIndex = card.unfoldedStagesIndex
self.card!.unfoldedStagesIndex = action.args.nStage
self.updateCard()
}
func replyTapped(_ card: MZCardViewModel, action: MZActionViewModel) {
self.card!.state = MZCardViewModel.CardState.loading
self.showLoadingCard()
self.cardsInteractor?.sendActionCard(card, action: action, completion: { (error) in
if error == nil
{
self.showSuccess()
}
else
{
self.showError()
}
})
}
func showLoadingCard()
{
self.card?.state = MZCardViewModel.CardState.loading
self.updateCard()
}
func browseTapped(_ card: MZCardViewModel, action: MZActionViewModel, url: URL) {
UIApplication.shared.openURL(url)
}
func pubMQTT(_ card: MZCardViewModel, action: MZActionViewModel, topic: String, payload: NSDictionary) {
}
func doneTapped(_ card: MZCardViewModel, action: MZActionViewModel, stage: MZStageViewModel) {
// Show loading
self.cardsInteractor?.sendActionCard(card, action: action, stage: stage, completion: { (error) in
if(error == nil)
{
self.showSuccess()
}
else
{
self.showError()
MZAnalyticsInteractor.cardFinishEvent(card.identifier, cardClass: card.cardModel.className, cardType: card.cardModel.type, action: action.type, detail: error != nil ? error!.description : nil)
}
})
}
func dismissTapped(_ card: MZCardViewModel, action: MZActionViewModel, stage: MZStageViewModel) {
self.cardsInteractor?.sendActionCard(card, action: action, stage: stage, completion: { (error) in
MZAnalyticsInteractor.cardFinishEvent(card.identifier, cardClass: card.cardModel.className, cardType: card.cardModel.type, action: action.type, detail: error != nil ? error!.description : nil)
})
hideCard()
}
func showInfo(_ card: MZCardViewModel, action: MZActionViewModel, stage: MZStageViewModel) {
self.delegate?.showCardInfo(cardVM: card, action: action, stage: stage)
}
func actionTapped(_ card: MZCardViewModel, action: MZActionViewModel) {
self.cardsInteractor?.sendNotifyCard(card, action: action)
if action.refreshAfter
{
self.delegate?.showPullToRefresh()
}
if action.pubMQTT != nil
{
self.cardsInteractor?.pubMQTT(action.pubMQTT!.topic, payload: action.pubMQTT!.payload)
}
}
func nextField(_ card: MZCardViewModel) {
let stage = card.stages[card.unfoldedStagesIndex]
if(stage.fields.count > 0)
{
stage.unfoldedFieldsIndex += 1
}
updateCard()
}
func resetCard(_ card: MZCardViewModel) {
self.currentStageIndex = 0
updateCard()
}
func mapTapped(_ coordinates: CoordinatesTemp?, field: MZFieldViewModel) {
var vc = MZCardLocationPickerViewController(nibName: "MZCardLocationPickerViewController", bundle: Bundle.main)
vc.delegate = self
vc.coordinates = coordinates
vc.indexPath = self.indexPath
vc.setup(field)
(self.parentViewController! as! MZCardsViewController).parentWireframe?.push(vc, animated: true)
// self.parentViewController?.present(vc, animated: true, completion: nil)
}
func didMapChooseSetLocation(_ result: MZLocationPlaceholderViewModel, objectToUpdate: AnyObject, indexPath: IndexPath?) {
let fieldToUpdate = objectToUpdate as! MZFieldViewModel
fieldToUpdate.setValue(result)
self.updateCard()
// self.parentViewController?.dismiss(animated: true, completion: nil)
}
func addDeviceTapped(_ fieldVM: MZFieldViewModel, card: MZCardViewModel) {
let deviceSelectionVC = MZAddDevicePopupViewController(interactor: self.cardsInteractor, fieldVM: fieldVM, filter: fieldVM.filters as [AnyObject], card: card)
deviceSelectionVC.delegate = self
if(indexPath != nil)
{
deviceSelectionVC.indexPath = indexPath as! NSIndexPath
}
(self.parentViewController! as! MZCardsViewController).parentWireframe?.push(deviceSelectionVC, animated: true)
}
func removeDeviceTapped(_ indexPath: IndexPath?) {
self.delegate?.cardContentDidChange(indexPath: self.indexPath!)
}
func didDeviceChooseDone(_ card: MZCardViewModel) {
updateCard()
}
func datePickerToggled() {
// self.delegate?.cardContentDidChange(indexPath: self.indexPath!)
}
func buttonTapped(_ viewModel: MZFieldViewModel) {
}
func onAdTap(_ adsViewModel: MZAdsPlaceholderViewModel) {
self.showProductDetailForCard(cardId: self.card!.identifier, detailUrl: adsViewModel.detailUrl)
}
func showProductDetailForCard(cardId : String, detailUrl: String)
{
// let productVC = MZProductViewController(parentWireframe: parentWireframe!, interactor: self.cardsInteractor!)
// productVC.cardId = cardId
// productVC.detailUrl = detailUrl
// self.parentWireframe?.push(productVC, animated: true)
}
/// Feedback tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.tableViewPopupItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let tableViewPopupItem = self.tableViewPopupItems[indexPath.row]
let cell = self.tableViewPopup.dequeueReusableCell(withIdentifier: "Cell")
cell!.textLabel!.text = NSLocalizedString(tableViewPopupItem, comment: tableViewPopupItem)
cell!.textLabel!.font = UIFont.regularFontOfSize(16)
cell!.textLabel?.textColor = UIColor.muzzleyGray2Color(withAlpha: 1)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.tableViewPopupItems[indexPath.row]
self.hideCard()
self.sendHideOption(hideOption: item)
self.hidePopupItemsTableView()
}
func sendHideOption(hideOption: String)
{
MZAnalyticsInteractor.cardHideEvent(self.card!.identifier, cardClass: self.card!.cardModel.className, cardType: self.card!.cardModel.type, value: hideOption)
self.cardsInteractor!.sendHideCard(self.card!, hideOption: hideOption, completion: nil)
}
func hidePopupItemsTableView()
{
self.tableViewPopup.removeFromSuperview()
if(!self.uiOverlayView.isHidden)
{
self.uiOverlayView.isHidden = true
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.uiBackgroundView.layer.cornerRadius = CORNER_RADIUS
self.uiBackgroundView.clipsToBounds = true
self.uiBackgroundView.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
self.uiBackgroundView.layer.shadowOpacity = 0.2
self.uiBackgroundView.layer.shadowColor = UIColor.black.cgColor
self.uiBackgroundView.layer.shadowRadius = 1
self.uiBackgroundView.layer.shadowPath = UIBezierPath(roundedRect: self.uiBackgroundView!.bounds, cornerRadius: self.uiBackgroundView!.layer.cornerRadius).cgPath
}
}
| 35.19863 | 255 | 0.624197 |
5df8f1c2695f8ab40fbf4fce652ae0351400c772 | 5,788 | //
// Company.swift
// EquityStatus
//
// Created by Paul Tangen on 11/16/19.
// Copyright © 2019 Paul Tangen. All rights reserved.
//
import Foundation
class Company {
var ticker: String
var name: String
var tenYrsOld: Bool
var eps_i: Int?
var eps_sd: Double?
var eps_last: Double?
var roe_avg: Int?
var bv_i: Int?
var dr_avg: Int?
var so_reduced: Int?
var pe_avg: Double?
var pe_change: Double?
var price_last: Double?
var previous_roi: Int?
var expected_roi: Int?
var q1_answer: String?
var q2_answer: String?
var q3_answer: String?
var q4_answer: String?
var q5_answer: String?
var q6_answer: String?
var own_answer: String?
var q1_passed: Bool?
var q2_passed: Bool?
var q3_passed: Bool?
var q4_passed: Bool?
var q5_passed: Bool?
var q6_passed: Bool?
var own_passed: Bool?
init(ticker: String, name:String, tenYrsOld:Bool) {
self.ticker = ticker
self.name = name
self.tenYrsOld = tenYrsOld
}
subscript(key: String) -> Any? {
switch key {
case "name" : return name
case "q1_passed" : return q1_passed
default : return nil
}
}
var eps_i_passed: Bool? {
get {
if let eps_iUnwrapped = eps_i {
return Double(eps_iUnwrapped) >= Constants.thresholdValues.eps_i.rawValue
}
return nil
}
}
var eps_sd_passed: Bool? {
get {
if let eps_sdUnwrapped = eps_sd {
return eps_sdUnwrapped <= Double(Constants.thresholdValues.eps_sd.rawValue)
}
return nil
}
}
var roe_avg_passed: Bool? {
get {
if let roe_avgUnwrapped = roe_avg {
return Double(roe_avgUnwrapped) >= Constants.thresholdValues.roe_avg
}
return nil
}
}
var bv_i_passed: Bool? {
get {
if let bv_iUnwrapped = bv_i {
return Double(bv_iUnwrapped) >= Constants.thresholdValues.bv_i.rawValue
}
return nil
}
}
var dr_avg_passed: Bool? {
get {
if let dr_avgUnwrapped = dr_avg {
return Double(dr_avgUnwrapped) <= Constants.thresholdValues.dr_avg
}
return nil
}
}
var so_reduced_passed: Bool? {
get {
if let so_reducedUnwrapped = so_reduced {
return Double(so_reducedUnwrapped) >= Constants.thresholdValues.so_reduced.rawValue
}
return nil
}
}
var pe_change_passed: Bool? {
get {
if let pe_changeUnwrapped = pe_change {
return Double(pe_changeUnwrapped) <= Constants.thresholdValues.pe_change.rawValue
}
return nil
}
}
var expected_roi_passed: Bool? {
get {
if let expected_roiUnwrapped = expected_roi {
return Double(expected_roiUnwrapped) >= Constants.thresholdValues.expected_roi
}
return nil
}
}
var previous_roi_passed: Bool? {
get {
if let previous_roiUnwrapped = previous_roi {
return Double(previous_roiUnwrapped) >= Constants.thresholdValues.previous_roi
}
return nil
}
}
var tab: Constants.EquityTabValue {
get {
var might_be_buy: Bool = false
if let own_passedUnwrapped = own_passed {
if own_passedUnwrapped {
return .own
}
}
if let eps_i_passed_unwrapped = eps_i_passed, let eps_sd_passed_unwrapped = eps_sd_passed, let roe_avg_passed_unwrapped = roe_avg_passed, let dr_avg_passed_unwrapped = dr_avg_passed, let so_reduced_passed_unwrapped = so_reduced_passed, let pe_change_passed_unwrapped = pe_change_passed, let expected_roi_passed_unwrapped = expected_roi_passed, let previous_roi_passed_unwrapped = previous_roi_passed {
// if any of the calculated measures failed set to .sell
if !eps_i_passed_unwrapped || !eps_sd_passed_unwrapped || !roe_avg_passed_unwrapped || !dr_avg_passed_unwrapped || !so_reduced_passed_unwrapped || !pe_change_passed_unwrapped || !expected_roi_passed_unwrapped || !previous_roi_passed_unwrapped {
return .sell }
// the remaining companies are can be:
// .sell if any of the subjective measures failed
// .evaluate if any of the objective measures are nill
// .buy if all the objective measures are true
let questionProperties = [q1_passed, q2_passed, q3_passed, q4_passed, q5_passed, q6_passed]
for questionProperty in questionProperties {
if let questionProperty_unwrapped = questionProperty {
if questionProperty_unwrapped {
might_be_buy = true
} else {
return .sell // property is false
}
} else {
return .evaluate // one of the subjective measures is nil
}
}
// now we can assign buy or evaluate
if might_be_buy {
return .buy
}
} else {
return .sell // one of the financial measures was nil
}
return .sell
}
}
}
| 30.951872 | 415 | 0.550795 |
3812c9ba4680c5fb7d56f5c1e77a352834fe02d7 | 477 | //
// RequestOption+Extension.swift
// CoreRequest
//
// Created by Robert on 8/10/19.
//
extension ProgressTrackable {
@inlinable
public var queue: DispatchQueue { .main }
}
extension TrackingOption where Self: ProgressTrackable {
@inlinable
public var tracking: ProgressTrackable? { self }
}
extension DownloadRequestOption where Self: DownloadFileDestination {
@inlinable
public var downloadFileDestination: DownloadFileDestination? { self }
}
| 21.681818 | 73 | 0.737945 |
9b0384219ebd4f7bdc6c2411cc8116b0117cb845 | 4,202 | //
// EditorToolbar.swift
// EditImage
//
// Created by Mihály Papp on 03/07/2018.
// Copyright © 2018 Mihály Papp. All rights reserved.
//
import UIKit
class EditorToolbar: UIToolbar {
weak var editorDelegate: EditorToolbarDelegate?
var space: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
var rotate: UIBarButtonItem {
let rotate = imageBarButton("icon-rotate", action: #selector(rotateSelected))
rotate.tintColor = .white
return rotate
}
var crop: UIBarButtonItem {
let crop = imageBarButton("icon-crop", action: #selector(cropSelected))
crop.tintColor = .white
return crop
}
var circle: UIBarButtonItem {
let circle = imageBarButton("icon-circle", action: #selector(circleSelected))
circle.tintColor = .white
return circle
}
var save: UIBarButtonItem {
let save = imageBarButton("icon-tick", action: #selector(saveSelected))
redo.tintColor = editColor
return save
}
var cancel: UIBarButtonItem {
let cancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelSelected))
cancel.tintColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
return cancel
}
var done: UIBarButtonItem {
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneSelected))
redo.tintColor = editColor
return done
}
lazy var undo: UIBarButtonItem = {
let undo = imageBarButton("icon-undo", action: #selector(undoSelected))
redo.tintColor = editColor
return undo
}()
lazy var redo: UIBarButtonItem = {
let redo = imageBarButton("icon-redo", action: #selector(redoSelected))
redo.tintColor = editColor
return redo
}()
private func imageBarButton(_ imageName: String, action: Selector) -> UIBarButtonItem {
let image = UIImage.fromFilestackBundle(imageName)
return UIBarButtonItem(image: image, style: .plain, target: self, action: action)
}
private var editColor: UIColor {
return UIColor(red: 240/255, green: 180/255, blue: 0, alpha: 1)
}
}
extension EditorToolbar {
@objc func rotateSelected() {
editorDelegate?.rotateSelected()
}
@objc func cropSelected() {
editorDelegate?.cropSelected()
}
@objc func circleSelected() {
editorDelegate?.circleSelected()
}
@objc func saveSelected() {
editorDelegate?.saveSelected()
}
@objc func cancelSelected() {
editorDelegate?.cancelSelected()
}
@objc func doneSelected() {
editorDelegate?.doneSelected()
}
@objc func undoSelected() {
editorDelegate?.undoSelected()
}
@objc func redoSelected() {
editorDelegate?.redoSelected()
}
}
protocol EditorToolbarDelegate: class {
func cancelSelected()
func rotateSelected()
func cropSelected()
func circleSelected()
func saveSelected()
func doneSelected()
func undoSelected()
func redoSelected()
}
class BottomEditorToolbar: EditorToolbar {
var isEditing: Bool = false {
didSet {
setupItems()
}
}
init() {
super.init(frame: .zero)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupItems() {
setItems([cancel, space, rotate, crop, circle, space, finish], animated: false)
}
var finish: UIBarButtonItem {
return isEditing ? save : done
}
}
private extension BottomEditorToolbar {
func setupView() {
setupItems()
barTintColor = .black
backgroundColor = UIColor(white: 31/255, alpha: 1)
}
}
class TopEditorToolbar: EditorToolbar {
init() {
super.init(frame: .zero)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUndo(hidden: Bool) {
let items = hidden ? [space] : [space, undo]
setItems(items, animated: false)
}
}
private extension TopEditorToolbar {
func setupView() {
setUndo(hidden: true)
setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
barTintColor = .clear
backgroundColor = .clear
}
}
| 23.344444 | 111 | 0.679914 |
abfd99a5959e9ebcff9d9fcd384e24a5867bc2c3 | 1,712 | // swift-tools-version:5.4.0
// Package.swift
//
// Copyright © 2017 Zebulon Frantzich
//
// 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.
// See https://developer.apple.com/documentation/xcode/creating_a_standalone_swift_package_with_xcode
import PackageDescription
let package = Package(
name: "DoubleMetaphoneSwift",
products: [
.library(
name: "DoubleMetaphoneSwift",
targets: ["DoubleMetaphone", "DoubleMetaphoneSwift"]
)
],
targets: [
.target(
name: "DoubleMetaphone"
),
.target(
name: "DoubleMetaphoneSwift",
dependencies: ["DoubleMetaphone"]
)
]
)
| 35.666667 | 101 | 0.70736 |
f8dd93e0ac7f08a1fe2232c44732a2d8f9309cea | 4,532 | //
// ContentFiltersTests.swift
// ListableUI-Unit-Tests
//
// Created by Kyle Van Essen on 8/21/20.
//
import XCTest
@testable import ListableUI
class ContentFiltersTests: XCTestCase
{
func test_contains()
{
let sections = [
Section(
"",
header: HeaderFooter(TestHeaderFooter()),
footer: HeaderFooter(TestHeaderFooter()),
items: [
Item(TestItem()),
Item(TestItem()),
Item(TestItem()),
]
)
]
let empty = Content()
let noHeader = Content(
header: nil,
footer: HeaderFooter(TestHeaderFooter()),
overscrollFooter: HeaderFooter(TestHeaderFooter()),
sections: sections
)
let noFooter = Content(
header: HeaderFooter(TestHeaderFooter()),
footer: nil,
overscrollFooter: HeaderFooter(TestHeaderFooter()),
sections: sections
)
let noOverscroll = Content(
header: HeaderFooter(TestHeaderFooter()),
footer: HeaderFooter(TestHeaderFooter()),
overscrollFooter: nil,
sections: sections
)
let noSections = Content(
header: HeaderFooter(TestHeaderFooter()),
footer: HeaderFooter(TestHeaderFooter()),
overscrollFooter: HeaderFooter(TestHeaderFooter()),
sections: []
)
let populated = Content(
header: HeaderFooter(TestHeaderFooter()),
footer: HeaderFooter(TestHeaderFooter()),
overscrollFooter: HeaderFooter(TestHeaderFooter()),
sections: sections
)
self.testcase("list header") {
XCTAssertEqual(empty.contains(any: [.listHeader]), false)
XCTAssertEqual(noHeader.contains(any: [.listHeader]), false)
XCTAssertEqual(noFooter.contains(any: [.listHeader]), true)
XCTAssertEqual(noOverscroll.contains(any: [.listHeader]), true)
XCTAssertEqual(noSections.contains(any: [.listHeader]), true)
XCTAssertEqual(populated.contains(any: [.listHeader]), true)
}
self.testcase("list footer") {
XCTAssertEqual(empty.contains(any: [.listFooter]), false)
XCTAssertEqual(noHeader.contains(any: [.listFooter]), true)
XCTAssertEqual(noFooter.contains(any: [.listFooter]), false)
XCTAssertEqual(noOverscroll.contains(any: [.listFooter]), true)
XCTAssertEqual(noSections.contains(any: [.listFooter]), true)
XCTAssertEqual(populated.contains(any: [.listFooter]), true)
}
self.testcase("overscroll footer") {
XCTAssertEqual(empty.contains(any: [.overscrollFooter]), false)
XCTAssertEqual(noHeader.contains(any: [.overscrollFooter]), true)
XCTAssertEqual(noFooter.contains(any: [.overscrollFooter]), true)
XCTAssertEqual(noOverscroll.contains(any: [.overscrollFooter]), false)
XCTAssertEqual(noSections.contains(any: [.overscrollFooter]), true)
XCTAssertEqual(populated.contains(any: [.overscrollFooter]), true)
}
self.testcase("section only fields") {
XCTAssertEqual(empty.contains(any: [.items]), false)
XCTAssertEqual(noHeader.contains(any: [.items]), true)
XCTAssertEqual(noFooter.contains(any: [.items]), true)
XCTAssertEqual(noOverscroll.contains(any: [.items]), true)
XCTAssertEqual(noSections.contains(any: [.items]), false)
XCTAssertEqual(populated.contains(any: [.items]), true)
}
}
}
fileprivate struct TestHeaderFooter : HeaderFooterContent, Equatable {
typealias ContentView = UIView
static func createReusableContentView(frame: CGRect) -> UIView {
UIView(frame: frame)
}
func apply(to views: HeaderFooterContentViews<TestHeaderFooter>, reason: ApplyReason) {}
}
fileprivate struct TestItem : ItemContent, Equatable {
var identifier: Identifier<TestItem> {
.init()
}
typealias ContentView = UIView
static func createReusableContentView(frame: CGRect) -> UIView {
UIView(frame: frame)
}
func apply(to views: ItemContentViews<TestItem>, for reason: ApplyReason, with info: ApplyItemContentInfo) {}
}
| 34.59542 | 113 | 0.596425 |
187345d095eea9a19e20c7a178aaaafe76d78d05 | 2,165 | /*
* Copyright (c) 2019 Telekom Deutschland AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import Core
class AuthenticationController {
let logger = LoggerProvider.sharedInstance.logger
var configuration: SmartCredentialsConfiguration
// MARK: - Initializers
init(configuration: SmartCredentialsConfiguration) {
self.configuration = configuration
}
// MARK: - Jailbreak Check
private func isJailbroken() -> Bool {
if configuration.jailbreakCheckEnabled {
return JailbreakDetection.isJailbroken()
}
return false
}
}
// MARK: - Authentication API
extension AuthenticationController: AuthenticationAPI {
func getAuthService(with configuration: [String : Any], authStateKey: String, completionHandler: @escaping AuthServiceCompletionHandler) {
guard isJailbroken() == false else {
logger?.log(.error, message: Constants.Logger.jailbreakError, className: className)
completionHandler(.failure(error: .jailbreakDetected))
return
}
AuthorizationModuleProvider.authorizationModule(with: configuration, authStateKey: authStateKey) { result in
switch result {
case .success(let authModule):
completionHandler(.success(result: authModule))
case .failure(let error):
completionHandler(.failure(error: error))
@unknown default:
// Any future cases not recognized by the compiler yet
break
}
}
}
}
extension AuthenticationController: Nameable {
}
| 33.307692 | 142 | 0.679908 |
e4276435b5fe22d05888b1fdf828f65bd394ce22 | 4,302 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Package Collection Generator open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift Package Collection Generator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Package Collection Generator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
import TSCUtility
public enum GitUtilities {
public static func clone(_ repositoryURL: String, to path: AbsolutePath) throws {
try ShellUtilities.run(Git.tool, "clone", repositoryURL, path.pathString)
}
public static func fetch(_ repositoryURL: String, at gitDirectoryPath: AbsolutePath) throws {
try ShellUtilities.run(Git.tool, "-C", gitDirectoryPath.pathString, "fetch")
}
public static func checkout(_ reference: String, at gitDirectoryPath: AbsolutePath) throws {
try ShellUtilities.run(Git.tool, "-C", gitDirectoryPath.pathString, "checkout", reference)
}
public static func listTags(for gitDirectoryPath: AbsolutePath) throws -> [String] {
let output = try ShellUtilities.run(Git.tool, "-C", gitDirectoryPath.pathString, "tag")
let tags = output.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty }
return tags
}
public static func tagInfo(_ tag: String, for gitDirectoryPath: AbsolutePath) throws -> GitTagInfo? {
// If a tag is annotated (i.e., has a message), this command will return "tag", otherwise it will return "commit".
let tagType = try ShellUtilities.run(Git.tool, "-C", gitDirectoryPath.pathString, "cat-file", "-t", tag).trimmingCharacters(in: .whitespacesAndNewlines)
guard tagType == "tag" else {
return nil
}
// The following commands only make sense for annotated tag. Otherwise, `contents` would be
// the message of the commit that the tag points to, which isn't always appropriate, and
// `taggerdate` would be empty
let message = try ShellUtilities.run(Git.tool, "-C", gitDirectoryPath.pathString, "tag", "-l", "--format=%(contents:subject)", tag).trimmingCharacters(in: .whitespacesAndNewlines)
// This shows the date when the tag was created. This would be empty if the tag was created on GitHub as part of a release.
let createdAt = try ShellUtilities.run(Git.tool, "-C", gitDirectoryPath.pathString, "tag", "-l", "%(taggerdate:iso8601-strict)", tag).trimmingCharacters(in: .whitespacesAndNewlines)
return GitTagInfo(message: message, createdAt: createdAt)
}
}
public struct GitTagInfo {
public let message: String
public let createdAt: Date?
private static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter
}()
init(message: String, createdAt: String) {
self.message = message
self.createdAt = Self.dateFormatter.date(from: createdAt)
}
}
public struct GitURL {
public let host: String
public let owner: String
public let repository: String
public static func from(_ gitURL: String) -> GitURL? {
do {
let regex = try NSRegularExpression(pattern: #"([^/@]+)[:/]([^:/]+)/([^/.]+)(\.git)?$"#, options: .caseInsensitive)
if let match = regex.firstMatch(in: gitURL, options: [], range: NSRange(location: 0, length: gitURL.count)) {
if let hostRange = Range(match.range(at: 1), in: gitURL),
let ownerRange = Range(match.range(at: 2), in: gitURL),
let repoRange = Range(match.range(at: 3), in: gitURL) {
let host = String(gitURL[hostRange])
let owner = String(gitURL[ownerRange])
let repository = String(gitURL[repoRange])
return GitURL(host: host, owner: owner, repository: repository)
}
}
return nil
} catch {
return nil
}
}
}
| 44.8125 | 189 | 0.634124 |
e6344c5529ba0195f7244bcc1e99cde978e81044 | 2,060 | //
// Mode.swift
// FanFindSDK
//
// Created by Christopher Woolum on 7/27/19.
// Copyright © 2019 Turnoutt Inc. All rights reserved.
//
import Foundation
import MapKit
extension Navigator {
internal enum Mode: String {
case walking
case bicycling
case driving
case transit
case taxi
/// Look up the transport mode identifier name for a given app.
///
/// - Parameter app: navigation app
/// - Returns: For Apple Maps a `[String:String]`, `String` for anything else. `nil` if
/// irrelevant.
func identifier(for app: Navigator.NavigationApp) -> Any? { // swiftlint:disable:this cyclomatic_complexity
switch app {
case .appleMaps:
switch self {
case .walking:
return [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking]
case .driving:
return [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
case .transit:
return [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeTransit]
case .taxi:
// it is supported, but there's no key for this...
return [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
default: return nil
}
case .googleMaps:
switch self {
case .walking: return "walking"
case .bicycling: return "bicycling"
case .driving: return "driving"
case .transit: return "transit"
// just like Apple Maps this actually is supported, but the key isn't specified in the
// docs... meh.
case .taxi: return "driving"
}
case .lyft, .uber:
return nil
case .waze:
return nil
}
}
}
}
| 34.915254 | 115 | 0.542718 |
50ce285e4ede8ca8580fbc517108aae6f2878c2d | 608 | //
// ValidateContact.swift
// ContactsApp
//
// Created by Rohit Bansal on 04/10/15.
//
import Foundation
class ContactsValidator {
static func isValidContact(contact: Contact) -> Bool {
return isValidName(contact.firstName) && isValidName(contact.lastName)
&& isValidPhonenumber(contact.phonenumber)
}
// MARK: Validation methods
private static func isValidName(input: String) -> Bool {
return !(input ?? "").isEmpty
}
private static func isValidPhonenumber(input: String) -> Bool {
return !(input ?? "").isEmpty
}
} | 22.518519 | 78 | 0.631579 |
76f99fe5b5f1a3f4a196f0f5ba3a620b2d6bc821 | 995 | //
// QuickActivityOption.swift
// ForYouAndMe
//
// Created by Leonardo Passeri on 06/08/2020.
//
import Foundation
struct QuickActivityOption {
let id: String
let type: String
@NilIfEmptyString
var label: String?
@ImageDecodable
var image: UIImage?
@ImageDecodable
var selectedImage: UIImage?
}
extension QuickActivityOption: JSONAPIMappable {
enum CodingKeys: String, CodingKey {
case id
case type
case label
case image
case selectedImage = "selected_image"
}
}
extension QuickActivityOption: Equatable {
static func == (lhs: QuickActivityOption, rhs: QuickActivityOption) -> Bool {
return lhs.id == rhs.id
}
}
extension QuickActivityOption {
var networkResultData: TaskNetworkResult {
var resultData: [String: Any] = [:]
resultData["selected_quick_activity_option_id"] = Int(self.id)
return TaskNetworkResult(data: resultData, attachedFile: nil)
}
}
| 22.111111 | 81 | 0.670352 |
ffd3de092ccb5e3466054b0d25edf4af49e22789 | 9,424 | //
// StatementPositionRule.swift
// SwiftLint
//
// Created by Alex Culeva on 10/22/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct StatementPositionRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = StatementConfiguration(statementMode: .default,
severity: SeverityConfiguration(.warning))
public init() {}
public static let description = RuleDescription(
identifier: "statement_position",
name: "Statement Position",
description: "Else and catch should be on the same line, one space after the previous " +
"declaration.",
nonTriggeringExamples: [
"} else if {",
"} else {",
"} catch {",
"\"}else{\"",
"struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)",
"struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)"
],
triggeringExamples: [
"↓}else if {",
"↓} else {",
"↓}\ncatch {",
"↓}\n\t catch {"
],
corrections: [
"↓}\n else {\n": "} else {\n",
"↓}\n else if {\n": "} else if {\n",
"↓}\n catch {\n": "} catch {\n"
]
)
public static let uncuddledDescription = RuleDescription(
identifier: "statement_position",
name: "Statement Position",
description: "Else and catch should be on the next line, with equal indentation to the " +
"previous declaration.",
nonTriggeringExamples: [
" }\n else if {",
" }\n else {",
" }\n catch {",
" }\n\n catch {",
"\n\n }\n catch {",
"\"}\nelse{\"",
"struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)",
"struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)"
],
triggeringExamples: [
"↓ }else if {",
"↓}\n else {",
"↓ }\ncatch {",
"↓}\n\t catch {"
],
corrections: [
" }else if {": " }\n else if {",
"}\n else {": "}\nelse {",
" }\ncatch {": " }\n catch {",
"}\n\t catch {": "}\ncatch {"
]
)
public func validate(file: File) -> [StyleViolation] {
switch configuration.statementMode {
case .default:
return defaultValidate(file: file)
case .uncuddledElse:
return uncuddledValidate(file: file)
}
}
public func correct(file: File) -> [Correction] {
switch configuration.statementMode {
case .default:
return defaultCorrect(file: file)
case .uncuddledElse:
return uncuddledCorrect(file: file)
}
}
}
// Default Behaviors
private extension StatementPositionRule {
// match literal '}'
// followed by 1) nothing, 2) two+ whitespace/newlines or 3) newlines or tabs
// followed by 'else' or 'catch' literals
static let defaultPattern = "\\}(?:[\\s\\n\\r]{2,}|[\\n\\t\\r]+)?\\b(else|catch)\\b"
func defaultValidate(file: File) -> [StyleViolation] {
return defaultViolationRanges(in: file, matching: type(of: self).defaultPattern).flatMap { range in
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity.severity,
location: Location(file: file, characterOffset: range.location))
}
}
func defaultViolationRanges(in file: File, matching pattern: String) -> [NSRange] {
return file.match(pattern: pattern).filter { _, syntaxKinds in
return syntaxKinds.starts(with: [.keyword])
}.flatMap { $0.0 }
}
func defaultCorrect(file: File) -> [Correction] {
let violations = defaultViolationRanges(in: file, matching: type(of: self).defaultPattern)
let matches = file.ruleEnabled(violatingRanges: violations, for: self)
if matches.isEmpty { return [] }
let regularExpression = regex(type(of: self).defaultPattern)
let description = type(of: self).description
var corrections = [Correction]()
var contents = file.contents
for range in matches.reversed() {
contents = regularExpression.stringByReplacingMatches(in: contents, options: [], range: range,
withTemplate: "} $1")
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}
// Uncuddled Behaviors
private extension StatementPositionRule {
func uncuddledValidate(file: File) -> [StyleViolation] {
return uncuddledViolationRanges(in: file).flatMap { range in
return StyleViolation(ruleDescription: type(of: self).uncuddledDescription,
severity: configuration.severity.severity,
location: Location(file: file, characterOffset: range.location))
}
}
// match literal '}'
// preceded by whitespace (or nothing)
// followed by 1) nothing, 2) two+ whitespace/newlines or 3) newlines or tabs
// followed by newline and the same amount of whitespace then 'else' or 'catch' literals
static let uncuddledPattern = "([ \t]*)\\}(\\n+)?([ \t]*)\\b(else|catch)\\b"
static let uncuddledRegex = regex(uncuddledPattern, options: [])
static func uncuddledMatchValidator(contents: String) -> ((NSTextCheckingResult) -> NSTextCheckingResult?) {
return { match in
if match.numberOfRanges != 5 {
return match
}
if match.rangeAt(2).length == 0 {
return match
}
let range1 = match.rangeAt(1)
let range2 = match.rangeAt(3)
let whitespace1 = contents.substring(from: range1.location, length: range1.length)
let whitespace2 = contents.substring(from: range2.location, length: range2.length)
if whitespace1 == whitespace2 {
return nil
}
return match
}
}
static func uncuddledMatchFilter(contents: String, syntaxMap: SyntaxMap) -> ((NSTextCheckingResult) -> Bool) {
return { match in
let range = match.range
guard let matchRange = contents.bridge().NSRangeToByteRange(start: range.location,
length: range.length) else {
return false
}
let tokens = syntaxMap.tokens(inByteRange: matchRange).flatMap { SyntaxKind(rawValue: $0.type) }
return tokens == [.keyword]
}
}
func uncuddledViolationRanges(in file: File) -> [NSRange] {
let contents = file.contents
let range = NSRange(location: 0, length: contents.utf16.count)
let syntaxMap = file.syntaxMap
let matches = StatementPositionRule.uncuddledRegex.matches(in: contents, options: [], range: range)
let validator = type(of: self).uncuddledMatchValidator(contents: contents)
let filterMatches = type(of: self).uncuddledMatchFilter(contents: contents, syntaxMap: syntaxMap)
let validMatches = matches.flatMap(validator).filter(filterMatches).map({ $0.range })
return validMatches
}
func uncuddledCorrect(file: File) -> [Correction] {
var contents = file.contents
let range = NSRange(location: 0, length: contents.utf16.count)
let syntaxMap = file.syntaxMap
let matches = StatementPositionRule.uncuddledRegex.matches(in: contents, options: [], range: range)
let validator = type(of: self).uncuddledMatchValidator(contents: contents)
let filterRanges = type(of: self).uncuddledMatchFilter(contents: contents, syntaxMap: syntaxMap)
let validMatches = matches.flatMap(validator).filter(filterRanges)
.filter { !file.ruleEnabled(violatingRanges: [$0.range], for: self).isEmpty }
if validMatches.isEmpty { return [] }
let description = type(of: self).uncuddledDescription
var corrections = [Correction]()
for match in validMatches.reversed() {
let range1 = match.rangeAt(1)
let range2 = match.rangeAt(3)
let newlineRange = match.rangeAt(2)
var whitespace = contents.bridge().substring(with: range1)
let newLines: String
if newlineRange.location != NSNotFound {
newLines = contents.bridge().substring(with: newlineRange)
} else {
newLines = ""
}
if !whitespace.hasPrefix("\n") && newLines != "\n" {
whitespace.insert("\n", at: whitespace.startIndex)
}
contents = contents.bridge().replacingCharacters(in: range2, with: whitespace)
let location = Location(file: file, characterOffset: match.range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}
| 40.446352 | 114 | 0.578735 |
e0d814cd0d47a69dd334367f4fa9cb8de6c29a76 | 3,939 | //
// HDMainController.swift
// Chromatic
//
// Created by Lakr Aream on 2021/8/8.
// Copyright © 2021 Lakr Aream. All rights reserved.
//
import DropDown
import FluentIcon
import SPIndicator
import SwiftMD5
import UIKit
class HDMainNavigator: UINavigationController {
init() {
super.init(rootViewController: HDMainController())
navigationBar.prefersLargeTitles = true
tabBarItem = UITabBarItem(title: NSLocalizedString("MAIN", comment: "Main"),
image: UIImage.fluent(.timeline24Regular),
tag: 0)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class HDMainController: DashboardController {
var welcomeCard: WelcomeCard?
let welcomeCardDropDownAnchor = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = cLXUIDefaultBackgroundColor
title = NSLocalizedString("MAIN", comment: "Main")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: .fluent(.settings24Regular),
style: .done,
target: self,
action: #selector(rightButtonCall))
collectionView.contentInset = UIEdgeInsets(top: 200, left: 20, bottom: 50, right: 20)
searchBar.removeFromSuperview()
let welcome = WelcomeCard { [weak self] in
self?.onTouchAvatar()
} onTouchCard: { [weak self] in
self?.onTouchCard()
}
welcomeCard = welcome
collectionView.addSubview(welcome)
welcome.snp.makeConstraints { x in
x.left.equalTo(view).offset(20)
x.right.equalTo(view).offset(-20)
x.bottom.equalTo(collectionView.snp.top)
x.height.equalTo(220)
}
collectionView.addSubview(welcomeCardDropDownAnchor)
welcomeCardDropDownAnchor.snp.makeConstraints { x in
x.left.equalTo(view).offset(20)
x.right.equalTo(view).offset(-20)
x.bottom.equalTo(collectionView.snp.top).offset(10)
x.height.equalTo(5)
}
refreshControl.alpha = 0
DispatchQueue.main.async {
self.updateWelcomeCardHeight()
}
}
var updateDecision: CGSize?
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
DispatchQueue.main.async {
if self.updateDecision != self.view.frame.size {
self.updateDecision = self.view.frame.size
self.updateWelcomeCardHeight()
}
}
}
func updateWelcomeCardHeight() {
var height: CGFloat = 200
let frame = view.frame.width - 30
height = frame * 0.55
if height < 150 { height = 150 }
if height > 250 { height = 250 }
welcomeCard?.snp.updateConstraints { x in
x.height.equalTo(height - 10)
}
collectionView.contentInset = UIEdgeInsets(top: height, left: 20, bottom: 50, right: 20)
}
@objc
func rightButtonCall() {
let target = SettingController()
present(next: target)
}
func onTouchAvatar() {
onTouchCard()
}
func onTouchCard() {
InterfaceBridge.appleCardTouched(dropDownAnchor: welcomeCardDropDownAnchor)
}
override func collectionView(_: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: packageCellID, for: indexPath)
as! PackageCollectionCell
cell.prepareForNewValue()
cell.loadValue(package: dataSource[indexPath.section].package[indexPath.row])
return cell
}
}
| 31.261905 | 115 | 0.601676 |
64b8e727661f919333d1743380543c3f379204d6 | 17,706 | // Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment
// -- Generated Code; do not edit --
//
// SecurityTokenModelTypes.swift
// SecurityTokenModel
//
import Foundation
/**
Type definition for the Audience field.
*/
public typealias Audience = String
/**
Type definition for the Issuer field.
*/
public typealias Issuer = String
/**
Type definition for the NameQualifier field.
*/
public typealias NameQualifier = String
/**
Type definition for the SAMLAssertionType field.
*/
public typealias SAMLAssertionType = String
/**
Type definition for the Subject field.
*/
public typealias Subject = String
/**
Type definition for the SubjectType field.
*/
public typealias SubjectType = String
/**
Type definition for the AccessKeyIdType field.
*/
public typealias AccessKeyIdType = String
/**
Type definition for the AccessKeySecretType field.
*/
public typealias AccessKeySecretType = String
/**
Type definition for the AccountType field.
*/
public typealias AccountType = String
/**
Type definition for the ArnType field.
*/
public typealias ArnType = String
/**
Type definition for the AssumedRoleIdType field.
*/
public typealias AssumedRoleIdType = String
/**
Type definition for the ClientTokenType field.
*/
public typealias ClientTokenType = String
/**
Type definition for the DateType field.
*/
public typealias DateType = String
/**
Type definition for the DecodedMessageType field.
*/
public typealias DecodedMessageType = String
/**
Type definition for the DurationSecondsType field.
*/
public typealias DurationSecondsType = Int
/**
Type definition for the EncodedMessageType field.
*/
public typealias EncodedMessageType = String
/**
Type definition for the ExpiredIdentityTokenMessage field.
*/
public typealias ExpiredIdentityTokenMessage = String
/**
Type definition for the ExternalIdType field.
*/
public typealias ExternalIdType = String
/**
Type definition for the FederatedIdType field.
*/
public typealias FederatedIdType = String
/**
Type definition for the IdpCommunicationErrorMessage field.
*/
public typealias IdpCommunicationErrorMessage = String
/**
Type definition for the IdpRejectedClaimMessage field.
*/
public typealias IdpRejectedClaimMessage = String
/**
Type definition for the InvalidAuthorizationMessage field.
*/
public typealias InvalidAuthorizationMessage = String
/**
Type definition for the InvalidIdentityTokenMessage field.
*/
public typealias InvalidIdentityTokenMessage = String
/**
Type definition for the MalformedPolicyDocumentMessage field.
*/
public typealias MalformedPolicyDocumentMessage = String
/**
Type definition for the NonNegativeIntegerType field.
*/
public typealias NonNegativeIntegerType = Int
/**
Type definition for the PackedPolicyTooLargeMessage field.
*/
public typealias PackedPolicyTooLargeMessage = String
/**
Type definition for the RegionDisabledMessage field.
*/
public typealias RegionDisabledMessage = String
/**
Type definition for the RoleDurationSecondsType field.
*/
public typealias RoleDurationSecondsType = Int
/**
Type definition for the RoleSessionNameType field.
*/
public typealias RoleSessionNameType = String
/**
Type definition for the SerialNumberType field.
*/
public typealias SerialNumberType = String
/**
Type definition for the SessionPolicyDocumentType field.
*/
public typealias SessionPolicyDocumentType = String
/**
Type definition for the TokenCodeType field.
*/
public typealias TokenCodeType = String
/**
Type definition for the TokenType field.
*/
public typealias TokenType = String
/**
Type definition for the UrlType field.
*/
public typealias UrlType = String
/**
Type definition for the UserIdType field.
*/
public typealias UserIdType = String
/**
Type definition for the UserNameType field.
*/
public typealias UserNameType = String
/**
Type definition for the WebIdentitySubjectType field.
*/
public typealias WebIdentitySubjectType = String
/**
Validation for the SAMLAssertionType field.
*/
extension SecurityTokenModel.SAMLAssertionType {
public func validateAsSAMLAssertionType() throws {
if self.count < 4 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to SAMLAssertionType violated the minimum length constraint.")
}
if self.count > 100000 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to SAMLAssertionType violated the maximum length constraint.")
}
}
}
/**
Validation for the AccessKeyIdType field.
*/
extension SecurityTokenModel.AccessKeyIdType {
public func validateAsAccessKeyIdType() throws {
if self.count < 16 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to accessKeyIdType violated the minimum length constraint.")
}
if self.count > 128 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to accessKeyIdType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to accessKeyIdType violated the regular expression constraint.")
}
}
}
/**
Validation for the ArnType field.
*/
extension SecurityTokenModel.ArnType {
public func validateAsArnType() throws {
if self.count < 20 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to arnType violated the minimum length constraint.")
}
if self.count > 2048 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to arnType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\u0009\\u000A\\u000D\\u0020-\\u007E\\u0085\\u00A0-\\uD7FF\\uE000-\\uFFFD\\u10000-\\u10FFFF]+", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to arnType violated the regular expression constraint.")
}
}
}
/**
Validation for the AssumedRoleIdType field.
*/
extension SecurityTokenModel.AssumedRoleIdType {
public func validateAsAssumedRoleIdType() throws {
if self.count < 2 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to assumedRoleIdType violated the minimum length constraint.")
}
if self.count > 193 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to assumedRoleIdType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w+=,.@:-]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to assumedRoleIdType violated the regular expression constraint.")
}
}
}
/**
Validation for the ClientTokenType field.
*/
extension SecurityTokenModel.ClientTokenType {
public func validateAsClientTokenType() throws {
if self.count < 4 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to clientTokenType violated the minimum length constraint.")
}
if self.count > 2048 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to clientTokenType violated the maximum length constraint.")
}
}
}
/**
Validation for the DurationSecondsType field.
*/
extension SecurityTokenModel.DurationSecondsType {
public func validateAsDurationSecondsType() throws {
if self < 900 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to durationSecondsType violated the minimum range constraint.")
}
if self > 129600 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to durationSecondsType violated the maximum range constraint.")
}
}
}
/**
Validation for the EncodedMessageType field.
*/
extension SecurityTokenModel.EncodedMessageType {
public func validateAsEncodedMessageType() throws {
if self.count < 1 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to encodedMessageType violated the minimum length constraint.")
}
if self.count > 10240 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to encodedMessageType violated the maximum length constraint.")
}
}
}
/**
Validation for the ExternalIdType field.
*/
extension SecurityTokenModel.ExternalIdType {
public func validateAsExternalIdType() throws {
if self.count < 2 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to externalIdType violated the minimum length constraint.")
}
if self.count > 1224 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to externalIdType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w+=,.@:\\/-]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to externalIdType violated the regular expression constraint.")
}
}
}
/**
Validation for the FederatedIdType field.
*/
extension SecurityTokenModel.FederatedIdType {
public func validateAsFederatedIdType() throws {
if self.count < 2 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to federatedIdType violated the minimum length constraint.")
}
if self.count > 193 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to federatedIdType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w+=,.@\\:-]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to federatedIdType violated the regular expression constraint.")
}
}
}
/**
Validation for the NonNegativeIntegerType field.
*/
extension SecurityTokenModel.NonNegativeIntegerType {
public func validateAsNonNegativeIntegerType() throws {
if self < 0 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to nonNegativeIntegerType violated the minimum range constraint.")
}
}
}
/**
Validation for the RoleDurationSecondsType field.
*/
extension SecurityTokenModel.RoleDurationSecondsType {
public func validateAsRoleDurationSecondsType() throws {
if self < 900 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to roleDurationSecondsType violated the minimum range constraint.")
}
if self > 43200 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to roleDurationSecondsType violated the maximum range constraint.")
}
}
}
/**
Validation for the RoleSessionNameType field.
*/
extension SecurityTokenModel.RoleSessionNameType {
public func validateAsRoleSessionNameType() throws {
if self.count < 2 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to roleSessionNameType violated the minimum length constraint.")
}
if self.count > 64 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to roleSessionNameType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w+=,.@-]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to roleSessionNameType violated the regular expression constraint.")
}
}
}
/**
Validation for the SerialNumberType field.
*/
extension SecurityTokenModel.SerialNumberType {
public func validateAsSerialNumberType() throws {
if self.count < 9 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to serialNumberType violated the minimum length constraint.")
}
if self.count > 256 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to serialNumberType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w+=/:,.@-]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to serialNumberType violated the regular expression constraint.")
}
}
}
/**
Validation for the SessionPolicyDocumentType field.
*/
extension SecurityTokenModel.SessionPolicyDocumentType {
public func validateAsSessionPolicyDocumentType() throws {
if self.count < 1 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to sessionPolicyDocumentType violated the minimum length constraint.")
}
if self.count > 2048 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to sessionPolicyDocumentType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\u0009\\u000A\\u000D\\u0020-\\u00FF]+", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to sessionPolicyDocumentType violated the regular expression constraint.")
}
}
}
/**
Validation for the TokenCodeType field.
*/
extension SecurityTokenModel.TokenCodeType {
public func validateAsTokenCodeType() throws {
if self.count < 6 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to tokenCodeType violated the minimum length constraint.")
}
if self.count > 6 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to tokenCodeType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\d]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to tokenCodeType violated the regular expression constraint.")
}
}
}
/**
Validation for the UrlType field.
*/
extension SecurityTokenModel.UrlType {
public func validateAsUrlType() throws {
if self.count < 4 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to urlType violated the minimum length constraint.")
}
if self.count > 2048 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to urlType violated the maximum length constraint.")
}
}
}
/**
Validation for the UserNameType field.
*/
extension SecurityTokenModel.UserNameType {
public func validateAsUserNameType() throws {
if self.count < 2 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to userNameType violated the minimum length constraint.")
}
if self.count > 32 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to userNameType violated the maximum length constraint.")
}
guard let matchingRange = self.range(of: "[\\w+=,.@-]*", options: .regularExpression),
matchingRange == startIndex..<endIndex else {
throw SecurityTokenCodingError.validationError(
reason: "The provided value to userNameType violated the regular expression constraint.")
}
}
}
/**
Validation for the WebIdentitySubjectType field.
*/
extension SecurityTokenModel.WebIdentitySubjectType {
public func validateAsWebIdentitySubjectType() throws {
if self.count < 6 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to webIdentitySubjectType violated the minimum length constraint.")
}
if self.count > 255 {
throw SecurityTokenCodingError.validationError(reason: "The provided value to webIdentitySubjectType violated the maximum length constraint.")
}
}
}
| 33.095327 | 176 | 0.712753 |
4a21944e0da6cbee40697f0832120d22c5b7fb63 | 2,390 | /**
* 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 WatchKit
import Foundation
class RecipeDetailController: WKInterfaceController {
@IBOutlet var table: WKInterfaceTable!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// 1
if let recipe = context as? Recipe {
// 1
let rowTypes: [String] =
["RecipeHeader"] + recipe.steps.map({ _ in "RecipeStep" })
table.setRowTypes(rowTypes)
for i in 0..<table.numberOfRows {
let row = table.rowController(at: i)
if let header = row as? RecipeHeaderController {
header.titleLabel.setText(recipe.name)
// 2
} else if let step = row as? RecipeStepController {
step.stepLabel.setText("\(i). " + recipe.steps[i - 1])
}
}
}
}
}
| 41.206897 | 81 | 0.727615 |
dd6fc5dcabc51b24c33bdfb2ca4257e0bbf9b8ec | 260 | //
// File.swift
//
//
// Created by Wolf McNally on 12/25/21.
//
import Foundation
public enum KeychainError: Error {
case couldNotCreate(Int)
case couldNotRead(Int)
case couldNotUpdate(Int)
case couldNotDelete(Int)
case wrongType
}
| 15.294118 | 40 | 0.676923 |
fe70901978e61c6785a75d7802bb7ec64dbc3932 | 9,091 | import Foundation
/// List of default plugins which will be injected into all MoyaProviders.
public var defaultPlugins: [PluginType] = []
/// Closure to be executed when a request has completed.
public typealias Completion = (_ result: Result<Moya.Response, MoyaError>) -> Void
/// Closure to be executed when progress changes.
public typealias ProgressBlock = (_ progress: ProgressResponse) -> Void
/// A type representing the progress of a request.
public struct ProgressResponse {
/// The optional response of the request.
public let response: Response?
/// An object that conveys ongoing progress for a given request.
public let progressObject: Progress?
/// Initializes a `ProgressResponse`.
public init(progress: Progress? = nil, response: Response? = nil) {
self.progressObject = progress
self.response = response
}
/// The fraction of the overall work completed by the progress object.
public var progress: Double {
if completed {
return 1.0
} else if let progressObject = progressObject, progressObject.totalUnitCount > 0 {
// if the Content-Length is specified we can rely on `fractionCompleted`
return progressObject.fractionCompleted
} else {
// if the Content-Length is not specified, return progress 0.0 until it's completed
return 0.0
}
}
/// A Boolean value stating whether the request is completed.
public var completed: Bool {
return response != nil
}
}
/// A protocol representing a minimal interface for a MoyaProvider.
/// Used by the reactive provider extensions.
public protocol MoyaProviderType: AnyObject {
associatedtype Target: TargetType
/// Designated request-making method. Returns a `Cancellable` token to cancel the request later.
func request(_ target: Target, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable
}
/// Request provider class. Requests should be made through this class only.
open class MoyaProvider<Target: TargetType>: MoyaProviderType {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = (Target) -> Endpoint
/// Closure that decides if and what request should be performed.
public typealias RequestResultClosure = (Result<URLRequest, MoyaError>) -> Void
/// Closure that resolves an `Endpoint` into a `RequestResult`.
public typealias RequestClosure = (Endpoint, @escaping RequestResultClosure) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = (Target) -> Moya.StubBehavior
/// A closure responsible for mapping a `TargetType` to an `EndPoint`.
public let endpointClosure: EndpointClosure
/// A closure deciding if and what request should be performed.
public let requestClosure: RequestClosure
/// A closure responsible for determining the stubbing behavior
/// of a request for a given `TargetType`.
public let stubClosure: StubClosure
public let session: Session
/// A list of plugins.
/// e.g. for logging, network activity indicator or credentials.
public let plugins: [PluginType]
public let trackInflights: Bool
open internal(set) var inflightRequests: [Endpoint: [Moya.Completion]] = [:]
/// Propagated to Alamofire as callback queue. If nil - the Alamofire default (as of their API in 2017 - the main queue) will be used.
let callbackQueue: DispatchQueue?
let lock: NSRecursiveLock = NSRecursiveLock()
/// Initializes a provider.
public init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
callbackQueue: DispatchQueue? = nil,
session: Session = MoyaProvider<Target>.defaultAlamofireSession(),
plugins: [PluginType] = [],
trackInflights: Bool = false) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.session = session
self.plugins = plugins + defaultPlugins
self.trackInflights = trackInflights
self.callbackQueue = callbackQueue
}
/// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`.
open func endpoint(_ token: Target) -> Endpoint {
return endpointClosure(token)
}
/// Designated request-making method. Returns a `Cancellable` token to cancel the request later.
@discardableResult
open func request(_ target: Target,
callbackQueue: DispatchQueue? = .none,
progress: ProgressBlock? = .none,
completion: @escaping Completion) -> Cancellable {
let callbackQueue = callbackQueue ?? self.callbackQueue
return requestNormal(target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
// swiftlint:disable function_parameter_count
/// When overriding this method, call `notifyPluginsOfImpendingStub` to prepare your request
/// and then use the returned `URLRequest` in the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
@discardableResult
open func stubRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, completion: @escaping Moya.Completion, endpoint: Endpoint, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let callbackQueue = callbackQueue ?? self.callbackQueue
let cancellableToken = CancellableToken { }
let preparedRequest = notifyPluginsOfImpendingStub(for: request, target: target)
let plugins = self.plugins
let stub: () -> Void = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins, request: preparedRequest)
switch stubBehavior {
case .immediate:
switch callbackQueue {
case .none:
stub()
case .some(let callbackQueue):
callbackQueue.async(execute: stub)
}
case .delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = DispatchTime.now() + Double(killTimeOffset) / Double(NSEC_PER_SEC)
(callbackQueue ?? DispatchQueue.main).asyncAfter(deadline: killTime) {
stub()
}
case .never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
// swiftlint:enable function_parameter_count
}
// MARK: Stubbing
/// Controls how stub responses are returned.
public enum StubBehavior {
/// Do not stub.
case never
/// Return a response immediately.
case immediate
/// Return a response after a delay.
case delayed(seconds: TimeInterval)
}
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
/// Do not stub.
final class func neverStub(_: Target) -> Moya.StubBehavior {
return .never
}
/// Return a response immediately.
final class func immediatelyStub(_: Target) -> Moya.StubBehavior {
return .immediate
}
/// Return a response after a delay.
final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior {
return { _ in return .delayed(seconds: seconds) }
}
}
/// A public function responsible for converting the result of a `URLRequest` to a Result<Moya.Response, MoyaError>.
public func convertResponseToResult(_ response: HTTPURLResponse?, request: URLRequest?, data: Data?, error: Swift.Error?) ->
Result<Moya.Response, MoyaError> {
switch (response, data, error) {
case let (.some(response), data, .none):
let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response)
return .success(response)
case let (.some(response), _, .some(error)):
let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response)
let error = MoyaError.underlying(error, response)
return .failure(error)
case let (_, _, .some(error)):
let error = MoyaError.underlying(error, nil)
return .failure(error)
default:
let error = MoyaError.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil), nil)
return .failure(error)
}
}
| 41.511416 | 209 | 0.682763 |
eb3836958bb46e5a0499262c0eebe41708bac2d4 | 16,761 | import Foundation
enum PeerMergedOperationLogOperation {
case append(PeerMergedOperationLogEntry)
case remove(tag: PeerOperationLogTag, mergedIndices: Set<Int32>)
case updateContents(PeerMergedOperationLogEntry)
}
public struct PeerMergedOperationLogEntry {
public let peerId: PeerId
public let tag: PeerOperationLogTag
public let tagLocalIndex: Int32
public let mergedIndex: Int32
public let contents: PostboxCoding
}
public enum StorePeerOperationLogEntryTagLocalIndex {
case automatic
case manual(Int32)
}
public enum StorePeerOperationLogEntryTagMergedIndex {
case none
case automatic
}
public struct PeerOperationLogEntry {
public let peerId: PeerId
public let tag: PeerOperationLogTag
public let tagLocalIndex: Int32
public let mergedIndex: Int32?
public let contents: PostboxCoding
public func withUpdatedContents(_ contents: PostboxCoding) -> PeerOperationLogEntry {
return PeerOperationLogEntry(peerId: self.peerId, tag: self.tag, tagLocalIndex: self.tagLocalIndex, mergedIndex: self.mergedIndex, contents: contents)
}
public var mergedEntry: PeerMergedOperationLogEntry? {
if let mergedIndex = self.mergedIndex {
return PeerMergedOperationLogEntry(peerId: self.peerId, tag: self.tag, tagLocalIndex: self.tagLocalIndex, mergedIndex: mergedIndex, contents: self.contents)
} else {
return nil
}
}
}
public struct PeerOperationLogTag: Equatable {
let rawValue: UInt8
public init(value: Int) {
self.rawValue = UInt8(value)
}
public static func ==(lhs: PeerOperationLogTag, rhs: PeerOperationLogTag) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
public enum PeerOperationLogEntryUpdateContents {
case none
case update(PostboxCoding)
}
public enum PeerOperationLogEntryUpdateTagMergedIndex {
case none
case remove
case newAutomatic
}
public struct PeerOperationLogEntryUpdate {
let mergedIndex: PeerOperationLogEntryUpdateTagMergedIndex
let contents: PeerOperationLogEntryUpdateContents
public init(mergedIndex: PeerOperationLogEntryUpdateTagMergedIndex, contents: PeerOperationLogEntryUpdateContents) {
self.mergedIndex = mergedIndex
self.contents = contents
}
}
private func parseEntry(peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ value: ReadBuffer) -> PeerOperationLogEntry? {
var hasMergedIndex: Int8 = 0
value.read(&hasMergedIndex, offset: 0, length: 1)
var mergedIndex: Int32?
if hasMergedIndex != 0 {
var mergedIndexValue: Int32 = 0
value.read(&mergedIndexValue, offset: 0, length: 4)
mergedIndex = mergedIndexValue
}
var contentLength: Int32 = 0
value.read(&contentLength, offset: 0, length: 4)
assert(value.length - value.offset == Int(contentLength))
if let contents = PostboxDecoder(buffer: MemoryBuffer(memory: value.memory.advanced(by: value.offset), capacity: Int(contentLength), length: Int(contentLength), freeWhenDone: false)).decodeRootObject() {
return PeerOperationLogEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, mergedIndex: mergedIndex, contents: contents)
} else {
return nil
}
}
private func parseMergedEntry(peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, _ value: ReadBuffer) -> PeerMergedOperationLogEntry? {
if let entry = parseEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, value), let mergedIndex = entry.mergedIndex {
return PeerMergedOperationLogEntry(peerId: entry.peerId, tag: entry.tag, tagLocalIndex: entry.tagLocalIndex, mergedIndex: mergedIndex, contents: entry.contents)
} else {
return nil
}
}
final class PeerOperationLogTable: Table {
static func tableSpec(_ id: Int32) -> ValueBoxTable {
return ValueBoxTable(id: id, keyType: .binary, compactValuesOnCreation: false)
}
private let metadataTable: PeerOperationLogMetadataTable
private let mergedIndexTable: PeerMergedOperationLogIndexTable
init(valueBox: ValueBox, table: ValueBoxTable, metadataTable: PeerOperationLogMetadataTable, mergedIndexTable: PeerMergedOperationLogIndexTable) {
self.metadataTable = metadataTable
self.mergedIndexTable = mergedIndexTable
super.init(valueBox: valueBox, table: table)
}
private func key(peerId: PeerId, tag: PeerOperationLogTag, index: Int32) -> ValueBoxKey {
let key = ValueBoxKey(length: 8 + 1 + 4)
key.setInt64(0, value: peerId.toInt64())
key.setUInt8(8, value: tag.rawValue)
key.setInt32(9, value: index)
return key
}
func getNextEntryLocalIndex(peerId: PeerId, tag: PeerOperationLogTag) -> Int32 {
return self.metadataTable.getNextLocalIndex(peerId: peerId, tag: tag)
}
func resetIndices(peerId: PeerId, tag: PeerOperationLogTag, nextTagLocalIndex: Int32) {
self.metadataTable.setNextLocalIndex(peerId: peerId, tag: tag, index: nextTagLocalIndex)
}
func addEntry(peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: StorePeerOperationLogEntryTagLocalIndex, tagMergedIndex: StorePeerOperationLogEntryTagMergedIndex, contents: PostboxCoding, operations: inout [PeerMergedOperationLogOperation]) {
let index: Int32
switch tagLocalIndex {
case .automatic:
index = self.metadataTable.takeNextLocalIndex(peerId: peerId, tag: tag)
case let .manual(manualIndex):
index = manualIndex
}
var mergedIndex: Int32?
switch tagMergedIndex {
case .automatic:
mergedIndex = self.mergedIndexTable.add(peerId: peerId, tag: tag, tagLocalIndex: index)
case .none:
break
}
let buffer = WriteBuffer()
var hasMergedIndex: Int8 = mergedIndex != nil ? 1 : 0
buffer.write(&hasMergedIndex, offset: 0, length: 1)
if let mergedIndex = mergedIndex {
var mergedIndexValue: Int32 = mergedIndex
buffer.write(&mergedIndexValue, offset: 0, length: 4)
}
let encoder = PostboxEncoder()
encoder.encodeRootObject(contents)
withExtendedLifetime(encoder, {
let contentBuffer = encoder.readBufferNoCopy()
var contentBufferLength: Int32 = Int32(contentBuffer.length)
buffer.write(&contentBufferLength, offset: 0, length: 4)
buffer.write(contentBuffer.memory, offset: 0, length: contentBuffer.length)
})
self.valueBox.set(self.table, key: self.key(peerId: peerId, tag: tag, index: index), value: buffer)
if let mergedIndex = mergedIndex {
operations.append(.append(PeerMergedOperationLogEntry(peerId: peerId, tag: tag, tagLocalIndex: index, mergedIndex: mergedIndex, contents: contents)))
}
}
func removeEntry(peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex index: Int32, operations: inout [PeerMergedOperationLogOperation]) -> Bool {
var indices: [Int32] = []
var mergedIndices: [Int32] = []
var removed = false
if let value = self.valueBox.get(self.table, key: self.key(peerId: peerId, tag: tag, index: index)) {
indices.append(index)
var hasMergedIndex: Int8 = 0
value.read(&hasMergedIndex, offset: 0, length: 1)
if hasMergedIndex != 0 {
var mergedIndex: Int32 = 0
value.read(&mergedIndex, offset: 0, length: 4)
mergedIndices.append(mergedIndex)
}
removed = true
}
for index in indices {
self.valueBox.remove(self.table, key: self.key(peerId: peerId, tag: tag, index: index), secure: false)
}
if !mergedIndices.isEmpty {
self.mergedIndexTable.remove(tag: tag, mergedIndices: mergedIndices)
operations.append(.remove(tag: tag, mergedIndices: Set(mergedIndices)))
}
return removed
}
func removeAllEntries(peerId: PeerId, tag: PeerOperationLogTag, operations: inout [PeerMergedOperationLogOperation]) {
var indices: [Int32] = []
var mergedIndices: [Int32] = []
self.valueBox.range(self.table, start: self.key(peerId: peerId, tag: tag, index: 0).predecessor, end: self.key(peerId: peerId, tag: tag, index: Int32.max).successor, values: { key, value in
let index = key.getInt32(9)
indices.append(index)
var hasMergedIndex: Int8 = 0
value.read(&hasMergedIndex, offset: 0, length: 1)
if hasMergedIndex != 0 {
var mergedIndex: Int32 = 0
value.read(&mergedIndex, offset: 0, length: 4)
mergedIndices.append(mergedIndex)
}
return true
}, limit: 0)
for index in indices {
self.valueBox.remove(self.table, key: self.key(peerId: peerId, tag: tag, index: index), secure: false)
}
if !mergedIndices.isEmpty {
self.mergedIndexTable.remove(tag: tag, mergedIndices: mergedIndices)
operations.append(.remove(tag: tag, mergedIndices: Set(mergedIndices)))
}
}
func removeEntries(peerId: PeerId, tag: PeerOperationLogTag, withTagLocalIndicesEqualToOrLowerThan maxTagLocalIndex: Int32, operations: inout [PeerMergedOperationLogOperation]) {
var indices: [Int32] = []
var mergedIndices: [Int32] = []
self.valueBox.range(self.table, start: self.key(peerId: peerId, tag: tag, index: 0).predecessor, end: self.key(peerId: peerId, tag: tag, index: maxTagLocalIndex).successor, values: { key, value in
let index = key.getInt32(9)
indices.append(index)
var hasMergedIndex: Int8 = 0
value.read(&hasMergedIndex, offset: 0, length: 1)
if hasMergedIndex != 0 {
var mergedIndex: Int32 = 0
value.read(&mergedIndex, offset: 0, length: 4)
mergedIndices.append(mergedIndex)
}
return true
}, limit: 0)
for index in indices {
self.valueBox.remove(self.table, key: self.key(peerId: peerId, tag: tag, index: index), secure: false)
}
if !mergedIndices.isEmpty {
self.mergedIndexTable.remove(tag: tag, mergedIndices: mergedIndices)
operations.append(.remove(tag: tag, mergedIndices: Set(mergedIndices)))
}
}
func getMergedEntries(tag: PeerOperationLogTag, fromIndex: Int32, limit: Int) -> [PeerMergedOperationLogEntry] {
var entries: [PeerMergedOperationLogEntry] = []
for (peerId, tagLocalIndex, mergedIndex) in self.mergedIndexTable.getTagLocalIndices(tag: tag, fromMergedIndex: fromIndex, limit: limit) {
if let value = self.valueBox.get(self.table, key: self.key(peerId: peerId, tag: tag, index: tagLocalIndex)) {
if let entry = parseMergedEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, value) {
entries.append(entry)
} else {
assertionFailure()
}
} else {
self.mergedIndexTable.remove(tag: tag, mergedIndices: [mergedIndex])
assertionFailure()
}
}
return entries
}
func enumerateEntries(peerId: PeerId, tag: PeerOperationLogTag, _ f: (PeerOperationLogEntry) -> Bool) {
self.valueBox.range(self.table, start: self.key(peerId: peerId, tag: tag, index: 0).predecessor, end: self.key(peerId: peerId, tag: tag, index: Int32.max).successor, values: { key, value in
if let entry = parseEntry(peerId: peerId, tag: tag, tagLocalIndex: key.getInt32(9), value) {
if !f(entry) {
return false
}
} else {
assertionFailure()
}
return true
}, limit: 0)
}
func updateEntry(peerId: PeerId, tag: PeerOperationLogTag, tagLocalIndex: Int32, f: (PeerOperationLogEntry?) -> PeerOperationLogEntryUpdate, operations: inout [PeerMergedOperationLogOperation]) {
let key = self.key(peerId: peerId, tag: tag, index: tagLocalIndex)
if let value = self.valueBox.get(self.table, key: key) {
var hasMergedIndex: Int8 = 0
value.read(&hasMergedIndex, offset: 0, length: 1)
var mergedIndex: Int32?
if hasMergedIndex != 0 {
var mergedIndexValue: Int32 = 0
value.read(&mergedIndexValue, offset: 0, length: 4)
mergedIndex = mergedIndexValue
}
let previousMergedIndex = mergedIndex
var contentLength: Int32 = 0
value.read(&contentLength, offset: 0, length: 4)
assert(value.length - value.offset == Int(contentLength))
if let contents = PostboxDecoder(buffer: MemoryBuffer(memory: value.memory.advanced(by: value.offset), capacity: Int(contentLength), length: Int(contentLength), freeWhenDone: false)).decodeRootObject() {
let entryUpdate = f(PeerOperationLogEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, mergedIndex: mergedIndex, contents: contents))
var updatedContents: PostboxCoding?
switch entryUpdate.contents {
case .none:
break
case let .update(contents):
updatedContents = contents
}
switch entryUpdate.mergedIndex {
case .none:
if let previousMergedIndex = previousMergedIndex, let updatedContents = updatedContents {
operations.append(.updateContents(PeerMergedOperationLogEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, mergedIndex: previousMergedIndex, contents: updatedContents)))
}
case .remove:
if let mergedIndexValue = mergedIndex {
mergedIndex = nil
self.mergedIndexTable.remove(tag: tag, mergedIndices: [mergedIndexValue])
operations.append(.remove(tag: tag, mergedIndices: Set([mergedIndexValue])))
}
case .newAutomatic:
if let mergedIndexValue = mergedIndex {
self.mergedIndexTable.remove(tag: tag, mergedIndices: [mergedIndexValue])
operations.append(.remove(tag: tag, mergedIndices: Set([mergedIndexValue])))
}
let updatedMergedIndexValue = self.mergedIndexTable.add(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex)
mergedIndex = updatedMergedIndexValue
operations.append(.append(PeerMergedOperationLogEntry(peerId: peerId, tag: tag, tagLocalIndex: tagLocalIndex, mergedIndex: updatedMergedIndexValue, contents: updatedContents ?? contents)))
}
if previousMergedIndex != mergedIndex || updatedContents != nil {
let buffer = WriteBuffer()
var hasMergedIndex: Int8 = mergedIndex != nil ? 1 : 0
buffer.write(&hasMergedIndex, offset: 0, length: 1)
if let mergedIndex = mergedIndex {
var mergedIndexValue: Int32 = mergedIndex
buffer.write(&mergedIndexValue, offset: 0, length: 4)
}
let encoder = PostboxEncoder()
if let updatedContents = updatedContents {
encoder.encodeRootObject(updatedContents)
} else {
encoder.encodeRootObject(contents)
}
let contentBuffer = encoder.readBufferNoCopy()
withExtendedLifetime(encoder, {
var contentBufferLength: Int32 = Int32(contentBuffer.length)
buffer.write(&contentBufferLength, offset: 0, length: 4)
buffer.write(contentBuffer.memory, offset: 0, length: contentBuffer.length)
self.valueBox.set(self.table, key: key, value: buffer)
})
}
} else {
assertionFailure()
}
} else {
let _ = f(nil)
}
}
}
| 46.301105 | 253 | 0.626216 |
dbc6a9d1d822b98e35c20b80285a1a92f485cd82 | 694 | import XCTest
@testable import Nanomsg
class PubSubTests: XCTestCase {
let addr = "ipc:///tmp/pubsub.ipc"
func testPubSub() {
let server = try! Socket(.PUB)
_ = try! server.bind(addr)
let client = try! Socket(.SUB)
_ = try! client.connect(addr)
client.sub_subscribe = ""
#if os(OSX)
let msg = "yo"
DispatchQueue(label: "nanomsg").async {
XCTAssertEqual(try! server.send(msg), msg.count + 1)
}
XCTAssertEqual(try! client.recv(), msg)
#endif
}
#if !os(OSX)
static let allTests = [
("testPubSub", testPubSub),
]
#endif
}
| 21.030303 | 68 | 0.523055 |
3a71075f71e2f73471855c1eca291512178096b9 | 633 | //
// SpeedNotificationView.swift
// FIT5140Assignment3iOS
//
// Created by sunkai on 23/10/20.
//
import UIKit
class SpeedNotificationView: UIView {
@IBOutlet weak var speedNotification: UILabel!
override func layoutSubviews() {
super.layoutSubviews()
layer.shadowColor = CGColor.init(srgbRed: 0, green: 0, blue: 0, alpha: 73)
layer.shadowRadius = 4
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowOpacity = 0.7
layer.cornerRadius = bounds.size.width/2
}
func setSpeedNotification(_ speed:String){
speedNotification.text = speed
}
}
| 25.32 | 82 | 0.661927 |
c155e62aa18010bf3cffa2dc570af4c19362cceb | 14,072 | //
// ParameterEncoding.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
/// A type used to define how a set of parameters are applied to a `URLRequest`.
public protocol ParameterEncoding {
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
// MARK: -
/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
/// the HTTP body depends on the destination of the encoding.
///
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
/// `application/x-www-form-urlencoded; charset=utf-8`.
///
/// There is no published specification for how to encode collection types. By default the convention of appending
/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
/// square brackets appended to array keys.
///
/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
/// `true` as 1 and `false` as 0.
public struct URLEncoding: ParameterEncoding {
// MARK: Helper Types
/// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
/// resulting URL request.
///
/// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
/// requests and sets as the HTTP body for requests with any other HTTP method.
/// - queryString: Sets or appends encoded query string result to existing query string.
/// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
public enum Destination {
case methodDependent, queryString, httpBody
}
/// Configures how `Array` parameters are encoded.
///
/// - brackets: An empty set of square brackets is appended to the key for every value.
/// This is the default behavior.
/// - noBrackets: No brackets are appended. The key is encoded as is.
public enum ArrayEncoding {
case brackets, noBrackets
func encode(key: String) -> String {
switch self {
case .brackets:
return "\(key)[]"
case .noBrackets:
return key
}
}
}
/// Configures how `Bool` parameters are encoded.
///
/// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior.
/// - literal: Encode `true` and `false` as string literals.
public enum BoolEncoding {
case numeric, literal
func encode(value: Bool) -> String {
switch self {
case .numeric:
return value ? "1" : "0"
case .literal:
return value ? "true" : "false"
}
}
}
// MARK: Properties
/// Returns a default `URLEncoding` instance.
public static var `default`: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.methodDependent` destination.
public static var methodDependent: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
/// The destination defining where the encoded query string is to be applied to the URL request.
public let destination: Destination
/// The encoding to use for `Array` parameters.
public let arrayEncoding: ArrayEncoding
/// The encoding to use for `Bool` parameters.
public let boolEncoding: BoolEncoding
// MARK: Initialization
/// Creates a `URLEncoding` instance using the specified destination.
///
/// - parameter destination: The destination defining where the encoded query string is to be applied.
/// - parameter arrayEncoding: The encoding to use for `Array` parameters.
/// - parameter boolEncoding: The encoding to use for `Bool` parameters.
///
/// - returns: The new `URLEncoding` instance.
public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) {
self.destination = destination
self.arrayEncoding = arrayEncoding
self.boolEncoding = boolEncoding
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = Data(query(parameters).utf8)
}
return urlRequest
}
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The value of the query component.
///
/// - returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape(boolEncoding.encode(value: bool))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
return string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
switch destination {
case .queryString:
return true
case .httpBody:
return false
default:
break
}
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
}
// MARK: -
/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { return JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates a `JSONEncoding` instance using the specified options.
///
/// - parameter options: The options for writing the parameters as JSON data.
///
/// - returns: The new `JSONEncoding` instance.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
///
/// - parameter urlRequest: The request to apply the JSON object to.
/// - parameter jsonObject: The JSON object to apply to the request.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
| 40.788406 | 143 | 0.654136 |
713a3aed137adacae85f21132a7c034abbc9e3a8 | 7,963 | //: [Previous](@previous)
//: For this page, make sure your build target is set to ParseSwift (macOS) and targeting
//: `My Mac` or whatever the name of your mac is. Also be sure your `Playground Settings`
//: in the `File Inspector` is `Platform = macOS`. This is because
//: Keychain in iOS Playgrounds behaves differently. Every page in Playgrounds should
//: be set to build for `macOS` unless specified.
import PlaygroundSupport
import Foundation
import ParseSwift
PlaygroundPage.current.needsIndefiniteExecution = true
initializeParse()
//: Create your own value typed `ParseObject`.
struct Book: ParseObject, ParseQueryScorable {
//: These are required by ParseObject
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
var score: Double?
var originalData: Data?
//: Your own properties.
var title: String?
var relatedBook: Pointer<Book>?
//: Implement your own version of merge
func merge(with object: Self) throws -> Self {
var updated = try mergeParse(with: object)
if updated.shouldRestoreKey(\.title,
original: object) {
updated.title = object.title
}
if updated.shouldRestoreKey(\.relatedBook,
original: object) {
updated.relatedBook = object.relatedBook
}
return updated
}
}
//: It's recommended to place custom initializers in an extension
//: to preserve the memberwise initializer.
extension Book {
init(title: String) {
self.title = title
}
}
struct Author: ParseObject {
//: These are required by ParseObject.
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
var originalData: Data?
//: Your own properties.
var name: String?
var book: Book?
var otherBooks: [Book]?
//: Implement your own version of merge
func merge(with object: Self) throws -> Self {
var updated = try mergeParse(with: object)
if updated.shouldRestoreKey(\.name,
original: object) {
updated.name = object.name
}
if updated.shouldRestoreKey(\.book,
original: object) {
updated.book = object.book
}
if updated.shouldRestoreKey(\.otherBooks,
original: object) {
updated.otherBooks = object.otherBooks
}
return updated
}
}
//: It's recommended to place custom initializers in an extension
//: to preserve the memberwise initializer.
extension Author {
init(name: String, book: Book) {
self.name = name
self.book = book
}
}
var newBook = Book(title: "hello")
let author = Author(name: "Alice", book: newBook)
author.save { result in
switch result {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
print("Saved \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Pointer array.
let otherBook1 = Book(title: "I like this book")
let otherBook2 = Book(title: "I like this book also")
var author2 = Author(name: "Bruce", book: newBook)
author2.otherBooks = [otherBook1, otherBook2]
author2.save { result in
switch result {
case .success(let savedAuthorAndBook):
assert(savedAuthorAndBook.objectId != nil)
assert(savedAuthorAndBook.createdAt != nil)
assert(savedAuthorAndBook.updatedAt != nil)
assert(savedAuthorAndBook.otherBooks?.count == 2)
//: Notice the pointer objects haven't been updated on the client.
print("Saved \(savedAuthorAndBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
//: Query for your new saved author
let query1 = Author.query("name" == "Bruce")
query1.first { results in
switch results {
case .success(let author):
print("Found author: \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
/*: You will notice in the query above, the fields `book` and `otherBooks` only contain
arrays consisting of key/value pairs of `objectId`. These are called Pointers
in `Parse`.
If you want to retrieve the complete object pointed to in `book`, you need to add
the field names containing the objects specifically in `include` in your query.
*/
/*: Here, we include `book`. If you wanted `book` and `otherBook`, you
could have used: `.include(["book", "otherBook"])`.
*/
let query2 = Author.query("name" == "Bruce")
.include("book")
query2.first { results in
switch results {
case .success(let author):
//: Save the book to use later
if let book = author.book {
newBook = book
}
print("Found author and included \"book\": \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
/*: When you have many fields that are pointing to objects, it may become tedious
to add all of them to the list. You can quickly retreive all pointer objects by
using `includeAll`. You can also use `include("*")` to retrieve all pointer
objects.
*/
let query3 = Author.query("name" == "Bruce")
.includeAll()
query3.first { results in
switch results {
case .success(let author):
print("Found author and included all: \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
//: You can also check if a field is equal to a ParseObject.
do {
let query4 = try Author.query("book" == newBook)
.includeAll()
query4.first { results in
switch results {
case .success(let author):
print("Found author and included all: \(author)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("\(error)")
}
//: Here's an example of saving Pointers as properties.
do {
//: First we query
let query5 = try Author.query("book" == newBook)
.include("book")
query5.first { results in
switch results {
case .success(let author):
print("Found author and included \"book\": \(author)")
//: Setup related books.
var modifiedNewBook = newBook.mergeable
modifiedNewBook.relatedBook = try? author.otherBooks?.first?.toPointer()
modifiedNewBook.save { result in
switch result {
case .success(let updatedBook):
assert(updatedBook.objectId != nil)
assert(updatedBook.createdAt != nil)
assert(updatedBook.updatedAt != nil)
assert(updatedBook.relatedBook != nil)
print("Saved \(updatedBook)")
case .failure(let error):
assertionFailure("Error saving: \(error)")
}
}
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("\(error)")
}
//: Here's an example of querying using matchesText.
do {
let query6 = try Book.query(matchesText(key: "title",
text: "like",
options: [:]))
.include(["*"])
.sortByTextScore()
query6.find { results in
switch results {
case .success(let books):
print("Found books and included all: \(books)")
case .failure(let error):
assertionFailure("Error querying: \(error)")
}
}
} catch {
print("\(error)")
}
PlaygroundPage.current.finishExecution()
//: [Next](@next)
| 29.82397 | 89 | 0.607811 |
2ff7525bb5c8b0d280a827782af8f49f65a0a91d | 374 | //
// Module.swift
// CloudCore
//
// Created by Vasily Ulianov on 14/12/2017.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
/// Enumeration with module name that issued an error in `CloudCoreErrorDelegate`
public enum Module {
/// Save to CloudKit module
case saveToCloud
/// Fetch from CloudKit module
case fetchFromCloud
}
| 17.809524 | 81 | 0.719251 |
189fb9ce5c051a898441942edde2d9cf7242a166 | 4,446 | // Copyright (c) 2016-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import XCTest
@testable import Instructions
class DataSourceCoachMarkAtTest: DataSourceBaseTest,
CoachMarksControllerDataSource,
CoachMarksControllerDelegate {
var delegateEndExpectation: XCTestExpectation?
var numberOfTimesCoachMarkAtWasCalled = 0
var numberOfTimesCoachMarkViewsAtWasCalled = 0
var numberOfTimesConstraintsForSkipViewWasCalled = 0
override func setUp() {
super.setUp()
coachMarksController.dataSource = self
coachMarksController.delegate = self
}
override func tearDown() {
super.tearDown()
delegateEndExpectation = nil
}
func testThatCoachMarkAtIsCalledAtLeastTheNumberOfExpectedTimes() {
delegateEndExpectation = self.expectation(description: "CoachMarkAt")
coachMarksController.start(in: .window(over: parentController))
waitForExpectations(timeout: 2) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testThatCoachMarkViewsAtIsCalledAtLeastTheNumberOfExpectedTimes() {
delegateEndExpectation = self.expectation(description: "CoachMarkViewsAt")
coachMarksController.start(in: .window(over: parentController))
waitForExpectations(timeout: 2) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testThatConstraintsForSkipViewIsCalledAtLeastTheNumberOfExpectedTimes() {
delegateEndExpectation = self.expectation(description: "ConstraintsForSkipView")
coachMarksController.start(in: .window(over: parentController))
waitForExpectations(timeout: 2) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int {
return 4
}
func coachMarksController(_ coachMarksController: CoachMarksController,
coachMarkAt index: Int) -> CoachMark {
numberOfTimesCoachMarkAtWasCalled += 1
return CoachMark()
}
func coachMarksController(
_ coachMarksController: CoachMarksController,
coachMarkViewsAt index: Int,
madeFrom coachMark: CoachMark
) -> (bodyView: (UIView & CoachMarkBodyView), arrowView: (UIView & CoachMarkArrowView)?) {
numberOfTimesCoachMarkViewsAtWasCalled += 1
return (bodyView: CoachMarkBodyDefaultView(), arrowView: nil)
}
func coachMarksController(_ coachMarksController: CoachMarksController,
constraintsForSkipView skipView: UIView,
inParent parentView: UIView) -> [NSLayoutConstraint]? {
numberOfTimesConstraintsForSkipViewWasCalled += 1
return nil
}
func coachMarksController(_ coachMarksController: CoachMarksController,
didShow coachMark: CoachMark,
afterChanging change: ConfigurationChange,
at index: Int) {
if change == .nothing {
coachMarksController.flow.showNext()
}
}
func coachMarksController(_ coachMarksController: CoachMarksController, didEndShowingBySkipping skipped: Bool) {
guard let delegateEndExpectation = self.delegateEndExpectation else {
XCTFail("Undefined expectation")
return
}
if delegateEndExpectation.description == "CoachMarkAt" {
if numberOfTimesCoachMarkAtWasCalled >= 4 {
delegateEndExpectation.fulfill()
return
}
} else if delegateEndExpectation.description == "CoachMarkViewsAt" {
if numberOfTimesCoachMarkViewsAtWasCalled >= 4 {
delegateEndExpectation.fulfill()
return
}
} else if delegateEndExpectation.description == "ConstraintsForSkipView" {
if numberOfTimesCoachMarkViewsAtWasCalled >= 1 {
delegateEndExpectation.fulfill()
return
}
}
XCTFail("Unfulfilled expectation")
}
}
| 36.146341 | 116 | 0.639451 |
1866e527dd2d0978a964457d9fcccb07097eaff9 | 3,580 | //
// MainTableViewController.swift
// WSJ
//
// Created by Nick on 5/13/19.
// Copyright © 2019 NickOwn. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
let viewModel = MainViewModel(Source: .Business)
lazy var loadingIdicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(style: .gray)
indicator.translatesAutoresizingMaskIntoConstraints = false
indicator.hidesWhenStopped = true
return indicator
}()
override func viewDidLoad() {
super.viewDidLoad()
//Setting UIBarButtonItem
let leftButton = UIBarButtonItem(customView: loadingIdicator)
self.navigationItem.setLeftBarButton(leftButton, animated: true)
let rightButton = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(changeSource))
self.navigationItem.setRightBarButton(rightButton, animated: true)
//register tableview cell
self.tableView.register(MainTableViewCell.self, forCellReuseIdentifier: MainTableViewCell.reuseID)
initBinding()
viewModel.start()
}
@objc func changeSource() {
let alertController = UIAlertController(title: "RSS Source", message: nil, preferredStyle: .actionSheet)
for name in WSJRSSSource.allCases {
alertController.addAction(UIAlertAction(title: "\(name)",
style: .default,
handler: { (action) in
self.viewModel.changeSource(source: name)
}))
}
let cancel = UIAlertAction(title: "DISMISS", style: .cancel, handler: nil)
alertController.addAction(cancel)
self.present(alertController, animated: true, completion: nil)
}
func initBinding() {
viewModel.rssItems.addObserver(fireNow: false) { [weak self] ([RSS]) in
self?.tableView.reloadData()
}
viewModel.isTableViewHidden.addObserver { [weak self] (isHidden) in
self?.tableView.isHidden = isHidden
}
viewModel.title.addObserver { [weak self] (title) in
print("now title: \(title)")
self?.navigationItem.title = title
}
viewModel.isLoading.addObserver { [weak self] (isLoading) in
if isLoading {
self?.loadingIdicator.startAnimating()
} else {
self?.loadingIdicator.stopAnimating()
}
}
}
}
extension MainTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.rssItems.value.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MainTableViewCell.reuseID, for: indexPath) as? MainTableViewCell ?? MainTableViewCell()
cell.setup(feed: viewModel.rssItems.value[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row < viewModel.rssItems.value.count {
let webVC = webviewViewController()
webVC.weburl = URL(string: viewModel.rssItems.value[indexPath.row].link)!
self.navigationController?.pushViewController(webVC, animated: true)
}
}
}
| 33.457944 | 152 | 0.632123 |
bf83f83f32a187c09047cb6338b06503535e02ff | 989 | //
// ATAlertViewTests.swift
// ATAlertViewTests
//
// Created by Thang Nguyen on 2018/05/24.
// Copyright © 2018 Thang Nguyen. All rights reserved.
//
import XCTest
@testable import ATAlertView
class ATAlertViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.72973 | 111 | 0.639029 |
1698fd4d6a31a5ed357233c9d5997791944ad7f4 | 4,701 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
@testable import AWSS3StoragePlugin
import Amplify
class StorageRequestUtilsValidatorTests: XCTestCase {
let testIdentityId = "TestIdentityId"
let testTargetIdentityId = "TestTargetIdentityId"
let testKey = "TestKey"
let testPath = "TestPath"
let testContentType = "TestContentType"
// MARK: ValidateTargetIdentityId tests
func testValidateTargetIdentityIdForEmptyTargetIdentityIdSuccess() {
let result = StorageRequestUtils.validateTargetIdentityId(nil, accessLevel: .guest)
XCTAssertNil(result)
}
func testValidateTargetIdentityIdWithPublicAccessLevelReturnsError() {
let result = StorageRequestUtils.validateTargetIdentityId(testIdentityId, accessLevel: .guest)
XCTAssertNotNil(result)
XCTAssertTrue(result!
.errorDescription
.contains(StorageErrorConstants.invalidAccessLevelWithTarget.errorDescription))
}
func testValidateTargetIdentityIdWithProtectedAccessLevelSuccess() {
let result = StorageRequestUtils.validateTargetIdentityId(testIdentityId, accessLevel: .protected)
XCTAssertNil(result)
}
func testValidateTargetIdentityIdWithPrivateAccessLevelReturnsError() {
let result = StorageRequestUtils.validateTargetIdentityId(testIdentityId, accessLevel: .private)
XCTAssertNotNil(result)
XCTAssertTrue(result!
.errorDescription
.contains(StorageErrorConstants.invalidAccessLevelWithTarget.errorDescription))
}
func testValidateTargetIdentityIdForEmpyTargetIdReturnsError() {
let result = StorageRequestUtils.validateTargetIdentityId("", accessLevel: .guest)
XCTAssertNotNil(result)
XCTAssertTrue(result!.errorDescription.contains(StorageErrorConstants.identityIdIsEmpty.errorDescription))
}
// MARK: ValidateKey tests
func testValidateKeySuccess() {
let result = StorageRequestUtils.validateKey(testKey)
XCTAssertNil(result)
}
func testValidateKeyForEmptyKeyReturnsError() {
let result = StorageRequestUtils.validateKey("")
XCTAssertNotNil(result)
XCTAssertTrue(result!.errorDescription.contains(StorageErrorConstants.keyIsEmpty.errorDescription))
}
// MARK: ValidatePath tests
func testValidatePathSuccess() {
let result = StorageRequestUtils.validatePath(testPath)
XCTAssertNil(result)
}
func testValidatePathForEmptyPathReturnsError() {
let result = StorageRequestUtils.validatePath("")
XCTAssertNotNil(result)
XCTAssertTrue(result!.errorDescription.contains(StorageErrorConstants.pathIsEmpty.errorDescription))
}
// MARK: ValidateContentType tests
func testValidateContentTypeSuccess() {
let result = StorageRequestUtils.validateContentType(testContentType)
XCTAssertNil(result)
}
func testValidateContentTypeForEmptyContentTypeReturnsError() {
let result = StorageRequestUtils.validateContentType("")
XCTAssertNotNil(result)
XCTAssertTrue(result!.errorDescription.contains(StorageErrorConstants.contentTypeIsEmpty.errorDescription))
}
// MARK: ValidateMetadata tests
func testValidateMetadataSuccess() {
let metadata = ["key1": "value1", "key2": "value2"]
let result = StorageRequestUtils.validateMetadata(metadata)
XCTAssertNil(result)
}
func testValidateMetadataWithNonLowercasedKeysReturnsError() {
let metadata = ["NonLowerCasedKey": "value1"]
let result = StorageRequestUtils.validateMetadata(metadata)
XCTAssertNotNil(result)
XCTAssertTrue(result!.errorDescription.contains(StorageErrorConstants.metadataKeysInvalid.errorDescription))
}
// MARK: ValidateFileExists tests
func testValidateFileExistsForUrlSuccess() {
let key = "testValidateFileExistsForUrlSuccess"
let filePath = NSTemporaryDirectory() + key + ".tmp"
let fileURL = URL(fileURLWithPath: filePath)
FileManager.default.createFile(atPath: filePath, contents: key.data(using: .utf8), attributes: nil)
let result = StorageRequestUtils.validateFileExists(fileURL)
XCTAssertNil(result)
}
func testValidateFileExistsForEmptyFileReturnsError() {
let fileURL = URL(fileURLWithPath: "path")
let result = StorageRequestUtils.validateFileExists(fileURL)
XCTAssertNotNil(result)
XCTAssertTrue(result!.errorDescription.contains(StorageErrorConstants.localFileNotFound.errorDescription))
}
}
| 37.015748 | 116 | 0.738141 |
e028750f34b3d370b0fb70c3a9e30da1fbb51705 | 15,256 | /*
* Copyright (c) 2015 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.
*
* 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 Photos
import Firebase
import JSQMessagesViewController
final class ChatViewController: JSQMessagesViewController {
// MARK: Properties
fileprivate let imageURLNotSetKey = "NOTSET"
var channelRef: FIRDatabaseReference?
fileprivate lazy var messageRef: FIRDatabaseReference = self.channelRef!.child("messages")
fileprivate lazy var storageRef: FIRStorageReference = FIRStorage.storage().reference(forURL: "gs://chatting-5191e.appspot.com")
fileprivate lazy var userIsTypingRef: FIRDatabaseReference = self.channelRef!.child("typingIndicator").child(self.senderId)
fileprivate lazy var usersTypingQuery: FIRDatabaseQuery = self.channelRef!.child("typingIndicator").queryOrderedByValue().queryEqual(toValue: true)
fileprivate var newMessageRefHandle: FIRDatabaseHandle?
fileprivate var updatedMessageRefHandle: FIRDatabaseHandle?
fileprivate var messages: [JSQMessage] = []
fileprivate var photoMessageMap = [String: JSQPhotoMediaItem]()
fileprivate var localTyping = false
var channel: Channel? {
didSet {
title = channel?.name
}
}
var isTyping: Bool {
get {
return localTyping
}
set {
localTyping = newValue
userIsTypingRef.setValue(newValue)
}
}
lazy var outgoingBubbleImageView: JSQMessagesBubbleImage = self.setupOutgoingBubble()
lazy var incomingBubbleImageView: JSQMessagesBubbleImage = self.setupIncomingBubble()
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.senderId = FIRAuth.auth()?.currentUser?.uid
observeMessages()
// No avatars
collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero
collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
observeTyping()
}
deinit {
if let refHandle = newMessageRefHandle {
messageRef.removeObserver(withHandle: refHandle)
}
if let refHandle = updatedMessageRefHandle {
messageRef.removeObserver(withHandle: refHandle)
}
}
func observeTyping() {
let typingIndicatorRef = channelRef!.child("typingIndicator")
userIsTypingRef = typingIndicatorRef.child(senderId)
userIsTypingRef.onDisconnectRemoveValue()
usersTypingQuery = typingIndicatorRef.queryOrderedByValue().queryEqual(toValue: true)
usersTypingQuery.observe(.value) { (data: FIRDataSnapshot) in
// You're the only typing, don't show the indicator
if data.childrenCount == 1 && self.isTyping {
return
}
// Are there others typing?
self.showTypingIndicator = data.childrenCount > 0
self.scrollToBottom(animated: true)
}
}
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
// 1
let itemRef = messageRef.childByAutoId()
// 2
let messageItem = [
"senderId": senderId!,
"senderName": senderDisplayName!,
"text": text!,
]
// 3
itemRef.setValue(messageItem)
// 4
JSQSystemSoundPlayer.jsq_playMessageSentSound()
// 5
finishSendingMessage()
isTyping = false
}
func setImageURL(_ url: String, forPhotoMessageWithKey key: String) {
let itemRef = messageRef.child(key)
itemRef.updateChildValues(["photoURL": url])
}
}
// MARK: UITextViewDelegate methods
extension ChatViewController {
override func textViewDidChange(_ textView: UITextView) {
super.textViewDidChange(textView)
// If the text is not empty, the user is typing
isTyping = textView.text != ""
}
}
// MARK: Firebase related methods
extension ChatViewController {
func observeMessages() {
messageRef = channelRef!.child("messages")
let messageQuery = messageRef.queryLimited(toLast:25)
// We can use the observe method to listen for new
// messages being written to the Firebase DB
newMessageRefHandle = messageQuery.observe(.childAdded, with: { (snapshot) -> Void in
self.scrollToBottom(animated: true)
let messageData = snapshot.value as! Dictionary<String, String>
guard let id = messageData["senderId"] else {
print("Error! Could not decode message data")
return
}
if let name = messageData["senderName"], let text = messageData["text"], text.characters.count > 0 {
self.addMessage(withId: id, name: name, text: text)
self.finishReceivingMessage()
} else if let photoURL = messageData["photoURL"] {
guard let mediaItem = JSQPhotoMediaItem(maskAsOutgoing: id == self.senderId) else {
return
}
self.addPhotoMessage(withId: id, key: snapshot.key, mediaItem: mediaItem)
if photoURL.hasPrefix("gs://") {
self.fetchImageDataAtURL(photoURL, forMediaItem: mediaItem, clearsPhotoMessageMapOnSuccessForKey: nil)
}
}
})
// We can also use the observer method to listen for
// changes to existing messages.
// We use this to be notified when a photo has been stored
// to the Firebase Storage, so we can update the message data
updatedMessageRefHandle = messageRef.observe(.childChanged, with: { (snapshot) in
self.scrollToBottom(animated: true)
let key = snapshot.key
let messageData = snapshot.value as! Dictionary<String, String>
if let photoURL = messageData["photoURL"], let mediaItem = self.photoMessageMap[key] {
// The photo has been updated.
self.fetchImageDataAtURL(photoURL, forMediaItem: mediaItem, clearsPhotoMessageMapOnSuccessForKey: key)
}
})
}
func addMessage(withId id: String, name: String, text: String) {
if let message = JSQMessage(senderId: id, displayName: name, text: text) {
messages.append(message)
}
}
func addPhotoMessage(withId id: String, key: String, mediaItem: JSQPhotoMediaItem) {
if let message = JSQMessage(senderId: id, displayName: "", media: mediaItem) {
messages.append(message)
if (mediaItem.image == nil) {
photoMessageMap[key] = mediaItem
}
collectionView.reloadData()
}
}
func sendPhotoMessage() -> String? {
let itemRef = messageRef.childByAutoId()
let messageItem = [
"photoURL": imageURLNotSetKey,
"senderId": senderId!,
]
itemRef.setValue(messageItem)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
finishSendingMessage()
return itemRef.key
}
}
// MARK: Collection view data source (and related) methods
extension ChatViewController {
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
return messages[indexPath.item]
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let message = messages[indexPath.item] // 1
if message.senderId == senderId { // 2
return outgoingBubbleImageView
} else { // 3
return incomingBubbleImageView
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
let message = messages[indexPath.item]
if message.senderId == senderId { // 1
cell.textView?.textColor = UIColor.white // 2
} else {
cell.textView?.textColor = UIColor.black // 3
}
return cell
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
return nil
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat {
return 15
}
override func collectionView(_ collectionView: JSQMessagesCollectionView?, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString? {
let message = messages[indexPath.item]
switch message.senderId {
case senderId:
return nil
default:
guard let senderDisplayName = message.senderDisplayName else {
assertionFailure()
return nil
}
return NSAttributedString(string: senderDisplayName)
}
}
}
extension ChatViewController {
func fetchImageDataAtURL(_ photoURL: String, forMediaItem mediaItem: JSQPhotoMediaItem, clearsPhotoMessageMapOnSuccessForKey key: String?) {
let storageRef = FIRStorage.storage().reference(forURL: photoURL)
storageRef.data(withMaxSize: INT64_MAX){ (data, error) in
if let error = error {
print("Error downloading image data: \(error)")
return
}
guard let data = data else { return }
storageRef.metadata(completion: { (metadata, metadataErr) in
if let error = metadataErr {
print("Error downloading metadata: \(error)")
return
}
mediaItem.image = metadata?.contentType == "image/gif" ? UIImage.gifWithData(data) : UIImage.init(data: data)
self.collectionView.reloadData()
guard let key = key else { return }
self.photoMessageMap.removeValue(forKey: key)
})
}
}
}
// MARK: UI and User Interaction
extension ChatViewController {
func setupOutgoingBubble() -> JSQMessagesBubbleImage {
let bubbleImageFactory = JSQMessagesBubbleImageFactory()
return bubbleImageFactory!.outgoingMessagesBubbleImage(with: UIColor.jsq_messageBubbleBlue())
}
func setupIncomingBubble() -> JSQMessagesBubbleImage {
let bubbleImageFactory = JSQMessagesBubbleImageFactory()
return bubbleImageFactory!.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray())
}
override func didPressAccessoryButton(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
// if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {
// picker.sourceType = UIImagePickerControllerSourceType.camera
// } else {
// picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
// }
present(picker, animated: true, completion:nil)
}
}
// MARK: Image Picker Delegate
extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion:nil)
guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }
// 1
guard let photoReferenceUrl = info[UIImagePickerControllerReferenceURL] as? URL else { return }
print(photoReferenceUrl.absoluteString)
// Handle picking a Photo from the Photo Library
// 2
let assets = PHAsset.fetchAssets(withALAssetURLs: [photoReferenceUrl], options: nil)
guard let asset = assets.firstObject else { return }
// 3
guard let key = sendPhotoMessage() else { return }
// 4
PHImageManager.default().requestImageData(for: asset, options: nil) { (imageData, dataUTI, orientation, info) in
guard let imageData = imageData else { return }
let path = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\(photoReferenceUrl.lastPathComponent)"
self.storageRef.child(path).put(imageData, metadata: nil, completion: { (metadata, error) in
if let error = error {
print("Error uploading photo: \(error.localizedDescription)")
return
}
guard let path = metadata?.path else { return }
// 7
self.setImageURL(self.storageRef.child(path).description, forPhotoMessageWithKey: key)
})
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
}
| 38.235589 | 214 | 0.631424 |
b912dd1f914041f0971ac8cc5f03f11991bd6664 | 1,425 | //
// GameViewController.swift
// Game
//
// Created by Marc O'Morain on 12/11/2015.
// Copyright (c) 2015 CircleCI. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .aspectFill
skView.presentScene(scene)
print("takasi")
}
}
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden : Bool {
return true
}
}
| 25.446429 | 94 | 0.594386 |
e5ff1e653de02b19698cd2e6662092491e4ec51d | 804 | // Copyright 2019 Hotspring Ventures Ltd.
//
// 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 UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityIdentifier = Accessibility.Home.mainView
}
}
| 33.5 | 76 | 0.733831 |
90ca0d1862cd7d0f992dd2ebbe08a460a808a2a0 | 2,680 | /*
* --------------------------------------------------------------------------------
* <copyright company="Aspose" file="TabStopsResponse.swift">
* Copyright (c) 2020 Aspose.Words for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------
*/
import Foundation
// The REST response with an array of tab stops.
public class TabStopsResponse : WordsResponse {
// Field of tabStops. The REST response with an array of tab stops.
private var tabStops : [TabStop]?;
private enum CodingKeys: String, CodingKey {
case tabStops = "TabStops";
case invalidCodingKey;
}
public override init() {
super.init();
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder);
let container = try decoder.container(keyedBy: CodingKeys.self);
self.tabStops = try container.decodeIfPresent([TabStop].self, forKey: .tabStops);
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder);
var container = encoder.container(keyedBy: CodingKeys.self);
if (self.tabStops != nil) {
try container.encode(self.tabStops, forKey: .tabStops);
}
}
// Sets tabStops. Gets or sets the array of tab stops.
public func setTabStops(tabStops : [TabStop]?) {
self.tabStops = tabStops;
}
// Gets tabStops. Gets or sets the array of tab stops.
public func getTabStops() -> [TabStop]? {
return self.tabStops;
}
}
| 39.411765 | 89 | 0.65 |
ffaed245e738a2075a96082e27be311bbd0758f3 | 877 | //
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import firebase_analytics
import firebase_core
import firebase_crashlytics
import path_provider_macos
import share_plus_macos
import url_launcher_macos
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FLTFirebaseAnalyticsPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseAnalyticsPlugin"))
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
FLTFirebaseCrashlyticsPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCrashlyticsPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
}
| 38.130435 | 108 | 0.844926 |
48cec04be591e5b6e8fbd150d06dc1b27b1399ca | 7,501 | //
// ChatVC.swift
// UniSpace
//
// Created by KiKan Ng on 7/3/2019.
// Copyright © 2019 KiKan Ng. All rights reserved.
//
import UIKit
import MessageKit
import MessageInputBar
/// A base class for the example controllers
class ChatVC: MessagesViewController, MessagesDataSource {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
var messageList: [MockMessage] = []
let refreshControl = UIRefreshControl()
let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
configureMessageCollectionView()
configureMessageInputBar()
loadFirstMessages()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MockSocket.shared.connect(messageId: -1, with: [])
.onNewMessages { [weak self] messages in
for message in messages {
self?.insertMessage(message)
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
MockSocket.shared.disconnect()
}
func loadFirstMessages() {
DispatchQueue.global(qos: .userInitiated).async {
let count = 20
SampleData.shared.getMessages(count: count) { messages in
DispatchQueue.main.async {
self.messageList = messages
self.messagesCollectionView.reloadData()
self.messagesCollectionView.scrollToBottom()
}
}
}
}
@objc
func loadMoreMessages() {
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
SampleData.shared.getMessages(count: 20) { messages in
DispatchQueue.main.async {
self.messageList.insert(contentsOf: messages, at: 0)
self.messagesCollectionView.reloadDataAndKeepOffset()
self.refreshControl.endRefreshing()
}
}
}
}
func configureMessageCollectionView() {
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messageCellDelegate = self
scrollsToBottomOnKeyboardBeginsEditing = true // default false
maintainPositionOnKeyboardFrameChanged = true // default false
messagesCollectionView.addSubview(refreshControl)
refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
}
func configureMessageInputBar() {
messageInputBar.delegate = self
messageInputBar.inputTextView.tintColor = Color.theme
messageInputBar.sendButton.tintColor = Color.theme
}
// MARK: - Helpers
func insertMessage(_ message: MockMessage) {
messageList.append(message)
// Reload last section to update header/footer labels and insert a new one
messagesCollectionView.performBatchUpdates({
messagesCollectionView.insertSections([messageList.count - 1])
if messageList.count >= 2 {
messagesCollectionView.reloadSections([messageList.count - 2])
}
}, completion: { [weak self] _ in
if self?.isLastSectionVisible() == true {
self?.messagesCollectionView.scrollToBottom(animated: true)
}
})
}
func isLastSectionVisible() -> Bool {
guard !messageList.isEmpty else { return false }
let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
}
// MARK: - MessagesDataSource
func currentSender() -> Sender {
return SampleData.shared.currentSender
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
return messageList.count
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
return messageList[indexPath.section]
}
func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if indexPath.section % 3 == 0 {
return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor: UIColor.darkGray])
}
return nil
}
func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let name = message.sender.displayName
return NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1)])
}
func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
let dateString = formatter.string(from: message.sentDate)
return NSAttributedString(string: dateString, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
}
}
// MARK: - MessageCellDelegate
extension ChatVC: MessageCellDelegate {
func didTapAvatar(in cell: MessageCollectionViewCell) {
print("Avatar tapped")
}
func didTapMessage(in cell: MessageCollectionViewCell) {
print("Message tapped")
}
func didTapCellTopLabel(in cell: MessageCollectionViewCell) {
print("Top cell label tapped")
}
func didTapMessageTopLabel(in cell: MessageCollectionViewCell) {
print("Top message label tapped")
}
func didTapMessageBottomLabel(in cell: MessageCollectionViewCell) {
print("Bottom label tapped")
}
func didTapAccessoryView(in cell: MessageCollectionViewCell) {
print("Accessory view tapped")
}
}
// MARK: - MessageLabelDelegate
extension ChatVC: MessageLabelDelegate {
func didSelectAddress(_ addressComponents: [String: String]) {
print("Address Selected: \(addressComponents)")
}
func didSelectDate(_ date: Date) {
print("Date Selected: \(date)")
}
func didSelectPhoneNumber(_ phoneNumber: String) {
print("Phone Number Selected: \(phoneNumber)")
}
func didSelectURL(_ url: URL) {
print("URL Selected: \(url)")
}
func didSelectTransitInformation(_ transitInformation: [String: String]) {
print("TransitInformation Selected: \(transitInformation)")
}
}
// MARK: - MessageInputBarDelegate
extension ChatVC: MessageInputBarDelegate {
@objc func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
for component in inputBar.inputTextView.components {
if let str = component as? String {
let message = MockMessage(text: str, sender: currentSender(), messageId: UUID().uuidString, date: Date())
insertMessage(message)
} else if let img = component as? UIImage {
let message = MockMessage(image: img, sender: currentSender(), messageId: UUID().uuidString, date: Date())
insertMessage(message)
}
}
inputBar.inputTextView.text = String()
messagesCollectionView.scrollToBottom(animated: true)
}
}
| 31.783898 | 244 | 0.660579 |
4bc1bf9477731686405c5554361ef7db7269a724 | 30,125 | //
// GRMustacheTest.swift
// CDAKit
//
// Created by Eric Whitley on 12/17/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import XCTest
@testable import CDAKit
import Mustache
class GRMustacheTest: XCTestCase {
let data = [
"name": "Arthur",
"date": NSDate(),
"realDate": NSDate().dateByAddingTimeInterval(60*60*24*3),
"late": true
]
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRawSwiftString() {
do {
let template = try Template(string: "Hello {{name}}")
let rendering = try template.render(Box(data))
XCTAssertEqual("Hello Arthur", rendering)
}
catch let error as MustacheError {
// Parse error at line 2 of template /path/to/template.mustache:
// Unclosed Mustache tag.
error.description
// TemplateNotFound, ParseError, or RenderError
error.kind
// The eventual template at the source of the error. Can be a path, a URL,
// a resource name, depending on the repository data source.
error.templateID
// The eventual faulty line.
error.lineNumber
// The eventual underlying error.
error.underlyingError
} catch {
//ehhhh
}
}
func testBundleResource() {
do {
let template = try Template(named: "document")
let rendering = try template.render(Box(data))
print(rendering)
// XCTAssertEqual("Hello Arthur", rendering)
} catch {
print("testBundleResource failed")
}
}
func testFileWithFile() {
do {
let bundle = NSBundle(forClass: self.dynamicType)
let path = bundle.pathForResource("document", ofType: "mustache")
let template = try Template(path: path!)
// Let template format dates with `{{format(...)}}`
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
template.registerInBaseContext("format", Box(dateFormatter))
let rendering = try template.render(Box(data))
print(rendering)
// XCTAssertEqual("Hello Arthur", rendering)
} catch {
print("testFileWithFile failed")
}
}
func testFileWithURL() {
do {
let templateURL = NSURL(fileURLWithPath: "document.mustache")
let template = try Template(URL: templateURL)
let rendering = try template.render(Box(data))
print(rendering)
// XCTAssertEqual("Hello Arthur", rendering)
} catch {
print("testFileWithURL failed")
}
}
// class UUIDGenerator: NSNumberFormatter {
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
//
// override init() {
// super.init()
// self.locale = NSLocale.currentLocale()
// self.maximumFractionDigits = 2
// self.minimumFractionDigits = 2
// self.alwaysShowsDecimalSeparator = true
// self.numberStyle = .CurrencyStyle
// }
//
// static let sharedInstance = UUIDGenerator()
// }
public class UUIDGenerator: MustacheBoxable {
// required init?(coder aDecoder: NSCoder) {
// //super.init(value: aDecoder)
// }
//
// init() {
// }
// var mustacheBox: MustacheBox {
// return Box(NSUUID().UUIDString)
// }
// public var mustacheBox: MustacheBox {
// return MustacheBox(
// value: NSUUID().UUIDString
// )
// }
public var mustacheBox: MustacheBox {
return Box(NSUUID().UUIDString)
}
static let sharedInstance = UUIDGenerator()
}
func testCustomNumberFormatter() {
//let uuid = NSUUID().UUIDString
let percentFormatter = NSNumberFormatter()
percentFormatter.numberStyle = .PercentStyle
do {
let template = try Template(string: "{{ percent(x) }}")
template.registerInBaseContext("percent", Box(percentFormatter))
// Rendering: 50%
let data = ["x": 0.5]
let rendering = try template.render(Box(data))
print(rendering)
XCTAssertEqual(rendering, "50%")
}
catch {
}
}
// func testCustomFunction() {
//
// let x = UUIDGenerator()
// print("x = \(x)")
// print("x.mustacheBox = \(x.mustacheBox)")
//
// do {
// let template = try Template(string: "{{ uuid_generate() }}")
// template.registerInBaseContext("uuid_generate", Box(UUIDGenerator()))
//
// // Rendering: 50%
// let data = ["x": 0.5]
// let rendering = try template.render(Box(data))
// print("rendering!")
// print(rendering)
// //XCTAssertEqual(rendering, "50%")
// }
// catch let error as NSError {
// print(error.localizedDescription)
// }
//
// }
func testFilter() {
let reverse = Filter { (rendering: Rendering) in
let reversedString = String(rendering.string.characters.reverse())
return Rendering(reversedString, rendering.contentType)
}
// let UUID_generate = Filter { (value: Any? ) in
// let uuid_string = NSUUID().UUIDString
// return Box(uuid_string)
// }
do {
// Register the reverse filter in our template:
// let template = try Template(string: "{{reverse(value)}}")
// template.registerInBaseContext("reverse", Box(reverse))
let template = try Template(string: "{{ UUID_generate(nil) }}")
template.registerInBaseContext("UUID_generate", Box(MustacheFilters.UUID_generate))
// Rendering: 50%
let data = ["x": 0.5]
let rendering = try template.render(Box(data))
print("rendering!")
print(rendering)
//XCTAssertEqual(rendering, "50%")
}
catch let error as NSError {
print(error.localizedDescription)
}
}
func testDateFilter() {
let DateAsNumber = Filter { (box: MustacheBox) in
if box.value == nil {
return Box(NSDate().stringFormattedAsHDSDateNumber)
}
switch box.value {
case let int as Int:
print("I'm an Int")
let d = NSDate(timeIntervalSince1970: Double(int))
return Box(d.stringFormattedAsHDSDateNumber)
case let double as Double:
print("I'm a double")
let d = NSDate(timeIntervalSince1970: double)
return Box(d.stringFormattedAsHDSDateNumber)
case let date as NSDate:
print("I'm a date")
return Box(date.stringFormattedAsHDSDateNumber)
default:
// GRMustache does not support any other numeric types: give up.
print("I'm of type \(box.value.dynamicType)")
return Box()
}
}
do {
let template = try Template(string: "Date: {{ date_as_number(x) }}, Int: {{date_as_number(y)}} , Double: {{ date_as_number(z) }}, nil: {{ date_as_number(nil) }}")
template.registerInBaseContext("date_as_number", Box(MustacheFilters.DateAsNumber))
let data = ["x": NSDate(), "y":Int(NSDate().timeIntervalSince1970), "z":NSDate().timeIntervalSince1970]
let rendering = try template.render(Box(data))
print(rendering)
}
catch let error as NSError {
print(error.localizedDescription)
}
}
func testCodeDisplayFilter() {
//code_display(entry, {'tag_name' => 'value', 'extra_content' => 'xsi:type="CD"', 'preferred_code_sets' => ['SNOMED-CT']})
// let code_display = VariadicFilter { (boxes: [MustacheBox]) in
// var result = ""
// for box in boxes {
// //sum += (box.value as? Int) ?? 0
// //result += "\(box.value.dynamicType) = \(box.value)\n"
// result += "\(box.value)\n"
// }
// return Box(result)
// }
func convertStringToDictionary(text: String) -> [String:Any] {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
var otherJson: [String:Any] = [:]
if let json = json {
for(key, value) in json {
otherJson[key] = (value as Any)
}
}
return otherJson
} catch let error as NSError {
print(error.localizedDescription)
}
}
return [:]
}
let code_display = Filter { (box: MustacheBox, info: RenderingInfo) in
let args = info.tag.innerTemplateString
var opts: [String:Any] = [:]
opts = convertStringToDictionary(args)
print("Got ops for ... \n \(opts) \n")
var out = ""
print("box = \(box)")
if let entry = box.value as? CDAKEntry {
out = ViewHelper.code_display(entry, options: opts)
} else {
print("couldn't cast entry")
print("entry = '\(box.value)'")
}
return Rendering(out)
}
do {
let template = try Template(string: "code_display = {{# code_display(x)}}{\"tag_name\":\"value\",\"extra_content\":\"xsi:type=CD\",\"preferred_code_sets\":[\"SNOMED-CT\"]}{{/ }}")
template.registerInBaseContext("code_display", Box(code_display))
let entry = CDAKEntry()
entry.time = 1270598400
entry.add_code("314443004", code_system: "SNOMED-CT")
let data = ["entry": entry]
let rendering = try template.render(Box(data))
print("trying to render...")
print(rendering)
print("rendering complete.")
}
catch let error as NSError {
print(error.localizedDescription)
}
}
func testDictionaryEachTemplate() {
do {
let entry = CDAKEntry()
entry.time = 1270598400
entry.add_code("314443004", code_system: "SNOMED-CT")
entry.add_code("123345344", code_system: "SNOMED-CT")
entry.add_code("345345345", code_system: "SNOMED-CT")
entry.add_code("ABCSDFDFS", code_system: "LOINC")
let template = try Template(string: "time:{{entry.time}} codes:{{#each(entry.codes)}}{{@key}} {{#each(.)}} {{.}} {{/}} {{/}}")
//each(entry.codes)
let data = ["entry": entry]
template.registerInBaseContext("each", Box(StandardLibrary.each))
let rendering = try template.render(Box(data))
print("trying to render...")
print(rendering)
print("rendering complete.")
}
catch let error as MustacheError {
print("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
}
catch let error as NSError {
print(error.localizedDescription)
}
}
func testCodeDisplayFilter2() {
do {
//triple mustache tags to disable escaping
let template = try Template(string: "code_display = {{{code_display}}}")
let entry = CDAKEntry()
entry.time = 1270598400
entry.add_code("314443004", code_system: "SNOMED-CT")
let opts : [String:Any] = [
"tag_name":"value",
"extra_content": "xsi:type=\"CD\"",
"preferred_code_sets" : ["SNOMED-CT"]
]
let data = ["code_display": ViewHelper.code_display(entry, options: opts)]
let rendering = try template.render(Box(data))
print("trying to render...")
print(rendering)
print("rendering complete.")
}
catch let error as MustacheError {
fatalError("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
}
catch let error as NSError {
print(error.localizedDescription)
}
}
var bigTestRecord: CDAKRecord {
let entry = CDAKEntry()
entry.time = 1270598400
entry.add_code("314443004", code_system: "SNOMED-CT")
entry.add_code("123345344", code_system: "SNOMED-CT")
entry.add_code("345345345", code_system: "SNOMED-CT")
entry.add_code("ABCSDFDFS", code_system: "LOINC")
let testRecord = TestRecord()
let record: CDAKRecord = testRecord.bigger_record()
record.first = "Steven"
record.last = "Smith"
record.gender = "female"
record.telecoms.append(CDAKTelecom(use: "Home", value: "(123)456-7890"))
record.telecoms.append(CDAKTelecom(use: "Work", value: "(987)654-3210"))
record.addresses.append(CDAKAddress(street: ["123 My Street","Unit xyz"], city: "Chicago", state: "IL", zip: "12345", country: "USA", use: "Home"))
record.addresses.append(CDAKAddress(street: ["One Derful Way"], city: "Kadavu", state: "IL", zip: "99999", country: "Fiji", use: "Vacation"))
record.allergies.append(CDAKAllergy(event: ["time": 1270598400, "codes":["SNOMED-CT":["xyz", "abc"]], "description": "my first allergy" ]))
record.allergies.append(CDAKAllergy(event: ["time": 1270597400, "codes":["LOINC":["987"]], "description": "my second allergy", "specifics": "specific2" ]))
record.allergies.append(CDAKAllergy(event: ["time": 1270597400, "codes":["RxNorm":["987"]], "description": "my third allergy", "specifics": "specific3" ]))
let lr = CDAKLabResult(event: ["time": 1270598400, "codes":["LOINC":["xyz", "abc"]], "description": "my first lab result" ])
// in case you want to test the other result value template info
// lr.values.append(PhysicalQuantityResultValue(scalar: nil, units: "imanilvalue"))
// lr.values.append(PhysicalQuantityResultValue(scalar: "left", units: "imastring"))
// lr.values.append(PhysicalQuantityResultValue(scalar: true, units: "imabool"))
lr.values.append(CDAKPhysicalQuantityResultValue(scalar: 6, units: "inches"))
lr.values.append(CDAKPhysicalQuantityResultValue(scalar: 12.2, units: "liters"))
lr.values.append(CDAKPhysicalQuantityResultValue(scalar: -3.333, units: "hectares"))
record.results.append(lr)
return record
}
func testPartialTemplate() {
do {
//set this BEFORE you create the template
// disables all HTML escaping
// Mustache.DefaultConfiguration.contentType = .Text
let bundle = NSBundle(forClass: self.dynamicType)
let path = bundle.pathForResource("record", ofType: "mustache")
let template = try Template(path: path!)
let data = ["patient": bigTestRecord]
// USE: telecoms:{{#each(patient.telecoms)}} hi {{value}} {{use}} {{/}}
template.registerInBaseContext("each", Box(StandardLibrary.each))
// USE: {{ UUID_generate(nil) }}
template.registerInBaseContext("UUID_generate", Box(MustacheFilters.UUID_generate))
// USE: {{ date_as_number(z) }}, nil: {{ date_as_number(nil) }}
template.registerInBaseContext("date_as_number", Box(MustacheFilters.DateAsNumber))
// USE: {{ value_or_null_flavor(entry.as_point_in_time) }}
template.registerInBaseContext("value_or_null_flavor", Box(MustacheFilters.value_or_null_flavor))
template.registerInBaseContext("oid_for_code_system", Box(MustacheFilters.oid_for_code_system))
template.registerInBaseContext("is_numeric", Box(MustacheFilters.is_numeric))
template.registerInBaseContext("is_bool", Box(MustacheFilters.is_bool))
//Removing this registration
// keep to show how you can abuse things
// USE code_display = {{# code_display(x)}}{\"tag_name\":\"value\",\"extra_content\":\"xsi:type=CD\",\"preferred_code_sets\":[\"SNOMED-CT\"]}{{/ }}
//template.registerInBaseContext("code_display", Box(MustacheFilters.codeDisplayForEntry))
//configuration.contentType = .Text
//template.contentType = .Text
//codeDisplayForEntry
let rendering = try template.render(Box(data))
print("trying to render...")
print("======================")
print(rendering)
print("======================")
print("rendering complete.")
}
catch let error as MustacheError {
print("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
}
catch let error as NSError {
print(error.localizedDescription)
}
}
// func testWithTemplateGenerator() {
//
// let template_helper = CDAKTemplateHelper(template_format: "c32", template_subdir: "c32", template_directory: nil)
// let template = template_helper.template("show")
//
// let data = ["patient": bigTestRecord]
//
// // USE: telecoms:{{#each(patient.telecoms)}} hi {{value}} {{use}} {{/}}
// template.registerInBaseContext("each", Box(StandardLibrary.each))
// // USE: {{ UUID_generate(nil) }}
// template.registerInBaseContext("UUID_generate", Box(MustacheFilters.UUID_generate))
// // USE: {{ date_as_number(z) }}, nil: {{ date_as_number(nil) }}
// template.registerInBaseContext("date_as_number", Box(MustacheFilters.DateAsNumber))
// // USE: {{ value_or_null_flavor(entry.as_point_in_time) }}
// template.registerInBaseContext("value_or_null_flavor", Box(MustacheFilters.value_or_null_flavor))
// template.registerInBaseContext("oid_for_code_system", Box(MustacheFilters.oid_for_code_system))
// template.registerInBaseContext("is_numeric", Box(MustacheFilters.is_numeric))
// template.registerInBaseContext("is_bool", Box(MustacheFilters.is_bool))
//
//
// do {
// let rendering = try template.render(Box(data))
//
// print("trying to render...")
// print("======================")
// print(rendering)
// print("======================")
// print("rendering complete.")
// }
// catch let error as MustacheError {
// print("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
// }
// catch let error as NSError {
// print(error.localizedDescription)
// }
//
//// let str = "{\"name\":\"James\"}"
////
//// let result = convertStringToDictionary(str) // ["name": "James"]
//
//
// }
func transformAnyObjectDict(dict: [String:AnyObject]) -> [String:Any?] {
var otherJson: [String:Any?] = [:]
for(key, value) in dict {
if let value = value as? [String:AnyObject] {
//print("converting json dict for key: \(key)")
otherJson[key] = transformAnyObjectDict(value)
} else if let value = value as? [AnyObject] {
var values = [Any]()
for v in value {
if let v = v as? [String:AnyObject] {
//print("going to try to convert nested for key: \(key)")
values.append(transformAnyObjectDict(v))
} else {
//print("appending array entry for key: \(key)")
values.append(v as Any)
}
}
otherJson[key] = values
}
else {
otherJson[key] = (value as Any)
}
//we need to do the whole thing
}
return otherJson
}
// func testLoadFileFromPath() {
//
// let json_files : [String] = [
//// "506afdf87042f9e32c000069", //Mary Berry
//// "506afdf87042f9e32c000001", //Barry Berry
// "4dcbecdb431a5f5878000004" //Rosa Vasquez
// ]
//
// let format = "c32"
//
// for json_file in json_files {
// let json = loadJSONFromBundleFile(json_file)
// if let json = json {
//
// var otherJson: [String:Any?] = [:]
// otherJson = transformAnyObjectDict(json)
// let test_record = CDAKRecord(event: otherJson)
//// print(test_record)
//
//
//
// let template_helper = CDAKTemplateHelper(template_format: format, template_subdir: format, template_directory: nil)
// let template = template_helper.template("show")
//
// let data = ["patient": test_record]
//
// // USE: telecoms:{{#each(patient.telecoms)}} hi {{value}} {{use}} {{/}}
// template.registerInBaseContext("each", Box(StandardLibrary.each))
// // USE: {{ UUID_generate(nil) }}
// template.registerInBaseContext("UUID_generate", Box(MustacheFilters.UUID_generate))
// // USE: {{ date_as_number(z) }}, nil: {{ date_as_number(nil) }}
// template.registerInBaseContext("date_as_number", Box(MustacheFilters.DateAsNumber))
// template.registerInBaseContext("date_as_string", Box(MustacheFilters.DateAsHDSString))
//
// // USE: {{ value_or_null_flavor(entry.as_point_in_time) }}
// template.registerInBaseContext("value_or_null_flavor", Box(MustacheFilters.value_or_null_flavor))
// template.registerInBaseContext("oid_for_code_system", Box(MustacheFilters.oid_for_code_system))
// template.registerInBaseContext("is_numeric", Box(MustacheFilters.is_numeric))
// template.registerInBaseContext("is_bool", Box(MustacheFilters.is_bool))
//
//
// do {
// let rendering = try template.render(Box(data))
//
// print("trying to render...")
// print("======================")
// print(rendering)
// print("======================")
// print("rendering complete.")
// }
// catch let error as MustacheError {
// print("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
// }
// catch let error as NSError {
// print(error.localizedDescription)
// }
//
//
//
// }
// }
//
// }
func loadJSONFromBundleFile(filename: String) -> [String:AnyObject]? {
let fileName = "\(filename)"
let directory: String? = nil
let bundle = NSBundle(forClass: self.dynamicType)
//NSBundle.mainBundle()
guard let filePath = bundle.pathForResource(fileName, ofType: "json", inDirectory: directory) else {
fatalError("Failed to find file '\(fileName)' in path '\(directory)' ")
}
let templateURL = NSURL(fileURLWithPath: filePath)
if let data = NSData(contentsOfURL: templateURL) {
return convertDataToDictionary(data)
}
return nil
}
//http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
// do {
// let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
// return json
// }
// catch let error as NSError {
// print(error.localizedDescription)
// }
return convertDataToDictionary(data)
}
return nil
}
func convertDataToDictionary(data: NSData) -> [String:AnyObject]? {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
return json
}
catch let error as NSError {
print(error.localizedDescription)
}
return nil
}
func testHeaderInC32() {
let doc = TestHelpers.fileHelpers.load_xml_string_from_file("Patient-673")
do {
let record = try CDAKImport_BulkRecordImporter.importRecord(doc)
//record.header = nil
let x = record.export(inFormat: .c32)
// let x = record.export(inFormat: .ccda)
print(x)
}
catch {
}
}
func testHeaderInCCDA() {
let doc = TestHelpers.fileHelpers.load_xml_string_from_file("Patient-673")
do {
let record = try CDAKImport_BulkRecordImporter.importRecord(doc)
//record.header = nil
let x = record.export(inFormat: .ccda)
// let x = record.export(inFormat: .ccda)
print(x)
}
catch {
}
}
func testGlobalHeaderAcrossRecords() {
var header: CDAKQRDAHeader?
var records: [CDAKRecord] = []
var files: [String] = ["Patient-673", "Vitera_CCDA_SMART_Sample", "export_cda"]
for file in files {
let doc = TestHelpers.fileHelpers.load_xml_string_from_file(file)
do {
let record = try CDAKImport_BulkRecordImporter.importRecord(doc)
records.append(record)
if records.count == 1 {
header = record.header
} else {
record.header = header
}
}
catch {
}
}
for record in records {
XCTAssertEqual(record.header?.description, header?.description)
//print(record.export(inFormat: .ccda))
}
}
func testViteraImport() {
let doc = TestHelpers.fileHelpers.load_xml_string_from_file("Vitera_CCDA_SMART_Sample")
do {
let record = try CDAKImport_BulkRecordImporter.importRecord(doc)
//record.header = nil
// for encounter in record.encounters {
// print(encounter.performer)
// }
//let x = record.export(inFormat: .ccda)
let x = record.export(inFormat: .c32)
print(x)
}
catch {
}
}
func testTemplatesFromDifferentDirectories() {
let doc = TestHelpers.fileHelpers.load_xml_string_from_file("Patient-673")
do {
let record = try CDAKImport_BulkRecordImporter.importRecord(doc)
// print(record.header?.json)
// let repo = TemplateRepository(
// bundle: CDAKCommonUtility.bundle,
// templateExtension: "mustache")
let repo = TemplateRepository(bundle: CDAKCommonUtility.bundle)
// print(CDAKCommonUtility.bundle)
// let filemanager:NSFileManager = NSFileManager()
// let files = filemanager.enumeratorAtPath(CDAKCommonUtility.bundle.bundlePath)
// while let file = files?.nextObject() {
// print(file)
// }
// let enumerator = NSFileManager.defaultManager().enumeratorAtPath(CDAKCommonUtility.bundle.bundlePath)
// var filePaths = [NSURL]()
//
// while let filePath = enumerator?.nextObject() as? String {
// print(filePath)
// }
// let repo = TemplateRepository(directoryPath: "/health-data-standards/templates")
// let repo = TemplateRepository(bundle: NSBundle.mainBundle())
// let repo = TemplateRepository(bundle: NSBundle(forClass: self.dynamicType))
//NSBundle.mainBundle()
// print(repo)
let format = "c32"
//c32_show.c32.mustache
// let template_name = "\(format)_show.\(format).mustache"
let template_name = "c32_show.c32"
do {
// let template = try repo.template(named: "health-data-standards/templates/\(format)/\(format)_show.\(format)")
let template = try repo.template(named: template_name)
let data = ["patient": record]
template.registerInBaseContext("each", Box(StandardLibrary.each))
template.registerInBaseContext("UUID_generate", Box(MustacheFilters.UUID_generate))
template.registerInBaseContext("date_as_number", Box(MustacheFilters.DateAsNumber))
template.registerInBaseContext("date_as_string", Box(MustacheFilters.DateAsHDSString))
template.registerInBaseContext("value_or_null_flavor", Box(MustacheFilters.value_or_null_flavor))
template.registerInBaseContext("oid_for_code_system", Box(MustacheFilters.oid_for_code_system))
template.registerInBaseContext("is_numeric", Box(MustacheFilters.is_numeric))
template.registerInBaseContext("is_bool", Box(MustacheFilters.is_bool))
do {
let rendering = try template.render(Box(data))
print("trying to render...")
print("======================")
print(rendering)
print("======================")
print("rendering complete.")
}
catch let error as MustacheError {
print("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
}
catch let error as NSError {
print(error.localizedDescription)
}
}
catch {
print("no template found '\(template_name)'")
}
// let template_helper = CDAKTemplateHelper(template_format: "c32", template_subdir: "c32", template_directory: nil)
// let template = template_helper.template("show")
}
catch {
XCTFail()
}
}
// func testHeaderGeneration() {
// let doc = TestHelpers.fileHelpers.load_xml_string_from_file("Patient-673")
// do {
// let record = try CDAKImport_BulkRecordImporter.importRecord(doc)
//
// let template_helper = CDAKTemplateHelper(template_format: "cat1", template_subdir: "cat1", template_directory: nil)
// let template = template_helper.template("header")
//
// record.header = nil
//
// let data = ["patient": record]
//
// template.registerInBaseContext("each", Box(StandardLibrary.each))
// template.registerInBaseContext("UUID_generate", Box(MustacheFilters.UUID_generate))
// template.registerInBaseContext("date_as_number", Box(MustacheFilters.DateAsNumber))
// template.registerInBaseContext("date_as_string", Box(MustacheFilters.DateAsHDSString))
// template.registerInBaseContext("value_or_null_flavor", Box(MustacheFilters.value_or_null_flavor))
// template.registerInBaseContext("oid_for_code_system", Box(MustacheFilters.oid_for_code_system))
// template.registerInBaseContext("is_numeric", Box(MustacheFilters.is_numeric))
// template.registerInBaseContext("is_bool", Box(MustacheFilters.is_bool))
//
//
// do {
// let rendering = try template.render(Box(data))
//
// print("trying to render...")
// print("======================")
// print(rendering)
// print("======================")
// print("rendering complete.")
// }
// catch let error as MustacheError {
// print("Failed to process template. Line \(error.lineNumber) - \(error.kind). Error: \(error.description)")
// }
// catch let error as NSError {
// print(error.localizedDescription)
// }
//
//
//
// }
// catch {
// XCTFail()
// }
// }
}
| 33.068057 | 185 | 0.614705 |
218e8e5bfa822024d52e9be730b31a8362cb73ec | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
class A {
func b
struct B<I :
let d: p
let a {
struct c<T where T.f : P {
var b : B
var b
| 19.214286 | 87 | 0.70632 |
ff45ec8812ae6f616eeefb21716f0ac66be091f7 | 26,598 | //
// HostControllerCommand.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 3/23/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/**
The Controller & Baseband Commands provide access and control to various capabilities of the Bluetooth hardware. These parameters provide control of BR/EDR Controllers and of the capabilities of the Link Manager and Baseband in the BR/EDR Controller, the PAL in an AMP Controller, and the Link Layer in an LE Controller. The Host can use these commands to modify the behavior of the local Controller.
*/
public enum HostControllerBasebandCommand: UInt16, HCICommand {
public static let opcodeGroupField = HCIOpcodeGroupField.hostControllerBaseband
/// Set Event Mask
///
/// Used to control which events are generated by the HCI for the Host.
case setEventMask = 0x0001
/**
Reset Command
The Reset command will reset the Controller and the Link Manager on the BR/ EDR Controller, the PAL on an AMP Controller, or the Link Layer on an LE Controller. If the Controller supports both BR/EDR and LE then the Reset command shall reset the Link Manager, Baseband and Link Layer. The Reset command shall not affect the used HCI transport layer since the HCI transport layers may have reset mechanisms of their own. After the reset is completed, the current operational state will be lost, the Controller will enter standby mode and the Controller will automatically revert to the default values for the parameters for which default values are defined in the specification.
- Note: The Reset command will not necessarily perform a hardware reset. This is implementation defined. On an AMP Controller, the Reset command shall reset the service provided at the logical HCI to its initial state, but beyond this the exact effect on the Controller device is implementation defined and should not interrupt the service provided to other protocol stacks.
The Host shall not send additional HCI commands before the Command Complete event related to the Reset command has been received.
*/
case reset = 0x0003
/**
Set Event Filter Command
Used by the Host to specify different event filters.
The Host may issue this command multiple times to request various conditions for the same type of event filter and for different types of event filters. The event filters are used by the Host to specify items of interest, which allow the BR/EDR Controller to send only events which interest the Host. Only some of the events have event filters. By default (before this command has been issued after power-on or Reset) no filters are set, and the Auto_Accept_Flag is off (incoming connections are not automatically accepted). An event filter is added each time this command is sent from the Host and the Filter_Condition_Type is not equal to 0x00. (The old event filters will not be overwritten). To clear all event filters, the Filter_Type = 0x00 is used. The Auto_Accept_Flag will then be set to off. To clear event filters for only a certain Filter_Type, the Filter_Condition_Type = 0x00 is used.
The Inquiry Result filter allows the BR/EDR Controller to filter out Inquiry Result, Inquiry Result with RSSI, or Extended Inquiry Result events. The Inquiry Result filter allows the Host to specify that the BR/EDR Controller only sends Inquiry Results to the Host if the report meets one of the specified conditions set by the Host. For the Inquiry Result filter, the Host can specify one or more of the following Filter Condition Types:
1. Return responses from all devices during the Inquiry process
2. A device with a specific Class of Device responded to the Inquiry process 3. A device with a specific BD_ADDR responded to the Inquiry process
The Inquiry Result filter is used in conjunction with the Inquiry and Periodic Inquiry command.
The Connection Setup filter allows the Host to specify that the Controller only sends a Connection Complete or Connection Request event to the Host if the event meets one of the specified conditions set by the Host. For the Connection Setup filter, the Host can specify one or more of the following Filter Condition Types:
1. Allow Connections from all devices
2. Allow Connections from a device with a specific Class of Device 3. Allow Connections from a device with a specific BD_ADDR
For each of these conditions, an Auto_Accept_Flag parameter allows the Host to specify what action should be done when the condition is met. The Auto_ Accept_Flag allows the Host to specify if the incoming connection should be auto accepted (in which case the BR/EDR Controller will send the Connection Complete event to the Host when the connection is completed) or if the Host should make the decision (in which case the BR/EDR Controller will send the Connection Request event to the Host, to elicit a decision on the connection).
The Connection Setup filter is used in conjunction with the Read/Write_ Scan_Enable commands. If the local device is in the process of a page scan, and is paged by another device which meets one on the conditions set by the Host, and the Auto_Accept_Flag is off for this device, then a Connection Request event will be sent to the Host by the BR/EDR Controller. A Connection Complete event will be sent later on after the Host has responded to the incoming connection attempt. In this same example, if the Auto_Accept_Flag is on, then a Connection Complete event will be sent to the Host by the Controller. (No Connection Request event will be sent in that case.)
The BR/EDR Controller will store these filters in volatile memory until the Host clears the event filters using the Set_Event_Filter command or until the Reset command is issued. The number of event filters the BR/EDR Controller can store is implementation dependent. If the Host tries to set more filters than the BR/EDR Controller can store, the BR/EDR Controller will return the Memory Full error code and the filter will not be installed.
- Note: The Clear All Filters has no Filter Condition Types or Conditions.
- Note: In the condition that a connection is auto accepted, a Link Key Request event and possibly also a PIN Code Request event and a Link Key Notification event could be sent to the Host by the Controller before the Connection Complete event is sent.
If there is a contradiction between event filters, the latest set event filter will override older ones. An example is an incoming connection attempt where more than one Connection Setup filter matches the incoming connection attempt, but the Auto-Accept_Flag has different values in the different filters.
*/
case setEventFilter = 0x0005
/// Flush Command
///
/// The Flush command is used to discard all data that is currently pending for transmission in the Controller for the specified Connection_Handle
case flush = 0x0008
/// Read PIN Type Command
///
/// The Read_PIN_Type command is used to read the PIN_Type configuration parameter.
case readPINType = 0x0009
/// Write PIN Type Command
///
/// The Write_PIN_Type command is used to write the PIN Type configuration parameter.
case writePINType = 0x000A
/// Create New Unit Key Command
///
/// The Create_New_Unit_Key command is used to create a new unit key.
case createNewUnitKey = 0x000B
/// Read Stored Link Key Command
///
/// The Read_Stored_Link_Key command provides the ability to read whether one or more link keys are stored in the BR/EDR Controller.
case readStoredLinkKey = 0x000D
/// Write Stored Link Key Command
///
/// The Write_Stored_Link_Key command provides the ability to write one or more link keys to be stored in the BR/EDR Controller.
case writeStoredLinkKey = 0x0011
/// Delete Stored Link Key Command
///
/// The Delete_Stored_Link_Key command provides the ability to remove one or more of the link keys stored in the BR/EDR Controller.
case deleteStoredLinkKey = 0x0012
/// Write Local Name Command
///
/// The Write Local Name command provides the ability to modify the user-friendly name for the BR/EDR Controller.
case writeLocalName = 0x0013
/// Read Local Name Command
///
/// The Read Local Name command provides the ability to read the stored user- friendly name for the BR/EDR Controller.
case readLocalName = 0x0014
/// Read Connection Accept Timeout Command
///
/// This command reads the value for the Connection Accept Timeout configuration parameter.
case readConnectionAcceptTimeout = 0x0015
/// Write Connection Accept Timeout Command
///
/// This command writes the value for the Connection Accept Timeout configuration parameter.
case writeConnectionAcceptTimeout = 0x0016
/// Read Page Timeout Command
///
/// This command reads the value for the Page_Timeout configuration parameter.
case readPageTimeout = 0x0017
/// Write Page Timeout Command
///
/// This command writes the value for the Page_Timeout configuration parameter.
case writePageTimeout = 0x0018
/// Read Scan Enable Command
///
/// This command reads the value for the Scan_Enable parameter configuration parameter.
case readScanEnable = 0x0019
/// Write Scan Enable Command
///
/// This command writes the value for the Scan_Enable configuration parameter.
case writeScanEnable = 0x001A
/// Read Page Scan Activity Command
///
/// This command reads the value for Page_Scan_Interval and Page_Scan_Window configuration parameters.
case readPageScanActivity = 0x001B
/// Write Page Scan Activity Command
///
/// This command writes the values for the Page_Scan_Interval and Page_Scan_Window configuration parameters.
case writePageScanActivity = 0x001C
/// Read Inquiry Scan Activity Command
///
/// This command reads the value for Inquiry_Scan_Interval and Inquiry_Scan_Window configuration parameter.
case readInquiryScanActivity = 0x001D
/// Write Inquiry Scan Activity Command
///
/// This command writes the values for the Inquiry_Scan_Interval and Inquiry_Scan_Window configuration parameters.
case writeInquiryScanActivity = 0x001E
/// Read Authentication Enable Command
///
/// This command reads the value for the Authentication_Enable configuration parameter.
case readAuthenticationEnable = 0x001F
/// Write Authentication Enable Command
///
/// This command writes the value for the Authentication_Enable configuration parameter.
case writeAuthenticationEnable = 0x0020
/// Read Class of Device Command
///
/// This command reads the value for the Class_of_Device parameter.
case readClassOfDevice = 0x0023
/// Write Class of Device Command
///
/// This command writes the value for the Class_of_Device parameter.
case writeClassOfDevice = 0x0024
/// Read Voice Setting Command
///
/// This command reads the values for the Voice_Setting configuration parameter.
case readVoiceSetting = 0x0025
/// Write Voice Setting Command
///
/// This command writes the values for the Voice_Setting configuration parameter.
case writeVoiceSetting = 0x0026
/// Read Automatic Flush Timeout Command
///
/// This command reads the value for the Flush_Timeout parameter for the specified Connection_Handle.
case readAutomaticFlushTimeout = 0x0027
/// Write Automatic Flush Timeout Command
///
/// This command writes the value for the Flush_Timeout parameter for the speci- fied Connection_Handle
case writeAutomaticFlushTimeout = 0x0028
/// Read Num Broadcast Retransmissions Command
///
/// This command reads the device’s parameter value for the Number of Broadcast Retransmissions.
case readNumBroadcastRetransmissions = 0x0029
/// Write Num Broadcast Retransmissions Command
///
/// This command writes the device’s parameter value for the Number of Broadcast Retransmissions.
case writeNumBroadcastRetransmissions = 0x002A
/// Read Hold Mode Activity Command
///
/// This command reads the value for the Hold_Mode_Activity parameter.
case readHoldModeActivity = 0x002B
/// Write Hold Mode Activity Command
///
/// This command writes the value for the Hold_Mode_Activity parameter.
case writeHoldModeActivity = 0x002C
/// Read Transmit Power Level Command
///
/// This command reads the values for the Transmit_Power_Level parameter for the specified Connection_Handle.
case readTransmitPowerLevel = 0x002D
/// Read Synchronous Flow Control Enable Command
///
/// The Read_Synchronous_Flow_Control_Enable command provides the ability to read the Synchronous_Flow_Control_Enable parameter.
case readSynchronousFlowControlEnable = 0x002E
/// Write Synchronous Flow Control Enable Command
///
/// The Write_Synchronous_Flow_Control_Enable command provides the ability to write the Synchronous_Flow_Control_Enable parameter.
case writeSynchronousFlowControlEnable = 0x002F
/// Set Controller To Host Flow Control Command
///
/// This command is used by the Host to turn flow control on or off for data and/or voice sent in the direction from the Controller to the Host.
case setControllerToHostFlowControl = 0x0031
/// Host Buffer Size Command
///
/// The Host_Buffer_Size command is used by the Host to notify the Controller about the maximum size of the data portion of HCI ACL and synchronous Data Packets sent from the Controller to the Host.
case hostBufferSize = 0x0033
/// Host Number Of Completed Packets Command
///
/// The Host_Number_Of_Completed_Packets command is used by the Host to indicate to the Controller the number of HCI Data Packets that have been com- pleted for each Connection Handle since the previous Host_Number_Of_ Completed_Packets command was sent to the Controller.
case hostNumberOfCompletedPackets = 0x0035
/// Read Link Supervision Timeout Command
///
/// This command reads the value for the Link_Supervision_Timeout parameter for the Controller.
case readLinkSupervisionTimeout = 0x0036
/// Write Link Supervision Timeout Command
///
/// This command writes the value for the Link_Supervision_Timeout parameter for a BR/EDR or AMP Controller.
case writeLinkSupervisionTimeout = 0x0037
/// Read Number Of Supported IAC Command
///
/// This command reads the value for the number of Inquiry Access Codes (IAC) that the local BR/EDR Controller can simultaneous listen for during an Inquiry Scan.
case readNumberOfSupportedIAC = 0x0038
/// Read Current IAC LAP Command
///
/// This command reads the LAP(s) used to create the Inquiry Access Codes (IAC) that the local BR/EDR Controller is simultaneously scanning for during Inquiry Scans.
case readCurrentIACLAP = 0x0039
/// Write Current IAC LAP Command
///
/// This command writes the LAP(s) used to create the Inquiry Access Codes (IAC) that the local BR/EDR Controller is simultaneously scanning for during Inquiry Scans.
case writeCurrentIACLAP = 0x003A
/// Set AFH Host Channel Classification Command
///
/// The Set_AFH_Host_Channel_Classification command allows the Host to specify a channel classification based on its “local information”.
case setAFHHostChannelClassification = 0x003F
/// Read Inquiry Scan Type Command
///
/// This command reads the Inquiry_Scan_Type configuration parameter from the local BR/EDR Controller.
case readInquiryScanType = 0x0042
/// Write Inquiry Scan Type Command
///
/// This command writes the Inquiry Scan Type configuration parameter of the local BR/EDR Controller.
case writeInquiryScanType = 0x0043
/// Read Inquiry Mode Command
///
/// This command reads the Inquiry_Mode configuration parameter of the local BR/EDR Controller.
case readInquiryMode = 0x0044
/// Write Inquiry Mode Command
///
/// This command writes the Inquiry_Mode configuration parameter of the local BR/EDR Controller.
case writeInquiryMode = 0x0045
/// Read Page Scan Type Command
///
/// This command reads the Page Scan Type configuration parameter of the local BR/EDR Controller.
case readPageScanType = 0x0046
/// Write Page Scan Type Command
///
/// This command writes the Page Scan Type configuration parameter of the local BR/EDR Controller.
case writePageScanType = 0x0047
/// Read AFH Channel Assessment Mode Command
///
/// The Read_AFH_Channel_Assessment_Mode command reads the value for the AFH_Channel_Assessment_Mode parameter.
case readAFHChannelAssessmentMode = 0x0048
/// Write AFH Channel Assessment Mode Command
///
/// The Write_AFH_Channel_Assessment_Mode command writes the value for the AFH_Channel_Assessment_Mode parameter.
case writeAFHChannelAssessmentMode = 0x0049
/// Read Extended Inquiry Response Command
///
/// The Read_Extended_Inquiry_Response command reads the extended inquiry response to be sent during the extended inquiry response procedure.
case readExtendedInquiryResponse = 0x0051
/// Write Extended Inquiry Response Command
///
/// The Write_Extended_Inquiry_Response command writes the extended inquiry response to be sent during the extended inquiry response procedure.
case writeExtendedInquiryResponse = 0x0052
/// Refresh Encryption Key Command
///
/// This command is used by the Host to cause the BR/EDR Controller to refresh the encryption key by pausing and resuming encryption.
case refreshEncryptionKey = 0x0053
/// Read Simple Pairing Mode Command
///
/// This command reads the Simple_Pairing_Mode parameter in the BR/EDR Controller.
case readSimplePairingMode = 0x0055
/// Write Simple Pairing Mode Command
///
/// This command enables Simple Pairing mode in the BR/EDR Controller.
case writeSimplePairingMode = 0x0056
/// Read Local OOB Data Command
///
/// This command obtains a Simple Pairing Hash C and Simple Pairing Randomizer R which are intended to be transferred to a remote device using an OOB mechanism.
case readLocalOOBData = 0x0057
/// Read Inquiry Response Transmit Power Level Command
///
/// This command reads the inquiry Transmit Power level used to transmit the FHS and EIR data packets.
case readInquiryResponseTransmitPowerLevel = 0x0058
/// Write Inquiry Transmit Power Level Command
///
/// This command writes the inquiry transmit power level used to transmit the inquiry (ID) data packets.
case writeInquiryResponseTransmitPowerLevel = 0x0059
/// Send Keypress Notification Command
///
/// This command is used during the Passkey Entry protocol by a device with Key- boardOnly IO capabilities
case sendKeypressNotification = 0x0060
/// Read Default Erroneous Data Reporting
///
/// This command reads the Erroneous_Data_Reporting parameter
case readDefaultErroneousData = 0x005A
/// Write Default Erroneous Data Reporting
///
/// This command writes the Erroneous_Data_Reporting parameter.
case writeDefaultErroneousData = 0x005B
/// Enhanced Flush Command
///
/// The Enhanced_Flush command is used to discard all L2CAP packets identified by Packet_Type that are currently pending for transmission in the Controller for the specified Handle
case enhancedFlush = 0x005F
/// Read Logical Link Accept Timeout Command
///
/// This command reads the value for the Logical_Link_Accept_Timeout configuration parameter.
case readLogicalLinkAcceptTimeout = 0x0061
/// Write Logical Link Accept Timeout Command
///
/// This command writes the value for the Logical_Link_Accept_Timeout configuration parameter. See Logical Link Accept Timeout.
case writeLogicalLinkAcceptTimeout = 0x0062
/// Set Event Mask Page 2 Command
///
/// The Set_Event_Mask_Page_2 command is used to control which events are generated by the HCI for the Host
case setEventMaskPage2 = 0x0063
/// Read Location Data Command
///
/// The Read_Location_Data command provides the ability to read any stored knowledge of environment or regulations or currently in use in the AMP Con- troller.
case readLocationData = 0x0064
/// Write Location Data Command
///
/// The Write_Location_Data command writes information about the environment or regulations currently in force, which may affect the operation of the Control- ler.
case writeLocationData = 0x0065
/// Read Flow Control Mode Command
///
/// This command reads the value for the Flow_Control_Mode configuration parameter.
case readFlowControlMode = 0x0066
/// Write Flow Control Mode Command
///
/// This command writes the value for the Flow_Control_Mode configuration parameter.
case writeFlowControlMode = 0x0067
/// Read Enhanced Transmit Power Level Command
///
/// This command reads the values for the Enhanced_Transmit_Power_Level parameters for the specified Connection Handle
case radEnhancedTransmitPowerLevel = 0x0068
/// Read Best Effort Flush Timeout Command
///
/// This command reads the value of the Best Effort Flush Timeout from the AMP Controller.
case readBestEffortFlushTimeout = 0x0069
/// Write Best Effort Flush Timeout Command
///
/// This command writes the value of the Best_Effort_Flush_Timeout into the AMP Controller.
case writeBestEffortFlushTimeout = 0x006A
/// Short Range Mode Command
///
/// This command will configure the value of Short_Range_Mode to the AMP Controller and is AMP type specific
case shortRangeMode = 0x006B
/// Read LE Host Supported Command
///
/// The Read_LE_Host_Support command is used to read the LE Supported (Host) and Simultaneous LE and BR/EDR to Same Device Capable (Host) Link Manager Protocol feature bits.
case readLEHostSupported = 0x006C
/// Write LE Host Supported Command
///
/// The Write_LE_Host_Support command is used to set the LE Supported (Host) and Simultaneous LE and BR/EDR to Same Device Capable (Host) Link Man- ager Protocol feature bits.
case writeLEHostSupported = 0x006D
}
// MARK: - Name
public extension HostControllerBasebandCommand {
var name: String {
return type(of: self).names[Int(rawValue)]
}
private static let names = [
"Unknown",
"Set Event Mask",
"Unknown",
"Reset",
"Unknown",
"Set Event Filter",
"Unknown",
"Unknown",
"Flush",
"Read PIN Type ",
"Write PIN Type",
"Create New Unit Key",
"Unknown",
"Read Stored Link Key",
"Unknown",
"Unknown",
"Unknown",
"Write Stored Link Key",
"Delete Stored Link Key",
"Write Local Name",
"Read Local Name",
"Read Connection Accept Timeout",
"Write Connection Accept Timeout",
"Read Page Timeout",
"Write Page Timeout",
"Read Scan Enable",
"Write Scan Enable",
"Read Page Scan Activity",
"Write Page Scan Activity",
"Read Inquiry Scan Activity",
"Write Inquiry Scan Activity",
"Read Authentication Enable",
"Write Authentication Enable",
"Read Encryption Mode",
"Write Encryption Mode",
"Read Class of Device",
"Write Class of Device",
"Read Voice Setting",
"Write Voice Setting",
"Read Automatic Flush Timeout",
"Write Automatic Flush Timeout",
"Read Num Broadcast Retransmissions",
"Write Num Broadcast Retransmissions",
"Read Hold Mode Activity ",
"Write Hold Mode Activity",
"Read Transmit Power Level",
"Read Synchronous Flow Control Enable",
"Write Synchronous Flow Control Enable",
"Unknown",
"Set Host Controller To Host Flow Control",
"Unknown",
"Host Buffer Size",
"Unknown",
"Host Number of Completed Packets",
"Read Link Supervision Timeout",
"Write Link Supervision Timeout",
"Read Number of Supported IAC",
"Read Current IAC LAP",
"Write Current IAC LAP",
"Read Page Scan Period Mode",
"Write Page Scan Period Mode",
"Read Page Scan Mode",
"Write Page Scan Mode",
"Set AFH Host Channel Classification",
"Unknown",
"Unknown",
"Read Inquiry Scan Type",
"Write Inquiry Scan Type",
"Read Inquiry Mode",
"Write Inquiry Mode",
"Read Page Scan Type",
"Write Page Scan Type",
"Read AFH Channel Assessment Mode",
"Write AFH Channel Assessment Mode",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Read Extended Inquiry Response",
"Write Extended Inquiry Response",
"Refresh Encryption Key",
"Unknown",
"Read Simple Pairing Mode",
"Write Simple Pairing Mode",
"Read Local OOB Data",
"Read Inquiry Response Transmit Power Level",
"Write Inquiry Transmit Power Level",
"Read Default Erroneous Data Reporting",
"Write Default Erroneous Data Reporting",
"Unknown",
"Unknown",
"Unknown",
"Enhanced Flush",
"Unknown",
"Read Logical Link Accept Timeout",
"Write Logical Link Accept Timeout",
"Set Event Mask Page 2",
"Read Location Data",
"Write Location Data",
"Read Flow Control Mode",
"Write Flow Control Mode",
"Read Enhanced Transmit Power Level",
"Read Best Effort Flush Timeout",
"Write Best Effort Flush Timeout",
"Short Range Mode",
"Read LE Host Supported",
"Write LE Host Supported"
]
}
| 47.666667 | 903 | 0.712234 |
5633967d37ce02717da91d2ffe83acd0ec9357b0 | 642 | //
// Created by Арабаджиян Артем on 2019-09-29.
// Copyright (c) 2019 DigitalCustoms. All rights reserved.
//
import Foundation
class BlockDaoAdapter: BaseDaoAdapter<CDMBlock, LMBlock> {
override func map(from emm: LMBlock, to cdm: CDMBlock) {
cdm.id = emm.id
cdm.comment = emm.comment
cdm.idTicket = emm.idTicket
}
override func map(from cdm: CDMBlock) -> LMBlock {
return LMBlock(id: cdm.id ?? "", idTicket: cdm.idTicket ?? "", comment: cdm.comment ?? "")
}
func lm(from nm: NMBlock) -> LMBlock {
return LMBlock(id: nm.id, idTicket: nm.idTicket, comment: nm.comment)
}
}
| 27.913043 | 98 | 0.638629 |
9bb399172b8fedc83ca150a3d6746381b523e3fa | 4,143 | extension QueryBuilder {
// MARK: Aggregate
public func count() -> EventLoopFuture<Int> {
self.count(\._$id)
}
public func count<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Int>
where
Field: QueryableProperty,
Field.Model == Model
{
self.aggregate(.count, key, as: Int.self)
}
public func sum<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value?>
where
Field: QueryableProperty,
Field.Model == Model
{
self.aggregate(.sum, key)
}
public func sum<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value>
where
Field: QueryableProperty,
Field.Value: OptionalType,
Field.Model == Model
{
self.aggregate(.sum, key)
}
public func average<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value?>
where
Field: QueryableProperty,
Field.Model == Model
{
self.aggregate(.average, key)
}
public func average<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value>
where
Field: QueryableProperty,
Field.Value: OptionalType,
Field.Model == Model
{
self.aggregate(.average, key)
}
public func min<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value?>
where
Field: QueryableProperty,
Field.Model == Model
{
self.aggregate(.minimum, key)
}
public func min<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value>
where
Field: QueryableProperty,
Field.Value: OptionalType,
Field.Model == Model
{
self.aggregate(.minimum, key)
}
public func max<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value?>
where
Field: QueryableProperty,
Field.Model == Model
{
self.aggregate(.maximum, key)
}
public func max<Field>(_ key: KeyPath<Model, Field>) -> EventLoopFuture<Field.Value>
where
Field: QueryableProperty,
Field.Value: OptionalType,
Field.Model == Model
{
self.aggregate(.maximum, key)
}
public func aggregate<Field, Result>(
_ method: DatabaseQuery.Aggregate.Method,
_ field: KeyPath<Model, Field>,
as type: Result.Type = Result.self
) -> EventLoopFuture<Result>
where
Field: QueryableProperty,
Field.Model == Model,
Result: Codable
{
self.aggregate(method, Model.path(for: field), as: Result.self)
}
public func aggregate<Result>(
_ method: DatabaseQuery.Aggregate.Method,
_ field: FieldKey,
as type: Result.Type = Result.self
) -> EventLoopFuture<Result>
where Result: Codable
{
self.aggregate(method, [field])
}
public func aggregate<Result>(
_ method: DatabaseQuery.Aggregate.Method,
_ path: [FieldKey],
as type: Result.Type = Result.self
) -> EventLoopFuture<Result>
where Result: Codable
{
let copy = self.copy()
// Remove all eager load requests otherwise we try to
// read IDs from the aggreate reply when performing
// the eager load subqueries.
copy.eagerLoaders = .init()
// Remove all sorts since they may be incompatible with aggregates.
copy.query.sorts = []
// Set custom action.
copy.query.action = .aggregate(
.field(
.path(path, schema: Model.schema),
method
)
)
let promise = self.database.eventLoop.makePromise(of: Result.self)
copy.run { output in
do {
let result = try output.decode(.aggregate, as: Result.self)
promise.succeed(result)
} catch {
promise.fail(error)
}
}.cascadeFailure(to: promise)
return promise.futureResult
}
}
| 28.770833 | 93 | 0.568911 |
1de5003b2679f546330300f4b7a7d665f1d668ef | 253 | //
// APIResponse.swift
// GameSDKCore
//
// Created by Abhayam Rastogi on 13/08/19.
// Copyright © 2019 Abhayam. All rights reserved.
//
import Foundation
public enum APIResponse<T: APIResource> {
case resource(T)
case error(APIError)
}
| 15.8125 | 50 | 0.687747 |
d763acf53d1dfcd14e606c976976a1fe4848ef64 | 1,484 | //
// Node.swift
// NinetyNineSwiftProblems
//
// Created by Uday Pandey on 03/05/2019.
// Copyright © 2019 Uday Pandey. All rights reserved.
//
import Foundation
protocol NodeType {
associatedtype Element
}
class Node<T>: NodeType {
typealias Element = T
var value: T
var next: Node<T>?
init(value: T, next: Node<T>? = nil) {
self.value = value
self.next = next
}
convenience init(_ values: T...) {
self.init(values)
}
init(_ values: [T]) {
guard !values.isEmpty else {
preconditionFailure("Empty list")
}
self.value = values[0]
var next = self
for elm in values[1..<values.count] {
let nextNode = Node(value: elm)
next.next = nextNode
next = nextNode
}
}
}
extension Node: Equatable where T: Equatable {
static func == (left: Node, right: Node) -> Bool {
guard left.value == right.value else { return false }
guard let leftNext = left.next,
let rightNext = right.next else { return left.next == right.next }
return leftNext == rightNext
}
}
extension Node: CustomStringConvertible {
var description: String {
var str = ["\(value)"]
var root = self
while let nextNode = root.next {
str.append("\(nextNode.value)")
root = nextNode
}
return "Node(" + str.joined(separator: ", ") + ")"
}
}
| 21.507246 | 80 | 0.557278 |
e83a41fc00ad2f178db1ad10931a265f76e6b688 | 983 | //
// SystemVersionCell.swift
// CTFeedbackSwift
//
// Created by 和泉田 領一 on 2017/09/24.
// Copyright © 2017 CAPH TECH. All rights reserved.
//
import UIKit
class SystemVersionCell: UITableViewCell {
override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}
extension SystemVersionCell: CellFactoryProtocol {
class func configure(_ cell: SystemVersionCell,
with item: SystemVersionItem,
for indexPath: IndexPath,
eventHandler: Any?) {
#if targetEnvironment(macCatalyst)
cell.textLabel?.text = "macOS"
#else
cell.textLabel?.text = CTLocalizedString("CTFeedback.iOS")
#endif
cell.detailTextLabel?.text = item.version
cell.selectionStyle = .none
}
}
| 29.787879 | 86 | 0.639878 |
33e27cfd8ac0236266d0d1f5b2d7d42b2abbae46 | 2,365 | //
// AppDelegate.swift
// VDLocalization
//
// Created by [email protected] on 04/07/2020.
// Copyright (c) 2020 [email protected]. All rights reserved.
//
import UIKit
import VDLocalization
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let vc = HomeViewController(nibName: "HomeViewController", bundle: nil)
self.window?.rootViewController = vc
if !TKLocalizeSession.shared.isFirstTime {
TKLocalizeSession.shared.isFirstTime = true
TKLocalize.shared.loadLocalLanguage()
}
TKLocalize.shared.checkPackVersion()
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
TKLocalize.shared.checkPackVersion()
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 43 | 285 | 0.736998 |
d7c885e59c7392efd70b422ed4af046f2896ee9d | 1,916 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Colors at https://www.figma.com/file/X4XTH9iS2KGJ2wFKDqkyed/Compound?node-id=1255%3A1104
public protocol Colors {
associatedtype ColorType
/// - Focused/Active states
/// - CTAs
var accent: ColorType { get }
/// - Error messages
/// - Content requiring user attention
/// - Notification, alerts
var alert: ColorType { get }
/// - Text
/// - Icons
var primaryContent: ColorType { get }
/// - Text
/// - Icons
var secondaryContent: ColorType { get }
/// - Text
/// - Icons
var tertiaryContent: ColorType { get }
/// - Text
/// - Icons
var quarterlyContent: ColorType { get }
/// - separating lines and other UI components
var quinaryContent: ColorType { get }
/// - System-based areas and backgrounds
var system: ColorType { get }
/// Separating line
var separator: ColorType { get }
// Cards, tiles
var tile: ColorType { get }
/// Top navigation background on iOS
var navigation: ColorType { get }
/// Background UI color
var background: ColorType { get }
/// - Names in chat timeline
/// - Avatars default states that include first name letter
var namesAndAvatars: [ColorType] { get }
}
| 26.985915 | 92 | 0.640397 |
2225a7d1bbf8a74cd3599daa3d2f57b5fa6f3ecd | 421 | //
// SearchCore.swift
// Mongsil
//
// Created by Chanwoo Cho on 2022/05/09.
//
import Combine
import ComposableArchitecture
struct SearchState: Equatable {
}
enum SearchAction {
case backButtonTapped
}
struct SearchEnvironment {
}
let searchReducer = Reducer<WithSharedState<SearchState>, SearchAction, SearchEnvironment> {
_, action, _ in
switch action {
case .backButtonTapped:
return .none
}
}
| 15.035714 | 92 | 0.729216 |
50dd3e784a4a9fdfbdffcd9ab8d0d3a9c55329a3 | 1,212 | //
// Regex.swift
// Additions
//
// Created by James Froggatt on 20.08.2016.
//
//
/*
inactive
• no valid use found (see String.CompareOptions.regularExpression)
*/
import Foundation
public struct RegEx: ExpressibleByStringLiteral {
public var pattern: String
public var options: NSRegularExpression.Options
public init(stringLiteral value: String) {
self.pattern = value
self.options = [.caseInsensitive]
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(_ pattern: String, options: NSRegularExpression.Options = []) {
self.pattern = pattern
self.options = options
}
public func matches(_ string: String, options: NSRegularExpression.MatchingOptions = []) -> Bool {
return try? NSRegularExpression(pattern: self.pattern, options: self.options)
.firstMatch(in: string, options: options, range: range(string)) ¬= nil
}
}
public func ~=(pattern: RegEx, matched: String) -> Bool {
return pattern.matches(matched)
}
private func range(_ string: String) -> NSRange {
return NSRange(location: 0, length: (string as NSString).length)
}
| 26.347826 | 99 | 0.735974 |
1d63aebb80a2054ae56c1efcd9350640d733adc6 | 6,984 | //
// HeroTableViewController.swift
// Overwatch
//
// Created by Jim Campagno on 10/22/16.
// Copyright © 2016 Gamesmith, LLC. All rights reserved.
//
import UIKit
import AVFoundation
class HeroTableViewController: UITableViewController {
var heroes: [Type : [Hero]]!
var audioPlayer: AVAudioPlayer!
var sectionViews: [HeroSectionView]!
var heroview: HeroView!
var selectedFrame: CGRect!
var selectedHero: Hero!
var topConstraint: NSLayoutConstraint!
var heightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setup()
addGestureRecognizer(to: tableView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
createSectionViews()
}
}
// MARK: - UITableView Methods
extension HeroTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return heroes.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sortedTypes = Array(heroes.keys).sorted { $0 < $1 }
let type = sortedTypes[section]
let heroesForType = heroes[type]!
return heroesForType.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HeroCell", for: indexPath) as! HeroTableViewCell
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let heroCell = cell as! HeroTableViewCell
let type = Type.allTypes[indexPath.section]
let heroesForType = heroes[type]!
heroCell.hero = heroesForType[indexPath.row]
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let heroSectionView = sectionViews[section]
heroSectionView.type = Type.allTypes[section]
heroSectionView.willDisplay()
return heroSectionView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(HeroSectionView.height)
}
func retrieveCell(for indexPath: IndexPath, at point: CGPoint) -> HeroTableViewCell {
let cell = self.tableView.cellForRow(at: indexPath) as! HeroTableViewCell
return cell
}
func visibleCells(excluding cell: HeroTableViewCell) -> [HeroTableViewCell] {
let viewableCells = self.tableView.visibleCells as! [HeroTableViewCell]
let nonTappedCells = viewableCells.filter { $0 != cell }
return nonTappedCells
}
}
// MARK: - Setup Methods
extension HeroTableViewController {
func setup() {
setupAudioPlayer()
setupBarButtonItem()
heroes = [.offense : Hero.offense, .defense : Hero.defense]
view.backgroundColor = UIColor.lightBlack
}
func setupAudioPlayer() {
let filePath = Bundle.main.path(forResource: "ElectricSound", ofType: "wav")!
let url = URL(fileURLWithPath: filePath)
audioPlayer = try! AVAudioPlayer(contentsOf: url)
}
func setupBarButtonItem() {
let mcCreeWeapon = McCreeWeaponView(frame: CGRect(x: 0, y: 0, width: 70, height: 35))
let barButtonItem = UIBarButtonItem(customView: mcCreeWeapon)
navigationItem.rightBarButtonItem = barButtonItem
}
func addGestureRecognizer(to view: UIView) {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(gestureRecognizer)
}
}
// MARK: - Section Header Views
extension HeroTableViewController {
func createSectionViews() {
let width = Int(tableView.frame.size.width)
let height = HeroSectionView.height
let frame = CGRect(x: 0, y: 0, width: width, height: height)
let offense = HeroSectionView(frame: frame, type: .offense)
let defense = HeroSectionView(frame: frame, type: .defense)
let tank = HeroSectionView(frame: frame, type: .tank)
let support = HeroSectionView(frame: frame, type: .support)
sectionViews = [offense, defense, tank, support]
}
}
// MARK: - Action Methods
extension HeroTableViewController {
func viewTapped(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: point) else { return }
let cell = retrieveCell(for: indexPath, at: point)
tableView.isUserInteractionEnabled = false
runAnimations(with: cell, indexPath: indexPath)
animateSelection(at: point)
audioPlayer.play()
}
func animateSelection(at point: CGPoint) {
UIView.animateRainbow(in: tableView, center: point) { _ in }
}
func runAnimations(with cell: HeroTableViewCell, indexPath: IndexPath) {
scale(cell: cell, indexPath: indexPath) { _ in
self.tableView.isUserInteractionEnabled = true
}
}
func scale(cell: HeroTableViewCell, indexPath: IndexPath, handler: @escaping () -> Void) {
let rect = tableView.rectForRow(at: indexPath)
let y = abs(self.tableView.contentOffset.y - rect.origin.y)
let origin = CGPoint(x: 0.0, y: y)
let frame = CGRect(origin: origin, size: rect.size)
heroview = cell.heroView.copy(with: rect) as! HeroView
selectedHero = heroview.hero
selectedFrame = frame
tableView.addSubview(heroview)
delay(0.1) { [unowned self] _ in
self.performSegue(withIdentifier: "DetailSegue", sender: nil)
}
UIView.animate(withDuration: 0.3, animations: {
self.heroview.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.heroview.alpha = 0.5
}) { [unowned self] _ in
DispatchQueue.main.async {
self.tableView.willRemoveSubview(self.heroview)
self.heroview.removeFromSuperview()
handler()
}
}
}
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
}
// MARK: - Segue Methods
extension HeroTableViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destVC = segue.destination as! HeroDetailViewController
destVC.selectedFrame = selectedFrame
destVC.hero = selectedHero
}
}
| 31.318386 | 121 | 0.649771 |
f4d2e9f916c4e14aef7a0da07cb2310eda23f122 | 32,691 | //这是自动生成的代码,不要改动,否则你的改动会被覆盖!!!!!!!
import Foundation
import HTTPIDL
struct TSPStruct1 {
var a: Int32?
var b: String?
var c: [[String: Int64]]?
var d: [String: [Int64]]?
}
extension TSPStruct1: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content, case .dictionary(let value) = content else {
return nil
}
self.a = Int32(content: value["a"])
self.b = String(content: value["bc"])
if let content = value["c"] {
var c: [[String: Int64]]? = nil
if case .array(let value) = content {
c = [[String: Int64]]()
value.forEach { (content) in
let _c = [String: Int64](content: content)
if let tmp = _c {
c!.append(tmp)
}
}
}
self.c = c
} else {
self.c = nil
}
if let content = value["df"] {
var d: [String: [Int64]]? = nil
if case .dictionary(let value) = content {
d = [String: [Int64]]()
value.forEach { (kv) in
let content = kv.value
let _d = [Int64](content: content)
if let tmp = _d {
d!.updateValue(tmp, forKey: kv.key)
}
}
}
self.d = d
} else {
self.d = nil
}
}
}
extension TSPStruct1: RequestContentConvertible {
func asRequestContent() -> RequestContent {
var result = [String: RequestContent]()
if let tmp = a {
result["a"] = tmp.asRequestContent()
}
if let tmp = b {
result["bc"] = tmp.asRequestContent()
}
if let tmp = c {
let tmp = tmp.reduce(.array(value: []), { (soFar, soGood) -> RequestContent in
guard case .array(var content) = soFar else {
return soFar
}
let tmp = soGood.asRequestContent()
content.append(tmp)
return .array(value: content)
})
result["c"] = tmp
}
if let tmp = d {
let tmp = tmp.reduce(.dictionary(value: [:]), { (soFar, soGood) -> RequestContent in
guard case .dictionary(var content) = soFar else {
return soFar
}
let tmp = soGood.value.asRequestContent()
content[soGood.key.asHTTPParamterKey()] = tmp
return .dictionary(value: content)
})
result["df"] = tmp
}
return .dictionary(value: result)
}
}
struct TSPStruct2 {
var body: Int32?
}
extension TSPStruct2: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
self.body = Int32(content: content)
}
}
extension TSPStruct2: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
return body.asRequestContent()
} else {
return .dictionary(value: [:])
}
}
}
struct TSPStruct3 {
var body: [[String: Int64]]?
}
extension TSPStruct3: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
var body: [[String: Int64]]? = nil
if case .array(let value) = content {
body = [[String: Int64]]()
value.forEach { (content) in
let _body = [String: Int64](content: content)
if let tmp = _body {
body!.append(tmp)
}
}
}
self.body = body
}
}
extension TSPStruct3: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
let tmp = body.reduce(.array(value: []), { (soFar, soGood) -> RequestContent in
guard case .array(var content) = soFar else {
return soFar
}
let tmp = soGood.asRequestContent()
content.append(tmp)
return .array(value: content)
})
return tmp
} else {
return .dictionary(value: [:])
}
}
}
struct TSPStruct4 {
var body: [String: [Int64]]?
}
extension TSPStruct4: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
var body: [String: [Int64]]? = nil
if case .dictionary(let value) = content {
body = [String: [Int64]]()
value.forEach { (kv) in
let content = kv.value
let _body = [Int64](content: content)
if let tmp = _body {
body!.updateValue(tmp, forKey: kv.key)
}
}
}
self.body = body
}
}
extension TSPStruct4: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
let tmp = body.reduce(.dictionary(value: [:]), { (soFar, soGood) -> RequestContent in
guard case .dictionary(var content) = soFar else {
return soFar
}
let tmp = soGood.value.asRequestContent()
content[soGood.key.asHTTPParamterKey()] = tmp
return .dictionary(value: content)
})
return tmp
} else {
return .dictionary(value: [:])
}
}
}
struct TSPStruct5 {
var body: TSPStruct1?
}
extension TSPStruct5: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
self.body = TSPStruct1(content: content)
}
}
extension TSPStruct5: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
return body.asRequestContent()
} else {
return .dictionary(value: [:])
}
}
}
struct TSPStruct6 {
var body: TSPStruct2?
}
extension TSPStruct6: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
self.body = TSPStruct2(content: content)
}
}
extension TSPStruct6: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
return body.asRequestContent()
} else {
return .dictionary(value: [:])
}
}
}
struct TSPStruct7 {
var body: TSPStruct3?
}
extension TSPStruct7: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
self.body = TSPStruct3(content: content)
}
}
extension TSPStruct7: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
return body.asRequestContent()
} else {
return .dictionary(value: [:])
}
}
}
struct TSPStruct8 {
var body: TSPStruct4?
}
extension TSPStruct8: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
self.body = TSPStruct4(content: content)
}
}
extension TSPStruct8: RequestContentConvertible {
func asRequestContent() -> RequestContent {
if let body = body {
return body.asRequestContent()
} else {
return .dictionary(value: [:])
}
}
}
class GetArrayRequest: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/array"
}
var body: [[String: Int64]]?
var content: RequestContent? {
if let body = body {
let tmp = body.reduce(.array(value: []), { (soFar, soGood) -> RequestContent in
guard case .array(var content) = soFar else {
return soFar
}
let tmp = soGood.asRequestContent()
content.append(tmp)
return .array(value: content)
})
return tmp
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetArrayResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetArrayResponse> {
let future: RequestFuture<GetArrayResponse> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetArrayResponse: Response {
let body: [[String: String]]?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
var body: [[String: String]]? = nil
if case .array(let value) = content {
body = [[String: String]]()
value.forEach { (content) in
let _body = [String: String](content: content)
if let tmp = _body {
body!.append(tmp)
}
}
}
self.body = body
}
}
class GetDictRequest: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/dict"
}
var body: [String: [Int64]]?
var content: RequestContent? {
if let body = body {
let tmp = body.reduce(.dictionary(value: [:]), { (soFar, soGood) -> RequestContent in
guard case .dictionary(var content) = soFar else {
return soFar
}
let tmp = soGood.value.asRequestContent()
content[soGood.key.asHTTPParamterKey()] = tmp
return .dictionary(value: content)
})
return tmp
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetDictResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetDictResponse> {
let future: RequestFuture<GetDictResponse> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetDictResponse: Response {
let body: [String: [String]]?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
var body: [String: [String]]? = nil
if case .dictionary(let value) = content {
body = [String: [String]]()
value.forEach { (kv) in
let content = kv.value
let _body = [String](content: content)
if let tmp = _body {
body!.updateValue(tmp, forKey: kv.key)
}
}
}
self.body = body
}
}
class GetSimpleRequest: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/simple"
}
var body: Int64?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetSimpleResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetSimpleResponse> {
let future: RequestFuture<GetSimpleResponse> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetSimpleResponse: Response {
let body: String?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = String(content: content)
}
}
class PostFileRequest: Request {
var method: String = "POST"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/file"
}
var body: HTTPFile?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (PostFileResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<PostFileResponse> {
let future: RequestFuture<PostFileResponse> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct PostFileResponse: Response {
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
}
}
class PostDataRequest: Request {
var method: String = "POST"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/data"
}
var body: HTTPData?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (PostDataResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<PostDataResponse> {
let future: RequestFuture<PostDataResponse> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct PostDataResponse: Response {
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
}
}
class GetStruct1Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct1"
}
var body: TSPStruct1?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct1Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct1Response> {
let future: RequestFuture<GetStruct1Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct1Response: Response {
let body: TSPStruct1?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct1(content: content)
}
}
class GetStruct2Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct2"
}
var body: TSPStruct2?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct2Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct2Response> {
let future: RequestFuture<GetStruct2Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct2Response: Response {
let body: TSPStruct2?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct2(content: content)
}
}
class GetStruct3Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct3"
}
var body: TSPStruct3?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct3Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct3Response> {
let future: RequestFuture<GetStruct3Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct3Response: Response {
let body: TSPStruct3?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct3(content: content)
}
}
class GetStruct4Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct4"
}
var body: TSPStruct4?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct4Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct4Response> {
let future: RequestFuture<GetStruct4Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct4Response: Response {
let body: TSPStruct4?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct4(content: content)
}
}
class GetStruct5Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct5"
}
var body: TSPStruct5?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct5Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct5Response> {
let future: RequestFuture<GetStruct5Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct5Response: Response {
let body: TSPStruct5?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct5(content: content)
}
}
class GetStruct6Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct6"
}
var body: TSPStruct6?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct6Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct6Response> {
let future: RequestFuture<GetStruct6Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct6Response: Response {
let body: TSPStruct6?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct6(content: content)
}
}
class GetStruct7Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct7"
}
var body: TSPStruct7?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct7Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct7Response> {
let future: RequestFuture<GetStruct7Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct7Response: Response {
let body: TSPStruct7?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct7(content: content)
}
}
class GetStruct8Request: Request {
var method: String = "GET"
private var _configuration: RequestConfiguration?
var configuration: RequestConfiguration {
get {
guard let config = _configuration else {
return BaseRequestConfiguration.create(from: manager.configuration, request: self)
}
return config
}
set {
_configuration = newValue
}
}
var manager: RequestManager = BaseRequestManager.shared
var uri: String {
return "/struct8"
}
var body: TSPStruct8?
var content: RequestContent? {
if let body = body {
return body.asRequestContent()
} else {
return nil
}
}
@discardableResult
func send(completion: @escaping (GetStruct8Response) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<GetStruct8Response> {
let future: RequestFuture<GetStruct8Response> = manager.send(self, responseHandler: completion, errorHandler: errorHandler, progressHandler: nil)
return future
}
@discardableResult
func send(rawResponseHandler: @escaping (HTTPResponse) -> Void, errorHandler: @escaping (HIError) -> Void) -> RequestFuture<HTTPResponse> {
let future = manager.send(self, responseHandler: rawResponseHandler, errorHandler: errorHandler, progressHandler: nil)
return future
}
}
struct GetStruct8Response: Response {
let body: TSPStruct8?
let rawResponse: HTTPResponse
init(content: ResponseContent?, rawResponse: HTTPResponse) throws {
self.rawResponse = rawResponse
guard let content = content else {
self.body = nil
return
}
self.body = TSPStruct8(content: content)
}
}
| 30.753528 | 153 | 0.596923 |
d7049a5251e4217622595ad36fd3a890862b06c1 | 995 | //
// On_The_MapTests.swift
// On The MapTests
//
// Created by John Longenecker on 1/28/16.
// Copyright © 2016 John Longenecker. All rights reserved.
//
import XCTest
@testable import On_The_Map
class On_The_MapTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.891892 | 111 | 0.639196 |
79d90abb81f4bf2aaf1a4cae9a066f35167a369a | 1,986 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift
// RUN: %target-build-swift -module-name main -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s --color
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574
// UNSUPPORTED: windows
import _Distributed
import FakeDistributedActorSystems
typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem
distributed actor Greeter {
distributed func takeThrowReturn(name: String) async throws -> String {
throw SomeError()
}
}
struct SomeError: Error, Sendable, Codable {}
func test() async throws {
let system = DefaultDistributedActorSystem()
let local = Greeter(system: system)
let ref = try Greeter.resolve(id: local.id, using: system)
do {
let value = try await ref.takeThrowReturn(name: "Example")
// CHECK: >> remoteCall: on:main.Greeter, target:RemoteCallTarget(_mangledName: "$s4main7GreeterC15takeThrowReturn4nameS2S_tYaKFTE"), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Example"], returnType: Optional(Swift.String), errorType: Optional(Swift.Error)), throwing:Swift.Error, returning:Swift.String
print("did not throw")
// CHECK-NOT: did not throw
} catch {
// CHECK: << onThrow: SomeError()
// CHECK: << remoteCall throw: SomeError()
print("error: \(error)")
// CHECK: error: SomeError()
}
}
@main struct Main {
static func main() async {
try! await test()
}
}
| 36.109091 | 327 | 0.740181 |
018caf06b3add14699494750fbb45af3a97bb726 | 1,418 | //
// Router.swift
// Tabbar
//
// Created by lenbo lan on 2020/12/26.
//
import UIKit
class Router {
typealias Submodules = (
chatrooms: UIViewController,
friends: UIViewController,
profile: UIViewController
)
private weak var viewController: UIViewController?
init(viewController: UIViewController) {
self.viewController = viewController
}
}
extension Router {
static func tabs(usingSubmodules submodules: Submodules) -> LiaoliaoTabs {
let chatsImage = UIImage(systemName: "ellipsis.bubble.fill")
let friendsImage = UIImage(systemName: "person.2.fill")
let profileImage = UIImage(systemName: "person.fill")
let chatroomsTabbarItem = UITabBarItem(title: "Chat", image: chatsImage, tag: 100)
let friendsTabbarItem = UITabBarItem(title: "Friends", image: friendsImage, tag: 101)
let profileTabbarItem = UITabBarItem(title: "Profile", image: profileImage, tag: 102)
submodules.chatrooms.tabBarItem = chatroomsTabbarItem
submodules.friends.tabBarItem = friendsTabbarItem
submodules.profile.tabBarItem = profileTabbarItem
return (
chatrooms: submodules.chatrooms,
friends: submodules.friends,
profile: submodules.profile
)
}
}
extension Router: Routing {
}
| 26.259259 | 94 | 0.643865 |
294ef6b2730bdbc17184d443015785d25a6c20dc | 771 | //
// LightweightSpaceship.swift
// Life
//
// Created by Brian Partridge on 11/1/15.
// Copyright © 2015 PearTreeLabs. All rights reserved.
//
public struct LightweightSpaceship: Pattern {
// MARK: - Initialization
public init() {}
// MARK: - Pattern
public var size: Size {
return Size(width: 5, height: 4)
}
public var coordinates: [Coordinate] {
return [
Coordinate(x: 1, y: 0),
Coordinate(x: 2, y: 0),
Coordinate(x: 3, y: 0),
Coordinate(x: 4, y: 0),
Coordinate(x: 0, y: 1),
Coordinate(x: 4, y: 1),
Coordinate(x: 4, y: 2),
Coordinate(x: 0, y: 3),
Coordinate(x: 3, y: 3),
]
}
}
| 22.028571 | 55 | 0.494163 |
edc4865a403b5dc29a92e0f42b96206b15012067 | 217 | //
// APIArticleCommentResponse.swift
// NimbleMedium
//
// Created by Minh Pham on 19/10/2021.
//
import Foundation
struct APIArticleCommentResponse: Decodable, Equatable {
let comment: APIArticleComment
}
| 15.5 | 56 | 0.741935 |
89f5613f23878292401d238fbcbab6ae74fcf1aa | 5,921 | //
// ZQRecommendCycleView.swift
// DouYuZB
//
// Created by 张泉 on 2021/8/23.
//
import UIKit
private let cellID = "ecommendCycleCellId"
private let maxPage = 1000
class ZQRecommendCycleView: UIView {
var cycleTimer : Timer?
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(collectionView )
self.addSubview(pageControl)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
pageControl.snp.makeConstraints { (make) in
make.right.equalTo(-15)
make.bottom.equalToSuperview().offset(-10)
}
}
var cycleModels: [ZQCycleModel]? {
didSet {
// 1.刷新collectionView
collectionView.reloadData()
// 2.设置pageControl个数
pageControl.numberOfPages = cycleModels?.count ?? 0
self.collectionView.reloadData()
// 3.默认滚动到中间某一个位置
let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
removeCycleTimer()
addCycleTimer()
}
}
private lazy var collectionView: UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: screenWidth, height: self.bounds.height)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.white
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(ZQRecommendCycleCell.self, forCellWithReuseIdentifier: cellID)
return collectionView
}()
private lazy var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.currentPageIndicatorTintColor = .orange
pageControl.pageIndicatorTintColor = .gray
return pageControl
}()
}
extension ZQRecommendCycleView: UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 1.获取滚动的偏移量
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
// 2.计算pageControl的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
}
extension ZQRecommendCycleView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: ZQRecommendCycleCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! ZQRecommendCycleCell
cell.model = cycleModels![(indexPath as NSIndexPath).item % cycleModels!.count]
return cell
}
}
// MARK: - 对定时器的操作方法
extension ZQRecommendCycleView {
fileprivate func addCycleTimer() {
cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: .common)
}
fileprivate func removeCycleTimer() {
cycleTimer?.invalidate() // 从运行循环中移除
cycleTimer = nil
}
@objc fileprivate func scrollToNext() {
// 1.获取滚动的偏移量
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
// 2.滚动该位置
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
class ZQRecommendCycleCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(coverView)
self.addSubview(nameLabel)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
coverView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
nameLabel.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(0)
make.height.equalTo(50)
}
}
var model: ZQCycleModel? {
didSet {
nameLabel.text = " \(model?.title ?? "")"
guard let iconURL = URL(string: model!.pic_url) else { return }
coverView.kf.setImage(with: iconURL, placeholder: R.image.img_default())
}
}
lazy var coverView: UIImageView = {
let coverView = UIImageView(image: R.image.live_cell_default_phone())
coverView.layer.cornerRadius = 5
coverView.layer.masksToBounds = true
return coverView
}()
lazy var nameLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 16)
titleLabel.textColor = .white
titleLabel.backgroundColor = UIColor.black.withAlphaComponent(0.4)
return titleLabel
}()
}
| 32.355191 | 145 | 0.64077 |