text stringlengths 8 1.32M |
|---|
//
// ApiURL.swift
// SSUMAP_iOS
//
// Created by 김태인 on 2017. 7. 6..
// Copyright © 2017년 Personal. All rights reserved.
//
import Foundation
class ApiURL {
static var hostURL = "http://ssumap-service.azurewebsites.net"
static var listURL = "/api/spots"
}
|
*/
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution.
*/
let nums = [2, 11, 7, 15]
let target = 9
func findTheTargetSum(_ arr: [Int], target: Int) -> (Int?,Int?) {
var addend1:Int?
var addend2: Int?
for indexOfNum1 in 0..<arr.count {
for indexOfNum2 in 0..<arr.count {
if arr[indexOfNum1] + arr[indexOfNum2] == target {
addend1 = indexOfNum1
addend2 = indexOfNum2
}
}
}
return (addend1, addend2)
}
findTheTargetSum(nums, target: 9)
func findTheTargetSumAlternate(_ arr: [Int], target: Int) -> (Int?,Int?) {
var addend1:Int?
var addend2: Int?
var diff: Int
var checkerArr = [Int]()
for indexOfNum1 in 0..<arr.count {
if target > arr[indexOfNum1] {
diff = target - arr[indexOfNum1]
} else {
diff = arr[indexOfNum1] - target
}
checkerArr.append(diff)
}
for findingTheMatch in 0..<arr.count {
var counter = 0
if arr[findingTheMatch + counter] + checkerArr[(arr.count - 1) - findingTheMatch] == target {
print(checkerArr[(arr.count - 1) - findingTheMatch])
addend1 = findingTheMatch + counter
addend2 = (arr.count - 1) - findingTheMatch
break
} else {
counter += 1
continue
}
}
return (addend1, addend2)
}
findTheTargetSumAlternate(nums, target: 18)
|
// Copyright © T-Mobile USA Inc. All rights reserved.
import RIBs
protocol SearchDetailRouting: ViewableRouting {
// TODO: Declare methods the interactor can invoke to manage sub-tree via the router.
}
protocol SearchDetailPresentable: Presentable {
var listener: SearchDetailPresentableListener? { get set }
// TODO: Declare methods the interactor can invoke the presenter to present data.
}
protocol SearchDetailListener: AnyObject {
// TODO: Declare methods the interactor can invoke to communicate with other RIBs.
}
final class SearchDetailInteractor: PresentableInteractor<SearchDetailPresentable>, SearchDetailInteractable, SearchDetailPresentableListener {
weak var router: SearchDetailRouting?
weak var listener: SearchDetailListener?
// TODO: Add additional dependencies to constructor. Do not perform any logic
// in constructor.
override init(presenter: SearchDetailPresentable) {
super.init(presenter: presenter)
presenter.listener = self
}
override func didBecomeActive() {
super.didBecomeActive()
// TODO: Implement business logic here.
}
override func willResignActive() {
super.willResignActive()
// TODO: Pause any business logic.
}
}
|
import UIKit
private enum SuffixArrayVCRow: Int {
case creation = 0,
creationWithAlgoNames,
search10Random,
search10RandomWithCondition,
remove1Entry,
remove5Entries,
remove10Entries,
lookup1Entry,
lookup10Entries
}
class SuffixArrayViewController: DataStructuresViewController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.viewModel = SuffixArrayViewModel()
}
override func viewDidLoad() {
super.viewDidLoad()
createAndTestButton.setTitle("Create SuffixArray and Test", for: [])
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let vm = self.viewModel as? SuffixArrayViewModel {
switch (indexPath as NSIndexPath).row {
case SuffixArrayVCRow.creation.rawValue:
cell.textLabel!.text = "Array Creation:"
cell.detailTextLabel!.text = formattedTime(vm.creationTime)
case SuffixArrayVCRow.creationWithAlgoNames.rawValue:
cell.textLabel!.text = "Creation with AlgoProvider:"
cell.detailTextLabel!.text = formattedTime(vm.creationAlgoTime)
case SuffixArrayVCRow.search10Random.rawValue:
cell.textLabel!.text = "Search 10 words:"
cell.detailTextLabel!.text = formattedTime(vm.search10Words)
default:
print("Unhandled row! \((indexPath as NSIndexPath).row)")
}
}
return cell
}
}
|
//
// HSCYLeftRightTableCellView.swift
// hscy
//
// Created by 周子聪 on 2017/9/13.
// Copyright © 2017年 melodydubai. All rights reserved.
//
import Foundation
class HSCYLeftRightTableCellView: UITableViewCell {
@IBOutlet weak var rightLabel: UILabel!
@IBOutlet weak var leftLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
//
// EventTableViewCell.swift
// Metsterios
//
// Created by Chelsea Green on 4/10/16.
// Copyright © 2016 Chelsea Green. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class MapviewTableViewCell: UITableViewCell {
var itemdescp : UILabel!
var itemline1seg3 : UILabel!
var itemline1seg2 : UILabel!
var itemline1seg1 : UILabel!
var itemTitle : UILabel!
var itemdetail : UILabel!
var itemImage : UIImageView?
var publishbutton : UIButton!
var chatButton : UIButton?
var fbButton : UIButton?
required init(coder aDecorder: NSCoder) {
fatalError("init(coder:)")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
itemImage = UIImageView()
itemImage?.frame = CGRectMake(2, 10, 85, 85)
itemImage!.layer.cornerRadius = 8.0
itemImage!.clipsToBounds = true
contentView.addSubview(itemImage!)
itemTitle = UILabel()
itemTitle.frame = CGRectMake(90, 11, screenWidth-100, 30)
itemTitle.textColor = UIColor(red: 0.81, green: 0.71, blue: 0.23, alpha: 1)
itemTitle.font = UIFont(name: "GILLSANSCE-ROMAN-Bold", size: 35)
contentView.addSubview(itemTitle)
itemline1seg1 = UILabel() // rate
itemline1seg1.frame = CGRectMake(90, 30, screenWidth-100, 25)
itemline1seg1.textColor = UIColor.grayColor()
itemline1seg1.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
contentView.addSubview(itemline1seg1)
itemline1seg2 = UILabel()
itemline1seg2.frame = CGRectMake(200, 30, screenWidth-100, 25)
itemline1seg2.textColor = UIColor.grayColor()
itemline1seg2.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
contentView.addSubview(itemline1seg2)
itemline1seg3 = UILabel()
itemline1seg3.frame = CGRectMake(220, 30, screenWidth-100, 25)
itemline1seg3.textColor = UIColor.grayColor()
itemline1seg3.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
contentView.addSubview(itemline1seg3)
itemdescp = UILabel()
itemdescp.frame = CGRectMake(90, 48, screenWidth-100, 25)
itemdescp.textColor = UIColor.grayColor()
itemdescp.font = UIFont(name: "HelveticaNeue-Light", size: 12)
contentView.addSubview(itemdescp)
itemdetail = UILabel()
itemdetail.frame = CGRectMake(90, 68, screenWidth-100, 25)
itemdetail.textColor = UIColor.grayColor()
itemdetail.font = UIFont(name: "HelveticaNeue-Light", size: 12)
contentView.addSubview(itemdetail)
chatButton = UIButton()
chatButton?.frame = CGRectMake(screenWidth-30, 40, 25, 25)
contentView.addSubview(chatButton!)
fbButton = UIButton()
fbButton?.frame = CGRectMake(screenWidth-60, 40, 25, 25)
contentView.addSubview(fbButton!)
}
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
}
}
|
//
// MVLoginContract.swift
// Movies
//
// Created by Rubens Pessoa on 4/5/18.
// Copyright © 2018 Ilhasoft. All rights reserved.
//
import Foundation
protocol MVLoginContract: class {
func facebookLogin(success: Bool)
func showLoginError(error: Error)
func navigateToHome()
}
|
//
//
//
//
// Created by m2sar on 02/11/2020.
// Copyright © 2020 UPMC. All rights reserved.
//
import Foundation
import UIKit
class GameView: UIView {
let left = UIButton(type: .system)
let right = UIButton(type: .system)
let gameOver = UILabel()
let score = UILabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
gameOver.text = "Loooooser !"
gameOver.textAlignment = .center
gameOver.font = UIFont.boldSystemFont(ofSize: 60)
gameOver.textColor = UIColor.white
gameOver.frame = frame
gameOver.isHidden = true
score.text = "Score: 0"
score.font = UIFont.boldSystemFont(ofSize: 30)
score.sizeToFit()
score.textColor = UIColor.white
left.setTitle("<<<", for: .normal)
left.titleLabel!.font = UIFont.boldSystemFont(ofSize: 40)
right.setTitle(">>>", for: .normal)
right.titleLabel!.font = UIFont.boldSystemFont(ofSize: 40)
left.addTarget(self.superview, action: #selector(ViewController.left_touch), for: .touchDown)
right.addTarget(self.superview, action: #selector(ViewController.right_touch), for: .touchDown)
left.addTarget(self.superview, action: #selector(ViewController.left_release(_:)), for: .touchUpInside)
right.addTarget(self.superview, action: #selector(ViewController.right_release), for: .touchUpInside)
left.addTarget(self.superview, action: #selector(ViewController.left_release(_:)), for: .touchUpOutside)
right.addTarget(self.superview, action: #selector(ViewController.right_release), for: .touchUpOutside)
self.addSubview(left)
self.addSubview(right)
self.addSubview(gameOver)
self.addSubview(score)
draw_in_format(frame: frame.size)
//question_label.font = UIFont(name: "Times new roman",size: 15)
}
func hideGameOver(b : Bool){
gameOver.isHidden = b
}
func draw_in_format(frame: CGSize){
left.frame=CGRect(x: 20, y: frame.height-100, width: 80, height: 80)
right.frame=CGRect(x: frame.width-100, y: frame.height-100, width: 80, height: 80)
score.frame.origin.x = frame.width-score.frame.width-20
score.frame.origin.y = 20
}
func setScore(t : String){
score.text = "Score: "+t
score.sizeToFit()
score.frame.origin.x = frame.width-score.frame.width-20
score.frame.origin.y = 20
}
func movePlayer(p : Player){
p.img.center.x = p.pos.x
p.img.center.y = p.pos.y
}
func moveAsteroid(a : Asteroid){
a.img.center.x = a.pos.x
a.img.center.y = a.pos.y
a.img.transform = CGAffineTransform(rotationAngle: a.theta)
}
func addPlayer(player : Player){
self.addSubview(player.img)
player.img.frame = CGRect(x: frame.width/2-Player.size/2, y: frame.height-40-Player.size/2, width: Player.size, height: Player.size)
}
func addAsteroid(a : Asteroid){
self.addSubview(a.img)
a.img.frame = CGRect(x: a.pos.x, y: a.pos.y, width: Asteroid.size, height: Asteroid.size)
}
}
|
//
// ViewPagerCell.swift
// ViewPagerWithTabs
//
// Created by Sonu Malik on 01/10/17.
// Copyright © 2017 yodevelopers. All rights reserved.
//
import UIKit
class ViewPagerCell: BaseCell {
override func setUpView() {
}
}
|
//
// StoreObserver.swift
// Calm Cloud
//
// Created by Kate Duncan-Welke on 7/1/20.
// Copyright © 2020 Kate Duncan-Welke. All rights reserved.
//
import Foundation
import StoreKit
class StoreObserver: NSObject, SKPaymentTransactionObserver {
static let iapObserver = StoreObserver()
var restored: [String] = []
var purchased: [String] = []
static var isComplete = false
static var coins = 0
static var isCloudsPurchase = false
override init() {
super.init()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
print("updating transactions")
for transaction in transactions {
switch transaction.transactionState {
case .purchasing:
break
case .deferred:
print("deferred")
// The purchase was successful.
case .purchased:
complete(transaction: transaction)
print("purchase succeeded")
if StoreObserver.isCloudsPurchase {
PlaysModel.clouds += 5
DataFunctions.saveClouds()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshClouds"), object: nil)
} else {
MoneyManager.total += StoreObserver.coins
DataFunctions.saveMoney()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateMoney"), object: nil)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateCoins"), object: nil)
}
// The transaction failed.
case .failed:
fail(transaction: transaction)
print("failed")
// There are restored products.
case .restored:
if !transaction.downloads.isEmpty {
queue.start(transaction.downloads)
}
print("restored")
default:
break
}
}
}
func buy(_ product: SKProduct) {
let payment = SKMutablePayment(product: product)
SKPaymentQueue.default().add(payment)
print("buy called")
}
private func complete(transaction: SKPaymentTransaction) {
print("complete...")
SKPaymentQueue.default().finishTransaction(transaction)
}
private func fail(transaction: SKPaymentTransaction) {
print("fail...")
if let transactionError = transaction.error as NSError?,
let localizedDescription = transaction.error?.localizedDescription,
transactionError.code != SKError.paymentCancelled.rawValue {
print("Transaction Error: \(localizedDescription)")
}
SKPaymentQueue.default().finishTransaction(transaction)
}
}
|
//
// TemporaryScheduleOverride.swift
// LoopKit
//
// Created by Michael Pangburn on 1/1/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
public struct TemporaryScheduleOverride: Equatable {
public enum Context: Equatable {
case preMeal
case preset(TemporaryScheduleOverridePreset)
case custom
}
public enum Duration: Equatable {
case finite(TimeInterval)
case indefinite
public var timeInterval: TimeInterval {
switch self {
case .finite(let interval):
return interval
case .indefinite:
return .infinity
}
}
public var isFinite: Bool {
switch self {
case .finite:
return true
case .indefinite:
return false
}
}
}
public var context: Context
public var settings: TemporaryScheduleOverrideSettings
public var startDate: Date
public var duration: Duration
public var activeInterval: DateInterval {
return DateInterval(start: startDate, duration: duration.timeInterval)
}
public func hasFinished(relativeTo date: Date = Date()) -> Bool {
return date > activeInterval.end
}
public init(context: Context, settings: TemporaryScheduleOverrideSettings, startDate: Date, duration: Duration) {
self.context = context
self.settings = settings
self.startDate = startDate
self.duration = duration
}
public func isActive(at date: Date = Date()) -> Bool {
return activeInterval.contains(date)
}
}
extension GlucoseRangeSchedule {
public func applyingOverride(
_ override: TemporaryScheduleOverride,
relativeTo date: Date = Date(),
calendar: Calendar = .current
) -> GlucoseRangeSchedule {
let rangeSchedule = self.rangeSchedule.applyingGlucoseRangeOverride(from: override, relativeTo: date, calendar: calendar)
return GlucoseRangeSchedule(rangeSchedule: rangeSchedule)
}
}
extension DailyQuantitySchedule where T == DoubleRange {
fileprivate func applyingGlucoseRangeOverride(
from override: TemporaryScheduleOverride,
relativeTo date: Date,
calendar: Calendar
) -> DailyQuantitySchedule {
guard let targetRange = override.settings.targetRange else {
return self
}
return DailyQuantitySchedule(
unit: unit,
valueSchedule: valueSchedule.applyingOverride(
during: override.activeInterval,
relativeTo: date,
calendar: calendar,
updatingOverridenValuesWith: { _ in targetRange }
)
)
}
}
extension /* BasalRateSchedule */ DailyValueSchedule where T == Double {
public func applyingBasalRateMultiplier(
from override: TemporaryScheduleOverride,
relativeTo date: Date = Date(),
calendar: Calendar = .current
) -> BasalRateSchedule {
return applyingOverride(override, relativeTo: date, calendar: calendar, multiplier: \.basalRateMultiplier)
}
}
extension /* InsulinSensitivitySchedule */ DailyQuantitySchedule where T == Double {
public func applyingSensitivityMultiplier(
from override: TemporaryScheduleOverride,
relativeTo date: Date = Date(),
calendar: Calendar = .current
) -> InsulinSensitivitySchedule {
return DailyQuantitySchedule(
unit: unit,
valueSchedule: valueSchedule.applyingOverride(
override,
relativeTo: date,
calendar: calendar,
multiplier: \.insulinSensitivityMultiplier
)
)
}
}
extension /* CarbRatioSchedule */ DailyQuantitySchedule where T == Double {
public func applyingCarbRatioMultiplier(
from override: TemporaryScheduleOverride,
relativeTo date: Date = Date(),
calendar: Calendar = .current
) -> CarbRatioSchedule {
return DailyQuantitySchedule(
unit: unit,
valueSchedule: valueSchedule.applyingOverride(
override,
relativeTo: date,
calendar: calendar,
multiplier: \.carbRatioMultiplier
)
)
}
}
extension DailyValueSchedule where T == Double {
fileprivate func applyingOverride(
_ override: TemporaryScheduleOverride,
relativeTo date: Date,
calendar: Calendar,
multiplier multiplierKeyPath: KeyPath<TemporaryScheduleOverrideSettings, Double?>
) -> DailyValueSchedule {
guard let multiplier = override.settings[keyPath: multiplierKeyPath] else { return self }
return applyingOverride(
during: override.activeInterval,
relativeTo: date,
calendar: calendar,
updatingOverridenValuesWith: { $0 * multiplier }
)
}
}
extension DailyValueSchedule {
fileprivate func applyingOverride(
during activeInterval: DateInterval,
relativeTo date: Date,
calendar: Calendar,
updatingOverridenValuesWith update: (T) -> T
) -> DailyValueSchedule {
guard let activeInterval = clamping(activeInterval, to: date, calendar: calendar) else {
// Active interval does not fall within this date; schedule is unchanged
return self
}
let overrideStartOffset = scheduleOffset(for: activeInterval.start)
let overrideEndOffset = scheduleOffset(for: activeInterval.end)
guard overrideStartOffset != overrideEndOffset else {
// Full schedule is overridden
let overriddenSchedule = items.map { item in
RepeatingScheduleValue(startTime: item.startTime, value: update(item.value))
}
return DailyValueSchedule(dailyItems: overriddenSchedule, timeZone: timeZone)!
}
let scheduleItemsIncludingOverride = scheduleItemsPaddedToClosedInterval
.adjacentPairs()
.flatMap { item, nextItem -> [RepeatingScheduleValue<T>] in
let scheduleItemInterval = item.startTime..<nextItem.startTime
switch (scheduleItemInterval.contains(overrideStartOffset), scheduleItemInterval.contains(overrideEndOffset)) {
case (true, true):
// Override fully contained by this segment
let overrideStart = RepeatingScheduleValue(startTime: overrideStartOffset, value: update(item.value))
let overrideEnd = RepeatingScheduleValue(startTime: overrideEndOffset, value: item.value)
if item.startTime == overrideStartOffset {
// Ignore the existing schedule item
return [overrideStart, overrideEnd]
} else {
// Include the start of the existing item up until the override start
return [item, overrideStart, overrideEnd]
}
case (true, false):
// Override begins within this segment
let overrideStart = RepeatingScheduleValue(startTime: overrideStartOffset, value: update(item.value))
if item.startTime == overrideStartOffset {
// Ignore the existing schedule item
return [overrideStart]
} else {
// Include the start of the existing item up until the override start
return [item, overrideStart]
}
case (false, true):
// Override ends within this segment
if item.startTime == overrideEndOffset {
// Override ends here naturally
return [item]
} else {
// Include partially overriden item up until end
let partiallyOverridenItem = RepeatingScheduleValue(startTime: item.startTime, value: update(item.value))
let overrideEnd = RepeatingScheduleValue(startTime: overrideEndOffset, value: item.value)
return [partiallyOverridenItem, overrideEnd]
}
case (false, false):
// Segment is either disjoint with the override -> should remain unaffected
// or fully encapsulated by the override -> should be updated
if item.startTime < overrideStartOffset || item.startTime > overrideEndOffset {
// The item is unaffected
return [item]
} else {
// The item is fully overriden
let overridenItem = RepeatingScheduleValue(startTime: item.startTime, value: update(item.value))
return [overridenItem]
}
}
}
return DailyValueSchedule(
dailyItems: scheduleItemsIncludingOverride,
timeZone: timeZone
)!
}
func clamping(_ interval: DateInterval, to date: Date, calendar: Calendar) -> DateInterval? {
let (startHour, startMinute) = referenceTimeInterval.hourAndMinuteComponents
let (endHour, endMinute) = maxTimeInterval.hourAndMinuteComponents
guard
let startOfDateRelativeToSchedule = calendar.date(bySettingHour: startHour, minute: startMinute, second: 0, of: date),
var endOfDateRelativeToSchedule = calendar.date(bySettingHour: endHour, minute: endMinute, second: 0, of: date)
else {
assertionFailure("Unable to compute dates relative to schedule using \(calendar)")
return interval
}
if endOfDateRelativeToSchedule <= startOfDateRelativeToSchedule {
endOfDateRelativeToSchedule += repeatInterval
}
let scheduleInterval = DateInterval(start: startOfDateRelativeToSchedule, end: endOfDateRelativeToSchedule)
guard scheduleInterval.intersects(interval) else {
// Interval falls on a different day
return nil
}
let startDate = max(interval.start, startOfDateRelativeToSchedule)
let endDate = min(interval.end, endOfDateRelativeToSchedule)
return DateInterval(start: startDate, end: endDate)
}
/// Pads the schedule with an extra item to form a closed interval.
private var scheduleItemsPaddedToClosedInterval: [RepeatingScheduleValue<T>] {
guard let lastItem = items.last else {
assertionFailure("Schedule should never be empty")
return []
}
let lastItemStartingAtDayEnd = RepeatingScheduleValue(startTime: maxTimeInterval, value: lastItem.value)
return items + [lastItemStartingAtDayEnd]
}
}
extension TemporaryScheduleOverride: RawRepresentable {
public typealias RawValue = [String: Any]
public init?(rawValue: RawValue) {
guard
let contextRawValue = rawValue["context"] as? Context.RawValue,
let context = Context(rawValue: contextRawValue),
let settingsRawValue = rawValue["settings"] as? TemporaryScheduleOverrideSettings.RawValue,
let settings = TemporaryScheduleOverrideSettings(rawValue: settingsRawValue),
let startDateSeconds = rawValue["startDate"] as? TimeInterval,
let durationRawValue = rawValue["duration"] as? Duration.RawValue,
let duration = Duration(rawValue: durationRawValue)
else {
return nil
}
let startDate = Date(timeIntervalSince1970: startDateSeconds)
self.init(context: context, settings: settings, startDate: startDate, duration: duration)
}
public var rawValue: RawValue {
return [
"context": context.rawValue,
"settings": settings.rawValue,
"startDate": startDate.timeIntervalSince1970,
"duration": duration.rawValue
]
}
}
extension TemporaryScheduleOverride.Context: RawRepresentable {
public typealias RawValue = [String: Any]
public init?(rawValue: RawValue) {
guard let context = rawValue["context"] as? String else {
return nil
}
switch context {
case "premeal":
self = .preMeal
case "preset":
guard
let presetRawValue = rawValue["preset"] as? TemporaryScheduleOverridePreset.RawValue,
let preset = TemporaryScheduleOverridePreset(rawValue: presetRawValue)
else {
return nil
}
self = .preset(preset)
case "custom":
self = .custom
default:
return nil
}
}
public var rawValue: RawValue {
switch self {
case .preMeal:
return ["context": "premeal"]
case .preset(let preset):
return [
"context": "preset",
"preset": preset.rawValue
]
case .custom:
return ["context": "custom"]
}
}
}
extension TemporaryScheduleOverride.Duration: RawRepresentable {
public typealias RawValue = [String: Any]
public init?(rawValue: RawValue) {
guard let duration = rawValue["duration"] as? String else {
return nil
}
switch duration {
case "finite":
guard let interval = rawValue["interval"] as? TimeInterval else {
return nil
}
self = .finite(interval)
case "indefinite":
self = .indefinite
default:
return nil
}
}
public var rawValue: RawValue {
switch self {
case .finite(let interval):
return [
"duration": "finite",
"interval": interval
]
case .indefinite:
return ["duration": "indefinite"]
}
}
}
private extension GlucoseRangeSchedule {
init(rangeSchedule: DailyQuantitySchedule<DoubleRange>) {
self.rangeSchedule = rangeSchedule
}
}
private extension DailyQuantitySchedule {
init(unit: HKUnit, valueSchedule: DailyValueSchedule<T>) {
self.unit = unit
self.valueSchedule = valueSchedule
}
}
private extension TimeInterval {
var hourAndMinuteComponents: (hour: Int, minute: Int) {
let base = self.truncatingRemainder(dividingBy: .hours(24))
let hour = Int(base.hours)
let minute = Int((base - .hours(Double(hour))).minutes)
return (hour, minute)
}
}
|
import Cocoa
import FlutterMacOS
private class EffectIDToMaterialConverter {
@available(macOS 10.14, *)
public static func getMaterialFromEffectID(effectID: NSNumber) -> NSVisualEffectView.Material {
switch(effectID) {
/* Try to mimic the behavior of the following effects as
closely as possible: */
case 0: // disabled
return NSVisualEffectView.Material.windowBackground
case 1: // solid
return NSVisualEffectView.Material.windowBackground
case 2: // transparent
return NSVisualEffectView.Material.underWindowBackground
case 3: // aero
return NSVisualEffectView.Material.hudWindow
case 4: // acrylic
return NSVisualEffectView.Material.fullScreenUI
case 5: // mica
return NSVisualEffectView.Material.headerView
case 6: // titlebar
return NSVisualEffectView.Material.titlebar
case 7: // selection
return NSVisualEffectView.Material.selection
case 8: // menu
return NSVisualEffectView.Material.menu
case 9: // popover
return NSVisualEffectView.Material.popover
case 10: // sidebar
return NSVisualEffectView.Material.sidebar
case 11: // headerView
return NSVisualEffectView.Material.headerView
case 12: // sheet
return NSVisualEffectView.Material.sheet
case 13: // windowBackground
return NSVisualEffectView.Material.windowBackground
case 14: // hudWindow
return NSVisualEffectView.Material.hudWindow
case 15: // fullScreenUI
return NSVisualEffectView.Material.fullScreenUI
case 16: // toolTip
return NSVisualEffectView.Material.toolTip
case 17: // contentBackground
return NSVisualEffectView.Material.contentBackground
case 18: // underWindowBackground
return NSVisualEffectView.Material.underWindowBackground
case 19: // underPageBackground
return NSVisualEffectView.Material.underPageBackground
default:
return NSVisualEffectView.Material.windowBackground
}
}
}
public class MainFlutterWindowManipulator {
private static var contentView: NSView?
private static var invalidateShadow: () -> Void = {}
private static func printMissingContentViewWarning() {
print("Warning: The MainFlutterWindowManipulator's contentView has not been set. Please make sure the flutter_acrylic plugin is initialized correctly in your MainFlutterWindow.swift file.")
}
public static func setContentView(contentView: NSView) {
self.contentView = contentView
}
public static func setInvalidateShadowFunction(invalidateShadow: @escaping () -> Void) {
self.invalidateShadow = invalidateShadow
}
@available(macOS 10.14, *)
public static func setAppearance(dark: Bool) {
let superView = contentView!.superview!
superView.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
self.invalidateShadow()
}
@available(macOS 10.14, *)
public static func setMaterial(material: NSVisualEffectView.Material) {
if (self.contentView == nil) {
printMissingContentViewWarning()
return
}
let superView = contentView!.superview!
let blurView = NSVisualEffectView()
blurView.frame = superView.bounds
blurView.autoresizingMask = [.width, .height]
blurView.blendingMode = NSVisualEffectView.BlendingMode.behindWindow
/* Pick the correct material for the task */
blurView.material = material
/* Replace the contentView and the background view */
superView.replaceSubview(contentView!, with: blurView)
blurView.addSubview(contentView!)
self.invalidateShadow()
}
@available(macOS 10.14, *)
public static func setEffect(material: NSVisualEffectView.Material) {
setMaterial(material: material)
}
}
public class FlutterAcrylicPlugin: NSObject, FlutterPlugin {
private var registrar: FlutterPluginRegistrar!;
private var channel: FlutterMethodChannel!
private static func printUnsupportedMacOSVersionWarning() {
print("Warning: Transparency effects are not supported for your macOS Deployment Target.")
}
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "com.alexmercerind/flutter_acrylic", binaryMessenger: registrar.messenger)
let instance = FlutterAcrylicPlugin(registrar, channel)
registrar.addMethodCallDelegate(instance, channel: channel)
}
public init(_ registrar: FlutterPluginRegistrar, _ channel: FlutterMethodChannel) {
super.init()
self.registrar = registrar
self.channel = channel
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let methodName: String = call.method
let args: [String: Any] = call.arguments as? [String: Any] ?? [:]
switch (methodName) {
case "Initialize":
if #available(macOS 10.14, *) {
let material = EffectIDToMaterialConverter.getMaterialFromEffectID(effectID: 0)
MainFlutterWindowManipulator.setEffect(material: material)
} else {
FlutterAcrylicPlugin.printUnsupportedMacOSVersionWarning()
}
result(true)
break
case "SetEffect":
if #available(macOS 10.14, *) {
let effectID = args["effect"] as! NSNumber
let material = EffectIDToMaterialConverter.getMaterialFromEffectID(effectID: effectID)
MainFlutterWindowManipulator.setEffect(material: material)
} else {
FlutterAcrylicPlugin.printUnsupportedMacOSVersionWarning()
}
result(true)
break
case "HideWindowControls":
print("Warning: Hiding window controls is currently not supported on macOS.")
result(true)
break
case "ShowWindowControls":
print("Warning: Showing window controls is currently not supported on macOS.")
result(true)
break
case "EnterFullscreen":
print("Warning: Entering fullscreen mode is currently not supported on macOS.")
result(true)
break
case "ExitFullscreen":
print("Warning: Exiting fullscreen mode is currently not supported on macOS.")
result(true)
break
case "OverrideMacOSBrightness":
if #available(macOS 10.14, *) {
let dark = args["dark"] as! Bool
MainFlutterWindowManipulator.setAppearance(dark: dark)
} else {
FlutterAcrylicPlugin.printUnsupportedMacOSVersionWarning()
}
result(true)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
}
|
//
// Character.swift
// smartFriend2
//
// Created by Daniel Braga on 7/3/18.
// Copyright © 2018 Daniel Braga. All rights reserved.
//
import UIKit
import os.log
class Character: NSObject, NSCoding {
//MARK: Properties
var name: String
var achievements: Int
var gender: Int
struct PropertyKey{
static let name = "name"
static let achievements = "achievements"
static let gender = "gender"
}
//MARK: Initialization
init?(name: String, achievements: Int, gender: Int){
guard !name.isEmpty else {
return nil
}
guard (achievements >= 0) else {
return nil
}
if name.isEmpty || achievements < 0 {return nil}
self.name = name
self.achievements = achievements
self.gender = gender
}
// MARK: NSCoding
func encode(with aCoder: NSCoder){
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(achievements, forKey: PropertyKey.achievements)
aCoder.encode(gender, forKey: PropertyKey.gender)
}
required convenience init?(coder aDecoder: NSCoder){
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {
os_log("Unable to decode the name for Character object.", log: OSLog.default, type: .debug)
return nil
}
let achievements = aDecoder.decodeInteger(forKey: PropertyKey.achievements)
let gender = aDecoder.decodeInteger(forKey: PropertyKey.gender)
self.init(name: name, achievements: achievements, gender: gender)
}
//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("characters")
}
|
//
// ListMissions.swift
// SpaceX
//
// Created by Carmelo Ruymán Quintana Santana on 25/2/21.
//
import SwiftUI
import SpaceXApi
struct ListMissions: View {
@StateObject var missionsService: MissionsService
var body: some View {
ScrollView(.vertical, showsIndicators: false, content: {
LazyVStack(alignment: .center, spacing: 8, pinnedViews: [], content: {
ForEach(missionsService.missions, id: \.self) { mission in
RowMission(mission: mission)
CustomDivider(color: Color.black).padding(.horizontal)
}
})
}).onAppear(perform: {
missionsService.getAllMissions()
})
}
}
// struct ListMissions_Previews: PreviewProvider {
// static var previews: some View {
// ListMissions()
// }
// }
|
//
// searchsummonerTVC.swift
// LOL4YOU
//
// Created by Emanuel Root on 16/04/17.
// Copyright © 2017 Emanuel Root. All rights reserved.
//
import UIKit
import SVProgressHUD
import ActionSheetPicker_3_0
import GoogleMobileAds
import FirebaseAnalytics
class searchsummonerTVC: UITableViewController, UITextFieldDelegate, GADBannerViewDelegate {
@IBOutlet weak var srchsummoner: UIButton!
@IBOutlet weak var summonernick: UITextField!
@IBOutlet weak var summonerserver: UIButton!
@IBOutlet weak var switchSpec: UISwitch!
let admob = rootadmob.sharedInstance
let rt = rootclass.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
self.initAdMob()
self.initView()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
@IBAction func btnsrchsummoner(_ sender: AnyObject) {
admob.addCountAdMobInterstitial();
if admob.showAdMobInterstitial() {
if let adMobInterstitial = admob.getAdInterstitial() {
adMobInterstitial.present(fromRootViewController: self)
return
}
}
if switchSpec.isOn == false {
self.buscaSummoner()
} else {
self.buscaSpec()
}
}
func buscaSummoner() {
SVProgressHUD.show()
if summonernick.text != nil && (summonernick.text?.isEmpty)! {
let alert = UIAlertController(title: "Notice", message: "Invalid Summoner", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
SVProgressHUD.dismiss()
return
}
rt.listarSummoner(summonername: summonernick.text!.replacingOccurrences(of: " ", with: "")) {(error) in
if error.id == 1 {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "perfil") as! perfilVC
self.navigationController?.pushViewController(vc, animated: true)
}
if error.id == 400 {
let alert = UIAlertController(title: "Notice", message: "Invalid Summoner", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
SVProgressHUD.dismiss()
}
}
func buscaSpec() {
SVProgressHUD.show()
if summonernick.text != nil && (summonernick.text?.isEmpty)! {
let alert = UIAlertController(title: "Notice", message: "Invalid Summoner", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
SVProgressHUD.dismiss()
return
}
rt.listarSummoner(summonername: summonernick.text!.replacingOccurrences(of: " ", with: "")) {(error) in
if error.id == 400 {
let alert = UIAlertController(title: "Notice", message: "Invalid Summoner", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
SVProgressHUD.dismiss()
return
}
self.rt.listarSpec() {(spec) in
if spec.participants.count > 0 {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "spec") as! specTVC
vc.spec = spec
self.navigationController?.pushViewController(vc, animated: true)
} else {
let alert = UIAlertController(title: "Notice", message: "Invalid Match", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
SVProgressHUD.dismiss()
}
}
}
@objc func validadados(_ textField: UITextField) {
if (self.summonernick.text?.isEmpty)! {
self.srchsummoner.isEnabled = false
self.srchsummoner.alpha = 0.5
return
}
if (self.summonerserver.title(for: .normal)?.lowercased() == "server") {
self.srchsummoner.isEnabled = false
self.srchsummoner.alpha = 0.5
return
}
self.srchsummoner.isEnabled = true
self.srchsummoner.alpha = 1
}
func initAdMob() {
Analytics.setScreenName(rootclass.screens.search, screenClass: String(describing: searchsummonerTVC.self))
if rt.viewbanner {
let adBannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
adBannerView.adUnitID = rootadmob.admob.admob_banner
adBannerView.delegate = self
adBannerView.rootViewController = self
adBannerView.load(GADRequest())
self.tableView.tableHeaderView = adBannerView
}
}
func initView(){
let attnav = [
NSAttributedStringKey.foregroundColor: UIColor(hex:rootclass.colors.TEXTO_TOP_BAR.rawValue),
NSAttributedStringKey.font: UIFont(name: "Friz Quadrata TT", size: 17)!
]
self.summonernick.delegate = self
self.title = "Summoner"
self.summonernick.addTarget(self, action: #selector(validadados(_:)), for: .editingChanged)
self.navigationController?.navigationBar.barTintColor = UIColor(hex: rootclass.colors.FUNDO.rawValue)
self.navigationController?.navigationBar.titleTextAttributes = attnav
}
@IBAction func btnServerPicker(_ sender: AnyObject) {
let servers = ["Brazil",
"EU Nordic & East",
"EU West",
"Latin America North",
"Latin America South",
"North America",
"Oceania",
"Russia",
"Turkey",
"Japan",
"Korea"]
let acp = ActionSheetStringPicker(title: "Server", rows: servers, initialSelection: 0, doneBlock: {
picker, value, index in
switch value {
case 0:
rootclass.lol.server = "BR"
case 1:
rootclass.lol.server = "EUNE"
case 2:
rootclass.lol.server = "EUW"
case 3:
rootclass.lol.server = "LAN"
case 4:
rootclass.lol.server = "LAS"
case 5:
rootclass.lol.server = "NA"
case 6:
rootclass.lol.server = "OCE"
case 7:
rootclass.lol.server = "RU"
case 8:
rootclass.lol.server = "TR"
case 9:
rootclass.lol.server = "JP"
case 10:
rootclass.lol.server = "KR"
default:
rootclass.lol.server = "BR"
}
self.summonerserver.setTitle(index as! String?, for: .normal)
self.validadados(UITextField())
self.view.endEditing(true)
return
}, cancel: {
ActionStringCancelBlock in return
self.view.endEditing(true)
}, origin: sender)
let textTitleAtributes = [
NSAttributedStringKey.foregroundColor: UIColor(hex:rootclass.colors.TEXTO_TOP_BAR.rawValue),
NSAttributedStringKey.font: UIFont(name: "Friz Quadrata TT", size: 17)!
]
let pickerTextAttributes:NSMutableDictionary = [NSAttributedStringKey.foregroundColor:UIColor(hex:rootclass.colors.FUNDO.rawValue),
NSAttributedStringKey.font: UIFont(name: "Friz Quadrata TT", size: 15)!]
let btDone = UIButton.init(type: .custom)
btDone.setTitle("Done", for: .normal)
btDone.setTitleColor(UIColor(hex:rootclass.colors.TEXTO_VITORIA.rawValue), for: .normal)
btDone.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
btDone.titleLabel!.font = UIFont(name: "Friz Quadrata TT", size: 15)!
let btBarDone = UIBarButtonItem(customView: btDone)
let btCancel = UIButton.init(type: .custom)
btCancel.setTitle("Cancel", for: .normal)
btCancel.setTitleColor(UIColor(hex:rootclass.colors.TEXTO_DERROTA.rawValue), for: .normal)
btCancel.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
btCancel.titleLabel!.font = UIFont(name: "Friz Quadrata TT", size: 15)!
let btBarCancel = UIBarButtonItem(customView: btCancel)
acp!.titleTextAttributes = textTitleAtributes
acp!.pickerTextAttributes = pickerTextAttributes
acp!.toolbarBackgroundColor = UIColor(hex:rootclass.colors.FUNDO.rawValue)
acp!.toolbarButtonsColor = UIColor(hex:rootclass.colors.FUNDO_CLARO.rawValue)
acp!.setDoneButton(btBarDone)
acp!.setCancelButton(btBarCancel)
acp!.show()
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.view.endEditing(true)
}
func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
self.view.endEditing(true)
return true
}
}
|
//
// RevealViewController.swift
// interactive-transition-animations
//
// Created by Rachel Unthank on 17/02/2019.
// Copyright © 2019 rachelunthank. All rights reserved.
//
import UIKit
class RevealViewController: UIViewController, DismissController {
var swipeInteractionController: SwipeInteractionController?
var dismissTransitionDelegate: DismissTransitionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setUpDismissalController()
}
}
|
//
// CreationOptionTableViewCell.swift
// Bracket
//
// Created by Justin Galang on 7/21/20.
// Copyright © 2020 Justin Galang. All rights reserved.
//
import UIKit
class CreationOptionTableViewCell: UITableViewCell {
@IBOutlet weak var optionOneTextField: UITextField!
@IBOutlet weak var optionTwoTextField: UITextField!
static let identifier = "CreationOptionTableViewCell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func load(viewModel: OptionViewModel) {
optionOneTextField.text = viewModel.text
optionOneTextField.delegate = viewModel
optionTwoTextField.text = viewModel.text
optionTwoTextField.delegate = viewModel
}
}
|
//
// SystemUI.swift
// Little Orion
//
// Created by Thomas Ricouard on 25/11/2016.
// Copyright © 2016 Thomas Ricouard. All rights reserved.
//
import UIKit
import ReSwift
class StarCell: UITableViewCell {
static let id = "starCell"
@IBOutlet var starImageView: UIImageView!
@IBOutlet var starTitleLabel: UILabel!
@IBOutlet var kindTitleLabel: UILabel!
public var planet: PlanetEntity? {
didSet {
starTitleLabel.text = "\(planet!.name) (\(planet!.kind.name()))"
let radius = String(format: "%.0f", planet!.radius)
kindTitleLabel.text = "Score: \(planet!.resourceScore) | Radius: \(radius) Km"
starImageView.image = planet!.kind.image()
starImageView.transform = CGAffineTransform(scaleX: planet!.scale, y: planet!.scale)
}
}
}
protocol SystemUiDelegate {
func systemUISelectedPlanet(planet: PlanetEntity)
}
class SystemUI: BaseUI, UITableViewDelegate, UITableViewDataSource, StoreSubscriber {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var starName: UILabel!
@IBOutlet var starImageView: UIImageView!
@IBOutlet var tableView: UITableView!
var delegate: SystemUiDelegate?
public var system: SystemEntity? {
didSet {
if let system = system {
titleLabel.text = system.description
starName.text = "Star: \(system.star.kind.name())"
starImageView.image = system.star.kind.image()
tableView.reloadData()
}
}
}
public func show() {
system = store.state.uiState.selectedSystem
store.subscribe(self) {
$0.select{ $0.uiState }.skipRepeats()
}
isHidden = false
alpha = 0
layer.transform = CATransform3DMakeScale(0.2, 0.2, 0.2)
UIView.animate(withDuration: 0.50,
delay: 0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 15,
options: .curveEaseInOut, animations: {
self.alpha = 1
self.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0)
}, completion: nil)
}
public func hide() {
store.unsubscribe(self)
UIView.animate(withDuration: 0.30, animations: {
self.alpha = 0
self.layer.transform = CATransform3DMakeScale(0.2, 0.2, 0.2)
}, completion: {(success) in
self.isHidden = true
})
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
frame = CGRect(x: 0, y: 0, width: 300, height: 400)
center = superview!.center
tableView.register(UINib(nibName: "StarCell", bundle: Bundle.main),
forCellReuseIdentifier: StarCell.id)
tableView.rowHeight = 60
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let system = system {
return system.planetsCount()
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: StarCell.id, for: indexPath) as! StarCell
cell.planet = system!.planet(at: indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let delegate = delegate {
delegate.systemUISelectedPlanet(planet: system!.planet(at: indexPath.row))
}
}
func newState(state: UIState) {
if system != state.selectedSystem {
system = state.selectedSystem
}
}
}
|
//
// Day27Testing.swift
// Datasnok
//
// Created by Vladimir Urbano on 7/24/16.
// Copyright © 2016 Vladimir Urbano. All rights reserved.
//
/*
Objective
This challenge is very different from the others we've completed because it requires you to generate a valid test case for a problem instead of solving the problem. There is no input to read, you simply have to generate and print test values for the problem that satisfy both the problem's Input Format and the criteria laid out in the Task section. Check out the Tutorial tab for an instructional video on testing!
Consider the following problem:
Problem Statement
A Discrete Mathematics professor has a class of students. Frustrated with their lack of discipline, the professor decides to cancel class if fewer than students are present when class starts. Given the arrival time of each student, determine if the class is canceled.
Input Format
The first line of input contains , the number of lectures.
The information for each lecture spans two lines. The first line has two space-separated integers, (the number of students in the class) and (the cancelation threshold). The second line contains space-separated integers describing the array of students' arrival times ().
Note: Non-positive arrival times () indicate the student arrived early or on time; positive arrival times () indicate the student arrived minutes late. If a student arrives exactly on time , the student is considered to have entered before the class started.
Output Format
For each test case, print the word YES if the class is canceled or NO if it is not.
Example
When properly solved, this input:
2
4 3
-1 -3 4 2
4 2
0 -1 2 1
Produces this output:
YES
NO
For the first test case, . The professor wants at least students in attendance, but only arrive on time (and ). Thus, the class is canceled.
For the second test case, . The professor wants at least students in attendance, and do arrive on time (and ). Thus, the class is not canceled.
Task
Create and print a test case for the problem above that meet the following criteria:
The value of must be distinct across all the test cases.
Array must have at least zero, positive integer, and negative integer.
Scoring
If you submit correct test cases, you will earn of the maximum score. You must submit test cases to earn the maximum possible score.
Input Format
You are not responsible for reading anything from stdin.
Output Format
Print lines of output that can be read by the Professor challenge as valid input. Your test case must result in the following output when fed as input to the Professor challenge's solution:
YES
NO
YES
NO
YES
Explanation
Your code must print lines of output that follow the Input Format in the Professor challenge above. For example, this partial solution to this challenge:
print('2')
print('4 3')
print('-1 -3 4 2')
print('5 2')
print('0 -1 2 1 4')
prints the following output that can be used as valid input for the Professor challenge:
2
4 3
-1 -3 4 2
5 2
0 -1 2 1 4
When read by a valid solution to the Professor challenge, it produces the following output:
YES
NO
You must do something similar to this, except that the test case you develop must meet the constraints set in the Task section above.
*/
import Foundation
class Day27Testing {
init() {
var cumulativeN = Array<Int>()
let cases = [true, false, true, false, true]
print(cases.count)
for c in cases {
var n = random(5, max: 200)
while cumulativeN.contains(n) {
n = random(5, max: 200)
}
cumulativeN.append(n)
var arr = Array<Int>()
let k = random(3, max: n - 3)
print("\(n) \(k)")
if c {
for _ in 0 ... n - k {
let a = random(1, max: 1000)
arr.append(a)
}
arr.append(0)
arr.append(random(1, max: 1000) * -1)
} else {
for _ in 1 ... k {
let a = random(0, max: 1000) * -1
arr.append(a)
}
arr.append(random(1, max: 1000))
if !arr.contains(0) {
arr.append(0)
}
}
for _ in arr.count ..< n {
let s = randomBool()
var a = random(0, max: 1000)
if !s {
a *= -1
}
arr.append(a)
}
let s = arr.map({ String($0) }).joinWithSeparator(" ")
print(s)
}
}
func random(min: Int, max: Int) -> Int {
var r = 0
repeat {
r = Int(arc4random_uniform(UInt32(max)))
} while r < min || r > max
return r
}
func randomBool() -> Bool {
return random(1, max: 100) % 2 == 0
}
}
|
//
// DashboardUseCase.swift
// MVVM_Demo
//
// Created by Hoang Lam on 23/09/2021.
//
import Foundation
class DashboardUseCase {
func excute(completion: @escaping (Customer) ->Void) {
DispatchQueue.main.asyncAfter(deadline: .now()) {
let name = self.randomName()
let status = self.randomStatus()
completion(Customer(name: name, status: status))
}
}
private func randomName() -> String {
let listFirstNames = ["John", "Paul", "Jim", "Robert", "Ann", "Kate", "Emily", "Jane"]
let listLastNames = ["Appleseed", "Martin", "Torvalds", "Kernighan", "Ritchie", "Lovelace"]
let firstName = listFirstNames.randomElement() ?? listFirstNames.first!
let lastName = listLastNames.randomElement() ?? listLastNames.first!
return firstName + " " + lastName
}
private func randomStatus() -> String {
let listStatuses = ["ACTIVE", "EXPIRED", "UNKNOWN"]
return listStatuses.randomElement() ?? listStatuses.first!
}
}
|
//
// HourlyForecastViewController.swift
// BeachBum
//
// Created by Jordan Dumlao on 9/6/18.
// Copyright © 2018 Jordan Dumlao. All rights reserved.
//
import UIKit
import ChameleonFramework
protocol HourlyForecastViewControllerDelegate: class {
func toggleExpansionPressed()
}
class HourlyForecastViewController: UIViewController {
weak var delegate: HourlyForecastViewControllerDelegate?
var hourlyForecast: Forecast.Hourly?
var borderColor: UIColor?
@IBOutlet var hourlyForecastView: UIView! { didSet { configureView() } }
@IBOutlet weak var hourlyForecastCollectionView: UICollectionView! { didSet { configureCollectionView() } }
}
//MARK: View Lifecycle
extension HourlyForecastViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureBlurEffect()
}
}
//MARK: UI Configuration
extension HourlyForecastViewController {
private func configureCollectionView() {
hourlyForecastCollectionView?.backgroundColor = .clear
hourlyForecastCollectionView?.layer.cornerRadius = 10.0
hourlyForecastCollectionView?.dataSource = self
}
private func configureView() {
hourlyForecastView?.layer.cornerRadius = 30.0
hourlyForecastView?.layer.masksToBounds = true
hourlyForecastView?.layer.borderColor = borderColor?.cgColor
hourlyForecastView?.layer.borderWidth = 2.0
}
private func configureBlurEffect() {
let blurEffect = UIBlurEffect(style: .extraLight)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(blurView, at: 0)
NSLayoutConstraint.activate([
blurView.heightAnchor.constraint(equalTo: view.heightAnchor),
blurView.widthAnchor.constraint(equalTo: view.widthAnchor),
])
}
}
//MARK: Data Source
extension HourlyForecastViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hourlyForecast?.data.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Hourly Forecast Cell", for: indexPath)
guard let hourlyCell = cell as? HourlyForecastCollectionViewCell else { return cell }
guard let hourlyForecast = self.hourlyForecast?.data[indexPath.item] else { return hourlyCell }
hourlyCell.model = HourlyForecastCellViewModel(hourlyForecast)
return cell
}
}
//MARK: Hourly Forecast View Controller Delegate Method
extension HourlyForecastViewController {
@IBAction func toggleCollapseButtonPressed(_ sender: UIButton) {
delegate?.toggleExpansionPressed()
}
}
|
//
// Constants.swift
// Currency-Converter
//
// Created by Kristina Gelzinyte on 2/11/18.
// Copyright © 2018 Kristina Gelzinyte. All rights reserved.
//
let conversionTaxesRate: Double = 0.007
let currencyInitDefaults: [(type: String, amount: Double)] = [ ("EUR", 1000.0), ("USD", 0.0), ("JPY", 0.0)]
|
//
// ViewController.swift
// PIP
//
// Created by Felipe Kimio Nishikaku on 05/28/2018.
// Copyright (c) 2018 kimiokun1@gmail.com. All rights reserved.
//
import UIKit
import PIP
extension UIViewController: PIPDelegate {
public func onFullScreen() {
print("full screen")
}
public func onMoveEnded(frame: CGRect) {
print("moved")
}
public func onRemove() {
print("removed")
}
}
class ViewController: UIViewController {
@IBOutlet weak var viewToPip: UIView!
@IBOutlet weak var removeView: UIView!
var pip: PIP?
override func viewDidLoad() {
super.viewDidLoad()
let pipConfiguration = PIPConfiguration(viewToPip: viewToPip)
pipConfiguration.animateDuration = 0.5
pipConfiguration.removeView = removeView
pip = PIP(configuration: pipConfiguration)
pip?.delegate = self
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
pip?.updatePipRect(CGRect(x: 0,
y: 0,
width: size.width,
height: size.height))
}
}
|
//
// Utils.swift
// ekko
//
// Created by Mark Lochrie on 04/06/2015.
// Copyright (c) 2015 Mark Lochrie. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
class Utils:UIViewController{
internal func urlForFileName(fileName: String) -> NSURL {
let fm = NSFileManager.defaultManager()
let urls = fm.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
inDomains: NSSearchPathDomainMask.UserDomainMask)
let directoryURL = urls[0]
let fileURL = directoryURL.URLByAppendingPathComponent(fileName)
return fileURL
}
}
|
//
// FixtureClient.swift
// Tests
//
// Created by Mederic Petit on 10/10/2017.
// Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved.
//
import Foundation
@testable import OmiseGO
class FixtureCoreAPI: HTTPAPI {
let fixturesDirectoryURL: URL
init(fixturesDirectoryURL: URL, config: Configuration) {
self.fixturesDirectoryURL = fixturesDirectoryURL
super.init(config: config)
}
@discardableResult
override func request<ResultType>(toEndpoint endpoint: APIEndpoint,
callback: Request<ResultType>.Callback?) -> Request<ResultType>? {
do {
let request: FixtureRequest<ResultType> = FixtureRequest(fixturesDirectoryURL: self.fixturesDirectoryURL,
client: self,
endpoint: endpoint,
callback: callback)
return try request.start()
} catch let error as NSError {
operationQueue.addOperation { callback?(.fail(error: .other(error: error))) }
} catch let error as OMGError {
operationQueue.addOperation { callback?(.fail(error: error)) }
}
return nil
}
}
class FixtureRequest<ResultType: Decodable>: Request<ResultType> {
let fixturesDirectoryURL: URL
init(fixturesDirectoryURL: URL, client: HTTPAPI, endpoint: APIEndpoint, callback: Callback?) {
self.fixturesDirectoryURL = fixturesDirectoryURL
super.init(client: client, endpoint: endpoint, callback: callback)
}
override func start() throws -> Self {
let fixtureFilePath = endpoint.fixtureFilePath
let fixtureFileURL = self.fixturesDirectoryURL.appendingPathComponent(fixtureFilePath)
DispatchQueue.global().async {
let data: Data?
let error: Error?
defer { self.didComplete(data: data, error: error) }
do {
data = try Data(contentsOf: fixtureFileURL)
error = nil
} catch let thrownError {
data = nil
error = thrownError
}
}
return self
}
fileprivate func didComplete(data: Data?, error: Error?) {
guard callback != nil else { return }
if let error = error {
return performCallback(.fail(error: .other(error: error)))
}
guard let data = data else {
return performCallback(.fail(error: .unexpected(message: "empty response.")))
}
performCallback(self.result(withData: data, statusCode: 200))
}
}
extension OmiseGO.APIEndpoint {
var fixtureFilePath: String {
let filePath = URL(string: "api")!.appendingPathComponent(path).absoluteString
return (filePath as NSString).appendingPathExtension("json")! as String
}
}
|
//
// ContentView.swift
// TrafficLightsSUI
//
// Created by SERGEY VOROBEV on 27.07.2021.
//
import SwiftUI
struct ContentView: View {
@State private var currentLight: TrafficLightsColor?
@State private var isStarted = false
private let signals: [TrafficLightsColor] = [.red, .yellow, .green]
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
VStack {
Spacer()
ForEach(signals, id: \.self) { signalColor in
Signal(color: signalColor, state: currentLight == signalColor ? .on : .off)
.padding(.bottom, 10)
}
Spacer()
VStack {
Button(action: {
isStarted = true
switch currentLight {
case .red:
currentLight = .yellow
case .yellow:
currentLight = .green
case .green, .none:
currentLight = .red
}
}, label: {
Text(isStarted ? "Next" : "Start")
.font(.title)
.foregroundColor(.white)
.padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6))
.frame(width: 200)
.overlay(
RoundedRectangle(cornerRadius: 25)
.stroke(Color.white, lineWidth: 2))
}).padding(.bottom, 20)
}
}.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// SWBAmenitieCollectionViewCell.swift
// SweepBright
//
// Created by Kaio Henrique on 1/12/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import UIKit
class SWBAmenityCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textAmenity: UILabel!
@IBOutlet weak var selectedSwitch: SWBSwitch!
var amenity: SWBAmenity! {
didSet {
self.imageView?.image = amenity.icon
self.textAmenity.text = amenity.title
}
}
}
|
//
// QuoteModel.swift
// Module2-16 wrap-up
//
// Created by Yasuko Kurata on 2021-02-05.
//
import Foundation
class AuthorModel: ObservableObject {
@Published var authors = [Author]()
init() {
self.authors = DataService.getLocalData()
}
}
|
//
// Constants.swift
// ContainerViewSlideMenu
//
// Created by Shakti Pratap Singh on 30/07/16.
// Copyright © 2016 Shakti Pratap Singh. All rights reserved.
//
import Foundation
class Constants{
enum ApiSearchQueries : String{
case apiKey = "ce7724b78a09f5436d559f3e56ad4ffa"
enum MovieRelated : String{
case popularMovies = "https://api.themoviedb.org/3/movie/popular"
case topRatedMovies = "https://api.themoviedb.org/3/movie/top_rated"
case upcomingMovies = "https://api.themoviedb.org/3/movie/upcoming"
}
enum TvRelated:String{
case airedToday="https://api.themoviedb.org/3/tv/airing_today"
case onTheAir="https://api.themoviedb.org/3/tv/on_the_air"
case latest="https://api.themoviedb.org/3/tv/latest"
case topRated="https://api.themoviedb.org/3/tv/top_rated"
case popular="https://api.themoviedb.org/3/tv/popular"
}
enum CelebsRelated:String {
case popular = "https://api.themoviedb.org/3/person/popular"
case latest = "https://api.themoviedb.org/3/person/latest"
}
}
struct viewControllerIdentifiers{
static let rightSliderVc = "app_right"
static let homeVc = "home"
static let homeMainVc = "home_main"
static let moviesVc = "movies"
static let moviesMainVc = "movie_main"
static let requestedMoviesVc = "movies_list"
static let tvVc = "tv"
static let tvMainVc = "tv_main"
static let requestedTvVc = "tv_list"
static let celebsVc = "celebs"
static let celebsMainVc = "celebs_main"
static let requestedCelebsVc = "celebs_list"
}
struct cellIdentifiers{
static let homePopularMovieCell = "home_movie_cell"
static let homePopularTvCell = "home_tv_cell"
static let homePopularCelebsCell = "home_celeb_cell"
static let homeMainTableViewCell = "table_cell"
static let homeMainCollectionCellEmbeddedInTableCell = "collection_cell"
static let movieMainCollectionCell = "popular_movie_cell"
static let movieMainTableCell = "movie_table_cell"
static let tvMainCollectionCell = "popular_tv_cell"
static let tvMainTableCell = "tv_table_cell"
static let celebsMainCollectionCell = "popular_celebs_cell"
static let celebsMainTableCell = "celebs_table_cell"
static let requestedListMovieCell = "movies_cell"
static let requestedListTvCell = "tv_show_cell"
static let requestedListCelebsCell = "celebs_cell"
}
struct imageIdentifiers{
static let rightOptionMenuButtonImage = "si0010s"
static let placeHolderImage = "placeHolderImage"
}
struct imageUrls{
static let baseImageUrl = "http://image.tmdb.org/t/p/w500"
}
}
|
//: Playground - noun: a place where people can play
import Cocoa
//
//for i in 1...100 where i % 3 == 0 {
//
// print("FIZZ")
//
// }
//
//for i in 1...100 where i % 5 == 0 {
//
// print("BUZZ")
//
//}
var number: Int = 1
var fizz = 0
var buzz = 0
while number > 0 {
if number == 101 {
break
}
if number % 3 == 0 {
print("FIZZ")
}
if number % 5 == 0 {
print("BUZZ")
}
if number % 3 == 0 && number % 5 == 0 {
print("FIZZ BUZZ")
}
if number > 0 {
print(number)
number += 1
}
} |
//
// FormatCheckCell.swift
// one-note
//
// Created by zuber on 2018/9/10.
// Copyright © 2018年 duzhe. All rights reserved.
//
import UIKit
protocol FormatCheckCellDelegate: class {
func formatCheckCell(_ cell: FormatCheckCell,type: RichTextFormatView.RowType ,sigleCheckedAt index: Int, value: CheckView.CheckValue)
func formatCheckCell(_ cell: FormatCheckCell,type: RichTextFormatView.RowType ,mutipleCheckedAt index: Int, value: CheckView.CheckValue, checked: Bool)
}
class FormatCheckCell: UITableViewCell {
@IBOutlet private weak var leftLabel: UILabel!
@IBOutlet private weak var rightLabel: UILabel!
@IBOutlet private weak var checkView: CheckView!
weak var delegate: FormatCheckCellDelegate?
var rightValue: String = "" {
didSet{
rightLabel.text = rightValue
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
leftLabel.style(.cellName("label"))
checkView.delegate = self
rightValue = ""
rightLabel.font = UIFont.lightOf(15)
rightLabel.textColor = UIColor.body
}
var type: RichTextFormatView.RowType?
func config(_ type: RichTextFormatView.RowType){
self.type = type
checkView.allowCancelCheck = type.allowCancel
checkView.allowMutipleSelected = type.allowMutipleSelected
checkView.groups = type.group
checkView.reloadItems()
leftLabel.text = type.title
switch type {
case .size:
rightLabel.isHidden = false
default:
rightLabel.isHidden = true
}
}
// 设置字体大小
func setFontSize(_ size: CGFloat){
rightValue = "\(Int(size))"
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.rightLabel.transform = CGAffineTransform.identity.scaledBy(x: 1.2, y: 1.2)
}) { _ in
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.rightLabel.transform = CGAffineTransform.identity
})
}
}
}
// MARK: - CheckViewDelegate
extension FormatCheckCell: CheckViewDelegate {
func checkView(_ view: CheckView, sigleCheckedAt index: Int, value: CheckView.CheckValue) {
guard let type = type else { return }
delegate?.formatCheckCell(self, type: type, sigleCheckedAt: index, value: value)
}
func checkView(_ view: CheckView, mutipleCheckedAt index: Int, value: CheckView.CheckValue, checked: Bool) {
guard let type = type else { return }
delegate?.formatCheckCell(self, type: type, mutipleCheckedAt: index, value: value, checked: checked)
}
}
|
//
// Constants.swift
// TimeBook
//
// Created by Hoang Duc on 7/26/19.
// Copyright © 2019 Hoang Duc. All rights reserved.
//
import UserNotifications
import Foundation
import CoreData
public class Config {
public static let MeditationNumber = 6
public static let defaults = UserDefaults.standard
// Request to push local notification
public static func requestNotification() {
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .badge, .sound])
{ (granted, error) in
defaults.set(granted, forKey: "notification")
}
}
// Check notification granted or not
public static func notificationGranted() -> Bool {
return defaults.bool(forKey: "notification")
}
public static func pushNotification(hour: Hour, contents: String) {
if !notificationGranted() {
requestNotification()
}
var dateComponents = DateComponents()
switch hour {
case .H1030h:
dateComponents.hour = 10
dateComponents.minute = 30
break
case .H12h:
dateComponents.hour = 12
dateComponents.minute = 00
break
case .H15h:
dateComponents.hour = 15
dateComponents.minute = 00
break
case .H17h:
dateComponents.hour = 17
dateComponents.minute = 00
break
case .H20h:
dateComponents.hour = 20
dateComponents.minute = 00
break
case .H8h:
dateComponents.hour = 8
dateComponents.minute = 00
break
}
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Set notification's content
let content = UNMutableNotificationContent()
content.title = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
content.body = contents
content.sound = .default
content.badge = 1
let request = UNNotificationRequest(
identifier: hour.rawValue, content: content, trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
// This for save data
extension Config {
// // Init list of meditation
// public static func loadListChamNgon() -> [String] {
// if isTheFirstTime() {
// // Init list cham ngon
// var listChamNgon:[String] = [String]()
// for n in 0...9 {
// listChamNgon.insert(ChamNgon.allValues[n].rawValue, at: 0)
// }
// defaults.set(listChamNgon, forKey: "listChamNgon")
// }
// return defaults.object(forKey: "listChamNgon") as! [String]
// }
public static func loadListMeditationByHour() -> [String] {
if isTheFirstTime() {
// Init list MeditationByHour
var listChinh:[String] = [String]()
for n in 0...5 {
listChinh.append(ChamNgon.allValues[n].rawValue)
}
saveListMeditation(listChinh: listChinh)
}
var listChinh:[String] = [String]()
listChinh = defaults.object(forKey: "listMeditationByHour") as! [String]
return listChinh
}
public static func saveListMeditation(listChinh: [String]) {
defaults.set(listChinh, forKey: "listMeditationByHour")
for n in 0...5 {
pushNotification(hour: Hour.allValues[n], contents: listChinh[n])
}
}
public static func isTheFirstTime() -> Bool {
// return true
return !defaults.bool(forKey: "first")
}
public static func didNotFirst() {
if isTheFirstTime() {
defaults.set(false, forKey: "first")
}
}
}
public enum Hour:String {
case H8h = "8:00"
case H12h = "12:00"
case H1030h = "10:30"
case H15h = "15:00"
case H17h = "17:00"
case H20h = "20:00"
public static let allValues:[Hour] = [.H8h,.H1030h,.H12h,.H15h,.H17h,.H20h]
}
public enum ChamNgon: String {
case cau1 = "命を大事にする"
case cau2 = "他人のものを尊重する"
case cau3 = "他人の関係を尊重する"
case cau4 = "真実を話す"
case cau5 = "人を繋げる発言をする"
case cau6 = "優しく話す"
case cau7 = "意味のある発言をする"
case cau8 = "他人の喜びを喜ぶ"
case cau9 = "他人の問題に親身になる"
case cau10 = "ペンをよく理解する"
public static let allValues:[ChamNgon] = [.cau1,.cau2,.cau3,.cau4,.cau5,.cau6,.cau7,.cau8,.cau9,.cau10]
}
|
//
// ZDepths.swift
// SpaceShooter
//
// Created by Luke Deerinck on 7/22/19.
// Copyright © 2019 Chuck Deerinck. All rights reserved.
//
import CoreGraphics
//these are zPosition values for node types
let backgroundZDepth:CGFloat = 0
let asteroidZPDepth:CGFloat = 1
let bulletZDepth:CGFloat = 2
let mineZDepth:CGFloat = 3
let bombZDepth:CGFloat = 4
let shipZDepth:CGFloat = 5
|
//
// XRPAmount.swift
//
// Created by Mitch Lang on 5/23/19.
//
import Foundation
public enum XRPAmountError: Error {
case invalidAmount
}
public struct XRPAmount {
private(set) var drops: Int!
public init(drops: Int) throws {
if drops < 0 || drops > UInt64(100000000000000000) {
throw XRPAmountError.invalidAmount
}
self.drops = drops
}
public init(_ text: String) throws {
// removed commas
let stripped = text.replacingOccurrences(of: ",", with: "")
if !stripped.replacingOccurrences(of: ".", with: "").isNumber {
throw XRPAmountError.invalidAmount
}
// get parts
var xrp = stripped
var drops = ""
if let decimalIndex = stripped.firstIndex(of: ".") {
xrp = String(stripped.prefix(upTo: decimalIndex))
let _index = stripped.index(decimalIndex, offsetBy: 1)
drops = String(stripped.suffix(from: _index))
}
// adjust values
drops = drops + String.init(repeating: "0", count: 6-drops.count)
// combine parts
let _drops = Int(xrp+drops)!
if _drops < 0 || _drops > UInt64(100000000000000000) {
throw XRPAmountError.invalidAmount
}
self.drops = _drops
}
public func prettyPrinted() -> String {
let drops = self.drops%1000000
let xrp = self.drops/1000000
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let formattedNumber = numberFormatter.string(from: NSNumber(value: xrp))!
let leadingZeros: [Character] = Array(repeating: "0", count: 6 - String(drops).count)
return formattedNumber + "." + String(leadingZeros) + String(drops)
}
}
|
//
// UpdateProfileTableViewController.swift
// UPK-GE01
//
// Created by zhongzhong.cao on 2019/7/31.
// Copyright © 2019 umehealltd. All rights reserved.
//
import UIKit
class UpdateProfileTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Update your profile"
self.tabBarController?.hidesBottomBarWhenPushed = true
self.tabBarController?.tabBar.isHidden = true
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.view.frame.height
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell.init(style: .default , reuseIdentifier: nil)
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let ProfileLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 130))
ProfileLabel.backgroundColor = .green
cell.contentView.addSubview(ProfileLabel)
let ProfileImage = UIImageView.init(frame: CGRect(x: self.view.frame.width/2 - 25, y: 30, width: 50, height: 50))
//PadImage.backgroundColor = .green
ProfileImage.image = UIImage(named: "pic1")
ProfileImage.layer.cornerRadius = ProfileImage.frame.size.height/2
ProfileImage.clipsToBounds = true
cell.contentView.addSubview(ProfileImage)
let ProfileLabel1 = UILabel.init(frame: CGRect(x: 0, y: 90, width: self.view.frame.width, height: 30))
// ProfileLabel1.backgroundColor = .green
ProfileLabel1.text = "13016490924"
ProfileLabel1.textAlignment = .center
cell.contentView.addSubview(ProfileLabel1)
let ProfileLabel2 = UILabel.init(frame: CGRect(x: 10, y: 135, width: self.view.frame.width - 20 , height: 40))
// ProfileLabel1.backgroundColor = .green
ProfileLabel2.text = "Your profile info will help RelieforMe to provide more customized program recommendations just for you"
ProfileLabel2.textAlignment = .left
ProfileLabel2.numberOfLines = 2
ProfileLabel2.textColor = UIColor.orange
ProfileLabel2.font = ProfileLabel2.font.withSize(14)
cell.contentView.addSubview(ProfileLabel2)
let NameImage = UIImageView.init(frame: CGRect(x: 10, y: 190, width: 28, height: 23))
NameImage.image = UIImage(named: "pic")
cell.contentView.addSubview(NameImage)
let NameLabel = UILabel.init(frame: CGRect(x:38, y: 180, width: self.view.frame.width - 250, height: 40))
NameLabel.text = " First Name"
NameLabel.textAlignment = .left
cell.contentView.addSubview(NameLabel)
let NameField = UITextField(frame: CGRect(x: self.view.frame.width - 220, y: 180, width: 200, height: 40))
NameField.borderStyle = .line
NameField.placeholder = "zzzzzzz"
self.view.addSubview(NameField)
let GenderImage = UIImageView.init(frame: CGRect(x: 10, y: 235, width: 28, height: 23))
GenderImage.image = UIImage(named: "pic")
cell.contentView.addSubview(GenderImage)
let GenderLabel = UILabel.init(frame: CGRect(x:38, y: 225, width: self.view.frame.width - 250, height: 40))
GenderLabel.text = " Gender"
GenderLabel.textAlignment = .left
cell.contentView.addSubview(GenderLabel)
let GenderButton = UIButton.init(frame: CGRect(x: self.view.frame.width - 220, y: 225, width: 200, height: 40))
GenderButton.setTitle("Male", for: .normal)
GenderButton.setTitleColor(UIColor.black, for: .normal)
GenderButton.contentHorizontalAlignment = .right
GenderButton.addTarget(self, action: #selector(GenderButton_select), for: .touchUpInside)
cell.contentView.addSubview(GenderButton)
let BirthdayImage = UIImageView.init(frame: CGRect(x: 10, y: 280, width: 28, height: 23))
BirthdayImage.image = UIImage(named: "pic")
cell.contentView.addSubview(BirthdayImage)
let BirthdayLabel = UILabel.init(frame: CGRect(x:38, y: 270, width: self.view.frame.width - 250, height: 40))
BirthdayLabel.text = " Birthday"
BirthdayLabel.textAlignment = .left
cell.contentView.addSubview(BirthdayLabel)
let BirthdayButton = UIButton.init(frame: CGRect(x: self.view.frame.width - 220, y: 270, width: 200, height: 40))
BirthdayButton.setTitle("1994-04-19", for: .normal)
BirthdayButton.setTitleColor(UIColor.black, for: .normal)
BirthdayButton.contentHorizontalAlignment = .right
BirthdayButton.addTarget(self, action: #selector(BirthdayButton_select), for: .touchUpInside)
cell.contentView.addSubview(BirthdayButton)
let WeightImage = UIImageView.init(frame: CGRect(x: 10, y: 325, width: 28, height: 23))
WeightImage.image = UIImage(named: "pic")
cell.contentView.addSubview(WeightImage)
let WeightLabel = UILabel.init(frame: CGRect(x:38, y: 315, width: self.view.frame.width - 250, height: 40))
WeightLabel.text = " Weight"
WeightLabel.textAlignment = .left
cell.contentView.addSubview(WeightLabel)
let button_Save = UIButton.init(frame: CGRect(x: 10, y: 560, width: self.view.frame.width - 20, height: 40))
button_Save.backgroundColor = UIColor(red: 9/255.0, green: 187/255.0, blue: 7/255.0, alpha: 1)
// button_next.setImage(UIImage(named: "pic"), for: .normal)
button_Save.setTitle("SAVE", for: .normal)
//button_next.addTarget(self, action: #selector(buttonAction_save), for: .touchUpInside)
//button.setImage("pic", for: UIControl.State)
cell.contentView.addSubview(button_Save)
return cell
}
@objc func GenderButton_select(button: UIButton){
let menu = UIAlertController(title: "Select", message: "", preferredStyle: .alert)
let option1 = UIAlertAction(title: "Male", style: .default, handler: nil)
let option2 = UIAlertAction(title: "Female", style: .default, handler: nil)
let option3 = UIAlertAction(title: "Confidential", style: .default, handler: nil)
//let option4 = UIAlertAction(title: "OK", style: .default, handler: nil)
menu.addAction(option1)
menu.addAction(option2)
menu.addAction(option3)
self.present(menu, animated: true, completion: nil)
}
@IBAction func BirthdayButton_select(sender: AnyObject) {
let alertController:UIAlertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 250, height: 300))
datePicker.locale = NSLocale(localeIdentifier: "en_US") as Locale
datePicker.datePickerMode = .date
// set default time
datePicker.date = NSDate() as Date
// 响应事件(只要滚轮变化就会触发)
// datePicker.addTarget(self, action:Selector("datePickerValueChange:"), forControlEvents: UIControlEvents.ValueChanged)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:nil))
/*{
(alertAction)->Void in
print("date select: \(datePicker.date.description)")
获取上一节中自定义的按钮外观DateButton类,设置DateButton类属性thedate
let myDateButton=self.Datebutt as? DateButton
myDateButton?.thedate=datePicker.date
强制刷新
myDateButton?.setNeedsDisplay()
})*/
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel,handler:nil))
alertController.view.addSubview(datePicker)
self.present(alertController, animated: true, completion: nil)
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// BussinessBottomSheetViewController.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/24/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import YelpAPI
import CDYelpFusionKit
import MapKit
import Parse
class BusinessBottomSheetViewController: UIViewController {
// holdView can be UIImageView instead
@IBOutlet weak var holdView: UIView!
//@IBOutlet weak var left: UIButton!
@IBOutlet weak var right: UIButton!
@IBOutlet weak var businessImage: UIImageView!
@IBOutlet weak var businessNameLabel: UILabel!
@IBOutlet weak var displayAddr1: UILabel!
@IBOutlet weak var displayAddr2: UILabel!
@IBOutlet weak var reviewImage: UIImageView!
@IBOutlet weak var reviewCountLabel: UILabel!
@IBOutlet weak var ratingsCountLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var ratingTotalLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var addPriceSymbolLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
let fullView: CGFloat = 100
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var openNowLabel: UILabel!
var business: CDYelpBusiness!
var businesses: [CDYelpBusiness]!
override func viewDidLoad() {
super.viewDidLoad()
registerForNotifications()
if business != nil {
if business.name != nil {
businessNameLabel.text = "\((business?.name)!)"
}
if let reviewCount = business?.reviewCount {
if (reviewCount == 1) {
reviewCountLabel.text = "\(reviewCount) \(Constants.BusinessLabels.reviewLabel)"
} else {
reviewCountLabel.text = "\(reviewCount) \(Constants.BusinessLabels.reviewsLabel)"
}
}
self.right.addTarget(self, action: #selector(DetailViewController().onTripAdd), for: .touchDown)
//self.right.addTarget(self, action: #selector(self.onSavePlace), for: .allTouchEvents)
if let businessImageUrl = business.imageUrl {
// imageView?.setImageWith(businessImageUrl)
let backgroundImageView = UIImageView()
let backgroundImage = UIImage()
backgroundImageView.setImageWith(businessImageUrl)
businessImage.image = backgroundImageView.image//setImageWith(businessImageUrl)
businessImage.contentMode = .scaleAspectFill
businessImage.clipsToBounds = true
}
if let bussinessAddr = business.location?.displayAddress {
displayAddr1.text = bussinessAddr[0]
displayAddr2.text = bussinessAddr[1]
}
if let bussinessAddr = business.location?.addressOne {
print("bussinessAddr \(bussinessAddr)")
print("bussinessAddr2 \(business.location?.addressTwo)")
print("bussinessAddr3 \(business.location?.addressThree)")
print("bussinessAddr \(business.location?.displayAddress?.count)")
for da in (business.location?.displayAddress)! {
print("da \(da)")
}
}
if let phone = business.displayPhone {
phoneLabel.text = "\(phone)"
print("display phone \(business.displayPhone)")
}
if let price = business.price {
var nDollar = price.count
var missingDollar = 4-nDollar
var labelDollar = "$"
var mPrice = ""
for i in 0..<missingDollar {
mPrice += labelDollar
}
priceLabel.text = "\(price)"
addPriceSymbolLabel.text = "\(mPrice)"
}
else {
priceLabel.isHidden = true
addPriceSymbolLabel.isHidden = true
}
//print("business.distance \(business.distance)")
if let distance = business.distance {
var distInMiles = Double.init(distance as! NSNumber) * 0.000621371
distanceLabel.text = String(format: "%.2f", distInMiles)
}
if let closed = business.isClosed {
///openNowLabel.textColor = closed ? UIColor.red : UIColor.green
openNowLabel.text = closed ? "Closed" : "Open"
if !closed {
if let hours = business.hours {
}
}
if let photos = business.photos {
for p in photos {
print("photos \(p)")
}
}
if let hours = business.hours {
let date = Date()
let calendar = Calendar.current
let dayOfWeek = calendar.component(.weekday, from: date)
for hour in hours {
let textLabel = UILabel()
textLabel.textColor = hour.isOpenNow! ? UIColor.green : UIColor.red
textLabel.text = hour.isOpenNow! ? "Open" : "Closed"
let hourOpen = hour.open
let textLabelExt = UILabel()
textLabelExt.text = ""
for day in hourOpen! {
if (dayOfWeek-1) == day.day! {
print("hours end \(day.end)")
var timeString = day.end as! String
timeString.insert(":", at: (timeString.index((timeString.startIndex), offsetBy: 2)))
print("timeString \(timeString)")
/* let dateAsString = timeString
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let hourClose = dateFormatter.date(from: dateAsString)
print("hourClose \(hourClose)")
dateFormatter.dateFormat = "h:mm a"
let date12 = dateFormatter.string(from: date)
//let hourClose = day.end!*/
textLabelExt.text = hour.isOpenNow! ? " untill \(amAppend(str: timeString))" : ""
}
}
openNowLabel.text = "\(textLabel.text!) \(textLabelExt.text!)"
print("dayOfWeek\(dayOfWeek)")
if hour.isOpenNow! {
/// if let hours = business.hours {
//}
for h in hours {
print("hours \(h.hoursType)")
print("hours \(h.isOpenNow)")
print("hours \(h.open)")
for ho in h.open! {
print("hours \(ho.day)")
print("hours \(ho.end)")
print("hours \(ho.isOvernight)")
print("hours \(ho.toJSONString())")
}
}
}
}
}
if let ratingsCount = business.rating {
if ratingsCount == 0 {
reviewImage.image = UIImage(named: "0star")
}
else if ratingsCount > 0 && ratingsCount <= 1 {
reviewImage.image = UIImage(named: "1star")
}
else if ratingsCount > 1 && ratingsCount <= 1.5 {
reviewImage.image = UIImage(named: "1halfstar")
}
else if ratingsCount > 1.5 && ratingsCount <= 2 {
reviewImage.image = UIImage(named: "2star")
}
else if ratingsCount > 2 && ratingsCount <= 2.5 {
reviewImage.image = UIImage(named: "2halfstar")
}
else if ratingsCount > 2.5 && ratingsCount <= 3 {
reviewImage.image = UIImage(named: "3star")
}
else if ratingsCount > 3 && ratingsCount <= 3.5 {
reviewImage.image = UIImage(named: "3halfstar")
}
else if ratingsCount > 3.5 && ratingsCount <= 4 {
reviewImage.image = UIImage(named: "4star")
}
else if ratingsCount > 4 && ratingsCount <= 4.5 {
reviewImage.image = UIImage(named: "4halfstar")
}
else {
reviewImage.image = UIImage(named: "5star")
}
if !(ratingsCount.isLess(than: 4.0)) {
ratingsCountLabel.backgroundColor = UIColor(red: 39/255, green: 190/255, blue: 73/255, alpha: 1)
ratingTotalLabel.backgroundColor = UIColor(red: 39/255, green: 190/255, blue: 73/255, alpha: 1)
}
else if !(ratingsCount.isLess(than: 3.0)) && (ratingsCount.isLess(than: 4.0)) {
ratingsCountLabel.backgroundColor = UIColor.orange
ratingTotalLabel.backgroundColor = UIColor.orange
}
else {
ratingsCountLabel.backgroundColor = UIColor.yellow
ratingTotalLabel.backgroundColor = UIColor.yellow
}
let labelString = UILabel()
labelString.font = UIFont.boldSystemFont(ofSize: 5)
labelString.text = "5"
ratingsCountLabel.text = "\(business.rating!)" + " / " //+ labelString.text!
}
}
}
// roundViews()
}
func amAppend(str:String) -> String{
var temp = str
var strArr = str.characters.split{$0 == ":"}.map(String.init)
var hour = Int(strArr[0])!
var min = Int(strArr[1])!
if(hour > 12){
temp = temp + " PM"
}
else{
temp = temp + " AM"
}
return temp
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
self.loadViewIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.6, animations: { [weak self] in
let frame = self?.view.frame
// let yComponent = self?.partialView
// self?.view.frame = CGRect(x: 0, y: yComponent!, width: frame!.width, height: frame!.height)
})
}
func registerForNotifications() {
// Register to receive Businesses
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "BussinessUpdate"),
object: nil, queue: OperationQueue.main) {
[weak self] (notification: Notification) in
self?.business = notification.userInfo!["business"] as! CDYelpBusiness
//self?.addAnnotationFor(businesses: (self?.businesses)!)
print("self?.business id in nitofocation \(self?.business.id)")
print("self?.business photod in nitofocation \(self?.business.photos?.count)")
self?.view.setNeedsDisplay()
//self?.tableView.reloadData()
//self?.collectionView.reloadData()
//self?.mapView.reloadInputViews()
}
}
// @IBAction
func onAddRemoveTrip(_ sender: Any) {
print("onAddRemoveTrip")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
print("businesses \(businesses)")
if(businesses == nil) {
let createTripViewController = storyboard.instantiateViewController(withIdentifier: "CreateTripViewController") as! CreateTripViewController
createTripViewController.startTextField.text = "Current Location"
createTripViewController.destinationTextField.text = (self.business.location?.displayAddress![0])! + " " + (self.business.location?.displayAddress![1])!
navigationController?.pushViewController(createTripViewController, animated: true)
}
else {
let routeMapViewController = storyboard.instantiateViewController(withIdentifier: "RouteMapView") as! RouteMapViewController
let selectedLoc = self.business.coordinates
let currentLocMapItem = MKMapItem.forCurrentLocation()
var coord = CLLocationCoordinate2D.init(latitude: (selectedLoc?.latitude)!, longitude: (selectedLoc?.longitude)!)
let selectedPlacemark = MKPlacemark(coordinate: coord, addressDictionary: nil)
let selectedMapItem = MKMapItem(placemark: selectedPlacemark)
let mapItems = [selectedMapItem, currentLocMapItem]
var placemark = MKPlacemark(coordinate: coord)
let addMapItem = MKMapItem(placemark: placemark)
let intermediateLocation = CLLocation.init(latitude: placemark.coordinate.latitude, longitude: placemark.coordinate.longitude)
let intermediateSegment = TripSegment(name: placemark.title!, address: "Temp Address", geoPoint: PFGeoPoint(location: intermediateLocation))
//self.trip?.addSegment(tripSegment: intermediateSegment)
let selectedPlace = Places(cllocation: CLLocation.init(latitude: placemark.coordinate.latitude, longitude: placemark.coordinate.longitude)
, distance: 0, coordinate: placemark.coordinate)
//selectedPlace.calculateDistance(fromLocation: startPlace.cllocation)
routeMapViewController.placestops.append(selectedPlace)
routeMapViewController.placestops.sort(by: { ($0.distance?.isLess(than: $1.distance! ))! })
var stopIndex = 0
for i in 0...routeMapViewController.placestops.count-1 {
// if placestops[i].coordinate.latitude == placemark.coordinate.latitude && placestops[i].coordinate.longitude == placemark.coordinate.longitude {
stopIndex = i
break
//}
}
// locationArray.insert((textField: UITextField(), mapItem: addMapItem), at: stopIndex)
//self.mapView.removeOverlays(self.mapView.overlays)
// routeMapViewController.calculateSegmentDirections(index: 0, time: 0, routes: [])
// routeMapViewController.locationArray = locationArray
// routeMapViewController.trip = trip
navigationController?.pushViewController(routeMapViewController, animated: true)
}
}
@IBAction func onSavePlace(_ sender: Any) {
print("onSavePlace")
}
func prepareBackgroundView(){
let blurEffect = UIBlurEffect.init(style: .dark)
let visualEffect = UIVisualEffectView.init(effect: blurEffect)
let bluredView = UIVisualEffectView.init(effect: blurEffect)
bluredView.contentView.addSubview(visualEffect)
visualEffect.frame = UIScreen.main.bounds
bluredView.frame = UIScreen.main.bounds
view.insertSubview(bluredView, at: 0)
}
}
|
// KeyedDecodingContainerExtensionsTests.swift - Copyright 2020 SwifterSwift
import XCTest
@testable import SwifterSwift
private struct Video: Decodable {
let isPlaying: Bool
let isFullScreen: Bool?
private enum CodingKeys: CodingKey {
case isPlaying
case isFullScreen
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
isPlaying = try container.decodeBoolAsIntOrString(forKey: .isPlaying)
isFullScreen = try container.decodeBoolAsIntOrStringIfPresent(forKey: .isFullScreen)
}
}
final class KeyedDecodingContainerTests: XCTestCase {
func testDecodeBoolAsIntOrStringDataAsIntSuccessful() {
let isPlayingAndIsFullScreenAsInt = #"{"isPlaying": 1, "isFullScreen": 0}"#
let data = mockJsonData(from: isPlayingAndIsFullScreenAsInt)
let video = try! JSONDecoder().decode(Video.self, from: data) // swiftlint:disable:this force_try
XCTAssert(video.isPlaying)
XCTAssertEqual(video.isFullScreen, false)
}
func testDecodeBoolAsIntOrStringDataAsStringSuccessful() {
let isPlayingAndIsFullScreenAsString = #"{"isPlaying": "true", "isFullScreen": "false"}"#
let data = mockJsonData(from: isPlayingAndIsFullScreenAsString)
let video = try! JSONDecoder().decode(Video.self, from: data) // swiftlint:disable:this force_try
XCTAssert(video.isPlaying)
XCTAssertEqual(video.isFullScreen, false)
}
func testDecodeBoolAsIntOrStringDataAsBoolSuccessful() {
let isPlayingAndIsFullScreenAsBool = #"{"isPlaying": true, "isFullScreen": false}"#
let data = mockJsonData(from: isPlayingAndIsFullScreenAsBool)
let video = try! JSONDecoder().decode(Video.self, from: data) // swiftlint:disable:this force_try
XCTAssert(video.isPlaying)
XCTAssertEqual(video.isFullScreen, false)
}
func testDecodeBoolAsIntOrStringIfPresentSuccessful() {
let isPlayingAsIntAndIsFullScreenNotPresent = #"{"isPlaying": 0}"#
let data = mockJsonData(from: isPlayingAsIntAndIsFullScreenNotPresent)
let video = try! JSONDecoder().decode(Video.self, from: data) // swiftlint:disable:this force_try
XCTAssertFalse(video.isPlaying)
XCTAssertNil(video.isFullScreen)
}
func testDecodeBoolAsIntOrStringThrowsError() {
let isPlayingAndIsFullScreenTypeMismatch = #"{"isPlaying": [1], "isFullScreen": ["true"]}"#
let data = mockJsonData(from: isPlayingAndIsFullScreenTypeMismatch)
XCTAssertThrowsError(try JSONDecoder().decode(Video.self, from: data))
}
private func mockJsonData(from json: String) -> Data {
return Data(json.utf8)
}
}
|
//
// VideoViewController.swift
// PetsNPals
//
// Created by Isaiah Sylvester on 2021-04-14.
//
import UIKit
class VideoViewController: UIViewController {
@IBOutlet weak var videoTableView: UITableView!
var posts: [VideoPost] = []
override func viewDidLoad() {
super.viewDidLoad()
posts = createArray()
}
func createArray() -> [VideoPost] {
var tempPosts: [VideoPost] = []
let post1 = VideoPost(vid: URLRequest(url: URL(string: "https://www.youtube.com/embed/N2iDeGiY9Xw")!), title: "New Puppy Tips - Surviving the First Week")
let post2 = VideoPost(vid: URLRequest(url: URL(string: "https://www.youtube.com/embed/ZipzqCphi8s")!), title: "The Science of Dogs")
tempPosts.append(post1)
tempPosts.append(post2)
return tempPosts
}
}
extension VideoViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 400
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let video = posts[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoPostTableViewCell") as! VideoPostTableViewCell
cell.setVideo(vid: video)
return cell
}
}
|
//
// ProfileViewController.swift
// TestApp
//
// Created by ALEKSANDR KUNDRYUKOV on 28.03.2020.
// Copyright © 2020 ALEKSANDR KUNDRYUKOV. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
let profilePropertyCellId = "PROFILE_PROPERTY_CELL"
var profileModelController: ProfileModelController
var propertiesTableView: UITableView!
// MARK: - Events
required init(_ modelController: ProfileModelController) {
profileModelController = modelController
super.init(nibName: nil, bundle: nil)
}
required init(coder: NSCoder) {
fatalError("Error: NSCoder is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
showView()
showNavigationBar()
showProfilePropertiesTable()
profileModelController.loadProfileAsync {
self.profileModelController.isProfileLoaded = true
self.reloadProfilePropertiesTable()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if profileModelController.isProfileLoaded {
reloadProfilePropertiesTable()
}
}
@objc func editNavButtonPressed() {
showEditProfileScreen()
}
// MARK: - Actions
func showView() {
view.backgroundColor = .white
}
func showEditProfileScreen() {
let editProfileModelController = EditProfileModelController(profileModelController.profile, delegate: profileModelController)
let editProfileViewController = EditProfileViewController(editProfileModelController)
navigationController?.pushViewController(editProfileViewController, animated: true)
}
func showNavigationBar() {
if let navigationBar = navigationController?.navigationBar {
navigationBar.topItem?.title = "Просмотр"
let editItem = UIBarButtonItem(title: "Редактировать", style: .plain, target: self,
action: #selector(editNavButtonPressed))
navigationBar.topItem?.rightBarButtonItem = editItem
}
}
func showProfilePropertiesTable() {
propertiesTableView = UITableView()
propertiesTableView.delegate = self
propertiesTableView.dataSource = self
propertiesTableView.translatesAutoresizingMaskIntoConstraints = false
propertiesTableView.register(PropertyViewCell.self, forCellReuseIdentifier: profilePropertyCellId)
view.addSubview(propertiesTableView)
propertiesTableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
propertiesTableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
propertiesTableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
propertiesTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func reloadProfilePropertiesTable() {
propertiesTableView.reloadData()
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension ProfileViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
profileModelController.getPropertiesCount()
}
// MARK: - Events
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: profilePropertyCellId) as! PropertyViewCell
showPropertyCell(cell: cell, indexPath: indexPath)
return cell
}
// MARK: - Actions
func showPropertyCell(cell: PropertyViewCell, indexPath: IndexPath) {
cell.selectionStyle = .none
cell.rowIndex = indexPath.row
cell.isEditableProperty = false
cell.delegate = self
let propertyData = profileModelController.getPropertyCellData(indexPath.row)
cell.updateCell(propertyData)
}
}
// MARK: - PropertyViewCellDelegate
extension ProfileViewController: PropertyViewCellDelegate {
// MARK: - Events
func propertyTextChanged(_ cell: PropertyViewCell, text: String, rowIndex: Int) {
// do nothing
}
// MARK: - Actions
func updatePropertyCellHeight(_ cell: PropertyViewCell) {
propertiesTableView.beginUpdates()
propertiesTableView.endUpdates()
}
}
|
//
// SportcastWeatherAPI.swift
// Sportcast
//
// Created by Alexandre Rubio on 7/10/17.
// Copyright © 2017 Alexandre Rubio. All rights reserved.
//
import UIKit
import CoreLocation
typealias ForecastJSON = [String: Any]
final class SportcastAPI: NSObject {
static var shared = SportcastAPI()
// Generate url of type: http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID={APIKEY}
// Call API with that url
// Return error or success with forecast information
func getWeather(range: WeatherRange, type: OpenWeatherAPISearchType, value: Any, completion: @escaping (Result<[ForecastJSON], APIError>) -> ()) {
guard let urlString = type.url(baseURL: K.API.BaseURL, value: value, range: range, apiKey: K.API.Key) else {
completion(.failure(.invalidParameter))
return
}
print("API CALL URL: \(urlString)")
guard let url = URL(string: urlString) else {
completion(.failure(.invalidURL(urlString)))
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
completion(.failure(.networkError(error!)))
return
}
guard let response = response as? HTTPURLResponse else {
completion(.failure(.noResponseError))
return
}
if response.statusCode != 200 {
completion(.failure(.unexpectedStatusCode(statusCode: response.statusCode)))
return
}
guard let data = data else {
completion(.failure(.noDataError))
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? ForecastJSON {
switch range {
case .current: completion(.success([json]))
case .threeHours:
if let list = json["list"] as? [ForecastJSON] {
completion(.success(list))
}
}
} else {
completion(.failure(.noDataError))
}
} catch let error {
completion(.failure(.jsonParseError(error)))
return
}
}.resume()
}
}
|
//
// SmartFeedsHomeView.swift
// Feedit
//
// Created by Tyler D Lawrence on 3/29/21.
//
import SwiftUI
import CoreData
import Combine
// MARK: DISCLOSURE GROUP STYLE
struct SmartFeedsHomeView: View {
@StateObject var rssFeedViewModel = RSSFeedViewModel(rss: RSS(), dataSource: DataSourceService.current.rssItem)
@StateObject var archiveListViewModel = ArchiveListViewModel(dataSource: DataSourceService.current.rssItem)
@StateObject var articles: AllArticles
@StateObject var unread: Unread
@State private var revealSmartFilters = true
private var allArticlesView: some View {
let rss = RSS()
return AllArticlesView(articles: AllArticles(dataSource: DataSourceService.current.rssItem), rssFeedViewModel: RSSFeedViewModel(rss: rss, dataSource: DataSourceService.current.rssItem))
}
private var archiveListView: some View {
ArchiveListView(viewModel: ArchiveListViewModel(dataSource: DataSourceService.current.rssItem), rssFeedViewModel: self.rssFeedViewModel)
}
private var unreadListView: some View {
UnreadListView(unreads: Unread(dataSource: DataSourceService.current.rssItem))
}
var body: some View {
DisclosureGroup(
isExpanded: $revealSmartFilters,
content: {
// Section(header: Text("Smart Feeds").font(.system(size: 18, weight: .medium, design: .rounded)).textCase(nil).foregroundColor(Color("text"))) {
HStack {
ZStack{
NavigationLink(destination: allArticlesView) {
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
HStack{
Image(systemName: "chart.bar.doc.horizontal")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 21, height: 21,alignment: .center)
// .foregroundColor(Color.red.opacity(0.8))
.foregroundColor(Color("tab").opacity(0.9))
Text("All Articles")
Spacer()
Text("\(articles.items.count)")
.font(.caption)
.fontWeight(.bold)
.padding(.horizontal, 7)
.padding(.vertical, 1)
.background(Color.gray.opacity(0.5))
.opacity(0.4)
.cornerRadius(8)
}.accentColor(Color("tab").opacity(0.9))
}
.onAppear {
self.articles.fecthResults()
}
}.listRowBackground(Color("accent"))
HStack {
ZStack{
NavigationLink(destination: unreadListView) {
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
HStack{
Image(systemName: "largecircle.fill.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 21, height: 21,alignment: .center)
.foregroundColor(Color("tab").opacity(0.9))
Text("Unread")
Spacer()
Text("\(unread.items.count)")
.font(.caption)
.fontWeight(.bold)
.padding(.horizontal, 7)
.padding(.vertical, 1)
.background(Color.gray.opacity(0.5))
.opacity(0.4)
.cornerRadius(8)
}.accentColor(Color("tab").opacity(0.8))
}.environment(\.managedObjectContext, Persistence.current.context)
.onAppear {
self.unread.fecthResults()
}
}.listRowBackground(Color("accent"))
HStack {
ZStack{
NavigationLink(destination: archiveListView) {
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
HStack{
Image(systemName: "star")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 21, height: 21,alignment: .center)
.foregroundColor(Color("tab").opacity(0.9))
// .foregroundColor(Color.yellow.opacity(0.8))
Text("Starred")
Spacer()
Text("\(archiveListViewModel.items.count)")
.font(.caption)
.fontWeight(.bold)
.padding(.horizontal, 7)
.padding(.vertical, 1)
.background(Color.gray.opacity(0.5))
.opacity(0.4)
.cornerRadius(8)
}
}
.accentColor(Color("tab").opacity(0.9))
.environment(\.managedObjectContext, Persistence.current.context)
.onAppear {
self.archiveListViewModel.fecthResults()
}
}.listRowBackground(Color("accent"))
},
label: {
HStack {
Text("Smart Feeds")
.font(.system(size: 18, weight: .regular, design: .rounded)).textCase(nil)
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.onTapGesture {
withAnimation {
self.revealSmartFilters.toggle()
}
}
}
})
// }.listStyle(InsetGroupedListStyle())
// .listRowBackground(Color("accent"))
.listRowBackground(Color("darkerAccent"))
.accentColor(Color("tab"))
}
}
struct SmartFeedsHomeView_Previews: PreviewProvider {
static let rss = RSS()
static var previews: some View {
NavigationView {
List {
SmartFeedsHomeView(rssFeedViewModel: RSSFeedViewModel(rss: rss, dataSource: DataSourceService.current.rssItem), archiveListViewModel: ArchiveListViewModel(dataSource: DataSourceService.current.rssItem), articles: AllArticles(dataSource: DataSourceService.current.rssItem), unread: Unread(dataSource: DataSourceService.current.rssItem))
.environmentObject(DataSourceService.current.rss)
.environmentObject(DataSourceService.current.rssItem)
.environment(\.managedObjectContext, Persistence.current.context)
.preferredColorScheme(.dark)
}
}
}
}
struct SmartFeedsSectionHomeView: View {
@StateObject var rssFeedViewModel = RSSFeedViewModel(rss: RSS(), dataSource: DataSourceService.current.rssItem)
@StateObject var archiveListViewModel = ArchiveListViewModel(dataSource: DataSourceService.current.rssItem)
@StateObject var articles: AllArticles
@StateObject var unread: Unread
@State private var revealSmartFilters = true
private var allArticlesView: some View {
let rss = RSS()
return AllArticlesView(articles: AllArticles(dataSource: DataSourceService.current.rssItem), rssFeedViewModel: RSSFeedViewModel(rss: rss, dataSource: DataSourceService.current.rssItem))
}
private var archiveListView: some View {
ArchiveListView(viewModel: ArchiveListViewModel(dataSource: DataSourceService.current.rssItem), rssFeedViewModel: self.rssFeedViewModel)
}
private var unreadListView: some View {
UnreadListView(unreads: Unread(dataSource: DataSourceService.current.rssItem))
}
@State var selectedFilter: FilterType
var body: some View {
Section(header: Text("Smart Feeds").font(.system(size: 18, weight: .medium, design: .rounded)).textCase(nil).foregroundColor(Color("text")).padding(.leading)) {
if selectedFilter == .all {
HStack {
ZStack{
NavigationLink(destination: allArticlesView) {
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
HStack{
Image(systemName: "chart.bar.doc.horizontal")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 21, height: 21,alignment: .center)
// .foregroundColor(Color.red.opacity(0.8))
.foregroundColor(Color("tab").opacity(0.9))
Text("All Articles")
Spacer()
Text("\(articles.items.count)")
.font(.caption)
.fontWeight(.bold)
.padding(.horizontal, 7)
.padding(.vertical, 1)
.background(Color.gray.opacity(0.5))
.opacity(0.4)
.cornerRadius(8)
}.accentColor(Color("tab").opacity(0.9))
}
.onAppear {
self.articles.fecthResults()
}
}//.listRowBackground(Color("accent"))
} else {
self.hidden(true)
}
if selectedFilter == .unreadIsOn {
HStack {
ZStack{
NavigationLink(destination: unreadListView) {
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
HStack{
Image(systemName: "largecircle.fill.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 21, height: 21,alignment: .center)
.foregroundColor(Color("tab").opacity(0.9))
Text("Unread")
Spacer()
Text("\(unread.items.count)")
.font(.caption)
.fontWeight(.bold)
.padding(.horizontal, 7)
.padding(.vertical, 1)
.background(Color.gray.opacity(0.5))
.opacity(0.4)
.cornerRadius(8)
}.accentColor(Color("tab").opacity(0.8))
}.environment(\.managedObjectContext, Persistence.current.context)
.onAppear {
self.unread.fecthResults()
}
}//.listRowBackground(Color("accent"))
} else {
self.hidden(true)
}
if selectedFilter == .isArchive {
HStack {
ZStack{
NavigationLink(destination: archiveListView) {
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
HStack{
Image(systemName: "star")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 21, height: 21,alignment: .center)
.foregroundColor(Color("tab").opacity(0.9))
// .foregroundColor(Color.yellow.opacity(0.8))
Text("Starred")
Spacer()
Text("\(archiveListViewModel.items.count)")
.font(.caption)
.fontWeight(.bold)
.padding(.horizontal, 7)
.padding(.vertical, 1)
.background(Color.gray.opacity(0.5))
.opacity(0.4)
.cornerRadius(8)
}
}
.accentColor(Color("tab").opacity(0.9))
.environment(\.managedObjectContext, Persistence.current.context)
.onAppear {
self.archiveListViewModel.fecthResults()
}
}
//.listRowBackground(Color("accent"))
} else {
self.hidden(true)
}
}.listStyle(InsetGroupedListStyle())
// .listRowBackground(Color("accent"))
// .listRowBackground(Color("darkerAccent"))
.accentColor(Color("tab"))
}
}
struct SmartFeedsSectionHomeView_Previews: PreviewProvider {
static let rss = RSS()
static var previews: some View {
NavigationView {
List {
SmartFeedsSectionHomeView(rssFeedViewModel: RSSFeedViewModel(rss: rss, dataSource: DataSourceService.current.rssItem), archiveListViewModel: ArchiveListViewModel(dataSource: DataSourceService.current.rssItem), articles: AllArticles(dataSource: DataSourceService.current.rssItem), unread: Unread(dataSource: DataSourceService.current.rssItem), selectedFilter: .all)
.environmentObject(DataSourceService.current.rss)
.environmentObject(DataSourceService.current.rssItem)
.environment(\.managedObjectContext, Persistence.current.context)
.preferredColorScheme(.dark)
}.listStyle(InsetGroupedListStyle())
}
}
}
|
import RxSwift
import RxRelay
import MarketKit
class BlockchainSettingsService {
private let btcBlockchainManager: BtcBlockchainManager
private let evmBlockchainManager: EvmBlockchainManager
private let evmSyncSourceManager: EvmSyncSourceManager
private let disposeBag = DisposeBag()
private let itemRelay = PublishRelay<Item>()
private(set) var item: Item = Item(btcItems: [], evmItems: []) {
didSet {
itemRelay.accept(item)
}
}
init(btcBlockchainManager: BtcBlockchainManager, evmBlockchainManager: EvmBlockchainManager, evmSyncSourceManager: EvmSyncSourceManager) {
self.btcBlockchainManager = btcBlockchainManager
self.evmBlockchainManager = evmBlockchainManager
self.evmSyncSourceManager = evmSyncSourceManager
subscribe(disposeBag, btcBlockchainManager.restoreModeUpdatedObservable) { [weak self] _ in self?.syncItem() }
subscribe(disposeBag, evmSyncSourceManager.syncSourceObservable) { [weak self] _ in self?.syncItem() }
syncItem()
}
private func syncItem() {
let btcItems: [BtcItem] = btcBlockchainManager.allBlockchains.map { blockchain in
let restoreMode = btcBlockchainManager.restoreMode(blockchainType: blockchain.type)
return BtcItem(blockchain: blockchain, restoreMode: restoreMode)
}
let evmItems: [EvmItem] = evmBlockchainManager.allBlockchains.map { blockchain in
let syncSource = evmSyncSourceManager.syncSource(blockchainType: blockchain.type)
return EvmItem(blockchain: blockchain, syncSource: syncSource)
}
item = Item(
btcItems: btcItems.sorted { $0.blockchain.type.order < $1.blockchain.type.order },
evmItems: evmItems.sorted { $0.blockchain.type.order < $1.blockchain.type.order }
)
}
}
extension BlockchainSettingsService {
var itemObservable: Observable<Item> {
itemRelay.asObservable()
}
}
extension BlockchainSettingsService {
struct Item {
let btcItems: [BtcItem]
let evmItems: [EvmItem]
}
struct BtcItem {
let blockchain: Blockchain
let restoreMode: BtcRestoreMode
}
struct EvmItem {
let blockchain: Blockchain
let syncSource: EvmSyncSource
}
}
|
//
// UIPageControl+XXColorStyle.swift
// XXColorTheme
//
// Created by xixi197 on 16/1/21.
// Copyright © 2016年 xixi197. All rights reserved.
//
import UIKit
import RxSwift
import NSObject_Rx
extension UIPageControl {
private struct AssociatedKeys {
static var PageIndicatorTintColorStyle = "xx_pageIndicatorTintColorStyle"
static var CurrentPageIndicatorTintColorStyle = "xx_currentPageIndicatorTintColorStyle"
}
var xx_pageIndicatorTintColorStyle: XXColorStyle? {
get {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.PageIndicatorTintColorStyle) as? String ?? ""
return XXColorStyle(rawValue: lookup)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.PageIndicatorTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
xx_addColorStyle(newValue, forSelector: "setPageIndicatorTintColor:")
}
}
var xx_currentPageIndicatorTintColorStyle: XXColorStyle? {
get {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.CurrentPageIndicatorTintColorStyle) as? String ?? ""
return XXColorStyle(rawValue: lookup)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.CurrentPageIndicatorTintColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
xx_addColorStyle(newValue, forSelector: "setCurrentPageIndicatorTintColor:")
}
}
}
|
//
// HomeViewController.swift
// SettleUp
//
// Created by Connor Neville on 3/26/18.
// Copyright © 2018 Connor Neville. All rights reserved.
//
import Anchorage
import Reusable
import Then
final class HomeViewController: UIViewController {
fileprivate let stackView = UIStackView().then {
$0.axis = .vertical
$0.spacing = 8
$0.isLayoutMarginsRelativeArrangement = true
$0.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
}
fileprivate let introLabel = UILabel().then {
$0.numberOfLines = 0
$0.attributedText = L10n.Home.intro.styled(with: .body)
}
fileprivate let tableView = UITableView().then {
$0.rowHeight = UITableViewAutomaticDimension
$0.estimatedRowHeight = 200
$0.separatorStyle = .none
}
fileprivate var childControllers: [IndexPath: UIViewController] = [:]
fileprivate let playButton = UIButton(type: .system).then {
$0.setAttributedTitle(
L10n.Home.play.styled(with: .cta), for: .normal)
}
fileprivate var selections: [Selection]
weak var delegate: Delegate?
init(categories: [Category]) {
self.selections = categories.map({ Selection(category: $0, count: 0) })
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = L10n.Home.title
tableView.register(cellType: ReuseNotifyingCell.self)
tableView.delegate = self
tableView.dataSource = self
playButton.addTarget(self, action: .playTapped, for: .touchUpInside)
stackView.addArrangedSubviews(introLabel, tableView, playButton)
view.addSubview(stackView)
stackView.edgeAnchors == edgeAnchors
}
}
extension HomeViewController: UITableViewDelegate { }
extension HomeViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return selections.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ReuseNotifyingCell = tableView.dequeueReusableCell(for: indexPath)
cell.delegate = self
cell.indexPath = indexPath
cell.selectionStyle = .none
let category = selections[indexPath.row].category
let supplementaryView: CategoryViewController.SupplementaryViewType
switch category.isCustom {
case true:
let supplementaryVC = AddCustomRuleViewController()
supplementaryVC.delegate = self
supplementaryView = .addCustomRule(supplementaryVC)
case false:
let supplementaryVC = CounterViewController(
category: category,
minimum: 0,
maximum: AppConstants.maximumRulesPerCategory)
supplementaryVC.delegate = self
supplementaryView = .counter(supplementaryVC)
}
let controller = CategoryViewController(
category: category,
supplementaryViewType: supplementaryView)
childControllers[indexPath] = controller
addChild(controller, constrainedTo: cell.contentView)
return cell
}
}
extension HomeViewController: Actionable {
enum Action {
case didTapPlay(selections: [Selection])
}
}
fileprivate extension Selector {
static let playTapped = #selector(HomeViewController.playTapped)
}
private extension HomeViewController {
@objc func playTapped() {
notify(.didTapPlay(selections: selections))
}
}
extension HomeViewController: ReuseNotifyingCellDelegate {
func reuseNotifyingCell(_ cell: ReuseNotifyingCell, didNotify action: ReuseNotifyingCell.Action) {
switch action {
case .preparedForReuse(let indexPath):
guard let controller = childControllers[indexPath] else {
fatalError("Missing child controller for index path \(indexPath)")
}
removeChild(controller, constrainedTo: cell.contentView)
childControllers[indexPath] = nil
}
}
}
extension HomeViewController: CounterViewControllerDelegate {
func counterViewController(_ vc: CounterViewController, didNotify action: CounterViewController.Action) {
let modifiedCategory: Category
let countOperation: (Int) -> Int
switch action {
case let .didIncrement(category):
modifiedCategory = category
countOperation = { count in return count + 1 }
case let .didDecrement(category):
modifiedCategory = category
countOperation = { count in return count - 1 }
}
let isCorrectSelection: (Selection) -> Bool = { selection in
return selection.category == modifiedCategory
}
guard let existingSelectionIndex = selections.index(where: isCorrectSelection) else {
fatalError("No selection found for category named \(modifiedCategory.title)")
}
let existingSelection = selections[existingSelectionIndex]
let newCount = countOperation(existingSelection.count)
let newSelection = Selection(category: existingSelection.category, count: newCount)
selections[existingSelectionIndex] = newSelection
}
}
extension HomeViewController: AddCustomRuleViewControllerDelegate {
func addCustomRuleViewController(_ vc: AddCustomRuleViewController, didNotify action: AddCustomRuleViewController.Action) {
switch action {
case .didTapButton:
print("IAP gate")
}
}
}
|
//
// MotorcycleViewController.swift
// SwiftMotorcycles
//
// Created by Jonas Frid on 2021-02-18.
// Copyright © 2021 Jonas Frid. All rights reserved.
//
import UIKit
protocol DismissProtocol {
func didDismiss()
}
class MotorcycleViewController: UIViewController {
var viewModel: EditMotorcycleViewModelProtocol?
var payloadId: String?
var didDismissDelegate: DismissProtocol?
@IBOutlet weak var brandTextField: UITextField!
@IBOutlet weak var modelTextField: UITextField!
@IBOutlet weak var yearTextField: UITextField!
@IBAction func saveButtonTapped(_ sender: Any) {
guard let mc = viewModel?.motorcycle else {
return
}
let isValid =
brandTextField.validate { v in return v.count >= 2 } &&
modelTextField.validate { v in return v.count >= 2 } &&
yearTextField.validate { v in return (1901...2099).contains(v.toIntOrZero()) }
if (!isValid) {
return
}
mc.brand = brandTextField?.text ?? ""
mc.model = modelTextField?.text ?? ""
mc.year = Int(yearTextField?.text ?? "0") ?? 0
viewModel?.saveMotorcycle(completion: { (success) in
self.dismiss(animated: true) {
self.didDismissDelegate?.didDismiss()
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel?.initWithPayload(payloadId: self.payloadId)
viewModel?.propertyChanged = { (propertyName) in
switch propertyName {
case "motorcycle":
guard let mc = self.viewModel?.motorcycle else {
self.brandTextField.text = ""
self.modelTextField.text = ""
self.yearTextField.text = ""
return
}
self.brandTextField.text = mc.brand
self.modelTextField.text = mc.model
self.yearTextField.text = String(mc.year)
default:
return
}
}
}
}
|
//
// CoreData Helper.swift
// Pokedex
//
// Created by Alley Pereira on 29/06/21.
//
import CoreData
struct CoreDataPokemonHelper {
static private var context: NSManagedObjectContext {
PersistenceController.shared.container.viewContext
}
static func readPokemonsFromCoreData() -> [PokemonsEntity] {
let fetchRequest = NSFetchRequest<PokemonsEntity>(entityName: "PokemonsEntity")
do {
let pokemonsEntities: [PokemonsEntity] = try context.fetch(fetchRequest)
return pokemonsEntities
} catch {
print(error)
}
return []
}
static func saveToCoreData(pokemon: Pokemon) {
let entity = PokemonsEntity(context: context)
entity.name = pokemon.model.name
entity.type = pokemon.model.type
entity.imageURL = pokemon.model.imageUrl
entity.pokemonDescription = pokemon.model.description
entity.id = Int16(pokemon.model.id)
entity.attack = Int16(pokemon.model.attack)
entity.defense = Int16(pokemon.model.defense)
entity.height = Int16(pokemon.model.height)
entity.weight = Int16(pokemon.model.weight)
do {
try context.save()
print("Saved!")
} catch {
print(error.localizedDescription)
}
}
static func updateToCoreData(imageData: Data?, entity: PokemonsEntity) {
guard let imageData = imageData else { return }
entity.imageData = imageData
do {
try context.save()
print("Updated!")
} catch {
print(error.localizedDescription)
}
}
}
|
import Foundation
import UIKit
open class LazyViewContainerViewController: UIViewController {
open var doInBackground: (() throws -> UIViewController?)! {
willSet {
guard !isViewLoaded else { fatalError("Must set before view load.") }
}
}
/// doInBackgroundの処理でerrorがthrowされた場合にmainThreadでcallされる
/// - parameter error: throwされたerrorObject.
/// - parameter lazyViewContainerViewController: self.
open var onError: ((Error, LazyViewContainerViewController) -> Void)?
open var progressViewController: UIViewController? {
willSet {
guard !isViewLoaded else { fatalError("Must set before view load.") }
}
}
private var defaultProgressViewController: UIViewController!
@IBOutlet private weak var contentContainerView: UIStackView!
private var contentViewController: UIViewController? {
willSet {
guard let contentViewController = self.contentViewController else { return }
contentViewController.willMove(toParentViewController: nil)
contentContainerView.subviews.forEach { $0.removeFromSuperview() }
contentViewController.removeFromParentViewController()
}
didSet {
guard let contentViewController = self.contentViewController else { return }
addChildViewController(contentViewController)
contentContainerView.addArrangedSubview(contentViewController.view)
contentViewController.didMove(toParentViewController: self)
}
}
open override func viewDidLoad() {
guard doInBackground != nil else { fatalError("Must set before view load.") }
super.viewDidLoad()
contentViewController = progressViewController ?? defaultProgressViewController
DispatchQueue.global(qos: .default).async { [weak self] in
do {
guard let contentViewController = try self?.doInBackground() else { return }
DispatchQueue.main.async { [weak self] in
self?.contentViewController = contentViewController
}
} catch {
DispatchQueue.main.async { [weak self] in
guard let `self` = self else { return }
self.onError?(error, self)
}
}
}
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier ?? "" {
case "EmbedDefaultProgress":
defaultProgressViewController = segue.destination
default:
break
}
}
}
|
//
// EventsTableView.swift
// diverCity
//
// Created by Lauren Shultz on 3/8/19.
// Copyright © 2019 Lauren Shultz. All rights reserved.
//
import Foundation
import UIKit
class EventsTableView: UITableView {
var eventsList: [CommunityEvent]
var onEventSelected: (_ event: CommunityEvent) -> () = {_ in }
init(frame: CGRect, eventsList: [CommunityEvent], eventSelectedCallback: @escaping (_ event: CommunityEvent) -> ()) {
let style: UITableViewStyle = UITableViewStyle.plain
onEventSelected = eventSelectedCallback
self.eventsList = eventsList
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.register(EventTableCell.self, forCellReuseIdentifier: "eventCell")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reloadEvents(events: [CommunityEvent]) {
self.eventsList = events
self.reloadData()
}
}
extension EventsTableView: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! EventTableCell
cell.eventItemView.loadEvent(event: eventsList[indexPath.row])
//cell.textLabel?.text = eventsList[indexPath.row].name
//cell.detailTextLabel?.text = eventsList[indexPath.row].description
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onEventSelected(eventsList[indexPath.row])
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
}
|
//
// SupportMessageTableViewCell.swift
// Fugu
//
// Created by Gagandeep Arora on 29/09/17.
// Copyright © 2017 CL-macmini-88. All rights reserved.
//
import UIKit
class SupportMessageTableViewCell: MessageTableViewCell {
@IBOutlet weak var shadowView: So_UIView!
@IBOutlet var bgView: UIView!
@IBOutlet weak var supportMessageTextView: UITextView!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var nameLabel: UILabel!
// @IBOutlet weak var constraint_Height : NSLayoutConstraint!
override func awakeFromNib() {
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.layoutIfNeeded()
}
override func layoutSubviews() {
super.layoutSubviews()
adjustShadow()
}
func setupBoxBackground(messageType: MessageType) {
switch messageType {
default:
print("default")
bgView.backgroundColor = HippoConfig.shared.theme.recievingBubbleColor
}
}
func adjustShadow() {
bgView.layoutIfNeeded()
}
func updateBottomConstraint(_ constant : CGFloat){
self.bottomConstraint.constant = constant
self.layoutIfNeeded()
}
func resetPropertiesOfSupportCell() {
selectionStyle = .none
supportMessageTextView.text = ""
supportMessageTextView.attributedText = nil
supportMessageTextView.isEditable = false
supportMessageTextView.dataDetectorTypes = UIDataDetectorTypes.all
supportMessageTextView.backgroundColor = .clear
timeLabel.text = ""
timeLabel.font = HippoConfig.shared.theme.dateTimeFontSize
timeLabel.textAlignment = .left
timeLabel.textColor = HippoConfig.shared.theme.incomingMsgDateTextColor
nameLabel.font = HippoConfig.shared.theme.senderNameFont
// DispatchQueue.main.async {
// let gradient = CAGradientLayer()
// gradient.frame = self.bgView.bounds
// gradient.colors = [HippoConfig.shared.theme.themeColor, HippoConfig.shared.theme.themeColor.cgColor]
// self.bgView.layer.insertSublayer(gradient, at: 0)
//
// //self.shadowView.backgroundColor = UIColor.red
// }
bgView.layer.cornerRadius = 10
bgView.clipsToBounds = true
if #available(iOS 11.0, *) {
bgView.layer.maskedCorners = [.layerMaxXMinYCorner,.layerMinXMaxYCorner,.layerMaxXMaxYCorner]
} else {
// Fallback on earlier versions
}
//bgView.backgroundColor = HippoConfig.shared.theme.incomingChatBoxColor
// bgView.layer.borderWidth = HippoConfig.shared.theme.chatBoxBorderWidth
// bgView.layer.borderColor = HippoConfig.shared.theme.chatBoxBorderColor.cgColor
supportMessageTextView.backgroundColor = .clear
supportMessageTextView.textContainer.lineFragmentPadding = 0
supportMessageTextView.textContainerInset = .zero
}
func configureCellOfSupportIncomingCell(resetProperties: Bool,attributedString: NSMutableAttributedString,channelId: Int,chatMessageObject: HippoMessage) -> SupportMessageTableViewCell
{
if resetProperties { resetPropertiesOfSupportCell() }
message?.messageRefresed = nil
super.intalizeCell(with: chatMessageObject, isIncomingView: true)
let messageType = chatMessageObject.type
message?.messageRefresed = {
DispatchQueue.main.async {
self.setSenderImageView()
}
}
//self.nameLabel.text = message?.senderFullName
let isMessageAllowedForImage = chatMessageObject.type == .consent || chatMessageObject.belowMessageType == .card || chatMessageObject.belowMessageType == .paymentCard || chatMessageObject.aboveMessageType == .consent || chatMessageObject.type == .dateTime || chatMessageObject.type == .botAttachment || chatMessageObject.type == .address
if (chatMessageObject.aboveMessageUserId == chatMessageObject.senderId && !isMessageAllowedForImage) {
self.nameLabel.text = ""
} else {
self.nameLabel.text = message?.senderFullName
}
setupBoxBackground(messageType: messageType)
setTime()
supportMessageTextView.attributedText = message?.attributtedMessage.attributedMessageString
setSenderImageView()
return self
}
}
|
//
// PostDetailPresenter.swift
// iOS-Viper-Architecture
//
// Created by Amir Samir on 23/06/21.
//
//
class PostDetailPresenter: PostDetailPresenterProtocol {
weak var view: PostDetailViewProtocol?
var wireFrame: PostDetailWireFrameProtocol?
var post: PostModel?
func viewDidLoad() {
view?.showPostDetail(forPost: post!)
}
}
|
//
// Adapter.swift
// StructuralPatterns
//
// Created by Vadim Mocan on 2/21/19.
// Copyright © 2019 MidnightWorks. All rights reserved.
//
import Foundation
import Reachability
protocol Ethernet {
func request()
}
class Adaptee {
static func someRequest() {
let reachability = Reachability()!
if reachability.connection == .none {
print("No connection. Can't start request")
} else {
reachability.connection == .wifi ? print("Start request from Wifi") : print("Start request from cellular")
}
}
}
|
//
// WebServer.swift
// Orion
//
// Created by Eduard Shahnazaryan on 3/12/21.
//
import Foundation
import GCDWebServer
import RealmSwift
class WebServer {
static let shared = WebServer()
let webServer = GCDWebServer()
let newTabHTMLStart = """
<!DOCTYPE html>
<html>
<head>
<title>New Tab</title>
<style type="text/css">
* {
font-family: sans-serif;
}
h1 {
padding-top: 72px;
font-size: 72px;
}
#noTopSite {
padding-top: 144px;
font-size: 48px;
}
.topSiteTitle {
margin: 0;
font-size: 36px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
}
.container {
padding-top: 144px;
padding-left: 5%;
padding-right: 5%;
}
.floatBlock {
display: inline-block;
float: left;
width: 33%;
padding-bottom: 33%
}
a img {
display: block;
margin: auto;
}
.footer {
background: #EFEFEF;
position: fixed;
bottom: 0;
width: 100%;
height: 100px;
font-size: 28px;
margin: 0;
padding-bottom: env(safe-area-inset-bottom);
}
</style>
</head>
<body>
<h1 align="center">Top Sites</h1>
"""
let newTabEnd = """
<div class="footer">
<p align=\"center\">Orion Web Browser v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.") (\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"))</p>
</div>
</body></html>
"""
init() {
webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: { _ in
return GCDWebServerDataResponse(html: self.getNewTabHTMLString())
})
webServer.addHandler(forMethod: "GET", path: "/noimage", request: GCDWebServerRequest.self, processBlock: { _ in
let img = #imageLiteral(resourceName: "globe")
return GCDWebServerDataResponse(data: img.pngData()!, contentType: "image/png")
})
webServer.addHandler(forMethod: "GET", path: "/favicon.ico", request: GCDWebServerRequest.self, processBlock: { _ in
let iconsDictionary = Bundle.main.infoDictionary?["CFBundleIcons"] as? NSDictionary
let primaryIconsDictionary = iconsDictionary?["CFBundlePrimaryIcon"] as? NSDictionary
let iconFiles = primaryIconsDictionary?["CFBundleIconFiles"] as? NSArray
// First will be smallest for the device class, last will be the largest for device class
let lastIcon = iconFiles?.lastObject as? NSString
guard let icon = lastIcon as String?, let img = UIImage(named: icon) else {
let img = #imageLiteral(resourceName: "globe")
return GCDWebServerDataResponse(data: img.pngData()!, contentType: "image/png")
}
return GCDWebServerDataResponse(data: img.pngData()!, contentType: "image/png")
})
}
func startServer() {
webServer.start(withPort: 8080, bonjourName: nil)
}
func getNewTabHTMLString() -> String {
var result = newTabHTMLStart
let topSites: Results<TopSite>?
var sites: [TopSite]?
do {
let realm = try Realm()
topSites = realm.objects(TopSite.self)
let sitesArray = (topSites?.toArray(ofType: TopSite.self) ?? [])
sites = sitesArray.unique
} catch {
topSites = nil
print("Error: \(error.localizedDescription)")
}
if let topSites = sites, topSites.count > 0 {
result += "<div class=\"container\">"
for i in 0..<min(10, topSites.count) {
let iconLoc = (topSites[i].iconURL == "") ? "http://localhost:8080/noimage" : topSites[i].iconURL
result += """
<div class="floatBlock">
<a href="\(topSites[i].pageURL)"><img src="\(iconLoc)" onerror=\"this.src='/noimage';\" width=200px height=200px></a>
<p class="topSiteTitle" align=\"center\">\(topSites[i].name)</p>
</div>
"""
}
result += "</div>"
} else {
result += "<p id=\"noTopSite\" align=\"center\">Go add some sites to see them here!</p>"
}
return result + newTabEnd
}
}
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for i in 0 ..< count {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
extension Sequence where Iterator.Element: Hashable {
func uniqueee() -> [Iterator.Element] {
var seen: Set<Iterator.Element> = []
return filter { seen.insert($0).inserted }
}
}
extension Array where Element: Hashable {
func distinct() -> Array<Element> {
var set = Set<Element>()
return filter {
guard !set.contains($0) else { return false }
set.insert($0)
return true
}
}
func distincts() -> Array<Element> {
var set = Set<Element>()
return filter { set.insert($0).inserted }
}
}
|
//
// AlbumTests.swift
// PinchChallengeTests
//
// Created by Feef Anthony on 5/24/20.
// Copyright © 2020 Feef Anthony. All rights reserved.
//
import XCTest
import CoreData
@testable import PinchChallenge
class AlbumTests: XCTestCase {
var context: NSManagedObjectContext!
override func setUp() {
context = UnitTestHelpers.setUpInMemoryManagedObjectContext()
}
override func tearDown() {
context = nil
}
func testParsingFromAPIResponse() {
guard let album: Album = ManagedObjectTestHelper.loadModelFromFile(named: "Album", in: context) else {
return
}
XCTAssertEqual(album.userId, 123)
XCTAssertEqual(album.id, 456)
XCTAssertEqual(album.title, "album title value")
}
}
|
//
// MainWindowExtension.swift
// unusedResources
//
// Created by thierryH24 on 07/10/2018.
// Copyright © 2018 thierryH24. All rights reserved.
//
import AppKit
extension MainWindowController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return unusedData.count
}
}
extension MainWindowController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let column = tableColumn {
let id = column.identifier
if let cellView = tableView.makeView(withIdentifier: id, owner: self) as? SelectCellView {
if column.identifier.rawValue == kSelect {
cellView.select.state = .off
return cellView
}
}
if let cellView = tableView.makeView(withIdentifier: id, owner: self) as? NSTableCellView {
let pngPath = unusedData[row]
if column.identifier.rawValue == kTableColumnImageIcon {
let folderWithFilenameAndEncoding = pngPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let imagePath = URL(string: folderWithFilenameAndEncoding!)
let image = NSImage(byReferencing : imagePath!)
cellView.imageView?.image = image
return cellView
}
if column.identifier.rawValue == kTableColumnImageShortName {
let folderWithFilenameAndEncoding = pngPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let imagePath = URL(string: folderWithFilenameAndEncoding!)
cellView.textField?.stringValue = imagePath?.lastPathComponent ?? "defaut"
return cellView
}
if column.identifier.rawValue == kTableColumnImageFullPath {
cellView.textField?.stringValue = pngPath
return cellView
}
}
}
return nil
}
}
extension MainWindowController: SearcherDelegate {
// MARK: - <SearcherDelegate>
public func searcherDidStartSearch() {
}
func searcher( didFindUnusedImage imagePath: String) {
// Add and reload
unusedData.append(imagePath )
// Reload
DispatchQueue.main.async { [unowned self] in
self.resultsTableView.reloadData()
}
// Scroll to the bottom
scrollTableView(resultsTableView, toBottom: true)
}
func searcher( didFinishSearch results: [String]) {
// Ensure all data is displayed
resultsTableView.reloadData()
status.removeAll()
// Calculate how much file size we saved and update the label
var size = UInt64(0)
for path in self.unusedData {
let folderWithFilenameAndEncoding: String? = path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let pathUrl = URL(string: folderWithFilenameAndEncoding!)
size += (pathUrl?.fileSize)!
status.append(false)
}
let time: TimeInterval = Date().timeIntervalSince(startTime!)
print(time)
statusLabel.stringValue = "Completed Found : " + String(self.unusedData.count) + String(format: " Time : %.2fs: ", arguments: [time]) + " images - Size " + FileUtil.shared.stringFromFileSize(fileSize: Int(size))
// Enable the ui
self.setUIEnabled( true)
}
}
extension URL {
var attributes: [FileAttributeKey : Any]? {
do {
return try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
print("FileAttribute error: \(error)")
}
return nil
}
var fileSize: UInt64 {
return attributes?[.size] as? UInt64 ?? UInt64(0)
}
var creationDate: Date? {
return attributes?[.creationDate] as? Date
}
}
final class SelectCellView: NSTableCellView {
@IBOutlet weak var select: NSButton!
}
extension NSUserInterfaceItemIdentifier {
static let ImageIcon = NSUserInterfaceItemIdentifier("ImageIcon")
static let ImageShortName = NSUserInterfaceItemIdentifier("ImageShortName")
static let ImageFullPath = NSUserInterfaceItemIdentifier("ImageFullPath")
static let Select = NSUserInterfaceItemIdentifier("Select")
}
|
//
// NotesListViewController.swift
// EvoNote
//
// Created by asd dsa on 5/10/19.
// Copyright © 2019 Mykola Korotun. All rights reserved.
//
import UIKit
import CoreData
class NotesListViewController: UIViewController {
@IBOutlet var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var notes = [Note]()
var searchedNotes = [Note]() {
didSet {
self.tableView.reloadData()
}
}
let fetchRequest: NSFetchRequest<Note> = Note.fetchRequest()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
fetchRequest.fetchBatchSize = 20
do {
let notes = try PersistenceService.context.fetch(fetchRequest)
self.notes = notes
searchedNotes = self.notes
} catch {
fatalError("NotesListViewController + viewWillAppear")
}
}
func pushNoteViewController(index: Int?, isNewNote: Bool) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "NoteViewControllerID") as! NoteViewController
controller.notes = notes
controller.noteIndex = index
controller.newNote = isNewNote
navigationController?.pushViewController(controller, animated: true)
}
//MARK: - IBAction methods
@IBAction func adNoteAction(_ sender: UIBarButtonItem) {
pushNoteViewController(index: nil, isNewNote: true)
}
@IBAction func sortNotesAction(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Sort by text", style: .default, handler: { _ in
self.sortBy(key: "text", asc: true)
}))
alert.addAction(UIAlertAction(title: "Sort by date ASC", style: .default, handler: { _ in
self.sortBy(key: "date", asc: true)
}))
alert.addAction(UIAlertAction(title: "Sort by date DESC", style: .default, handler: { _ in
self.sortBy(key: "date", asc: false)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
}))
present(alert, animated: true, completion: nil)
}
}
|
//
// RecordViewController.swift
// PitchPerfect
//
// Created by David Iriarte on 18/02/20.
// Copyright © 2020 David Iriarte. All rights reserved.
//
import UIKit
import AVFoundation
class RecordViewController: UIViewController, AVAudioRecorderDelegate {
@IBOutlet weak var recordBtn: UIButton!
var audioRecorder : AVAudioRecorder!
let STOP_SEGUE = "stopRecording"
private var recording = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
recordBtn.contentMode = .center
recordBtn.imageView?.contentMode = .scaleAspectFit
}
@IBAction func recordBtnClicked(_ sender: Any) {
if !recording {
record()
recording = true
if let image = UIImage(named: "Stop") {
recordBtn.setImage(image, for: [])
}
} else {
stopRecording()
recording = false
if let image = UIImage(named: "Record") {
recordBtn.setImage(image, for: [])
}
}
}
private func record() {
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
let recordingName = "recordedVoice.wav"
let pathArray = [dirPath, recordingName]
let filePath = URL(string: pathArray.joined(separator: "/"))
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
private func stopRecording() {
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if flag {
performSegue(withIdentifier: STOP_SEGUE, sender: audioRecorder.url)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == STOP_SEGUE {
let playSoundsVC = segue.destination as! PlaySoundsViewController
let recorderAudioURL = sender as! URL
playSoundsVC.recordedAudioURL = recorderAudioURL
}
}
}
|
//: [Previous](@previous)
import Foundation
//: __Exercise 1.__
//:
//:Earlier we used the method, remove() to remove the first letter of a string. This method belongs to the String class. See if you can use this same method to remove the last letter of a string.
var string = "stuff"
string.remove(at: string.index(before: string.endIndex))
//:Test out your discovery below by returning the last letter of the String, "bologna".
var word = "bologna"
word.remove(at: word.index(before: word.endIndex))
//: __Exercise 2__
//:
//: Write a function called combineLastCharacters. It should take in an array of strings, collect the last character of each string and combine those characters to make a new string to return. Use the strategy you discovered in Problem 1 along with a for-in loop to write combineLastCharacters. Then try it on the nonsenseArray below.
var nonsenseArray = ["bungalow", "buffalo", "indigo", "although", "Ontario", "albino", "%$&#!"]
func combineLastCharacters(arr: [String])->String{
var returnString = ""
for var str in nonsenseArray{
let lastChar = str.remove(at: str.index(before: str.endIndex))
returnString.append(lastChar)
}
return returnString
}
combineLastCharacters(arr: nonsenseArray)
//: __Exercise 3__
//:
//: Imagine you are writing an app that keeps track of what you spend during the week. Prices of items purchased are entered into a "price" textfield. The "price" field should only allow numbers, no letters.
//: CharacterSet.decimalDigitCharacterSet() is used below to define a set that is only digits. Using that set, write a function that takes in a String and returns true if that string is numeric and false if it contains any characters that are not numbers.
//: __3a.__ Write a signature for a function that takes in a String and returns a Bool
//: __3b.__ Write a for-in loop that checks each character of a string to see if it is a member of the "digits" set. Use the .unicodeScalars property to access all the characters in a string. Hint: the method longCharacterIsMember may come in handy.
let digits = CharacterSet.decimalDigits
func isOnlyDigits(string: String)->Bool{
var str = string
for char in str.characters{
switch char {
case "0":continue
case "1":continue
case "2":continue
case "3":continue
case "4":continue
case "5":continue
case "6":continue
case "7":continue
case "8":continue
case "9":continue
default:
return false
}
}
return true
}
isOnlyDigits(string: "124")
//: __Exercise 4__
//:
//: Write a function that takes in an array of dirtyWord strings, removes all of the four-letter words, and returns a clean array.
let dirtyWordsArray = ["phooey", "darn", "drat", "blurgh", "jupiters", "argh", "fudge"]
//: __Exercise 5__
//:
//: Write a method, filterByDirector(), that belongs to the MovieArchive class. This method should take in a dictionary of movie titles and a string representing the name of a director and return an array of movies created by that director. You can use the movie dictionary below. To test your method, instantiate an instance of the MovieArchive class and call filterByDirector from that instance.
var movies:Dictionary<String,String> = [ "Boyhood":"Richard Linklater","Inception":"Christopher Nolan", "The Hurt Locker":"Kathryn Bigelow", "Selma":"Ava Du Vernay", "Interstellar":"Christopher Nolan"]
class MovieArchive {
func filterByDirector(_ dict: Dictionary<String, String>,_ director: String){
var array = [String]()
for (movie, name) in dict{
if name == director {
array.append(movie)
}
}
for element in array{
print(element)
}
}
}
var movieArchive = MovieArchive()
movieArchive.filterByDirector(movies, "Christopher Nolan")
//: [Next](@next)
|
//
// MetadataStore.swift
// Ursus Chat
//
// Created by Daniel Clelland on 18/06/20.
// Copyright © 2020 Protonome. All rights reserved.
//
import Foundation
import Alamofire
import UrsusAirlock
extension Airlock {
func metadataStore(ship: Ship) -> MetadataStoreApp {
return app(ship: ship, app: "metadata-store")
}
}
class MetadataStoreApp: AirlockApp {
@discardableResult func allSubscribeRequest(handler: @escaping (SubscribeEvent<Result<SubscribeResponse, Error>>) -> Void) -> DataRequest {
return subscribeRequest(path: "/all", handler: handler)
}
@discardableResult func appNameSubscribeRequest(app: String, handler: @escaping (SubscribeEvent<Result<SubscribeResponse, Error>>) -> Void) -> DataRequest {
return subscribeRequest(path: "/app-name/\(app)", handler: handler)
}
}
extension MetadataStoreApp {
enum SubscribeResponse: Decodable {
case metadataUpdate(MetadataUpdate)
enum CodingKeys: String, CodingKey {
case metadataUpdate = "metadata-update"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch Set(container.allKeys) {
case [.metadataUpdate]:
self = .metadataUpdate(try container.decode(MetadataUpdate.self, forKey: .metadataUpdate))
default:
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Failed to decode \(type(of: self)); available keys: \(container.allKeys)"))
}
}
}
}
|
//
// ContactParser.swift
// ContactsList
//
// Created by Elliott Walker on 09/04/2021.
//
import Foundation
import CoreData
class ContactParser: EntityParser {
// MARK: - Variables
override var dataClass: Entity.Type {
return Contact.self
}
// MARK: - CRUD
override func update(_ entity: Entity, with json: JSONDictionary, context: NSManagedObjectContext) throws {
guard let contact = entity as? Contact else {
throw EntityParser.ParseError.unexpectedClass
}
contact.firstName = json[Parameters.firstName] as? String
contact.lastName = json[Parameters.lastName] as? String
contact.email = json[Parameters.email] as? String
contact.phone = json[Parameters.phone] as? String
contact.address = json[Parameters.address] as? String
try super.update(contact, with: json, context: context)
}
}
extension ContactParser {
private enum Parameters {
static let firstName = "name"
static let lastName = "last_name"
static let email = "company_email"
static let phone = "contact_number"
static let address = "address_line"
}
}
|
//
// Pokedex.swift
// Pokedex
//
// Created by Luiz Vasconcellos on 24/04/21.
//
import Foundation
struct Pokedex: Decodable {
var count: Int
var all:[Basic]
var nextPageUrl: String
var previousPageUrl: String?
enum CodingKeys: String, CodingKey {
case count
case all = "results"
case nextPageUrl = "next"
case previousPageUrl = "previous"
}
}
|
//
// RocketModel.swift
// Rocket launcher
//
// Created by Somya on 13/5/19.
// Copyright © 2019 MobileDEN. All rights reserved.
//
import Foundation
struct ResultsModel: Codable {
let count: Int
let results: [RocketModel]
}
struct RocketModel: Codable {
var name: String?
var status: StatusModel?
var windowStart: String?
var rocketInfo: RocketInfo
var rocketPad: RocketPadModel?
enum CodingKeys: String, CodingKey {
case name = "name"
case status = "status"
case windowStart = "window_start"
case rocketInfo = "rocket"
case rocketPad = "pad"
}
}
struct StatusModel: Codable {
var name: String?
enum CodingKeys: String, CodingKey {
case name = "name"
}
}
struct RocketInfo: Codable {
var launcherStage: [LauncherStageModel]?
enum CodingKeys: String, CodingKey {
case launcherStage = "launcher_stage"
}
init() {
self.launcherStage = [LauncherStageModel]()
}
}
struct LauncherStageModel: Codable {
var launcher: LauncherModel
enum CodingKeys: String, CodingKey {
case launcher = "launcher"
}
init() {
self.launcher = LauncherModel()
}
}
struct LauncherModel: Codable {
var details: String?
var imageUrl: String?
enum CodingKeys: String, CodingKey {
case details = "details"
case imageUrl = "image_url"
}
init() {
self.details = ""
self.imageUrl = ""
}
}
struct RocketPadModel: Codable {
var location: LocationModel
init() {
self.location = LocationModel()
}
}
struct LocationModel: Codable {
var name: String?
var countryCode: String?
enum CodingKeys: String, CodingKey {
case name = "name"
case countryCode = "country_code"
}
init() {
self.name = ""
self.countryCode = ""
}
}
|
//
// Cat.swift
// AppDynamics
//
// Created by Bojan Savic on 5/1/19.
// Copyright © 2019 Bojan Savic. All rights reserved.
//
import Foundation
import RealmSwift
class Cat: Object {
@objc dynamic var name: String?
@objc dynamic var color: String?
@objc dynamic var gender: String?
}
|
//
// ItemDAO.swift
// eggplant-brownie
//
// Created by Antonio Alves on 13/05/20.
// Copyright © 2020 Alura. All rights reserved.
//
import Foundation
class ItemDAO {
func save(_ item : [Item]) {
do{
let dados = try NSKeyedArchiver.archivedData(withRootObject: item, requiringSecureCoding: false)
guard let caminho = recuperaCaminho() else {return }
try dados.write(to: caminho)
}catch {
print(error.localizedDescription)
}
}
func recuperaCaminho() -> URL? {
guard let diretorio = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil}
let caminho = diretorio.appendingPathComponent("itens")
return caminho
}
func recuperaItens() -> [Item]{
guard let caminho = recuperaCaminho() else {return []}
do {
let dados = try Data(contentsOf: caminho)
guard let itensSalvos = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(dados) as? Array<Item> else {return []}
return itensSalvos
} catch {
print(error.localizedDescription)
return []
}
}
}
|
//
// MenuTableViewController.swift
// Experiment Go
//
// Created by luojie on 7/14/15.
// Copyright © 2015 LuoJie. All rights reserved.
//
import UIKit
import CloudKit
class MenuTableViewController: UITableViewController, CurrentUserHasChangeObserver {
@IBOutlet weak var tableHeaderContentViewHeightConstraint: NSLayoutConstraint! {
didSet { tableHeaderViewDefualtHeight = tableHeaderContentViewHeightConstraint.constant }
}
@IBOutlet weak var profileImageView: UIImageView! {
didSet {
// Add border
profileImageView.layer.borderColor = UIColor.whiteColor().CGColor
profileImageView.layer.borderWidth = profileImageView.bounds.size.height / 32
// Add corner radius
profileImageView.layer.cornerRadius = profileImageView.bounds.size.height / 2
profileImageView.layer.masksToBounds = true
}
}
var profileImage: UIImage {
get { return profileImageView.image ?? UIImage() }
set { profileImageView.image = newValue }
}
var currentUser: CKUsers? { return CKUsers.CurrentUser }
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setBarSeparatorHidden(true)
startObserveCurrentUserHasChange()
updateUI()
}
deinit { stopObserve() }
// MARK: - Update UI
var profileImageURL: NSURL? {
return currentUser?.profileImageAsset?.fileURL
}
func updateUI() {
// Clear UI
profileImage = CKUsers.ProfileImage
self.title = currentUser?.displayName ?? NSLocalizedString("Menu", comment: "")
guard let url = profileImageURL else { return }
UIImage.GetImageForURL(url) {
guard url == self.profileImageURL else { return }
self.profileImage = $0 ?? CKUsers.ProfileImage
}
}
private var egSplitViewController: EGSplitViewController { return splitViewController as! EGSplitViewController }
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.textLabel?.text == NSLocalizedString("Profile", comment: "") {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
guard didAuthoriseElseRequest(didAuthorize: { self.performSegueWithIdentifier(SegueID.ShowUserDetail.rawValue, sender: cell) }) else { return }
performSegueWithIdentifier(SegueID.ShowUserDetail.rawValue, sender: cell)
} else {
egSplitViewController.showDetailViewControllerAtIndex(indexPath.row)
}
}
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let height = tableHeaderViewDefualtHeight! - scrollView.contentOffset.y
tableHeaderContentViewHeightConstraint.constant = max(40, height)
}
private var tableHeaderViewDefualtHeight: CGFloat?
// MARK: - About App Button
@IBOutlet weak var aboutAppButton: UIButton! {
didSet {
// Add border
aboutAppButton.layer.borderColor = UIColor.whiteColor().CGColor
aboutAppButton.layer.borderWidth = aboutAppButton.bounds.size.height / 32
// Add corner radius
aboutAppButton.layer.cornerRadius = aboutAppButton.bounds.size.height / 2
aboutAppButton.layer.masksToBounds = true
}
}
// MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier else { return }
guard let segueID = SegueID(rawValue: identifier) else { return }
switch segueID {
case .ShowUserDetail:
guard let udvc = segue.destinationViewController.contentViewController as? UserDetailViewController else { abort() }
udvc.user = CKUsers.CurrentUser
case .ShowAppDetail:
guard let advc = segue.destinationViewController.contentViewController as? AppDetailViewController else { return }
guard let ppc = advc.navigationController?.popoverPresentationController else { return }
ppc.sourceRect = CGRect(origin: (sender as! UIButton).bounds.center, size: CGSize(width: 1, height: 1))
ppc.backgroundColor = UIColor.whiteColor()
ppc.delegate = self
}
}
private enum SegueID: String {
case ShowUserDetail
case ShowAppDetail
}
}
extension MenuTableViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .FullScreen
}
func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
let nav = controller.presentedViewController ; let advc = nav.contentViewController as! AppDetailViewController
advc.adapted = true
return nav
}
}
|
//
// FeedbackViewController.swift
// biaoqing
//
// Created by zhuanghl on 16/1/19.
// Copyright © 2016年 zhuanghl. All rights reserved.
//
import UIKit
class FeedbackViewController: BaseViewController {
// MARK: - Vars
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textField: UITextField!
var successAction: ( Void -> Void )?
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Colors.hex(0xFAFAFA)
setupView()
}
func setupView() {
self.navigationItem.title = "意见反馈"
createRightBarButton("发送", image: nil, highlightedImage: nil)
}
// MARK: - Action
override func rightBarButtonClick() {
guard textView.text.characters.count != 0 else {
self.view.showWarning("请输入您的意见或建议")
return
}
let problemInfo = textView.text
let contactInfo = textField.text
let feedback = UMFeedback()
feedback.post(["content": "反馈问题:\n\(problemInfo)\n\n联系方式:\n\(contactInfo!)"]) { (error) -> Void in
guard error == nil else {
self.view.showError("意见反馈提交失败了")
return
}
if let successAction = self.successAction {
successAction()
}
self.navigationController?.popViewControllerAnimated(true)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
textView.resignFirstResponder()
textField.resignFirstResponder()
}
}
|
//
// RXTableViewUITests.swift
// LoginDemoRxReduxUITests
//
// Created by Magdy Kamal on 2/10/20.
// Copyright © 2020 Mounir Dellagi. All rights reserved.
//
import XCTest
@testable import LoginDemoRxRedux
class RXTableViewUITests: BaseUITestClass {
override func setUp() {
super.setUp()
openRxTableView()
}
func openRxTableView() {
enterValidUserNameAndPassword()
app.buttons["Login"].tap()
}
func testCheckIfLoaderExists() {
let activityIndicator = app.activityIndicators["RxTableViewActivityIndictor"]
let exists = NSPredicate(format: "exists == 1")
expectation(for: exists, evaluatedWith: activityIndicator, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
func testCheckIfTableViewExists() {
let exists = NSPredicate(format: "exists == 1")
let tableView = app.tables["RxTableView"]
expectation(for: exists, evaluatedWith: tableView, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
func testCheckIfRefreshButtonExists() {
let exists = NSPredicate(format: "exists == 1")
let refreshBtn = app.buttons["Refresh"]
expectation(for: exists, evaluatedWith: refreshBtn, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
// as i have checked the code it choses 5 random charcters
func testCheckIf5TableViewCellsExists() {
let counts = NSPredicate(format: "count == 5")
let cells = app.tables["RxTableView"].cells
expectation(for: counts, evaluatedWith: cells, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
func testCharacterTitleLabelExists() {
let exists = NSPredicate(format: "exists == 1")
let firstCell = app.tables["RxTableView"].cells.element(boundBy: 0)
let titleLabel = firstCell.staticTexts["characterTitleLabel"]
expectation(for: exists, evaluatedWith: titleLabel, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
func testCharacterDescriptionLabelExists() {
let exists = NSPredicate(format: "exists == 1")
let firstCell = app.tables["RxTableView"].cells.element(boundBy: 0)
let descriptionLabel = firstCell.staticTexts["characterDescriptionLabel"]
expectation(for: exists, evaluatedWith: descriptionLabel, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
func testCharacterImageViewExists() {
let exists = NSPredicate(format: "exists == 1")
let firstCell = app.tables["RxTableView"].cells.element(boundBy: 0)
let imageView = firstCell.images["characterImageView"]
expectation(for: exists, evaluatedWith: imageView, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
func testRefreshAction() {
let tableView = app.tables["RxTableView"]
XCTAssert(tableView.waitForExistence(timeout: 10))
let refreshBtn = app.buttons["Refresh"]
refreshBtn.tap()
let activityIndicator = app.activityIndicators["RxTableViewActivityIndictor"]
XCTAssert(activityIndicator.exists)
let counts = NSPredicate(format: "count == 5")
let cells = app.tables["RxTableView"].cells
expectation(for: counts, evaluatedWith: cells, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
}
}
|
//
// ViewController.swift
// Taboo
//
// Created by Damian Ferens on 25.10.2016.
// Copyright © 2016 Damian Ferens. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var instructionsButton: UIButton!
@IBOutlet weak var settingsButton: UIButton!
@IBOutlet weak var newGameButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
newGameButton.layer.borderColor = UIColor.white.cgColor
newGameButton.layer.borderWidth = 1
newGameButton.layer.cornerRadius = 5
newGameButton.titleLabel?.font = UIFont.init(name: "Arial", size: 24)
instructionsButton.layer.borderColor = UIColor.white.cgColor
instructionsButton.layer.borderWidth = 1
instructionsButton.layer.cornerRadius = 5
instructionsButton.titleLabel?.font = UIFont.init(name: "Arial", size: 24)
settingsButton.layer.borderColor = UIColor.white.cgColor
settingsButton.layer.borderWidth = 1
settingsButton.layer.cornerRadius = 5
settingsButton.titleLabel?.font = UIFont.init(name: "Arial", size: 24)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// MidiPacket.swift
// SwiftCoreMIDI
//
// Created by Владислав on 20.12.15.
// Copyright © 2015 Vladislav Taravkov. All rights reserved.
//
import Foundation
import CoreMIDI
public class MidiPacket {
public init() {
_currentPacket = MIDIPacketListInit(&_midiPacketList)
}
public func addEvent(midiEvent: MidiEvent) {
_currentPacket = MIDIPacketListAdd(&_midiPacketList, sizeof(MIDIPacketList), _currentPacket, 0, midiEvent.eventSize, midiEvent.eventData)
}
var _midiPacketList: MIDIPacketList = MIDIPacketList()
var _currentPacket: UnsafeMutablePointer<MIDIPacket>
} |
//
// Task.swift
// August
//
// Created by Bradley Hilton on 5/18/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
import AssociatedValues
open class Task : Equatable {
open internal(set) var request: Request
var task: URLSessionTask?
var body = Data()
var errors = [Error]()
var timer = August.Timer()
init(request: Request) {
self.request = request
augustQueue.addOperation {
do {
self.task = try self.request.task()
self.task?.parent = self
self.request.session.tasks.append(self)
} catch {
self.start()
self.handleError(error)
self.complete(nil)
}
}
}
func start() {
request.log()
request.reportStart(self)
request.reportProgress(self)
}
func handleError(_ error: Error) {
errors.append(error)
request.reportFailure(error, request: request)
request.failureCallback = nil
request.reportError(error, request: request)
}
func complete(_ response: Response<Data>?) {
if let response = response {
for error in request.reportResponse(response) {
handleError(error)
}
}
request.reportCompletion(response, errors: errors, request: request)
}
open internal(set) var sent = 0.0 { didSet { if oldValue != sent { request.reportProgress(self) } } }
open internal(set) var received = 0.0 { didSet { if oldValue != received { request.reportProgress(self) } } }
open var state: URLSessionTask.State {
return task?.state ?? .completed
}
open func cancel() {
augustQueue.addOperation {
self.task?.cancel()
}
}
open func suspend() {
augustQueue.addOperation {
self.timer.suspend()
self.task?.suspend()
}
}
private var started = false
open func resume() {
augustQueue.addOperation {
self.timer.resume()
guard !self.started else { self.task?.resume(); return }
self.started = true
self.start()
if self.state == .suspended {
self.task?.resume()
}
}
}
}
public func ==(lhs: Task, rhs: Task) -> Bool {
return lhs === rhs
}
extension URLSessionTask {
weak var parent: Task? {
get {
return getAssociatedValue(key: "parent", object: self)
}
set {
set(weakAssociatedValue: newValue, key: "parent", object: self)
}
}
}
|
//
// JChatAlertViewManager.swift
// JChatSwift
//
// Created by oshumini on 16/3/2.
// Copyright © 2016年 HXHG. All rights reserved.
//
import UIKit
@objc(JChatBubbleAlertViewDelegate)
protocol JChatBubbleAlertViewDelegate {
func clickBubbleFristBtn()
func clickBubbleSecondBtn()
}
class JChatAlertViewManager: NSObject {
var alertView:UIView!
weak var delegate:JChatBubbleAlertViewDelegate?
var isShowing:Bool!
class var sharedInstance: JChatAlertViewManager {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: JChatAlertViewManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = JChatAlertViewManager()
}
return Static.instance!
}
override init() {
super.init()
self.alertView = UIView()
self.isShowing = false
}
func showBubbleBtn(inView view: UIView, delegate: JChatBubbleAlertViewDelegate) {
self.isShowing = true
self.delegate = delegate
let bubbleView = UIImageView()
var bubbleImg = UIImage(named: "frame")
bubbleImg = bubbleImg?.resizableImageWithCapInsets(UIEdgeInsetsMake(30, 10, 30, 64), resizingMode: .Tile)
bubbleView.image = bubbleImg
self.alertView.addSubview(bubbleView)
bubbleView.snp_makeConstraints { (make) -> Void in
make.left.right.top.bottom.equalTo(self.alertView)
}
let fristBtn = UIButton()
self.alertView.addSubview(fristBtn)
fristBtn.setBackgroundColor(UIColor(netHex: 0x4880d7), forState: .Highlighted)
fristBtn.setTitle("发起群聊", forState: .Normal)
fristBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(self.alertView).offset(10)
make.right.equalTo(self.alertView).offset(-10)
make.height.equalTo(30)
make.top.equalTo(self.alertView).offset(20)
}
fristBtn.addTarget(self, action: #selector(JChatAlertViewManager.clickFristBtn), forControlEvents: .TouchUpInside)
let secondBtn = UIButton()
self.alertView.addSubview(secondBtn)
secondBtn.setBackgroundColor(UIColor(netHex: 0x4880d7), forState: .Highlighted)
secondBtn.setTitle("添加朋友", forState: .Normal)
secondBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(self.alertView).offset(10)
make.right.equalTo(self.alertView).offset(-10)
make.height.equalTo(30)
make.top.equalTo(fristBtn.snp_bottom).offset(10)
}
secondBtn.addTarget(self, action: #selector(JChatAlertViewManager.clickSecondBtn), forControlEvents: .TouchUpInside)
view.addSubview(self.alertView)
self.alertView.snp_makeConstraints { (make) -> Void in
make.size.equalTo(CGSize(width: 100, height: 100))
make.right.equalTo(view)
make.top.equalTo(view).offset(1)
}
}
func clickFristBtn() {
self.delegate?.clickBubbleFristBtn()
}
func clickSecondBtn() {
self.delegate?.clickBubbleSecondBtn()
}
func hidenAll() {
self.isShowing = false
self.alertView.removeFromSuperview()
self.alertView = UIView()
}
}
|
//
// BSUICardDisplayer.swift
// Traverse
//
// Created by Benjamin Su on 2/12/18.
// Copyright © 2018 Benjamin Su. All rights reserved.
//
import Foundation
import SpriteKit
protocol BSUICardDisplayerDelegate: AnyObject {
func cardTapped(_ card: BSSkillCard)
}
class BSUICardDisplayer: SKNode {
var width: CGFloat
var backgroundNode: SKSpriteNode
var confirmButton: BSGenericButton
var visibleCards: [BSUICardSprite]
weak var displayedCard: BSUICardSprite?
weak var delegate: BSUICardDisplayerDelegate?
private var animationDuration = 0.5
init(sceneSize: CGSize) {
width = sceneSize.width / 2
backgroundNode = SKSpriteNode(texture: nil, color: .clear, size: CGSize(width: width, height: CGFloat(TileHeight) * 1.5))
visibleCards = []
confirmButton = BSGenericButton(size: CGSize(width: 200, height: 60))
confirmButton.color = .cyan
confirmButton.position = CGPoint(x: 200, y: 356)
confirmButton.isHidden = true
super.init()
addChild(backgroundNode)
confirmButton.setButtonAction(target: self, action: #selector(confirmButtonAction))
addChild(confirmButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func confirmButtonAction() {
if let card = displayedCard,
let index = visibleCards.index(of: card) {
// animated card destruction / usage
delegate?.cardTapped(card.skill)
visibleCards.remove(at: index)
confirmButton.isHidden = true
card.removeFromParent()
repositionCards()
insertCard(BSSkillBlock(textureType: .hangedman))
}
}
func insertCard(_ card: BSSkillCard) {
let newCard = BSUICardSprite(skill: card)
newCard.position = CGPoint(x: -width, y: 0)
newCard.displayerNode = self
visibleCards.append(newCard)
addChild(newCard)
returnCardAction(newCard, to: visibleCards.count - 1)
}
func hasActionRunning() -> Bool {
for card in visibleCards {
if card.hasActions() { return true }
}
return false
}
func displayCardAction(_ card: BSUICardSprite) {
displayedCard = card
let moveAction = SKAction.move(to: CGPoint(x: 0, y: 256), duration: animationDuration)
let scaleAction = SKAction.scale(to: 1.8, duration: animationDuration)
card.run(SKAction.group([moveAction, scaleAction]))
}
func returnCardAction(_ card: BSUICardSprite, to index: Int) {
let moveAction = SKAction.move(to: CGPoint(x: width / 2 - CGFloat(index * 132), y: 0), duration: animationDuration)
card.run(moveAction)
if card.xScale != 1 {
let scaleAction = SKAction.scale(to: 1, duration: animationDuration)
card.run(scaleAction)
}
}
func repositionCards() {
for (ind, card) in visibleCards.enumerated() {
returnCardAction(card, to: ind)
}
}
func tapActionBy(card: BSUICardSprite) {
if hasActionRunning() { return }
if let displayedCard = displayedCard,
let index = visibleCards.index(of: displayedCard) {
returnCardAction(displayedCard, to: index)
if displayedCard == card {
self.displayedCard = nil
confirmButton.isHidden = true
} else {
displayCardAction(card)
}
} else {
displayCardAction(card)
confirmButton.isHidden = false
}
}
}
class BSUICardSprite: SKSpriteNode, BSNodeButton {
var isEnabled: Bool {
return isUserInteractionEnabled
}
var isSelected: Bool = false
var nodeParent: SKNode? {
return parent
}
var nodeFrame: CGRect {
return frame
}
var skill: BSSkillCard
weak var displayerNode: BSUICardDisplayer?
init(skill: BSSkillCard) {
self.skill = skill
super.init(texture: SKTexture.init(imageNamed: skill.textureType.rawValue), color: .blue, size: CGSize(width: 100, height: 180))
isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if hasTouchDown(touches: touches) {
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if hasTouchMove(touches: touches) {
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if hasTouchEnd(touches: touches) {
displayerNode?.tapActionBy(card: self)
}
}
}
|
//
// ScreenView.swift
// TimeTracker
//
// Created by Hoang Tung on 2/13/20.
// Copyright © 2020 Hoang Tung. All rights reserved.
//
import UIKit
/// Giao thức HasCustomView xác định thuộc tính customView cho UIViewControllers được sử dụng để thay đổi thuộc tính view.
public protocol HasCustomView {
associatedtype CustomView: UIView
}
extension HasCustomView where Self: UIViewController {
/// The UIViewController's custom view.
public var customView: CustomView {
guard let customView = view as? CustomView else {
fatalError("Expected view to be of type \(CustomView.self) but got \(type(of: view)) instead")
}
return customView
}
}
class ScreenView: UIView {
// MARK: initial children View
let screenScrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.contentSize = CGSize(width: UIScreen.main.bounds.maxX, height: UIScreen.main.bounds.maxY * 2)
scrollView.alwaysBounceVertical = false
scrollView.alwaysBounceHorizontal = false
scrollView.isScrollEnabled = false
return scrollView
}()
let activateView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .systemTeal
return view
}()
let logoImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "riskIcon")
return imageView
}()
let appNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "iTracking"
label.font = .boldSystemFont(ofSize: 40)
label.textColor = .white
label.textAlignment = .center
return label
}()
let usernameTextField: CustomTextField = {
let textField = CustomTextField()
textField.placeholder = "Username"
return textField
}()
let usernameImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "user")
return imageView
}()
let passwordTextField: CustomTextField = {
let textField = CustomTextField()
textField.placeholder = "Password"
textField.isSecureTextEntry = true
return textField
}()
let passwordImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "password")
return imageView
}()
let submitButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Đăng nhập", for: .normal)
button.backgroundColor = .systemBlue
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 20
return button
}()
// MARK: initial View
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: setup view and layout
func setupView() {
addSubview(screenScrollView)
screenScrollView.addSubview(activateView)
activateView.addSubview(logoImageView)
activateView.addSubview(appNameLabel)
activateView.addSubview(usernameTextField)
activateView.addSubview(usernameImageView)
activateView.addSubview(passwordTextField)
activateView.addSubview(passwordImageView)
activateView.addSubview(submitButton)
}
func setupLayout() {
screenScrollView.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
screenScrollView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0).isActive = true
screenScrollView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0).isActive = true
screenScrollView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true
activateView.topAnchor.constraint(equalTo: screenScrollView.topAnchor, constant: 0).isActive = true
activateView.leadingAnchor.constraint(equalTo: screenScrollView.leadingAnchor, constant: 0).isActive = true
activateView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.maxX).isActive = true
activateView.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.maxY).isActive = true
logoImageView.centerXAnchor.constraint(equalTo: activateView.centerXAnchor, constant: 0).isActive = true
logoImageView.widthAnchor.constraint(equalTo: activateView.widthAnchor, multiplier: 0.4).isActive = true
logoImageView.centerYAnchor.constraint(equalTo: activateView.centerYAnchor,
constant: -UIScreen.main.bounds.maxY / 4).isActive = true
logoImageView.heightAnchor.constraint(equalTo: logoImageView.widthAnchor, multiplier: 1.3).isActive = true
appNameLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 16).isActive = true
appNameLabel.leadingAnchor.constraint(equalTo: activateView.leadingAnchor, constant: 0).isActive = true
appNameLabel.trailingAnchor.constraint(equalTo: activateView.trailingAnchor, constant: 0).isActive = true
appNameLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 32).isActive = true
usernameTextField.topAnchor.constraint(equalTo: appNameLabel.bottomAnchor, constant: 100).isActive = true
usernameTextField.centerXAnchor.constraint(equalTo: appNameLabel.centerXAnchor, constant: 0).isActive = true
usernameTextField.widthAnchor.constraint(equalTo: appNameLabel.widthAnchor, multiplier: 0.8).isActive = true
usernameTextField.heightAnchor.constraint(equalToConstant: 40).isActive = true
usernameImageView.centerYAnchor.constraint(equalTo: usernameTextField.centerYAnchor, constant: 0).isActive = true
usernameImageView.heightAnchor.constraint(equalTo: usernameTextField.heightAnchor, multiplier: 0.5).isActive = true
usernameImageView.widthAnchor.constraint(equalTo: usernameImageView.heightAnchor, multiplier: 1).isActive = true
usernameImageView.leadingAnchor.constraint(equalTo: usernameTextField.leadingAnchor, constant: 10).isActive = true
passwordTextField.topAnchor.constraint(equalTo: usernameTextField.bottomAnchor, constant: 16).isActive = true
passwordTextField.leadingAnchor.constraint(equalTo: usernameTextField.leadingAnchor, constant: 0).isActive = true
passwordTextField.trailingAnchor.constraint(equalTo: usernameTextField.trailingAnchor, constant: 0).isActive = true
passwordTextField.heightAnchor.constraint(equalTo: usernameTextField.heightAnchor, multiplier: 1).isActive = true
passwordImageView.centerYAnchor.constraint(equalTo: passwordTextField.centerYAnchor, constant: 0).isActive = true
passwordImageView.heightAnchor.constraint(equalTo: passwordTextField.heightAnchor, multiplier: 0.5).isActive = true
passwordImageView.widthAnchor.constraint(equalTo: passwordImageView.heightAnchor, multiplier: 1).isActive = true
passwordImageView.leadingAnchor.constraint(equalTo: passwordTextField.leadingAnchor, constant: 10).isActive = true
submitButton.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor, constant: 100).isActive = true
submitButton.leadingAnchor.constraint(equalTo: usernameTextField.leadingAnchor, constant: 0).isActive = true
submitButton.trailingAnchor.constraint(equalTo: usernameTextField.trailingAnchor, constant: 0).isActive = true
submitButton.heightAnchor.constraint(equalTo: usernameTextField.heightAnchor, multiplier: 1).isActive = true
}
}
|
//
// PinCodeView.swift
// Vozon
//
// Created by Дастан Сабет on 21.05.2018.
// Copyright © 2018 Дастан Сабет. All rights reserved.
//
import UIKit
protocol PinCodeDetection: class {
func login(code: String)
}
class PinCodeView: UIView {
var arrayOfLabel: [UILabel] = []
var arrayOfView: [UIView] = []
var numberOfDigits: Int = 0
var filledColor: UIColor!
var emptyColor: UIColor!
lazy var textField: UITextField = {
let textfield = UITextField()
textfield.tintColor = UIColor.clear
textfield.textColor = UIColor.clear
textfield.backgroundColor = UIColor.clear
textfield.keyboardType = .numberPad
textfield.addTarget(self, action: #selector(textFieldAction), for: .editingChanged)
return textfield
}()
weak var delegate: PinCodeDetection?
init(numberOfDigits: Int, filledColor: UIColor, emptyColor: UIColor, space: CGFloat) {
super.init(frame: .zero)
self.numberOfDigits = numberOfDigits
self.filledColor = filledColor
self.emptyColor = emptyColor
for _ in 0..<numberOfDigits {
arrayOfLabel.append(createLabel())
arrayOfView.append(createView(color: emptyColor))
}
let stackOfLabel = UIStackView()
stackOfLabel.distribution = .fillEqually
stackOfLabel.axis = .horizontal
stackOfLabel.spacing = space
let stackOfView = UIStackView()
stackOfView.distribution = .fillEqually
stackOfView.axis = .horizontal
stackOfView.spacing = space
for label in arrayOfLabel {
stackOfLabel.addArrangedSubview(label)
}
for view in arrayOfView {
stackOfView.addArrangedSubview(view)
view.snp.makeConstraints { (make) in
make.height.equalTo(4)
}
}
let fullStack = UIStackView(arrangedSubviews: [stackOfLabel, stackOfView])
fullStack.axis = .vertical
fullStack.spacing = 8
addSubview(fullStack)
fullStack.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
addSubview(textField)
}
func createLabel() -> UILabel {
let label = UILabel()
label.textColor = UIColor(hex: "222222")
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 30)
return label
}
func createView(color: UIColor) -> UIView {
let view = UIView()
view.backgroundColor = color
return view
}
@objc func textFieldAction(_ textField: UITextField) {
var text = textField.text!
if text.count <= numberOfDigits {
checkText(text.count)
}else {
let indexEndOfText = text.index(text.startIndex, offsetBy: numberOfDigits)
text = String(text[..<indexEndOfText])
textField.text = text
checkText(text.count)
}
}
func checkText(_ count: Int) {
fillColor(in: count)
if count == 4 {
delegate?.login(code: textField.text!)
}
}
func fillColor(in range: Int) {
let text = textField.text!
for i in 0..<range {
arrayOfView[i].backgroundColor = filledColor
let indexStartOfText = text.index(text.startIndex, offsetBy: i)
arrayOfLabel[i].text = String(text[indexStartOfText])
}
for range in range..<arrayOfView.count {
arrayOfView[range].backgroundColor = emptyColor
arrayOfLabel[range].text = nil
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
//
// model.swift
// contact
//
// Created by test on 11/24/15.
// Copyright © 2015 Mrtang. All rights reserved.
//
import Foundation
class TodoModel:NSObject {
var imageUrl:String
var name:String
var gender:String
var phoneNumber:String
init(imageUrl:String,name:String,gender:String,phoneNumber:String) {
self.imageUrl = imageUrl
self.name = name
self.gender = gender
self.phoneNumber = phoneNumber
}
}
|
//
// CDMovie+CoreDataClass.swift
//
//
// Created by Elias Paulino on 08/06/19.
//
//
import Foundation
import CoreData
@objc(CDMovie)
public class CDMovie: NSManagedObject {
var toMovie: Movie {
var genresArray: [Int] = []
if let genres = self.genres?.components(separatedBy: " ") {
genresArray = genres.compactMap({ (genre) -> Int? in
return Int(genre)
})
}
let movie = Movie.init(id: Int(self.id ?? "nil"), title: self.title, posterPath: self.poster, backdropPath: self.backDrop, isAdult: nil, overview: self.overview, releaseDate: self.releaseDate, genreIDs: genresArray)
return movie
}
@discardableResult
convenience init?(_ context: NSManagedObjectContext? = CoreDataStack.persistentContainer.viewContext, fromMovie movie: Movie) {
guard let context = context else {
return nil
}
self.init(context: context)
updateWithMovieValues(movie: movie)
}
func updateWithMovieValues(movie: Movie) {
self.id = movie.id != nil ? String(movie.id!) : nil
self.title = movie.title
self.backDrop = movie.backdropPath
self.poster = movie.posterPath
self.overview = movie.overview
self.genres = movie.genreIDs.map({ (genreID) -> String in
return String(genreID)
}
).joined(separator: " ")
self.releaseDate = movie.releaseDate
}
}
|
//
// LostDelegatesViewController.swift
// CMUNC
//
// Created by Cameron Hamidi on 4/2/19.
// Copyright © 2019 Cornell Model United Nations Conference. All rights reserved.
//
import UIKit
import Mailgun_In_Swift
import CoreLocation
class LostDelegatesViewController: UIViewController, UITextViewDelegate {
var locationManager: CLLocationManager!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var committeeTextField: UITextField!
@IBOutlet weak var schoolTextField: UITextField!
@IBOutlet weak var destinationTextField: UITextField!
@IBOutlet weak var notesTextView: UITextView!
@IBOutlet weak var submitButton: UIButton!
let notesTextViewPlaceholder = "The app can determine your approximate location, but additional information (such as the building and room you are currently in, nearby landmarks, etc) will help us reach you faster."
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: Selector("endEditing:")))
notesTextView.delegate = self
notesTextView.layer.borderWidth = 1
notesTextView.layer.borderColor = UIColor(white: 2/3.0, alpha: 1.0).cgColor
notesTextView.layer.cornerRadius = 5
submitButton.layer.cornerRadius = 5
submitButton.layer.borderWidth = 1
submitButton.layer.borderColor = UIColor.lightGray.cgColor
// let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
// rightSwipe.direction = .right
// view.addGestureRecognizer(rightSwipe)
locationManager = CLLocationManager()
// Ask for Authorisation from the User.
// self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
if locationManager.location?.coordinate == nil {
noLocationServicesAlert()
}
} else {
noLocationServicesAlert()
}
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
view.addGestureRecognizer(pan)
}
@objc func handlePanGesture(_ sender: UIPanGestureRecognizer) {
var initialPoint: CGPoint = .zero
switch sender.state {
case .began:
initialPoint = sender.translation(in: self.view)
break
case .changed:
let panned = sender.translation(in: self.view)
if panned.x > initialPoint.x { //right swipe
dismiss(animated: true, completion: nil)
}
break
default:
break
}
}
// @objc func handleSwipes(_ sender: UISwipeGestureRecognizer) {
// if sender.direction == .right {
// dismiss(animated: true, completion: nil)
// }
// }
func noLocationServicesAlert() {
var alert = UIAlertController(title: "Enable Location Services", message: "In order to determine your location so that we may send a staffer to assist you, the app needs to know your GPS coordinates. In Settings, please enable location services and allow the CMUNC app to view your location.", preferredStyle: .alert)
var action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true)
}
@IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView == self.notesTextView {
if textView.text == self.notesTextViewPlaceholder {
textView.text = ""
textView.textColor = .black
}
}
}
@IBAction func submitPressed(_ sender: Any) {
if nameTextField.text == "" || phoneTextField.text == "" || committeeTextField.text == "" || schoolTextField.text == "" || destinationTextField.text == "" || notesTextView.text == "" || notesTextView.text == notesTextViewPlaceholder {
displayIncompleteAlert()
} else {
var name = nameTextField.text!
var phone = phoneTextField.text!
var committee = committeeTextField.text!
var school = schoolTextField.text!
var destination = destinationTextField.text!
var notes = notesTextView.text!
var coordinates = locationManager.location?.coordinate
if coordinates == nil {
locationManager.requestWhenInUseAuthorization()
noLocationServicesAlert()
return
}
var latitude = coordinates!.latitude
var longitude = coordinates!.longitude
print(latitude)
print(longitude)
// let mailgun = MailgunAPI(apiKey: appDataResponse.apiKey, clientDomain: appDataResponse.clientDomain)
var bodyIntro = "<body><b>Delegate Information:</b></body>"
var bodyName = "<body>Name: \(name)</body>"
var bodyPhone = "<body>Phone: \(phone)</body>"
var bodyCommittee = "<body>Committee: \(committee)</body>"
var bodySchool = "<body>School: \(school)</body>"
var bodyDestination = "<body>Destination: \(destination)</body>"
var bodyNotes = "<body>Notes: \(notes)</body>"
var locationNotes = "<body><a href=\"https://www.google.com/maps\">Location (copy and paste into google maps):</a> \(latitude), \(longitude)</body>"
var emailBody = bodyIntro + bodyName + bodyPhone + bodyCommittee + bodySchool + bodyDestination + bodyNotes
print(appDataResponse!)
print(appDataResponse.apiKey)
// mailgun.sendEmail(to: appDataResponse.toEmail, from: appDataResponse.fromEmail, subject: "Lost Delegate", bodyHTML: emailBody) { mailgunResult in
if mailgunResult.success{
print("Email was sent")
}
}
var alert = UIAlertController(title: "Message Sent", message: "We have received your message. A staffer will arrive at your location shortly. Please do not move.", preferredStyle: .alert)
var action = UIAlertAction(title: "Ok", style: .default, handler: { alert in
self.dismiss(animated: true, completion: nil)
})
alert.addAction(action)
present(alert, animated: true)
}
}
func displayIncompleteAlert() {
var alert = UIAlertController(title: "Incomplete Submission", message: "Please fill out all fields.", preferredStyle: .alert)
var action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true)
}
}
|
//
// FirstViewController.swift
// ikid
//
// Created by JJ Guo on 2/3/18.
// Copyright © 2018 JJ Guo. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var jokeImage: UIImageView!
@IBOutlet weak var jokeChangeButton: UIButton!
let question = UIImage(named: "question.png")
let answer = UIImage(named: "answer.png")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func jokeChangeButtonPressed(_ sender: Any) {
if jokeImage.image == question {
jokeImage.image = answer
UIView.transition(with: jokeImage, duration: 0.3, options: .transitionFlipFromLeft, animations: nil, completion: nil)
} else {
jokeImage.image = question
UIView.transition(with: jokeImage, duration: 0.3, options: .transitionFlipFromLeft, animations: nil, completion: nil)
}
}
}
|
//
// HerbList.swift
// FolkMedicine
//
// Created by Minho Choi on 2020/04/18.
// Copyright © 2020 Minho Choi. All rights reserved.
//
import SwiftUI
struct HerbRow: View {
let item: herbItem
var body: some View {
HStack {
AsyncImage(url: URL(string: item.thumbImgUrl)!, placeholder: Image(systemName: "photo")).scaledToFit()
.clipShape(Circle())
VStack(alignment: .leading) {
HStack {
Text("\(item.korName)")
Spacer()
Text("\(item.sciName) ")
.italic()
.lineLimit(1)
.font(.custom("Didot", size: 12))
.minimumScaleFactor(0.5)
}
Text("\(item.chnName)")
.foregroundColor(.gray)
}
Spacer()
}.frame(height: 60)
}
}
|
//: Playground - noun: a place where people can play
import Foundation
public class Store {
let storesToDisk: Bool = true
}
public class BookmarkStore: Store {
let itemCount: Int = 10
}
public struct Bookmark {
enum Group {
case Tech
case News
}
private let store = {
return BookmarkStore()
}()
let title: String?
let url: NSURL
let keywords: [String]
let group: Group
}
let aBookmark = Bookmark(title: "Appventure", url: NSURL(string: "appventure.me")!, keywords: ["Swift", "iOS", "OSX"], group: .Tech)
func reflectableSubject<T>(_ subject: Any, hasPropertyWithName name: String, ofType type: T.Type) -> Bool {
let mirror = Mirror(reflecting: subject)
guard let propertyChild = mirror.children.first(where: { name == ($0.label ?? "") }) else {
return false
}
let propertyChildValueMirror = Mirror(reflecting: propertyChild.value)
return (propertyChildValueMirror.subjectType == type.self)
}
let hasOptionalTitle = reflectableSubject(aBookmark, hasPropertyWithName: "title", ofType: Optional<String>.self)
let hasKeywords = reflectableSubject(aBookmark, hasPropertyWithName: "keywords", ofType: [String].self)
|
//
// TodoListViewModel.swift
// BMKToDo
//
// Created by Bharat Khatke on 28/07/21.
//
import Foundation
class TodoListViewModel {
var todoSectionDataList: [SectionModel]
init() {
todoSectionDataList = [SectionModel]()
}
func refershTodoList() -> [SectionModel] {
return TodoCoreDataModel().getSavedDataFromCoreData()
}
func getTodoHeaderObject(_ section: Int) -> SectionModel {
return self.todoSectionDataList[section]
}
var numberOFSections: Int {
return todoSectionDataList.count
}
func numberOfRowsInSection(_ section: Int) -> Int {
return self.todoSectionDataList[section].numberOfItems
}
func todoTaskAtIndex(_ section: Int, _ index: Int) -> TodoTask {
let todoTaskData = self.todoSectionDataList[section].data[index]
return todoTaskData
}
func getSectionID(_ section: Int) -> Int {
return self.todoSectionDataList[section].id
}
func deleteTodoItemFromList(_ managedObject: TodoTask) {
TodoCoreDataModel().deleteEntityData(managedObject)
todoSectionDataList = refershTodoList()
}
//Here you can add more mothods or property that need in your controller
}
|
//
// CustomMath.swift
// Nebula Messenger
//
// Created by Shelby McCowan on 1/8/19.
// Copyright © 2019 Shelby McCowan. All rights reserved.
//
import Foundation
import UIKit
// Class to explicitly access CustomMath
class CustomMath {
static func getPathToCircleCenter(degrees: CGFloat, radius: CGFloat) -> [CGFloat]{
let rads = (degrees * CGFloat.pi)/180
let xRatio = cos(rads)
let yRatio = sin(rads)
return [xRatio, yRatio]
}
}
|
import Bow
import SwiftCheck
// MARK: Generator for Property-based Testing
extension Kleisli: Arbitrary where F: ArbitraryK, A: Arbitrary {
public static var arbitrary: Gen<Kleisli<F, D, A>> {
Gen.from(KleisliPartial.generate >>> Kleisli.fix)
}
}
// MARK: Instance of ArbitraryK for Kleisli
extension KleisliPartial: ArbitraryK where F: ArbitraryK {
public static func generate<A: Arbitrary>() -> KleisliOf<F, D, A> {
let x: Kind<F, A> = F.generate()
return Kleisli { _ in x }
}
}
|
//
// AssetsGridViewController.swift
// Social Photos
//
// Created by shoulong li on 12/28/15.
// Copyright © 2015 shoulong li. All rights reserved.
//
import UIKit
import PhotosUI
import Photos
private let reuseIdentifier = "assetReuseIdentifier"
class AssetsGridViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PHPhotoLibraryChangeObserver {
var assetsFetchResults: PHFetchResult?
var assetCollection: PHAssetCollection?
let LINE_SPACING: CGFloat = 2.0
let INTERITEM_SPACING: CGFloat = 2.0
let COLUMNS: CGFloat = 4.0
private var imageManager: PHCachingImageManager?
private var previousPreheatRect: CGRect = CGRect()
static var AssetGridThumbnailSize: CGSize = CGSize()
override func awakeFromNib() {
self.imageManager = PHCachingImageManager()
self.resetCachedAssets()
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}
deinit {
PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.backgroundColor = UIColor.whiteColor()
//self.collectionView!.registerClass(GridViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Begin caching assets in and around collection view's visible rect.
self.updateCachedAssets()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Determine the size of the thumbnails to request from the PHCachingImageManager
let scale = UIScreen.mainScreen().scale
//let cellSize = (self.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
let itemWidth = getCollectionCellSize()
let cellSize = CGSize(width: itemWidth, height: itemWidth)
AssetsGridViewController.AssetGridThumbnailSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale)
// // Add button to the navigation bar if the asset collection supports adding content.
// if self.assetCollection == nil || self.assetCollection!.canPerformEditOperation(.AddContent) {
// self.navigationItem.rightBarButtonItem = self.addButton
// } else {
// self.navigationItem.rightBarButtonItem = nil
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - PHPhotoLibraryChangeObserver
func photoLibraryDidChange(changeInstance: PHChange) {
// Check if there are changes to the assets we are showing.
guard let
assetsFetchResults = self.assetsFetchResults,
collectionChanges = changeInstance.changeDetailsForFetchResult(assetsFetchResults)
else {return}
/*
Change notifications may be made on a background queue. Re-dispatch to the
main queue before acting on the change as we'll be updating the UI.
*/
dispatch_async(dispatch_get_main_queue()) {
// Get the new fetch result.
self.assetsFetchResults = collectionChanges.fetchResultAfterChanges
let collectionView = self.collectionView!
if !collectionChanges.hasIncrementalChanges || collectionChanges.hasMoves {
// Reload the collection view if the incremental diffs are not available
collectionView.reloadData()
} else {
/*
Tell the collection view to animate insertions and deletions if we
have incremental diffs.
*/
collectionView.performBatchUpdates({
if let removedIndexes = collectionChanges.removedIndexes
where removedIndexes.count > 0 {
collectionView.deleteItemsAtIndexPaths(removedIndexes.aapl_indexPathsFromIndexesWithSection(0))
}
if let insertedIndexes = collectionChanges.insertedIndexes
where insertedIndexes.count > 0 {
collectionView.insertItemsAtIndexPaths(insertedIndexes.aapl_indexPathsFromIndexesWithSection(0))
}
if let changedIndexes = collectionChanges.changedIndexes
where changedIndexes.count > 0 {
collectionView.reloadItemsAtIndexPaths(changedIndexes.aapl_indexPathsFromIndexesWithSection(0))
}
}, completion: nil)
}
self.resetCachedAssets()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.assetsFetchResults?.count ?? 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let asset = self.assetsFetchResults![indexPath.item] as! PHAsset
// Dequeue an AAPLGridViewCell.
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! GridViewCell
cell.representedAssetIdentifier = asset.localIdentifier
// Add a badge to the cell if the PHAsset represents a Live Photo.
if #available(iOS 9.1, *) {
let hasLivePhoto = asset.mediaSubtypes.contains(.PhotoLive)
if hasLivePhoto {
// Add Badge Image to the cell to denote that the asset is a Live Photo.
let badge = PHLivePhotoView.livePhotoBadgeImageWithOptions(.OverContent)
cell.livePhotoBadgeImage = badge
}
}
// Request an image for the asset from the PHCachingImageManager.
self.imageManager?.requestImageForAsset(asset,
targetSize: AssetsGridViewController.AssetGridThumbnailSize,
contentMode: PHImageContentMode.AspectFill,
options: nil)
{result, info in
// Set the cell's thumbnail image if it's still showing the same asset.
if cell.representedAssetIdentifier == asset.localIdentifier {
cell.thumbnailImage = result
}
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
self.performSegueWithIdentifier("showAsset", sender: cell)
}
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
//MARK: UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let itemWidth = getCollectionCellSize()
return CGSize(width: itemWidth, height: itemWidth)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return LINE_SPACING
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return INTERITEM_SPACING
}
//MARK: - UIScrollViewDelegate
override func scrollViewDidScroll(scrollView: UIScrollView) {
// Update cached assets for the new visible area.
self.updateCachedAssets()
}
//MARK: - Asset Caching
private func resetCachedAssets() {
self.imageManager?.stopCachingImagesForAllAssets()
self.previousPreheatRect = CGRectZero
}
private func updateCachedAssets() {
guard self.isViewLoaded() && self.view.window != nil else {
return
}
// The preheat window is twice the height of the visible rect.
var preheatRect = self.collectionView!.bounds
preheatRect = CGRectInset(preheatRect, 0.0, -0.5 * CGRectGetHeight(preheatRect))
/*
Check if the collection view is showing an area that is significantly
different to the last preheated area.
*/
let delta = abs(CGRectGetMidY(preheatRect) - CGRectGetMidY(self.previousPreheatRect))
if delta > CGRectGetHeight(self.collectionView!.bounds) / 3.0 {
// Compute the assets to start caching and to stop caching.
var addedIndexPaths: [NSIndexPath] = []
var removedIndexPaths: [NSIndexPath] = []
self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: {removedRect in
let indexPaths = self.collectionView!.aapl_indexPathsForElementsInRect(removedRect)
removedIndexPaths += indexPaths
}, addedHandler: {addedRect in
let indexPaths = self.collectionView!.aapl_indexPathsForElementsInRect(addedRect)
addedIndexPaths += indexPaths
})
let assetsToStartCaching = self.assetsAtIndexPaths(addedIndexPaths)
let assetsToStopCaching = self.assetsAtIndexPaths(removedIndexPaths)
// Update the assets the PHCachingImageManager is caching.
self.imageManager?.startCachingImagesForAssets(assetsToStartCaching,
targetSize: AssetsGridViewController.AssetGridThumbnailSize,
contentMode: PHImageContentMode.AspectFill,
options: nil)
self.imageManager?.stopCachingImagesForAssets(assetsToStopCaching,
targetSize: AssetsGridViewController.AssetGridThumbnailSize,
contentMode: PHImageContentMode.AspectFill,
options: nil)
// Store the preheat rect to compare against in the future.
self.previousPreheatRect = preheatRect
}
}
private func computeDifferenceBetweenRect(oldRect: CGRect, andRect newRect: CGRect, removedHandler: (CGRect)->Void, addedHandler: (CGRect)->Void) {
if CGRectIntersectsRect(newRect, oldRect) {
let oldMaxY = CGRectGetMaxY(oldRect)
let oldMinY = CGRectGetMinY(oldRect)
let newMaxY = CGRectGetMaxY(newRect)
let newMinY = CGRectGetMinY(newRect)
if newMaxY > oldMaxY {
let rectToAdd = CGRectMake(newRect.origin.x, oldMaxY, newRect.size.width, (newMaxY - oldMaxY))
addedHandler(rectToAdd)
}
if oldMinY > newMinY {
let rectToAdd = CGRectMake(newRect.origin.x, newMinY, newRect.size.width, (oldMinY - newMinY))
addedHandler(rectToAdd)
}
if newMaxY < oldMaxY {
let rectToRemove = CGRectMake(newRect.origin.x, newMaxY, newRect.size.width, (oldMaxY - newMaxY))
removedHandler(rectToRemove)
}
if oldMinY < newMinY {
let rectToRemove = CGRectMake(newRect.origin.x, oldMinY, newRect.size.width, (newMinY - oldMinY))
removedHandler(rectToRemove)
}
} else {
addedHandler(newRect)
removedHandler(oldRect)
}
}
private func assetsAtIndexPaths(indexPaths: [NSIndexPath]) -> [PHAsset] {
let assets = indexPaths.map{self.assetsFetchResults![$0.item] as! PHAsset}
return assets
}
func getCollectionCellSize() -> CGFloat {
return (view.bounds.size.width - ( COLUMNS - 1 ) * INTERITEM_SPACING) / COLUMNS
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Configure the destination AAPLAssetViewController.
if let assetViewController = segue.destinationViewController as? AssetViewController {
let indexPath = self.collectionView!.indexPathForCell(sender as! UICollectionViewCell)!
assetViewController.asset = self.assetsFetchResults![indexPath.item] as? PHAsset
assetViewController.assetCollection = self.assetCollection
}
}
}
|
//
// ShoppingcartViewController.swift
// CP103D_Topic0308
//
// Created by User on 2019/3/21.
// Copyright © 2019 min-chia. All rights reserved.
//
import UIKit
class ShoppingcartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var cartTableView: UITableView!
@IBOutlet weak var cartTotalPrice: UILabel!
var totalPrice = 0.0
var carts = [Cart]()
override func viewDidLoad() {
let cart1 = Cart(id: 1, name: "發熱衣", descrip: "冬天最好的選擇", price: 200.0, mainclass: "Man", subclass: "0", shelf: "true", evulation: 4, color1: "0", color2: "1", size1: "0", size2: "1", specialPrice: 180.0, quatity: 1)
let cart2 = Cart(id: 2, name: "牛仔褲", descrip: "丹寧布永不退流行", price: 300.0, mainclass: "Woman", subclass: "1", shelf: "true", evulation: 5, color1: "1", color2: "0", size1: "1", size2: "0", specialPrice: 270.0, quatity: 2)
carts.append(cart1)
carts.append(cart2)
}
override func viewWillAppear(_ animated: Bool) {
// loadData()
cartTableView.reloadData()
}
func fileInDocuments(fileName: String) -> URL {
let fileManager = FileManager()
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let fileUrl = urls.first!.appendingPathComponent(fileName)
return fileUrl
}
func saveData(carts:[Cart]) {
let dataUrl = fileInDocuments(fileName: "cartData")
let encoder = JSONEncoder()
let jsonData = try! encoder.encode(carts)
do {
/* 如果將requiringSecureCoding設為true,Spot類別必須改遵從NSCoding的子型NSSecureCoding */
let cartData = try NSKeyedArchiver.archivedData(withRootObject: jsonData, requiringSecureCoding: true)
try cartData.write(to: dataUrl)
} catch let error {
print(error.localizedDescription)
}
}
func loadData() {
let fileManager = FileManager()
let decoder = JSONDecoder()
let dataUrl = fileInDocuments(fileName: "cartData")
if fileManager.fileExists(atPath: dataUrl.path) {
if let data = try? Data(contentsOf: dataUrl) {
if let jsonData = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! Data {
let result = try! decoder.decode([Cart].self, from: jsonData)
carts = result
} else {
// lbFile.text = "no data found error"
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return carts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
// Configure the cell...
let cart = carts[indexPath.row]
cell.numberStepper.value = Double(cart.quatity)
cell.nameLabel.text = cart.name
cell.priceLabel.text = String(cart.price * Double(cart.quatity))
cell.colarLabel.text = cart.color1
cell.sizeLabel.text = cart.size1
cell.quantityLabel.text = cart.quatity.description
let item = carts[indexPath.row] // assuming `dataSource` is the data source array
cell.numberStepper.value = Double(item.quatity)
cell.quantityLabel.text = "\(item.quatity)"
var totalprice = 0.0
for cartTmp in self.carts{
totalprice += (cartTmp.price * Double(cartTmp.quatity))
}
cartTotalPrice.text = totalprice.description
cell.observation = cell.numberStepper.observe( \.value, options: [.new, .old]) { (stepper, change) in
cell.quantityLabel.text = "\(Int(change.newValue!))"
cell.priceLabel.text = String(change.newValue! * cart.price)
totalprice = Double(self.cartTotalPrice.text!)!
totalprice = totalprice + (change.newValue! - change.oldValue!) * cart.price
print(change.newValue!.description)
print(change.oldValue!.description)
self.cartTotalPrice.text = totalprice.description
self.carts[indexPath.row].quatity = Int(cell.quantityLabel.text!)!
}
return cell
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
(cell as! CartCell).observation = nil
}
func stepperButton(sender: CartCell) {
if let indexPath = cartTableView.indexPath(for: sender){
print(indexPath)
let cart = carts[indexPath.row]
cart.quatity = Int(sender.numberStepper.value)
}
}
func statusDescription(stayusCode:Int) -> (String) {
if stayusCode == 0 {
return "未出貨"
} else if stayusCode == 1 {
return "已出貨"
} else if stayusCode == 2 {
return "已退貨"
} else {
return "已取消"
}
}
// 左滑修改與刪除資料
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// // 左滑時顯示Edit按鈕
// let edit = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
// let spotUpdateVC = self.storyboard?.instantiateViewController(withIdentifier: "spotUpdateVC") as! SpotUpdateVC
// let spot = self.spots[indexPath.row]
// spotUpdateVC.spot = spot
// self.navigationController?.pushViewController(spotUpdateVC, animated: true)
// })
// edit.backgroundColor = UIColor.lightGray
// 左滑時顯示Delete按鈕
let delete = UITableViewRowAction(style: .destructive, title: "Delete", handler: { (action, indexPath) in
self.carts.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadData()
})
return [delete]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func checkout(_ sender: UIButton) {
if carts.count == 0 {
let alert = UIAlertController.init(title: "沒有商品", message: "請將商品加入購物車", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel))
self.present(alert, animated: true, completion: nil)
}
else {
self.performSegue(withIdentifier: "Checkout", sender: sender)
}
}
override func viewDidDisappear(_ animated: Bool) {
saveData(carts: carts)
}
}
|
//
// ViewController.swift
// RVCGenerator
//
// Created by Ivan Shokurov on 8/8/19.
// Copyright © 2019 Ivan Shokurov. All rights reserved.
//
import UIKit
/**
`ResponsiveViewController` is a class with interactive behavior to present
error, loading and normal state depending on your own needs.
*/
public class ResponsiveViewController: UIViewController {
// MARK: – View State
/// `ViewState` is enumeration which defines view controller's visual state.
public enum ViewState {
/// Set this value everytime when it's necessary to present data.
case normal
/// Set this value everytime when it's necessary to present error.
case error
/// Set this value everytime when it's necessary to load data.
/// - Note: This is a default value.
case loading // <- default value.
}
private var _viewState: ViewState
/// Property which mainly focused on view state logic.
public final var viewState: ViewState {
set(newViewState) {
self._viewState = newViewState
self.refreshView()
}
get {
return self._viewState
}
}
// MARK: – Error Description
/// Structure of view model which will be presented in
/// default error view.
public typealias ErrorDescription = (title: String, message: String?)
private var errorDescription: ErrorDescription?
private let defaultErrorDescription = ErrorDescription(
"Unknown Error",
"It seems you need to debug code inside app."
)
// MARK: – Loading Description
/// Structure of view model which will be presented in
/// default loading view.
public typealias LoadingDescription = String
private var loadingDescription: LoadingDescription?
private let defaultLoadingDescription = LoadingDescription("Loading..")
// MARK: – Private Properties
private var needsCustomErrorView = false
private var needsCustomLoadingView = false
// MARK: – UI
private lazy var defaultErrorView = ErrorView(
frame: UIScreen.main.bounds,
inside: self
)
private lazy var defaultLoadingView = LoadingView(frame: UIScreen.main.bounds)
private let normalView: UIView
private var customErrorView: UIView?
private var customLoadingView: UIView?
// MARK: – Initialization
/// Main initialiazer.
/// - Parameter normalView: this parameter defines default value where you needs to put and present data further.
/// - Parameter viewState: this parameter defines view state. Default value is equal to `loading`.
/// - Returns: UIViewController instance with responsive and adaptive view. 👍🏻
init(withCustomView normalView: UIView, andViewState viewState: ViewState = .loading) {
self.normalView = normalView
self._viewState = viewState
super.init(nibName: nil, bundle: nil)
self.view = normalView
#if DEBUG
print("[\(self) init]")
#endif
}
required init?(coder aDecoder: NSCoder) {
fatalError("[ResponsiveViewController init:coder] it had been not implemented yet.")
}
// MARK: – View Life Cycle
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.defineLoadingDescription("Идёт загрузка данных..")
self.refreshView()
}
deinit {
#if DEBUG
print("[\(self) deinit]")
#endif
}
// MARK: – Orientation Rotations
override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.resizeView(byNewValue: size)
}
// MARK: – Public Methods
/// Define you own custom view to present view controller's state
/// when its loads something.
public final func setCustomLoadingView(_ loadingView: UIView) {
self.needsCustomLoadingView = true
self.customLoadingView = loadingView
}
/// Define you own custom view to present error.
public final func setCustomErrorView(_ errorView: UIView) {
self.needsCustomErrorView = true
self.customErrorView = errorView
}
/// Removing your custom loading view, `ResponsiveViewController` will return
/// default LoadingView instance each time `ResponsiveViewController` will load something.
public final func removeCustomLoadingView() {
self.needsCustomLoadingView = false
self.customLoadingView = nil
}
/// Removing your custom error view, `ResponsiveViewController` will return
/// default ErrorView instance each time `ResponsiveViewController` will receive
/// some error.
public final func removeCustomErrorView() {
self.needsCustomErrorView = false
self.customErrorView = nil
}
/// Depending on you needs, define error description when its has just been catched.
public final func defineErrorDescription(_ errorDescription: ErrorDescription) {
self.errorDescription = errorDescription
}
/// Depending on you needs, define description while something is loading.
public final func defineLoadingDescription(_ loadingDescription: LoadingDescription) {
self.loadingDescription = loadingDescription
}
// MARK: – Private Methods
private func refreshView() {
switch self._viewState {
case .normal:
self.presentDefaultView()
case .loading:
self.presentLoadingView()
case .error:
self.presentErrorView()
}
}
private func presentDefaultView() {
self.hideErrorViewIfNecessary()
self.hideLoadingViewIfNecessary()
}
private func hideLoadingViewIfNecessary() {
switch self.needsCustomLoadingView {
case true:
if let loadingView = self.customLoadingView, self.view.subviews.contains(loadingView) {
self.customErrorView?.removeFromSuperview()
}
case false:
if self.view.subviews.contains(self.defaultLoadingView) {
self.defaultLoadingView.removeFromSuperview()
}
}
}
private func hideErrorViewIfNecessary() {
switch self.needsCustomErrorView {
case true:
if let errorView = self.customErrorView, self.view.subviews.contains(errorView) {
self.customErrorView?.removeFromSuperview()
}
case false:
if self.view.subviews.contains(self.defaultErrorView) {
self.defaultErrorView.removeFromSuperview()
}
}
}
private func presentLoadingView() {
switch self.needsCustomLoadingView {
case true:
if let loadingView = self.customLoadingView {
self.view.addSubview(loadingView)
}
case false:
self.defaultLoadingView.setLoadingText(self.loadingDescription ?? self.defaultLoadingDescription)
self.view.addSubview(self.defaultLoadingView)
}
}
private func presentErrorView() {
self.hideLoadingViewIfNecessary()
switch self.needsCustomErrorView {
case true:
if let errorView = self.customErrorView {
self.view.addSubview(errorView)
}
case false:
self.defaultErrorView.setErrorDescription(self.errorDescription ?? self.defaultErrorDescription)
self.view.addSubview(self.defaultErrorView)
}
}
private func resizeView(byNewValue newSize: CGSize) {
switch self._viewState {
case .normal:
return
case .loading:
self.resizeLoadingView(byNewValue: newSize)
case .error:
self.resizeErrorView(byNewValue: newSize)
}
}
private func resizeLoadingView(byNewValue newSize: CGSize) {
switch self.needsCustomLoadingView {
case true:
self.customLoadingView?.frame = CGRect(origin: .zero, size: newSize)
case false:
self.defaultLoadingView.frame = CGRect(origin: .zero, size: newSize)
}
}
private func resizeErrorView(byNewValue newSize: CGSize) {
switch self.needsCustomErrorView {
case true:
self.customErrorView?.frame = CGRect(origin: .zero, size: newSize)
case false:
self.defaultErrorView.frame = CGRect(origin: .zero, size: newSize)
}
}
}
// MARK: – Error View Delegate
extension ResponsiveViewController: ErrorViewDelegate {
/// Override this method to handle button touch event
/// when ResponsiveViewController has error view state.
public func didTouchButtonInErrorView() {
print("[\(self) didTouchButtonInErrorView] has not been implemented in sub class yet.")
}
}
|
import Kanna
class PassageBuilder {
let name: String
let content: String
init(name: String, content: String) {
self.name = name
self.content = content
}
func build() -> PassageData {
var passageContent = ""
var next = [String]()
for (index, component) in content.components(separatedBy: "[[").enumerated() {
if index == 0 {
passageContent = component.replacingOccurrences(of: "\n", with: "")
} else {
let filtered = component.replacingOccurrences(of: "]]", with: "").replacingOccurrences(of: "[[", with: "").replacingOccurrences(of: "\n", with: "")
next.append(filtered.components(separatedBy: "->").first ?? "")
}
}
return PassageData(name: name,
content: passageContent,
next: next)
}
}
|
//
// StoreFSM.swift
// Podest
//
// Created by Michael Nisi on 21.04.18.
// Copyright © 2018 Michael Nisi. All rights reserved.
//
import UIKit
import StoreKit
import os.log
private let log = OSLog(subsystem: "ink.codes.podest", category: "store")
/// Enumerates known events within the store.
private enum StoreEvent {
case resume
case pause
case failed(ShoppingError)
case online
case pay(ProductIdentifier)
case productsReceived([SKProduct], ShoppingError?)
case purchased(ProductIdentifier)
case purchasing(ProductIdentifier)
case receiptsChanged
case update
case considerReview
case review
case cancelReview(Bool)
}
extension StoreEvent: CustomStringConvertible {
var description: String {
switch self {
case .resume:
return "StoreEvent: resume"
case .pause:
return "StoreEvent: pause"
case .failed(let error):
return "StoreEvent: failed: \(error)"
case .online:
return "StoreEvent: online"
case .pay(let productIdentifier):
return "StoreEvent: pay: \(productIdentifier)"
case .productsReceived(let products, let error):
return """
StoreEvent: productsReceived: (
products: \(products),
error: \(error.debugDescription)
)
"""
case .purchased(let productIdentifier):
return "StoreEvent: purchased: \(productIdentifier)"
case .purchasing(let productIdentifier):
return "StoreEvent: purchasing: \(productIdentifier)"
case .receiptsChanged:
return "StoreEvent: receiptsChanged"
case .update:
return "StoreEvent: update"
case .review:
return "StoreEvent: review"
case .considerReview:
return "StoreEvent: considerReview"
case .cancelReview:
return "StoreEvent: cancelReview"
}
}
}
private class DefaultPaymentQueue: Paying {}
/// StoreFSM is a store for in-app purchases, offering a single non-renewing
/// subscription at three flexible prices. After a successful purchase the store
/// disappears. It returns when the subscription expires or its receipts has
/// been deleted from the `Storing` key-value database.
///
/// The exposed `Shopping` API expects calls from the main queue.
final class StoreFSM: NSObject {
/// The file URL of where to find the product identifiers.
private let url: URL
/// The maximum age of cached products should be kept relatively short, not
/// existing products cannot be sold. However, products don’t change often.
private let ttl: TimeInterval
/// A queue of payment transactions to be processed by the App Store.
private let paymentQueue: Paying
/// The (default) iCloud key-value store object.
private let db: NSUbiquitousKeyValueStore
/// The version of the app.
private let version: BuildVersion
static var unsealedKey = "ink.codes.podest.store.unsealed"
private var unsealedTime: TimeInterval {
db.double(forKey: StoreFSM.unsealedKey)
}
/// Sets unsealed timestamp in `db` and returns existing or new timestamp.
@discardableResult
private static func unseal(
_ db: NSUbiquitousKeyValueStore,
env: BuildVersion.Environment
) -> TimeInterval {
let value = db.double(forKey: StoreFSM.unsealedKey)
guard env != .sandbox, value != 0 else {
os_log("unsealing", log: log)
let ts = Date().timeIntervalSince1970
db.set(ts, forKey: StoreFSM.unsealedKey)
return ts
}
return value
}
private var reviewRequester: ReviewRequester?
/// Creates a new store with minimal dependencies. **Protocol dependencies**
/// for easier testing.
///
/// - Parameters:
/// - url: The file URL of a JSON file containing product identifiers.
/// - ttl: The maximum age, 10 minutes, of cached products in seconds.
/// - paymentQueue: The App Store payment queue.
/// - db: The (default) iCloud key-value store object.
/// - version: The version of this app.
init(
url: URL,
ttl: TimeInterval = 600,
paymentQueue: Paying = DefaultPaymentQueue(),
db: NSUbiquitousKeyValueStore = .default,
version: BuildVersion = BuildVersion()
) {
self.url = url
self.ttl = ttl
self.paymentQueue = paymentQueue
self.db = db
self.version = version
self.state = .initialized
let t = StoreFSM.unseal(db, env: version.env)
self.reviewRequester = ReviewRequester(
version: version, unsealedTime: t, log: log)
}
/// A date formatting block.
public var formatDate: ((Date) -> String)?
/// Flag for asserts, `true` if we are observing the payment queue.
private var isObserving: Bool {
return didChangeExternallyObserver != nil
}
/// The currently available products.
private (set) var products: [SKProduct]?
weak var delegate: StoreDelegate?
weak var subscriberDelegate: StoreAccessDelegate?
// MARK: Reachability
private func isReachable() -> Bool {
return subscriberDelegate?.reach() ?? false
}
// MARK: Products and Identifiers
/// Returns the first product matching `identifier`.
private func product(matching identifier: ProductIdentifier) -> SKProduct? {
return products?.first { $0.productIdentifier == identifier }
}
/// The current products request.
var request: SKProductsRequest?
private var _productIdentifiers: Set<String>?
/// Product identifiers of, locally known, available products. If necessary,
/// loaded from a configuration file.
private var productIdentifiers: Set<String> {
if let pids = _productIdentifiers {
return pids
}
dispatchPrecondition(condition: .notOnQueue(.main))
do {
os_log("loading product identifiers", log: log, type: .debug)
let json = try Data(contentsOf: url)
let localProducts = try JSONDecoder().decode(
[LocalProduct].self, from: json
)
_productIdentifiers = Set(localProducts.map { $0.productIdentifier })
os_log("product identifiers: %@", log: log, type: .debug,
_productIdentifiers!)
return _productIdentifiers!
} catch {
os_log("no product identifiers", log: log, type: .error)
return []
}
}
private func fetchProducts() {
os_log("fetching products: %@", log: log, type: .debug, self.productIdentifiers)
request?.cancel()
let req = SKProductsRequest(productIdentifiers: self.productIdentifiers)
req.delegate = self
req.start()
request = req
}
private func updateProducts() -> StoreState {
guard isReachable() else {
delegateQueue.async {
self.delegate?.store(self, offers: [], error: .offline)
}
if case .subscribed = validateReceipts() {
return .offline(true)
} else {
return .offline(validateTrial())
}
}
fetchProducts()
return .fetchingProducts
}
// MARK: Saving and Loading Receipts
/// Returns different key for store and sandbox `environment`.
private static func receiptsKey(suiting environment: BuildVersion.Environment) -> String {
return environment == .sandbox ? "receiptsSandbox" : "receipts"
}
public func removeReceipts(forcing: Bool = false) -> Bool {
switch (version.env, forcing) {
case (.sandbox, _), (.store, true), (.simulator, _):
os_log("removing receipts", log: log)
db.removeObject(forKey: StoreFSM.receiptsKey(suiting: version.env))
StoreFSM.unseal(db, env: version.env)
return true
case (.store, _):
os_log("not removing production receipts without force", log: log)
return false
}
}
private func loadReceipts() -> [PodestReceipt] {
dispatchPrecondition(condition: .notOnQueue(.main))
let r = StoreFSM.receiptsKey(suiting: version.env)
os_log("loading receipts: %@", log: log, type: .debug, r)
guard let json = db.data(forKey: r) else {
os_log("no receipts: creating container: %@", log: log, type: .debug, r)
return []
}
do {
return try JSONDecoder().decode([PodestReceipt].self, from: json)
} catch {
precondition(removeReceipts(forcing: true))
return []
}
}
private func updateSettings(status: String, expiration: Date) {
let date = formatDate?(expiration) ?? expiration.description
os_log("updating settings: ( %@, %@ )", log: log, type: .debug, status, date)
UserDefaults.standard.set(status, forKey: UserDefaults.statusKey)
UserDefaults.standard.set(date, forKey: UserDefaults.expirationKey)
}
static func makeExpiration(date: Date, period: Period) -> Date {
return Date(timeIntervalSince1970: date.timeIntervalSince1970 + period.rawValue)
}
private func saveReceipt(_ receipt: PodestReceipt) {
os_log("saving receipt: %@", log: log, type: .debug,
String(describing: receipt))
let acc = loadReceipts() + [receipt]
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(acc)
let r = StoreFSM.receiptsKey(suiting: version.env)
db.set(data, forKey: r)
if let (status, expiration) = StoreFSM.makeSettingsInfo(receipts: acc) {
updateSettings(status: status, expiration: expiration)
}
let str = String(data: data, encoding: .utf8)!
os_log("saved: ( %@, %@ )", log: log, type: .debug, r, str)
}
/// Enumerates time periods in seconds.
enum Period: TimeInterval {
typealias RawValue = TimeInterval
case subscription = 3.154e7
case trial = 2.419e6
case always = 0
/// Returns `true` if `date` exceeds this period into the future.
func isExpired(date: Date) -> Bool {
return date.timeIntervalSinceNow <= -rawValue
}
}
/// Returns the product identifier of the first valid subscription found in
/// `receipts` or `nil` if a matching product identifier could not be found
/// or, respectively, all matching transactions are older than one year, the
/// duration of our subscriptions.
static func validProductIdentifier(
_ receipts: [PodestReceipt],
matching productIdentifiers: Set<ProductIdentifier>
) -> ProductIdentifier? {
for r in receipts {
let id = r.productIdentifier
guard productIdentifiers.contains(id),
!Period.subscription.isExpired(date: r.transactionDate) else {
continue
}
return id
}
return nil
}
private func validateTrial(updatingSettings: Bool = false) -> Bool {
os_log("validating trial", log: log, type: .debug)
let ts = unsealedTime
if updatingSettings {
let unsealed = Date(timeIntervalSince1970: ts)
let expiration = StoreFSM.makeExpiration(date: unsealed, period: Period.trial)
updateSettings(status: "Free Trial", expiration: expiration)
}
return !Period.trial.isExpired(date: Date(timeIntervalSince1970: ts))
}
/// Returns a tuple for updating Settings.app with subscription status name
/// and expiration date of the latest receipt in `receipts` or `nil` if
/// `receipts` is empty.
static func makeSettingsInfo(receipts: [PodestReceipt]) -> (String, Date)? {
let sorted = receipts.sorted { $0.transactionDate < $1.transactionDate }
guard let receipt = sorted.first else {
return nil
}
let id = receipt.productIdentifier
let status = (id.split(separator: ".").last ?? "unknown").capitalized
let expiration = StoreFSM.makeExpiration(
date: receipt.transactionDate,
period: .subscription
)
return (status, expiration)
}
private func validateReceipts() -> StoreState {
let receipts = loadReceipts()
os_log("validating receipts: %@", log: log, type: .debug,
String(describing: receipts))
guard let id = StoreFSM.validProductIdentifier(
receipts, matching: productIdentifiers) else {
return .interested(validateTrial(updatingSettings: true))
}
if let (status, expiration) = StoreFSM.makeSettingsInfo(receipts: receipts) {
updateSettings(status: status, expiration: expiration)
}
return .subscribed(id)
}
// MARK: Handling Events and Managing State
/// An internal serial queue for synchronized access.
private let sQueue = DispatchQueue(
label: "ink.codes.podest.StoreFSM",
target: .global(qos: .userInitiated)
)
private (set) var state: StoreState {
didSet {
os_log("new state: %{public}@, old state: %{public}@",
log: log, type: .debug,
state.description, oldValue.description
)
}
}
// Calling the delegate on a distinct system queue for keeping things
// serially in order.
private var delegateQueue = DispatchQueue.global(qos: .userInitiated)
/// Is `true` for interested users with the intention of hiding the store for customers.
private var isAccessible: Bool = false {
didSet {
guard isAccessible != oldValue else {
return
}
delegateQueue.async {
self.subscriberDelegate?.store(self, isAccessible: self.isAccessible)
}
}
}
/// Updates `isAccessible` matching `state`.
private func updateIsAccessible(matching state: StoreState) -> StoreState {
switch state {
case .subscribed:
isAccessible = false
case .interested:
isAccessible = true
default:
break
}
return state
}
private func addPayment(matching productIdentifier: ProductIdentifier) -> StoreState {
guard let p = product(matching: productIdentifier) else {
delegateQueue.async {
self.delegate?.store(self, error: .invalidProduct(productIdentifier))
}
return state
}
let payment = SKPayment(product: p)
paymentQueue.add(payment)
return .purchasing(productIdentifier, state)
}
private var didChangeExternallyObserver: NSObjectProtocol?
/// Begin observing kv-store for receipt and account changes. In both cases
/// firing a `.receiptsChanged` event.
private func observeUbiquitousKeyValueStore() {
precondition(didChangeExternallyObserver == nil)
let r = StoreFSM.receiptsKey(suiting: version.env)
didChangeExternallyObserver = NotificationCenter.default.addObserver(
forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: db,
queue: .main
) { notification in
guard let info = notification.userInfo,
let reason = info[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int else {
return
}
switch reason {
case NSUbiquitousKeyValueStoreAccountChange:
os_log("push received: account change", log: log, type: .info)
DispatchQueue.global(qos: .utility).async {
self.event(.receiptsChanged)
}
case NSUbiquitousKeyValueStoreInitialSyncChange,
NSUbiquitousKeyValueStoreServerChange:
guard
let keys = info[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String],
keys.contains(r) else {
break
}
os_log("push received: initial sync | server change",
log: log, type: .info)
DispatchQueue.global(qos: .utility).async {
self.event(.receiptsChanged)
}
case NSUbiquitousKeyValueStoreQuotaViolationChange:
os_log("push received: quota violation", log: log)
default:
break
}
}
}
private func stopObservingUbiquitousKeyValueStore() {
guard let observer = didChangeExternallyObserver else {
return
}
NotificationCenter.default.removeObserver(observer)
didChangeExternallyObserver = nil
}
private func addObservers() -> StoreState {
precondition(!isObserving)
paymentQueue.add(self)
observeUbiquitousKeyValueStore()
return updateProducts()
}
private func removeObservers() -> StoreState {
precondition(isObserving)
paymentQueue.remove(self)
stopObservingUbiquitousKeyValueStore()
return .initialized
}
private func receiveProducts(_ products: [SKProduct], error: ShoppingError?) -> StoreState {
self.products = products
delegateQueue.async {
self.delegate?.store(self, offers: products, error: error)
}
return updateIsAccessible(matching: validateReceipts())
}
/// Returns the next state after an `error`, overriding `nextState` in some
/// cases.
///
/// Designated to **never** prompt subscribers about their expired free trial.
/// OK, there’s still the rare case, where users subscribed on another device
/// and are launching the app on an offline unsynchronized device. Thoughts?
private func updatedState(
after error: ShoppingError,
next nextState: StoreState
) -> StoreState {
let er: ShoppingError = isReachable() ? error : .offline
delegateQueue.async {
self.delegate?.store(self, error: er)
}
if case .offline = er {
if case .subscribed = validateReceipts() {
return .offline(true)
} else {
return .offline(validateTrial())
}
}
return nextState
}
/// Returns the new store state after processing `event` relatively to the
/// current state. `interested` and `subscribed` are the two main antagonistic
/// states this finite state machine can be in. Its other states are
/// transitional.
///
/// This strict FSM **traps** on unexpected events. All switch statements must
/// be **exhaustive**.
///
/// - Parameter event: The event to handle.
///
/// - Returns: The state resulting from the event.
private func updatedState(after event: StoreEvent) -> StoreState {
dispatchPrecondition(condition: .onQueue(sQueue))
switch state {
// MARK: initialized
case .initialized:
switch event {
case .resume:
return addObservers()
case .pause,
.considerReview,
.review:
return state
case .cancelReview(let resetting):
reviewRequester?.cancelReview(resetting: resetting)
return state
case .failed,
.online,
.pay,
.productsReceived,
.purchased,
.purchasing,
.receiptsChanged,
.update:
fatalError("unhandled event")
}
// MARK: fetchingProducts
case .fetchingProducts:
switch event {
case .productsReceived(let products, let error):
return receiveProducts(products, error: error)
case .receiptsChanged, .update, .online:
return state
case .failed(let error):
return updatedState(after: error, next: .interested(validateTrial()))
case .resume, .considerReview, .review:
return state
case .cancelReview(let resetting):
reviewRequester?.cancelReview(resetting: resetting)
return state
case .pause:
return removeObservers()
case .pay, .purchased, .purchasing:
fatalError("unhandled event")
}
// MARK: offline
case .offline:
switch event {
case .online, .receiptsChanged, .update:
return updateProducts()
case .pause:
return removeObservers()
case .considerReview, .review:
return state
case .cancelReview(let resetting):
reviewRequester?.cancelReview(resetting: resetting)
return state
case .resume, .failed, .pay, .productsReceived, .purchased, .purchasing:
fatalError("unhandled event")
}
// MARK: interested
case .interested:
switch event {
case .receiptsChanged:
return updateIsAccessible(matching: validateReceipts())
case .purchased(let pid):
delegateQueue.async {
self.delegate?.store(self, purchased: pid)
}
return updateIsAccessible(matching: validateReceipts())
case .purchasing(let pid):
delegateQueue.async {
self.delegate?.store(self, purchasing: pid)
}
return .purchasing(pid, state)
case .failed(let error):
return updatedState(after: error, next: state)
case .pay(let pid):
delegateQueue.async {
self.delegate?.store(self, purchasing: pid)
}
return addPayment(matching: pid)
case .update:
return updateProducts()
case .productsReceived(let products, let error):
return receiveProducts(products, error: error)
case .resume:
return state
case .pause:
return removeObservers()
case .online:
fatalError("unhandled event")
case .considerReview:
reviewRequester?.setReviewTimeout { [weak self] in
self?.event(.review)
}
return state
case .review:
reviewRequester?.requestReview()
return state
case .cancelReview(let resetting):
reviewRequester?.cancelReview(resetting: resetting)
return state
}
// MARK: subscribed
case .subscribed:
return state
// MARK: purchasing
case .purchasing(let current, let nextState):
switch event {
case .purchased(let pid):
if current != pid {
os_log("mismatching products: ( %@, %@ )",
log: log, current, pid)
}
delegateQueue.async {
self.delegate?.store(self, purchased: pid)
}
return updateIsAccessible(matching: validateReceipts())
case .failed(let error):
return updatedState(after: error, next: nextState)
case .purchasing(let pid), .pay(let pid):
if current != pid {
os_log("parallel purchasing: ( %@, %@ )", log: log, current, pid)
}
return state
case .receiptsChanged:
return updateIsAccessible(matching: validateReceipts())
case .update:
return updateProducts()
case .pause:
return removeObservers()
case .productsReceived(let products, let error):
return receiveProducts(products, error: error)
case .considerReview, .review:
return state
case .cancelReview(let resetting):
reviewRequester?.cancelReview(resetting: resetting)
return state
case .resume, .online:
fatalError("unhandled event")
}
}
}
/// Synchronously handles event using `sQueue`, our event queue. Obviously,
/// a store with one cashier works sequentially.
private func event(_ e: StoreEvent) {
sQueue.sync {
os_log("handling event: %{public}@", log: log, type: .debug, e.description)
state = updatedState(after: e)
}
}
}
// MARK: - SKProductsRequestDelegate
extension StoreFSM: SKProductsRequestDelegate {
func productsRequest(
_ request: SKProductsRequest,
didReceive response: SKProductsResponse
) {
os_log("response received: %@", log: log, type: .debug, response)
DispatchQueue.main.async {
self.request = nil
}
DispatchQueue.global(qos: .utility).async {
let error: ShoppingError? = {
let invalidIDs = response.invalidProductIdentifiers
guard invalidIDs.isEmpty else {
os_log("invalid product identifiers: %@",
log: log, type: .error, invalidIDs)
return .invalidProduct(invalidIDs.first!)
}
return nil
}()
let products = response.products
self.event(.productsReceived(products, error))
}
}
}
// MARK: - SKPaymentTransactionObserver
extension StoreFSM: SKPaymentTransactionObserver {
private func finish(transaction t: SKPaymentTransaction) {
os_log("finishing: %@", log: log, type: .debug, t)
paymentQueue.finishTransaction(t)
}
private func process(transaction t: SKPaymentTransaction) {
os_log("processing: %@", log: log, type: .debug, t)
let pid = t.payment.productIdentifier
guard t.error == nil else {
let er = t.error!
os_log("handling transaction error: %@",
log: log, type: .error, er as CVarArg)
event(.failed(ShoppingError(underlyingError: er)))
return finish(transaction: t)
}
switch t.transactionState {
case .failed:
os_log("transactionState: failed", log: log, type: .debug)
event(.failed(.failed))
finish(transaction: t)
case .purchased:
os_log("transactionState: purchased", log: log, type: .debug)
guard let receipt = PodestReceipt(transaction: t) else {
fatalError("receipt missing")
}
saveReceipt(receipt)
event(.purchased(pid))
finish(transaction: t)
case .purchasing, .deferred:
os_log("transactionState: purchasing | deferred", log: log, type: .debug)
event(.purchasing(pid))
case .restored:
fatalError("unexpected transaction state")
@unknown default:
fatalError("unknown case in switch: \(t.transactionState)")
}
}
func paymentQueue(
_ queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction]
) {
os_log("payment queue has updated transactions", log: log, type: .debug)
DispatchQueue.global(qos: .utility).async {
for t in transactions {
self.process(transaction: t)
}
}
}
}
// MARK: - Shopping
extension StoreFSM: Shopping {
func online() {
DispatchQueue.global(qos: .utility).async {
self.event(.online)
}
}
func update() {
DispatchQueue.global(qos: .utility).async {
self.event(.update)
}
}
func resume() {
os_log("resuming: %@", log: log, type: .debug, String(describing: version))
DispatchQueue.global(qos: .utility).async {
self.event(.resume)
}
}
func pause() {
DispatchQueue.global(qos: .utility).async {
self.event(.pause)
}
}
func payProduct(matching productIdentifier: String) {
DispatchQueue.global(qos: .userInitiated).async {
self.event(.pay(productIdentifier))
}
}
var canMakePayments: Bool {
return SKPaymentQueue.canMakePayments()
}
}
// MARK: - Rating
extension StoreFSM: Rating {
func considerReview() {
DispatchQueue.global().async {
self.event(.considerReview)
}
}
func cancelReview(resetting: Bool) {
DispatchQueue.global().async {
self.event(.cancelReview(resetting))
}
}
func cancelReview() {
DispatchQueue.global().async {
self.event(.cancelReview(false))
}
}
}
// MARK: - Expiring
extension StoreFSM: Expiring {
func isExpired() -> Bool {
return sQueue.sync {
switch state {
case .offline(let free), .interested(let free):
let expired = !free
if expired {
// Preventing overlapping alerts.
reviewRequester?.invalidate()
reviewRequester = nil
}
delegateQueue.async {
self.subscriberDelegate?.store(self, isExpired: expired)
}
return expired
case .fetchingProducts, .initialized, .purchasing, .subscribed:
return false
}
}
}
}
|
//
// CoreDataManager.swift
// CoreData-Lab
//
// Created by Juan Ceballos on 4/25/20.
// Copyright © 2020 Juan Ceballos. All rights reserved.
//
import UIKit
import CoreData
class CoreDataManager {
static let shared = CoreDataManager()
private init() {}
private var favorites = [Favorite]()
private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
public func createFavorite(id: String, tags: String, previewURL: String, webformatURL: String, photoURL: String, date: Date, likes: String) -> Favorite {
let favorite = Favorite(entity: Favorite.entity(), insertInto: context)
favorite.favoritedDate = date
favorite.id = id
favorite.photoURL = photoURL
favorite.likes = likes
favorite.tags = tags
favorite.previewURL = previewURL
favorite.webformatURL = webformatURL
do {
try context.save()
} catch {
print("\(error)")
}
return favorite
}
public func fetchFavorites() -> [Favorite] {
do {
favorites = try context.fetch(Favorite.fetchRequest())
} catch {
print("\(error)")
}
return favorites
}
}
|
//
// RecordViewController.swift
// RWExample
//
// Created by Joe Zobkiw on 12/26/17.
// Copyright © 2017 Roundware. All rights reserved.
//
import UIKit
import Foundation
import RWFramework
class RecordViewController: UIViewController, RWFrameworkProtocol {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var recordStopPlayButton: UIButton!
@IBOutlet weak var uploadButton: UIButton!
@IBOutlet weak var rerecordButton: UIButton!
@IBOutlet weak var addImageButton: UIButton!
@IBOutlet weak var addTextButton: UIButton!
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
RWFramework.sharedInstance.addDelegate(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
RWFramework.sharedInstance.removeDelegate(self)
}
// MARK: -
func updateUI() {
let rwf = RWFramework.sharedInstance
if rwf.hasRecording() && !rwf.isRecording() { // playback
recordStopPlayButton.setTitle(rwf.isPlayingBack() ? "Stop" : "Play", for: .normal)
recordStopPlayButton.isEnabled = true
uploadButton.isEnabled = !rwf.isPlayingBack()
rerecordButton.isEnabled = !rwf.isPlayingBack()
addImageButton.isEnabled = !rwf.isPlayingBack()
addTextButton.isEnabled = !rwf.isPlayingBack()
} else { // record
recordStopPlayButton.setTitle(rwf.isRecording() ? "Stop" : "Record", for: .normal)
recordStopPlayButton.isEnabled = true
uploadButton.isEnabled = false
rerecordButton.isEnabled = false
addImageButton.isEnabled = false
addTextButton.isEnabled = false
}
}
@IBAction func recordStopPlay(_ sender: UIButton) {
let rwf = RWFramework.sharedInstance
if rwf.hasRecording() && !rwf.isRecording() { // playback
if rwf.isPlayingBack() {
rwf.stopPlayback()
} else {
rwf.startPlayback()
}
} else { // record
if rwf.isRecording() {
rwf.stopRecording()
} else {
rwf.startRecording()
}
}
updateUI()
}
@IBAction func upload(_ sender: UIButton) {
let rwf = RWFramework.sharedInstance
_ = rwf.addRecording()
rwf.uploadAllMedia()
performSegue(withIdentifier: "ThankYouViewController", sender: self)
}
@IBAction func rerecord(_ sender: UIButton) {
let rwf = RWFramework.sharedInstance
rwf.deleteRecording()
updateUI()
}
@IBAction func addImage(_ sender: UIButton) {
let rwf = RWFramework.sharedInstance
#if (arch(i386) || arch(x86_64)) && os(iOS)
rwf.doPhotoLibrary()
#else
rwf.doImage()
#endif
}
@IBAction func addText(_ sender: UIButton) {
let rwf = RWFramework.sharedInstance
if let key = rwf.addText("Hello String", description: "Hello Description") {
print("addText succeeded to path \(key)")
} else {
print("addText failed")
}
}
// MARK: -
func rwRecordingProgress(_ percentage: Double, maxDuration: TimeInterval, peakPower: Float, averagePower: Float) {
var timeLeft = maxDuration - (maxDuration * percentage)
timeLeft = timeLeft >= 0 ? timeLeft : 0
timerLabel.text = String(format: "%.0f", timeLeft.rounded(.up))
}
func rwPlayingBackProgress(_ percentage: Double, duration: TimeInterval, peakPower: Float, averagePower: Float) {
timerLabel.text = "..."
}
func rwAudioRecorderDidFinishRecording() {
print("rwAudioRecorderDidFinishRecording")
updateUI()
}
func rwAudioPlayerDidFinishPlaying() {
print("rwAudioPlayerDidFinishPlaying")
updateUI()
}
// MARK: -
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
override func canPerformUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> Bool {
return true
}
@IBAction func unwindToRecordViewController(sender: UIStoryboardSegue) {
// let sourceViewController = sender.source
// Pull any data from the view controller which initiated the unwind segue.
}
}
|
import Foundation
public func solution(_ S : inout String, _ P : inout [Int], _ Q : inout [Int]) -> [Int] {
// write your code in Swift 4.2.1 (Linux)
var A = [Int]()
var C = [Int]()
var G = [Int]()
var T = [Int]()
A.append(0)
C.append(0)
G.append(0)
T.append(0)
let byteString: [UInt8] = Array(S.utf8)
let byteA: UInt8 = Array("A".utf8)[0]
let byteC: UInt8 = Array("C".utf8)[0]
let byteG: UInt8 = Array("G".utf8)[0]
let byteT: UInt8 = Array("T".utf8)[0]
for i in 0..<S.count {
if byteString[i] == byteA {
A.append(A[i] + 1)
C.append(C[i])
G.append(G[i])
T.append(T[i])
} else if byteString[i] == byteC {
A.append(A[i])
C.append(C[i] + 1)
G.append(G[i])
T.append(T[i])
} else if byteString[i] == byteG {
A.append(A[i])
C.append(C[i])
G.append(G[i] + 1)
T.append(T[i])
} else if byteString[i] == byteT {
A.append(A[i])
C.append(C[i])
G.append(G[i])
T.append(T[i] + 1)
}
}
let numQueries = P.count
var queryResults = [Int]()
for j in 0..<numQueries {
if A[Q[j] + 1] > A[P[j]] {
queryResults.append(1)
} else if C[Q[j] + 1] > C[P[j]] {
queryResults.append(2)
} else if G[Q[j] + 1] > G[P[j]] {
queryResults.append(3)
} else if T[Q[j] + 1] > T[P[j]] {
queryResults.append(4)
}
}
return queryResults
}
var S = "CAGCCTA"
var P = [2,5,0]
var Q = [4,5,6]
print(solution(&S, &P, &Q)) // -> [2, 4, 1]
// MARK: - Prompt
/*
A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?
The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).
For example, consider string S = CAGCCTA and arrays P, Q such that:
P[0] = 2 Q[0] = 4
P[1] = 5 Q[1] = 5
P[2] = 0 Q[2] = 6
The answers to these M = 3 queries are as follows:
The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2.
The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.
The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.
Write a function:
public func solution(_ S : inout String, _ P : inout [Int], _ Q : inout [Int]) -> [Int]
that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.
Result array should be returned as an array of integers.
For example, given the string S = CAGCCTA and arrays P, Q such that:
P[0] = 2 Q[0] = 4
P[1] = 5 Q[1] = 5
P[2] = 0 Q[2] = 6
the function should return the values [2, 4, 1], as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
M is an integer within the range [1..50,000];
each element of arrays P, Q is an integer within the range [0..N − 1];
P[K] ≤ Q[K], where 0 ≤ K < M;
string S consists only of upper-case English letters A, C, G, T.
*/
|
//
// animals.swift
// Zoo
//
// Created by Caden Cheek on 10/14/16.
// Copyright © 2016 Interapt. All rights reserved.
//
import Foundation
//class to track overall condition of all animals in the park
class Animal {
// tracking animal health, age and statistics such as weight,height vet records
var listAnimals = [String]()
var generalFeeding = [String]()
init() {
self.generalFeeding.append("TIME")
}
//func feedingSchedule(schedule: String) -> [String] {
// if schedule == "Yes" {
// return generalFeeding
//} else {
// return ["Ah, I will still show you. \(generalFeeding)"]
//}
//}
}
class Mammal:Animal{
//this will detail the species and discription of all animals of the mammal family
// would need a function to track last feeding and next feeding
}
class Reptile:Animal{
//this would detail the species and discription of all reptiles in the park
//need func to track feeding schdule and hibernation schdule
override init(){
super.init()
generalFeeding = ["7:00am", "11:00am", "3:00pm", "7:00pm"]
}
}
class Bird:Animal{
//would detail the species and discription of all birds in the park
//need func to track feeding schdule and breeding schdule
override init(){
super.init()
generalFeeding = ["9:00am", "1:00pm", "5:00pm", "8:00pm", "10:00pm"]
}
}
|
//
// UserListRepository.swift
// UsersApp-SwiftUI
//
// Created by Jorge Luis Rivera Ladino on 4/09/21.
//
import Combine
protocol UserListRepositoryProtocol {
func getUsers() -> AnyPublisher<[UserList.User.Domain]?, Error>?
func getPost(request: PostList.Post.Request) -> AnyPublisher<[PostList.Post.Domain]?, Error>?
func saveUsers(_ users: [UserList.User.Domain])
}
class UserListRepository: UserListRepositoryProtocol, ObservableObject {
private var dataSource: RemoteUserListDataSource
private var localDataSource: LocalUserListDataSource
init(dataSource: RemoteUserListDataSource,
localDataSource: LocalUserListDataSource
) {
self.dataSource = dataSource
self.localDataSource = localDataSource
}
func getUsers() -> AnyPublisher<[UserList.User.Domain]?, Error>? {
guard ApiTool.isConnected else {
return localDataSource.getUsers()
}
return dataSource.getUsers()
.eraseToAnyPublisher()
}
func getPost(request: PostList.Post.Request) -> AnyPublisher<[PostList.Post.Domain]?, Error>? {
dataSource.getPost(request: request)
.eraseToAnyPublisher()
}
func saveUsers(_ users: [UserList.User.Domain]) {
localDataSource.saveUsers(users)
}
}
|
//
// GugudanViewController.swift
// JWSRxSwiftBeginningSample
//
// Created by Clint on 16/11/2018.
// Copyright © 2018 clintjang. All rights reserved.
//
import UIKit
final class GugudanViewController: BaseViewController {
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var runButton: UIButton!
@IBOutlet weak var resultTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let inputValueValid = inputTextField.rx.text.orEmpty
.map { $0.count < 1 }
.share(replay: 1)
inputValueValid
.bind(to: runButton.rx.isHidden)
.disposed(by: disposeBag)
runButton.rx.tap
.bind(onNext:calculateGugudan)
.disposed(by: disposeBag)
// 앱 시작시 콘솔 구구단 전부 찍기, 케이스 1
consoleFrom1To9DanCase1()
// 앱 시작시 콘솔 구구단 전부 찍기, 케이스 2
// consoleFrom1To9DanCase2()
}
func calculateGugudan() {
if let danString = inputTextField.text, let danValue = Int(danString) {
Observable.just(danValue)
.flatMap { dan in
Observable.range(start: 1, count: 9).map({ row in
return "\(dan) * \(row) = \(dan * row)\n"
}).reduce("\(dan)단 출력\n", accumulator: { "\($0)\($1)" })
}
.debug() // 콜솔 결과 보기
.bind(to: resultTextView.rx.text)
.disposed(by: disposeBag)
}
}
}
extension GugudanViewController {
func consoleFrom1To9DanCase1() {
print("===============================")
print("== 콘솔 로그용")
print("\n\n")
// 1단
// Observable.just(1)
// .flatMap { dan in
// Observable.range(start: 1, count: 9).map({ row in
// return "\(dan) * \(row) = \(dan * row)"
// }) }
// .subscribe(onNext:{ print($0)},
// onError:{ print($0) },
// onCompleted:{ print("onCompleted")}
// )
// .disposed(by: disposeBag)
// 1부터 9단 찍기, flatMap 활용
Observable.range(start: 1, count: 9)
.flatMap { dan in
Observable.range(start: 1, count: 9).map({ row in
return "\(dan) * \(row) = \(dan * row)\n"
}).reduce("\(dan)단 출력\n", accumulator: { "\($0)\($1)" })
}
.subscribe(onNext:{ print($0)},
onError:{ print($0) },
onCompleted:{ print("onCompleted")}
)
.disposed(by: disposeBag)
}
func consoleFrom1To9DanCase2() {
print("===============================")
print("== 콘솔 로그용")
print("\n\n")
// 1부터 9단 찍기, concatMap 활용
Observable.range(start: 1, count: 9)
.concatMap { dan in
Observable.range(start: 1, count: 9).map({ row in
return "\(dan) * \(row) = \(dan * row)\n"
})
}
.subscribe(onNext:{ print($0)},
onError:{ print($0) },
onCompleted:{ print("onCompleted")}
)
.disposed(by: disposeBag)
}
}
|
//
// DetalleViewController.swift
// vista jerarquicas
//
// Created by Wilmer Mendoza on 19/11/16.
// Copyright © 2016 Wilmer Mendoza. All rights reserved.
//
import UIKit
class DetalleViewController: UIViewController {
var titulo = String()
var autor = [String]()
var portada = UIImage()
@IBOutlet weak var autorLabel: UILabel!
@IBOutlet weak var tituloLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tituloLabel.text = titulo
for nombre in autor{
autorLabel.text = "\(nombre) "
}
imageView.image = portada
}
}
|
import UIKit
for num in 1...100 {
if ((num % 3 == 0) && (num % 5 == 0)) {
print("FizzBuzz")
} else if (num % 3 == 0){
print("Fizz")
} else if num % 5 == 0{
print("Buzz")
} else {
print(num)
}
}
|
//
// Extensions.swift
// App Store
//
// Created by Chidi Emeh on 1/12/18.
// Copyright © 2018 Chidi Emeh. All rights reserved.
//
import UIKit
import Foundation
//Adds cornerRadius to two edges
extension UIVisualEffectView {
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.contentView.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
//Adds cornerRadius to two edges
extension UIView {
func roundBottomCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
extension UIImageView {
func downloadImage(string : String){
//Image Settings
self.layer.cornerRadius = 15
self.layer.borderWidth = 0.5
self.layer.borderColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 0.5).cgColor
let imageCache = NSCache<AnyObject, AnyObject>()
guard let url = URL(string: string) else {return}
if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {
self.image = imageFromCache
return
}else {
let imageDownloader = NetworkProcessor(url: url )
imageDownloader.downloadImageDataFromURL { (data, response, error) in
if error == nil {
guard let image = UIImage(data: data!) else { return }
imageCache.setObject(image, forKey: url as AnyObject)
DispatchQueue.main.async {
self.clipsToBounds = true
self.image = image
}
}else {
print("Error Downloading image: \(error! as NSError)")
}
}
}
}
}
|
//
// CoursesTableViewController.swift
// watchout
//
// Created by Rafael Fernandes de Oliveira Carvalho on 6/20/15.
// Copyright (c) 2015 Rafael Fernandes de Oliveira Carvalho. All rights reserved.
//
import UIKit
import CoreData
class CoursesTableViewController: UITableViewController {
var courses = [Course]()
var lecture: Lecture?
var selectedCourse: Course? {
didSet {
if selectedCourse != nil {
lecture?.course = selectedCourse!
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Course")
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]
if let results = fetchedResults as? [Course] {
courses = results
}
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courses.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("courseCell", forIndexPath: indexPath) as! UITableViewCell
let course = courses[indexPath.row]
cell.textLabel?.text = course.name
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedCourse = courses[indexPath.row]
}
// MARK: - Navigation
@IBAction func presentNewCourse(sender: AnyObject) {
performSegueWithIdentifier("presentNewCourse", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "presentNewCourse" {
if let nav = segue.destinationViewController as? UINavigationController {
if let vc = nav.visibleViewController as? NewCourseTableViewController {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
if let entity = NSEntityDescription.entityForName("Course", inManagedObjectContext: managedContext) {
let course = Course(entity: entity, insertIntoManagedObjectContext: managedContext)
vc.course = course
}
}
}
}
}
}
|
//
// Manager.swift
// Simulation
//
// Created by 郝赟 on 15/9/10.
// Copyright (c) 2015年 郝赟. All rights reserved.
//
import UIKit
class Manager: cloudletDelegate,ApDelegate{
var allUsers: [MUser] //系统中所有用户
var allAPs: [AP] //系统中所有接入点
var apGraph: MGraph //系统中所有接入点的拓扑图
var randomCloudlets: [Cloudlet] //系统中random算法的所有的Cloudlet
var HAFCloudlets: [Cloudlet] //系统中HAF算法的所有的Cloudlet
var DBCCloudlets: [Cloudlet] //系统中DBC算法的所有的Cloudlet
var GMACloudlets: [Cloudlet] //系统中GMA算法的所有的Cloudlet
var taskId: Int = 0 //发送任务ID开始编号
var switchCount = 0 //用户切换AP次数统计
var newAccPercent: Float = 0.2 //用户最新移动位置的可信百分比
var successTaskNum:Dictionary<String,Int> //系统成功的所有任务
var failTaskNum: Dictionary<String,Int> //系统失败的任务数
var reponseTime: Dictionary<String,Float> //系统平均响应时间
var repeatTimesOfSendTask:Int //发送任务刷新次数
init(){
allUsers = []
allAPs = []
apGraph = MGraph()
randomCloudlets = []
HAFCloudlets = []
DBCCloudlets = []
GMACloudlets = []
successTaskNum = ["Random":0,"HAF":0,"DBC":0,"GMA":0]
failTaskNum = ["Random":0,"HAF":0,"DBC":0,"GMA":0]
reponseTime = ["Random":0.0,"HAF":0.0,"DBC":0.0,"GMA":0.0]
repeatTimesOfSendTask = 0
}
//开始模拟实验
func startSimulation(){
allUsers = generateRandomUser(UserNum)
allAPs = getAPNetwork()
usersAndAPInit()
dispatch_async(dispatch_get_global_queue(0,0), {
while(2>0){
self.userRandomMove()
NSThread.sleepForTimeInterval(2.0)
}
})
dispatch_async(dispatch_get_global_queue(0,0), {
while(2>0){
self.userRandomSendTask()
NSThread.sleepForTimeInterval(Double(RandomSendTaskRefreshTime))
}
})
}
//结束模拟实验
func stopSimulation(){
//printAPData()
printCloudletData()
//printUserData()
printSystemData()
}
//随机产生一定数量的用户
func generateRandomUser(userNumber:Int) ->[MUser]{
let users = NSMutableArray()
print("加入新用户:")
print("用户Id 用户位置")
for (var i = 0 ; i < userNumber; i++) {
let newUser = MUser()
let userX = randomIn(min: 0, max: MaxX)
let userY = randomIn(min: 0, max: MaxY)
newUser.location = CGPoint(x: userX,y: userY)
newUser.userId = i + 1
newUser.moveLever = .Slow
print(" \(newUser.userId) (\(userX),\(userY))")
users.addObject(newUser)
}
return NSArray(array: users) as! [MUser]
}
func getAPNetwork() ->[AP]{
let aps = NSMutableArray()
print("加入新AP:")
print("AP Id AP位置")
//初始化AP网络节点
for (var i = 0 ; i < APNetworkX.count; i++) {
let newAP = AP()
let APX = APNetworkX[i]
let APY = APNetworkY[i]
newAP.location = CGPoint(x: APX,y: APY)
newAP.APId = i + 1
newAP.delegate = self
switch i + 1 {
case 2,3,4,5: newAP.apLever = .Company
case 6,7,9,10,29,36: newAP.apLever = .Cafe
case 12,13,14,16,31,32,33,34: newAP.apLever = .Park
case 1,8,10,17,18,19,20,22,23,25,26,28,30: newAP.apLever = .Street
case 11,15,21,24,27,35: newAP.apLever = .Car
default: newAP.apLever = .Park
}
print(" \(newAP.APId) (\(APX),\(APY))")
aps.addObject(newAP)
}
//添加AP网络拓扑
var apArray = NSArray(array: aps) as! [AP]
for (var j = 0 ; j < apArray.count ; j++){
// var ap = apArray[j]
let neighbour = NSMutableArray()
let switchTimes = NSMutableArray()
for (var k = 0 ;k < APNetWorkConnect[j].count ; k++){
neighbour.addObject(apArray[APNetWorkConnect[j][k] - 1])
switchTimes.addObject(0)
}
apArray[j].neighbour = NSArray(array: neighbour) as! [AP]
apArray[j].switchTimes = NSArray(array: switchTimes) as! [Int]
}
return apArray
//return NSArray(array: aps) as! [AP]
}
//用户和AP初始化,AP网络拓扑生成
func usersAndAPInit(){
//为每个用户设置最近的AP进行连接
for (var i = 0 ; i < allUsers.count ; i++ ) {
let ap = getClosestAP(allUsers[i])
//向该AP加入用户
ap.addUser(allUsers[i])
allUsers[i].currentAP = ap
switch allUsers[i].currentAP.apLever {
case .Company: allUsers[i].moveLever = .Quiet
case .Cafe: allUsers[i].moveLever = .Slow
case .Park: allUsers[i].moveLever = .Middle
case .Street: allUsers[i].moveLever = .Fast
case .Car: allUsers[i].moveLever = .Fastest
default: allUsers[i].moveLever = .Slow
}
let randomX = sqrt(allUsers[i].moveLever.rawValue * allUsers[i].moveLever.rawValue) * Float(randomIn(min: 0, max: 20) - 10) / 10
let randomYAbs = sqrt(allUsers[i].moveLever.rawValue * allUsers[i].moveLever.rawValue - randomX * randomX)
let randomY = inPercentEvent(0.5) ? randomYAbs : (-1.0 * randomYAbs)
allUsers[i].acceleration = CGPoint(x: CGFloat(randomX), y: CGFloat(randomY))
}
//初始化AP网络拓扑
let node = allAPs.count
var edge = 0
var matrix:[[Float]] = [[Float]](count: node, repeatedValue: [Float](count: node, repeatedValue: 0.0))
for ap in allAPs {
for neighbour in ap.neighbour {
let r = ap.APId - 1
let l = neighbour.APId - 1
matrix[r][l] = 1.0
edge += 1
}
}
apGraph = MGraph(m: matrix, node: node, edge: Int(edge/2))
print("\(apGraph.matrix)")
printAPData()
printUserData()
}
func getCloudlets(number:Int){
//对AP按照工作负载的大小从大到小进行重新排序
allAPs.sortInPlace({ $0.workload > $1.workload })
printAPData()
RandomGenerateCloudlet(number)
HAFGenerateCloudlet(number)
DBCGenerateCloudlet(number)
GMAGenerateCloudlet(number)
dispatch_async(dispatch_get_global_queue(0,0), {
while(2>0){
//let currentTime = NSDate()
for randomCloudlet in self.randomCloudlets {
randomCloudlet.getTaskToExcute()
}
for HAFCloudlet in self.HAFCloudlets {
HAFCloudlet.getTaskToExcute()
}
for DBCCloudlet in self.DBCCloudlets {
DBCCloudlet.getTaskToExcute()
}
for GMACloudlet in self.GMACloudlets {
GMACloudlet.getTaskToExcute()
}
//print("该过程花了 \(currentTime.timeIntervalSinceNow * -1.0)")
NSThread.sleepForTimeInterval(Double(refreshTime))
}
})
}
//
func RandomGenerateCloudlet(number:Int){
let cloudletsArray = NSMutableArray()
var range = randomInRange(min: 0, max: allAPs.count - 1, number: number)
for i in 0 ... number - 1 {
let cloudlet = Cloudlet()
cloudlet.cloudletId = i + 1
cloudlet.ap = allAPs[range[i]]
cloudlet.delegate = self
cloudlet.type = "Random"
cloudletsArray.addObject(cloudlet)
}
randomCloudlets = NSArray(array: cloudletsArray) as! [Cloudlet]
}
func HAFGenerateCloudlet(number:Int){
let cloudletsArray = NSMutableArray()
for i in 0 ... number - 1 {
let cloudlet = Cloudlet()
cloudlet.cloudletId = i + 1
cloudlet.ap = allAPs[i]
cloudlet.delegate = self
cloudlet.type = "HAF"
cloudletsArray.addObject(cloudlet)
}
HAFCloudlets = NSArray(array: cloudletsArray) as! [Cloudlet]
}
func DBCGenerateCloudlet(number:Int){
// print("AP Id AP平均负载 AP类型")
// for (var i = 0 ; i < allAPs.count ; i++ ) {
// print(" \(allAPs[i].APId) \(allAPs[i].workload) \(allAPs[i].apLever.toString())")
// }
let hop = 2
var cloudletsSet = Set<AP>()
let workloadArray = NSMutableArray()
var isExit = Set<Int>()
for _ in allAPs {
workloadArray.addObject(0.0)
}
for i in 0 ... number - 1 {
let cloudlet = Cloudlet()
cloudlet.cloudletId = i + 1
for index in 0 ... allAPs.count - 1 {
var isZero = false
for tmp in isExit {
if index == tmp {
workloadArray[index] = 0.0
isZero = true
}
}
if !isZero {
workloadArray[index] = computeWorkLoad(removeApsFromSet(cloudletsSet, fromSet:getNeighbours(allAPs[index], hops: hop)))
}
// print("AP ID:\(allAPs[index].APId) 总负载:\(workloadArray[index])")
}
var candiate = 0
var mostWorkload = workloadArray[0] as! Float
for index in 0 ... allAPs.count - 1 {
if (workloadArray[index] as! Float) > mostWorkload {
mostWorkload = workloadArray[index] as! Float
candiate = index
}
}
isExit.insert(candiate)
workloadArray[candiate] = 0.0
cloudlet.cloudletId = i + 1
cloudlet.ap = allAPs[candiate]
cloudlet.delegate = self
cloudlet.type = "DBC"
//allAPs[candiate].currentCloudlet = cloudlet
cloudletsSet.insert(allAPs[candiate])
DBCCloudlets.append(cloudlet)
}
}
//FIXME:
func GMAGenerateCloudlet(number:Int){
let hop = 2
var workloadArray = Array<Float>()
var cloudletsArray = Array<Cloudlet>()
var apWorkload = Array<Float>()
var isExit = Set<Int>()
//print("GMAWorkload:")
for ap in allAPs {
apWorkload.append(ap.workload)
}
for ap in allAPs {
let workload = getGMAWorkload(ap,hops:hop,workload: apWorkload)
workloadArray.append(workload)
}
for i in 0 ... number - 1 {
for index in 0 ... allAPs.count - 1 {
if isExit.contains(index){
workloadArray[index] = 0.0
}
else{
let workload = getGMAWorkload(allAPs[index],hops:hop,workload: apWorkload)
workloadArray[index] = workload
}
//print("\(workload) ")
}
var candiate = 0
var mostWorkload = workloadArray[0]
for index in 0 ... allAPs.count - 1 {
if (workloadArray[index]) > mostWorkload {
mostWorkload = workloadArray[index]
candiate = index
}
}
apWorkload = updateGMAWorkload(allAPs[candiate], hops: hop, workload: apWorkload)
let cloudlet = Cloudlet()
cloudlet.cloudletId = i + 1
cloudlet.ap = allAPs[candiate]
cloudlet.delegate = self
cloudlet.type = "GMA"
cloudletsArray.append(cloudlet)
isExit.insert(candiate)
}
GMACloudlets = NSArray(array: cloudletsArray) as! [Cloudlet]
}
func updateGMAWorkload(ap:AP,hops:Int,workload:Array<Float>)->Array<Float>{
var newWorkload = workload
var tranferPercent:Float = 1.0
for hop in 0 ... hops {
let aps = getNeighboursInHop(hop, fromAp: ap)
for index in 0 ... allAPs.count - 1 {
if aps.contains(allAPs[index]) {
let lessWorkload = newWorkload[index] - allAPs[index].workload * tranferPercent
newWorkload[index] = (lessWorkload > 0) ? lessWorkload : 0
}
}
tranferPercent *= 0.5
}
return newWorkload
}
//算出GMA算法的AP负载
func getGMAWorkload(ap:AP,hops:Int,workload:Array<Float>)-> Float {
var GMAWorkload:Float = ap.workload
var tranferPercent:Float = 1.0
for hop in 1 ... hops {
tranferPercent *= 0.5
for hopAp in getNeighboursInHop(hop, fromAp: ap){
for index in 0 ... allAPs.count - 1 {
if hopAp.APId == allAPs[index].APId{
GMAWorkload += workload[index] * tranferPercent
}
}
// aps += "\(hopAp.APId)(\(tranferPercent)) "
}
//print("\(aps)")
}
return GMAWorkload
// var apSet = getNeighbours(ap, hops: hops)
//
// print("getGMAWorkload:apID:\(ap.APId) ")
//
// func getWorkload(ap:AP) -> Float{
// var apWorkload:Float = 0.0
// for index in 0 ... allAPs.count - 1 {
// if ap.APId == allAPs[index].APId{
// apWorkload += workload[index]
// }
// }
//
//
// apSet.remove(ap)
// print(" ap:\(ap.APId)")
//
// for fromAp in allAPs {
// if apSet.contains(fromAp){
//
// let switchPercent = switchPercentTo(ap, fromAp: fromAp)
// if switchPercent != 0 {
// let childWorkload = getWorkload(fromAp)
// apWorkload += switchPercent * childWorkload
// //workload += switchPercentTo(ap, fromAp: fromAp) * getGMAWorkload(fromAp, hops: hops)
// //print(" childAP:\(fromAp.APId) switchPercent:\(switchPercent) ")
// }
//
// }
// else{
// apWorkload += 0.0
// }
//
// }
// return apWorkload
//
// }
// return getWorkload(ap)
}
func switchPercentTo(toAp:AP,fromAp:AP)->Float{
var allSwitchTimes = 0
var switchPercent:Float = 0.0
for index in 0 ... fromAp.neighbour.count - 1{
if fromAp.neighbour[index].APId == toAp.APId{
for switchTime in fromAp.switchTimes {
allSwitchTimes += switchTime
}
if allSwitchTimes == 0 {
switchPercent = 1.0 / Float(fromAp.neighbour.count)
}
else{
switchPercent = Float(fromAp.switchTimes[index]) / Float(allSwitchTimes)
}
}
}
return switchPercent
}
//将用户分配给Cloudlet
func assignUsersToCloudlet(){
// assignUsersToHAFCloudlet()
// assignUsersToDBCCloudlet()
// assignUsersToGMACloudlet()
userIsAssignedToCloudlet = true
}
func assignUsersToHAFCloudlet(){
let avgUserNum = Int(ceil(Double(allUsers.count / HAFCloudlets.count) * 0.8))
for cloudletIndex in 0 ... HAFCloudlets.count - 1 {
var userHopArray = Array<Array<Int>>()
let canditeUsers = getCanditeUsersIn(DBCCloudlets[cloudletIndex].ap, hops: 2)
for userIndex in canditeUsers {
if allUsers[userIndex].linkCloudelt[0] == -1 {
let hopsFromUserToCloudlet = getHopNum(HAFCloudlets[cloudletIndex].ap, toAp: allUsers[userIndex].currentAP)
let userAndHop = [userIndex,hopsFromUserToCloudlet]
userHopArray.append(userAndHop)
}
}
userHopArray.sortInPlace({ $0[1] < $1[1]})
let forTimes = userHopArray.count > avgUserNum ? avgUserNum : userHopArray.count
for index in 0 ... forTimes - 1 {
allUsers[userHopArray[index][0]].linkCloudelt[0] = cloudletIndex
}
}
}
func assignUsersToDBCCloudlet(){
let avgUserNum = Int(ceil(Double(allUsers.count / HAFCloudlets.count) * 0.8))
for cloudletIndex in 0 ... DBCCloudlets.count - 1 {
var userHopArray = Array<Array<Float>>()
let canditeUsers = getCanditeUsersIn(DBCCloudlets[cloudletIndex].ap, hops: 2)
for userIndex in canditeUsers {
if allUsers[userIndex].linkCloudelt[1] == -1 {
let hopsFromUserToCloudlet = getHopNum(DBCCloudlets[cloudletIndex].ap, toAp: allUsers[userIndex].currentAP)
let firstCloudletIndex = sortCloudletByDistance(.DBC, fromAp: allUsers[userIndex].currentAP)[0]
let secondCloudletIndex = sortCloudletByDistance(.DBC, fromAp: allUsers[userIndex].currentAP)[1]
let secondCloudletDistance = (DBCCloudlets[cloudletIndex].cloudletId == DBCCloudlets[firstCloudletIndex[0]].cloudletId) ? secondCloudletIndex[1] : firstCloudletIndex[1]
let userAndRelativeDistance = [Float(userIndex),Float(hopsFromUserToCloudlet)/Float(secondCloudletDistance)]
userHopArray.append(userAndRelativeDistance)
}
}
userHopArray.sortInPlace({ $0[1] < $1[1]})
let forTimes = userHopArray.count > avgUserNum ? avgUserNum : userHopArray.count
for index in 0 ... forTimes - 1 {
allUsers[Int(userHopArray[index][0])].linkCloudelt[1] = cloudletIndex
}
}
}
func assignUsersToGMACloudlet(){
let avgUserNum = (allUsers.count % GMACloudlets.count) > 0 ? (allUsers.count / GMACloudlets.count + 1) : (allUsers.count / GMACloudlets.count)
var usersInCloudlet = Array(count: GMACloudlets.count, repeatedValue: 0)
var userHopArray = Array<Array<Float>>()
for userIndex in 0 ... allUsers.count - 1 {
let cloudletAndDistance = sortCloudletByDistance(.GMA, fromAp:allUsers[userIndex].currentAP)
var pui:Float = 0.0
for k in 1 ... Int(ceil(Float(GMACloudlets.count/2))) {
pui += pow(Float(cloudletAndDistance[k - 1][1]), Float(1.0 / Float(k)))
}
userHopArray.append([Float(userIndex),pui])
}
userHopArray.sortInPlace({ $0[1] > $1[1]})
for userAndHop in userHopArray {
let cloudletAndDistance = sortCloudletByDistance(.GMA, fromAp:allUsers[Int(userAndHop[0])].currentAP)
for index in 0 ... cloudletAndDistance.count - 1 {
if usersInCloudlet[cloudletAndDistance[index][0]] < avgUserNum {
allUsers[Int(userAndHop[0])].linkCloudelt[2] = cloudletAndDistance[index][0]
usersInCloudlet[cloudletAndDistance[index][0]] += 1
break
}
}
}
}
//用户随机移动(用移动算法描述)
func userRandomMove() {
//print("用户位置更新: \n 用户Id 用户位置")
for (var i = 0 ; i < allUsers.count ; i++ ) {
//新的移动位置 = 用户原来位置 + 平均加速度 + 噪声误差
var newX: Float
var newY: Float
if inPercentEvent(0.8) {
newX = Float(allUsers[i].location.x) + Float(allUsers[i].acceleration.x) + allUsers[i].moveLever.rawValue * Float(randomIn(min: 0, max: 20) - 10) / 10
newY = Float(allUsers[i].location.y) + Float(allUsers[i].acceleration.y) + allUsers[i].moveLever.rawValue * Float(randomIn(min: 0, max: 20) - 10) / 10
}
else {
newX = Float(allUsers[i].location.x) + allUsers[i].moveLever.rawValue * Float(randomIn(min: 0, max: 20) - 10) / 5
newY = Float(allUsers[i].location.y) + allUsers[i].moveLever.rawValue * Float(randomIn(min: 0, max: 20) - 10) / 5
}
if newX < 0 {
newX = 0
allUsers[i].acceleration.x = allUsers[i].acceleration.x * (-1.0)
}
else if newX > Float(MaxX) {
newX = Float(MaxX)
allUsers[i].acceleration.x = allUsers[i].acceleration.x * (-1.0)
}
if newY < 0 {
newY = 0
allUsers[i].acceleration.y = allUsers[i].acceleration.y * (-1.0)
}
else if newY > Float(MaxY) {
newY = Float(MaxY)
allUsers[i].acceleration.y = allUsers[i].acceleration.y * (-1.0)
}
//计算新的平均加速度 新的平均加速度 = ((移动次数-1)*原加速度 + 最近一次加速度 * 可信百分比)/ 移动次数
// var percentX = 1.0 - abs((newX - Float(allUsers[i].location.x)) / allUsers[i].moveLever.rawValue - 1.0)
// var percentY = 1.0 - abs((newY - Float(allUsers[i].location.y)) / allUsers[i].moveLever.rawValue - 1.0)
let newAccelerationX = (1.0 - newAccPercent) * Float(allUsers[i].acceleration.x) + newAccPercent * (newX - Float(allUsers[i].location.x))
let newAccelerationY = (1.0 - newAccPercent) * Float(allUsers[i].acceleration.y) + newAccPercent * (newY - Float(allUsers[i].location.y))
allUsers[i].acceleration = CGPoint(x: CGFloat(newAccelerationX), y: CGFloat(newAccelerationY))
allUsers[i].location = CGPoint(x: CGFloat(newX), y: CGFloat(newY))
//判断是否应该切换AP
if !getClosestAP(allUsers[i]).isEqual(allUsers[i].currentAP ){
switchCount += 1
allUsers[i].switchAP(allUsers[i].currentAP, toAP: getClosestAP(allUsers[i]))
}
// let printX = String(format: "%.2f", allUsers[i].location.x)
// let printY = String(format: "%.2f", allUsers[i].location.y)
// let aX = String(format: "%.5f", allUsers[i].acceleration.x)
// let aY = String(format: "%.5f", allUsers[i].acceleration.y)
// print(" \(allUsers[i].userId) (\(printX) , \(printY)) (\(aX) , \(aY))")
}
// var printX = String(format: "%.2f", allUsers[10].location.x)
// var printY = String(format: "%.2f", allUsers[10].location.y)
// print(" \(allUsers[10].userId) (\(printX) , \(printY)) (\(allUsers[10].acceleration.x) , \(allUsers[10].acceleration.y))")
//
}
//FIXME:应该向每种算法的cloudlet发送同样的任务 用户发送任务(遵循泊松分布)
func userRandomSendTask(){
for user in allUsers {
if user.taskNum <= 0 {
let taskNum = possionNum(TaskNumOfUnitTime)
if taskNum <= 0 {
user.taskNum = Int(TimeSlot / RandomSendTaskRefreshTime)
user.IntervalTimes = Int(TimeSlot / RandomSendTaskRefreshTime)
}
else {
user.taskNum = taskNum > 2 * Int(TaskNumOfUnitTime) ? 2 * Int(TaskNumOfUnitTime) : taskNum
user.IntervalTimes = Int(TimeSlot / RandomSendTaskRefreshTime / Float(user.taskNum))
for _ in 1 ... user.taskNum {
randomGenerateTaskToUser(user)
}
}
}
else{
if repeatTimesOfSendTask % user.IntervalTimes == 0 {
for (_ , queue) in user.taskQueues {
if queue.count() > 0 {
user.sendTask(queue.pop())
//print("发送任务\(queue.pop().taskId)")
}
}
user.taskNum -= 1
}
}
}
repeatTimesOfSendTask += 1
}
//向用户随机发送一个任务
func randomGenerateTaskToUser(user:MUser){
//产生一个100- 3000的随机任务 平均值为1000的泊松分布
let randomFile = possionNum(1000)
let fileSize = (randomFile > 3000 ? 3000 : randomFile) < 100 ? 100 : (randomFile > 3000 ? 3000 : randomFile)
//Random算法的任务
let randomTask:Task = Task()
randomTask.fileSize = fileSize
taskId += 1
randomTask.taskId = taskId
randomTask.taskType = .Random
randomTask.fromUser = user
user.taskQueues["Random"]!.push(randomTask)
//HAF算法的任务
let HAFTask:Task = Task()
HAFTask.fileSize = fileSize
taskId += 1
HAFTask.taskId = taskId
HAFTask.taskType = .HAF
HAFTask.fromUser = user
user.taskQueues["HAF"]!.push(HAFTask)
//DBC算法的任务
let DBCTask:Task = Task()
DBCTask.fileSize = fileSize
taskId += 1
DBCTask.taskId = taskId
DBCTask.taskType = .DBC
DBCTask.fromUser = user
user.taskQueues["DBC"]!.push(DBCTask)
//GMA算法的任务
let GMATask:Task = Task()
GMATask.fileSize = fileSize
taskId += 1
GMATask.taskId = taskId
GMATask.taskType = .GMA
GMATask.fromUser = user
user.taskQueues["GMA"]!.push(GMATask)
// print("发送任务:")
// print("任务Id 用户Id 任务大小")
//print("\(task.taskId) \(allUsers[i].userId) \(task.fileSize) ")
}
//cloudletDelegate所需实现的方法,用于cloudlet完成任务时修改manager中的总的任务信息
func finishTask(time: Float?,taskType:TaskType) {
let keyString:String = taskType.toString() //Random,HAF,DBC,GMA算法的key值,根据任务的不同更改对应的信息
if let _ = time {
reponseTime[keyString] = (reponseTime[keyString]! * Float(successTaskNum[keyString]!) + time!) / Float(successTaskNum[keyString]! + 1)
successTaskNum[keyString]! += 1
}
else{
failTaskNum[keyString]! += 1
}
}
//cloudletDelegate所需实现的方法,用于cloudlet完成任务时修改manager中的总的任务信息
func offloadToCloudlet(task:Task,fromAp:AP){
if userIsAssignedToCloudlet {
switch task.taskType {
case .Random: offloadRandom(task,fromAp:fromAp) //Random算法将任务offload
case .HAF: offloadHAF(task,fromAp:fromAp)
case .DBC: offloadDBC(task,fromAp:fromAp)
case .GMA: offloadGMA(task,fromAp:fromAp)
default: break
}
//print("offload任务 \(task.taskId)")
}
else{
//cloudlet还未产生,不能进行offload
}
}
//FIXME:在cloudlet中随机挑选一个进行offload
func offloadRandom(task:Task,fromAp:AP){
let index = randomIn(min: 0, max: randomCloudlets.count - 1)
let toCloudlet = randomCloudlets[index]
sendToCloudlet(task, fromAp: fromAp, toCloudlet: toCloudlet)
}
//FIXME:
func offloadHAF(task:Task,fromAp:AP){
let user = task.fromUser
//如果HAF算法已经将用户绑定到了具体的Cloudlet
if user.linkCloudelt[0] > -1 {
sendToCloudlet(task, fromAp: fromAp, toCloudlet: HAFCloudlets[user.linkCloudelt[0]])
}
//如果没有,则将用户绑定到具体的Cloudlet
else {
let linkCloudet = sortCloudletByDistance(task.taskType, fromAp: fromAp)[0][0]
user.linkCloudelt[0] = linkCloudet
sendToCloudlet(task, fromAp: fromAp, toCloudlet: HAFCloudlets[user.linkCloudelt[0]])
}
}
//FIXME:
func offloadDBC(task:Task,fromAp:AP){
let user = task.fromUser
//如果DBC算法已经将用户绑定到了具体的Cloudlet
if user.linkCloudelt[1] > -1 {
sendToCloudlet(task, fromAp: fromAp, toCloudlet: DBCCloudlets[user.linkCloudelt[1]])
}
//如果没有,则将用户绑定到具体的Cloudlet
else {
let linkCloudet = sortCloudletByDistance(task.taskType, fromAp: fromAp)[0][0]
user.linkCloudelt[1] = linkCloudet
sendToCloudlet(task, fromAp: fromAp, toCloudlet: DBCCloudlets[user.linkCloudelt[1]])
}
}
//FIXME:
func offloadGMA(task:Task,fromAp:AP){
//sendToCloudlet(task, fromAp: fromAp, toCloudlet: GMACloudlets[findClosetCloudlet(task, fromAp: fromAp)])
let user = task.fromUser
//如果GMA算法已经将用户绑定到了具体的Cloudlet
if user.linkCloudelt[2] > -1 {
sendToCloudlet(task, fromAp: fromAp, toCloudlet: GMACloudlets[user.linkCloudelt[2]])
}
//如果没有,则将用户绑定到具体的Cloudlet
else {
let linkCloudet = sortCloudletByDistance(task.taskType, fromAp: fromAp)[0][0]
user.linkCloudelt[2] = linkCloudet
sendToCloudlet(task, fromAp: fromAp, toCloudlet: GMACloudlets[user.linkCloudelt[2]])
}
}
//根据当前用户连接到的AP寻找到最近的Cloudlet
func sortCloudletByDistance(taskType:TaskType,fromAp:AP) -> Array<Array<Int>>{
let dijkstra = Dijkstra(graph: apGraph)
var cloudletIndexAndDistance = Array<Array<Int>>()
var cloudlets:[Cloudlet] = []
switch taskType {
case .HAF: cloudlets = HAFCloudlets
case .DBC: cloudlets = DBCCloudlets
case .GMA: cloudlets = GMACloudlets
default: print("findClosetCloudlet出错!")
}
for cloudletIndex in 0 ... cloudlets.count - 1 {
dijkstra.getPath(fromAp.APId - 1 , toNode: cloudlets[cloudletIndex].ap.APId - 1)
let dist = dijkstra.getDistance(fromAp.APId - 1 , toNode:cloudlets[cloudletIndex].ap.APId - 1)
let tmp = [cloudletIndex,Int(dist)]
cloudletIndexAndDistance.append(tmp)
}
cloudletIndexAndDistance.sortInPlace{$0[1] < $1[1]}
return cloudletIndexAndDistance
}
//根据不同的算法得到任务offload到的cloudlet后将任务发送到特定的Cloudlet
func sendToCloudlet(task:Task,fromAp:AP,toCloudlet:Cloudlet){
let currentTask = task
let toAp = toCloudlet.ap
currentTask.tansferPath = getMinTransferPath(fromAp, toAp: toAp) //设置任务的传输路径
toCloudlet.receiveTask(currentTask) //向对应的cloudlet发送任务
// print("当前任务Id:\(currentTask.taskId) 任务类型:\(currentTask.taskType.toString()) 用户当前AP:\(currentTask.fromUser.currentAP.APId) 任务传输路径:\(outputPath)")
}
//计算多个AP总的工作负载
func computeWorkLoad(aps:Set<AP>) ->Float{
var workload:Float = 0.0
for ap in aps {
workload += ap.workload
}
return workload
}
func getCanditeUsersIn(ap:AP,hops:Int)->Array<Int>{
var users = Array<Int>()
for index in 0 ... allUsers.count - 1 {
let hop = getHopNum(allUsers[index].currentAP, toAp: ap)
if hop <= hops {
users.append(index)
}
}
return users
}
//得到某个AP的N跳邻居
func getNeighbours (ap:AP,hops:Int) ->Set<AP>{
var apArray = Set<AP>()
apArray.insert(ap)
//apArray.addObject(ap)
var hopNum = hops
while hopNum > 0
{
for apTmp in apArray {
for neighbour in (apTmp as AP).neighbour{
apArray.insert(neighbour)
}
}
hopNum -= 1
}
// print("AP ID 邻居 \n\(ap.APId)")
// for tmp in apArray {
//
// print(" \(tmp.APId)\n")
// }
return apArray
}
//得到某个AP的第N跳邻居
func getNeighboursInHop (hop:Int,fromAp:AP) ->Set<AP>{
var apArray = Set<AP>()
apArray.insert(fromAp)
if hop > 0 {
apArray = getNeighbours(fromAp, hops: hop).subtract(getNeighbours(fromAp, hops: (hop - 1)))
}
return apArray
}
//得到两个AP之间最短传输路径
func getMinTransferPath(fromAp:AP,toAp:AP) -> [AP] {
let dijkstra = Dijkstra(graph: apGraph)
//用path中的值 = APId - 1
let path = dijkstra.getPath(fromAp.APId - 1 , toNode: toAp.APId - 1)
let apPath = NSMutableArray()
//var outputPath = ""
for node in path {
for ap in allAPs {
if ap.APId == node + 1 {
apPath.addObject(ap)
//outputPath += "\(ap.APId) "
}
}
}
return NSArray(array: apPath) as! [AP] //设置任务的传输路径
}
//得到两个点之间的跳数
func getHopNum(fromAp:AP,toAp:AP) ->Int{
if fromAp.APId == fromAp.APId {
return 0
}
var count = 0
var apArray = NSMutableArray()
apArray.addObject(fromAp)
while true {
for apTmp in apArray {
for neighbour in (apTmp as! AP).neighbour{
count += 1
if neighbour.APId == toAp.APId {
return count
}
else {
apArray = addApToArray(apArray, ap: neighbour)
}
}
}
}
//return count
}
//从一个AP集合中移除掉特定的AP
func removeApsFromSet(aps:Set<AP>,fromSet:Set<AP>)-> Set<AP>{
var set = fromSet
for ap in aps {
set.remove(ap)
}
return set
}
//向一个AP数组中加入新的AP(以集合的方式加入)
func addApToArray(apArray:NSMutableArray,ap:AP) ->NSMutableArray{
var isExit = false
for m in 0 ... apArray.count - 1 {
if apArray[m].APId == ap.APId {
isExit = true
}
}
if !isExit {
apArray.addObject(ap)
}
return apArray
}
//产生一个区间的随机数
func randomIn(min min: Int, max: Int) -> Int {
return Int(arc4random()) % (max - min + 1) + min
}
//产生number个在区间min到max内的数,不重复
func randomInRange(min min: Int, max: Int,number:Int) ->[Int]{
var set = Set<Int>()
for _ in 0 ... number - 1 {
var randomNum = randomIn(min: min, max: max)
while set.contains(randomNum){
randomNum = randomIn(min: min, max: max)
}
set.insert(randomNum)
}
let tmp = NSMutableArray()
for num in set {
tmp.addObject(num)
}
return NSArray(array: tmp) as! [Int]
}
//判断一个概率事件是否成立
func inPercentEvent(percent:Float) -> Bool{
let tmp = Int(percent * 100)
let randomInt = randomIn(min: 0, max: 100)
return randomInt < tmp
}
//得到距离用户最近的AP
func getClosestAP(user:MUser) -> AP {
var ap:AP = allAPs[0]
var minDistance:Float = distance(user.location, toPoint: allAPs[0].location)
for (var i = 1 ; i < allAPs.count ; i++ ) {
if minDistance > distance(user.location, toPoint: allAPs[i].location){
minDistance = distance(user.location, toPoint: allAPs[i].location)
ap = allAPs[i]
}
}
return ap
}
//计算从一个点到另一个点的距离
func distance(fromPoint:CGPoint,toPoint:CGPoint) ->Float{
let fromX = Float(fromPoint.x)
let fromY = Float(fromPoint.y)
let toX = Float(toPoint.x)
let toY = Float(toPoint.y)
return sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY))
}
//产生服从泊松分布的随机数
func possionNum (lamda:Float) ->Int {
//产生一个0-1之间的随机数
func randomDecimal() -> Float {
return Float(randomIn(min: 0, max: 99)) / 100.0
}
//FIXME:得到泊松分布的概率
func getPossionProbaility(k:Int,lamda:Float) ->Float{
var sum:Float = 1.0
for i in 0 ... k {
//i =0时系数为1
if i != 0 {
sum *= (lamda / Float(i))
}
}
return sum * exp(-lamda)
}
var x = 0
let random = randomDecimal()
var tmp = getPossionProbaility(x, lamda: lamda)
while tmp < random {
x += 1
tmp += getPossionProbaility(x, lamda: lamda)
}
return x
}
//FIXME:存在问题 打印AP信息
func printAPData(){
print("AP Id AP位置 AP类型 AP平均负载 AP邻居")
for (var i = 0 ; i < allAPs.count ; i++ ) {
var topology = "("
for ap in allAPs[i].neighbour {
topology += "\(ap.APId),"
}
topology += ")"
print(" \(allAPs[i].APId) (\(allAPs[i].location.x) , \((allAPs[i].location.y))) \(allAPs[i].apLever.toString()) \(allAPs[i].workload) \(topology)")
}
}
//打印用户数据
func printUserData(){
print("用户Id 用户位置 移动速度 当前AP[APId,AP位置,AP类型] 加速度 HAFCloudletId DBCCloudletId")
for user in allUsers {
let aX = String(format: "%.5f", user.acceleration.x)
let aY = String(format: "%.5f", user.acceleration.y)
print(" \(user.userId) (\(user.location.x),\(user.location.y)) \(user.moveLever.rawValue) [\(user.currentAP.APId),(\(user.currentAP.location.x),\(user.currentAP.location.y)),\(user.currentAP.apLever.toString())] (\(aX),\(aY)) \(user.linkCloudelt[0]) \(user.linkCloudelt[1])")
}
}
//FIXME:打印cloudlet数据
func printCloudletData(){
let k = Float(randomCloudlets.count)
var workload:Float = 0.0
var piRandom:Float = 0.0
var piHAF:Float = 0.0
var piDBC:Float = 0.0
var piGMA:Float = 0.0
for cloudlet in randomCloudlets {
workload += cloudlet.cpuWorkload
}
workload = workload / k * 10.0
print("Random算法:\n cloudlet Id 所在AP Id CPU负载 Memory负载 平均排队时间")
for cloudlet in randomCloudlets {
let tmp = cloudlet.cpuWorkload * 10.0 - workload
piRandom += tmp * tmp
print("\(cloudlet.cloudletId) \(cloudlet.ap.APId) \(cloudlet.getCpuWorkload()) \(cloudlet.memoryWorkload) \(cloudlet.queueTime)")
}
print("HAF算法:\n cloudlet Id 所在AP Id CPU负载 Memory负载 平均排队时间")
for cloudlet in HAFCloudlets {
let tmp = cloudlet.cpuWorkload * 10.0 - workload
piHAF += tmp * tmp
print("\(cloudlet.cloudletId) \(cloudlet.ap.APId) \(cloudlet.getCpuWorkload()) \(cloudlet.memoryWorkload) \(cloudlet.queueTime)")
}
print("DBC算法:\n cloudlet Id 所在AP Id CPU负载 Memory负载 平均排队时间")
for cloudlet in DBCCloudlets {
let tmp = cloudlet.cpuWorkload * 10.0 - workload
piDBC += tmp * tmp
print("\(cloudlet.cloudletId) \(cloudlet.ap.APId) \(cloudlet.getCpuWorkload()) \(cloudlet.memoryWorkload) \(cloudlet.queueTime)")
}
print("GMA算法:\n cloudlet Id 所在AP Id CPU负载 Memory负载 平均排队时间")
for cloudlet in GMACloudlets {
let tmp = cloudlet.cpuWorkload * 10.0 - workload
piGMA += tmp * tmp
print("\(cloudlet.cloudletId) \(cloudlet.ap.APId) \(cloudlet.getCpuWorkload()) \(cloudlet.memoryWorkload) \(cloudlet.queueTime)")
}
piRandom = sqrt(piRandom / k)
piHAF = sqrt(piHAF / k)
piDBC = sqrt(piDBC / k)
piGMA = sqrt(piGMA / k)
print("\n平均负载: \(workload) Cloudlet数量:\(randomCloudlets.count) 用户数量:\(allUsers.count)")
print("Cloudlet平均负载标准差:\nRandom: \(piRandom) HAF: \(piHAF) DBC: \(piDBC) GMA: \(piGMA)")
}
//打印系统数据
func printSystemData(){
print("算法 平均响应时间 任务失败率")
for (key,value) in reponseTime {
let successPercent = String(format: "%.4f", 1.0 - Float(successTaskNum[key]!) / Float((successTaskNum[key]! + failTaskNum[key]!)))
print("\(key) \(value) \(successPercent)")
}
}
}
|
//
// ZXDrugListView.swift
// YDHYK
//
// Created by 120v on 2017/11/22.
// Copyright © 2017年 screson. All rights reserved.
//
import UIKit
import AnimatedCollectionViewLayout
class ZXDrugListView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.setUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUI()
}
//MARK: - UI
func setUI() {
self.backgroundColor = UIColor.zx_tintColor
self.addSubview(self.pageControl)
self.addSubview(self.collectionView)
self.pageControl.numberOfPages = 1
}
override func layoutSubviews() {
super.layoutSubviews()
self.collectionView.frame = CGRect.init(x: 0, y: 7, width: self.bounds.size.width, height: 229)
self.pageControl.frame = CGRect.init(x: 0, y: self.collectionView.frame.maxY, width: self.bounds.size.width, height: 32)
}
//MARK: - LoadData
func loadData(_ dataArr: Array<Any>?) {
self.remindTimeArray.removeAll()
if dataArr != nil {
self.remindTimeArray = dataArr!
self.pageControl.numberOfPages = self.remindTimeArray.count
}
self.collectionView.reloadData()
self.selectedNearestTime()
}
//MARK: - 选中距当前时间最近的cell
func selectedNearestTime() {
//1. 获取当前时间
let currTime = ZXDateUtils.current.time(false)
//2. 时间格式
let format: DateFormatter = DateFormatter()
format.dateFormat = "HH:mm"
//3. 当前时间格式
let currDate: Date = format.date(from: currTime)!
let currDateInt: TimeInterval = currDate.timeIntervalSinceReferenceDate
//4. 去绝对值
var dateDict: Dictionary<String,Any> = Dictionary()
for (idx,dict) in self.remindTimeArray.enumerated() {
if let dict = dict as? Dictionary<String,Any> {
let pushTime = dict.keys.first
//推送时间
let pushDate:Date = format.date(from: pushTime!)!
//取与当前时间比较后的绝对值
let pushDateInt: TimeInterval = pushDate.timeIntervalSinceReferenceDate
let result = fabs(pushDateInt - currDateInt)
//
dateDict["\(idx)"] = result
}
}
//5. 排序
if dateDict.count > 0 {
let resultArr = dateDict.sorted { (arg0, arg1) -> Bool in
let value0: Double = arg0.value as! Double
let value1: Double = arg1.value as! Double
return value1 > value0
}
//6. 取最小值
let firstDic = resultArr.first
let firstValue: Double = firstDic?.value as! Double
//7. 获取索引
for (idx,objc) in dateDict.enumerated() {
let val: Double = objc.value as! Double
if val == firstValue {
let indexPath: IndexPath = IndexPath.init(row: idx, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
break
}
}
}
}
//MARK: Lazy
lazy var remindTimeArray: Array<Any> = {
let arr: Array<Any> = Array.init()
return arr
}()
lazy var pageControl: UIPageControl = {
let pagCon: UIPageControl = UIPageControl.init()
pagCon.currentPageIndicatorTintColor = UIColor.white
pagCon.pageIndicatorTintColor = UIColor.zx_textColorBody
pagCon.currentPage = 0;
pagCon.backgroundColor = UIColor.zx_tintColor
return pagCon
}()
lazy var collectionView: UICollectionView = {
let animLayout: AnimatedCollectionViewLayout = AnimatedCollectionViewLayout()
var animator: LinearCardAttributesAnimator = LinearCardAttributesAnimator()
animator.itemSpacing = 0.20
animator.scaleRate = 0.85
animLayout.animator = animator
animLayout.scrollDirection = .horizontal
animLayout.minimumLineSpacing = 0
animLayout.minimumInteritemSpacing = 0
animLayout.sectionInset = UIEdgeInsets.zero
let collView: UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: animLayout)
collView.showsVerticalScrollIndicator = false
collView.showsHorizontalScrollIndicator = false
collView.delegate = self
collView.dataSource = self
collView.backgroundColor = UIColor.zx_tintColor
collView.isPagingEnabled = true
collView.autoresizingMask = [UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))]
collView.register(UINib.init(nibName: String.init(describing: ZXRemindListCell.self), bundle: nil), forCellWithReuseIdentifier: ZXRemindListCell.ZXRemindListCellID)
collView.register(UINib.init(nibName: String.init(describing: ZXNoRemindCell.self), bundle: nil), forCellWithReuseIdentifier: ZXNoRemindCell.ZXNoRemindCellID)
return collView
}()
}
extension ZXDrugListView:UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.pageControl.currentPage = (NSInteger)(scrollView.contentOffset.x/(scrollView.bounds.size.width))
}
}
extension ZXDrugListView: UICollectionViewDelegate {
}
extension ZXDrugListView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: ZXBOUNDS_WIDTH, height: 249.0)
}
}
extension ZXDrugListView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.remindTimeArray.count > 0 {
return self.remindTimeArray.count
}else{
return 1
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if self.remindTimeArray.count > 0 {
let cell: ZXRemindListCell = collectionView.dequeueReusableCell(withReuseIdentifier: ZXRemindListCell.ZXRemindListCellID, for: indexPath) as! ZXRemindListCell
cell.loadData(self.remindTimeArray[indexPath.row] as! Dictionary<String, Any>)
return cell
}else{
let cell: ZXNoRemindCell = collectionView.dequeueReusableCell(withReuseIdentifier: ZXNoRemindCell.ZXNoRemindCellID, for: indexPath) as! ZXNoRemindCell
return cell
}
}
}
|
//
// SQLQueryFetcher+decodeOptional.swift
// KognitaCore
//
// Created by Mats Mollestad on 9/2/19.
//
import SQL
import PostgreSQL
extension SQLQueryFetcher {
/// Collects the first decoded output and returns it.
///
/// builder.first(decoding: Planet.self)
///
public func first<D>(decoding type: Optional<D>.Type) -> Future<D?>
where D: Decodable
{
return self.all(decoding: type).map { $0.first }
}
/// Collects the first decoded output and returns it.
///
/// builder.first(decoding: Planet.self)
///
public func first<A, B>(decoding typeA: Optional<A>.Type, _ typeB: Optional<B>.Type) -> Future<(A?, B?)?>
where A: Decodable, B: Decodable
{
return self.all(decoding: typeA, typeB).map { $0.first }
}
/// Collects the first decoded output and returns it.
///
/// builder.first(decoding: Planet.self)
///
public func first<A, B>(decoding typeA: A.Type, _ typeB: Optional<B>.Type) -> Future<(A, B?)?>
where A: Decodable, B: Decodable
{
return self.all(decoding: typeA, typeB).map { $0.first }
}
/// Collects the first decoded output and returns it.
///
/// builder.first(decoding: Planet.self)
///
public func first<A, B, C>(decoding typeA: Optional<A>.Type, _ typeB: Optional<B>.Type, _ typeC: Optional<C>.Type) -> Future<(A?, B?, C?)?>
where A: Decodable, B: Decodable, C: Decodable
{
return self.all(decoding: typeA, typeB, typeC).map { $0.first }
}
/// Collects the first decoded output and returns it.
///
/// builder.first(decoding: Planet.self)
///
public func first<A, B, C>(decoding typeA: A.Type, _ typeB: Optional<B>.Type, _ typeC: Optional<C>.Type) -> Future<(A, B?, C?)?>
where A: Decodable, B: Decodable, C: Decodable
{
return self.all(decoding: typeA, typeB, typeC).map { $0.first }
}
/// Collects the first decoded output and returns it.
///
/// builder.first(decoding: Planet.self)
///
public func first<A, B, C>(decoding typeA: A.Type, _ typeB: B.Type, _ typeC: Optional<C>.Type) -> Future<(A, B, C?)?>
where A: Decodable, B: Decodable, C: Decodable
{
return self.all(decoding: typeA, typeB, typeC).map { $0.first }
}
/// Collects all decoded output into an array and returns it.
///
/// builder.all(decoding: Planet.self)
///
public func all<A>(decoding type: Optional<A>.Type) -> Future<[A]>
where A: Decodable
{
var all: [A] = []
return run(decoding: type) {
if let element = $0 {
all.append(element)
}
}.map { all }
}
/// Collects all decoded output into an array and returns it.
///
/// builder.all(decoding: Planet.self)
///
public func all<A, B>(decoding typeA: Optional<A>.Type, _ typeB: Optional<B>.Type) -> Future<[(A?, B?)]>
where A: Decodable, B: Decodable
{
var all: [(A?, B?)] = []
return run(decoding: typeA, typeB) { aValue, bValue in
if aValue != nil || bValue != nil {
all.append((aValue, bValue))
}
}.map { all }
}
/// Collects all decoded output into an array and returns it.
///
/// builder.all(decoding: Planet.self)
///
public func all<A, B>(decoding typeA: A.Type, _ typeB: Optional<B>.Type) -> Future<[(A, B?)]>
where A: Decodable, B: Decodable
{
var all: [(A, B?)] = []
return run(decoding: typeA, typeB) { aValue, bValue in all.append((aValue, bValue)) }.map { all }
}
/// Collects all decoded output into an array and returns it.
///
/// builder.all(decoding: Planet.self)
///
public func all<A, B, C>(decoding typeA: Optional<A>.Type, _ typeB: Optional<B>.Type, _ typeC: Optional<C>.Type) -> Future<[(A?, B?, C?)]>
where A: Decodable, B: Decodable, C: Decodable
{
var all: [(A?, B?, C?)] = []
return run(decoding: typeA, typeB, typeC) { aValue, bValue, cValue in
if aValue != nil || bValue != nil || cValue != nil {
all.append((aValue, bValue, cValue))
}
}.map { all }
}
/// Collects all decoded output into an array and returns it.
///
/// builder.all(decoding: Planet.self)
///
public func all<A, B, C>(decoding typeA: A.Type, _ typeB: Optional<B>.Type, _ typeC: Optional<C>.Type) -> Future<[(A, B?, C?)]>
where A: Decodable, B: Decodable, C: Decodable
{
var all: [(A, B?, C?)] = []
return run(decoding: typeA, typeB, typeC) { aValue, bValue, cValue in all.append((aValue, bValue, cValue)) }.map { all }
}
/// Collects all decoded output into an array and returns it.
///
/// builder.all(decoding: Planet.self)
///
public func all<A, B, C>(decoding typeA: A.Type, _ typeB: B.Type, _ typeC: Optional<C>.Type) -> Future<[(A, B, C?)]>
where A: Decodable, B: Decodable, C: Decodable
{
var all: [(A, B, C?)] = []
return run(decoding: typeA, typeB, typeC) { aValue, bValue, cValue in all.append((aValue, bValue, cValue)) }.map { all }
}
/// Runs the query, passing decoded output to the supplied closure as it is recieved.
///
/// builder.run(decoding: Planet.self) { planet in
/// // ..
/// }
///
/// The returned future will signal completion of the query.
public func run<A>(
decoding type: Optional<A>.Type,
into handler: @escaping (A?) throws -> ()
) -> Future<Void>
where A: Decodable
{
return connectable.withSQLConnection { conn in
return conn.query(self.query) { row in
let identifier = Connectable.Connection.Query.Select.TableIdentifier.table(any: A.self)
let dValue = conn.decodeOptional(type, from: row, table: identifier)
try handler(dValue)
}
}
}
/// Runs the query, passing decoded output to the supplied closure as it is recieved.
///
/// builder.run(decoding: Planet.self, Galaxy.self, SolarSystem.self) { planet, galaxy, solarSystem in
/// // ..
/// }
///
/// The returned future will signal completion of the query.
public func run<A, B>(
decoding aType: Optional<A>.Type, _ bType: Optional<B>.Type,
into handler: @escaping (A?, B?) throws -> ()
) -> Future<Void>
where A: Decodable, B: Decodable
{
return connectable.withSQLConnection { conn in
return conn.query(self.query) { row in
let identifierA = Connectable.Connection.Query.Select.TableIdentifier.table(any: A.self)
let identifierB = Connectable.Connection.Query.Select.TableIdentifier.table(any: B.self)
let aValue = conn.decodeOptional(aType, from: row, table: identifierA)
let bValue = conn.decodeOptional(bType, from: row, table: identifierB)
try handler(aValue, bValue)
}
}
}
/// Runs the query, passing decoded output to the supplied closure as it is recieved.
///
/// builder.run(decoding: Planet.self, Galaxy.self, SolarSystem.self) { planet, galaxy, solarSystem in
/// // ..
/// }
///
/// The returned future will signal completion of the query.
public func run<A, B>(
decoding aType: A.Type, _ bType: Optional<B>.Type,
into handler: @escaping (A, B?) throws -> ()
) -> Future<Void>
where A: Decodable, B: Decodable
{
return connectable.withSQLConnection { conn in
return conn.query(self.query) { row in
let identifierA = Connectable.Connection.Query.Select.TableIdentifier.table(any: A.self)
let identifierB = Connectable.Connection.Query.Select.TableIdentifier.table(any: B.self)
let aValue = try conn.decode(aType, from: row, table: identifierA)
let bValue = conn.decodeOptional(bType, from: row, table: identifierB)
try handler(aValue, bValue)
}
}
}
/// Runs the query, passing decoded output to the supplied closure as it is recieved.
///
/// builder.run(decoding: Planet.self, Galaxy.self, SolarSystem.self) { planet, galaxy, solarSystem in
/// // ..
/// }
///
/// The returned future will signal completion of the query.
public func run<A, B, C>(
decoding aType: Optional<A>.Type, _ bType: Optional<B>.Type, _ cType: Optional<C>.Type,
into handler: @escaping (A?, B?, C?) throws -> ()
) -> Future<Void>
where A: Decodable, B: Decodable, C: Decodable
{
return connectable.withSQLConnection { conn in
return conn.query(self.query) { row in
let identifierA = Connectable.Connection.Query.Select.TableIdentifier.table(any: A.self)
let identifierB = Connectable.Connection.Query.Select.TableIdentifier.table(any: B.self)
let identifierC = Connectable.Connection.Query.Select.TableIdentifier.table(any: C.self)
let aValue = conn.decodeOptional(aType, from: row, table: identifierA)
let bValue = conn.decodeOptional(bType, from: row, table: identifierB)
let cValue = conn.decodeOptional(cType, from: row, table: identifierC)
try handler(aValue, bValue, cValue)
}
}
}
/// Runs the query, passing decoded output to the supplied closure as it is recieved.
///
/// builder.run(decoding: Planet.self, Galaxy.self, SolarSystem.self) { planet, galaxy, solarSystem in
/// // ..
/// }
///
/// The returned future will signal completion of the query.
public func run<A, B, C>(
decoding aType: A.Type, _ bType: Optional<B>.Type, _ cType: Optional<C>.Type,
into handler: @escaping (A, B?, C?) throws -> ()
) -> Future<Void>
where A: Decodable, B: Decodable, C: Decodable
{
return connectable.withSQLConnection { conn in
return conn.query(self.query) { row in
let identifierA = Connectable.Connection.Query.Select.TableIdentifier.table(any: A.self)
let identifierB = Connectable.Connection.Query.Select.TableIdentifier.table(any: B.self)
let identifierC = Connectable.Connection.Query.Select.TableIdentifier.table(any: C.self)
let aValue = try conn.decode(aType, from: row, table: identifierA)
let bValue = conn.decodeOptional(bType, from: row, table: identifierB)
let cValue = conn.decodeOptional(cType, from: row, table: identifierC)
try handler(aValue, bValue, cValue)
}
}
}
/// Runs the query, passing decoded output to the supplied closure as it is recieved.
///
/// builder.run(decoding: Planet.self, Galaxy.self, SolarSystem.self) { planet, galaxy, solarSystem in
/// // ..
/// }
///
/// The returned future will signal completion of the query.
public func run<A, B, C>(
decoding aType: A.Type, _ bType: B.Type, _ cType: Optional<C>.Type,
into handler: @escaping (A, B, C?) throws -> ()
) -> Future<Void>
where A: Decodable, B: Decodable, C: Decodable
{
return connectable.withSQLConnection { conn in
return conn.query(self.query) { row in
let identifierA = Connectable.Connection.Query.Select.TableIdentifier.table(any: A.self)
let identifierB = Connectable.Connection.Query.Select.TableIdentifier.table(any: B.self)
let identifierC = Connectable.Connection.Query.Select.TableIdentifier.table(any: C.self)
let aValue = try conn.decode(aType, from: row, table: identifierA)
let bValue = try conn.decode(bType, from: row, table: identifierB)
let cValue = conn.decodeOptional(cType, from: row, table: identifierC)
try handler(aValue, bValue, cValue)
}
}
}
}
/// Types conforming to this protocol can be used to build SQL queries.
extension SQLConnection {
/// Decodes a `Decodable` type from this connection's output.
/// If a table is specified, values should come only from columns in that table.
public func decodeOptional<D>(_ type: Optional<D>.Type, from row: Output, table: Query.Select.TableIdentifier?) -> D?
where D: Decodable {
do {
return try self.decode(D.self, from: row, table: table)
} catch {
return nil
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.