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
|
---|---|---|---|---|---|
28350a7450b9e9fa2dcd536ab85a9ff93747f402 | 5,878 | import Combine
import SwiftUI
// NB: Deprecated after 0.17.0:
extension IfLetStore {
@available(*, deprecated, message: "'else' now takes a view builder closure")
public init<IfContent, ElseContent>(
_ store: Store<State?, Action>,
@ViewBuilder then ifContent: @escaping (Store<State, Action>) -> IfContent,
else elseContent: @escaping @autoclosure () -> ElseContent
) where Content == _ConditionalContent<IfContent, ElseContent> {
self.init(store, then: ifContent, else: elseContent)
}
}
// NB: Deprecated after 0.13.0:
@available(*, deprecated, renamed: "BindingAction")
public typealias FormAction = BindingAction
extension Reducer {
@available(*, deprecated, renamed: "binding")
public func form(action toFormAction: CasePath<Action, BindingAction<State>>) -> Self {
self.binding(action: toFormAction)
}
}
// NB: Deprecated after 0.10.0:
@available(iOS 13, *)
@available(macCatalyst 13, *)
@available(macOS, unavailable)
@available(tvOS 13, *)
@available(watchOS 6, *)
extension ActionSheetState {
@available(*, deprecated, message: "'title' and 'message' should be 'TextState'")
@_disfavoredOverload
public init(
title: LocalizedStringKey,
message: LocalizedStringKey? = nil,
buttons: [Button]
) {
self.init(
title: .init(title),
message: message.map { .init($0) },
buttons: buttons
)
}
}
extension AlertState {
@available(*, deprecated, message: "'title' and 'message' should be 'TextState'")
@_disfavoredOverload
public init(
title: LocalizedStringKey,
message: LocalizedStringKey? = nil,
dismissButton: Button? = nil
) {
self.init(
title: .init(title),
message: message.map { .init($0) },
dismissButton: dismissButton
)
}
@available(*, deprecated, message: "'title' and 'message' should be 'TextState'")
@_disfavoredOverload
public init(
title: LocalizedStringKey,
message: LocalizedStringKey? = nil,
primaryButton: Button,
secondaryButton: Button
) {
self.init(
title: .init(title),
message: message.map { .init($0) },
primaryButton: primaryButton,
secondaryButton: secondaryButton
)
}
}
extension AlertState.Button {
@available(*, deprecated, message: "'label' should be 'TextState'")
@_disfavoredOverload
public static func cancel(
_ label: LocalizedStringKey,
send action: Action? = nil
) -> Self {
Self(action: action, type: .cancel(label: .init(label)))
}
@available(*, deprecated, message: "'label' should be 'TextState'")
@_disfavoredOverload
public static func `default`(
_ label: LocalizedStringKey,
send action: Action? = nil
) -> Self {
Self(action: action, type: .default(label: .init(label)))
}
@available(*, deprecated, message: "'label' should be 'TextState'")
@_disfavoredOverload
public static func destructive(
_ label: LocalizedStringKey,
send action: Action? = nil
) -> Self {
Self(action: action, type: .destructive(label: .init(label)))
}
}
// NB: Deprecated after 0.9.0:
extension Store {
@available(*, deprecated, renamed: "publisherScope(state:)")
public func scope<P: Publisher, LocalState>(
state toLocalState: @escaping (AnyPublisher<State, Never>) -> P
) -> AnyPublisher<Store<LocalState, Action>, Never>
where P.Output == LocalState, P.Failure == Never {
self.publisherScope(state: toLocalState)
}
@available(*, deprecated, renamed: "publisherScope(state:action:)")
public func scope<P: Publisher, LocalState, LocalAction>(
state toLocalState: @escaping (AnyPublisher<State, Never>) -> P,
action fromLocalAction: @escaping (LocalAction) -> Action
) -> AnyPublisher<Store<LocalState, LocalAction>, Never>
where P.Output == LocalState, P.Failure == Never {
self.publisherScope(state: toLocalState, action: fromLocalAction)
}
}
// NB: Deprecated after 0.6.0:
extension Reducer {
@available(*, deprecated, renamed: "optional()")
public var optional: Reducer<State?, Action, Environment> {
self.optional()
}
}
// NB: Deprecated after 0.1.4:
extension Reducer {
@available(*, unavailable, renamed: "debug(_:environment:)")
public func debug(
prefix: String,
environment toDebugEnvironment: @escaping (Environment) -> DebugEnvironment = { _ in
DebugEnvironment()
}
) -> Reducer {
self.debug(prefix, state: { $0 }, action: .self, environment: toDebugEnvironment)
}
@available(*, unavailable, renamed: "debugActions(_:environment:)")
public func debugActions(
prefix: String,
environment toDebugEnvironment: @escaping (Environment) -> DebugEnvironment = { _ in
DebugEnvironment()
}
) -> Reducer {
self.debug(prefix, state: { _ in () }, action: .self, environment: toDebugEnvironment)
}
@available(*, unavailable, renamed: "debug(_:state:action:environment:)")
public func debug<LocalState, LocalAction>(
prefix: String,
state toLocalState: @escaping (State) -> LocalState,
action toLocalAction: CasePath<Action, LocalAction>,
environment toDebugEnvironment: @escaping (Environment) -> DebugEnvironment = { _ in
DebugEnvironment()
}
) -> Reducer {
self.debug(prefix, state: toLocalState, action: toLocalAction, environment: toDebugEnvironment)
}
}
extension WithViewStore {
@available(*, unavailable, renamed: "debug(_:)")
public func debug(prefix: String) -> Self {
self.debug(prefix)
}
}
// NB: Deprecated after 0.1.3:
extension Effect {
@available(*, unavailable, renamed: "run")
public static func async(
_ work: @escaping (Effect.Subscriber) -> Cancellable
) -> Self {
self.run(work)
}
}
extension Effect where Failure == Swift.Error {
@available(*, unavailable, renamed: "catching")
public static func sync(_ work: @escaping () throws -> Output) -> Self {
self.catching(work)
}
}
| 28.955665 | 99 | 0.681524 |
e0288a54aa40dfd02d90e0d61b056aca14207b4e | 1,125 | //
// LinguisticVariable+Hedges.swift
// Fuzzy
//
// Created by Anton Bronnikov on 04/11/2016.
// Copyright © 2016 Anton Bronnikov. All rights reserved.
//
public extension LinguisticVariable {
/// A modifier (hedge) that can be applied to the existing lingustic variable.
public enum Hedge: String {
case not = "not"
case very = "very"
}
/// Creates a new linguistic variable using a hedge applied on the existing one.
///
/// - parameters:
/// - hedge: A hedge to be applied.
/// - base: An underlying (base) linguistic variable to be modified with a hedge.
public init(hedge: Hedge, base: LinguisticVariable) {
let modifiedName = "\(hedge.rawValue) \(base.name)"
switch hedge {
case .not:
self.init(name: modifiedName) { crisp in
return 1 - base.membershipFunction(crisp)
}
case .very:
self.init(name: modifiedName) { crisp in
let baseResult = base.membershipFunction(crisp)
return baseResult * baseResult
}
}
}
}
| 26.785714 | 87 | 0.593778 |
794911e322f1a10e08e37425c807415b20c57bbf | 2,136 | //
// LyricsViewModel.swift
// PFXPlayer
//
// Created by succorer on 02/02/2020.
// Copyright © 2020 PFXStudio. All rights reserved.
//
import Foundation
import RxSwift
import RxRelay
public class LyricsViewModel {
typealias ReactiveSection = BehaviorRelay<[LyricsModel]>
var data = ReactiveSection(value: [])
var scaleValue = BehaviorRelay<LyricsScale>(value: LyricsScale.x1)
var favorite = BehaviorRelay<Int>(value: -1)
var autoScroll = BehaviorRelay<Bool>(value: true)
var isMiniSize = BehaviorRelay<Bool>(value: true)
init() {
self.data.accept([LyricsModel(header: "", items: [LyricsCellModel]())])
if let index = UserDefaults.standard.integer(forKey: kFavoriteKey) as Int? {
if index != 0 {
self.favorite.accept(index)
}
}
}
func update(items: [LyricsCellModel]) {
self.data.accept([LyricsModel(header: "", items: items)])
}
func toggledScale() {
if self.scaleValue.value == LyricsScale.x1 {
self.scaleValue.accept(LyricsScale.x2)
return
}
else if self.scaleValue.value == LyricsScale.x2 {
self.scaleValue.accept(LyricsScale.x4)
return
}
self.scaleValue.accept(LyricsScale.x1)
}
func toggledAutoScroll(isAuto: Bool) {
self.autoScroll.accept(isAuto)
}
func toggledFavorite(index: Int, isSelected: Bool) {
if index == 0 {
return
}
DispatchQueue.main.async {
UserDefaults.standard.removeObject(forKey: kFavoriteKey)
defer {
UserDefaults.standard.synchronize()
}
if isSelected == false {
self.favorite.accept(-1)
return
}
let lyricsModel = self.data.value.first?.items[index]
UserDefaults.standard.set(index, forKey: kFavoriteKey)
self.favorite.accept(index)
MusicPlayer.shared.move(millisecond: lyricsModel!.millisecond)
}
}
}
| 28.105263 | 84 | 0.583801 |
d7ce8f1c34365bb56be3c71e3893329837125443 | 958 | //
// PlayingWithSwiftUITests.swift
// PlayingWithSwiftUITests
//
// Created by jaime Laino Guerra on 7/3/19.
// Copyright © 2019 jaime Laino Guerra. All rights reserved.
//
import XCTest
@testable import PlayingWithSwiftUI
class PlayingWithSwiftUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.371429 | 111 | 0.67119 |
bbaead3f992621a3c099862c7e76c1e2c0ed2f33 | 383 | //
// LogController.swift
// Swift-LightBlue
//
// Created by Pluto Y on 16/1/6.
// Copyright © 2016年 Pluto-y. All rights reserved.
//
import UIKit
class LogController : UITableViewController {
/**
Back to preview controller
*/
@IBAction func closeClick(_ sender: AnyObject) {
self.navigationController?.popViewController(animated: true)
}
}
| 19.15 | 68 | 0.663185 |
7532c5b7947d5a1c5740ed46c8faac570e88caff | 665 | //
// KeyboardDismissable.swift
// ArchitectureTest
//
// Created by Jakub Łaszczewski on 07/04/2019.
// Copyright © 2019 letUs. All rights reserved.
//
import RxCocoa
public protocol KeyboardDismissable {
func dismissKeyboard()
}
extension KeyboardDismissable where Self: ViewController<BaseView<ViewModel>> {
func configureKeyboardDismissing() {
let tapGesture = UITapGestureRecognizer()
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
tapGesture.rx.event.bind(onNext: { [weak self] _ in
self?.dismissKeyboard()
}).disposed(by: baseView.disposeBag)
}
}
| 25.576923 | 79 | 0.696241 |
1ca39939c7f194fbe948c256ed6e4dc2e5361096 | 362 | //
// UsersView.swift
// ModernOctopodium
//
// Created by Nuno Gonçalves on 31/08/2019.
// Copyright © 2019 numicago. All rights reserved.
//
import SwiftUI
struct UsersView: View {
var body: some View {
Text("Hello Users")
}
}
struct UsersView_Previews: PreviewProvider {
static var previews: some View {
UsersView()
}
}
| 16.454545 | 51 | 0.646409 |
8fbcedc67839abccebe7be79907e886414ae282b | 1,083 | //
// ScheduleListRow.swift
// Dividend App
//
// Created by Kevin Li on 1/17/20.
// Copyright © 2020 Kevin Li. All rights reserved.
//
import SwiftUI
struct ScheduleListRow: View {
let stock: PortfolioStock
let date: Date
let amount: String
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(stock.ticker)
.font(.system(size: 16))
.bold()
.foregroundColor(Color("textColor"))
Text(stock.fullName)
.font(.system(size: 15))
.foregroundColor(Color.gray)
}
Spacer()
VStack(alignment: .trailing) {
Text(amount)
.font(.system(size: 16))
.bold()
.foregroundColor(Color.green)
Text(date.mediumStyle)
.font(.system(size: 15))
.foregroundColor(Color("textColor"))
}
}
}
}
| 25.785714 | 56 | 0.451524 |
690dad4088fe6e0d2bb6040df9f5aa1b09d8500f | 494 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}(a)(i<T) -> [T, 3] {
}
func b<Y> {
var _ = h: H) {
}
class A {
func b[1]
class a {
}
var d = b
| 26 | 79 | 0.690283 |
1c4d785245fa5075a071ec7d9dee25a85d8e53da | 10,380 | //
// NotificationsViewController.swift
// NetNewsWire-iOS
//
// Created by Stuart Breckenridge on 26/01/2022.
// Copyright © 2022 Ranchero Software. All rights reserved.
//
import UIKit
import Account
import UserNotifications
class NotificationsViewController: UIViewController {
@IBOutlet weak var notificationsTableView: UITableView!
private lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.placeholder = NSLocalizedString("Find a feed", comment: "Find a feed")
searchController.searchBar.searchBarStyle = .minimal
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
self.definesPresentationContext = true
return searchController
}()
private var status: UNAuthorizationStatus = .notDetermined
private var newArticleNotificationFilter: Bool = false {
didSet {
filterButton.menu = notificationFilterMenu()
}
}
private var filterButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("New Article Notifications", comment: "Notifications")
navigationItem.searchController = searchController
notificationsTableView.isPrefetchingEnabled = false
filterButton = UIBarButtonItem(
title: nil,
image: AppAssets.moreImage,
primaryAction: nil,
menu: notificationFilterMenu())
navigationItem.rightBarButtonItem = filterButton
reloadNotificationTableView()
NotificationCenter.default.addObserver(self, selector: #selector(updateCellsFrom(_:)), name: .WebFeedIconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(reloadVisibleCells(_:)), name: .FaviconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(reloadNotificationTableView(_:)), name: UIScene.willEnterForegroundNotification, object: nil)
}
@objc
private func reloadNotificationTableView(_ sender: Any? = nil) {
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
self.status = settings.authorizationStatus
if self.status != .authorized {
self.filterButton.isEnabled = false
self.newArticleNotificationFilter = false
}
self.notificationsTableView.reloadData()
}
}
}
@objc
private func updateCellsFrom(_ notification: Notification) {
guard let webFeed = notification.userInfo?[UserInfoKey.webFeed] as? WebFeed else { return }
if let visibleIndexPaths = notificationsTableView.indexPathsForVisibleRows {
for path in visibleIndexPaths {
if let cell = notificationsTableView.cellForRow(at: path) as? NotificationsTableViewCell {
if cell.feed! == webFeed {
cell.configure(webFeed)
return
}
}
}
}
}
@objc
private func reloadVisibleCells(_ notification: Notification) {
guard let faviconURLString = notification.userInfo?["faviconURL"] as? String,
let faviconHost = URL(string: faviconURLString)?.host else {
return
}
for cell in notificationsTableView.visibleCells {
if let notificationCell = cell as? NotificationsTableViewCell {
if let feedURLHost = URL(string: notificationCell.feed!.url)?.host {
if faviconHost == feedURLHost {
notificationCell.configure(notificationCell.feed!)
return
}
}
}
}
}
private func notificationFilterMenu() -> UIMenu {
if filterButton != nil {
if newArticleNotificationFilter {
filterButton.image = AppAssets.moreImageFill
} else {
filterButton.image = AppAssets.moreImage
}
}
let filterMenu = UIMenu(title: "",
image: nil,
identifier: nil,
options: [.displayInline],
children: [
UIAction(
title: NSLocalizedString("Show Feeds with Notifications Enabled", comment: "Feeds with Notifications"),
image: nil,
identifier: nil,
discoverabilityTitle: nil,
attributes: [],
state: newArticleNotificationFilter ? .on : .off,
handler: { [weak self] _ in
self?.newArticleNotificationFilter.toggle()
self?.notificationsTableView.reloadData()
})])
var menus = [UIMenuElement]()
menus.append(filterMenu)
for account in AccountManager.shared.sortedActiveAccounts {
let accountMenu = UIMenu(title: account.nameForDisplay, image: nil, identifier: nil, options: .singleSelection, children: [enableAllAction(for: account), disableAllAction(for: account)])
menus.append(accountMenu)
}
let combinedMenu = UIMenu(title: "",
image: nil,
identifier: nil,
options: .displayInline,
children: menus)
return combinedMenu
}
private func enableAllAction(for account: Account) -> UIAction {
let action = UIAction(title: NSLocalizedString("Enable All Notifications", comment: "Enable All"),
image: nil,
identifier: nil,
discoverabilityTitle: nil,
attributes: [],
state: .off) { [weak self] _ in
for feed in account.flattenedWebFeeds() {
feed.isNotifyAboutNewArticles = true
}
self?.notificationsTableView.reloadData()
self?.filterButton.menu = self?.notificationFilterMenu()
}
return action
}
private func disableAllAction(for account: Account) -> UIAction {
let action = UIAction(title: NSLocalizedString("Disable All Notifications", comment: "Disable All"),
image: nil,
identifier: nil,
discoverabilityTitle: nil,
attributes: [],
state: .off) { [weak self] _ in
for feed in account.flattenedWebFeeds() {
feed.isNotifyAboutNewArticles = false
}
self?.notificationsTableView.reloadData()
self?.filterButton.menu = self?.notificationFilterMenu()
}
return action
}
// MARK: - Feed Filtering
private func sortedWebFeedsForAccount(_ account: Account) -> [WebFeed] {
return Array(account.flattenedWebFeeds()).sorted(by: { $0.nameForDisplay.caseInsensitiveCompare($1.nameForDisplay) == .orderedAscending })
}
private func filteredWebFeeds(_ searchText: String? = "", account: Account) -> [WebFeed] {
sortedWebFeedsForAccount(account).filter { feed in
return feed.nameForDisplay.lowercased().contains(searchText!.lowercased())
}
}
private func feedsWithNotificationsEnabled(_ account: Account) -> [WebFeed] {
sortedWebFeedsForAccount(account).filter { feed in
return feed.isNotifyAboutNewArticles == true
}
}
}
// MARK: - UITableViewDataSource
extension NotificationsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if status == .denied { return 1 }
return 1 + AccountManager.shared.activeAccounts.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if status == .denied { return 1 }
return 0
}
if searchController.isActive {
return filteredWebFeeds(searchController.searchBar.text, account: AccountManager.shared.sortedActiveAccounts[section - 1]).count
} else if newArticleNotificationFilter == true {
return feedsWithNotificationsEnabled(AccountManager.shared.sortedActiveAccounts[section - 1]).count
} else {
return AccountManager.shared.sortedActiveAccounts[section - 1].flattenedWebFeeds().count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let openSettingsCell = tableView.dequeueReusableCell(withIdentifier: "OpenSettingsCell") as! VibrantBasicTableViewCell
return openSettingsCell
} else {
if searchController.isActive {
let cell = tableView.dequeueReusableCell(withIdentifier: "NotificationsCell") as! NotificationsTableViewCell
let account = AccountManager.shared.sortedActiveAccounts[indexPath.section - 1]
cell.configure(filteredWebFeeds(searchController.searchBar.text, account: account)[indexPath.row])
return cell
} else if newArticleNotificationFilter == true {
let cell = tableView.dequeueReusableCell(withIdentifier: "NotificationsCell") as! NotificationsTableViewCell
let account = AccountManager.shared.sortedActiveAccounts[indexPath.section - 1]
cell.configure(feedsWithNotificationsEnabled(account)[indexPath.row])
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "NotificationsCell") as! NotificationsTableViewCell
let account = AccountManager.shared.sortedActiveAccounts[indexPath.section - 1]
cell.configure(sortedWebFeedsForAccount(account)[indexPath.row])
return cell
}
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 { return nil }
return AccountManager.shared.sortedActiveAccounts[section - 1].nameForDisplay
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 0 {
if status == .denied {
return NSLocalizedString("Notification permissions are currently denied. Enable notifications in the Settings app.", comment: "Notifications denied.")
}
}
return nil
}
}
// MARK: - UITableViewDelegate
extension NotificationsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
UIApplication.shared.open(URL(string: "\(UIApplication.openSettingsURLString)")!)
}
}
}
// MARK: - UISearchControllerDelegate
extension NotificationsViewController: UISearchControllerDelegate {
func didDismissSearchController(_ searchController: UISearchController) {
print(#function)
searchController.isActive = false
notificationsTableView.reloadData()
}
}
// MARK: - UISearchBarDelegate
extension NotificationsViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchController.isActive = true
newArticleNotificationFilter = false
notificationsTableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
notificationsTableView.reloadData()
}
}
| 33.811075 | 189 | 0.740366 |
d77be03ce3a053c6c668c97aa07f3684dbeb0884 | 2,170 | // Copyright 2016-2018 Cisco Systems Inc
//
// 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
import WebexSDK
struct Config {
static let TestcaseInterval = 1.0
static let TestcaseRetryCount = 3
static let TestcasePendingCheckTimeout = 20.0
static let TestcasePendingCheckPollInterval = 0.2
static let TestcasePendingMediaInit = 3.0
static let InvalidLocalAddress = "abc/edf"
static let InvalidId = "abc"
static let InvalidEmail = EmailAddress.fromString("[email protected]")!
static let FakeSpaceId = "Y2lzY29zcGFyazovL3VzL1JPT00vYWNmNjg3MDAtY2FhZC0xMWU3LTg1Y2EtMjUzNjhiNjY3YjQz"
static let FakeSelfDeviceUrl = "https://wdmServer.com/self"
static let FakeOtherDeviceUrl = "https://wdmServer.com/other"
static let FakeWebSocketUrl = "https://WebSocketServer.com/"
static let FakeLocusServiceUrl = "https://locusServer.com/"
static let FakeConversationServiceUrl = "https://conversationServiceUrl.com/"
static let FakeCalliopeDiscoveryServiceUrl = "https://calliopeDiscoveryServiceUrl.com/"
static let FakeMetricsServiceUrl = "https://metricsServiceUrl.com/"
}
| 45.208333 | 107 | 0.764055 |
145708748c46de4e0a5cb93a5a783640e1372752 | 8,590 | //
// AppDelegate.swift
// VenEcon2
//
// Created by Girish Gupta on 08/08/2016.
// Copyright © 2016 Girish Gupta. All rights reserved.
//
import UIKit
//import Inapptics
import Firebase
import FirebaseMessaging
import UserNotifications
// https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExampleSwift/AppDelegate.swift#L40-L55 and https://firebase.google.com/docs/cloud-messaging/ios/client 20170704
//let TokenKey = "TokenKey" //with Pat on 20170715
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
SubscriptionService.shared.LoadSubscription()
FirebaseApp.configure()
//https://firebase.google.com/docs/admob/ios/quick-start 20171125
GADMobileAds.configure(withApplicationID: "ca-app-pub-7175811277195688~7903495316")
Messaging.messaging().delegate = self as! MessagingDelegate
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo // hit when app in foreground, receives notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert, .badge, .sound]) // added with Pat on 20170716 to show alert etc when app is open
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
//USOilViewController
if var ViewControllerName = userInfo["ViewToGoTo"] as? String
{
if !SubscriptionService.shared.isSubscriptionValid() //20171111 - the person hasn't subscribed so can't go to the right screen, so just default to the FX ViewController
{
ViewControllerName = "FXViewController"
}
let NavViewController = window!.rootViewController as! MyNavigationController
NavViewController.GoToViewControllerWithName(name: ViewControllerName)
}
completionHandler() //This breakpoint hit when tapping notification, where in backgrounf or in foreground
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
//UserDefaults.standard.set(fcmToken, forKey: TokenKey)
//Messaging.messaging().subscribe(toTopic: "/topics/all")
let session = URLSession(configuration: URLSessionConfiguration.default)
let url = URL(string: "https://api.venezuelaecon.com/notifications.php?id=" + fcmToken + "&lan=" + (Locale.preferredLanguages.first?.components(separatedBy: "-")[0])!)!
let request = URLRequest(url: url)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
guard let data = data else {
print("No internet connection")
return
}
if let response = String(data: data, encoding: String.Encoding.utf8)
{
print(response)
} else {
print("Couldn't do")
}
})
task.resume()
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
| 41.699029 | 188 | 0.652619 |
91440cf70981f22b65932cae14bb0d45f47321cd | 178 | import Cocoa
class MVTitlebarAccessoryViewController: NSTitlebarAccessoryViewController {
override func loadView() {
self.view = NSView(frame: NSZeroRect)
}
}
| 17.8 | 76 | 0.735955 |
209403b1e43ab90795717161212907fdb9786022 | 1,355 | //
// AppDelegate.swift
// Meditate
//
// Created by Mehmet Anıl Kul on 23.05.2021.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
@available(iOS 13.0, *)
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)
}
@available(iOS 13.0, *)
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.714286 | 177 | 0.76679 |
23884327fb215c3867a64faf56590b6a8071499a | 2,254 | //
// Node.swift
// Incremental
//
// Created by Sasha Lopoukhine on 01/11/2017.
// Copyright © 2017 Incremental. All rights reserved.
//
public class NodeBase {
public var higherNodes: [WeakBox<NodeBase>] = []
public var dirtyPseudoHeight = false
public var pseudoHeight: Int
public var getMaxChildPseudoHeight: () -> Int
public init(getMaxChildPseudoHeight: @escaping () -> Int) {
self.pseudoHeight = getMaxChildPseudoHeight() + 1
self.getMaxChildPseudoHeight = getMaxChildPseudoHeight
}
public func addHigherNode(_ higherNode: NodeBase) {
higherNodes.append(WeakBox(higherNode))
}
func getHigherNodes() -> [NodeBase] {
var nonNil = [NodeBase]()
for index in (0 ..< higherNodes.count).reversed() {
guard let higherNode = higherNodes[index].value else {
higherNodes.remove(at: index)
continue
}
nonNil.append(higherNode)
}
return nonNil
}
public final func recomputePseudoHeight() {
defer { dirtyPseudoHeight = false }
let childMax = getMaxChildPseudoHeight()
guard pseudoHeight < childMax + 1 else { return }
pseudoHeight = childMax + 1
for higherNode in getHigherNodes() {
higherNode.setPseudoHeightDirty()
}
}
public func setPseudoHeightDirty() {
dirtyPseudoHeight = true
}
public func recomputeValue() -> Bool {
fatalError("Unimplemented")
}
}
public final class Node<Value>: NodeBase {
public weak var observer: Observer<Value>? = nil
public var value: Value
public var computeValue: () -> Value
public init(computeValue: @escaping () -> Value, getMaxChildPseudoHeight: @escaping () -> Int) {
self.value = computeValue()
self.computeValue = computeValue
super.init(getMaxChildPseudoHeight: getMaxChildPseudoHeight)
}
public func observe(onUpdate: @escaping (Value) -> ()) -> Observer<Value> {
return Observer(incremental: self, onUpdate: onUpdate)
}
public override func recomputeValue() -> Bool {
self.value = computeValue()
observer?.onUpdate(value)
return true
}
}
| 26.517647 | 100 | 0.631322 |
629db9da4bb7f1dab6ff16def35a97600e209be1 | 5,425 | //
// API.swift
// Herald
//
// Created by lizhuoli on 15/5/9.
// Copyright (c) 2015年 WangShuo. All rights reserved.
//
import Foundation
protocol APIGetter{
func getResult(APIName:String, results:JSON)
func getError(APIName:String, statusCode:Int)
}
class HeraldAPI{
//先声公开API的appid
let appid = "9f9ce5c3605178daadc2d85ce9f8e064"
//代理模式,在VC使用的时候实例化一个代理,即let API = HeraldAPI(); API.delegate = self
var delegate:APIGetter?
//manager是AFNetworking的一个管理者,需要首先初始化一个
var manager = AFHTTPRequestOperationManager()
//plist是APIList.plist的根字典
var plist:NSDictionary?
//apiList是从APIList.plist中API List的字典,存储API的URL,Query等记录
var apiList:NSDictionary?
init(){
let file = NSFileManager.defaultManager()
var plistPath = Tool.libraryPath + "APIList.plist"
if !file.fileExistsAtPath(plistPath) {
let bundle = NSBundle.mainBundle()
plistPath = bundle.pathForResource("APIList", ofType: "plist") ?? ""
}
if let plistContent = NSDictionary(contentsOfFile: plistPath){
plist = plistContent
apiList = plistContent["API List"] as? NSDictionary
}
}
//单独获取属性表的根路径下的Key对应的值
func getValue(key:String) -> String? {
return plist?[key] as? String ?? nil
}
func sendAPI(APIName:String, APIParameter:String...){
//发送API,要确保APIParameter数组按照API Info.plist表中规定的先后顺序
if apiList == nil{
return;
}
let uuid = Config.UUID ?? ""
if let apiName = apiList?[APIName] as? NSDictionary{
let apiURL = apiName["URL"] as? String ?? ""
let apiParamArray = apiName["Param"] as? [String] ?? ["uuid"]//从API列表中读到的参数列表
var apiParameter = APIParameter//方法调用的传入参数列表
for param in apiParamArray{
if param == "uuid"{
apiParameter.append(uuid)
break
}
if param == "appid"{
apiParameter.append(appid)
break
}
}
let apiParamDic = NSDictionary(objects: apiParameter, forKeys: apiParamArray)//将从plist属性表中的读取到的参数数的值作为key,将方法传入的参数作为value,传入要发送的参数字典
self.postRequest(apiURL, parameter: apiParamDic, tag: APIName)
}
}
//对请求结果进行代理
func didReceiveResults(results: AnyObject, tag: String){
let json = JSON(results)//一个非常好的东西,能方便操作JSON,甚至对不是JSON格式(比如字符串,数组),保留了这个类型本身
self.delegate?.getResult(tag, results: json)
}
//对错误进行代理
func didReceiveError(code: Int, tag: String) {
self.delegate?.getError(tag, statusCode: code)
}
//POST请求,接收MIME类型为text/html,只处理非JSON返回格式的数据
func postRequest(url:String,parameter:NSDictionary,tag:String)
{
print("\nRequest:\n\(parameter)\n***********\n")
manager.responseSerializer = AFHTTPResponseSerializer()//使用自定义的Serializer,手动对返回数据进行判断
manager.POST(url, parameters: parameter,
success: {(operation :AFHTTPRequestOperation!,responseObject :AnyObject!) ->Void in
if let receiveData = responseObject as? NSData{
//按照NSDictionary -> NSArray -> NSString的顺序进行过滤
if let receiveDic = (try? NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary{
print("\nResponse(Dictionary):\n\(receiveDic)\n***********\n")
if let statusCode = receiveDic["code"] as? Int {//部分API状态码虽然为200,但是返回content为空,code为500
if statusCode == 200{
self.didReceiveResults(receiveDic, tag: tag)
}
else{
self.didReceiveError(500, tag: tag)
}
}
else{
self.didReceiveResults(receiveDic, tag: tag)
}
}
else if let receiveArray = (try? NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions.MutableContainers)) as? NSArray{
print("\nResponse(Array):\n\(receiveArray)\n***********\n")
self.didReceiveResults(receiveArray, tag: tag)
}
else if let receiveString = NSString(data: receiveData,encoding: NSUTF8StringEncoding){
print("\nResponse(String):\n\(receiveString)\n***********\n")
self.didReceiveResults(receiveString, tag: tag)
}//默认使用UTF-8编码
else{
self.didReceiveError(500, tag: tag)
}
}
},
failure: {(operation :AFHTTPRequestOperation?, error :NSError) ->Void in
var codeStatue = 500//默认错误HTTP状态码为500
if let code = operation?.response?.statusCode {
codeStatue = code
}
self.didReceiveError(codeStatue, tag: tag)
print(error)
}
)
}
//取消所有请求
func cancelAllRequest(){
manager.operationQueue.cancelAllOperations()
}
} | 38.204225 | 167 | 0.555207 |
dd42dbc2f07bc716a9e92008f7b71cd84ee9a0c6 | 29,053 | //
// ViewController.swift
// ImageMetalling-12
//
// Created by denis svinarchuk on 12.06.16.
// Copyright © 2016 ImageMetalling. All rights reserved.
//
//
// http://dolboeb.livejournal.com/2957593.html
//
//
import Cocoa
import IMProcessing
import SnapKit
import ImageIO
import MediaLibrary
import ObjectMapper
// MARK: - Расширяем многоугольник полезными утилитами
public extension IMPQuad {
public func differenceRegion(quad:IMPQuad) -> IMPRegion {
let difference = self-quad
let left = min(difference.left_bottom.x,difference.left_top.x)
let right = max(difference.right_top.x,difference.right_bottom.x)
let top = max(difference.left_top.y,difference.right_top.y)
let bottom = min(difference.left_bottom.y,difference.right_bottom.y)
return IMPRegion(left: left, right: right, top: top, bottom: bottom)
}
func fit2source(diff:IMPRegion) -> IMPRegion {
var diff = diff
diff.left = diff.left > 0 ? 0 : diff.left
diff.right = diff.right < 0 ? 0 : diff.right
diff.top = diff.top < 0 ? 0 : diff.top
diff.bottom = diff.bottom > 0 ? 0 : diff.bottom
return diff
}
///
/// Прямоугольный регион между многоугольниками
///
public func croppedRegion(quad:IMPQuad) -> IMPRegion {
let diff = fit2source(differenceRegion(quad))
return IMPRegion(left: abs(diff.left)/2, right: abs(diff.right)/2, top: abs(diff.top)/2, bottom: abs(diff.bottom)/2)
}
///
/// Прямоугольный многоугольник растянутый до соотношения сторон исходного
///
public func strechedQuad(quad:IMPQuad) -> IMPQuad {
let diff = fit2source(differenceRegion(quad))
var stretchedQuad = quad
stretchedQuad.left_bottom.x += diff.left
stretchedQuad.left_top.x += diff.left
stretchedQuad.right_bottom.x += diff.right
stretchedQuad.right_top.x += diff.right
stretchedQuad.left_top.y += diff.top
stretchedQuad.right_top.y += diff.top
stretchedQuad.right_bottom.y += diff.bottom
stretchedQuad.left_bottom.y += diff.bottom
return stretchedQuad
}
}
class ViewController: NSViewController {
var context = IMPContext()
/// Основной фильтр коррекции геометрических искажений
lazy var warp:IMPWarpFilter = {
let w = IMPWarpFilter(context: self.context)
w.backgroundColor = IMPColor(color: IMPPrefs.colors.background)
return w
}()
/// Для визуализации кропа будем использовать фильтр виньетирования.
/// Просто выставим резкие границы.
lazy var crop:IMPVignetteFilter = {
let f = IMPVignetteFilter(context:self.context, type:.Frame)
f.adjustment.blending.opacity = 0.8
f.adjustment.start = 0
f.adjustment.end = 0
f.adjustment.color = IMPPrefs.colors.background.rgb
return f
}()
/// Квадратная сетка
lazy var grid:IMTLGridGenerator = {
let g = IMTLGridGenerator(context: self.context)
g.enabled = self.toolBar.enabledGrid
g.adjustment.step = 50
g.adjustment.color = float4(1,1,1,0.5)
g.adjustment.subDivisionColor = float4(0.75,0,0,0.9)
return g
}()
/// Подсвечивание областей за которые можно тянуть картинку во время коррекции
lazy var imageSpots:IMTLGridGenerator = {
let g = IMTLGridGenerator(context: self.context)
g.enabled = self.grid.enabled
g.adjustment.step = 50
g.adjustment.color = float4(0)
g.adjustment.subDivisionColor = float4(0)
g.adjustment.spotAreaColor = float4(1,1,1,0.3)
g.adjustment.spotAreaType = .Solid
return g
}()
/// Композитный фильтры
lazy var filter:IMPFilter = {
let f = IMPFilter(context: self.context)
/// Первый слой с подсветкой будет трансфоримироваться с основной картинкой
f.addFilter(self.imageSpots)
/// Корректор
f.addFilter(self.warp)
/// "Кроп"
f.addFilter(self.crop)
/// Сетка
f.addFilter(self.grid)
return f
}()
lazy var imageView:IMPImageView = {
let v = IMPImageView(context: self.context, frame: self.view.bounds)
v.filter = self.filter
v.backgroundColor = IMPColor(color: IMPPrefs.colors.background)
/// События от курсора экрана обрабатываем для манипуляции с геометрией
v.addMouseEventObserver({ (event, location, view) in
switch event.type {
case .LeftMouseDown:
self.localMouseDown(event, location:location, view:view)
case .LeftMouseUp:
self.localMouseUp(event, location:location, view:view)
case .MouseMoved:
self.localMouseMoved(event, location:location, view:view)
case .MouseExited:
if !self.touched {
self.spotArea(IMPRegion.null)
}
case .LeftMouseDragged:
self.localMouseDragged(event, location:location, view:view)
default:
break
}
})
return v
}()
func spotArea(region:IMPRegion) {
self.imageSpots.adjustment.spotArea = region
}
override func viewDidLoad() {
super.viewDidLoad()
if !IMPContext.supportsSystemDevice {
self.asyncChanges({ () -> Void in
let alert = NSAlert(error: NSError(domain: "com.imagemetalling.08", code: 0, userInfo: [
NSLocalizedFailureReasonErrorKey:"MTL initialization error",
NSLocalizedDescriptionKey:"The system does not support MTL..."
]))
alert.runModal()
})
return
}
func loadImage(file:String, size:Float) -> IMPImageProvider? {
var image:IMPImageProvider? = nil
do{
//
// Загружаем файл и связываем источником фильтра
//
let meta = IMPJpegProvider.metadata(file)
var orientation = IMPExifOrientationUp
if let o = meta?[IMProcessing.meta.imageOrientationKey] as? NSNumber {
orientation = IMPExifOrientation(rawValue: o as Int)
}
image = try IMPJpegProvider(context: self.context, file: file, maxSize: size, orientation: orientation)
}
catch let error as NSError {
self.asyncChanges({ () -> Void in
let alert = NSAlert(error: error)
alert.runModal()
})
}
return image
}
IMPDocument.sharedInstance.addDocumentObserver { (file, type) -> Void in
if type == .Image {
if let image = loadImage(file, size: 1200) {
self.imageView.filter?.source = image
self.currentImageFile = file
self.asyncChanges({ () -> Void in
self.zoomFit()
dispatch_after(1 * NSEC_PER_SEC, dispatch_get_main_queue(), {
self.restoreConfig()
})
})
}
}
}
imageView.dragOperation = { (files) in
if files.count > 0 {
let path = files[0]
let url = NSURL(fileURLWithPath: path)
if let suffix = url.pathExtension {
for ext in ["jpg", "jpeg"] {
if ext.lowercaseString == suffix.lowercaseString {
IMPDocument.sharedInstance.currentFile = path
return true
}
}
}
}
return false
}
IMPDocument.sharedInstance.addSavingObserver { (file, type) in
if type == .Image {
if let image = loadImage(IMPDocument.sharedInstance.currentFile!, size: 0) {
NSLog("save \(file)")
let filter = IMPFilter(context: IMPContext())
let warp = IMPWarpFilter(context: filter.context)
let crop = IMPCropFilter(context: filter.context)
filter.addFilter(warp)
filter.addFilter(crop)
warp.sourceQuad = self.warp.sourceQuad
warp.destinationQuad = self.warp.destinationQuad
crop.region = self.crop.region
filter.source = image
do {
try filter.destination?.writeToJpeg(file, compression: 1)
}
catch let error as NSError {
self.asyncChanges({ () -> Void in
let alert = NSAlert(error: error)
alert.runModal()
})
}
}
}
}
IMPMenuHandler.sharedInstance.addMenuObserver { (item) -> Void in
if let tag = IMPMenuTag(rawValue: item.tag) {
switch tag {
case .zoomFit:
self.zoomFit()
case .zoom100:
self.zoom100()
default:
break
}
}
}
view.addSubview(toolBar)
toolBar.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(self.view.snp_bottom).offset(1)
make.left.equalTo(self.view.snp_left).offset(-1)
make.right.equalTo(self.view.snp_right).offset(1)
make.height.equalTo(40)
make.width.greaterThanOrEqualTo(600)
}
view.addSubview(imageView)
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.view.snp_top).offset(10)
make.bottom.equalTo(self.toolBar.snp_top).offset(0)
make.left.equalTo(self.view).offset(10)
make.right.equalTo(self.view.snp_right).offset(0)
}
}
var mouse_point_offset = NSPoint()
var mouse_point_before = NSPoint()
var mouse_point = NSPoint() {
didSet{
mouse_point_before = oldValue
mouse_point_offset = mouse_point_before - mouse_point
}
}
var touched = false
var warpDelta:Float = 0.005
/// Зона действия курсора.
/// Подразумеваем 8 зон за которые нам можно тянуть фотопластину:
/// - угловые зоны позволяют исправлять угловые искажения
/// - центральные по краяем парралельные стороным прямоугольника основного
/// "рабочего стола"
/// Кждая зона 1/3 фотопластины.
///
enum PointerPlace: Int {
case LeftBottom
case LeftTop
case RightTop
case RightBottom
case Top
case Bottom
case Left
case Right
case Undefined
}
/// Конвертируем абсолютное значение текущего курсора в координаты скорректированного объекта
func convertPoint(point:NSPoint, fromFrame:NSRect, toFrame:NSRect) -> NSPoint {
/// получаем трансформацию обратную выполненной
let transform = warp.destinationQuad.transformTo(destination: warp.sourceQuad)
let size = float2(toFrame.size.width.float,toFrame.size.height.float)
/// приводим в соответствие с относительными координатами вершин объекта
///
let x = (point.x/fromFrame.size.width - 0.5 ) * 2
let y = (point.y/fromFrame.size.height - 0.5 ) * 2
var p = ((transform * float4(x.float,y.float,0,1)).xy/2) + float2(0.5)
p = p * size
return NSPoint(x: p.x.cgfloat,y: p.y.cgfloat)
}
var pointerPlace:PointerPlace = .Undefined
/// Вычисляем зону где находится курсор
func getPointerPlace(point:NSPoint, view:NSView) -> PointerPlace {
var frame = view.frame
frame.setRegion(warp.sourceQuad.croppedRegion(warp.destinationQuad))
let w = frame.size.width.float
let h = frame.size.height.float
let point = convertPoint(point, fromFrame: view.frame, toFrame: frame)
if point.x > w/3 && point.x < w*2/3 && point.y < h/3 {
return .Bottom
}
else if point.x < w/3 && point.y >= h/3 && point.y <= h*2/3 {
return .Left
}
else if point.x < w/3 && point.y < h/3 {
return .LeftBottom
}
else if point.x < w/3 && point.y > h*2/3 {
return .LeftTop
}
else if point.x > w/3 && point.x < w*2/3 && point.y > h*2/3 {
return .Top
}
else if point.x > w*2/3 && point.y >= h/3 && point.y <= h*2/3 {
return .Right
}
else if point.x > w*2/3 && point.y < h/3 {
return .RightBottom
}
else if point.x > w*2/3 && point.y > h*2/3 {
return .RightTop
}
return .Undefined
}
func localMouseMoved(theEvent: NSEvent, location:NSPoint, view:NSView) {
if touched {return}
let point = location
var spotArea = IMPRegion.null
switch getPointerPlace(point,view:view) {
case .LeftBottom:
spotArea = IMPRegion(left: 0, right: 2/3, top: 0, bottom: 2/3)
case .Left:
spotArea = IMPRegion(left: 0, right: 2/3, top: 1/3, bottom: 1/3)
case .LeftTop:
spotArea = IMPRegion(left: 0, right: 2/3, top: 2/3, bottom: 0)
case .Top:
spotArea = IMPRegion(left: 1/3, right: 1/3, top: 2/3, bottom: 0)
case .RightTop:
spotArea = IMPRegion(left: 2/3, right: 0, top: 2/3, bottom: 0)
case .Right:
spotArea = IMPRegion(left: 2/3, right: 0, top: 1/3, bottom: 1/3)
case .RightBottom:
spotArea = IMPRegion(left: 2/3, right: 0, top: 0, bottom: 2/3)
case .Bottom:
spotArea = IMPRegion(left: 1/3, right: 1/3, top: 0, bottom: 2/3)
default:
spotArea = IMPRegion.null
break
}
self.spotArea(spotArea)
}
func localMouseDown(theEvent: NSEvent, location:NSPoint, view:NSView) {
mouse_point = location
mouse_point_before = mouse_point
mouse_point_offset = NSPoint(x: 0,y: 0)
touched = true
pointerPlace = getPointerPlace(mouse_point, view: view)
deltaStrechedQuad = warp.destinationQuad
}
func localMouseUp(theEvent: NSEvent, location:NSPoint, view:NSView) {
touched = false
deltaStrechedQuad = warp.destinationQuad-deltaStrechedQuad
self.spotArea(IMPRegion.null)
if toolBar.enabledAspectRatio {
stretchWarp()
}
else{
cropWarp()
}
}
///Растягиваем до исходного соотношения сторон
func stretchWarp(){
if !touched {
let start = warp.destinationQuad
let final = warp.sourceQuad.strechedQuad(warp.destinationQuad)
IMPDisplayTimer.cancelAll()
IMPDisplayTimer.execute(duration: duration, options: .EaseInOut, update: { (atTime) in
self.warp.destinationQuad = start.lerp(final: final, t: atTime.float)
}, complete: { (flag) in
self.updateConfig()
})
}
}
/// Подрезаем без сохранения соотношений сторон
func cropWarp() {
if !touched {
let start = crop.region
let final = warp.sourceQuad.croppedRegion(warp.destinationQuad)
IMPDisplayTimer.cancelAll()
IMPDisplayTimer.execute(duration: duration, options: .EaseInOut, update: { (atTime) in
self.crop.region = start.lerp(final: final, t: atTime.float)
}, complete: { (flag) in
self.updateConfig()
})
}
}
func pointerMoved(theEvent: NSEvent, location:NSPoint, view:NSView) {
if !touched {
return
}
mouse_point = location
let w = view.frame.size.width.float
let h = view.frame.size.height.float
let distancex = 1/w * mouse_point_offset.x.float
let distancey = 1/h * mouse_point_offset.y.float
var destinationQuad = warp.destinationQuad
if pointerPlace == .Left {
destinationQuad.left_bottom.x = destinationQuad.left_bottom.x - distancex
destinationQuad.left_top.x = destinationQuad.left_top.x - distancex
}
else if pointerPlace == .Bottom {
destinationQuad.left_bottom.y = destinationQuad.left_bottom.y - distancey
destinationQuad.right_bottom.y = destinationQuad.right_bottom.y - distancey
}
else if pointerPlace == .LeftBottom {
destinationQuad.left_bottom.x = destinationQuad.left_bottom.x - distancex
destinationQuad.left_bottom.y = destinationQuad.left_bottom.y - distancey
}
else if pointerPlace == .LeftTop {
destinationQuad.left_top.x = destinationQuad.left_top.x - distancex
destinationQuad.left_top.y = destinationQuad.left_top.y - distancey
}
else if pointerPlace == .Right {
destinationQuad.right_bottom.x = destinationQuad.right_bottom.x - distancex
destinationQuad.right_top.x = destinationQuad.right_top.x - distancex
}
else if pointerPlace == .Top {
destinationQuad.left_top.y = destinationQuad.left_top.y - distancey
destinationQuad.right_top.y = destinationQuad.right_top.y - distancey
}
else if pointerPlace == .RightBottom {
destinationQuad.right_bottom.x = destinationQuad.right_bottom.x - distancex
destinationQuad.right_bottom.y = destinationQuad.right_bottom.y - distancey
}
else if pointerPlace == .RightTop {
destinationQuad.right_top.x = destinationQuad.right_top.x - distancex
destinationQuad.right_top.y = destinationQuad.right_top.y - distancey
}
///
/// Основное действие - трансфоримируем в искомый многоугольник!
///
warp.destinationQuad = destinationQuad
updateConfig()
}
func localMouseDragged(theEvent: NSEvent, location:NSPoint, view:NSView) {
pointerMoved(theEvent, location:location, view:view)
localMouseMoved(theEvent, location:location, view:view)
}
func enableFilter(sender:NSButton){
if sender.state == 1 {
filter.enabled = true
}
else {
filter.enabled = false
}
}
var lastCropRegion = IMPRegion()
var lastStrechedQuad = IMPQuad()
lazy var deltaStrechedQuad:IMPQuad = IMPQuad.null
func aspectRatio(flag:Bool){
if flag {
lastCropRegion = crop.region
lastStrechedQuad = warp.destinationQuad
deltaStrechedQuad = IMPQuad.null
let startCrop = crop.region
let finalCrop = IMPRegion()
let startQuad = warp.destinationQuad
let finalQuad = warp.sourceQuad.strechedQuad(warp.destinationQuad)
IMPDisplayTimer.cancelAll()
IMPDisplayTimer.execute(duration: duration, options: .EaseInOut, update: { (atTime) in
self.warp.destinationQuad = startQuad.lerp(final: finalQuad, t: atTime.float)
self.crop.region = startCrop.lerp(final: finalCrop, t: atTime.float)
}, complete: { (flag) in
self.updateConfig()
})
}
else {
lastStrechedQuad = lastStrechedQuad+deltaStrechedQuad
deltaStrechedQuad = IMPQuad.null
let startQuad = warp.destinationQuad
let startCrop = self.crop.region
let finalCrop = warp.sourceQuad.croppedRegion(lastStrechedQuad)
IMPDisplayTimer.cancelAll()
IMPDisplayTimer.execute(duration: duration, options: .EaseInOut, update: { (atTime) in
self.warp.destinationQuad = startQuad.lerp(final: self.lastStrechedQuad, t: atTime.float)
self.crop.region = startCrop.lerp(final: finalCrop, t: atTime.float)
}, complete: { (flag) in
self.updateConfig()
})
}
}
func reset(){
lastCropRegion = IMPRegion()
lastStrechedQuad = IMPQuad()
deltaStrechedQuad = IMPQuad.null
let startDestination = warp.destinationQuad
let finalWarp = IMPQuad()
let startCrop = crop.region
let finalCrop = IMPRegion()
let startSlider = Float(toolBar.gridSize)
IMPDisplayTimer.cancelAll()
IMPDisplayTimer.execute(duration: duration, options: .EaseOut, update: { (atTime) in
self.warp.destinationQuad = startDestination.lerp(final: finalWarp, t: atTime.float)
self.crop.region = startCrop.lerp(final: finalCrop, t: atTime.float)
self.toolBar.gridSize = Int(startSlider.lerp(final: 50, t: atTime.float))
}, complete: { (flag) in
self.toolBar.gridSize = 50
self.updateConfig()
self.saveConfig()
})
}
func zoomFit(){
asyncChanges { () -> Void in
self.imageView.sizeFit()
}
}
func zoom100(){
asyncChanges { () -> Void in
self.imageView.sizeOriginal()
}
}
let duration:NSTimeInterval = 1
lazy var toolBar:IMPToolBar = {
let t = IMPToolBar(frame: NSRect(x: 0,y: 0,width: 100,height: 20))
t.enableFilterHandler = { (flag) in
self.filter.enabled = flag
self.grid.enabled = t.enabledGrid
}
t.enableAspectRatioHandler = { (flag) in
self.aspectRatio(flag)
}
t.enableGridHandler = { (flag) in
self.grid.enabled = flag
}
t.gridSizeHendler = { (step) in
self.grid.adjustment.step = uint(step)
}
t.resetHandler = {
self.reset()
}
return t
}()
var q = dispatch_queue_create("ViewController", DISPATCH_QUEUE_CONCURRENT)
private func asyncChanges(block:()->Void) {
dispatch_async(q, { () -> Void in
dispatch_after(0, dispatch_get_main_queue()) { () -> Void in
block()
}
})
}
override func viewWillDisappear() {
saveConfig()
}
var currentImageFile:String? = nil {
willSet {
self.saveConfig()
}
}
var configKey:String? {
if let file = self.currentImageFile {
return "IMTL-CONFIG-" + file
}
return nil
}
func restoreConfig() {
if let key = self.configKey {
let json = NSUserDefaults.standardUserDefaults().valueForKey(key) as? String
if let m = Mapper<IMTLConfig>().map(json) {
config = m
}
}
else{
config = IMTLConfig()
}
let startCrop = crop.region
let startQuad = warp.destinationQuad
IMPDisplayTimer.cancelAll()
IMPDisplayTimer.execute(duration: duration, options: .EaseOut, update: { (atTime) in
self.warp.destinationQuad = startQuad.lerp(final: self.config.quad, t: atTime.float)
self.crop.region = startCrop.lerp(final: self.config.crop, t: atTime.float)
})
}
func updateConfig() {
config.quad = warp.destinationQuad
config.crop = crop.region
}
func saveConfig(){
if let key = self.configKey {
let json = Mapper().toJSONString(config, prettyPrint: true)
NSUserDefaults.standardUserDefaults().setValue(json, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
lazy var config = IMTLConfig()
}
///
/// Всякие полезные и в целом понятные уитилитарные расширения
///
public extension NSRect {
mutating func setRegion(region:IMPRegion){
let x = region.left.cgfloat*size.width
let y = region.top.cgfloat*size.height
self = NSRect(x: origin.x+x,
y: origin.y+y,
width: size.width*(1-region.right.cgfloat)-x,
height: size.height*(1-region.bottom.cgfloat)-y)
}
}
public func == (left:NSPoint, right:NSPoint) -> Bool{
return left.x==right.x && left.y==right.y
}
public func != (left:NSPoint, right:NSPoint) -> Bool{
return !(left==right)
}
public func - (left:NSPoint, right:NSPoint) -> NSPoint {
return NSPoint(x: left.x-right.x, y: left.y-right.y)
}
public func + (left:NSPoint, right:NSPoint) -> NSPoint {
return NSPoint(x: left.x+right.x, y: left.y+right.y)
}
extension IMPJpegProvider {
static func metadata(file:String) -> [String: AnyObject]? {
let url = NSURL(fileURLWithPath: file)
guard let imageSrc = CGImageSourceCreateWithURL(url as CFURL, nil) else {
NSLog ("Error: file name : %@", file);
return nil
}
let meta = CGImageSourceCopyPropertiesAtIndex ( imageSrc, 0, nil ) as NSDictionary?
guard let metadata = meta as? [String: AnyObject] else {
NSLog ("Error: read meta : %@", file);
return nil
}
return metadata
}
}
/// https://github.com/Hearst-DD/ObjectMapper
///
/// Мапинг объектов в JSON для сохранения контекста редактирования файла, просто для удобства
///
public class IMTLConfig:Mappable {
var quad = IMPQuad()
var crop = IMPRegion()
public init(){}
required public init?(_ map: Map) {
}
public func mapping(map: Map) {
quad <- (map["quad"],transformQuad)
crop <- (map["crop"],transformRegion)
}
let transformQuad = TransformOf<IMPQuad, [String:[Float]]>(fromJSON: { (value: [String:[Float]]?) -> IMPQuad? in
if let value = value {
let left_bottom = value["left_bottom"]!
let left_top = value["left_top"]!
let right_bottom = value["right_bottom"]!
let right_top = value["right_top"]!
let object = IMPQuad(
left_bottom: float2(left_bottom[0],left_bottom[1]),
left_top: float2(left_top[0],left_top[1]),
right_bottom: float2(right_bottom[0],right_bottom[1]),
right_top: float2(right_top[0],right_top[1]))
return object
}
return nil
}, toJSON: { (value: IMPQuad?) -> [String:[Float]]? in
if let quad = value {
let json = [
"left_bottom": [quad.left_bottom.x, quad.left_bottom.y],
"left_top": [quad.left_top.x, quad.left_top.y],
"right_bottom": [quad.right_bottom.x,quad.right_bottom.y],
"right_top": [quad.right_top.x, quad.right_top.y],
]
return json
}
return nil
})
let transformRegion = TransformOf<IMPRegion, [String:Float]>(fromJSON: { (value: [String:Float]?) -> IMPRegion? in
if let value = value {
return IMPRegion(
left: value["left"]!,
right: value["right"]!,
top: value["top"]!,
bottom: value["bottom"]!)
}
return nil
}, toJSON: { (value: IMPRegion?) -> [String:Float]? in
if let region = value {
let json = [
"left": region.left,
"right": region.right,
"top": region.top,
"bottom": region.bottom,
]
return json
}
return nil
})
}
| 33.355913 | 124 | 0.547585 |
fb37d000358dbf83c154f40bb91399887e4275c8 | 152 | import Foundation
extension DispatchQueue {
static var walletQueue: DispatchQueue = {
return DispatchQueue(label: C.walletQueue)
}()
}
| 19 | 50 | 0.703947 |
1e1c5cea406ac47a6c51e8345cc41fc7d626df3c | 2,263 | //
// XBaseViewController.swift
// Swift-X
//
// Created by wangcong on 24/03/2017.
// Copyright © 2017 ApterKing. All rights reserved.
//
import UIKit
open class XBaseViewController: UIViewController, UIGestureRecognizerDelegate {
public var isNavigationBarHiddenInController: Bool {
return navigationBarHidden
}
fileprivate var navigationBarHidden = false
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override open func viewDidLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationBarHidden = self.navigationController?.isNavigationBarHidden ?? false
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if ((self.navigationController != nil) && (self.navigationController?.topViewController?.isKind(of: XBaseViewController.self))!) {
let controller: XBaseViewController = self.navigationController?.topViewController as! XBaseViewController
self.navigationController?.setNavigationBarHidden(controller.isNavigationBarHiddenInController, animated: true)
}
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override open var shouldAutorotate: Bool {
return false
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
}
| 31.873239 | 138 | 0.726911 |
08ea61b9d858e05e66fc2ad02eb565c9b6df5e05 | 15,168 | //
// CPCCalendarView_DataSource.swift
// Copyright © 2018 Cleverpumpkin, Ltd. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/* internal */ extension CPCCalendarView {
internal final class DataSource: NSObject {
internal static let cellReuseIdentifier = "CellID";
internal var calendar: CPCCalendarWrapper {
return self.startingDay.calendarWrapper;
}
internal var minimumDate: Date?;
internal var maximumDate: Date?;
internal let startingDay: CPCDay;
internal let monthViewsManager: CPCMonthViewsManager;
private let cache: Cache;
private let referenceIndexPath: IndexPath;
internal override convenience init () {
self.init (statingAt: .today);
}
internal init (statingAt startingDay: CPCDay) {
self.startingDay = startingDay;
self.monthViewsManager = CPCMonthViewsManager ();
self.referenceIndexPath = IndexPath (referenceForDay: startingDay);
self.cache = Cache (startingYear: startingDay.containingYear);
super.init ();
}
internal convenience init (statingAt startingMonth: CPCMonth) {
self.init (statingAt: startingMonth.middleDay);
}
internal convenience init (statingAt startingYear: CPCYear) {
self.init (statingAt: startingYear.middleDay);
}
internal init (replacing oldSource: DataSource, calendar: CPCCalendarWrapper) {
self.startingDay = CPCDay (containing: oldSource.startingDay.start, calendar: calendar);
self.monthViewsManager = oldSource.monthViewsManager;
self.referenceIndexPath = IndexPath (referenceForDay: self.startingDay);
self.cache = Cache (startingYear: self.startingDay.containingYear);
}
}
}
extension CPCCalendarView.DataSource: UIScrollViewDelegate {
internal func scrollViewShouldScrollToTop (_ scrollView: UIScrollView) -> Bool {
guard let collectionView = scrollView as? UICollectionView else {
return true;
}
self.scrollToToday (collectionView);
return false;
}
}
extension CPCCalendarView.DataSource: UICollectionViewDataSource {
internal func collectionView (_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return .virtualItemsCount;
}
internal func collectionView (_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = guarantee (collectionView.dequeueReusableCell (withReuseIdentifier: CPCCalendarView.DataSource.cellReuseIdentifier, for: indexPath) as? CPCCalendarView.Cell);
cell.monthViewsManager = self.monthViewsManager;
if let month = self.cachedMonth (for: indexPath) {
cell.month = month;
} else {
self.prepareCacheData (for: indexPath, highPriority: true, collectionView: collectionView);
}
return cell;
}
}
extension CPCCalendarView.DataSource: UICollectionViewDataSourcePrefetching {
internal func collectionView (_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
guard let (minIndexPath, maxIndexPath) = indexPaths.minmax () else {
return;
}
if (self.cachedMonth (for: minIndexPath) == nil) {
self.cache.fetchCacheItems (for: minIndexPath, highPriority: false, completion: self.monthsUpdateHandler (collectionView));
}
if (self.cachedMonth (for: maxIndexPath) == nil) {
self.cache.fetchCacheItems (for: minIndexPath, highPriority: false, completion: self.monthsUpdateHandler (collectionView));
}
}
}
/* internal */ extension CPCCalendarView.DataSource {
internal func scrollToToday (_ collectionView: UICollectionView, animated: Bool = true) {
return self.scroll (collectionView: collectionView, to: CPCDay (containing: self.scrollToTodayDate, calendar: self.calendar), animated: animated);
}
internal func scroll (collectionView: UICollectionView, to day: CPCDay, animated: Bool = true) {
let distance = self.startingMonth.distance (to: day.containingMonth);
let indexPath = self.referenceIndexPath.offset (by: distance);
collectionView.scrollToItem (at: indexPath, at: .centeredVertically, animated: animated);
}
}
extension CPCCalendarView.DataSource: CPCCalendarViewLayoutDelegate {
internal func referenceIndexPathForCollectionView (_ collectionView: UICollectionView) -> IndexPath {
return self.referenceIndexPath;
}
internal func collectionView (_ collectionView: UICollectionView, estimatedAspectRatioComponentsForItemAt indexPath: IndexPath) -> CPCMonthView.AspectRatio {
let partialAttributes = self.monthViewsManager.monthViewPartialLayoutAttributes (separatorWidth: collectionView.separatorWidth);
if let month = self.cachedMonth (for: indexPath) {
return CPCMonthView.aspectRatioComponents (for: CPCMonthView.LayoutAttributes (month: month, partialAttributes: partialAttributes))!;
}
let aspectRatiosRange = CPCMonthView.aspectRatiosComponentsRange (for: partialAttributes, using: self.calendar.calendar);
return (
multiplier: sqrt (aspectRatiosRange.lower.multiplier * aspectRatiosRange.upper.multiplier),
constant: (aspectRatiosRange.lower.constant + aspectRatiosRange.upper.constant) / 2
);
}
internal func collectionView (_ collectionView: UICollectionView, startOfSectionFor indexPath: IndexPath) -> IndexPath {
let month = self.cache.month (for: indexPath), year = month.containingYear, monthIndex = year.index (of: month)!;
return indexPath.offset (by: year.distance (from: monthIndex, to: year.startIndex));
}
internal func collectionView (_ collectionView: UICollectionView, endOfSectionFor indexPath: IndexPath) -> IndexPath {
let month = self.cache.month (for: indexPath), year = month.containingYear, monthIndex = year.index (of: month)!;
return indexPath.offset (by: year.distance (from: monthIndex, to: year.endIndex));
}
internal func collectionView (_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? CPCCalendarView.Cell {
cell.monthViewsManager = self.monthViewsManager;
cell.month = self.cachedMonth (for: indexPath);
let minimumDay: CPCDay?, maximumDay: CPCDay?;
if let minimumDate = self.minimumDate {
minimumDay = CPCDay (containing: minimumDate, calendar: self.calendar);
} else {
minimumDay = nil;
}
if let maximumDate = self.maximumDate {
maximumDay = CPCDay (containing: maximumDate, calendar: self.calendar);
} else {
maximumDay = nil;
}
switch (minimumDay, maximumDay) {
case (nil, nil):
cell.enabledRegion = nil;
case (.some (let minimumDay), nil):
cell.enabledRegion = minimumDay ..< CPCDay (containing: .distantFuture, calendar: self.calendar);
case (nil, .some (let maximumDay)):
cell.enabledRegion = CPCDay (containing: .distantPast, calendar: self.calendar) ..< maximumDay;
case (.some (let minimumDay), .some (let maximumDay)):
cell.enabledRegion = minimumDay ..< maximumDay;
}
}
}
}
private extension CPCCalendarView.DataSource {
private final class Cache {
private var cachedMonths: FloatingBaseArray <CPCMonth>;
private var updatesLock = DispatchSemaphore (value: 1);
private var firstCalculatedIndexPath = UnfairThreadsafeStorage (IndexPath?.none);
private var lastCalculatedIndexPath = UnfairThreadsafeStorage (IndexPath?.none);
private let backgroundQueue = DispatchQueue (label: "CPCCalendarDataSourceCache", qos: .default, attributes: .concurrent);
private let priorityQueue = DispatchQueue (label: "CPCCalendarDataSourceCeche", qos: .userInteractive, attributes: .concurrent);
fileprivate init (startingYear: CPCYear) {
let prevYear = startingYear.prev, nextYear = startingYear.next;
self.cachedMonths = FloatingBaseArray (Array (prevYear) + startingYear + nextYear, baseOffset: .zerothVirtualItemIndex - prevYear.count);
}
fileprivate func cachedMonth (for indexPath: IndexPath) -> CPCMonth? {
return self.cachedMonths.indices.contains (indexPath.item) ? self.cachedMonths [indexPath.item] : nil;
}
fileprivate func month (for indexPath: IndexPath) -> CPCMonth {
let nearestMonthIndex: Int;
if (indexPath.item < self.cachedMonths.startIndex) {
nearestMonthIndex = self.cachedMonths.startIndex;
} else if (indexPath.item >= self.cachedMonths.endIndex) {
nearestMonthIndex = self.cachedMonths.endIndex - 1;
} else {
return self.cachedMonths [indexPath.item];
}
return self.cachedMonths [nearestMonthIndex].advanced (by: indexPath.item - nearestMonthIndex);
}
fileprivate func fetchCacheItems (for indexPath: IndexPath, highPriority: Bool, completion: @escaping (_ updated: [IndexPath]) -> ()) {
let canCalculateEarlierMonths: Bool = self.firstCalculatedIndexPath.withMutableStoredValue {
if let currentFirstIndexPath = $0, (indexPath >= currentFirstIndexPath) {
return false;
}
$0 = indexPath;
return true;
}
let canCalculateLaterMonths: Bool = self.lastCalculatedIndexPath.withMutableStoredValue {
if let currentLastIndexPath = $0, (indexPath < currentLastIndexPath) {
return false;
}
$0 = indexPath.offset (by: -1);
return true;
}
guard (canCalculateLaterMonths || canCalculateEarlierMonths), !(self.cachedMonths.indices ~= indexPath.item) else {
return;
}
(highPriority ? self.priorityQueue : self.backgroundQueue).async { self.calculateAndStoreYears (untilReaching: indexPath, completion: completion) };
}
private func determineCalculationAttributes (for indexPath: IndexPath) -> (start: CPCMonth, targetCount: Int, advance: Int)? {
self.updatesLock.wait ();
defer { self.updatesLock.signal () }
if (indexPath.item < self.cachedMonths.startIndex) {
return (
start: self.cachedMonths [self.cachedMonths.startIndex],
targetCount: self.cachedMonths.startIndex - indexPath.item,
advance: -1
);
} else if (indexPath.item >= self.cachedMonths.endIndex) {
return (
start: self.cachedMonths [self.cachedMonths.endIndex - 1],
targetCount: indexPath.item - self.cachedMonths.endIndex + 1,
advance: 1
);
} else {
return nil;
}
}
private func calculateAndStoreYears (untilReaching indexPath: IndexPath, completion: @escaping (_ updated: [IndexPath]) -> ()) {
guard let (start, targetCount, advance) = self.determineCalculationAttributes (for: indexPath) else {
return;
}
var months = [CPCMonth] (), minimumIndexPath: IndexPath?, maximumIndexPath: IndexPath?;
months.reserveCapacity (targetCount);
for _ in 0 ..< targetCount {
months.append ((months.last ?? start).advanced (by: advance));
}
let lastMonth = months.last ?? start, lastYear = lastMonth.containingYear, monthIndex = lastYear.index (of: lastMonth)!, endIndexPath: IndexPath;
if (advance > 0) {
let additionalMonths = lastYear [lastYear.index (after: monthIndex)...];
months.append (contentsOf: additionalMonths);
endIndexPath = indexPath.offset (by: additionalMonths.count)
} else {
let additionalMonths = lastYear [..<monthIndex];
months.append (contentsOf: additionalMonths.reversed ());
endIndexPath = indexPath.offset (by: -additionalMonths.count);
}
self.updatesLock.wait ();
defer { self.updatesLock.signal () }
let indexPaths: [IndexPath];
if (endIndexPath.item < self.cachedMonths.startIndex) {
indexPaths = (endIndexPath.item ..< self.cachedMonths.startIndex).map { IndexPath (item: $0, section: 0) };
self.cachedMonths.prepend (contentsOf: months.suffix (indexPaths.count).reversed ());
} else if (endIndexPath.item >= self.cachedMonths.endIndex) {
indexPaths = (self.cachedMonths.endIndex ... endIndexPath.item).map { IndexPath (item: $0, section: 0) };
self.cachedMonths.append (contentsOf: months.suffix (indexPaths.count));
} else {
return;
}
DispatchQueue.main.async {
completion (indexPaths);
};
}
}
}
/* fileprivate */ extension CPCCalendarView.DataSource {
fileprivate var startingMonth: CPCMonth {
return self.startingDay.containingMonth;
}
fileprivate var startingYear: CPCYear {
return self.startingDay.containingYear;
}
fileprivate func cachedMonth (for indexPath: IndexPath) -> CPCMonth? {
return self.cache.cachedMonth (for: indexPath);
}
private func prepareCacheData (for indexPath: IndexPath, highPriority: Bool, collectionView: UICollectionView) {
self.cache.fetchCacheItems (for: indexPath, highPriority: highPriority, completion: self.monthsUpdateHandler (collectionView));
}
private func monthsUpdateHandler (_ collectionView: UICollectionView) -> ([IndexPath]) -> () {
return { [weak self, weak collectionView] indexPaths in
guard let strongSelf = self else {
return;
}
guard let collectionView = collectionView, collectionView.dataSource === strongSelf else {
return;
}
collectionView.reloadItems (at: indexPaths);
}
}
private var scrollToTodayDate: Date {
if let minimumDate = self.minimumDate, minimumDate.timeIntervalSinceNow > 0.0 {
return minimumDate;
} else if let maximumDate = self.maximumDate, maximumDate.timeIntervalSinceNow < 0.0 {
return maximumDate;
} else {
return Date ();
}
}
}
/* fileprivate */ extension IndexPath {
fileprivate init (referenceForDay day: CPCDay) {
self.init (item: .zerothVirtualItemIndex + day.containingYear [ordinal: 0].distance (to: day.containingMonth), section: 0);
}
}
/* fileprivate */ extension Sequence where Element: Comparable {
fileprivate func minmax () -> (minimum: Element, maximum: Element)? {
var iterator = self.makeIterator ();
guard let first = iterator.next () else {
return nil;
}
var result = (minimum: first, maximum: first);
while let next = iterator.next () {
result.minimum = Swift.min (result.minimum, next);
result.maximum = Swift.max (result.maximum, next);
}
return result;
}
}
/* fileprivate */ extension CPCCalendarUnit {
fileprivate var middleDay: CPCDay {
return CPCDay (containing: self.start + self.duration / 2, calendar: self.calendarWrapper);
}
}
/* fileprivate */ extension Int {
fileprivate static let virtualItemsCount = 0x40000;
fileprivate static let zerothVirtualItemIndex = Int.virtualItemsCount / 2;
}
| 40.55615 | 171 | 0.740968 |
69ab9cd97e17c5f4ad28a8c97ad00f87953d0b02 | 1,433 | //
// AppDelegate.swift
// PreviewOnDifferentDevices
//
// Created by Edgar Nzokwe on 3/30/20.
// Copyright © 2020 Edgar Nzokwe. 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.
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.
}
}
| 37.710526 | 179 | 0.750174 |
e64e53b1d46f1ac88eda5302f27dba6125ded6cc | 2,437 | //
// Copyright (c) 2020, Erick Jung.
// All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import Foundation
public class Button: GuiNode,
SizeModifier,
BackgroundColorModifier,
BorderColorModifier,
ActiveColorModifier,
HoveredColorModifier {
public enum ButtonType {
/// sizeable button
case `default`
/// small fixed size
case small
}
public var size: GuiSize?
public var backgroundColor: GuiColor?
public var borderColor: GuiColor?
public var activeColor: GuiColor?
public var hoveredColor: GuiColor?
public var text: String
public private(set) var type: ButtonType
private let onTap: (() -> Void)?
public init(_ text: String,
type: ButtonType = .default,
onTap: (() -> Void)? = nil) {
self.text = text
self.type = type
self.onTap = onTap
}
public override func drawComponent() {
if let color = self.backgroundColor {
ImGuiWrapper.pushStyleColor(GuiColorProperty.button.rawValue, colorRef: color.cgColor)
}
if let color = self.borderColor {
ImGuiWrapper.pushStyleColor(GuiColorProperty.border.rawValue, colorRef: color.cgColor)
}
if let color = self.activeColor {
ImGuiWrapper.pushStyleColor(GuiColorProperty.buttonActive.rawValue, colorRef: color.cgColor)
}
if let color = self.hoveredColor {
ImGuiWrapper.pushStyleColor(GuiColorProperty.buttonHovered.rawValue, colorRef: color.cgColor)
}
switch self.type {
case .small:
if ImGuiWrapper.smallButton(self.text) {
onTap?()
}
case .default:
if ImGuiWrapper.button(self.text, size: self.size ?? .zero) {
onTap?()
}
}
if self.backgroundColor != nil {
ImGuiWrapper.popStyleColor(1)
}
if self.borderColor != nil {
ImGuiWrapper.popStyleColor(1)
}
if self.activeColor != nil {
ImGuiWrapper.popStyleColor(1)
}
if self.hoveredColor != nil {
ImGuiWrapper.popStyleColor(1)
}
}
}
| 25.385417 | 105 | 0.576939 |
ed36c31ea84c11437fabc199778d1adc326b3261 | 524 | //
// AppDelegate.swift
// VideoPlayer
//
// Created by Nicolás Miari on 2020/02/03.
// Copyright © 2020 Nicolás Miari. All rights reserved.
//
import UIKit
import UIKit
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
| 23.818182 | 145 | 0.730916 |
2180ef9755fd655bee01b1564bfe56556a2fd5b5 | 3,921 | //
// EventRow.swift
// Countdown
//
// Created by funway on 2020/7/30.
// Copyright © 2020 funwaywang. All rights reserved.
//
import SwiftUI
import Combine
struct EventRow: View {
let cdEvent: CountdownEvent
#if DEBUG
private let deallocPrinter: DeallocPrinter!
#endif
@State var hovered = false
@State var progress: Double
@State var endTimeString: String = ""
@State var relativeTimeString: String
init(cdEvent: CountdownEvent) {
self.cdEvent = cdEvent
// 在构造器中对 @State 值进行初始化的正确方式
self._progress = State(initialValue: cdEvent.progress)
self._relativeTimeString = State(initialValue: cdEvent.endAt.toStringWithRelativeTimeEx())
#if DEBUG
self.deallocPrinter = DeallocPrinter(forType: String(describing: Self.self) + "[\(cdEvent.title)]")
#endif
}
var body: some View {
ZStack {
HStack {
CircularProgress(progress: CGFloat(progress), foregroundColor: Color(cdEvent.color), lineWidth: 4, clockwise: false)
.frame(width: 32, height: 32)
VStack(alignment: .leading, spacing: 5.0) {
Text(cdEvent.title)
.font(Font.system(size: 13, weight: .medium).monospacedDigit())
Text(endTimeString)
.font(Font.system(size: 12, weight: .light).monospacedDigit())
}
Spacer()
VStack(alignment: .trailing, spacing: 5.0) {
Text(relativeTimeString)
.font(Font.system(size: 13, weight: .medium).monospacedDigit())
Text(String(format: "%.1f%%", (progress * 1000).rounded(.down) / 10))
.font(Font.system(size: 12, weight: .light).monospacedDigit())
}
if hovered {
Image("RightIcon")
.opacity(0.5)
.transition(AnyTransition.opacity.combined(with: .move(edge: .trailing)))
}
}
if hovered {
Rectangle()
.fill(LinearGradient(
gradient: .init(colors: [.clear, .secondary, .clear]),
startPoint: .leading,
endPoint: .trailing
)).opacity(0.1)
}
}
.frame(height: Theme.popViewEventRowHeight)
.onAppear(perform: {
self.refresh()
})
.onReceive(AppTimer.shared.$ticktock) { currentTime in
self.refresh()
}
.onHoverAware { hovered in
withAnimation {
self.hovered = hovered
}
}
}
func refresh() {
progress = cdEvent.progress
if (cdEvent.endAt.compare(.isToday) || cdEvent.endAt.compare(.isTomorrow)) {
if Preference.shared.display24hour {
self.endTimeString = cdEvent.endAt.toString(format: .custom("HH:mm"))
} else {
self.endTimeString = cdEvent.endAt.toString(format: .custom(DateFormatter.dateFormat(fromTemplate: "jm", options: 0, locale: Locale.current)!))
}
}else {
self.endTimeString = cdEvent.endAt.toString(format: .custom("yyyy/M/d"))
}
relativeTimeString = cdEvent.endAt.toStringWithRelativeTimeEx()
}
}
struct EventRow_Previews: PreviewProvider {
static var previews: some View {
let cdEvents = loadCountdownEvent()
return VStack {
ForEach(cdEvents, id: \.self.uuid) { cdEvent in
EventRow(cdEvent: cdEvent)
}
}.frame(width: 360)
.padding(.horizontal, 10)
}
}
| 33.228814 | 159 | 0.522571 |
56a4a680203aa3d9c3b2ecb21ad87f2791145d3f | 3,130 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension SPSafeSymbol {
public static var platter: Platter { .init(name: "platter") }
open class Platter: SPSafeSymbol {
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var _2FilledIpad: SPSafeSymbol { ext(.start + ".2.filled.ipad") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var _2FilledIpadLandscape: SPSafeSymbol { ext(.start + ".2.filled.ipad.landscape") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var _2FilledIphone: SPSafeSymbol { ext(.start + ".2.filled.iphone") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var _2FilledIphoneLandscape: SPSafeSymbol { ext(.start + ".2.filled.iphone.landscape") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var bottomApplewatchCase: SPSafeSymbol { ext(.start + ".bottom.applewatch.case") }
@available(iOS 15.1, macOS 12.0, tvOS 15.1, watchOS 8.1, *)
open var filledBottomAndArrowDownIphone: SPSafeSymbol { ext(.start + ".filled.bottom.and.arrow.down.iphone") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var filledBottomApplewatchCase: SPSafeSymbol { ext(.start + ".filled.bottom.applewatch.case") }
@available(iOS 15.1, macOS 12.0, tvOS 15.1, watchOS 8.1, *)
open var filledBottomIphone: SPSafeSymbol { ext(.start + ".filled.bottom.iphone") }
@available(iOS 15.1, macOS 12.0, tvOS 15.1, watchOS 8.1, *)
open var filledTopAndArrowUpIphone: SPSafeSymbol { ext(.start + ".filled.top.and.arrow.up.iphone") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var filledTopApplewatchCase: SPSafeSymbol { ext(.start + ".filled.top.applewatch.case") }
@available(iOS 15.1, macOS 12.0, tvOS 15.1, watchOS 8.1, *)
open var filledTopIphone: SPSafeSymbol { ext(.start + ".filled.top.iphone") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var topApplewatchCase: SPSafeSymbol { ext(.start + ".top.applewatch.case") }
}
}
| 54.912281 | 112 | 0.719808 |
5b388be6c5a09791138c3e4d375cb7cb5bff69df | 4,662 | //
// NotificationSetting.swift
// StudyHub
//
// Created by Дмитрий Лисин on 03.04.2020.
// Copyright © 2020 Dmitriy Lisin. All rights reserved.
//
import SwiftUI
struct NotificationSetting: View {
@EnvironmentObject var sessionStore: SessionStore
@ObservedObject private var notificationStore = NotificationStore.shared
@State private var notificationLesson: Bool = true
private func openSettings() {
guard let settingsURL = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(settingsURL)
else {
return
}
UIApplication.shared.open(settingsURL)
}
var footerNotification: Text {
switch notificationStore.enabled {
case .denied:
return Text("Чтобы активировать уведомления нажмите на кнопку \"Включить уведомления\", после чего активируйте уведомления в настройках.")
case .notDetermined:
return Text("Чтобы активировать уведомления нажмите на кнопку \"Включить уведомления\".")
default:
return Text("")
}
}
var footerNotificationLesson: Text {
switch notificationLesson {
case true:
return Text("Здесь настраивается время отсрочки уведомлений от начала пары.")
case false:
return Text("Если вы хотите получать уведомления перед началом пары, активируйте этот параметр.")
}
}
var body: some View {
Form {
if notificationStore.enabled == .authorized {
Section(header: Text("Настройки уведомлений о паре").fontWeight(.bold), footer: footerNotificationLesson) {
Toggle(isOn: $notificationLesson.animation()) {
Image(systemName: "person.2")
.frame(width: 24)
.foregroundColor(Color.rgb(red: sessionStore.userData.rValue, green: sessionStore.userData.gValue, blue: sessionStore.userData.bValue))
Text("Перед парой")
}
if notificationLesson {
Stepper(value: $sessionStore.userData.notifyMinute, in: 5 ... 30) {
Image(systemName: "timer")
.frame(width: 24)
.foregroundColor(Color.rgb(red: sessionStore.userData.rValue, green: sessionStore.userData.gValue, blue: sessionStore.userData.bValue))
Text("\(sessionStore.userData.notifyMinute) мин")
}
}
}
}
Section(header: Text("Активация уведомлений").fontWeight(.bold), footer: footerNotification) {
if notificationStore.enabled == .authorized {
HStack {
Image(systemName: "bell")
.frame(width: 24)
.foregroundColor(Color.rgb(red: sessionStore.userData.rValue, green: sessionStore.userData.gValue, blue: sessionStore.userData.bValue))
Button(action: openSettings) {
Text("Выключить уведомления")
.foregroundColor(.primary)
}
}
}
if notificationStore.enabled == .notDetermined {
HStack {
Image(systemName: "bell")
.frame(width: 24)
.foregroundColor(Color.rgb(red: sessionStore.userData.rValue, green: sessionStore.userData.gValue, blue: sessionStore.userData.bValue))
Button(action: notificationStore.requestPermission) {
Text("Включить уведомления")
.foregroundColor(.primary)
}
}
}
if notificationStore.enabled == .denied {
HStack {
Image(systemName: "bell")
.frame(width: 24)
.foregroundColor(Color.rgb(red: sessionStore.userData.rValue, green: sessionStore.userData.gValue, blue: sessionStore.userData.bValue))
Button(action: openSettings) {
Text("Включить уведомления")
.foregroundColor(.primary)
}
}
}
}
}
.environment(\.horizontalSizeClass, .regular)
.navigationBarTitle("Уведомления", displayMode: .inline)
}
}
| 44.4 | 167 | 0.536894 |
2631de637ed1513312e722ebdf25353e4b8ced94 | 438 | //
// SaveState.swift
// Easy Share Uploader
//
// Created by Ozan Mirza on 2/19/21.
// Copyright © 2021 Aries Sciences LLC. All rights reserved.
//
import Foundation
struct SaveState {
private(set) var saved: Bool
private(set) var destination: URL?
init(destination: URL) {
self.destination = destination
saved = true
}
init() {
destination = nil
saved = false
}
}
| 17.52 | 61 | 0.600457 |
d5354a4d8d18a3091d826bfa79da97ded96c3d7f | 2,847 | //
// UIView+SimpleLayout.swift
// SimpleLayout
//
// Created by pisces on 9/7/16.
// Copyright © 2016 Steve Kim. All rights reserved.
//
import UIKit
extension UIView {
// MARK: - Public Constants
private struct AssociatedKeys {
static var LayoutName = "LayoutName"
}
// MARK: - Public Properties
private(set) public var layout: SimpleLayoutObject {
get {
if let layout = objc_getAssociatedObject(self, &AssociatedKeys.LayoutName) as? SimpleLayoutObject {
return layout
}
translatesAutoresizingMaskIntoConstraints = false
let layout = SimpleLayoutObject(view: self)
objc_setAssociatedObject(self, &AssociatedKeys.LayoutName, layout, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return layout
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.LayoutName, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var right: CGFloat {
return frame.maxX
}
public var bottom: CGFloat {
return frame.maxY
}
public var x: CGFloat {
get {
return frame.minX
}
set {
frame = CGRect(x: newValue, y: frameOrigin.y, width: frameSize.width, height: frameSize.height)
}
}
public var y: CGFloat {
get {
return frame.minY
}
set {
frame = CGRect(x: frameOrigin.x, y: newValue, width: frameSize.width, height: frameSize.height)
}
}
public var height: CGFloat {
get {
return frame.height
}
set {
frame = CGRect(x: frameOrigin.x, y: frameOrigin.y, width: frameSize.width, height: newValue)
}
}
public var width: CGFloat {
get {
return frame.width
}
set {
frame = CGRect(x: frameOrigin.x, y: frameOrigin.y, width: newValue, height: frameSize.height)
}
}
public var frameOrigin: CGPoint {
get {
return frame.origin
}
set {
frame = CGRect(x: newValue.x, y: newValue.y, width: frame.size.width, height: frame.size.height)
}
}
public var frameSize: CGSize {
get {
return frame.size
}
set {
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: newValue.width, height: newValue.height)
}
}
public var _safeAreaInsets: UIEdgeInsets {
if #available(iOS 11, *) {
return safeAreaInsets
}
return .zero
}
public var _safeAreaLayoutGuide: UILayoutGuide? {
if #available(iOS 11, *) {
return safeAreaLayoutGuide
}
return nil
}
}
| 27.640777 | 138 | 0.568669 |
146648c0fc095b2319c05730b122f77ea309e657 | 216 | //
// GSLExtensible.swift
// GSLAdditions
//
public struct GSLExtension<T> {
// MARK: - Properties
let target: T
// MARK: - Initializers
init(_ target: T) {
self.target = target
}
}
| 12.705882 | 31 | 0.569444 |
fc94aa2242aa64b87793000782c5db17bc9530dd | 38,744 | //
// TimePeriodTests.swift
// DateToolsTests
//
// Created by Grayson Webster on 8/19/16.
// Copyright © 2016 Matthew York. All rights reserved.
//
import XCTest
@testable import DateToolsSwift
class TimePeriodTests : XCTestCase {
var formatter = DateFormatter()
var controlTimePeriod = TimePeriod()
override func setUp() {
self.formatter.dateFormat = "yyyy MM dd HH:mm:ss.SSS"
self.formatter.timeZone = TimeZone(abbreviation: "UTC")
self.controlTimePeriod.beginning = self.formatter.date(from: "2014 11 05 18:15:12.000")
self.controlTimePeriod.end = self.formatter.date(from: "2016 11 05 18:15:12.000")
}
override func tearDown() {
super.tearDown()
}
// MARK: - Inits
func testInits() {
//Basic init
let testPeriodInit = TimePeriod(beginning: (self.controlTimePeriod.beginning)!, end: self.controlTimePeriod.end!)
XCTAssertTrue(self.controlTimePeriod.equals(testPeriodInit) && self.controlTimePeriod.end!.equals(testPeriodInit.end!))
}
// **Add more init tests**
//MARK: - Operator Overloads
func testEqualsOperator() {
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.end!)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testAdditionOperator() {
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.end!) + 86400
let endDate = self.formatter.date(from: "2016 11 06 18:15:12.000")
XCTAssertTrue(controlTimePeriod.beginning! == self.controlTimePeriod.beginning! && endDate == testPeriod.end!)
}
func testAdditionOperatorChunk() {
let testPeriod = controlTimePeriod + 1.days
let endDate = self.formatter.date(from: "2016 11 06 19:15:12.000") //Includes DST change
XCTAssertTrue(controlTimePeriod.beginning! == self.controlTimePeriod.beginning! && endDate == testPeriod.end!)
}
func testSubtractionOperator() {
let testPeriod = controlTimePeriod - 86400
let endDate = self.formatter.date(from: "2016 11 04 18:15:12.000")
XCTAssertTrue(controlTimePeriod.beginning! == self.controlTimePeriod.beginning! && endDate == testPeriod.end!)
}
func testSubtractionOperatorChunk() {
let testPeriod = controlTimePeriod - 1.days
let endDate = self.formatter.date(from: "2016 11 04 18:15:12.000")
XCTAssertTrue(controlTimePeriod.beginning! == self.controlTimePeriod.beginning! && endDate == testPeriod.end!)
}
// MARK: - Time Period Information
func testIsMoment() {
//Is moment
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.beginning!)
XCTAssertTrue(testPeriod.isMoment)
//Is not moment
XCTAssertFalse(self.controlTimePeriod.isMoment)
}
func testDurationInYears() {
XCTAssertEqual(2, self.controlTimePeriod.years)
}
func testDurationInWeeks() {
XCTAssertEqual(104, self.controlTimePeriod.weeks)
}
func testDurationInDays() {
XCTAssertEqual(731, self.controlTimePeriod.days)
}
func testDurationInHours() {
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.beginning!.add(4.hours))
XCTAssertEqual(4, testPeriod.hours)
}
func testDurationInMinutes() {
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.beginning!.add(4.hours))
XCTAssertEqual(240, testPeriod.minutes)
}
func testDurationInSeconds() {
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.beginning!.add(4.hours))
XCTAssertEqual(14400, testPeriod.seconds)
}
// MARK: - Time Period Relationship
func testEquals() {
//Same
XCTAssertTrue(self.controlTimePeriod.equals(self.controlTimePeriod))
//Different ending
let differentEndPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: self.controlTimePeriod.end!.add(1.years))
XCTAssertFalse(self.controlTimePeriod.equals(differentEndPeriod))
//Different beginning
let differentStartPeriod = TimePeriod (beginning: self.controlTimePeriod.beginning!.subtract(1.years), end: self.controlTimePeriod.end!)
XCTAssertFalse(self.controlTimePeriod.equals(differentStartPeriod))
//Both endings different
let differentStartAndEndPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!.subtract(1.weeks), end: self.controlTimePeriod.end!.subtract(1.weeks))
XCTAssertFalse(self.controlTimePeriod.equals(differentStartAndEndPeriod))
}
func testInside() {
//POSITIVE MATCHES
//Test exact match
//Test exact match
let testTimePeriodExact = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(testTimePeriodExact.isInside(of: self.controlTimePeriod))
//Test same start
let testTimePeriodSameStart = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!)
XCTAssertTrue(testTimePeriodSameStart.isInside(of: self.controlTimePeriod))
//Test same end
let testTimePeriodSameEnd = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(testTimePeriodSameEnd.isInside(of: self.controlTimePeriod))
//Test completely inside
let testTimePeriodCompletelyInside = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 04 05 18:15:12.000")!)
XCTAssertTrue(testTimePeriodCompletelyInside.isInside(of: self.controlTimePeriod))
//NEGATIVE MATCHES
//Test before
let testTimePeriodBefore = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 04 18:15:12.000")!)
XCTAssertFalse(testTimePeriodBefore.isInside(of: self.controlTimePeriod))
//Test end same as start
let testTimePeriodEndSameStart = TimePeriod(beginning: self.formatter.date(from: "2013 11 05 18:15:12.000")!, end: self.formatter.date(from: "2014 11 05 18:15:12.000")!)
XCTAssertFalse(testTimePeriodEndSameStart.isInside(of: self.controlTimePeriod))
//Test end inside
let testTimePeriodEndInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 07 18:15:12.000")!)
XCTAssertFalse(testTimePeriodEndInside.isInside(of: self.controlTimePeriod))
//Test start inside
let testTimePeriodStartInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 07 18:15:12.000")!, end: self.formatter.date(from: "2016 12 05 18:15:12.000")!)
XCTAssertFalse(testTimePeriodStartInside.isInside(of: self.controlTimePeriod))
//Test start same as end
let testTimePeriodStartSameEnd = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 10 18:15:12.000")!)
XCTAssertFalse(testTimePeriodStartSameEnd.isInside(of: self.controlTimePeriod))
//Test after
let testTimePeriodAfter = TimePeriod(beginning: self.formatter.date(from: "2016 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 12 10 18:15:12.000")!)
XCTAssertFalse(testTimePeriodAfter.isInside(of: self.controlTimePeriod))
}
func testContainsInterval() {
//POSITIVE MATCHES
//Test exact match
let testTimePeriodExact = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.contains(testTimePeriodExact))
//Test same start
let testTimePeriodSameStart = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.contains(testTimePeriodSameStart))
//Test same end
let testTimePeriodSameEnd = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.contains(testTimePeriodSameEnd))
//Test completely inside
let testTimePeriodCompletelyInside = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 04 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.contains(testTimePeriodCompletelyInside))
//NEGATIVE MATCHES
//Test before
let testTimePeriodBefore = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 04 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.contains(testTimePeriodBefore))
//Test end same as start
let testTimePeriodEndSameStart = TimePeriod(beginning: self.formatter.date(from: "2013 11 05 18:15:12.000")!, end: self.formatter.date(from: "2014 11 05 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.contains(testTimePeriodEndSameStart))
//Test end inside
let testTimePeriodEndInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 07 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.contains(testTimePeriodEndInside))
//Test start inside
let testTimePeriodStartInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 07 18:15:12.000")!, end: self.formatter.date(from: "2016 12 05 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.contains(testTimePeriodStartInside))
//Test start same as end
let testTimePeriodStartSameEnd = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 10 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.contains(testTimePeriodStartSameEnd))
//Test after
let testTimePeriodAfter = TimePeriod(beginning: self.formatter.date(from: "2016 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 12 10 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.contains(testTimePeriodAfter))
}
func testOverlaps() {
//POSITIVE MATCHES
//Test exact match
let testTimePeriodExact = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.overlaps(with: testTimePeriodExact))
//Test same start
let testTimePeriodSameStart = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.overlaps(with: testTimePeriodSameStart))
//Test same end
let testTimePeriodSameEnd = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.overlaps(with: testTimePeriodSameEnd))
//Test completely inside
let testTimePeriodCompletelyInside = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 04 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.overlaps(with: testTimePeriodCompletelyInside))
//Test start inside
let testTimePeriodStartInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 07 18:15:12.000")!, end: self.formatter.date(from: "2016 12 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.overlaps(with: testTimePeriodStartInside))
//Test end inside
let testTimePeriodEndInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 07 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.overlaps(with: testTimePeriodEndInside))
//NEGATIVE MATCHES
//Test before
let testTimePeriodBefore = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 04 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.overlaps(with: testTimePeriodBefore))
//Test end same as start
let testTimePeriodEndSameStart = TimePeriod(beginning: self.formatter.date(from: "2013 11 05 18:15:12.000")!, end: self.formatter.date(from: "2014 11 05 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.overlaps(with: testTimePeriodEndSameStart))
//Test start same as end
let testTimePeriodStartSameEnd = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 10 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.overlaps(with: testTimePeriodStartSameEnd))
//Test after
let testTimePeriodAfter = TimePeriod(beginning: self.formatter.date(from: "2016 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 12 10 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.overlaps(with: testTimePeriodAfter))
}
func testIntersects() {
//POSITIVE MATCHES
//Test exact match
let testTimePeriodExact = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodExact))
//Test same start
let testTimePeriodSameStart = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodSameStart))
//Test same end
let testTimePeriodSameEnd = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodSameEnd))
//Test completely inside
let testTimePeriodCompletelyInside = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 04 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodCompletelyInside))
//Test start inside
let testTimePeriodStartInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 07 18:15:12.000")!, end: self.formatter.date(from: "2016 12 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodStartInside))
//Test end inside
let testTimePeriodEndInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 07 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodEndInside))
//Test end same as start
let testTimePeriodEndSameStart = TimePeriod(beginning: self.formatter.date(from: "2013 11 05 18:15:12.000")!, end: self.formatter.date(from: "2014 11 05 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodEndSameStart))
//Test start same as end
let testTimePeriodStartSameEnd = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 10 18:15:12.000")!)
XCTAssertTrue(self.controlTimePeriod.intersects(with: testTimePeriodStartSameEnd))
//NEGATIVE MATCHES
//Test before
let testTimePeriodBefore = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 04 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.intersects(with: testTimePeriodBefore))
//Test after
let testTimePeriodAfter = TimePeriod(beginning: self.formatter.date(from: "2016 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 12 10 18:15:12.000")!)
XCTAssertFalse(self.controlTimePeriod.intersects(with: testTimePeriodAfter))
}
func testRelation() {
//Test exact match
let testTimePeriodExact = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertEqual(Relation.exactMatch, testTimePeriodExact.relation(to: self.controlTimePeriod))
//Test same start
let testTimePeriodSameStart = TimePeriod(beginning: self.formatter.date(from: "2014 11 05 18:15:12.000")!, end: self.formatter.date(from: "2015 11 05 18:15:12.000")!)
XCTAssertEqual(Relation.insideStartTouching, testTimePeriodSameStart.relation(to: self.controlTimePeriod))
//Test same end
let testTimePeriodSameEnd = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 05 18:15:12.000")!)
XCTAssertEqual(Relation.insideEndTouching, testTimePeriodSameEnd.relation(to: self.controlTimePeriod))
//Test completely inside
let testTimePeriodCompletelyInside = TimePeriod(beginning: self.formatter.date(from: "2015 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 04 05 18:15:12.000")!)
XCTAssertEqual(Relation.inside, testTimePeriodCompletelyInside.relation(to: self.controlTimePeriod))
//NEGATIVE MATCHES
//Test before
let testTimePeriodBefore = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 04 18:15:12.000")!)
XCTAssertEqual(Relation.before, testTimePeriodBefore.relation(to: self.controlTimePeriod))
//Test end same as start
let testTimePeriodEndSameStart = TimePeriod(beginning: self.formatter.date(from: "2013 11 05 18:15:12.000")!, end: self.formatter.date(from: "2014 11 05 18:15:12.000")!)
XCTAssertEqual(Relation.endTouching, testTimePeriodEndSameStart.relation(to: self.controlTimePeriod))
//Test end inside
let testTimePeriodEndInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 02 18:15:12.000")!, end: self.formatter.date(from: "2014 11 07 18:15:12.000")!)
XCTAssertEqual(Relation.endInside, testTimePeriodEndInside.relation(to: self.controlTimePeriod))
//Test start inside
let testTimePeriodStartInside = TimePeriod(beginning: self.formatter.date(from: "2014 11 07 18:15:12.000")!, end: self.formatter.date(from: "2016 12 05 18:15:12.000")!)
XCTAssertEqual(Relation.startInside, testTimePeriodStartInside.relation(to: self.controlTimePeriod))
//Test start same as end
let testTimePeriodStartSameEnd = TimePeriod(beginning: self.formatter.date(from: "2016 11 05 18:15:12.000")!, end: self.formatter.date(from: "2016 11 10 18:15:12.000")!)
XCTAssertEqual(Relation.startTouching, testTimePeriodStartSameEnd.relation(to: self.controlTimePeriod))
//Test after
let testTimePeriodAfter = TimePeriod(beginning: self.formatter.date(from: "2016 12 05 18:15:12.000")!, end: self.formatter.date(from: "2016 12 10 18:15:12.000")!)
XCTAssertEqual(Relation.after, testTimePeriodAfter.relation(to: self.controlTimePeriod))
}
func testHasGap() {
//We are going to treat some of these as False=noGap and True=gap
//No Gap Same
XCTAssertFalse(self.controlTimePeriod.hasGap(between: self.controlTimePeriod))
//No Gap End Inside
let testPeriodNoGap = TimePeriod(beginning: self.controlTimePeriod.beginning! - 1.days, end: self.controlTimePeriod.end!.subtract(1.days))
XCTAssertFalse(self.controlTimePeriod.hasGap(between: testPeriodNoGap))
//Gap receiver early
let testPeriodReceiverEarly = TimePeriod(beginning: self.controlTimePeriod.end!.add(1.years), chunk: 1.weeks)
XCTAssertTrue(self.controlTimePeriod.hasGap(between: testPeriodReceiverEarly))
//Gap parameter early
let testPeriodParameterEarly = TimePeriod(end: self.controlTimePeriod.beginning! - 1.years, chunk: 1.weeks)
XCTAssertTrue(self.controlTimePeriod.hasGap(between: testPeriodParameterEarly))
}
func testGap() {
//Gap of 1 minute
let testPeriodParameter1MinuteEarly = TimePeriod(end: self.controlTimePeriod.beginning! - 1.minutes, chunk: 1.seconds)
XCTAssertEqual(60, self.controlTimePeriod.gap(between: testPeriodParameter1MinuteEarly))
}
// MARK: - Date Relationships
func testContainsDate() {
let testDateBefore = self.formatter.date(from: "2014 10 05 18:15:12.000")!
let testDateBetween = self.formatter.date(from: "2015 11 05 18:15:12.000")!
let testDateAfter = self.formatter.date(from: "2016 12 05 18:15:12.000")!
// Test before
XCTAssertFalse(self.controlTimePeriod.contains(testDateBefore, interval: Interval.open))
XCTAssertFalse(self.controlTimePeriod.contains(testDateBefore, interval: Interval.closed))
// Test on start date
XCTAssertFalse(self.controlTimePeriod.contains(self.controlTimePeriod.beginning!, interval: Interval.open))
XCTAssertTrue(self.controlTimePeriod.contains(self.controlTimePeriod.beginning!, interval: Interval.closed))
// Test in middle
XCTAssertTrue(self.controlTimePeriod.contains(testDateBetween, interval: Interval.closed))
XCTAssertTrue(self.controlTimePeriod.contains(testDateBetween, interval: Interval.closed))
// Test on end date
XCTAssertFalse(self.controlTimePeriod.contains(self.controlTimePeriod.end!, interval: Interval.open))
XCTAssertTrue(self.controlTimePeriod.contains(self.controlTimePeriod.end!, interval: Interval.closed))
// Test after
XCTAssertFalse(self.controlTimePeriod.contains(testDateAfter, interval: Interval.open))
XCTAssertFalse(self.controlTimePeriod.contains(testDateAfter, interval: Interval.closed))
}
// MARK: - Period Manipulation
// MARK: Shift Earlier by Time Interval
func testShiftSecondEarlierInterval() {
let startEarlierSecond = self.formatter.date(from: "2014 11 05 18:15:11.000")!
let endEarlierSecond = self.formatter.date(from: "2016 11 05 18:15:11.000")!
//Second time period
let testPeriod = TimePeriod(beginning: startEarlierSecond, end: endEarlierSecond)
self.controlTimePeriod.shift(by: -1)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMinuteEarlierInterval() {
let startEarlier = self.formatter.date(from: "2014 11 05 18:14:12.000")!
let endEarlier = self.formatter.date(from: "2016 11 05 18:14:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -Constants.SecondsInMinute)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftHourEarlierInterval() {
let startEarlier = self.formatter.date(from: "2014 11 05 17:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 11 05 17:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -Constants.SecondsInHour)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftDayEarlierInterval() {
let startEarlier = self.formatter.date(from: "2014 11 04 18:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 11 04 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -Constants.SecondsInDay)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftWeekEarlierInterval() {
let startEarlier = self.formatter.date(from: "2014 10 29 18:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 10 29 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -Constants.SecondsInWeek)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMonthEarlierInterval() {
let startEarlier = self.formatter.date(from: "2014 10 05 18:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 10 05 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -Constants.SecondsInMonth31)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftYearEarlierInterval() {
let startEarlier = self.formatter.date(from: "2013 11 04 18:15:12.000")!
let endEarlier = self.formatter.date(from: "2015 11 05 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -Constants.SecondsInLeapYear) // note: a leap year is subtracted from both beginning and end
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
// MARK: Shift Earlier by Time Chunk
func testShiftSecondEarlierChunk() {
let startEarlierSecond = self.formatter.date(from: "2014 11 05 18:15:11.000")!
let endEarlierSecond = self.formatter.date(from: "2016 11 05 18:15:11.000")!
//Second time period
let testPeriod = TimePeriod(beginning: startEarlierSecond, end: endEarlierSecond)
self.controlTimePeriod.shift(by: -1.seconds)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMinuteEarlierChunk() {
let startEarlier = self.formatter.date(from: "2014 11 05 18:14:12.000")!
let endEarlier = self.formatter.date(from: "2016 11 05 18:14:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -1.minutes)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftHourEarlierChunk() {
let startEarlier = self.formatter.date(from: "2014 11 05 17:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 11 05 17:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -1.hours)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftDayEarlierChunk() {
let startEarlier = self.formatter.date(from: "2014 11 04 18:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 11 04 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -1.days)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftWeekEarlierChunk() {
let startEarlier = self.formatter.date(from: "2014 10 29 17:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 10 29 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -1.weeks)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMonthEarlierChunk() {
let startEarlier = self.formatter.date(from: "2014 10 05 17:15:12.000")!
let endEarlier = self.formatter.date(from: "2016 10 05 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -1.months)
XCTAssertTrue(testPeriod == controlTimePeriod)
}
func testShiftYearEarlierChunk() {
let startEarlier = self.formatter.date(from: "2013 11 05 18:15:12.000")!
let endEarlier = self.formatter.date(from: "2015 11 05 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startEarlier, end: endEarlier)
self.controlTimePeriod.shift(by: -1.years)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
// MARK: Shift Later by Interval
func testShiftSecondLaterInterval() {
let startLater = self.formatter.date(from: "2014 11 05 18:15:13.000")!
let endLater = self.formatter.date(from: "2016 11 05 18:15:13.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMinuteLaterInterval() {
let startLater = self.formatter.date(from: "2014 11 05 18:16:12.000")!
let endLater = self.formatter.date(from: "2016 11 05 18:16:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: Constants.SecondsInMinute)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftHourLaterInterval() {
let startLater = self.formatter.date(from: "2014 11 05 19:15:12.000")!
let endLater = self.formatter.date(from: "2016 11 05 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: Constants.SecondsInHour)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftDayLaterInterval() {
let startLater = self.formatter.date(from: "2014 11 06 18:15:12.000")!
let endLater = self.formatter.date(from: "2016 11 06 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: Constants.SecondsInDay) //Will not take into account daylight savings
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftWeekLaterInterval() {
let startLater = self.formatter.date(from: "2014 11 12 18:15:12.000")!
let endLater = self.formatter.date(from: "2016 11 12 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: Constants.SecondsInWeek) //Will not take into account daylight savings
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMonthLaterInterval() {
let startLater = self.formatter.date(from: "2014 12 05 18:15:12.000")!
let endLater = self.formatter.date(from: "2016 12 05 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: Constants.SecondsInMonth30) //Will not take into account daylight savings
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftYearLaterInterval() {
let startLater = self.formatter.date(from: "2015 11 05 18:15:12.000")!
let endLater = self.formatter.date(from: "2017 11 05 18:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: Constants.SecondsInYear) //Will not take into account daylight savings or leap year
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
// MARK: Shift Later by Chunk
func testShiftSecondLaterChunk() {
let startLater = self.formatter.date(from: "2014 11 05 18:15:13.000")!
let endLater = self.formatter.date(from: "2016 11 05 18:15:13.000")!
//Second time period
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.seconds)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMinuteLaterChunk() {
let startLater = self.formatter.date(from: "2014 11 05 18:16:12.000")!
let endLater = self.formatter.date(from: "2016 11 05 18:16:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.minutes)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftHourLaterChunk() {
let startLater = self.formatter.date(from: "2014 11 05 19:15:12.000")!
let endLater = self.formatter.date(from: "2016 11 05 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.hours)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftDayLaterChunk() {
let startLater = self.formatter.date(from: "2014 11 06 18:15:12.000")!
let endLater = self.formatter.date(from: "2016 11 06 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.days)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftWeekLaterChunk() {
let startLater = self.formatter.date(from: "2014 11 12 18:15:12.000")!
let endLater = self.formatter.date(from: "2016 11 12 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.weeks)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftMonthLaterChunk() {
let startLater = self.formatter.date(from: "2014 12 05 18:15:12.000")!
let endLater = self.formatter.date(from: "2016 12 05 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.months)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShiftYearLaterChunk() {
let startLater = self.formatter.date(from: "2015 11 05 18:15:12.000")!
let endLater = self.formatter.date(from: "2017 11 05 19:15:12.000")!
let testPeriod = TimePeriod(beginning: startLater, end: endLater)
self.controlTimePeriod.shift(by: 1.years)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
// MARK: Lengthen / Shorten by Interval
func testLengthenAnchorBeginningInterval() {
//Test dates
let lengthenedEnd = self.formatter.date(from: "2016 11 05 18:15:14.000")!
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: lengthenedEnd)
self.controlTimePeriod.lengthen(by: 2, at: Anchor.beginning)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testLengthenAnchorCenterInterval() {
//Test dates
let lengthenedStart = self.formatter.date(from: "2014 11 05 18:15:11.000")!
let lengthenedEnd = self.formatter.date(from: "2016 11 05 18:15:13.000")!
let testPeriod = TimePeriod(beginning: lengthenedStart, end: lengthenedEnd)
self.controlTimePeriod.lengthen(by: 2, at: Anchor.center)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testLengthenAnchorEndInterval() {
//Test dates
let lengthenedStart = self.formatter.date(from: "2014 11 05 18:15:10.000")!
let testPeriod = TimePeriod(beginning: lengthenedStart, end: self.controlTimePeriod.end!)
self.controlTimePeriod.lengthen(by: 2, at: Anchor.end)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShortenAnchorStartInterval() {
//Test dates
let shortenedEnd = self.formatter.date(from: "2016 11 05 18:15:10.000")!
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: shortenedEnd)
self.controlTimePeriod.shorten(by: 2, at: Anchor.beginning)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShortenAnchorCenterInterval() {
//Test dates
let shortenedStart = self.formatter.date(from: "2014 11 05 18:15:13.000")!
let shortenedEnd = self.formatter.date(from: "2016 11 05 18:15:11.000")!
let testPeriod = TimePeriod(beginning: shortenedStart, end: shortenedEnd)
self.controlTimePeriod.shorten(by: 2, at: Anchor.center)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShortenAnchorEndInterval() {
//Test dates
let shortenedStart = self.formatter.date(from: "2014 11 05 18:15:14.000")!
let testPeriod = TimePeriod(beginning: shortenedStart, end: self.controlTimePeriod.end!)
self.controlTimePeriod.shorten(by: 2, at: Anchor.end)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
// MARK: Lengthen / Shorten by Chunk
func testLengthenAnchorBeginningChunk() {
//Test dates
let lengthenedEnd = self.formatter.date(from: "2016 11 05 18:15:14.000")!
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: lengthenedEnd)
self.controlTimePeriod.lengthen(by: 2.seconds, at: Anchor.beginning)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testLengthenAnchorEndChunk() {
//Test dates
let lengthenedStart = self.formatter.date(from: "2014 11 05 18:15:10.000")!
let testPeriod = TimePeriod(beginning: lengthenedStart, end: self.controlTimePeriod.end!)
self.controlTimePeriod.lengthen(by: 2.seconds, at: Anchor.end)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShortenAnchorStartChunk() {
//Test dates
let shortenedEnd = self.formatter.date(from: "2016 11 05 18:15:10.000")!
let testPeriod = TimePeriod(beginning: self.controlTimePeriod.beginning!, end: shortenedEnd)
self.controlTimePeriod.shorten(by: 2.seconds, at: Anchor.beginning)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
func testShortenAnchorEndChunk() {
//Test dates
let shortenedStart = self.formatter.date(from: "2014 11 05 18:15:14.000")!
let testPeriod = TimePeriod(beginning: shortenedStart, end: self.controlTimePeriod.end!)
self.controlTimePeriod.shorten(by: 2.seconds, at: Anchor.end)
XCTAssertTrue(testPeriod == self.controlTimePeriod)
}
}
| 57.228951 | 181 | 0.695979 |
b98205d9b7db7346c477b56733dd2fc99a7df045 | 1,447 | //
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
@available(iOS 11, *)
open class CompoundMessageCollectionViewCell: BaseMessageCollectionViewCell<CompoundBubbleView> {
open override func createBubbleView() -> CompoundBubbleView! {
return CompoundBubbleView()
}
public final var viewReferences: [ViewReference]?
}
| 43.848485 | 97 | 0.760194 |
6476649925b6b719a802a9504f793452dbf44e7e | 1,913 | import Foundation
#if os(Linux)
import FoundationNetworking
#endif
public struct AppPreviewSet: Codable {
public struct Attributes: Codable {
public var previewType: String?
}
public struct Relationships: Codable {
public var appPreviews: AppPreviewSet.Relationships.AppPreviews?
public var appStoreVersionLocalization: AppPreviewSet.Relationships.AppStoreVersionLocalization?
}
public var attributes: AppScreenshot.Attributes?
public var id: String
public var relationships: AppScreenshot.Relationships?
public private(set) var type: String = "appPreviewSets"
public var links: ResourceLinks<AppScreenshotResponse>
}
public extension AppPreviewSet.Relationships {
struct AppPreviews: Codable {
public var data: AppPreviewSet.Relationships.AppPreviews.Data?
public var links: AppPreviewSet.Relationships.AppPreviews.Links?
public var meta: PagingInformation?
}
struct AppStoreVersionLocalization: Codable {
public var data: AppPreviewSet.Relationships.AppStoreVersionLocalization.Data?
public var links: AppPreviewSet.Relationships.AppStoreVersionLocalization.Links?
}
}
public extension AppPreviewSet.Relationships.AppPreviews {
struct Data: Codable {
public var id: String
public private(set) var type: String = "appPreviews"
}
struct Links: Codable {
/// uri-reference
public var related: URL?
/// uri-reference
public var `self`: URL?
}
}
public extension AppPreviewSet.Relationships.AppStoreVersionLocalization {
struct Data: Codable {
public var id: String
public private(set) var type: String = "appStoreVersionLocalizations"
}
struct Links: Codable {
/// uri-reference
public var related: URL?
/// uri-reference
public var `self`: URL?
}
}
| 25.506667 | 104 | 0.703084 |
096e6f0861a8cd9bc24c467c33f936fa4a34060b | 3,854 | //
// CollectionViewCell.swift
// MyProduct
//
// Created by 王雪慧 on 2020/1/17.
// Copyright © 2020 王雪慧. All rights reserved.
//
import UIKit
import SnapKit
class CollectionViewCell: UICollectionViewCell {
static let reuseIdentifier = "reuseIdentifier"
var imageView: UIImageView!
var imageViewOverlay: UIView!
var imageViewSelected: UIImageView!
var imageViewUnselected: UIImageView!
private var showSelectionIcons = false
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(frame: .zero)
if #available(iOS 13.0, *) {
imageView.image = UIImage(systemName: "photo")
} else {
imageView.image = UIImage(named: "photo")
}
imageView.backgroundColor = .clear
contentView.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
imageViewOverlay = UIImageView(frame: .zero)
imageViewOverlay.backgroundColor = UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 0.5)
contentView.addSubview(imageViewOverlay)
imageViewOverlay.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
imageViewUnselected = UIImageView(frame: .zero)
if #available(iOS 13.0, *) {
imageViewUnselected.image = UIImage(systemName: "circle")
} else {
imageViewUnselected.image = UIImage(named: "circle")
}
imageViewUnselected.layer.cornerRadius = 10
imageViewUnselected.backgroundColor = .white
contentView.addSubview(imageViewUnselected)
imageViewUnselected.snp.makeConstraints { (make) in
make.right.bottom.equalToSuperview().offset(-4)
make.width.equalTo(20)
make.height.equalTo(20)
}
imageViewSelected = UIImageView(frame: .zero)
if #available(iOS 13.0, *) {
imageViewSelected.image = UIImage(systemName: "checkmark.circle.fill")
} else {
imageViewSelected.image = UIImage(named: "checkmark.circle.fill")
}
imageViewSelected.layer.cornerRadius = 10
imageViewSelected.backgroundColor = .white
contentView.addSubview(imageViewSelected)
imageViewSelected.snp.makeConstraints { (make) in
make.edges.equalTo(imageViewUnselected)
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
// override func awakeFromNib() {
// super.awakeFromNib()
// // Turn `imageViewSelected` into a circle to make its background
// // color act as a border around the checkmark symbol.
// imageViewSelected.layer.cornerRadius = imageViewSelected.bounds.width / 2
// imageViewUnselected.layer.cornerRadius = imageViewSelected.bounds.width / 2
// }
func configureCell(with model: PhotoModel, showSelectionIcons: Bool) {
self.showSelectionIcons = showSelectionIcons
if let image = model.image {
imageView.image = image
}
showSelectionOverlay()
}
private func showSelectionOverlay() {
let alpha: CGFloat = (isSelected && showSelectionIcons) ? 1.0 : 0.0
imageViewOverlay.alpha = alpha
imageViewSelected.alpha = alpha
imageViewUnselected.alpha = showSelectionIcons ? 1.0 : 0.0
}
override func prepareForReuse() {
super.prepareForReuse()
isSelected = false
showSelectionIcons = false
showSelectionOverlay()
}
override var isSelected: Bool {
didSet {
showSelectionOverlay()
setNeedsLayout()
}
}
}
| 32.386555 | 113 | 0.623508 |
61bbdd5ab293ef932d15e73d3c578bb3ea169249 | 736 |
import Foundation
import Network
protocol NetworkMonitoring {
var onSatisfied: (()->())? {get set}
var onUnsatisfied: (()->())? {get set}
func startMonitoring()
}
class NetworkMonitor: NetworkMonitoring {
var onSatisfied: (() -> ())?
var onUnsatisfied: (() -> ())?
private let monitor = NWPathMonitor()
private let monitorQueue = DispatchQueue(label: "com.walletconnect.sdk.network.monitor")
func startMonitoring() {
monitor.pathUpdateHandler = { [weak self] path in
if path.status == .satisfied {
self?.onSatisfied?()
} else {
self?.onUnsatisfied?()
}
}
monitor.start(queue: monitorQueue)
}
}
| 24.533333 | 92 | 0.580163 |
e964b7e4a16dc063abeb81c2babbad7769f0745e | 271 | //
// Interactor.swift
// Particle
//
// Created by Artem Misesin on 5/30/18.
// Copyright © 2018 Artem Misesin. All rights reserved.
//
import UIKit
class Interactor: UIPercentDrivenInteractiveTransition {
var hasStarted = false
var shouldFinish = false
}
| 18.066667 | 56 | 0.712177 |
8753ef852b0a19644f228e8d38c792c26b9e0b15 | 659 | //
// User.swift
// IssueTracker
//
// Created by 김병인 on 2020/11/03.
//
import Foundation
import Alamofire
struct User {
var id = -1
var type = 1
var identifier = ""
var name = ""
var profileUrl = ""
}
extension User {
var model: UserVO {
return UserVO(id: id, type: type, identifier: identifier, name: name, profileUrl: profileUrl)
}
}
struct UserVO : Codable {
var id = -1
var type = 1
var identifier = ""
var name = ""
var profileUrl = ""
}
extension UserVO {
func decode() -> User {
return User(id: id, type: type, identifier: identifier, name: name, profileUrl: profileUrl)
}
}
| 19.382353 | 101 | 0.599393 |
22256256719c68a1be1155fbc521b4b2417b56ab | 9,953 | //
// QRScanViewController.swift
// lovek12
//
// Created by 汪诗雨 on 15/10/25.
// Copyright © 2015年 manyi. All rights reserved.
//
import UIKit
open class HLQRCodeScanner: UIViewController {
/// 扫描二维码,handle回调内返回扫描结果
/// 返回值为QRCodeScanner类型对象
open class func scanner(_ handle: @escaping (String) -> ()) -> HLQRCodeScanner {
let sc = HLQRCodeScanner()
weak var weakSC = sc
weakSC?.scanImageFinished = handle
weakSC?.scanner.prepareScan(sc.view) {
weakSC?.dissmissVC()
handle($0)
}
return sc
}
/// 创建二维码图片
/// 参数:字符串,内嵌图片,内嵌占比,二维码前景色,二维码后景色
/// 返回值为UIImage?
open class func createQRCodeImage(_ withStringValue: String, avatarImage: UIImage? = nil, avatarScale: CGFloat? = nil, color: CIColor = CIColor(color: UIColor.black), backColor: CIColor = CIColor(color: UIColor.white)) -> UIImage? {
return QRCode.generateImage(withStringValue, avatarImage: avatarImage, avatarScale: avatarScale ?? 0.25, color: color, backColor: backColor)
}
fileprivate var scanImageStringValue: String? {
didSet {
if let value = scanImageStringValue {
scanImageFinished!(value)
}
}
}
fileprivate var scanImageFinished: ((String) -> ())?
fileprivate let scanner = QRCode()
fileprivate var animating = true
/// MARK: - UI布局
fileprivate lazy var scanViewHeight: CGFloat = {
return self.view.frame.width * 0.75
}()
fileprivate lazy var backgroundView: UIView = {
self.view.layoutIfNeeded()
let aView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
aView.backgroundColor = UIColor.clear
let cropLayer = CAShapeLayer()
aView.layer.addSublayer(cropLayer)
let path = CGMutablePath()
let cropRect = CGRect(x: (aView.frame.width - self.scanViewHeight) * 0.5, y: (aView.frame.height - self.scanViewHeight) * 0.5, width: self.scanViewHeight, height: self.scanViewHeight)
path.addRect(aView.bounds)
path.addRect(cropRect)
cropLayer.fillRule = kCAFillRuleEvenOdd
cropLayer.path = path
cropLayer.fillColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor
return aView
}()
fileprivate lazy var photoButton: UIButton = {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: "HLQRCodeScanner", withExtension: "bundle")
let imageBundle = Bundle(url: url!)
let button = UIButton(type: .custom)
button.setImage(self.imageWithName("ScanPhoto", bundle: imageBundle!), for: UIControlState())
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.addTarget(self, action: #selector(self.clickAlbumButton), for: .touchUpInside)
self.view.addSubview(button)
return button
}()
fileprivate lazy var torchButton: UIButton = {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: "HLQRCodeScanner", withExtension: "bundle")
let imageBundle = Bundle(url: url!)
let button = UIButton(type: .custom)
button.setImage(self.imageWithName("ScanTorch", bundle: imageBundle!), for: UIControlState())
button.setImage(self.imageWithName("ScanTorch_selected", bundle: imageBundle!), for: .selected)
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.addTarget(self, action: #selector(self.torchClick), for: .touchUpInside)
self.view.addSubview(button)
return button
}()
fileprivate lazy var descLabel: UILabel = {
let descLabel = UILabel(frame: CGRect.zero)
descLabel.text = "将二维码放入框内,即可自动扫描"
descLabel.font = UIFont.systemFont(ofSize: 12)
descLabel.textColor = UIColor.white
descLabel.sizeToFit()
descLabel.center = self.view.center
return descLabel
}()
fileprivate lazy var scanView: UIView = {
let aView = UIView(frame: CGRect(x: 0, y: 0, width: self.scanViewHeight, height: self.scanViewHeight))
aView.center = self.view.center
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: "HLQRCodeScanner", withExtension: "bundle")
let imageBundle = Bundle(url: url!)
let imageView1 = UIImageView(image: self.imageWithName("ScanQR1", bundle: imageBundle!))
let imageView2 = UIImageView(image: self.imageWithName("ScanQR2", bundle: imageBundle!))
let imageView3 = UIImageView(image: self.imageWithName("ScanQR3", bundle: imageBundle!))
let imageView4 = UIImageView(image: self.imageWithName("ScanQR4", bundle: imageBundle!))
imageView1.frame = CGRect(x: 0, y: 0, width: 16, height: 16)
imageView2.frame = CGRect(x: aView.frame.width - 16, y: 0, width: 16, height: 16)
imageView3.frame = CGRect(x: 0, y: aView.frame.height - 16, width: 16, height: 16)
imageView4.frame = CGRect(x: aView.frame.width - 16, y: aView.frame.height - 16, width: 16, height: 16)
aView.addSubview(imageView1)
aView.addSubview(imageView2)
aView.addSubview(imageView3)
aView.addSubview(imageView4)
aView.addSubview(self.lineImage)
aView.backgroundColor = UIColor.clear
self.descLabel.frame.origin.y = aView.frame.maxY + 8
//self.torchButton.center = CGPoint(x: self.view.frame.width / 3, y: aView.frame.origin.y - 32)
//self.photoButton.center = CGPoint(x: self.view.frame.width / 3 * 2, y: aView.frame.origin.y - 32)
self.view.addSubview(self.descLabel)
return aView
}()
fileprivate lazy var lineImage: UIImageView = {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.scanViewHeight, height: 15))
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: "HLQRCodeScanner", withExtension: "bundle")
let imageBundle = Bundle(url: url!)
imageView.image = self.imageWithName("QRCodeScanLine", bundle: imageBundle!)
return imageView
}()
/// MARK: - 点击事件
fileprivate func dissmissVC() {
if (self.navigationController?.responds(to: #selector(self.navigationController?.popViewController(animated:))) != nil) {
let _ = self.navigationController?.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
@objc fileprivate func torchClick() {
let _ = scanner.openTorch()
torchButton.isSelected = !torchButton.isSelected
}
@objc fileprivate func clickAlbumButton() {
if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
descLabel.text = "无法访问相册"
return
}
let picker = UIImagePickerController()
picker.view.backgroundColor = UIColor.white
picker.delegate = self
showDetailViewController(picker, sender:nil)
}
/// 初始化方法
fileprivate func setupSubviews() {
view.backgroundColor = UIColor.white
view.addSubview(backgroundView)
view.addSubview(scanView)
}
fileprivate func setupScaner() {
scanner.scanFrame = scanView.frame
scanner.autoRemoveSubLayers = true
}
@objc fileprivate func lineMoveAnimate() {
if animating {
UIView.animate(withDuration: 2.5, animations: {
self.lineImage.frame.origin.y = self.scanView.frame.height - 16
}, completion: { (finished) -> Void in
self.lineImage.frame.origin.y = 0
self.lineMoveAnimate()
})
}
}
/// MARK: - 生命周期方法
override open func viewDidLoad() {
super.viewDidLoad()
title = "二维码"
setupSubviews()
setupScaner()
lineMoveAnimate()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
scanner.startScan()
animating = true
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
scanner.stopScan()
animating = false
}
fileprivate func imageWithName(_ named: String, bundle: Bundle) -> UIImage? {
let filename = "\(named)@2x"
let path = bundle.path(forResource: filename, ofType: "png")
return UIImage(contentsOfFile: path!)?.withRenderingMode(.alwaysOriginal)
}
deinit {
debugPrint("deinit")
}
}
extension HLQRCodeScanner: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
weak var weakSC = self
weakSC?.scanner.scanImage(image) {
if ($0.count > 0) {
weakSC?.scanImageStringValue = $0.first
picker.dismiss(animated: false) {
if ((weakSC?.navigationController?.responds(to: #selector(weakSC?.navigationController?.popViewController(animated:)))) != nil) {
let _ = weakSC?.navigationController?.popViewController(animated: true)
} else {
weakSC?.dismiss(animated: true, completion: nil)
}
}
} else {
weakSC?.descLabel.text = "没有识别到二维码,请选择其他照片"
weakSC?.descLabel.sizeToFit()
picker.dismiss(animated: true, completion: nil)
}
}
}
}
}
| 39.339921 | 236 | 0.616498 |
fc4a87adc0ed24f70f4acb512b88a4fb5265e946 | 1,966 | import Foundation
import kubewardenSdk
import SwiftPath
import Foundation
import GenericJSON
func mutateOrReject(payload: String, fallbackRuntime: String?, rejectionMessage: String) -> String {
if let newRuntime = fallbackRuntime,
let mutatedObject = patchRuntime(payload: payload, newRuntime: newRuntime)
{
return mutateRequest(mutatedObject: mutatedObject)
}
return rejectRequest(message: rejectionMessage, code: nil)
}
func patchRuntime(payload: String, newRuntime: String) -> JSON? {
let objPath = SwiftPath("$.request.object")!
if let match = try! objPath.evaluate(with: payload),
var obj = match as? [String: Any] {
var spec = obj["spec"] as! [String: Any]
spec["runtimeClassName"] = newRuntime
obj["spec"] = spec
return try? JSON.init(obj)
}
return nil
}
public func validate(payload: String) -> String {
let vr : ValidationRequest<Settings> = try! JSONDecoder().decode(
ValidationRequest<Settings>.self, from: Data(payload.utf8))
let jsonPath = SwiftPath("$.request.object.spec.runtimeClassName")!
if let match = try? jsonPath.evaluate(with: payload),
let runtimeClassName = match as? String
{
if vr.settings.reservedRuntimes.contains(runtimeClassName) {
return mutateOrReject(
payload: payload,
fallbackRuntime: vr.settings.fallbackRuntime,
rejectionMessage: "runtime '\(runtimeClassName)' is reserved")
}
return acceptRequest()
}
// we're here because no runtimeClassName is specified
if vr.settings.defaultRuntimeReserved {
return mutateOrReject(
payload: payload,
fallbackRuntime: vr.settings.fallbackRuntime,
rejectionMessage: "Usage of the default runtime is reserved")
}
if let fallbackRuntime = vr.settings.fallbackRuntime,
let mutatedObject = patchRuntime(payload: payload, newRuntime: fallbackRuntime) {
return mutateRequest(mutatedObject: mutatedObject)
}
return acceptRequest()
}
| 30.246154 | 100 | 0.721261 |
4b16a7579946f9401546384c6d0f0beb3fd9334e | 1,830 | //
// ProgramChangedSpec.swift
// AnalyticsTests
//
// Created by Fredrik Sjöberg on 2017-12-13.
// Copyright © 2017 emp. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import ExposurePlayback
class ProgramChangedSpec: QuickSpec {
override func spec() {
describe("ProgramChanged") {
let timeStamp: Int64 = 10
let offset: Int64 = 10
let type = "Playback.ProgramChanged"
let programId = "programAsset"
let videoLength: Int64 = 10
it("Should init and record complete structure") {
let event = Playback.ProgramChanged(timestamp: timeStamp, offsetTime: offset, programId: programId, videoLength: videoLength)
expect(event.timestamp).to(equal(timeStamp))
expect(event.eventType).to(equal(type))
expect(event.offsetTime).to(equal(offset))
expect(event.programId).to(equal(programId))
expect(event.videoLength).to(equal(videoLength))
expect(event.bufferLimit).to(equal(3000))
}
it("Should produce correct jsonPayload") {
let json = Playback.ProgramChanged(timestamp: timeStamp, offsetTime: offset, programId: programId, videoLength: videoLength).jsonPayload
expect(json["EventType"] as? String).to(equal(type))
expect(json["Timestamp"] as? Int64).to(equal(timeStamp))
expect(json["OffsetTime"] as? Int64).to(equal(offset))
expect(json["ProgramId"] as? String).to(equal(programId))
expect(json["VideoLength"] as? Int64).to(equal(videoLength))
expect(json.count).to(equal(11))
}
}
}
}
| 38.125 | 152 | 0.591803 |
09a8fd1c8b85c9877d149e630a4960bbd15edb73 | 2,173 | //
// AppDelegate.swift
// PFMediator-master
//
// Created by guo-pf on 2018/7/12.
// Copyright © 2018年 guo-pf. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.234043 | 285 | 0.754717 |
48edbafdfe27293d0b8b71a51b8b556ecab25452 | 593 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "physix2",
products: [
.executable(name: "physix2", targets: ["physix2"])
],
dependencies: [
.package(name: "JavaScriptKit", url: "https://github.com/swiftwasm/JavaScriptKit", from: "0.9.0")
],
targets: [
.target(
name: "physix2",
dependencies: [
.product(name: "JavaScriptKit", package: "JavaScriptKit")
]),
.testTarget(
name: "physix2Tests",
dependencies: ["physix2"]),
]
) | 28.238095 | 105 | 0.541315 |
bfbb2e516e82b57e3305f371269c0f4e3edde65c | 1,259 | //
// ProductGateway.swift
// CleanArchitecture
//
// Created by Tuan Truong on 7/14/20.
// Copyright © 2020 Tuan Truong. All rights reserved.
//
import Combine
import Foundation
protocol ProductGatewayType {
func getProducts() -> Observable<[Product]>
}
struct ProductGateway: ProductGatewayType {
func getProducts() -> Observable<[Product]> {
Future<[Product], Error> { promise in
let products = [
Product(id: 0, name: "iPhone", price: 999),
Product(id: 1, name: "MacBook", price: 2999)
]
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
// promise(.failure(AppError.error(message: "Get product list failed!")))
promise(.success(products))
}
}
.eraseToAnyPublisher()
}
}
struct PreviewProductGateway: ProductGatewayType {
func getProducts() -> Observable<[Product]> {
Future<[Product], Error> { promise in
let products = [
Product(id: 0, name: "iPhone", price: 999),
Product(id: 1, name: "MacBook", price: 2999)
]
promise(.success(products))
}
.eraseToAnyPublisher()
}
}
| 27.369565 | 88 | 0.55838 |
791e0911baf103a550ed7155e2d3cf6c6994ac64 | 4,857 | //
// Hero.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 7/16/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import SpriteKit
// MARK: - Hero: SKSpriteNode
class Hero: SKSpriteNode {
// MARK: Properties
var inventory = [UDItem]()
var badgeManager: BadgeManager? = nil
// MARK: Initializers
init(name: String, position: CGPoint, items: [UDItem]) {
super.init(texture: UDAnimation.baseFrameForSprite[.Hero], color: UIColor.clear, size: CGSize(width: 225, height: 175))
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 225, height: 175))
if let heroPhysicsBody = self.physicsBody {
UDCollision.setCollisionForPhysicsBody(heroPhysicsBody, belongsToMask: .player, contactWithMask: .world, dynamic: true)
}
self.name = name
self.position = position
self.inventory = items
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Handling Requests Not Seen By Students
func checkItemComparison(_ item1: UDItem, item2: UDItem) -> Bool {
return item1 < item2
}
// Adding Badges
func addBadge(_ badge: Badge) {
if let badgeManager = badgeManager {
badgeManager.addBadge(badge)
}
}
}
extension Hero: UDRequestDelegate {
// Alien Adventure 1
func handleReverseLongestName(_ inventory: [UDItem]) -> String {
return reverseLongestName(inventory: inventory)
}
func handleMatchMoonRocks(_ inventory: [UDItem]) -> [UDItem] {
return matchMoonRocks(inventory: inventory)
}
func handleInscriptionEternalStar(_ inventory: [UDItem]) -> UDItem? {
return inscriptionEternalStar(inventory: inventory)
}
func handleLeastValuableItem(_ inventory: [UDItem]) -> UDItem? {
return leastValuableItem(inventory: inventory)
}
func handleShuffleStrings(_ s1: String, s2: String, shuffle: String) -> Bool {
return shuffleStrings(s1: s1, s2: s2, shuffle: shuffle)
}
// Alien Adventure 2
func handleItemsFromPlanet(_ inventory: [UDItem], planet: String) -> [UDItem] {
return itemsFromPlanet(inventory: inventory, planet: planet)
}
func handleOldestItemFromPlanet(_ inventory: [UDItem], planet: String) -> UDItem? {
return oldestItemFromPlanet(inventory: inventory, planet: planet)
}
func handleXORCipherKeySearch(_ encryptedString: [UInt8]) -> UInt8 {
return xorCipherKeySearch(encryptedString: encryptedString)
}
func handleRarityOfItems(_ inventory: [UDItem]) -> [UDItemRarity:Int] {
return rarityOfItems(inventory: inventory)
}
func handleItemComparison(_ item1: UDItem, item2: UDItem) -> Bool {
return checkItemComparison(item1, item2: item2)
}
func handleBannedItems(_ dataFile: String) -> [Int] {
return bannedItems(dataFile: dataFile)
}
func handlePlanetData(_ dataFile: String) -> String {
return planetData(dataFile: dataFile)
}
func handleMostCommonCharacter(_ inventory: [UDItem]) -> Character? {
return mostCommonCharacter(inventory: inventory)
}
// Alien Adventure 3
func handleBasicCheck() -> Bool {
return true
}
func handleAdvancedCheck() -> Bool {
return true
}
func handleExpertCheck() -> Bool {
return true
}
func handleCheckBadges(_ badges: [Badge], requestTypes: [UDRequestType]) -> Bool {
return checkBadges(badges: badges, requestTypes: requestTypes)
}
// Alien Adventure 4
func handlePolicingItems(_ inventory: [UDItem], policingFilter: (UDItem) throws -> Void) -> [UDPolicingError:Int] {
return policingItems(inventory: inventory, policingFilter: policingFilter)
}
func handleFindTheLasers() -> ((UDItem) -> Bool) {
return findTheLasers()
}
func handleRedefinePolicingItems() -> ((UDItem) throws -> Void) {
return redefinePolicingItems()
}
func handleBoostItemValue(_ inventory: [UDItem]) -> [UDItem] {
return boostItemValue(inventory: inventory)
}
func handleSortLeastToGreatest(_ inventory: [UDItem]) -> [UDItem] {
return sortLeastToGreatest(inventory: inventory)
}
func handleGetCommonItems(_ inventory: [UDItem]) -> [UDItem] {
return getCommonItems(inventory: inventory)
}
func handleTotalBaseValue(_ inventory: [UDItem]) -> Int {
return totalBaseValue(inventory: inventory)
}
func handleRemoveDuplicates(_ inventory: [UDItem]) -> [UDItem] {
return removeDuplicates(inventory: inventory)
}
}
| 29.615854 | 131 | 0.640725 |
72338ac1f3bba751e37863d9997ef851328dbd34 | 2,167 | //
// AppDelegate.swift
// Example
//
// Created by Egzon Arifi on 8/14/18.
// Copyright © 2018 Overjump. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.106383 | 285 | 0.754961 |
f9975663dffafa304c3f813fa566a4f11936399d | 1,113 | //
// PostCell.swift
// DogWalker_iosapp
//
// Created by 김경현 on 2021/01/14.
//
import UIKit
class PostCell: UITableViewCell
{
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var showContentTextView: UITextView!
var post: Post!{
didSet {
updateUI()
}
}
func imageCircle(){
profileImageView.layer.cornerRadius = profileImageView.frame.height / 2
profileImageView.layer.borderWidth = 1
profileImageView.clipsToBounds = true
profileImageView.layer.borderColor = UIColor.clear.cgColor //원형 이미지의 테두리 제거
}
func updateUI(){
imageCircle()
profileImageView.image = post.profileImage
usernameLabel.text = post.username
postImageView.image = post.image
showContentTextView.text = post.content
postImageView.clipsToBounds = true
postImageView.layer.borderWidth = 5
postImageView.layer.borderColor = UIColor.white.cgColor
}
}
| 27.146341 | 84 | 0.662174 |
016320298213fb72d06c8061b3a9a9b0506e5d2b | 650 | //
// ViewController.swift
// ForInCount
//
// Created by Tatsuya Tobioka on 2017/11/29.
// Copyright © 2017 tnantoka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
/// [marker1]
var num = 1
for _ in 0..<8 {
num *= 2
}
print(num)
/// [marker1]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.69697 | 80 | 0.590769 |
ef2f52ee3d90e665524f02161280ce8ffaff5ea4 | 253 | //
// PartnersViewModel.swift
// loafwallet
//
// Created by Kerry Washington on 11/29/20.
// Copyright © 2021 Sumcoin Wallet. All rights reserved.
//
import Foundation
class PartnerViewModel: ObservableObject {
init() {
}
}
| 14.882353 | 57 | 0.648221 |
0196d27d6681053b2fc7929771a891b3fae14729 | 229 | //
// ViewState.swift
// MQTTTest
//
// Created by Laura Corssac on 10/6/20.
// Copyright © 2020 Laura Corssac. All rights reserved.
//
import Foundation
enum TokenViewState {
case success, empty, error, loading
}
| 15.266667 | 56 | 0.672489 |
8932bf7cb518c22a58935df42d7ce285e4550208 | 2,338 | //
// TabmanViewController+AutoInsetting.swift
// Tabman
//
// Created by Merrick Sapsford on 22/11/2017.
// Copyright © 2017 UI At Six. All rights reserved.
//
import UIKit
internal extension TabmanViewController {
/// Notify the view controller that the current child view controller requires an inset update.
func setNeedsChildAutoInsetUpdate() {
setNeedsChildAutoInsetUpdate(for: currentViewController)
}
/// Notify the view controller that a child view controller requires an inset update.
func setNeedsChildAutoInsetUpdate(for childViewController: UIViewController?) {
calculateRequiredBarInsets()
guard let childViewController = childViewController else {
return
}
autoInsetEngine.inset(childViewController, requiredInsets: bar.requiredInsets)
}
}
// MARK: - Bar inset calculation
private extension TabmanViewController {
/// Reload the required bar insets for the current bar.
func calculateRequiredBarInsets() {
var layoutInsets: UIEdgeInsets = .zero
if #available(iOS 11, *) {
layoutInsets = view.safeAreaInsets
} else {
layoutInsets.top = topLayoutGuide.length
layoutInsets.bottom = bottomLayoutGuide.length
}
self.bar.requiredInsets = TabmanBar.Insets(safeAreaInsets: layoutInsets,
bar: self.actualBarInsets())
}
/// Calculate the actual required insets for the current bar.
///
/// - Returns: The required bar insets
private func actualBarInsets() -> UIEdgeInsets {
guard self.embeddingView == nil && self.attachedTabmanBar == nil else {
return .zero
}
guard self.activeTabmanBar?.isHidden != true else {
return .zero
}
let frame = self.activeTabmanBar?.frame ?? .zero
var insets = UIEdgeInsets.zero
var location = self.bar.location
if location == .preferred {
location = self.bar.style.preferredLocation
}
switch location {
case .bottom:
insets.bottom = frame.size.height
default:
insets.top = frame.size.height
}
return insets
}
}
| 31.173333 | 99 | 0.61976 |
d913f25bede0970e419a92bdefddb621e6717b10 | 675 | /* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* 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
* FACEBOOK 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
import CKSwift
import ComponentKit
import RenderCore
| 42.1875 | 78 | 0.792593 |
4ae706968b8e143c05e001865d7fc1fdf9ebf090 | 356 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s
public struct S {
func f() {
// CHECK: define {{.*}}_TFV4main1S1ffT_T_
// CHECK: call void @llvm.dbg.value(metadata i{{.*}} 0,
// CHECK-SAME: metadata ![[SELF:[0-9]+]]
// CHECK: ![[SELF]] = !DILocalVariable(name: "self", arg: 1,
}
}
| 32.363636 | 80 | 0.542135 |
2fa30d754c20c42cabb3e424b717ca69ba3142eb | 4,838 | import Foundation
import HSHDWalletKit
import RxSwift
import RealmSwift
class InitialSyncer {
private let disposeBag = DisposeBag()
private let realmFactory: RealmFactory
private let hdWallet: HDWallet
private let stateManager: StateManager
private let apiManager: ApiManager
private let addressManager: AddressManager
private let addressConverter: AddressConverter
private let factory: Factory
private let peerGroup: PeerGroup
private let network: NetworkProtocol
private let scheduler: ImmediateSchedulerType
init(realmFactory: RealmFactory, hdWallet: HDWallet, stateManager: StateManager, apiManager: ApiManager, addressManager: AddressManager, addressConverter: AddressConverter, factory: Factory, peerGroup: PeerGroup, network: NetworkProtocol, scheduler: ImmediateSchedulerType = ConcurrentDispatchQueueScheduler(qos: .background)) {
self.realmFactory = realmFactory
self.hdWallet = hdWallet
self.stateManager = stateManager
self.apiManager = apiManager
self.addressManager = addressManager
self.addressConverter = addressConverter
self.factory = factory
self.peerGroup = peerGroup
self.network = network
self.scheduler = scheduler
}
func sync() throws {
if !stateManager.apiSynced {
let maxHeight = network.checkpointBlock.height
let externalObservable = try fetchFromApi(external: true, maxHeight: maxHeight)
let internalObservable = try fetchFromApi(external: false, maxHeight: maxHeight)
Observable
.zip(externalObservable, internalObservable, resultSelector: { external, `internal` -> ([PublicKey], [BlockResponse]) in
let (externalKeys, externalResponses) = external
let (internalKeys, internalResponses) = `internal`
let set: Set<BlockResponse> = Set(externalResponses + internalResponses)
return (externalKeys + internalKeys, Array(set))
})
.subscribeOn(scheduler)
.subscribe(onNext: { [weak self] keys, responses in
try? self?.handle(keys: keys, responses: responses)
}, onError: { error in
Logger.shared.log(self, "Error: \(error)")
})
.disposed(by: disposeBag)
} else {
peerGroup.start()
}
// var keys = [PublicKey]()
// for i in 0...20 {
// keys.append(try hdWallet.publicKey(index: i, external: true))
// keys.append(try hdWallet.publicKey(index: i, external: false))
// }
// try handle(keys: keys, responses: [])
}
private func handle(keys: [PublicKey], responses: [BlockResponse]) throws {
let blocks = responses.compactMap { response -> Block? in
if let hash = Data(hex: response.hash) {
return self.factory.block(withHeaderHash: Data(hash.reversed()), height: response.height)
}
return nil
}
Logger.shared.log(self, "SAVING: \(keys.count) keys, \(blocks.count) blocks")
let realm = realmFactory.realm
try realm.write {
realm.add(blocks, update: true)
}
try addressManager.addKeys(keys: keys)
stateManager.apiSynced = true
peerGroup.start()
}
private func fetchFromApi(external: Bool, maxHeight: Int, lastUsedKeyIndex: Int = -1, keys: [PublicKey] = [], responses: [BlockResponse] = []) throws -> Observable<([PublicKey], [BlockResponse])> {
let count = keys.count
let gapLimit = hdWallet.gapLimit
let newKey = try hdWallet.publicKey(index: count, external: external)
return apiManager.getBlockHashes(address: addressConverter.convertToLegacy(keyHash: newKey.keyHash, version: network.pubKeyHash, addressType: .pubKeyHash).stringValue)
.flatMap { [unowned self] blockResponses -> Observable<([PublicKey], [BlockResponse])> in
var lastUsedKeyIndex = lastUsedKeyIndex
if !blockResponses.isEmpty {
lastUsedKeyIndex = keys.count
}
let keys = keys + [newKey]
if lastUsedKeyIndex < keys.count - gapLimit {
return Observable.just((keys, responses))
} else {
let validResponses = blockResponses.filter { $0.height < maxHeight }
return try self.fetchFromApi(external: external, maxHeight: maxHeight, lastUsedKeyIndex: lastUsedKeyIndex, keys: keys, responses: responses + validResponses)
}
}
}
}
| 42.069565 | 332 | 0.617197 |
e453fac11b0ec9e3f874f39fe997b391032b4c4a | 7,577 | import os
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
private var vlcLaunched = false
private enum Constants {
static let magnetStreamProtocol = "magnet"
static let magnetStreamUrlBeginning = Constants.magnetStreamProtocol + ":?xt=urn:btih:"
static let aceStreamProtocol = "acestream"
static let aceStreamUrlBeginning = Constants.aceStreamProtocol + "://"
static let vlcBundleId = "org.videolan.vlc"
static let startDockerExitCodes = [
100: "Cannot launch Docker",
101: "Cannot connect to Docker",
102: "Cannot connect to Acestream server",
103: "Cannot open stream",
104: "Cannot launch VLC"
]
}
enum StreamType {
case acestream
case magnet
case none
}
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
private func hashFromString(_ string: String) -> String {
return string.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(
of: Constants.aceStreamUrlBeginning,
with: ""
)
}
private func hashFromMagnetString(_ string: String) -> String {
let magnetHash = string.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(
of: Constants.magnetStreamUrlBeginning,
with: ""
)
let delimiter = "&"
let token = magnetHash.components(separatedBy: delimiter)
if token.isEmpty {
return ""
} else {
return token[0]
}
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
os_log("Application finished loading")
if let button = statusItem.button {
button.image = NSImage(named: "StatusBarIcon")
}
statusItem.menu = StatusMenu(title: "")
// One unnamed argument, must be the stream hash
if CommandLine.arguments.count % 1 == 1 {
os_log("Open stream from arg", CommandLine.arguments.last!)
openStream(CommandLine.arguments.last!, type: StreamType.acestream)
}
setupTerminationNotificationHandler()
}
func openStream(_ hash: String, type: StreamType) {
os_log("Open stream")
// TODO: statusItem.popUpMenu(statusItem.menu!)
// TODO: rewrite StartDocker.sh in Swift and show progress in a status item
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let scriptName = "StartDocker.sh"
let startDockerPath = Bundle.main.path(forResource: "StartDocker", ofType: "sh")!
let process = Process()
let pipe = Pipe()
let outHandle = pipe.fileHandleForReading
outHandle.readabilityHandler = { pipe in
if let line = String(data: pipe.availableData, encoding: .utf8) {
if line != "" && line != "." {
os_log("%{public}@ %{public}@", scriptName, line)
}
}
}
process.environment = ProcessInfo.processInfo.environment
process.environment!["image"] = "blaiseio/acelink:" + version
process.environment!["hash"] = hash
if type == StreamType.magnet {
process.environment!["stream_id_param"] = "infohash"
} else {
process.environment!["stream_id_param"] = "id"
}
process.launchPath = startDockerPath
process.standardOutput = pipe
process.launch()
process.waitUntilExit()
let exitCode = Int(process.terminationStatus)
let message = Constants.startDockerExitCodes[exitCode] ?? "unknown error"
if exitCode == 0 {
os_log("%{public}@ ran successfully", scriptName)
vlcLaunched = true
return
} else {
let formattedError = "\(message) (code \(exitCode))"
error(formattedError)
os_log("%{public}@ error: %{public}@", type: .error, scriptName, formattedError)
}
}
func error(_ text: String) {
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = "Ace Link error"
alert.icon = NSImage(named: NSImage.cautionName)
alert.informativeText = text
alert.addButton(withTitle: "OK")
alert.runModal()
}
func stopStream() {
os_log("Stop stream")
let path = Bundle.main.path(forResource: "StopDocker", ofType: "sh")!
let task = Process.launchedProcess(launchPath: path, arguments: [])
task.waitUntilExit()
if task.terminationStatus == 0 {
vlcLaunched = false
os_log("Stop stream done")
}
}
func getClipboardStringLinkType() -> StreamType {
let clipboardData = NSPasteboard.general.string(forType: NSPasteboard.PasteboardType.string)
if clipboardData == nil {
return StreamType.none
}
if clipboardData?.range(of: Constants.magnetStreamProtocol) != nil {
return StreamType.magnet
} else {
return StreamType.acestream
}
}
func getClipboardString() -> String {
let clipboardData = NSPasteboard.general.string(forType: NSPasteboard.PasteboardType.string)
if clipboardData == nil {
return ""
}
let clipboardString: String
if clipboardData?.range(of: Constants.magnetStreamProtocol) != nil {
clipboardString = hashFromMagnetString(clipboardData!)
} else {
clipboardString = hashFromString(clipboardData!)
}
// Verify conform SHA1
let range = NSRange(location: 0, length: clipboardString.count)
let regex = try! NSRegularExpression(
pattern: "^[a-fA-F0-9]{40}$",
options: NSRegularExpression.Options.caseInsensitive
)
if regex.firstMatch(in: clipboardString, options: [], range: range) != nil {
return clipboardString
}
return ""
}
func setupTerminationNotificationHandler() {
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didTerminateApplicationNotification,
object: nil,
queue: OperationQueue.main,
using: handleTerminationNotifications
)
}
func handleTerminationNotifications(_ notification: Notification) {
guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication else {
return
}
if app.bundleIdentifier == Constants.vlcBundleId && self.vlcLaunched {
os_log("VLC closed by user")
self.stopStream()
}
}
func applicationWillTerminate(_ aNotification: Notification) {
stopStream()
}
func application(_ application: NSApplication, open urls: [URL]) {
guard let url = urls.first else {
return
}
guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) else {
return
}
if urlComponents.scheme == Constants.aceStreamProtocol {
if url.absoluteString.range(of: Constants.magnetStreamProtocol) != nil {
openStream(hashFromMagnetString(url.absoluteString), type: StreamType.magnet)
} else {
openStream(hashFromString(url.absoluteString), type: StreamType.acestream)
}
}
}
}
| 33.977578 | 114 | 0.611588 |
fb5664ba601bdf6de4475d19e9016fd5e9494c91 | 834 | //
// CalanqueCellAlternative.swift
// Calanques
//
// Created by Karim Yarboua on 07/03/2019.
// Copyright © 2019 Karim Yarboua. All rights reserved.
//
import UIKit
class CalanqueCellAlternative: UITableViewCell {
@IBOutlet weak var calanqueImage: UIImageView!
@IBOutlet weak var calanqueLabel: UILabel!
var calanque: Calanque? {
didSet {
if calanque != nil {
calanqueImage.image = calanque!.image
calanqueLabel.text = calanque!.name
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.540541 | 65 | 0.621103 |
ffd7e76b2db032adb259571b9a254649b5a8e16e | 802 | // Generated using Sourcery 0.16.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// swiftlint:disable file_length
fileprivate func compareOptionals<T>(lhs: T?, rhs: T?, compare: (_ lhs: T, _ rhs: T) -> Bool) -> Bool {
switch (lhs, rhs) {
case let (lValue?, rValue?):
return compare(lValue, rValue)
case (nil, nil):
return true
default:
return false
}
}
fileprivate func compareArrays<T>(lhs: [T], rhs: [T], compare: (_ lhs: T, _ rhs: T) -> Bool) -> Bool {
guard lhs.count == rhs.count else { return false }
for (idx, lhsItem) in lhs.enumerated() {
guard compare(lhsItem, rhs[idx]) else { return false }
}
return true
}
// MARK: - AutoEquatable for classes, protocols, structs
// MARK: - AutoEquatable for Enums
| 27.655172 | 103 | 0.628429 |
18a33cd0d03dbe6b73f131999045b89c124ba6a0 | 3,154 | //
// FakeTwitterSegue.swift
// Pind My Way iOS
//
// Created by Atto Allas on 22/11/2018.
// Copyright © 2018 Atto Allas. All rights reserved.
//
import UIKit
let goControlViewBezel: CGFloat = 5
let curvatureLeeway: CGFloat = 25
class FakeTwitterSegue: UIStoryboardSegue {
override func perform() {
let mapViewController = self.source as! ViewController
mapViewController.savedGoControlViewFrame = mapViewController.goControlView.frame
let goViewControllerView = self.destination.view!
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let centerX = screenWidth * 0.5
let centerY = screenHeight * 0.5
let window = UIApplication.shared.keyWindow
goViewControllerView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
goViewControllerView.alpha = 0
window?.insertSubview(goViewControllerView, aboveSubview: mapViewController.view)
let goControlRadius = mapViewController.goControlView.frame.width * 0.5
// Unhides the dodgy pixel, this must be done now
mapViewController.animationView.isHidden = false
mapViewController.animationView.layer.zPosition = 2
UIView.animateKeyframes(withDuration: 0.8, delay: 0, options: .calculationModeLinear, animations: {
// Add animations
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {
let animationViewRadius = goControlRadius-goControlViewBezel
mapViewController.animationView.frame = CGRect(x: centerX-animationViewRadius, y: centerY-animationViewRadius, width: animationViewRadius*2, height: animationViewRadius*2)
mapViewController.goControlView.center = CGPoint(x: centerX, y: centerY)
mapViewController.bikeIcon.center = CGPoint(x: centerX, y: centerY)
mapViewController.animationView.center = CGPoint(x: centerX, y: centerY)
})
UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.55, animations: {
mapViewController.animationView.frame = CGRect(x: -curvatureLeeway, y: -curvatureLeeway*screenHeight/screenWidth, width: 2*curvatureLeeway+screenWidth, height: 2*curvatureLeeway*screenHeight/screenWidth+screenHeight)
mapViewController.goControlView.frame = CGRect(x: -curvatureLeeway-goControlViewBezel, y: (-curvatureLeeway)*screenHeight/screenWidth-goControlViewBezel, width: 2*(goControlViewBezel+curvatureLeeway)+screenWidth, height: 2*(curvatureLeeway)*screenHeight/screenWidth+2*goControlViewBezel+screenHeight)
})
UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
goViewControllerView.alpha = 1
})
}, completion: { _ in
self.source.present(self.destination, animated: false, completion: nil)
})
}
}
| 46.382353 | 316 | 0.669309 |
0e0ab37cbc4d0f11db065b92af448cfd9251ea0e | 8,282 | //
// TotalsSteadyStatePlotViewController.swift
// BalticBoxModel
//
// Created by Bo Gustafsson on 2017-01-12.
// Copyright © 2017 Bo Gustafsson. All rights reserved.
//
import Cocoa
import CorePlot
class TotalsSteadyStatePlotViewController: NSViewController {
var dataToPlot = [[[Double]]]()
var stability = [[Bool]]()
var variables = [[Int]]()
var variableNames = [[String]]()
var parameterName = ""
let topleftPG = SteadyStatePlotGenerator()
let topRightPG = SteadyStatePlotGenerator()
let lowerLeftPG = SteadyStatePlotGenerator()
let lowerRightPG = SteadyStatePlotGenerator()
@IBOutlet var plotView: NSView!
@IBOutlet weak var topRightView: CPTGraphHostingView!
@IBOutlet weak var lowerRightView: CPTGraphHostingView!
@IBOutlet weak var lowerLeftView: CPTGraphHostingView!
@IBOutlet weak var topLeftView: CPTGraphHostingView!
fileprivate var saveObserver : NSObjectProtocol?
fileprivate var steadyStateObserver : NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
// plotView.printRect = plotView.bounds
let size = CGSize(width: plotView.bounds.width * 0.5, height: plotView.bounds.height)
let rect = NSRect(origin: plotView.bounds.origin, size: size)
plotView.wantsLayer = true
topLeftView.printRect = rect
lowerLeftView.printRect = rect
topRightView.printRect = rect
lowerRightView.printRect = rect
let center = NotificationCenter.default
let queue = OperationQueue.main
steadyStateObserver = center.addObserver(forName: NSNotification.Name(rawValue: STEADYSTATEREADY.Notification), object: nil, queue: queue) { notification in
if let data = (notification as NSNotification).userInfo?[STEADYSTATEREADY.TotalsResults] as? [[[Double]]] {
self.dataToPlot = data
} else {
self.dataToPlot.removeAll()
}
if let data = (notification as NSNotification).userInfo?[STEADYSTATEREADY.StabilityResults] as? [[Bool]] {
self.stability = data
} else {
self.stability.removeAll()
}
if let vars = (notification as NSNotification).userInfo?[STEADYSTATEREADY.TotalsVariables] as? [[Int]] {
self.variables = vars
if let names = (notification as NSNotification).userInfo?[STEADYSTATEREADY.TotalsVarNames] as? [[String]] {
self.variableNames = names
if let pName = (notification as NSNotification).userInfo?[STEADYSTATEREADY.NameOfParameter] as? String {
self.parameterName = pName
self.plotData()
}
}
}
}
saveObserver = center.addObserver(forName: NSNotification.Name(rawValue: SAVE.Notification), object: nil, queue: queue) { notification in
if let myExporter = (notification as NSNotification).userInfo?[SAVE.ExporterInstance] as? ExportData {
let pdfData = self.plotView.dataWithPDF(inside: self.plotView.bounds)
if !((try? pdfData.write(to: URL(fileURLWithPath: myExporter.outputPath + "/SteadyStateTotalsplots" + ".pdf"), options: [.atomic])) != nil) {
print("PDF write failed")
}
let epsData = self.plotView.dataWithEPS(inside: self.plotView.bounds)
if !((try? epsData.write(to: URL(fileURLWithPath: myExporter.outputPath + "/SteadyStateTotalsplots" + ".eps"), options: [.atomic])) != nil) {
print("EPS write failed")
}
}
}
}
override func viewWillAppear() {
super.viewWillAppear()
plotView.layer?.backgroundColor = NSColor.white.cgColor
}
/* override func viewDidDisappear() {
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(saveObserver!)
center.removeObserver(steadyStateObserver!)
}
*/
fileprivate func plotData() {
makeOnePlot(topLeftView, plotGenerator: topleftPG, data: dataToPlot, stability: stability, vars: variables[0], names: variableNames[0])
makeOnePlot(topRightView, plotGenerator: topRightPG, data: dataToPlot, stability: stability, vars: variables[1], names: variableNames[1])
makeOnePlot(lowerLeftView, plotGenerator: lowerLeftPG, data: dataToPlot, stability: stability, vars: variables[2], names: variableNames[2])
makeOnePlot(lowerRightView, plotGenerator: lowerRightPG, data: dataToPlot, stability: stability, vars: variables[3], names: variableNames[3])
}
fileprivate func makeOnePlot(_ view: CPTGraphHostingView, plotGenerator: SteadyStatePlotGenerator, data: [[[Double]]], stability: [[Bool]], vars: [Int], names: [String]) {
let prepareResult = prepareDataForPlot(data, stabilityData: stability, variablesToPlot: vars)
let plottingData = prepareResult.plottingData
let limits = prepareResult.limits
let plottingVariables = prepareResult.plottingVariables
plotGenerator.plottingData = plottingData
plotGenerator.plottingStability = prepareResult.plottingStability
plotGenerator.xAxisTitle = self.parameterName
plotGenerator.makePlot(view, xyLimits: limits, variableNames: names, plottingVariables: plottingVariables)
}
fileprivate func prepareDataForPlot(_ data : [[[Double]]], stabilityData: [[Bool]], variablesToPlot : [Int]) -> (limits: XYLimits, plottingData: [Int: [Point]], plottingStability: [Int: [Bool]], plottingVariables: [Int]) {
var plottingData = [Int: [Point]]()
var plottingStability = [Int: [Bool]]()
var xmin = 1.0e10
var xmax = -1.0e10
var ymax = -1.0e10
var ymin = 1.0e10
var plottingVariables = [Int]()
var k = 0
var n = 0
for vars in variablesToPlot {
// data[x][solution][variable]
var temp = [Int: [Point]]()
var stemp = [Int: [Bool]]()
var imax = 0
var l = 0
for result in data { //Loop over "x" point
for i in 0..<result.count { //Loop over multiple solutions for given "x"
let solution = result[i]
let stab = stability[l][i]
if solution.count > 0 {
if var ta = temp[i] {
ta.append(Point(x: solution[0], y: solution[vars]))
temp[i] = ta
} else {
let ta = [Point(x: solution[0], y: solution[vars])]
temp[i] = ta
}
if var st = stemp[i] {
st.append(stab)
stemp[i] = st
} else {
let ts = [stab]
stemp[i] = ts
}
xmin = min(xmin, solution[0])
xmax = max(xmax, solution[0])
ymin = min(ymin, solution[vars])
ymax = max(ymax, solution[vars])
imax = max(i, imax)
}
}
l += 1
}
for i in 0...imax {
if let pd = temp[i] {
if pd.count > 0 {
plottingData[k] = pd
plottingStability[k] = stemp[i]
plottingVariables.append(n)
k += 1
}
}
}
n += 1
}
ymax = ymax + 0.1 * (ymax - ymin)
ymin = ymin - 0.1 * (ymax - ymin)
if abs(ymax) > 0 {
if abs(ymax - ymin)/abs(ymax) < 1.0e-4 {
ymax = ymax * 1.2
ymin = ymin * 0.8
}
}
return (XYLimits(min: Point(x: xmin, y: ymin), max: Point(x: xmax, y: ymax)), plottingData, plottingStability, plottingVariables)
}
}
| 44.053191 | 226 | 0.563511 |
48725d919292055a0f2d58cfb79f193f99e2df39 | 1,419 | //
// StressTestUITests.swift
// StressTestUITests
//
// Created by Julian Rex on 12/12/20.
//
import XCTest
class StressTestUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33 | 182 | 0.656801 |
1dc775348e580e4af648c9075b1ce5778fe13522 | 803 | //
// ImagePredictorProtocol.swift
// FritzAIStudio
//
// Created by Christopher Kelly on 4/24/19.
// Copyright © 2019 Fritz Labs, Inc. All rights reserved.
//
import Foundation
import Fritz
protocol ImagePredictor {
/// Runs prediction for a FritzVisionImage with user configurable options.
///
/// A common use case of this Delegate is to extend an existing FritzVision model
/// That just runs the predict method.
///
/// - Parameters:
/// - image: FritzVisionImage with camera orientation settings applied.
/// - options: Options that can be be configured for the model. These commonly can either be used to build the Model's options object or for postprocessing parameters.
func predict(_ image: FritzVisionImage, options: ConfigurableOptions) throws -> UIImage?
}
| 29.740741 | 172 | 0.731009 |
b9d49758b7e84987f8b43134a361f2ab54cef5a1 | 2,952 | // Copyright 2020-2021 Tokamak contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Created by Carson Katri on 6/29/20.
//
import Foundation
public struct _BackgroundModifier<Background>: ViewModifier, EnvironmentReader
where Background: View
{
public var environment: EnvironmentValues!
public var background: Background
public var alignment: Alignment
public init(background: Background, alignment: Alignment = .center) {
self.background = background
self.alignment = alignment
}
public func body(content: Content) -> some View {
// FIXME: Clip to bounds of foreground.
ZStack(alignment: alignment) {
background
content
}
}
mutating func setContent(from values: EnvironmentValues) {
environment = values
}
}
extension _BackgroundModifier: Equatable where Background: Equatable {
public static func == (
lhs: _BackgroundModifier<Background>,
rhs: _BackgroundModifier<Background>
) -> Bool {
lhs.background == rhs.background
}
}
public extension View {
func background<Background>(
_ background: Background,
alignment: Alignment = .center
) -> some View where Background: View {
modifier(_BackgroundModifier(background: background, alignment: alignment))
}
}
public struct _OverlayModifier<Overlay>: ViewModifier, EnvironmentReader
where Overlay: View
{
public var environment: EnvironmentValues!
public var overlay: Overlay
public var alignment: Alignment
public init(overlay: Overlay, alignment: Alignment = .center) {
self.overlay = overlay
self.alignment = alignment
}
public func body(content: Content) -> some View {
// FIXME: Clip to content shape.
ZStack(alignment: alignment) {
content
overlay
}
}
mutating func setContent(from values: EnvironmentValues) {
environment = values
}
}
extension _OverlayModifier: Equatable where Overlay: Equatable {
public static func == (lhs: _OverlayModifier<Overlay>, rhs: _OverlayModifier<Overlay>) -> Bool {
lhs.overlay == rhs.overlay
}
}
public extension View {
func overlay<Overlay>(_ overlay: Overlay, alignment: Alignment = .center) -> some View
where Overlay: View
{
modifier(_OverlayModifier(overlay: overlay, alignment: alignment))
}
func border<S>(_ content: S, width: CGFloat = 1) -> some View where S: ShapeStyle {
overlay(Rectangle().strokeBorder(content, lineWidth: width))
}
}
| 28.114286 | 98 | 0.720528 |
f7f78491a4efee9448f564d08c6a6ff94f8039ca | 2,609 | //
// UIScrollView+WCQ.swift
// SuperGina
//
// Created by 王策 on 15/6/17.
// Copyright (c) 2015年 Anve. All rights reserved.
//
import UIKit
public extension UIScrollView {
public var offsetX : CGFloat {
get {
return contentOffset.x
}
set {
contentOffset.x = newValue
}
}
public var offsetY : CGFloat {
get {
return contentOffset.y
}
set {
contentOffset.y = newValue
}
}
public var insetTop : CGFloat {
get {
return contentInset.top
}
set {
contentInset.top = newValue
scrollIndicatorInsets.top = newValue
}
}
public var insetBottom : CGFloat {
get {
return contentInset.bottom
}
set {
contentInset.bottom = newValue
scrollIndicatorInsets.bottom = newValue
}
}
public func insetBottom(bottom : CGFloat) -> Self {
insetBottom = bottom
scrollIndicatorInsets.bottom = bottom
return self
}
public func offsetX(offsetX:CGFloat) -> Self {
self.offsetX = offsetX
return self
}
public func offsetY(offsetY : CGFloat) -> Self {
self.offsetY = offsetY
return self
}
public func insetTop(top : CGFloat) -> Self {
insetTop = top
scrollIndicatorInsets.top = top
return self
}
public func bounces(bounces : Bool) -> Self {
self.bounces = bounces
return self
}
public func contentSize(size : CGSize) -> Self {
contentSize = size
return self
}
public func contentInset(contentInset : UIEdgeInsets) -> Self {
self.contentInset = contentInset
return self
}
public func scrollIndicatorInsets(scrollIndicatorInsets : UIEdgeInsets) -> Self {
self.scrollIndicatorInsets = scrollIndicatorInsets
return self
}
public func contentOffset(contentOffset : CGPoint) -> Self {
self.contentOffset = contentOffset
return self
}
public func alwaysBounceVertical(alwaysBounceVertical : Bool) -> Self {
self.alwaysBounceVertical = alwaysBounceVertical
return self
}
public func scrollEnabled(scrollEnabled : Bool) -> Self {
self.scrollEnabled = scrollEnabled
return self
}
public func pagingEnabled(pagingEnabled : Bool) -> Self {
self.pagingEnabled = pagingEnabled
return self
}
public func delegate(delegate : protocol<UIScrollViewDelegate>) -> Self {
self.delegate = delegate
return self
}
public func showsVerticalScrollIndicator(showsVerticalScrollIndicator:Bool) -> Self {
self.showsVerticalScrollIndicator = showsVerticalScrollIndicator
return self
}
public func showsHorizontalScrollIndicator(showsHorizontalScrollIndicator: Bool) -> Self {
self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator
return self
}
}
| 20.069231 | 91 | 0.718283 |
147076b631f910162420c40d734fb5aa2ba2c4d7 | 5,504 | //
// AuthViewControllerTheme2.swift
// AptoSDK
//
// Created by Takeichi Kanzaki on 30/10/2018.
//
import UIKit
import UIKit
import SnapKit
class AuthViewControllerTheme2: AuthViewControllerProtocol {
private unowned let eventHandler: AuthEventHandler
private let mode: AptoUISDKMode
private let formView: MultiStepForm
private let titleLabel: UILabel
private let explanationLabel: UILabel
private var continueButton: UIButton! // swiftlint:disable:this implicitly_unwrapped_optional
private var shouldBecomeFirstResponder = true
init(uiConfiguration: UIConfig, mode: AptoUISDKMode, eventHandler: AuthEventHandler) {
self.formView = MultiStepForm()
self.mode = mode
self.eventHandler = eventHandler
self.titleLabel = ComponentCatalog.largeTitleLabelWith(text: "", multiline: false, uiConfig: uiConfiguration)
self.explanationLabel = ComponentCatalog.formLabelWith(text: "auth.input_phone.explanation".podLocalized(),
multiline: true,
lineSpacing: uiConfiguration.lineSpacing,
letterSpacing: uiConfiguration.letterSpacing,
uiConfig: uiConfiguration)
super.init(uiConfiguration: uiConfiguration)
self.continueButton = ComponentCatalog.buttonWith(title: "auth.input_phone.call_to_action.title".podLocalized(),
showShadow: false,
accessibilityLabel: "Continue button",
uiConfig: uiConfiguration) { [unowned self] in
self.view.endEditing(true)
self.nextTapped()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
eventHandler.viewLoaded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if shouldBecomeFirstResponder {
shouldBecomeFirstResponder = false
formView.becomeFirstResponder()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Public methods
func setTitle(_ title: String) {
titleLabel.text = title
}
func setExplainationTitle(_ title: String) {
explanationLabel.updateAttributedText(title)
}
func setButtonTitle(_ title: String) {
continueButton.updateAttributedTitle(title, for: .normal)
}
func show(fields: [FormRowView]) {
formView.show(rows: fields)
}
func update(progress: Float) {
}
func showCancelButton() {
if mode == .embedded {
showNavCancelButton(uiConfiguration.textTopBarPrimaryColor)
} else {
showNavPreviousButton(uiConfiguration.textTopBarPrimaryColor)
}
}
func show(error: NSError) {
super.show(error: error)
}
func showNextButton() {
continueButton.isHidden = false
}
func activateNextButton() {
continueButton.isEnabled = true
continueButton.backgroundColor = uiConfiguration.uiPrimaryColor
}
func deactivateNextButton() {
continueButton.isEnabled = false
continueButton.backgroundColor = uiConfiguration.uiPrimaryColorDisabled
}
override func nextTapped() {
eventHandler.nextTapped()
}
override func closeTapped() {
eventHandler.closeTapped()
}
@objc func viewTapped() {
formView.resignFirstResponder()
}
}
// MARK: - Setup UI
private extension AuthViewControllerTheme2 {
func setUpUI() {
view.backgroundColor = uiConfiguration.uiBackgroundPrimaryColor
view.addGestureRecognizer(UITapGestureRecognizer(target: self,
action: #selector(AuthViewControllerTheme2.viewTapped)))
setUpNavigationBar()
edgesForExtendedLayout = .top
extendedLayoutIncludesOpaqueBars = false
setUpTitleLabel()
setUpExplanationLabel()
setUpFormView()
setUpContinueButton()
}
func setUpNavigationBar() {
navigationController?.navigationBar.hideShadow()
navigationController?.navigationBar.setUp(barTintColor: uiConfiguration.uiNavigationPrimaryColor,
tintColor: uiConfiguration.textTopBarPrimaryColor)
}
func setUpTitleLabel() {
titleLabel.adjustsFontSizeToFitWidth = true
view.addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(20)
make.top.equalToSuperview().offset(16)
}
}
func setUpExplanationLabel() {
view.addSubview(explanationLabel)
explanationLabel.snp.makeConstraints { make in
make.left.right.equalTo(titleLabel)
make.top.equalTo(titleLabel.snp.bottom).offset(8)
}
}
func setUpFormView() {
view.addSubview(formView)
formView.snp.makeConstraints { make in
make.top.equalTo(explanationLabel.snp.bottom).offset(24)
make.left.right.bottom.equalToSuperview()
}
formView.backgroundColor = UIColor.clear
}
func setUpContinueButton() {
view.addSubview(continueButton)
continueButton.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(20)
make.bottom.equalToSuperview().inset(buttonBottomMargin)
}
}
var buttonBottomMargin: Int {
switch UIDevice.deviceType() {
case .iPhone5:
return 60
case .iPhone678:
return 250
default:
return 320
}
}
}
| 29.751351 | 116 | 0.670422 |
8f6bbc9bdead6cd80945d3bba0f1997921850927 | 308 | //: [Previous](@previous)
import MetalKit
import PlaygroundSupport
let size: CGFloat = 400
let renderer = Renderer(size: size)
let frame = CGRect(x: 0, y: 0, width: size, height: size)
let view = MTKView(frame: frame, device: renderer.device)
view.delegate = renderer
PlaygroundPage.current.liveView = view
| 28 | 57 | 0.75 |
5dbd02715b0e992ac7a27e046637d8526e9d1691 | 1,887 | /*
* Copyright (C) 2014-2019 halo https://github.com/halo/macosvpn
*
* 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
extension ServiceConfig {
enum Splitter {
/// Splits an Array of command line arguments into one array per VPN service
static func parse(_ arguments: [String]) throws -> [ServiceConfig] {
let delimiters = Set([Flag.L2TP.dashed,
Flag.L2TPShort.dashed,
Flag.Cisco.dashed,
Flag.CiscoShort.dashed])
let slices = arguments.split(before: delimiters.contains)
var result: [ServiceConfig] = []
for slice in slices {
Log.debug("Processing argument slice: \(slice)")
let serviceConfig = try ServiceConfig.Parser.parse((Array(slice)))
result.append(serviceConfig)
}
return result
}
}
}
| 47.175 | 133 | 0.704293 |
ddcf8017249560666cdd246420b469929d661724 | 2,343 | //
// SceneDelegate.swift
// SwiftExample
//
// Created by Animax Deng on 5/9/20.
// Copyright © 2020 Animax. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.388889 | 147 | 0.713188 |
5be68551a0b510e5c1b544b8ed1d98e9c969b728 | 1,284 | // RUN: %swift -interpret %s | %FileCheck %s -check-prefix=CHECK-NONE
// RUN: %swift -interpret %s -Onone -g | %FileCheck %s -check-prefix=CHECK-NONE
// RUN: %swift -interpret %s -Onone -g -- | %FileCheck %s -check-prefix=CHECK-NONE
// RUN: %swift -interpret %s -Onone -g -- a b c | %FileCheck %s -check-prefix=CHECK-THREE
// REQUIRES: swift_interpreter
print("Begin arguments")
for arg in CommandLine.arguments { print(arg) }
print("End arguments")
// CHECK-NONE: Begin arguments
// CHECK-NONE-NEXT: {{.*}}process_arguments.swift
// CHECK-NONE-NEXT: End arguments
// CHECK-THREE: Begin arguments
// CHECK-THREE-NEXT: {{.*}}process_arguments.swift
// CHECK-THREE-NEXT: a
// CHECK-THREE-NEXT: b
// CHECK-THREE-NEXT: c
// CHECK-THREE-NEXT: End arguments
print("Begin unsafeArgv")
for i in 0...Int(CommandLine.argc) {
print(CommandLine.unsafeArgv[i].map { String(cString: $0) } ?? "(null)")
}
print("End unsafeArgv")
// CHECK-NONE: Begin unsafeArgv
// CHECK-NONE-NEXT: {{.*}}process_arguments.swift
// CHECK-NONE-NEXT: (null)
// CHECK-NONE-NEXT: End unsafeArgv
// CHECK-THREE: Begin unsafeArgv
// CHECK-THREE-NEXT: {{.*}}process_arguments.swift
// CHECK-THREE-NEXT: a
// CHECK-THREE-NEXT: b
// CHECK-THREE-NEXT: c
// CHECK-THREE-NEXT: (null)
// CHECK-THREE-NEXT: End unsafeArgv
| 31.317073 | 89 | 0.692368 |
2f4e16b9bf0d8d13336bbd0f8ea7cae86923226a | 1,125 | //
// FacebookUser.swift
// LoginScreen
//
// Created by Florian Marcu on 1/15/17.
// Copyright © 2017 iOS App Templates. All rights reserved.
//
class FacebookUser {
let firstName: String?
let lastName: String?
let email: String?
let id: String?
let profilePicture: String?
init (dictionary: [String: Any]) {
self.firstName = dictionary["first_name"] as? String
self.lastName = dictionary["last_name"] as? String
self.email = dictionary["email"] as? String
self.id = dictionary["id"] as? String
if let pictureDict = dictionary["picture"] as? [String: Any] {
if let dataDict = pictureDict["data"] as? [String: Any] {
self.profilePicture = dataDict["url"] as? String
return
}
}
self.profilePicture = ""
}
init (firstName: String?, lastName: String?, email: String?, id: String?, profilePicture: String?) {
self.firstName = firstName
self.lastName = lastName
self.email = email
self.id = id
self.profilePicture = profilePicture
}
}
| 29.605263 | 104 | 0.599111 |
ac85d2b79cda2c28a95360063b52417b2bf47ddc | 793 | /**
* https://leetcode.com/problems/wiggle-subsequence/
*
*
*/
// Date: Thu Mar 18 15:30:35 PDT 2021
class Solution {
func wiggleMaxLength(_ nums: [Int]) -> Int {
var up = Array(repeating: 1, count: nums.count)
var down = Array(repeating: 1, count: nums.count)
var result = 1
for index in stride(from: 1, to: nums.count, by: 1) {
for last in stride(from: 0, to: index, by: 1) {
if nums[index] > nums[last] {
up[index] = max(up[index], 1 + down[last])
} else if nums[index] < nums[last] {
down[index] = max(down[index], 1 + up[last])
}
}
result = max(result, max(down[index], up[index]))
}
return result
}
} | 33.041667 | 64 | 0.499369 |
f933e94fc0b26979ce77917e0bb40c4afb365820 | 928 | //
// QiitaKitError.swift
// QiitaKit
//
// Created by 山口 恭兵 on 2016/01/09.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import Foundation
/// QiitaAPIからのエラー
public enum QiitaKitError: Error {
case invalidRedirectScheme
case invalidState
case faildToGetAccessToken
case alreadyStocked
case apiError(APIError)
case invalidJSON(Swift.Error)
case unknown
case urlSessionError(Swift.Error)
internal init(object: Data) {
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .iso8601
guard let error = try? jsonDecoder.decode(APIError.self, from: object) else {
self = .unknown
return
}
switch error.type {
case "already_stocked": self = .alreadyStocked
default: self = .apiError(error)
}
}
}
| 20.173913 | 85 | 0.594828 |
290db7789a20818474a0d8c9c322f3ab8b7d50a6 | 1,809 | //
// TableViewController.swift
// SO-35001392
//
// Copyright © 2017, 2018 Xavier Schott
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class TableViewController: UITableViewController {
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
if let textLabel = cell.textLabel {
textLabel.backgroundColor = UIColor.clear
textLabel.text = "\(1 + indexPath.row)"
}
return cell
}
}
| 42.069767 | 109 | 0.725815 |
382a8cf552f24d5bb38a7c4433ace3d2a48dbb73 | 1,255 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public class AAHeaderCell: AATableViewCell {
public var titleView = UILabel()
public var iconView = UIImageView()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = appStyle.vcBackyardColor
selectionStyle = UITableViewCellSelectionStyle.None
titleView.textColor = appStyle.cellHeaderColor
titleView.font = UIFont.systemFontOfSize(14)
contentView.addSubview(titleView)
iconView.contentMode = UIViewContentMode.ScaleAspectFill
contentView.addSubview(iconView)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
let height = self.contentView.bounds.height
let width = self.contentView.bounds.width
titleView.frame = CGRectMake(15, height - 28, width - 48, 24)
iconView.frame = CGRectMake(width - 18 - 15, height - 18 - 4, 18, 18)
}
} | 32.179487 | 81 | 0.660558 |
1e3a9ccc94c6d2ca52cac31d2412c257a94816cc | 1,351 | public class Node<T: Hashable> {
public let value: T
public let left: Node?
public let right: Node?
public convenience init?(inorder: [T], preorder: [T]) {
var inorderIndexes = [T: Int]()
for (index, value) in inorder.enumerated() {
inorderIndexes[value] = index
}
self.init(
inorder: inorder[0..<inorder.count],
preorder: preorder[0..<preorder.count],
inorderIndexes: inorderIndexes
)
}
init?(inorder: ArraySlice<T>, preorder: ArraySlice<T>, inorderIndexes: [T: Int]) {
if inorder.isEmpty {
return nil
}
self.value = preorder.first!
let inorderRootIndex = inorderIndexes[self.value]!
let leftCount = inorderRootIndex - inorder.startIndex
let preorderRightStartIndex = preorder.startIndex + 1 + leftCount
self.left = Node(
inorder: inorder[inorder.startIndex..<inorderRootIndex],
preorder: preorder[preorder.startIndex + 1..<preorderRightStartIndex],
inorderIndexes: inorderIndexes
)
self.right = Node(
inorder: inorder[inorderRootIndex + 1..<inorder.endIndex],
preorder: preorder[preorderRightStartIndex..<preorder.endIndex],
inorderIndexes: inorderIndexes
)
}
}
| 31.418605 | 86 | 0.603997 |
ed70e3e8e14d477fa15132752af19233921b544c | 6,411 | // WARNING: This is a generated file. Do not edit it. Instead, edit the corresponding ".gyb" file.
// See "generate.sh" in the root of this repository for instructions how to regenerate files.
import Foundation
import TensorFlow
import XCTest
import SwiftFusion
class VectorNTests: XCTestCase {
/// Test that initializing a vector from coordinate values works.
func testVector1Init() {
let vector1 = Vector1(1)
XCTAssertEqual(vector1.x, 1)
}
func testVector1VectorConformance() {
let s = (0..<1).lazy.map { Double($0) }
let v = Vector1(0)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (1..<2).lazy.map { Double($0) },
maxSupportedScalarCount: 1)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 1)
}
/// Test that initializing a vector from coordinate values works.
func testVector2Init() {
let vector1 = Vector2(1, 2)
XCTAssertEqual(vector1.x, 1)
XCTAssertEqual(vector1.y, 2)
}
func testVector2VectorConformance() {
let s = (0..<2).lazy.map { Double($0) }
let v = Vector2(0, 1)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (2..<4).lazy.map { Double($0) },
maxSupportedScalarCount: 2)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 2)
}
/// Test that initializing a vector from coordinate values works.
func testVector3Init() {
let vector1 = Vector3(1, 2, 3)
XCTAssertEqual(vector1.x, 1)
XCTAssertEqual(vector1.y, 2)
XCTAssertEqual(vector1.z, 3)
}
func testVector3VectorConformance() {
let s = (0..<3).lazy.map { Double($0) }
let v = Vector3(0, 1, 2)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (3..<6).lazy.map { Double($0) },
maxSupportedScalarCount: 3)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 3)
}
/// Test that initializing a vector from coordinate values works.
func testVector4Init() {
let vector1 = Vector4(1, 2, 3, 4)
XCTAssertEqual(vector1.s0, 1)
XCTAssertEqual(vector1.s1, 2)
XCTAssertEqual(vector1.s2, 3)
XCTAssertEqual(vector1.s3, 4)
}
func testVector4VectorConformance() {
let s = (0..<4).lazy.map { Double($0) }
let v = Vector4(0, 1, 2, 3)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (4..<8).lazy.map { Double($0) },
maxSupportedScalarCount: 4)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 4)
}
/// Test that initializing a vector from coordinate values works.
func testVector5Init() {
let vector1 = Vector5(1, 2, 3, 4, 5)
XCTAssertEqual(vector1.s0, 1)
XCTAssertEqual(vector1.s1, 2)
XCTAssertEqual(vector1.s2, 3)
XCTAssertEqual(vector1.s3, 4)
XCTAssertEqual(vector1.s4, 5)
}
func testVector5VectorConformance() {
let s = (0..<5).lazy.map { Double($0) }
let v = Vector5(0, 1, 2, 3, 4)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (5..<10).lazy.map { Double($0) },
maxSupportedScalarCount: 5)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 5)
}
/// Test that initializing a vector from coordinate values works.
func testVector6Init() {
let vector1 = Vector6(1, 2, 3, 4, 5, 6)
XCTAssertEqual(vector1.s0, 1)
XCTAssertEqual(vector1.s1, 2)
XCTAssertEqual(vector1.s2, 3)
XCTAssertEqual(vector1.s3, 4)
XCTAssertEqual(vector1.s4, 5)
XCTAssertEqual(vector1.s5, 6)
}
func testVector6VectorConformance() {
let s = (0..<6).lazy.map { Double($0) }
let v = Vector6(0, 1, 2, 3, 4, 5)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (6..<12).lazy.map { Double($0) },
maxSupportedScalarCount: 6)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 6)
}
/// Test that initializing a vector from coordinate values works.
func testVector7Init() {
let vector1 = Vector7(1, 2, 3, 4, 5, 6, 7)
XCTAssertEqual(vector1.s0, 1)
XCTAssertEqual(vector1.s1, 2)
XCTAssertEqual(vector1.s2, 3)
XCTAssertEqual(vector1.s3, 4)
XCTAssertEqual(vector1.s4, 5)
XCTAssertEqual(vector1.s5, 6)
XCTAssertEqual(vector1.s6, 7)
}
func testVector7VectorConformance() {
let s = (0..<7).lazy.map { Double($0) }
let v = Vector7(0, 1, 2, 3, 4, 5, 6)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (7..<14).lazy.map { Double($0) },
maxSupportedScalarCount: 7)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 7)
}
/// Test that initializing a vector from coordinate values works.
func testVector8Init() {
let vector1 = Vector8(1, 2, 3, 4, 5, 6, 7, 8)
XCTAssertEqual(vector1.s0, 1)
XCTAssertEqual(vector1.s1, 2)
XCTAssertEqual(vector1.s2, 3)
XCTAssertEqual(vector1.s3, 4)
XCTAssertEqual(vector1.s4, 5)
XCTAssertEqual(vector1.s5, 6)
XCTAssertEqual(vector1.s6, 7)
XCTAssertEqual(vector1.s7, 8)
}
func testVector8VectorConformance() {
let s = (0..<8).lazy.map { Double($0) }
let v = Vector8(0, 1, 2, 3, 4, 5, 6, 7)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (8..<16).lazy.map { Double($0) },
maxSupportedScalarCount: 8)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 8)
}
/// Test that initializing a vector from coordinate values works.
func testVector9Init() {
let vector1 = Vector9(1, 2, 3, 4, 5, 6, 7, 8, 9)
XCTAssertEqual(vector1.s0, 1)
XCTAssertEqual(vector1.s1, 2)
XCTAssertEqual(vector1.s2, 3)
XCTAssertEqual(vector1.s3, 4)
XCTAssertEqual(vector1.s4, 5)
XCTAssertEqual(vector1.s5, 6)
XCTAssertEqual(vector1.s6, 7)
XCTAssertEqual(vector1.s7, 8)
XCTAssertEqual(vector1.s8, 9)
}
func testVector9VectorConformance() {
let s = (0..<9).lazy.map { Double($0) }
let v = Vector9(0, 1, 2, 3, 4, 5, 6, 7, 8)
v.checkVectorSemantics(
expectingScalars: s,
writingScalars: (9..<18).lazy.map { Double($0) },
maxSupportedScalarCount: 9)
v.scalars.checkRandomAccessCollectionSemantics(
expecting: s,
maxSupportedCount: 9)
}
}
| 30.383886 | 98 | 0.660895 |
ef0692acb694145e81fd975a9fc475ffe25baafb | 2,038 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
/**
Used to expose API on view controllers
*/
extension UIViewController {
/// top layout guide top
var snp_topLayoutGuideTop: ConstraintItem { return ConstraintItem(object: self.topLayoutGuide, attributes: ConstraintAttributes.Top) }
/// top layout guide bottom
var snp_topLayoutGuideBottom: ConstraintItem { return ConstraintItem(object: self.topLayoutGuide, attributes: ConstraintAttributes.Bottom) }
/// bottom layout guide top
var snp_bottomLayoutGuideTop: ConstraintItem { return ConstraintItem(object: self.bottomLayoutGuide, attributes: ConstraintAttributes.Top) }
/// bottom layout guide bottom
var snp_bottomLayoutGuideBottom: ConstraintItem { return ConstraintItem(object: self.bottomLayoutGuide, attributes: ConstraintAttributes.Bottom) }
}
#endif
| 44.304348 | 150 | 0.752208 |
8adf5f489963b8a0e85040dc8f2a21eafec6ba30 | 2,448 | //
// CircularCarouselDelegate.swift
// CircularCarousel Demo
//
// Created by Piotr Suwara on 24/12/18.
// Copyright © 2018 Piotr Suwara. All rights reserved.
//
import Foundation
import UIKit
public protocol CircularCarouselDelegate {
func carouselWillBeginScrolling(_ carousel: CircularCarousel)
func carouselDidEndScrolling(_ carousel: CircularCarousel)
func carousel(_ carousel: CircularCarousel, currentItemDidChangeToIndex index: Int)
func carousel(_ carousel: CircularCarousel, willBeginScrollingToIndex index: Int)
func carousel(_ carousel: CircularCarousel, didEndScrollingToIndex index: Int)
func carousel(_ carousel: CircularCarousel, didSelectItemAtIndex index: Int)
func carousel(_ carousel: CircularCarousel, valueForOption option: CircularCarouselOption, withDefaultValue defaultValue: CGFloat) -> CGFloat
func carousel(_ carousel: CircularCarousel, valueForOption option: CircularCarouselOption, withDefaultValue defaultValue: Bool) -> Bool
func carousel(_ carousel: CircularCarousel, shouldSelectItemAtIndex index: Int) -> Bool
func carousel(_ carousel: CircularCarousel, spacingForOffset offset: CGFloat) -> CGFloat
}
public extension CircularCarouselDelegate {
func carouselWillBeginScrolling(_ carousel: CircularCarousel) {
}
func carouselDidEndScrolling(_ carousel: CircularCarousel) {
}
func carousel(_ carousel: CircularCarousel, currentItemDidChangeToIndex index: Int) {
}
func carousel(_ carousel: CircularCarousel, willBeginScrollingToIndex index: Int) {
}
func carousel(_ carousel: CircularCarousel, didEndScrollingToIndex index: Int) {
}
func carousel(_ carousel: CircularCarousel, didSelectItemAtIndex index: Int) {
}
func carousel(_ carousel: CircularCarousel, valueForOption option: CircularCarouselOption, withDefaultValue defaultValue: CGFloat) -> CGFloat {
return defaultValue
}
func carousel(_ carousel: CircularCarousel, valueForOption option: CircularCarouselOption, withDefaultValue defaultValue: Bool) -> Bool {
return defaultValue
}
func carousel(_ carousel: CircularCarousel, shouldSelectItemAtIndex index: Int) -> Bool {
return true
}
func carousel(_ carousel: CircularCarousel, spacingForOffset offset: CGFloat) -> CGFloat {
return 1.0
}
}
| 36 | 147 | 0.735294 |
08e1f7181f3a1b143e97747f9efbc9ebbdb50374 | 1,586 | //
// MediumSizeWidgetView.swift
// Covid19 (iOS)
//
// Created by pbhaskar on 20/08/20.
//
import WidgetKit
import SwiftUI
struct MediumSizeWidgetView: View {
var entry: CovidEntry
let gradient = Gradient(colors: [Color(red: 255/255, green: 157/255, blue: 157/255), Color(red: 255/255, green: 196/255, blue: 196/255)])
var body: some View {
VStack {
HStack {
MediumSizeContentView(enumStatus: .active, globalStats: entry.countryTotalCase)
MediumSizeContentView(enumStatus: .confirmed, globalStats: entry.countryTotalCase)
}
HStack {
MediumSizeContentView(enumStatus: .recovered, globalStats: entry.countryTotalCase)
MediumSizeContentView(enumStatus: .deceased, globalStats: entry.countryTotalCase)
}
}
.padding(.all)
}
}
struct MediumSizeWidgetView_Previews: PreviewProvider {
static var previews: some View {
MediumSizeWidgetView(entry: CovidEntry.stubs)
.previewContext(WidgetPreviewContext(family: .systemMedium))
}
}
struct MediumSizeContentView: View {
let enumStatus: GlobalStatsViewData
let globalStats: CountryTotalCase
var body: some View {
ZStack {
ContainerRelativeShape()
.fill(LinearGradient(gradient: enumStatus.getGradientColor(), startPoint: .leading, endPoint: .topTrailing))
VStack {
Text(enumStatus.getThemeTitle())
.foregroundColor(.black)
.bold()
Text("\(enumStatus.getCountryTotalCount(globalStats))")
.foregroundColor(.black)
.bold()
}
}
}
}
| 27.824561 | 139 | 0.677806 |
50c648a9507725525d193e73afdb5e4964ab6089 | 807 | //
// GameResultDatabaseManager.swift
// JU Quiz
//
// Created by Garrit on 13.11.20.
//
import Foundation
import CoreData
class GameResultDatabaseManager {
func create(withNumbersOfQuestions numberOfQuestions: Int, andRightAnswers rightAnswers: Int) -> GameResult? {
let managedObjectContext = DatabaseManager.shared.managedObjectContext
let gameResult = NSEntityDescription.insertNewObject(forEntityName: "GameResult", into: managedObjectContext) as? GameResult
// Setting the data
gameResult?.numberOfQuestions = Int32(numberOfQuestions)
gameResult?.rightAnswers = Int32(rightAnswers)
gameResult?.date = Date()
return gameResult
}
func save() {
DatabaseManager.shared.saveContext()
}
}
| 26.9 | 132 | 0.690211 |
7a9b78912cf4024716ef6a77b4033869df2177be | 1,174 | //
// Extension.swift
// StructAndArithmetic
//
// Created by zl on 2021/4/19.
//
import Cocoa
extension String {
static func tk_blank(count: Int) -> String {
return " ".tk_repeat(count: count)
}
func tk_repeat(count: Int) -> String {
var size = count
var string = ""
while size > 0 {
string.append(self)
size -= 1
}
return string
}
public func substring(location: Int, length: Int) ->String? {
if location < 0 && location >= self.count {
return nil
}
if length <= 0 || length > self.count {
return nil
}
if location + length > self.count {
return nil
}
return (self as NSString).substring(with: NSMakeRange(location, length))
}
/// 只能输入由26个英文字母组成的字符串
var isLetter: Bool {
return isMatch("^[A-Za-z]+$")
}
private func isMatch(_ pred: String ) -> Bool {
let pred = NSPredicate(format: "SELF MATCHES[c] %@", pred)
let isMatch: Bool = pred.evaluate(with: self)
return isMatch
}
}
| 22.150943 | 80 | 0.51448 |
cca7dad1af823da2224a7d97ecafb8bdbf3b9b9a | 6,297 | //
// DateInRegion+Components.swift
// SwiftDate
//
// Created by Daniele Margutti on 06/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
public extension DateInRegion {
/// Indicates whether the month is a leap month.
var isLeapMonth: Bool {
let calendar = region.calendar
// Library function for leap contains a bug for Gregorian calendars, implemented workaround
if calendar.identifier == Calendar.Identifier.gregorian && year > 1582 {
guard let range: Range<Int> = calendar.range(of: .day, in: .month, for: date) else {
return false
}
return ((range.upperBound - range.lowerBound) == 29)
}
// For other calendars:
return calendar.dateComponents([.day, .month, .year], from: date).isLeapMonth!
}
/// Indicates whether the year is a leap year.
var isLeapYear: Bool {
let calendar = region.calendar
// Library function for leap contains a bug for Gregorian calendars, implemented workaround
if calendar.identifier == Calendar.Identifier.gregorian {
var newComponents = dateComponents
newComponents.month = 2
newComponents.day = 10
let testDate = DateInRegion(components: newComponents, region: region)
return testDate!.isLeapMonth
} else if calendar.identifier == Calendar.Identifier.chinese {
/// There are 12 or 13 months in each year and 29 or 30 days in each month.
/// A 13-month year is a leap year, which meaning more than 376 days is a leap year.
return ( dateAtStartOf(.year).toUnit(.day, to: dateAtEndOf(.year)) > 375 )
}
// For other calendars:
return calendar.dateComponents([.day, .month, .year], from: date).isLeapMonth!
}
/// Julian day is the continuous count of days since the beginning of
/// the Julian Period used primarily by astronomers.
var julianDay: Double {
let destRegion = Region(calendar: Calendars.gregorian, zone: Zones.gmt, locale: Locales.english)
let utc = convertTo(region: destRegion)
let year = Double(utc.year)
let month = Double(utc.month)
let day = Double(utc.day)
let hour = Double(utc.hour) + Double(utc.minute) / 60.0 + (Double(utc.second) + Double(utc.nanosecond) / 1e9) / 3600.0
var jd = 367.0 * year - floor( 7.0 * ( year + floor((month + 9.0) / 12.0)) / 4.0 )
jd -= floor( 3.0 * (floor( (year + (month - 9.0) / 7.0) / 100.0 ) + 1.0) / 4.0 )
jd += floor(275.0 * month / 9.0) + day + 1_721_028.5 + hour / 24.0
return jd
}
/// The Modified Julian Date (MJD) was introduced by the Smithsonian Astrophysical Observatory
/// in 1957 to record the orbit of Sputnik via an IBM 704 (36-bit machine)
/// and using only 18 bits until August 7, 2576.
var modifiedJulianDay: Double {
return julianDay - 2_400_000.5
}
/// Return elapsed time expressed in given components since the current receiver and a reference date.
/// Time is evaluated with the fixed measumerent of each unity.
///
/// - Parameters:
/// - refDate: reference date (`nil` to use current date in the same region of the receiver)
/// - component: time unit to extract.
/// - Returns: value
func getInterval(toDate: DateInRegion?, component: Calendar.Component) -> Int64 {
let refDate = (toDate ?? region.nowInThisRegion())
switch component {
case .year:
let end = calendar.ordinality(of: .year, in: .era, for: refDate.date)
let start = calendar.ordinality(of: .year, in: .era, for: date)
return Int64(end! - start!)
case .month:
let end = calendar.ordinality(of: .month, in: .era, for: refDate.date)
let start = calendar.ordinality(of: .month, in: .era, for: date)
return Int64(end! - start!)
case .day:
let end = calendar.ordinality(of: .day, in: .era, for: refDate.date)
let start = calendar.ordinality(of: .day, in: .era, for: date)
return Int64(end! - start!)
case .hour:
let interval = refDate.date.timeIntervalSince(date)
return Int64(interval / 1.hours.timeInterval)
case .minute:
let interval = refDate.date.timeIntervalSince(date)
return Int64(interval / 1.minutes.timeInterval)
case .second:
return Int64(refDate.date.timeIntervalSince(date))
case .weekday:
let end = calendar.ordinality(of: .weekday, in: .era, for: refDate.date)
let start = calendar.ordinality(of: .weekday, in: .era, for: date)
return Int64(end! - start!)
case .weekdayOrdinal:
let end = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: refDate.date)
let start = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: date)
return Int64(end! - start!)
case .weekOfYear:
let end = calendar.ordinality(of: .weekOfYear, in: .era, for: refDate.date)
let start = calendar.ordinality(of: .weekOfYear, in: .era, for: date)
return Int64(end! - start!)
default:
debugPrint("Passed component cannot be used to extract values using interval() function between two dates. Returning 0.")
return 0
}
}
/// The interval between the receiver and the another parameter.
/// If the receiver is earlier than anotherDate, the return value is negative.
/// If anotherDate is nil, the results are undefined.
///
/// - Parameter date: The date with which to compare the receiver.
/// - Returns: time interval between two dates
func timeIntervalSince(_ date: DateInRegion) -> TimeInterval {
return self.date.timeIntervalSince(date.date)
}
/// Extract DateComponents from the difference between two dates.
///
/// - Parameter rhs: date to compare
/// - Returns: components
func componentsTo(_ rhs: DateInRegion) -> DateComponents {
return calendar.dateComponents(DateComponents.allComponentsSet, from: rhs.date, to: date)
}
/// Returns the difference between two dates (`date - self`) expressed as date components.
///
/// - Parameters:
/// - date: reference date as initial date (left operand)
/// - components: components to extract, `nil` to use default `DateComponents.allComponentsSet`
/// - Returns: extracted date components
func componentsSince(_ date: DateInRegion, components: [Calendar.Component]? = nil) -> DateComponents {
if date.calendar != calendar {
debugPrint("Date has different calendar, results maybe wrong")
}
let cmps = (components != nil ? Calendar.Component.toSet(components!) : DateComponents.allComponentsSet)
return date.calendar.dateComponents(cmps, from: date.date, to: self.date)
}
}
| 39.111801 | 124 | 0.702716 |
29d17bfab0171c0418de35ec3048793ba5f9a589 | 1,057 | //
// DetailTableViewCell.swift
// WeatherAPP
//
// Created by hyeri kim on 05/08/2019.
// Copyright © 2019 hyeri kim. All rights reserved.
//
import UIKit
class DetailTableViewCell: UITableViewCell {
@IBOutlet weak var leftTitleLabel: UILabel!
@IBOutlet weak var leftDescriptionLabel: UILabel!
@IBOutlet weak var rightTitleLabel: UILabel!
@IBOutlet weak var rightDescriptionLabel: UILabel!
var weatherDetailData: WeatherInfo? {
didSet{
guard let speed = weatherDetailData?.wind.speed,
let humidity = weatherDetailData?.main.humidity else {
return
}
leftDescriptionLabel.text = "\(speed)"
rightDescriptionLabel.text = "\(humidity)"
}
}
override func awakeFromNib() {
super.awakeFromNib()
leftTitleLabel.text = "wind"
rightTitleLabel.text = "humidity"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 25.166667 | 70 | 0.636708 |
1ec5dfbbff60a8b11f43f0f1544c589c7d825110 | 1,856 | //
// ThemedNavigationController.swift
// NetNewsWire
//
// Created by Maurice Parker on 8/22/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
class ThemedNavigationController: UINavigationController {
static func template() -> UINavigationController {
let navController = ThemedNavigationController()
navController.configure()
return navController
}
static func template(rootViewController: UIViewController) -> UINavigationController {
let navController = ThemedNavigationController(rootViewController: rootViewController)
navController.configure()
return navController
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
configure()
}
}
private func configure() {
isToolbarHidden = false
if traitCollection.userInterfaceStyle == .dark {
navigationBar.standardAppearance = UINavigationBarAppearance()
navigationBar.tintColor = view.tintColor
toolbar.standardAppearance = UIToolbarAppearance()
toolbar.tintColor = view.tintColor
} else {
let navigationAppearance = UINavigationBarAppearance()
navigationAppearance.backgroundColor = AppAssets.barBackgroundColor
navigationAppearance.titleTextAttributes = [.foregroundColor: AppAssets.barTitleColor]
navigationAppearance.largeTitleTextAttributes = [.foregroundColor: AppAssets.barTitleColor]
navigationBar.standardAppearance = navigationAppearance
navigationBar.tintColor = AppAssets.barTintColor
let toolbarAppearance = UIToolbarAppearance()
toolbarAppearance.backgroundColor = UIColor.white
toolbar.standardAppearance = toolbarAppearance
toolbar.tintColor = AppAssets.barTintColor
}
}
}
| 32.561404 | 94 | 0.797953 |
8ac714ddac9109d6fb8c2d2a0d49b77742908c2b | 1,332 | //
// AllocDataError.swift
//
// Copyright 2021 FlowAllocator LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public enum AllocDataError: Error, Equatable, CustomStringConvertible {
case encodingError(_ msg: String)
case targetFormatNotSupported(_ supported: [AllocFormat])
case invalidPrimaryKey(_ msg: String)
public var localizedDescription: String { description }
public var description: String {
switch self {
case let .encodingError(msg):
return String("Failure to encode. \(msg)")
case let .targetFormatNotSupported(supported):
return String("Supported target types: '\(supported.map(\.rawValue))'.")
case let .invalidPrimaryKey(msg):
return String("Invalid primary key: [\(msg)]")
}
}
}
| 35.052632 | 84 | 0.701201 |
5d05638ad472b8a481a17df502ee5f81432645d6 | 191 | //
// EnvironmentProtocol.swift
// MyDictionary
//
// Created by Дмитрий Чумаков on 30.12.2020.
//
import Foundation
protocol EnvironmentProtocol {
var baseURL: String { get }
}
| 14.692308 | 45 | 0.685864 |
4b2e0d353b75ebbcf5df36dee5e3bb7bad07ef46 | 1,879 | //
// LineSDKLoginResult.swift
//
// Copyright (c) 2016-present, LINE Corporation. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by LINE Corporation.
//
// As with any software that integrates with the LINE Corporation platform, your use of this software
// is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement].
// This copyright 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.
//
#if !LineSDKCocoaPods && !LineSDKBinary
import LineSDK
#endif
@objcMembers
public class LineSDKLoginResult: NSObject {
let _value: LoginResult
init(_ value: LoginResult) { _value = value }
public var accessToken: LineSDKAccessToken { return .init(_value.accessToken) }
public var permissions: Set<LineSDKLoginPermission> { return Set(_value.permissions.map { .init($0) }) }
public var userProfile: LineSDKUserProfile? { return _value.userProfile.map { .init($0) } }
public var friendshipStatusChanged: NSNumber? { return _value.friendshipStatusChanged.map { .init(value: $0) } }
public var IDTokenNonce: String? { return _value.IDTokenNonce }
public var json: String? { return toJSON(_value) }
}
| 48.179487 | 116 | 0.750399 |
f41bc9f56c5aeb2c6cdd6915b26dd298e3aa63e8 | 94 | public func unreachable(_ message: String = "unreachable") -> Never {
fatalError(message)
}
| 23.5 | 69 | 0.723404 |
1ce619e982fb9728a24a7620a5e07531a7552e0b | 973 | //
// XL_Day01_SWTests.swift
// XL-Day01-SWTests
//
// Created by jyz on 2017/10/15.
// Copyright © 2017年 HDGS. All rights reserved.
//
import XCTest
@testable import XL_Day01_SW
class XL_Day01_SWTests: 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.297297 | 111 | 0.633094 |
7291ce209b69fc467de51308d6290b152edf95c5 | 507 | //
// Header.swift
// YouSign
//
// Created by Mahmoud Ben Messaoud on 31/05/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import Foundation
class Headers: Node {
public var content = [String: String]()
var name: String {
return XMLRequestKeys.header.rawValue
}
var attributes: [String : String]? {
return nil
}
var values: [String: String]? {
return content
}
var childs: [Node]? {
return nil
}
}
| 16.354839 | 63 | 0.591716 |
0ed6cb57ad169ef05bbd41f3e7a865545547a49b | 1,436 | //===----------------------------------------------------------------------===//
//
// This source file is part of the KafkaNIO open source project
//
// Copyright © 2020 Thomas Bartelmess.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIO
@testable import KafkaNIO
class OffsetCommitTests: XCTestCase {
func testParsingVersion3() throws {
var buffer = try ByteBuffer.from(fixture: "commit-offsets-v3-response")
let header = try KafkaResponseHeader.read(from: &buffer, correlationID: 1, version: APIKey.offsetCommit.responseHeaderVersion(for: 3))
let response = try OffsetCommitResponse(from: &buffer, responseHeader: header, apiVersion: 3)
XCTAssertEqual(response.throttleTimeMs, 0)
XCTAssertEqual(response.topics.count, 1)
guard let topic = response.topics.first else {
XCTFail("Expected one topic")
return
}
XCTAssertEqual(topic.name, "test-topic-2")
XCTAssertEqual(topic.partitions.count, 1)
guard let partition = topic.partitions.first else {
XCTFail("Expected one partition")
return
}
XCTAssertEqual(partition.errorCode, .noError)
XCTAssertEqual(partition.partitionIndex, 0)
}
}
| 33.395349 | 142 | 0.60585 |
fb45c256ac5602afc878f6a63590b4cbbc29c8ab | 1,408 |
//
// MatchViewController.swift
// FIDToolKit
//
// Created by Fidetro on 2017/1/24.
// Copyright © 2017年 Fidetro. All rights reserved.
//
import UIKit
class MatchViewController: BaseViewController {
var selectImage = UIImage();
var timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: DispatchQueue.global());
override func viewDidLoad() {
super.viewDidLoad()
self.timer.resume();
weak var weakSelf = self;
self.createActionSheet { (imagePath) in
self.selectImage = UIImage(contentsOfFile: imagePath!)!;
let cameraView = FIDCameraHelper.setCameraWithBounds(self.view.bounds);
self.view.addSubview(cameraView!);
FIDCameraHelper.startRunning();
weakSelf?.timer.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.seconds(2));
weakSelf?.timer.setEventHandler(handler: {
let han = GreyImageMatch.getSuitabilityWithImageA(self.selectImage, imageB: FIDCameraHelper.cameraImage());
print("\(han)");
});
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 24.275862 | 125 | 0.575284 |
755f8dc52847e59e36176c897412a438fcac45c8 | 2,796 | //
// InterfaceController.swift
// ynabWatchOS Extension
//
// Created by Jacob Pyke on 09.04.19.
// Copyright © 2019 pykeeco. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet weak var slider: WKInterfaceSlider!
@IBOutlet weak var valueLabel: WKInterfaceLabel!
var totalValue: Double = 0.0
var lastSliderValue: Float = 0.0
@IBAction func sliderAdjusted(_ value: Float) {
if lastSliderValue < value {
totalValue += Double(value)
} else {
totalValue -= Double(value)
}
lastSliderValue = value
setLabelValue()
}
@IBAction func foodPressed() {
}
var crownAccumulator = 0.0
override func awake(withContext context: Any?) {
super.awake(withContext: context)
crownSequencer.delegate = self as WKCrownDelegate
// Configure interface objects here.
}
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
crownAccumulator += rotationalDelta
print(rotationalDelta)
if rotationalDelta > 0.1 && rotationalDelta < 1 {
totalValue += 10
setSliderValue()
setLabelValue()
crownAccumulator = 0.0
} else if rotationalDelta > 1 && rotationalDelta < 10 {
totalValue += 100
setSliderValue()
setLabelValue()
crownAccumulator = 0.0
} else if rotationalDelta > 10 {
totalValue += 1000
setLabelValue()
crownAccumulator = 0.0
} else if rotationalDelta < -0.1 && rotationalDelta > -1 {
totalValue -= 10
setSliderValue()
setLabelValue()
crownAccumulator = 0.0
} else if rotationalDelta < -1 && rotationalDelta > -10 {
totalValue -= 100
setSliderValue()
setLabelValue()
crownAccumulator = 0.0
} else if rotationalDelta < -10 {
totalValue -= 1000
setSliderValue()
setLabelValue()
crownAccumulator = 0.0
}
}
func setSliderValue() {
slider.setValue(Float(totalValue))
}
func setLabelValue() {
valueLabel.setText("€" + String(totalValue / 1000))
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
crownSequencer.focus()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
extension InterfaceController: WKCrownDelegate {
}
| 28.824742 | 90 | 0.590129 |
e8188a367bc7f616db6cdebc968d8f1715243aaa | 1,667 | //
// SlideContainerController.swift
// SlideController
//
// Created by Evgeny Dedovets on 4/24/17.
// Copyright © 2017 Touchlane LLC. All rights reserved.
//
import UIKit
///SlideContainerController do control for specific container view
final class SlideContainerController {
private var internalView = UIView()
private var isViewLoaded = false
///Property to indicate if target view mounted to container
var hasContent: Bool {
return isViewLoaded
}
///Implements lazy load, add target view as subview to container view when needed and set hasContent = true
func load(view: UIView) {
guard !isViewLoaded else {
return
}
isViewLoaded = true
view.translatesAutoresizingMaskIntoConstraints = false
internalView.addSubview(view)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: internalView.topAnchor),
view.leadingAnchor.constraint(equalTo: internalView.leadingAnchor),
view.bottomAnchor.constraint(equalTo: internalView.bottomAnchor),
view.trailingAnchor.constraint(equalTo: internalView.trailingAnchor)
])
}
///Removes view from container and sets hasContent = false
func unloadView() {
guard isViewLoaded else {
return
}
isViewLoaded = false
internalView.subviews.forEach({ $0.removeFromSuperview() })
}
}
///Viewable protocol implementation
private typealias ViewableImplementation = SlideContainerController
extension ViewableImplementation: Viewable {
var view: UIView {
return internalView
}
}
| 30.87037 | 111 | 0.686863 |
fec1831839c6c8ef66ff8f91934d43eddf393edf | 6,639 | //
// NewWalletSortCell.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 4/23/19.
// Copyright © 2019 Waves Platform. All rights reserved.
//
import UIKit
import RxSwift
import DomainLayer
import Extensions
fileprivate enum Constants {
static let height: CGFloat = 56
static let delaySwitch: TimeInterval = 0.2
static let animationDuration: TimeInterval = 0.3
static let movedRowAlpha: CGFloat = 0.9
}
final class WalletSortCell: UITableViewCell, NibReusable {
@IBOutlet private weak var buttonFav: UIButton!
@IBOutlet private weak var imageIcon: UIImageView!
@IBOutlet private weak var labelTitle: UILabel!
@IBOutlet private weak var switchControl: UISwitch!
@IBOutlet private weak var viewShadow: UIView!
private var disposeBag = DisposeBag()
private var assetType = AssetType.list
private var isHiddenWhiteContainer = false
private var isMovingAnimation = false
var isBlockedCell = false
var changedValueSwitchControl: (() -> Void)?
var favouriteButtonTapped:(() -> Void)?
var didBlockAllActions:(() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
selectedBackgroundView = UIView()
selectionStyle = .none
backgroundColor = .basic50
contentView.backgroundColor = .basic50
viewShadow.addTableCellShadowStyle()
switchControl.addTarget(self, action: #selector(changedValueSwitchAction), for: .valueChanged)
buttonFav.addTarget(self, action: #selector(favouriteTapped), for: .touchUpInside)
}
override func prepareForReuse() {
super.prepareForReuse()
imageIcon.image = nil
disposeBag = DisposeBag()
}
override func layoutSubviews() {
super.layoutSubviews()
if alpha <= Constants.movedRowAlpha && !isMovingAnimation {
updateBackground()
}
}
@objc private func favouriteTapped() {
if isBlockedCell {
return
}
didBlockAllActions?()
favouriteButtonTapped?()
ImpactFeedbackGenerator.impactOccurred()
if assetType == .favourite {
buttonFav.setImage(Images.iconFavEmpty.image , for: .normal)
}
else {
buttonFav.setImage(Images.favorite14Submit300.image , for: .normal)
}
switchControl.setOn(true, animated: true)
if assetType == .list {
showBackgroundContentWithAnimation(isVisible: false)
}
else if assetType == .favourite {
showBackgroundContentWithAnimation(isVisible: true)
}
}
@objc private func changedValueSwitchAction() {
if isBlockedCell {
return
}
didBlockAllActions?()
DispatchQueue.main.asyncAfter(deadline: .now() + Constants.delaySwitch) {
self.changedValueSwitchControl?()
self.buttonFav.setImage(Images.iconFavEmpty.image , for: .normal)
if self.assetType == .hidden {
self.showBackgroundContentWithAnimation(isVisible: true)
}
else if self.assetType == .list {
self.showBackgroundContentWithAnimation(isVisible: false)
}
}
}
func showAnimationToFavoriteState() {
isMovingAnimation = true
buttonFav.setImage(Images.favorite14Submit300.image , for: .normal)
showBackgroundContentWithAnimation(isVisible: false)
}
func showAnimationToHiddenState() {
isMovingAnimation = true
buttonFav.setImage(Images.iconFavEmpty.image , for: .normal)
showBackgroundContentWithAnimation(isVisible: false)
}
func showAnimationToListState() {
isMovingAnimation = true
buttonFav.setImage(Images.iconFavEmpty.image , for: .normal)
showBackgroundContentWithAnimation(isVisible: true)
}
}
extension WalletSortCell: ViewHeight {
static func viewHeight() -> CGFloat {
return Constants.height
}
}
private extension WalletSortCell {
func updateBackground() {
if assetType == .favourite || assetType == .hidden {
viewShadow.alpha = 0
isHiddenWhiteContainer = true
} else {
viewShadow.alpha = 1
viewShadow.backgroundColor = .white
viewShadow.addTableCellShadowStyle()
isHiddenWhiteContainer = false
}
}
func showBackgroundContentWithAnimation(isVisible: Bool) {
if isVisible {
if !isHiddenWhiteContainer {
return
}
isHiddenWhiteContainer = false
viewShadow.backgroundColor = .white
viewShadow.addTableCellShadowStyle()
UIView.animate(withDuration: Constants.animationDuration) {
self.viewShadow.alpha = 1
}
}
else {
if isHiddenWhiteContainer {
return
}
isHiddenWhiteContainer = true
UIView.animate(withDuration: Constants.animationDuration) {
self.viewShadow.alpha = 0
}
}
}
}
// MARK: ViewConfiguration
extension WalletSortCell: ViewConfiguration {
enum AssetType {
case favourite
case list
case hidden
}
struct Model {
let name: String
let isMyWavesToken: Bool
let isVisibility: Bool
let isHidden: Bool
let isFavorite: Bool
let isGateway: Bool
let icon: AssetLogo.Icon
let isSponsored: Bool
let hasScript: Bool
let type: AssetType
}
func update(with model: Model) {
isMovingAnimation = false
let image = model.isFavorite ? Images.favorite14Submit300.image : Images.iconFavEmpty.image
buttonFav.setImage(image , for: .normal)
labelTitle.attributedText = NSAttributedString.styleForMyAssetName(assetName: model.name,
isMyAsset: model.isMyWavesToken)
switchControl.isHidden = !model.isVisibility
switchControl.isOn = !model.isHidden
assetType = model.type
isBlockedCell = false
updateBackground()
AssetLogo.logo(icon: model.icon,
style: .medium)
.observeOn(MainScheduler.instance)
.bind(to: imageIcon.rx.image)
.disposed(by: disposeBag)
}
}
| 29.246696 | 107 | 0.60732 |
5641341307d26de52581e7f6b0297d2ca5672dfa | 9,716 | /*
© Copyright 2020, Little Green Viper Software Development LLC
LICENSE:
MIT License
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.
Little Green Viper Software Development LLC: https://littlegreenviper.com
*/
import Cocoa
import ITCB_SDK_Mac
/* ###################################################################################################################################### */
// MARK: - The View Controller for a Peripheral Mode app -
/* ###################################################################################################################################### */
/**
This view controller is loaded over the mode selection, as we have decided to be a Peripheral.
*/
class ITCB_Peripheral_ViewController: ITCB_Base_ViewController {
/// The stroryboard ID, for instantiating the class.
static let storyboardID = "peripheral-initial-view-controller"
/* ################################################################## */
/**
This is here to satisfy the SDK Peripheral Observer requirement.
*/
var uuid: UUID = UUID()
/* ################################################################## */
/**
This is a semaphore that prevents questions from "piling up." If a question has not yet been answered, this is true.
*/
var workingWithQuestion: Bool = false
/* ################################################################## */
/**
This displays the question from the Central.
*/
@IBOutlet weak var questionAskedLabel: NSTextField!
/* ################################################################## */
/**
If the user hits this button, a random answer will be selected and sent.
*/
@IBOutlet weak var sendRandomButton: NSButton!
/* ################################################################## */
/**
This is the container scroll view for the table.
*/
@IBOutlet weak var containerScrollView: NSScrollView!
/* ################################################################## */
/**
The question picker table view.
*/
@IBOutlet var tableView: NSTableView!
/* ################################################################## */
/**
This displays a "waiting for question" screen.
*/
@IBOutlet weak var busyView: NSView!
/* ################################################################## */
/**
This is the "waiting" label.
*/
@IBOutlet weak var waitingLabel: NSTextField!
/* ################################################################## */
/**
This is an activity spinner.
*/
@IBOutlet weak var waitingActivityIndicator: NSProgressIndicator!
}
/* ###################################################################################################################################### */
// MARK: - IBAction Methods -
/* ###################################################################################################################################### */
extension ITCB_Peripheral_ViewController {
/* ################################################################## */
/**
Called when the user clicks the "Send Random" button.
- parameter inButton: The button instance.
*/
@IBAction func sendRandomButtonHit(_ inButton: NSButton) {
let answer = String(format: "SLUG-ANSWER-%02d", Int.random(in: 0..<20)).localizedVariant
getDeviceSDKInstanceAsPeripheral?.central.sendAnswer(answer, toQuestion: questionAskedLabel?.stringValue ?? "ERROR")
setUI(showItems: false)
}
}
/* ###################################################################################################################################### */
// MARK: - Instance Methods -
/* ###################################################################################################################################### */
extension ITCB_Peripheral_ViewController {
/* ################################################################## */
/**
Called to display the question.
- parameter inQuestionString: The question.
*/
func displayQuestion(_ inQuestion: String) {
self.questionAskedLabel?.stringValue = inQuestion.localizedVariant
setUI(showItems: true)
}
/* ################################################################## */
/**
This either shows or hides the "waiting" screen, or the answer handlers.
- parameter inShowItems: True, if we want to show the items. False, if we want to show the "waiting" screen.
*/
func setUI(showItems inShowItems: Bool) {
busyView?.isHidden = inShowItems
questionAskedLabel?.isHidden = !inShowItems
sendRandomButton?.isHidden = !inShowItems
containerScrollView?.isHidden = !inShowItems
}
}
/* ###################################################################################################################################### */
// MARK: - Base Class Override Methods -
/* ###################################################################################################################################### */
extension ITCB_Peripheral_ViewController {
/* ################################################################## */
/**
Called when the view has completed loading.
*/
override func viewDidLoad() {
super.viewDidLoad()
deviceSDKInstance = ITCB_SDK.createInstance(isCentral: false)
sendRandomButton?.title = sendRandomButton?.title.localizedVariant ?? "ERROR"
waitingLabel?.stringValue = waitingLabel.stringValue.localizedVariant
waitingActivityIndicator?.startAnimation(nil)
setUI(showItems: false)
}
/* ################################################################## */
/**
Called just before the view appears. We use this to register as an observer.
*/
override func viewWillAppear() {
super.viewWillAppear()
getDeviceSDKInstanceAsPeripheral?.addObserver(self)
}
/* ################################################################## */
/**
Called just before the view disappears. We use this to un-register as an observer.
*/
override func viewWillDisappear() {
super.viewWillDisappear()
getDeviceSDKInstanceAsPeripheral?.removeObserver(self)
}
}
/* ################################################################################################################################## */
// MARK: - NSTableViewDelegate/DataSource Methods
/* ################################################################################################################################## */
extension ITCB_Peripheral_ViewController: NSTableViewDelegate, NSTableViewDataSource {
/* ################################################################## */
/**
Called to supply the number of rows in the table.
- parameters:
- inTableView: The table instance.
- returns: A 1-based Int, with 0 being no rows.
*/
func numberOfRows(in inTableView: NSTableView) -> Int {
return Int("SLUG-NUMBER-MAX".localizedVariant) ?? 0
}
/* ################################################################## */
/**
This is called to supply the string display for one row that corresponds to a device.
- parameters:
- inTableView: The table instance.
- objectValueFor: Container object for the column that holds the row.
- row: 0-based Int, with the index of the row, within the column.
- returns: A String, with the device name.
*/
func tableView(_ inTableView: NSTableView, objectValueFor inTableColumn: NSTableColumn?, row inRow: Int) -> Any? {
return String(format: "SLUG-ANSWER-%02d", inRow).localizedVariant
}
/* ################################################################## */
/**
Called after a table row was selected by the user.
We open a modal sheet, with the device info.
- parameter: Ignored
*/
func tableViewSelectionDidChange(_: Notification) {
// Make sure that we have a selected row, and that the selection is valid.
if let selectedRow = tableView?.selectedRow,
(0..<tableView.numberOfRows).contains(selectedRow) {
let answer = String(format: "SLUG-ANSWER-%02d", selectedRow).localizedVariant
getDeviceSDKInstanceAsPeripheral?.central.sendAnswer(answer, toQuestion: questionAskedLabel?.stringValue ?? "ERROR")
setUI(showItems: false)
tableView.deselectRow(selectedRow) // Make sure that we clean up after ourselves.
}
}
}
| 43.375 | 140 | 0.491869 |
8768f49d0bedd45b395d05200586f44caae0ffb2 | 1,355 | //
// AppDelegate.swift
// DiscourseApp
//
// Created by Rodrigo Candido on 14/12/20.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// 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.
}
}
| 36.621622 | 179 | 0.746863 |
f4013e26c9b53d0d6bd3f863e76e8f4357bac300 | 25,431 | //
// AnnotationHandler.swift
// Swift Reuse Code
//
// Created by Oliver Klemenz on 25.07.14.
//
//
import AVFoundation
import AVKit
import CoreMedia
import MobileCoreServices
import UIKit
protocol AnnotationDataSource: class {
func dictionaryEntity() -> NSObject?
func dictionaryAggregation() -> String?
func numberOfAnnotation() -> Int
func numberOfAnnotationGroup() -> Int
func numberOfAnnotation(byGroup group: Int) -> Int
func numberOfAnnotation(byGroupName groupName: String?) -> Int
func annotationGroupName(_ group: Int) -> String?
func annotationGroupIndex(byUUID uuid: String?) -> IndexPath?
func annotation(byGroup group: Int, index: Int) -> Annotation?
func annotation(byUUID uuid: String?) -> Annotation?
func addAnnotation(_ parameters: [AnyHashable : Any]?) -> Annotation?
func insert(_ annotation: Annotation?)
func update(_ annotation: Annotation?, parameters: [AnyHashable : Any]?)
func removeAnnotation(byUUID uuid: String?)
func remove(_ annotation: Annotation?)
func sortAnnotation()
}
protocol AnnotationHandlerDelegate: NSObjectProtocol {
func didAddAnnotation(_ data: Data?, thumbnail: Data?, length: CGFloat, sender: Any?)
func didUpdateAnnotation(_ data: Data?, thumbnail: Data?, length: CGFloat, sender: Any?)
func didFinish()
}
class AnnotationHandler: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate, AVAudioPlayerDelegate, TextAnnotationViewControllerDelegate, PhotoAnnotationViewControllerDelegate, ImageAnnotationViewControllerDelegate {
private(set) var annotationType: Int = 0
weak var presenter: UIViewController?
weak var delegate: AnnotationHandlerDelegate?
weak var dataSource: (NSObject & AnnotationDataSource)?
weak var imageDataSource: (NSObject & ImageAnnotationDataSource)?
var editing = false
convenience init(annotationType type: Int, presenter: UIViewController?) {
self.init()
annotationType = type
self.presenter = presenter
}
func create(_ crop: Bool) {
var viewController: UIViewController?
if annotationType == 0 {
viewController = writeText()
} else if annotationType == 1 {
viewController = takePhoto(crop)
} else if annotationType == 2 {
viewController = drawImage()
} else if annotationType == 3 {
viewController = recordAudio()
} else if annotationType == 4 {
viewController = recordVideo()
}
show(viewController, annotation: nil, presenter: presenter)
}
func choose(_ crop: Bool) {
var viewController: UIViewController?
if annotationType == 0 {
return
} else if annotationType == 1 {
viewController = choosePhoto(crop)
} else if annotationType == 2 {
return
} else if annotationType == 3 {
return
} else if annotationType == 4 {
viewController = chooseVideo()
}
show(viewController, annotation: nil, presenter: presenter)
}
func display(_ annotation: Annotation?) {
var viewController: UIViewController?
if annotationType == 0 {
viewController = displayText(annotation?.text())
} else if annotationType == 1 {
viewController = display(annotation?.image())
} else if annotationType == 2 {
viewController = display(annotation?.image())
} else if annotationType == 3 {
viewController = playAudio(annotation?.data())
} else if annotationType == 4 {
viewController = playVideo(annotation?.data())
}
show(viewController, annotation: annotation, presenter: presenter)
}
func present(_ annotation: Annotation?, presenter: UIViewController?) -> UIViewController? {
var viewController: UIViewController?
if annotation?.type == 0 {
viewController = displayText(annotation?.text())?.embedInNavigationController()
} else if annotation?.type == 1 {
viewController = display(annotation?.image())?.embedInNavigationController()
} else if annotation?.type == 2 {
viewController = display(annotation?.image())?.embedInNavigationController()
} else if annotation?.type == 3 {
viewController = playAudio(annotation?.data())
} else if annotation?.type == 4 {
viewController = playVideo(annotation?.data())
}
if viewController != nil {
show(viewController, annotation: annotation, presenter: presenter)
}
return viewController
}
private var imagePicker: UIImagePickerController?
private var videoPicker: UIImagePickerController?
private var alert: UIAlertController?
private var startTime: Date?
private var timer: Timer?
private var audioPlayer: AVAudioPlayer?
private var audioRecorder: AVAudioRecorder?
private var filePath = ""
var navigationController: UINavigationController? {
return presenter?.navigationController
}
func show(_ viewController: UIViewController?, annotation: Annotation?, presenter: UIViewController?) {
if viewController != nil {
if annotation != nil {
var annotationViewController: UIViewController? = viewController
if (viewController is UINavigationController) {
annotationViewController = (viewController as? UINavigationController)?.topViewController
annotationViewController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Close".localized, style: .plain, target: presenter, action: nil)
annotationViewController?.navigationItem.rightBarButtonItems = nil
}
if (annotation?.subTitle()?.count ?? 0) > 0 {
let title = "\(annotation?.title() ?? "")\n\(annotation?.subTitle() ?? "")"
let label = UILabel.createTwoLineTitleLabel(title, color: UIColor.black)
annotationViewController?.navigationItem.titleView = label
} else {
annotationViewController?.title = annotation?.title()
}
}
if (viewController is UINavigationController) || (viewController is UIImagePickerController) || (viewController is UIAlertController) || presenter?.navigationController == nil {
if presenter?.navigationController != nil {
} else {
}
} else if (viewController is AVPlayerViewController) {
((viewController as? AVPlayerViewController)?.player)?.play()
} else {
if let viewController = viewController {
presenter?.navigationController?.pushViewController(viewController, animated: true)
}
}
}
}
func writeText() -> TextAnnotationViewController? {
let textAnnotation = TextAnnotationViewController()
textAnnotation.delegate = self
textAnnotation.isEditing = true
textAnnotation.dataSource = dataSource
return textAnnotation
}
func displayText(_ text: String?) -> TextAnnotationViewController? {
let textAnnotation = TextAnnotationViewController(text: text ?? "")
textAnnotation.delegate = self
textAnnotation.isEditing = editing
textAnnotation.dataSource = dataSource
textAnnotation.title = "View Text".localized
return textAnnotation
}
func didFinishWritingText(_ text: String?, updated: Bool) {
let data: Data? = text?.data(using: .utf8)
if !updated {
delegate?.didAddAnnotation(data, thumbnail: nil, length: CGFloat((text?.count ?? 0)), sender: self)
} else {
delegate?.didUpdateAnnotation(data, thumbnail: nil, length: CGFloat((text?.count ?? 0)), sender: self)
}
navigationController?.popViewController(animated: true)
delegate?.didFinish()
}
func takePhoto(_ crop: Bool) -> UIImagePickerController? {
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
imagePicker?.sourceType = .camera
imagePicker?.mediaTypes = [kUTTypeImage as String]
imagePicker?.allowsEditing = crop
return imagePicker
}
func choosePhoto(_ crop: Bool) -> UIImagePickerController? {
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
imagePicker?.sourceType = .photoLibrary
imagePicker?.mediaTypes = [kUTTypeImage as String]
imagePicker?.allowsEditing = crop
return imagePicker
}
func recordAudio() -> UIAlertController? {
alert = Common.showConfirmation(nil, title: "Record Audio".localized, message: "Tap record to start".localized, okButtonTitle: "Record".localized, destructive: false, cancelButtonTitle: nil, okHandler: {
self.alert = Common.showMessage(self.presenter, title: "Recording...".localized, message: Utilities.formatSeconds(0), okButtonTitle: "Stop".localized, okHandler: {
let length: Int = self.stopRecording()
let data = NSData(contentsOfFile: self.filePath) as Data?
self.delegate?.didAddAnnotation(data, thumbnail: nil, length: CGFloat(length), sender: self)
self.timer?.invalidate()
self.timer = nil
self.startTime = nil
self.alert = nil
})
self.filePath = URL(fileURLWithPath: "folder").appendingPathComponent("audio.aac").absoluteString
_ = self.startRecording(kAudioFormatMPEG4AAC, filePath: self.filePath)
self.startTime = Date()
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(AnnotationHandler.updateTime), userInfo: nil, repeats: true)
}, cancelHandler: {
self.alert = nil
})
return alert
}
@objc func updateTime() {
var seconds: Int? = nil
if let startTime = startTime {
seconds = Int(Date().timeIntervalSince(startTime))
}
alert?.message = Utilities.formatSeconds(seconds ?? 0)
}
func startRecording(_ format: AudioFormatID, filePath: String?) -> Bool {
audioRecorder = nil
let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setCategory(AVAudioSession.Category.record)
var recordSettings: [AnyHashable : Any]
if format == kAudioFormatLinearPCM {
recordSettings = [
AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM),
AVNumberOfChannelsKey: NSNumber(value: 2),
AVSampleRateKey: NSNumber(value: 44100),
AVLinearPCMBitDepthKey: NSNumber(value: 16),
AVLinearPCMIsBigEndianKey: NSNumber(value: false),
AVLinearPCMIsFloatKey: NSNumber(value: false)
]
} else {
recordSettings = [
AVEncoderAudioQualityKey: NSNumber(value: AVAudioQuality.medium.rawValue),
AVFormatIDKey: NSNumber(value: format),
AVEncoderBitRateKey: NSNumber(value: 128000),
AVNumberOfChannelsKey: NSNumber(value: 2),
AVSampleRateKey: NSNumber(value: 44100),
AVLinearPCMBitDepthKey: NSNumber(value: 16)
]
}
let url = URL(fileURLWithPath: filePath ?? "")
if let recordSettings = recordSettings as? [String : Any] {
audioRecorder = try? AVAudioRecorder(url: url, settings: recordSettings)
}
if audioRecorder?.prepareToRecord() ?? false {
audioRecorder?.record()
return true
}
return false
}
func stopRecording() -> Int {
let length: Int = lroundf(Float(audioRecorder?.currentTime ?? 0.0))
audioRecorder?.stop()
return length
}
func playAudio(_ data: Data?) -> UIAlertController? {
let url: URL? = URL(fileURLWithPath: "audio.aac")
alert = Common.showMessage(nil, title: "Playing...".localized, message: Utilities.formatSeconds(0), okButtonTitle: "Stop".localized, okHandler: {
self.stopPlaying()
self.playingStopped()
self.alert = nil
})
startTime = Date()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(AnnotationHandler.updateTime), userInfo: nil, repeats: true)
let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setCategory(AVAudioSession.Category.playback)
if let url = url {
audioPlayer = try? AVAudioPlayer(contentsOf: url)
}
audioPlayer?.delegate = self
audioPlayer?.numberOfLoops = 0
audioPlayer?.play()
return alert
}
func stopPlaying() {
audioPlayer?.stop()
}
func playingStopped() {
timer?.invalidate()
timer = nil
startTime = nil
alert = nil
delegate?.didFinish()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
playingStopped()
}
func drawImage() -> ImageAnnotationViewController? {
let imageAnnotation = ImageAnnotationViewController()
imageAnnotation.delegate = self
imageAnnotation.dataSource = imageDataSource
return imageAnnotation
}
func didFinishDrawing(_ image: UIImage?, updated: Bool) {
let data = image?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
let thumbnailImage: UIImage? = image?.scaledImage(CGFloat(kAnnotationThumbnailSize))
let thumbnailData = thumbnailImage?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
delegate?.didAddAnnotation(data, thumbnail: thumbnailData, length: CGFloat((data?.count ?? 0)), sender: self)
navigationController?.popViewController(animated: true)
delegate?.didFinish()
}
func display(_ image: UIImage?) -> PhotoAnnotationViewController? {
var photoAnnotation: PhotoAnnotationViewController? = nil
if let image = image {
photoAnnotation = PhotoAnnotationViewController(image: image)
}
photoAnnotation?.delegate = self
photoAnnotation?.dataSource = imageDataSource
photoAnnotation?.isEditing = editing
photoAnnotation?.title = "View Picture".localized
return photoAnnotation
}
func didFinishEdit(_ image: UIImage?) {
let data = image?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
let thumbnailImage: UIImage? = image?.scaledImage(CGFloat(kAnnotationThumbnailSize))
let thumbnailData = thumbnailImage?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
delegate?.didUpdateAnnotation(data, thumbnail: thumbnailData, length: CGFloat((data?.count ?? 0)), sender: self)
navigationController?.popViewController(animated: true)
delegate?.didFinish()
}
func recordVideo() -> UIImagePickerController? {
videoPicker = UIImagePickerController()
videoPicker?.delegate = self
videoPicker?.sourceType = .camera
videoPicker?.mediaTypes = [kUTTypeMovie as String]
videoPicker?.allowsEditing = true
videoPicker?.videoQuality = .typeMedium
videoPicker?.videoMaximumDuration = 30.0
return videoPicker
}
func chooseVideo() -> UIImagePickerController? {
videoPicker = UIImagePickerController()
videoPicker?.delegate = self
videoPicker?.sourceType = .photoLibrary
videoPicker?.mediaTypes = [kUTTypeMovie as String]
videoPicker?.allowsEditing = true
return videoPicker
}
func playVideo(_ data: Data?) -> AVPlayerViewController? {
let url: URL? = URL(fileURLWithPath: "video.mp4")
var player: AVPlayer? = nil
if let url = url {
player = AVPlayer(url: url)
}
let playerViewController = VideoAnnotationViewController()
playerViewController.player = player
return playerViewController
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if picker == imagePicker {
var image: UIImage?
if picker.allowsEditing {
image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
} else {
image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
let thumbnailImage: UIImage? = image?.scaledImage(CGFloat(kAnnotationThumbnailSize))
let data = image?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
let thumbnailData = thumbnailImage?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
delegate?.didAddAnnotation(data, thumbnail: thumbnailData, length: CGFloat((data?.count ?? 0)), sender: self)
delegate?.didFinish()
} else if picker == videoPicker {
let url = info[.mediaURL] as? URL
var movie: AVAsset? = nil
if let url = url {
movie = AVAsset(url: url)
}
let movieDuration: CMTime? = movie?.duration
let length: Int = Int(round(Float(movieDuration?.value ?? 0) / Float((movieDuration?.timescale ?? 0))))
var data: Data? = nil
if let url = url {
data = try? Data(contentsOf: url)
}
var asset: AVURLAsset? = nil
if let url = url {
asset = AVURLAsset(url: url, options: nil)
}
var generate1: AVAssetImageGenerator? = nil
if let asset = asset {
generate1 = AVAssetImageGenerator(asset: asset)
}
generate1?.appliesPreferredTrackTransform = true
let time: CMTime = CMTimeMake(value: 1, timescale: 2)
let thumbnailRef = try? generate1?.copyCGImage(at: time, actualTime: nil)
var thumbnailImage: UIImage? = nil
if let thumbnailRef = thumbnailRef {
thumbnailImage = UIImage(cgImage: thumbnailRef)
}
let thumbnailData = thumbnailImage?.jpegData(compressionQuality: CGFloat(kAnnotationJPGImageQuality))
delegate?.didAddAnnotation(data, thumbnail: thumbnailData, length: CGFloat(length), sender: self)
delegate?.didFinish()
}
}
func convertVideoToLowQuailty(withInputURL inputURL: URL?, outputURL: URL?) {
var videoAsset: AVAsset? = nil
if let inputURL = inputURL {
videoAsset = AVURLAsset(url: inputURL, options: nil)
}
let videoTrack: AVAssetTrack? = videoAsset?.tracks(withMediaType: .video)[0]
let videoSize: CGSize? = videoTrack?.naturalSize
let videoWriterCompressionSettings = [
AVVideoAverageBitRateKey : NSNumber(value: 1250000)
]
let videoWriterSettings:[String: Any] = [
AVVideoCodecKey : AVVideoCodecType.h264,
AVVideoCompressionPropertiesKey : videoWriterCompressionSettings,
AVVideoWidthKey : NSNumber(value: Float(videoSize?.width ?? 0.0)),
AVVideoHeightKey : NSNumber(value: Float(videoSize?.height ?? 0.0))
]
let videoWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoWriterSettings)
videoWriterInput.expectsMediaDataInRealTime = true
if let preferredTransform = videoTrack?.preferredTransform {
videoWriterInput.transform = preferredTransform
}
var videoWriter: AVAssetWriter? = nil
if let outputURL = outputURL {
videoWriter = try? AVAssetWriter(outputURL: outputURL, fileType: .mov)
}
videoWriter?.add(videoWriterInput)
let videoReaderSettings = [kCVPixelBufferPixelFormatTypeKey : NSNumber(value: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
var videoReaderOutput: AVAssetReaderTrackOutput? = nil
if let videoTrack = videoTrack {
videoReaderOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings as [String : Any])
}
var videoReader: AVAssetReader? = nil
if let videoAsset = videoAsset {
videoReader = try? AVAssetReader(asset: videoAsset)
}
if let videoReaderOutput = videoReaderOutput {
videoReader?.add(videoReaderOutput)
}
let audioWriterInput = AVAssetWriterInput(mediaType: .audio, outputSettings: nil)
audioWriterInput.expectsMediaDataInRealTime = false
videoWriter?.add(audioWriterInput)
let audioTrack: AVAssetTrack? = videoAsset?.tracks(withMediaType: .audio)[0]
var audioReaderOutput: AVAssetReaderOutput? = nil
if let audioTrack = audioTrack {
audioReaderOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: nil)
}
var audioReader: AVAssetReader? = nil
if let videoAsset = videoAsset {
audioReader = try? AVAssetReader(asset: videoAsset)
}
if let audioReaderOutput = audioReaderOutput {
audioReader?.add(audioReaderOutput)
}
videoWriter?.startWriting()
videoReader?.startReading()
videoWriter?.startSession(atSourceTime: .zero)
let processingQueue = DispatchQueue(label: "processingQueue1")
videoWriterInput.requestMediaDataWhenReady(on: processingQueue, using: {
while videoWriterInput.isReadyForMoreMediaData {
let sampleBuffer: CMSampleBuffer? = videoReaderOutput?.copyNextSampleBuffer()
if videoReader?.status == .reading && sampleBuffer != nil {
if let sampleBuffer = sampleBuffer {
videoWriterInput.append(sampleBuffer)
}
} else {
videoWriterInput.markAsFinished()
if videoReader?.status == .completed {
audioReader?.startReading()
videoWriter?.startSession(atSourceTime: .zero)
let processingQueue = DispatchQueue(label: "processingQueue2")
audioWriterInput.requestMediaDataWhenReady(on: processingQueue, using: {
while audioWriterInput.isReadyForMoreMediaData {
let sampleBuffer: CMSampleBuffer? = audioReaderOutput?.copyNextSampleBuffer()
if audioReader?.status == .reading && sampleBuffer != nil {
if let sampleBuffer = sampleBuffer {
audioWriterInput.append(sampleBuffer)
}
} else {
audioWriterInput.markAsFinished()
if audioReader?.status == .completed {
videoWriter?.finishWriting(completionHandler: {
DispatchQueue.main.async(execute: {
self.videoCompressionDone(outputURL)
})
})
} else if audioReader?.status == .failed || audioReader?.status == .cancelled {
DispatchQueue.main.async(execute: {
self.videoCompressionFailed()
})
}
}
}
})
} else if videoReader?.status == .failed || videoReader?.status == .cancelled {
DispatchQueue.main.async(execute: {
self.videoCompressionFailed()
})
}
}
}
})
navigationController?.popViewController(animated: true)
delegate?.didFinish()
}
func videoCompressionDone(_ videoURL: URL?) {
var data: Data? = nil
if let videoURL = videoURL {
data = try? Data(contentsOf: videoURL)
}
let fileManager = FileManager.default
try? fileManager.removeItem(atPath: videoURL?.path ?? "")
delegate?.didAddAnnotation(data, thumbnail: nil, length: CGFloat((data?.count ?? 0)), sender: self)
navigationController?.popViewController(animated: true)
delegate?.didFinish()
}
func videoCompressionFailed() {
navigationController?.popViewController(animated: true)
delegate?.didFinish()
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
}
}
let kAnnotationThumbnailSize = 100.0
let kAnnotationJPGImageQuality = 0.5
| 44.851852 | 239 | 0.626008 |
5b278d87b8504714b1b893511df0059180c7dfc5 | 1,748 | //
// Beer.swift
// BreweryTests
//
// Created by Alvaro Blazquez on 18/10/18.
// Copyright © 2018 Alvaro Blazquez. All rights reserved.
//
import XCTest
import SwiftyJSON
@testable import Brewery
class BeerTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
func testJSON() {
let string = "{\"id\": \"1\",\"name\": \"Beer\",\"description\": \"descripcion\",\"isOrganic\": \"Y\"," +
"\"abv\": \"10\",\"ibu\": \"2\", \"labels\": {\"medium\": \"icon\",\"large\": \"image\"}}"
let json = JSON(parseJSON: string)
let beer = Beer(json: json)
XCTAssertEqual(beer.id, "1")
XCTAssertEqual(beer.name, "Beer")
XCTAssertEqual(beer.description, "descripcion")
XCTAssertEqual(beer.isOrganic, "Y")
XCTAssertEqual(beer.abv, "10")
XCTAssertEqual(beer.ibu, "2")
XCTAssertEqual(beer.icon, "icon")
XCTAssertEqual(beer.image, "image")
}
func testBadJSON() {
let string = "{\"idd\": \"1\",\"namee\": \"Beer\",\"descriptionn\": \"descripcion\",\"isOrganicc\": \"Y\" ," +
"\"abvv\": \"10\",\"ibuu\": \"2\",\"mediumm\": \"icon\",\"largee\": \"image\"}"
let json = JSON(parseJSON: string)
let beer = Beer(json: json)
XCTAssertEqual(beer.id, "")
XCTAssertEqual(beer.name, "")
XCTAssertEqual(beer.description, "")
XCTAssertEqual(beer.isOrganic, "")
XCTAssertEqual(beer.abv, "")
XCTAssertEqual(beer.ibu, "")
XCTAssertEqual(beer.icon, "")
XCTAssertEqual(beer.image, "")
}
}
| 31.781818 | 118 | 0.547483 |
210c9493c803097783c66bc9e0a144808fd9d295 | 377 | //
// MovieListTableViewController+MainTabBarDelegate.swift
// BoxOffice
//
// Created by 강준영 on 13/12/2018.
// Copyright © 2018 강준영. All rights reserved.
//
import Foundation
extension MovieListTableViewController: MainTabBarDelegate {
func titleChange() {
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
}
}
| 20.944444 | 60 | 0.679045 |
ff861b88d06fec5533d172df3a5e4025e25d7535 | 1,068 | //
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2018-2021 Skyscanner 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
import UIKit
extension UIViewController {
var appDelegate: BPKAppDelegate? {
return UIApplication.shared.delegate as? BPKAppDelegate
}
var isUITesting: Bool {
guard let delegate = appDelegate else {
assertionFailure("The apps delegate should be of type `BPKAppDelegate`")
return false
}
return delegate.isUITestingEnabled
}
}
| 28.864865 | 84 | 0.708801 |
e00e6cacf307e6d53c49dfadbeabc90094ef8584 | 425 | //
// File.swift
//
//
// Created by Rob Jonson on 08/11/2021.
//
import Foundation
extension Zaphod {
public var faqURL: URL {
if let url = ZPreference.appInfo?.faqUrl {
return url
}
var urlC = URLComponents(url: Zaphod.serverURL, resolvingAgainstBaseURL: false)!
urlC.path = "/a/na/faqs"
urlC["identifier"]=config.identifier
return urlC.url!
}
}
| 17.708333 | 88 | 0.590588 |
e5346360fb6aa294f5e69157c881de506a3dd3c9 | 2,906 | import Vapor
import Foundation
public class GitlabRouter: FederatedServiceRouter {
public static var baseURL: String = "https://gitlab.com/"
public static var callbackURL: String = "callback"
public let tokens: FederatedServiceTokens
public let callbackCompletion: (Request, String)throws -> (Future<ResponseEncodable>)
public var scope: [String] = []
public let callbackURL: String
public let accessTokenURL: String = "\(GitlabRouter.baseURL.finished(with: "/"))oauth/token"
public func authURL(_ request: Request) throws -> String {
return "\(GitlabRouter.baseURL.finished(with: "/"))oauth/authorize?" +
"client_id=\(self.tokens.clientID)&" +
"redirect_uri=\(GitlabRouter.callbackURL)&" +
"scope=\(scope.joined(separator: "%20"))&" +
"response_type=code"
}
public required init(callback: String, completion: @escaping (Request, String)throws -> (Future<ResponseEncodable>)) throws {
self.tokens = try GitlabAuth()
self.callbackURL = callback
self.callbackCompletion = completion
}
public func fetchToken(from request: Request)throws -> Future<String> {
let code: String
if let queryCode: String = try request.query.get(at: "code") {
code = queryCode
} else if let error: String = try request.query.get(at: "error") {
throw Abort(.badRequest, reason: error)
} else {
throw Abort(.badRequest, reason: "Missing 'code' key in URL query")
}
let body = GitlabCallbackBody(clientId: self.tokens.clientID, clientSecret: self.tokens.clientSecret, code: code, grantType: "authorization_code", redirectUri: GitlabRouter.callbackURL)
return try body.encode(using: request).flatMap(to: Response.self) { request in
guard let url = URL(string: self.accessTokenURL) else {
throw Abort(.internalServerError, reason: "Unable to convert String '\(self.accessTokenURL)' to URL")
}
request.http.method = .POST
request.http.url = url
return try request.make(Client.self).send(request)
}.flatMap(to: String.self) { response in
return response.content.get(String.self, at: ["access_token"])
}
}
public func callback(_ request: Request)throws -> Future<Response> {
return try self.fetchToken(from: request).flatMap(to: ResponseEncodable.self) { accessToken in
let session = try request.session()
session.setAccessToken(accessToken)
try session.set("access_token_service", to: OAuthService.gitlab)
return try self.callbackCompletion(request, accessToken)
}.flatMap(to: Response.self) { response in
return try response.encode(for: request)
}
}
}
| 45.40625 | 193 | 0.638679 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.