text
stringlengths
8
1.32M
import UIKit // Switch - case let a = 2 switch a { case 1: print("The value is 1") case 2: print("The value is 2") case 3, 4: print("The value is 3 or 4") default: print("I don't recognize the value!") } let possibleVowel = "p" switch possibleVowel { case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U": print("It's a vowel") default: print("It's not a vowel") } // Intervals let moons = 62 let planet = "Saturno" let readableCount: String switch moons { case 0: readableCount = "ninguna" case 1..<5: readableCount = "algunas" case 5..<12: readableCount = "unas cuantas" case 12..<100: readableCount = "varias docenas" case 100..<1000: readableCount = "varios centernares" default: readableCount = "muchísimas" } print("Hay \(readableCount) de lunas en \(planet)") // Tuples let point = (2,-2) switch point { case (0,0): print("\(point) es el origen de coordenadas") case (_,0): print("\(point) se halla sobre el eje X") case (0,_): print("\(point) se halla sobre el eje Y") case (-2...2, -2...2): print("\(point) se halla dentro de la caja") default: print("\(point) está fuera de la caja") } switch point { case (let x, 0): print("Se halla sobre el eje de las X con la coordenada \(x)") case (0, let y): print("Se halla sobre el eje de las Y con la coordenada \(y)") case let(x, y): print("Este punto está sobre el eje \(x), \(y)") } switch point { case let(x,y) where x == y: print("El punto \(x), \(y) está sobre la recta x = y") case let(x,y) where x == -y: print("El punto \(x), \(y) está sobre la recta x = -y") case let(x,y): print("El punto \(x), \(y) es un punto cualquiera") } let character: Character = "e" switch character { case "a", "e", "i", "o", "u": print("\(character) es una vocal") case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z": print("\(character) es una consonante") default: print("\(character) no es ni vocal ni consonante") } let anotherPoint = (7,0) switch anotherPoint { case (let distance, 0), (0, let distance): print("Sobre el eje, y a distance \(distance) del origen de coordenadas") default: print("No está sobre el eje") }
// // AppDelegate.swift // AmazingApps // // Created by J.A. Korten on 21/10/2018. // Copyright © 2018 HAN University. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var fabulousApps: [FabulousApp] = [] let ptpManagerService = PeerToPeerConnectionManager() var lastPeerDeviceId : String? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let developers = ["Bart van der Wal", "Jille Treffers", "Robert Holwerda", "Lars Tijsma", "Johan Korten"] var myImage : Data? if let img = UIImage(named: "Image") { myImage = img.pngData() } let myFabulousApp = FabulousApp.init(appTitle: "My Fabulous App", appDescription: "This amazing app allows students to present their magnificent work using an Apple TV. It also allows others to rate their app :)", appDevelopers: developers, appImage: myImage, reviewScore: 4, deviceId: "") fabulousApps.append(myFabulousApp) // ... do other important app-wide things ptpManagerService.delegate = self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func addInfoToModel(info : String) { if let jsonData = info.data(using: .utf8) { let decoder = JSONDecoder() do { let appData = try decoder.decode(FabulousApp.self, from: jsonData) print("Info for: \(appData.appTitle) found from device: \(appData.deviceId)!") // Add to Model if deviceId does not exist, otherwise only update data lastPeerDeviceId = appData.deviceId var counter = 0 for app in fabulousApps { if app.deviceId == lastPeerDeviceId { fabulousApps[counter] = appData return } counter += 1 } fabulousApps.append(appData) // ToDo: send notification to listening viewcontrollers that app data was modified // We won't need it since we will update the Slideshow using a timer from the model. } catch { print(error.localizedDescription) } } } } extension AppDelegate : PeerToPeerServiceDelegate { func imageInfoChanged(manager: PeerToPeerConnectionManager, imageData: Data) { // try to add uiimage to model if (lastPeerDeviceId != nil) { var counter = 0 for app in fabulousApps { if app.deviceId == lastPeerDeviceId { fabulousApps[counter].appImage = imageData return } counter = counter + 1 } } } func connectedDevicesChanged(manager: PeerToPeerConnectionManager, connectedDevices: [String]) { OperationQueue.main.addOperation { print("Connections: \(connectedDevices)") } } func infoChanged(manager: PeerToPeerConnectionManager, infoString: String) { OperationQueue.main.addOperation { self.addInfoToModel(info: infoString) } } }
// // ViewController.swift // SwiftNotifications // // Created by Tony on 20/09/2014. // Copyright (c) 2014 com.dobrev. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // schedule notification var dateComponents:NSDateComponents = NSDateComponents() dateComponents.year = 2014 dateComponents.month = 09 dateComponents.day = 20 dateComponents.hour = 23 dateComponents.minute = 13 dateComponents.timeZone = NSTimeZone.systemTimeZone() var calendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar) var date:NSDate!! = calendar.dateFromComponents(dateComponents) var notification:UILocalNotification = UILocalNotification() notification.category = "FIRST_CATEGORY" notification.alertBody = "Hello notifications" notification.fireDate = date UIApplication.sharedApplication().scheduleLocalNotification(notification) // We are posting the actions to the notification center - add event observer NSNotificationCenter.defaultCenter().addObserver(self, selector:"drawAShape", name: "firstActionTapped", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"showAMessage", name: "secondActionTapped", object: nil) } func drawAShape(){ var view:UIView = UIView(frame: CGRectMake(10, 10, 100, 100)) view.backgroundColor = UIColor.redColor() self.view.addSubview(view) } func showAMessage(){ var view:UIView = UIView(frame: CGRectMake(10, 10, 100, 100)) view.backgroundColor = UIColor.redColor() var alertMessageController:UIAlertController = UIAlertController(title: "Notification App", message: "Hello notifications", preferredStyle: UIAlertControllerStyle.Alert) alertMessageController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertMessageController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // RouteStoreCase.swift // QiitaWithFluxSample // // Created by marty-suzuki on 2017/04/19. // Copyright © 2017年 marty-suzuki. All rights reserved. // import XCTest import RxSwift @testable import QiitaWithFluxSample class RouteStoreCase: XCTestCase { var routeStore: RouteStore! var routeDispatcher: RouteDispatcher! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. let dispatcher = RouteDispatcher.testable.make() routeDispatcher = dispatcher routeStore = RouteStore(registrator: dispatcher.registrator) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testLoginDisplayType() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let loginDisplayTypeExpectation = expectation(description: "loginDisplayType is .root") let disposeBag = DisposeBag() routeStore.login.skip(1) .subscribe(onNext: { XCTAssertEqual($0, LoginDisplayType.root) loginDisplayTypeExpectation.fulfill() }) .disposed(by: disposeBag) routeDispatcher.dispatcher.login.onNext(.root) waitForExpectations(timeout: 0.1, handler: nil) } func testSearchDisplayType() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. guard let url = URL(string: "https://github.com") else { XCTFail() return } let searchDisplayTypeExpectation = expectation(description: "searchDisplayType is .webView") let disposeBag = DisposeBag() routeStore.search.skip(1) .subscribe(onNext: { let url: URL? if case .webView(let value)? = $0 { url = value } else { url = nil } XCTAssertNotNil(url) XCTAssertEqual(url?.absoluteString, "https://github.com") searchDisplayTypeExpectation.fulfill() }) .disposed(by: disposeBag) routeDispatcher.dispatcher.search.onNext(.webView(url)) waitForExpectations(timeout: 0.1, handler: nil) } }
// // HttpRequestNetConnectivityChecker.swift // Grubbie // // Created by JABE on 11/26/15. // Copyright © 2015 JABELabs. All rights reserved. // class HttpRequestNetConnectivityChecker : NetConnectivityCheckerStrategy { func isNetworkAvailable() -> Bool { let url = NSURL(string: "https://google.com/") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "HEAD" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 10.0 var response: NSURLResponse? do { let _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData? if let httpResponse = response as? NSHTTPURLResponse { return httpResponse.statusCode == 200 } return false } catch { return false } } }
// // ScheduleViewController.swift // prkng-ios // // Created by Cagdas Altinkaya on 02/04/15. // Copyright (c) 2015 PRKNG. All rights reserved. // import UIKit class ScheduleViewController: PRKModalViewControllerChild, UIScrollViewDelegate { private var scheduleItems : Array<ScheduleItemModel> private var scrollView : UIScrollView private var contentView : UIView private var leftView : ScheduleLeftView private var columnViews : Array<ScheduleColumnView> private var scheduleItemViews : Array<ScheduleItemView> private(set) var LEFT_VIEW_WIDTH : CGFloat private(set) var COLUMN_SIZE : CGFloat private(set) var COLUMN_HEADER_HEIGHT : CGFloat private(set) var CONTENTVIEW_HEIGHT : CGFloat private(set) var ITEM_HOUR_HEIGHT : CGFloat override init(spot: ParkingSpot, view: UIView) { scrollView = UIScrollView() contentView = UIView() leftView = ScheduleLeftView() scheduleItems = [] columnViews = [] scheduleItemViews = [] LEFT_VIEW_WIDTH = UIScreen.mainScreen().bounds.size.width * 0.18 COLUMN_SIZE = UIScreen.mainScreen().bounds.size.width * 0.28 CONTENTVIEW_HEIGHT = UIScreen.mainScreen().bounds.size.height - Styles.Sizes.modalViewHeaderHeight - 71.0 COLUMN_HEADER_HEIGHT = 45.0 ITEM_HOUR_HEIGHT = (CONTENTVIEW_HEIGHT - COLUMN_HEADER_HEIGHT) / 24.0 super.init(spot: spot, view: view) scheduleItems = ScheduleHelper.getScheduleItems(spot) scheduleItems = ScheduleHelper.processScheduleItems(scheduleItems, respectDoNotProcess: true) } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override func loadView() { view = UIView() view.backgroundColor = Styles.Colors.stone setupViews() setupConstraints() } override func viewDidLoad() { super.viewDidLoad() self.screenName = "Schedule (Agenda) View" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateValues() } override func viewWillLayoutSubviews() { //forbidden views should be on top for column in columnViews { for view in column.subviews { if let subview = view as? ScheduleItemView { if(subview.rule.ruleType == ParkingRuleType.TimeMax) { column.bringSubviewToFront(subview) } } } } //...but snow removals should be on top of them! for column in columnViews { for view in column.subviews { if let subview = view as? ScheduleItemView { if(subview.rule.ruleType == ParkingRuleType.SnowRestriction) { column.bringSubviewToFront(subview) } } } } super.viewWillLayoutSubviews() } func setupViews() { scrollView.backgroundColor = Styles.Colors.cream2 scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false self.view.addSubview(scrollView) let scheduleTimes = ScheduleTimeModel.getScheduleTimesFromItems(scheduleItems) leftView = ScheduleLeftView(model: scheduleTimes) leftView.backgroundColor = Styles.Colors.cream2 self.view.addSubview(leftView) scrollView.addSubview(contentView) for _ in 0...6 { let columnView : ScheduleColumnView = ScheduleColumnView() contentView.addSubview(columnView) columnViews.append(columnView) columnView.setActive(false) } columnViews[0].setActive(true) for scheduleItem in scheduleItems { let scheduleItemView : ScheduleItemView = ScheduleItemView(model : scheduleItem) columnViews[scheduleItem.columnIndex!].addSubview(scheduleItemView) scheduleItemViews.append(scheduleItemView) } } func setupConstraints () { leftView.snp_makeConstraints { (make) -> () in make.top.equalTo(self.view).offset(Styles.Sizes.modalViewHeaderHeight) make.left.equalTo(self.view) make.bottom.equalTo(self.view) make.width.equalTo(self.LEFT_VIEW_WIDTH) } for label in leftView.timeLabels { label.snp_makeConstraints(closure: { (make) -> () in make.left.equalTo(self.leftView) make.right.equalTo(self.leftView).offset(-7) make.centerY.equalTo(self.leftView.snp_top).offset((self.ITEM_HOUR_HEIGHT * label.scheduleTimeModel!.yIndexMultiplier) + (label.scheduleTimeModel!.heightOffsetInHours * self.ITEM_HOUR_HEIGHT) + self.COLUMN_HEADER_HEIGHT) make.top.greaterThanOrEqualTo(self.leftView) make.bottom.lessThanOrEqualTo(self.leftView) }) } scrollView.snp_makeConstraints { (make) -> () in make.top.equalTo(self.view).offset(Styles.Sizes.modalViewHeaderHeight) make.left.equalTo(self.view).offset(self.LEFT_VIEW_WIDTH) make.right.equalTo(self.view) make.bottom.equalTo(self.view) } contentView.snp_makeConstraints { (make) -> () in make.height.equalTo(self.scrollView)//CONTENTVIEW_HEIGHT) make.width.equalTo(self.COLUMN_SIZE * 7.0) make.edges.equalTo(self.scrollView) } var columnIndex = 0 for column in columnViews { column.snp_makeConstraints(closure: { (make) -> () in make.top.equalTo(self.contentView) make.bottom.equalTo(self.contentView) make.width.equalTo(self.COLUMN_SIZE) make.left.equalTo(self.contentView).offset(self.COLUMN_SIZE * CGFloat(columnIndex)) }); columnIndex++; } var itemIndex = 0 for itemView in scheduleItemViews { let scheduleItem = scheduleItems[itemIndex] let columnView = columnViews[scheduleItem.columnIndex!] itemView.snp_makeConstraints(closure: { (make) -> () in make.top.equalTo(columnView).offset((self.ITEM_HOUR_HEIGHT * scheduleItem.yIndexMultiplier!) + self.COLUMN_HEADER_HEIGHT) make.height.equalTo(self.ITEM_HOUR_HEIGHT * scheduleItem.heightMultiplier!) make.left.equalTo(columnView) make.right.equalTo(columnView) }) itemIndex++; } } func updateValues () { var columnTitles = DateUtil.sortedDayAbbreviations() var index = 0 for columnView in columnViews { columnView.setTitle(columnTitles[index++]) } } // UIScrollViewDelegate func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let kMaxIndex : CGFloat = 7 let targetX : CGFloat = scrollView.contentOffset.x + velocity.x * 60.0 var targetIndex : CGFloat = round(targetX / COLUMN_SIZE) if (targetIndex < 0) { targetIndex = 0 } if (targetIndex > kMaxIndex) { targetIndex = kMaxIndex; } targetContentOffset.memory.x = targetIndex * (self.COLUMN_SIZE) } // func scrollViewDidScroll(scrollView: UIScrollView) { // // let maxOffset : Float = Float(COLUMN_SIZE * 4.0) // var ratio : Float = 0.0 // // if (scrollView.contentOffset.x != 0) { // ratio = Float(scrollView.contentOffset.x) / maxOffset // } // // } //MARK: Helper functions directly related to this view controller func scheduleItemViewOverlapsInColumn(itemView: ScheduleItemView, columnView:ScheduleColumnView) -> Bool { var scheduleItemViewsInColumn: [ScheduleItemView] = [] for view in columnView.subviews { if view.isKindOfClass(ScheduleItemView) { scheduleItemViewsInColumn.append(view as! ScheduleItemView) } } let intersectingViews = scheduleItemViewsInColumn.filter { $0 != itemView && itemView.frame.intersects($0.frame) } return intersectingViews.count > 0 } } //MARK: Helper class for managing and parsing schedules class ScheduleHelper { static func getAgendaItems(spot: ParkingSpot, respectDoNotProcess: Bool) -> [AgendaItem] { var agendaItems = [AgendaItem]() var dayIndexes = Set<Int>() var scheduleItems = getScheduleItems(spot) scheduleItems = processScheduleItems(scheduleItems, respectDoNotProcess: respectDoNotProcess) //convert schedule items into agenda items for scheduleItem in scheduleItems { let agendaItem = AgendaItem(startTime: NSTimeInterval(scheduleItem.startInterval), endTime: NSTimeInterval(scheduleItem.endInterval), dayIndex: scheduleItem.columnIndex!, timeLimit: Int(scheduleItem.limit), rule: scheduleItem.rule) agendaItems.append(agendaItem) dayIndexes.insert(scheduleItem.columnIndex!) } let notPresentDayIndexes = Set(0...6).subtract(dayIndexes) for dayIndex in notPresentDayIndexes { let agendaItem = AgendaItem(startTime: 0, endTime: 24*3600, dayIndex: dayIndex, timeLimit: 0, rule: ParkingRule(ruleType: .Free)) agendaItems.append(agendaItem) } agendaItems.sortInPlace { (first, second) -> Bool in if first.dayIndex == second.dayIndex { return first.startTime < second.startTime } else { return first.dayIndex < second.dayIndex } } return agendaItems } static func getScheduleItems(spot: ParkingSpot) -> [ScheduleItemModel] { var scheduleItems = [ScheduleItemModel]() let agenda = spot.sortedTimePeriods() for dayAgenda in agenda { var column : Int = 0 for period in dayAgenda.timePeriods { if (period != nil) { let startF : CGFloat = CGFloat(period!.start) let endF : CGFloat = CGFloat(period!.end) let scheduleItem = ScheduleItemModel(startF: startF, endF: endF, column : column, limitInterval: period!.timeLimit, rule: dayAgenda.rule) scheduleItems.append(scheduleItem) } ++column } } //the sorted time periods above are not enough to created a sorted schedule items list scheduleItems.sortInPlace { (left, right) -> Bool in if left.columnIndex == right.columnIndex { if left.startInterval == right.startInterval { return ParkingSpot.parkingRulesSorter(left.rule, right.rule) } else { return left.startInterval < right.startInterval } } return left.columnIndex < right.columnIndex } return scheduleItems } static func processScheduleItems(scheduleItems: [ScheduleItemModel], respectDoNotProcess: Bool) -> [ScheduleItemModel] { var newScheduleItems = [ScheduleItemModel]() for i in 0...6 { let tempScheduleItems = scheduleItems.filter({ (scheduleItem: ScheduleItemModel) -> Bool in return scheduleItem.columnIndex! == i && (!respectDoNotProcess || !scheduleItem.shouldNotProcess) }).sort({ (left: ScheduleItemModel, right: ScheduleItemModel) -> Bool in left.columnIndex! <= right.columnIndex! && left.startInterval <= right.startInterval && left.endInterval <= right.endInterval && left.limit <= right.limit }) for scheduleItem in tempScheduleItems { let lastScheduleItem = newScheduleItems.last //this loop is to see if this is the only item, potentially on other days of the week, in the schedule. //we can then deduce that it's safe to alter it and make it taller without messing with other items. var allScheduleItemsEqual = true for item in scheduleItems { if item.startInterval != scheduleItem.startInterval || item.endInterval != scheduleItem.endInterval || item.limit != scheduleItem.limit || item.rule.ruleType != scheduleItem.rule.ruleType { allScheduleItemsEqual = false } } //RULE: IF ONLY RESTRICTION, MAKE IT TALLER! if tempScheduleItems.count == 1 && allScheduleItemsEqual { scheduleItem.setMinimumHeight() newScheduleItems.append(scheduleItem) } //RULE: MERGE CONSECUTIVE EQUAL RULES else if (lastScheduleItem != nil && lastScheduleItem!.columnIndex! == scheduleItem.columnIndex! && lastScheduleItem!.endInterval >= scheduleItem.startInterval && lastScheduleItem!.limit == scheduleItem.limit && lastScheduleItem!.rule.ruleType == scheduleItem.rule.ruleType) { newScheduleItems.removeLast() let newScheduleItem = ScheduleItemModel(startF: lastScheduleItem!.startInterval, endF: scheduleItem.endInterval, column : scheduleItem.columnIndex!, limitInterval: scheduleItem.limit, rule: scheduleItem.rule) newScheduleItems.append(newScheduleItem) } //RULE: SPLIT (TIME MAXES OR PAID) IF A RESTRICTION OVERLAPS IT else if (lastScheduleItem != nil && lastScheduleItem!.columnIndex! == scheduleItem.columnIndex! && lastScheduleItem!.startInterval < scheduleItem.endInterval && lastScheduleItem!.endInterval > scheduleItem.startInterval && lastScheduleItem!.rule.ruleType != scheduleItem.rule.ruleType) { //now just determine which is the restriction and which is the time max var restriction: ScheduleItemModel = ScheduleItemModel() var timeMax: ScheduleItemModel = ScheduleItemModel() if lastScheduleItem!.rule.ruleType != .Restriction { //then this is the time max or paid restriction = scheduleItem timeMax = lastScheduleItem! newScheduleItems.removeLast() newScheduleItems.append(restriction) } else { restriction = lastScheduleItem! timeMax = scheduleItem } if timeMax.isLongerThan(restriction) { //now split the time max... if timeMax.startInterval >= restriction.startInterval { //then just make our time max start after timeMax = ScheduleItemModel(startF: restriction.endInterval, endF: timeMax.endInterval, column: timeMax.columnIndex!, limitInterval: timeMax.limit, rule: timeMax.rule) newScheduleItems.append(timeMax) } else if restriction.startInterval > timeMax.startInterval && restriction.endInterval < timeMax.endInterval { //we have a total overlap, make 2 new time maxes let timeMax1 = ScheduleItemModel(startF: timeMax.startInterval, endF: restriction.startInterval, column: timeMax.columnIndex!, limitInterval: timeMax.limit, rule: timeMax.rule) let timeMax2 = ScheduleItemModel(startF: restriction.endInterval, endF: timeMax.endInterval, column: timeMax.columnIndex!, limitInterval: timeMax.limit, rule: timeMax.rule) newScheduleItems.append(timeMax1) newScheduleItems.append(timeMax2) } else if restriction.endInterval >= timeMax.endInterval { timeMax = ScheduleItemModel(startF: timeMax.startInterval, endF: restriction.startInterval, column: timeMax.columnIndex!, limitInterval: timeMax.limit, rule: timeMax.rule) newScheduleItems.append(timeMax) } } } else { newScheduleItems.append(scheduleItem) } } } //in the first steps we removed the snow restrictions, now let's add them back, un-processed! if respectDoNotProcess { newScheduleItems += scheduleItems.filter({ (scheduleItem: ScheduleItemModel) -> Bool in return scheduleItem.shouldNotProcess }) } return newScheduleItems } } class ScheduleItemModel { var startInterval: CGFloat var endInterval: CGFloat var limit: NSTimeInterval var heightMultiplier: CGFloat? var yIndexMultiplier: CGFloat? var columnIndex: Int? var timeLimitText: String? var rule: ParkingRule var shouldNotProcess: Bool { return self.rule.ruleType == ParkingRuleType.SnowRestriction } init () { startInterval = 0 endInterval = 0 limit = 0 rule = ParkingRule(ruleType: ParkingRuleType.Free) } init (startF : CGFloat, endF : CGFloat, column : Int, limitInterval: NSTimeInterval, rule: ParkingRule) { self.rule = rule startInterval = startF endInterval = endF limit = limitInterval columnIndex = column heightMultiplier = (endF - startF) / 3600 yIndexMultiplier = startF / 3600 if (limit > 0) { let limitMinutes = Int(limit / 60) timeLimitText = String(NSString(format: "%01ld",limitMinutes)) } } func setMinimumHeight() { if heightMultiplier < 4 && ((startInterval / 3600) > 20 || (endInterval / 3600) > 20) { return // enable the lines below if we ever fix the labels displaying correctly // yIndexMultiplier = (endInterval / 3600) - 4 // heightMultiplier = 4 } if heightMultiplier < 4 { heightMultiplier = 4 } } func isLongerThan(otherScheduleItem: ScheduleItemModel) -> Bool { let myInterval = endInterval - startInterval let otherInterval = otherScheduleItem.endInterval - otherScheduleItem.startInterval return myInterval > otherInterval } func topOffset() -> CGFloat { let maxInterval: CGFloat = 24 let interval = startInterval / 3600 let offset = interval/maxInterval return offset } func bottomOffset() -> CGFloat { let maxInterval: CGFloat = 24 let interval = endInterval / 3600 let offset = interval/maxInterval return offset } private func offset() -> CGFloat { return 0 } /* ---(May be useful in the future)--- We are going to manipulate the data here to draw things in 6 hour periods. There are only 4 slots: 0 to 6 = 0 to 21600 6 to 12 = 21600 to 43200 12 to 18 = 43200 to 64800 18 to 24 = 64800 to 86400 */ let SIX_HOUR_BLOCK: CGFloat = 6*60*60 private func correctStartTimeToSixHourBlock(startF : CGFloat) -> CGFloat { var correctedStart: CGFloat = startF if startF < SIX_HOUR_BLOCK { correctedStart = 0 } else if startF < SIX_HOUR_BLOCK*2 { correctedStart = SIX_HOUR_BLOCK } else if startF < SIX_HOUR_BLOCK*3 { correctedStart = SIX_HOUR_BLOCK*2 } else if startF < SIX_HOUR_BLOCK*4 { correctedStart = SIX_HOUR_BLOCK*3 } return correctedStart } private func correctEndTimeToSixHourBlock(endF : CGFloat) -> CGFloat { var correctedEnd: CGFloat = endF if endF <= SIX_HOUR_BLOCK { correctedEnd = SIX_HOUR_BLOCK } else if endF <= SIX_HOUR_BLOCK*2 { correctedEnd = SIX_HOUR_BLOCK*2 } else if endF <= SIX_HOUR_BLOCK*3 { correctedEnd = SIX_HOUR_BLOCK*3 } else if endF <= SIX_HOUR_BLOCK*4 { correctedEnd = SIX_HOUR_BLOCK*4 } return correctedEnd } } class ScheduleTimeModel { var timeInterval: NSTimeInterval var heightOffsetInHours : CGFloat var yIndexMultiplier : CGFloat { get { return CGFloat(timeInterval / 3600) } } init(interval: NSTimeInterval, heightOff: CGFloat) { timeInterval = interval self.heightOffsetInHours = heightOff } init(interval: CGFloat, heightOff: CGFloat) { timeInterval = NSTimeInterval(interval) self.heightOffsetInHours = heightOff } static func getScheduleTimesFromItems(scheduleItems: [ScheduleItemModel]) -> [ScheduleTimeModel] { //maintain a list of the start and end values var allTimeValues = Set<CGFloat>() var startTimeValues = [CGFloat]() var endTimeValues = [CGFloat]() var endTimeHeightMultipliers = [CGFloat]() for scheduleItem in scheduleItems { allTimeValues.insert(scheduleItem.startInterval) allTimeValues.insert(scheduleItem.endInterval) startTimeValues.append(scheduleItem.startInterval) endTimeValues.append(scheduleItem.endInterval) endTimeHeightMultipliers.append(scheduleItem.heightMultiplier!) } return Array(allTimeValues).map { (interval: CGFloat) -> ScheduleTimeModel in if let index = endTimeValues.indexOf(interval) { let heightOffsetInHours = endTimeHeightMultipliers[index] - ((endTimeValues[index] - startTimeValues[index]) / 3600) return ScheduleTimeModel(interval: interval, heightOff: heightOffsetInHours) } return ScheduleTimeModel(interval: interval, heightOff: 0) } } }
// // CategoryDetailHeaderTableViewCell.swift // MakeChoice // // Created by 吴梦宇 on 7/20/15. // Copyright (c) 2015 ___mengyu wu___. All rights reserved. // import UIKit class CategoryDetailHeaderTableViewCell: UITableViewCell { @IBOutlet weak var postTimeLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var usericon: UIImageView! @IBOutlet weak var questionLabel: UILabel! var post: Post? { didSet{ if let post=post{ usernameLabel.text=post.poster?.username postTimeLabel.text=post.createdAt?.shortTimeAgoSinceDate(NSDate()) ?? "" questionLabel.text=post.title ?? "" var placeHolderIcon=UIImage(named:"Profile") var iconFile=post.poster?[PF_USER_PICTURE] as? PFFile if let iconFile=iconFile{ iconFile.getDataInBackgroundWithBlock{(data:NSData?, error: NSError?) -> Void in if let error = error { println("category detial header table view cell error:\(error)") } if let data = data { let image = UIImage(data:data, scale: 1.0)! self.usericon.image=image } } } DesignHelper.setCircleImage(self.usericon) } } } 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 } }
// // MagnetometerParametersViewController.swift // Calibration // // Created by Antonio on 14/01/2017. // Copyright © 2017 Adafruit. All rights reserved. // import UIKit protocol MagnetometerParametersViewControllerDelegate: AnyObject { func onParametersDone() } class MagnetometerParametersViewController: MagnetometerPageContentViewController { // Config private static let kSliderMaxDifferenceFromDefaultValue: Float = 0.1 // 1 = 100% difference // UI @IBOutlet weak var parametersStackView: UIStackView! // Data weak var parametersDelegate: MagnetometerParametersViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() for (i, view) in parametersStackView.arrangedSubviews.enumerated() { if let valueSlider = view.subviews[1] as? UISlider { var value: Float switch i { case 0: value = Calibration.kGapTarget case 1: value = Calibration.kWobbleTarget case 2: value = Calibration.kVarianceTarget default: value = Calibration.kFitErrorTarget } valueSlider.minimumValue = value - value*MagnetometerParametersViewController.kSliderMaxDifferenceFromDefaultValue valueSlider.maximumValue = value + value*MagnetometerParametersViewController.kSliderMaxDifferenceFromDefaultValue updateParametersUI() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onClickDone(_ sender: Any) { parametersDelegate?.onParametersDone() } @IBAction func onClickSetDefaults(_ sender: Any) { Preferences.magnetometerGapTarget = Calibration.kGapTarget Preferences.magnetometerVarianceTarget = Calibration.kVarianceTarget Preferences.magnetometerWobbleTarget = Calibration.kWobbleTarget Preferences.magnetometerFitErrorTarget = Calibration.kFitErrorTarget updateParametersUI() } private func updateParametersUI(shouldUpdateSliders: Bool = true) { for (i, view) in parametersStackView.arrangedSubviews.enumerated() { if let valueSlider = view.subviews[1] as? UISlider, let valueLabel = view.subviews.last as? UILabel { var value: Float switch i { case 0: value = Preferences.magnetometerGapTarget case 1: value = Preferences.magnetometerWobbleTarget case 2: value = Preferences.magnetometerVarianceTarget default: value = Preferences.magnetometerFitErrorTarget } valueSlider.value = value valueLabel.text = String(format: " <%.1f%%", value) } } } @IBAction func onSliderChanged(_ sender: UISlider) { let tag = sender.tag let value = sender.value switch tag { case 0: Preferences.magnetometerGapTarget = value case 1: Preferences.magnetometerWobbleTarget = value case 2: Preferences.magnetometerVarianceTarget = value default: Preferences.magnetometerFitErrorTarget = value } updateParametersUI(shouldUpdateSliders: false) delegate?.onMagnetometerParametersChanged() } }
// // SearchBarView.swift // Loompa // // Created by Brian Griffin on 1/17/20. // Copyright © 2020 swiftapprentice. All rights reserved. // import UIKit class SearchBarView: UIView { @IBOutlet weak var newSearchBar: UISearchBar! /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
// // UpdateDishViewController.swift // CenaNavidad // // Created by ALBERTO GURPEGUI RAMÓN on 10/1/19. // Copyright © 2019 David gimenez. All rights reserved. // import UIKit protocol UpdateDishViewControllerDelegate: class { func updateDishViewController(_ vc: UpdateDishViewController, didEditDish dish: Dish) func errorUpdateDishViewController(_ vc:UpdateDishViewController) } class UpdateDishViewController: UIViewController { @IBOutlet weak var viewpop: UIView! @IBOutlet weak var id: UILabel! @IBOutlet weak var name: UITextField! internal var repository: LocalDishRepository! weak var delegate: UpdateDishViewControllerDelegate? var dish = Dish() convenience init(dish: Dish){ self.init() self.dish = dish } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.25){ self.view.backgroundColor = UIColor.gray.withAlphaComponent(0.75) } } override func viewDidLoad() { super.viewDidLoad() id.text = dish.id name.text = dish.name viewpop.layer.cornerRadius = 8 viewpop.layer.masksToBounds = true repository = LocalDishRepository() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func updateButtonRessed() { if (repository.getCount(name: name.text!)! > 1) || (repository.get(identifier: dish.id)?.name != name.text!) || (name.text?.elementsEqual(""))! { self.delegate?.errorUpdateDishViewController(self) }else{ dish.id = id.text! dish.name = name.text! UIView.animate(withDuration: 0.25, animations: { self.view.backgroundColor = UIColor.clear }) { (bool) in if self.repository.update(a: self.dish){ self.delegate?.updateDishViewController(self, didEditDish: self.dish) } } } } @IBAction func cancelButtonRessed() { UIView.animate(withDuration: 0.25, animations: { self.view.backgroundColor = UIColor.clear }) { (bool) in self.dismiss(animated: true) } } }
// // Repository.swift // TodoList // // Created by Christian Oberdörfer on 24.03.19. // Copyright © 2019 Christian Oberdörfer. All rights reserved. // import Foundation /** The repository protocol */ protocol RepositoryProtocol: class {} typealias Repository = Component & RepositoryProtocol
// // NotificationsTableView.swift // diverCity // // Created by Lauren Shultz on 5/6/19. // Copyright © 2019 Lauren Shultz. All rights reserved. // import Foundation import UIKit class NotificationsTableView: UITableView { var itemsList: [Notification] var onNotificationSelected: (_ notification: Notification) -> () = {_ in } init(frame: CGRect, notificationsList: [Notification], notificationSelectedCallback: @escaping (_ notification: Notification) -> ()) { let style: UITableViewStyle = UITableViewStyle.plain onNotificationSelected = notificationSelectedCallback self.itemsList = notificationsList super.init(frame: frame, style: style) self.delegate = self self.dataSource = self self.register(UserTableCell.self, forCellReuseIdentifier: "notificationCell") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func reloadNotifications(notifications: [Notification]) { self.itemsList = notifications self.reloadData() } } extension NotificationsTableView: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.dequeueReusableCell(withIdentifier: "notificationCell", for: indexPath) as! NotificationTableCell cell.notificationItemView.loadPost(notification: itemsList[indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { onNotificationSelected(itemsList[indexPath.row]) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
// // InviteCell.swift // Shiso // // Created by Lucy DeLaurentis on 12/31/17. // Copyright © 2017 Micah DeLaurentis. All rights reserved. // import Foundation import UIKit //NOT BEING USED//NOT BEING USED //NOT BEING USED//NOT BEING USED //NOT BEING USED//NOT BEING USED class GameDisplayCell: UITableViewCell { var gameView = UIView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) gameView.frame = CGRect(x: 2 , y: 2, width: 30, height: 30) gameView.layer.borderWidth = 1.0 gameView.layer.borderColor = UIColor.red.cgColor addSubview(gameView) self.layer.borderColor = UIColor.black.cgColor self.layer.borderWidth = 1.0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // MedicineViewController.swift // szenzormodalitasok // // Created by Tóth Zoltán on 2021. 05. 08.. // Copyright © 2021. Tóth Zoltán. All rights reserved. // // Imports import UIKit // Medicines page - UIViewController class MedicinesViewController: UIViewController, ProvidingInjecting, UITableViewDelegate { // Args struct struct Args { var pageSource: PageSource } // Variables var args = Args(pageSource: .medicines) private(set) lazy var medicineProvier: MedicineProviding = { medicineInject(pageSource: args.pageSource) }() private(set) lazy var favouriteProvider: FavouriteProviding = { favouriteInject() }() private var filterString: String? // IB Outlets @IBOutlet weak var medicineSearchBar: UISearchBar! @IBOutlet weak var medicineQrCodeReaderButton: UIButton! @IBOutlet weak var medicineTableView: UITableView! // For grouped list variables var medicinesDictionary = [String: [MedicineModel]]() var sectionLetters = [String]() var medicines = [MedicineModel]() // viewDidLoad method override func viewDidLoad() { super.viewDidLoad() if navigationController is FavouritesNavigationController { args.pageSource = .favourites } controller.start(with: args.pageSource) self.dismissKey() medicineSearchBar.delegate = self medicineSearchBar.enablesReturnKeyAutomatically = true medicineSearchBar.placeholder = NSLocalizedString("medicinesTab.searchBar.placeholder.text", comment: "") medicineSearchBar.searchTextField.backgroundColor = Colors.appBlue medicineSearchBar.searchTextField.textColor = .white medicineSearchBar.searchTextField.tintColor = .white medicineSearchBar.image(for: .search, state: .normal) medicineTableView.sectionIndexBackgroundColor = .white medicineTableView.backgroundColor = .white medicineTableView.tintColor = .red medicineTableView.dataSource = self medicineTableView.delegate = self } func selectionCalculator(medicines: [MedicineModel]) { medicinesDictionary = [ : ] for medicineItem in medicines { let medicineKey = String(medicineItem.medicineName.prefix(1)) if var medicineValues = medicinesDictionary[medicineKey] { medicineValues.append(medicineItem) medicinesDictionary[medicineKey] = medicineValues } else { medicinesDictionary[medicineKey] = [medicineItem] } } sectionLetters = medicinesDictionary.keys.sorted() } func calculateDisplayingModel() { selectionCalculator(medicines: medicines.filter{ self.filterString == nil ? true : $0.medicineName.uppercased().starts(with: self.filterString!.uppercased())}) if sectionLetters.count == 1 { let key = sectionLetters[0] if medicinesDictionary[key]?.count == 1 { performSegue(withIdentifier: "showMedicineDetailFromMedicines", sender: medicinesDictionary[key]?[0]) } } } } //MARK: - MedicinesViewController - #1 Extension: Hide keyboard extension MedicinesViewController { func dismissKey() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MedicinesViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } //MARK: - UISearchBarDelegate extension MedicinesViewController: UISearchBarDelegate { // run when user choose a letter from keyboard -> searchText changed func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filterString = searchText.isEmpty ? nil : searchText calculateDisplayingModel() medicineTableView.reloadData() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { medicineSearchBar.resignFirstResponder() } }
// // Sorting.swift // LeetCode-Solutions // // Created by Vishal Patel on 9/10/17. // Copyright © 2017 Vishal Patel. All rights reserved. // import Foundation // QuickSort func swap( a:inout [Int], p: Int , q:Int ) { let t = a[p] a[p] = a[q] a[q] = t } func partition( a:inout [Int], p:Int, q:Int ) -> Int { var k = p let n = q for i in p..<n { // choose last element as pivote // if current element is smaller than last // exchange curren with counter // increment counter & current if a[i] <= a[n] { swap(a: &a, p: i, q: k) k = k + 1 } } // swap last element with counter // Fix last elemnt's position in array. swap(a: &a, p: n , q: k) return k // return the position } func quickSort( a:inout [Int], p: Int, q:Int ) { if ( p > q ) { return } let n = partition(a: &a, p: p, q: q) quickSort(a: &a, p: p , q: n-1) quickSort(a: &a, p: n+1 , q: q) } // MergeSort //---------------------------------------------------------- func mergeSortWorker(a: inout [Int], l : Int, m: Int, r: Int ){ let n1 = m - l + 1 let n2 = r - m var L:[Int] = [Int](repeatElement(0, count: n1)) var R:[Int] = [Int](repeatElement(0, count: n2)) for i in 0..<n1 { L[i] = a[l+i] } for j in 0..<n2 { R[j] = a[m+1+j] } var i = 0 var j = 0 var k = l // Imp: Don't forget you want to only update elements between provided range. while ( i < n1 && j < n2 ) { if ( L[i] <= R[j] ){ a[k] = L[i] i = i + 1 } else { a[k] = R[j] j = j + 1 } k = k + 1 // keep moving index pointer for main array } while ( i < n1 ) { a[k] = L[i] i = i + 1 k = k + 1 } while ( j < n2 ) { a[k] = R[j] j = j + 1 k = k + 1 } } func mergeSort( a: inout [Int], l: Int , r:Int ){ if ( l < r ) { let m = (l+r)/2 mergeSort(a: &a , l: l, r: m) mergeSort(a: &a , l: m+1, r: r) mergeSortWorker(a: &a , l: l , m: m , r: r) } }
// // UserInfoManager.swift // se_iOS_client // // Created by syon on 2021/05/22. // import UIKit import Alamofire struct UserInfoKey { static let loginId = "ID" } class UserInfoManager { let ud = UserDefaults.standard var loginId: String? { get { return UserDefaults.standard.string(forKey: UserInfoKey.loginId) } set (v) { let ud = UserDefaults.standard ud.set(v, forKey: UserInfoKey.loginId) ud.synchronize() } } var myAccountId: Int? { get{ return UserDefaults.standard.integer(forKey: "accountId") } set (v) { let ud = UserDefaults.standard ud.set(v, forKey: "accountId") ud.synchronize() } } func login(id: String, pw: String, success: (()->Void)? = nil, fail: ((String)->Void)? = nil) { //API 호출 let url = "http://swagger.se-testboard.duckdns.org/api/v1/signin" let param: Parameters = [ "id": id, "pw": pw ] //API 호출 결과 처리 let call = AF.request(url, method: .post, parameters: param, encoding: JSONEncoding.default) call.responseJSON { res in let result = try! res.result.get() guard let jsonObject = result as? NSDictionary else { fail?("오류:\(result)") return } if jsonObject["status"] is Int{ let resultCode = jsonObject["status"] as! Int if resultCode == 200 { self.ud.set(id, forKey: "loginId") print(self.ud.string(forKey: "loginId")!) let temp = jsonObject["data"] as? NSDictionary let accessToken = temp?.value(forKey: "token") as! String let tk = TokenUtils() tk.save("kit.cs.ailab.syonKim.se-iOS-client", account: "accessToken", value: accessToken) //AccessToken 잘 왔나 확인 if let accessToken = tk.load("kit.cs.ailab.syonKim.se-iOS-client", account: "accessToken") { print("accessToken = \(accessToken)") } else { print("accessToken is nil") } success?() } else { let msg = (jsonObject["message"] as? String) ?? "로그인 실패" fail?(msg) } } } } func getMyAcoount(success: (()->Void)? = nil, fail: ((String)->Void)? = nil) { //self.indicatorView.startAnimating() let url = "http://swagger.se-testboard.duckdns.org/api/v1/account/my" let tokenUtils = TokenUtils() let header = tokenUtils.getAuthorizationHeader() let call = AF.request(url, encoding: JSONEncoding.default, headers: header) call.responseJSON { res in let result = try! res.result.get() guard let jsonObject = result as? NSDictionary else { fail?("오류:\(result)") return } if jsonObject["status"] is Int { let resultCode = jsonObject["status"] as! Int if resultCode == 200 { print("status 부르기 성공") //var temp: NSDictionary! = nil let temp = jsonObject["data"] as? NSDictionary if let accountId = temp?.value(forKey: "accountId") as? Int { self.ud.set(accountId, forKey: "accountId") print("accountId 부르기 성공") print(accountId) } } success?() } else { let msg = (jsonObject["message"] as? String) ?? "개인정보 불러오기 실패" fail?(msg) } } //self.indicatorView.stopAnimating() } }
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// This class implements the _org.antlr.v4.runtime.misc.IntSet_ backed by a sorted array of /// non-overlapping intervals. It is particularly efficient for representing /// large collections of numbers, where the majority of elements appear as part /// of a sequential range of numbers that are all part of the set. For example, /// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }. /// /// /// This class is able to represent sets containing any combination of values in /// the range _Integer#MIN_VALUE_ to _Integer#MAX_VALUE_ /// (inclusive). /// public class IntervalSet: IntSet, Hashable, CustomStringConvertible { public static let COMPLETE_CHAR_SET: IntervalSet = { let set = IntervalSet.of(Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE) set.makeReadonly() return set }() public static let EMPTY_SET: IntervalSet = { let set = IntervalSet() set.makeReadonly() return set }() /// /// The list of sorted, disjoint intervals. /// internal var intervals: [Interval] internal var readonly = false public init(_ intervals: [Interval]) { self.intervals = intervals } public convenience init(_ set: IntervalSet) { self.init() try! addAll(set) } public init(_ els: Int...) { if els.isEmpty { intervals = [Interval]() // most sets are 1 or 2 elements } else { intervals = [Interval]() for e in els { try! add(e) } } } /// /// Create a set with all ints within range [a..b] (inclusive) /// public static func of(_ a: Int, _ b: Int) -> IntervalSet { let s = IntervalSet() try! s.add(a, b) return s } public func clear() throws { if readonly { throw ANTLRError.illegalState(msg: "can't alter readonly IntervalSet") } intervals.removeAll() } /// /// Add a single element to the set. An isolated element is stored /// as a range el..el. /// public func add(_ el: Int) throws { if readonly { throw ANTLRError.illegalState(msg: "can't alter readonly IntervalSet") } try! add(el, el) } /// /// Add interval; i.e., add all integers from a to b to set. /// If b&lt;a, do nothing. /// Keep list in sorted order (by left range value). /// If overlap, combine ranges. For example, /// If this is {1..5, 10..20}, adding 6..7 yields /// {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}. /// public func add(_ a: Int, _ b: Int) throws { try add(Interval.of(a, b)) } // copy on write so we can cache a..a intervals and sets of that internal func add(_ addition: Interval) throws { if readonly { throw ANTLRError.illegalState(msg: "can't alter readonly IntervalSet") } if addition.b < addition.a { return } // find position in list // Use iterators as we modify list in place var i = 0 while i < intervals.count { let r = intervals[i] if addition == r { return } if addition.adjacent(r) || !addition.disjoint(r) { // next to each other, make a single larger interval let bigger = addition.union(r) //iter.set(bigger); intervals[i] = bigger // make sure we didn't just create an interval that // should be merged with next interval in list while i < intervals.count - 1 { i += 1 let next = intervals[i] if !bigger.adjacent(next) && bigger.disjoint(next) { break } // if we bump up against or overlap next, merge /// /// iter.remove(); // remove this one /// iter.previous(); // move backwards to what we just set /// iter.set(bigger.union(next)); // set to 3 merged ones /// iter.next(); // first call to next after previous duplicates the resul /// intervals.remove(at: i) i -= 1 intervals[i] = bigger.union(next) } return } if addition.startsBeforeDisjoint(r) { // insert before r intervals.insert(addition, at: i) return } // if disjoint and after r, a future iteration will handle it i += 1 } // ok, must be after last interval (and disjoint from last interval) // just add it intervals.append(addition) } /// /// combine all sets in the array returned the or'd value /// public func or(_ sets: [IntervalSet]) -> IntSet { let r = IntervalSet() for s in sets { try! r.addAll(s) } return r } @discardableResult public func addAll(_ set: IntSet?) throws -> IntSet { guard let set = set else { return self } if let other = set as? IntervalSet { // walk set and add each interval for interval in other.intervals { try add(interval) } } else { let setList = set.toList() for value in setList { try add(value) } } return self } public func complement(_ minElement: Int, _ maxElement: Int) -> IntSet? { return complement(IntervalSet.of(minElement, maxElement)) } /// /// /// public func complement(_ vocabulary: IntSet?) -> IntSet? { guard let vocabulary = vocabulary, !vocabulary.isNil() else { return nil // nothing in common with null set } var vocabularyIS: IntervalSet if let vocabulary = vocabulary as? IntervalSet { vocabularyIS = vocabulary } else { vocabularyIS = IntervalSet() try! vocabularyIS.addAll(vocabulary) } return vocabularyIS.subtract(self) } public func subtract(_ a: IntSet?) -> IntSet { guard let a = a, !a.isNil() else { return IntervalSet(self) } if let a = a as? IntervalSet { return subtract(self, a) } let other = IntervalSet() try! other.addAll(a) return subtract(self, other) } /// /// Compute the set difference between two interval sets. The specific /// operation is `left - right`. If either of the input sets is /// `null`, it is treated as though it was an empty set. /// public func subtract(_ left: IntervalSet?, _ right: IntervalSet?) -> IntervalSet { guard let left = left, !left.isNil() else { return IntervalSet() } let result = IntervalSet(left) guard let right = right, !right.isNil() else { // right set has no elements; just return the copy of the current set return result } var resultI = 0 var rightI = 0 while resultI < result.intervals.count && rightI < right.intervals.count { let resultInterval = result.intervals[resultI] let rightInterval = right.intervals[rightI] // operation: (resultInterval - rightInterval) and update indexes if rightInterval.b < resultInterval.a { rightI += 1 continue } if rightInterval.a > resultInterval.b { resultI += 1 continue } var beforeCurrent: Interval? = nil var afterCurrent: Interval? = nil if rightInterval.a > resultInterval.a { beforeCurrent = Interval(resultInterval.a, rightInterval.a - 1) } if rightInterval.b < resultInterval.b { afterCurrent = Interval(rightInterval.b + 1, resultInterval.b) } if let beforeCurrent = beforeCurrent { if let afterCurrent = afterCurrent { // split the current interval into two result.intervals[resultI] = beforeCurrent result.intervals.insert(afterCurrent, at: resultI + 1) resultI += 1 rightI += 1 continue } else { // replace the current interval result.intervals[resultI] = beforeCurrent resultI += 1 continue } } else { if let afterCurrent = afterCurrent { // replace the current interval result.intervals[resultI] = afterCurrent rightI += 1 continue } else { // remove the current interval (thus no need to increment resultI) result.intervals.remove(at: resultI) //result.intervals.remove(resultI); continue } } } // If rightI reached right.intervals.size(), no more intervals to subtract from result. // If resultI reached result.intervals.size(), we would be subtracting from an empty set. // Either way, we are done. return result } public func or(_ a: IntSet) -> IntSet { let o = IntervalSet() try! o.addAll(self) try! o.addAll(a) return o } /// /// /// public func and(_ other: IntSet?) -> IntSet? { if other == nil { return nil // nothing in common with null set } let myIntervals = self.intervals let theirIntervals = (other as! IntervalSet).intervals var intersection: IntervalSet? = nil let mySize = myIntervals.count let theirSize = theirIntervals.count var i = 0 var j = 0 // iterate down both interval lists looking for nondisjoint intervals while i < mySize && j < theirSize { let mine = myIntervals[i] let theirs = theirIntervals[j] if mine.startsBeforeDisjoint(theirs) { // move this iterator looking for interval that might overlap i += 1 } else { if theirs.startsBeforeDisjoint(mine) { // move other iterator looking for interval that might overlap j += 1 } else { if mine.properlyContains(theirs) { // overlap, add intersection, get next theirs if intersection == nil { intersection = IntervalSet() } try! intersection!.add(mine.intersection(theirs)) j += 1 } else { if theirs.properlyContains(mine) { // overlap, add intersection, get next mine if intersection == nil { intersection = IntervalSet() } try! intersection!.add(mine.intersection(theirs)) i += 1 } else { if !mine.disjoint(theirs) { // overlap, add intersection if intersection == nil { intersection = IntervalSet() } try! intersection!.add(mine.intersection(theirs)) // Move the iterator of lower range [a..b], but not // the upper range as it may contain elements that will collide // with the next iterator. So, if mine=[0..115] and // theirs=[115..200], then intersection is 115 and move mine // but not theirs as theirs may collide with the next range // in thisIter. // move both iterators to next ranges if mine.startsAfterNonDisjoint(theirs) { j += 1 } else { if theirs.startsAfterNonDisjoint(mine) { i += 1 } } } } } } } } if intersection == nil { return IntervalSet() } return intersection } /// /// /// public func contains(_ el: Int) -> Bool { for interval in intervals { let a = interval.a let b = interval.b if el < a { break // list is sorted and el is before this interval; not here } if el >= a && el <= b { return true // found in this interval } } return false } /// /// /// public func isNil() -> Bool { return intervals.isEmpty } /// /// /// public func getSingleElement() -> Int { if intervals.count == 1 { let interval = intervals[0] if interval.a == interval.b { return interval.a } } return CommonToken.INVALID_TYPE } /// /// Returns the maximum value contained in the set. /// /// - returns: the maximum value contained in the set. If the set is empty, this /// method returns _org.antlr.v4.runtime.Token#INVALID_TYPE_. /// public func getMaxElement() -> Int { if isNil() { return CommonToken.INVALID_TYPE } let last = intervals[intervals.count - 1] return last.b } /// /// Returns the minimum value contained in the set. /// /// - returns: the minimum value contained in the set. If the set is empty, this /// method returns _org.antlr.v4.runtime.Token#INVALID_TYPE_. /// public func getMinElement() -> Int { if isNil() { return CommonToken.INVALID_TYPE } return intervals[0].a } /// /// Return a list of Interval objects. /// public func getIntervals() -> [Interval] { return intervals } public func hash(into hasher: inout Hasher) { for interval in intervals { hasher.combine(interval.a) hasher.combine(interval.b) } } /// /// Are two IntervalSets equal? Because all intervals are sorted /// and disjoint, equals is a simple linear walk over both lists /// to make sure they are the same. Interval.equals() is used /// by the List.equals() method to check the ranges. /// /// /// public func equals(obj : AnyObject) -> Bool { /// if ( obj==nil || !(obj is IntervalSet) ) { /// return false; /// } /// var other : IntervalSet = obj as! IntervalSet; /// return self.intervals.equals(other.intervals); /// public var description: String { return toString(false) } public func toString(_ elemAreChar: Bool) -> String { if intervals.isEmpty { return "{}" } let selfSize = size() var buf = "" if selfSize > 1 { buf += "{" } var first = true for interval in intervals { if !first { buf += ", " } first = false let a = interval.a let b = interval.b if a == b { if a == CommonToken.EOF { buf += "<EOF>" } else if elemAreChar { buf += "'\(a)'" } else { buf += "\(a)" } } else if elemAreChar { buf += "'\(a)'..'\(b)'" } else { buf += "\(a)..\(b)" } } if selfSize > 1 { buf += "}" } return buf } public func toString(_ vocabulary: Vocabulary) -> String { if intervals.isEmpty { return "{}" } let selfSize = size() var buf = "" if selfSize > 1 { buf += "{" } var first = true for interval in intervals { if !first { buf += ", " } first = false let a = interval.a let b = interval.b if a == b { buf += elementName(vocabulary, a) } else { for i in a...b { if i > a { buf += ", " } buf += elementName(vocabulary, i) } } } if selfSize > 1 { buf += "}" } return buf } internal func elementName(_ vocabulary: Vocabulary, _ a: Int) -> String { if a == CommonToken.EOF { return "<EOF>" } else if a == CommonToken.EPSILON { return "<EPSILON>" } else { return vocabulary.getDisplayName(a) } } public func size() -> Int { var n = 0 for interval in intervals { n += (interval.b - interval.a + 1) } return n } public func toList() -> [Int] { var values = [Int]() for interval in intervals { let a = interval.a let b = interval.b values.append(contentsOf: a...b) } return values } public func toSet() -> Set<Int> { var s = Set<Int>() for interval in intervals { let a = interval.a let b = interval.b for v in a...b { s.insert(v) } } return s } /// /// Get the ith element of ordered set. Used only by RandomPhrase so /// don't bother to implement if you're not doing that for a new /// ANTLR code gen target. /// public func get(_ i: Int) -> Int { var index = 0 for interval in intervals { let a = interval.a let b = interval.b for v in a...b { if index == i { return v } index += 1 } } return -1 } public func remove(_ el: Int) throws { if readonly { throw ANTLRError.illegalState(msg: "can't alter readonly IntervalSet") } var idx = intervals.startIndex while idx < intervals.endIndex { defer { intervals.formIndex(after: &idx) } var interval: Interval { get { return intervals[idx] } set { intervals[idx] = newValue } } let a = interval.a let b = interval.b if el < a { break // list is sorted and el is before this interval; not here } // if whole interval x..x, rm if el == a && el == b { intervals.remove(at: idx) break } // if on left edge x..b, adjust left if el == a { interval.a += 1 break } // if on right edge a..x, adjust right if el == b { interval.b -= 1 break } // if in middle a..x..b, split interval if el > a && el < b { // found in this interval let oldb = interval.b interval.b = el - 1 // [a..x-1] try add(el + 1, oldb) // add [x+1..b] } } } public func isReadonly() -> Bool { return readonly } public func makeReadonly() { readonly = true } } public func ==(lhs: IntervalSet, rhs: IntervalSet) -> Bool { return lhs.intervals == rhs.intervals }
import UIKit func primeString(_ s: String) -> Bool { let newString = Set(s) // for num in s { // if let matching = newString[Set(s)] { // // } // } // var letters = Array(s) // var count = 0 // for letter in letters { // if letter == newString { // count += 1 // } // } //if count % 2 // var // var words = s.components(separatedBy: " ") // var wordcount = [String: Int]() // for word in words { // wordcount.updateValue(Int(s,word), forKey: word) // } //return wordcount // var words = s.components(separatedBy: " ") // var anotherStr = String(newString) // var twoStr = "u" // var count = 0 // for thing in words { // if thing == twoStr { // count += 1 // print(count) // } // } // print(count) var dict: [Character: Int] = [:] for (index, char) in s.enumerated() { if dict[char] != nil { return false } dict[char] = index } return true } primeString("abcabcabcabc") primeString("utdutdtdutd") primeString("a") primeString("abcd")
// // PokeCell.swift // pokedex // // Created by Nixon Lee on 30/8/2016. // Copyright © 2016 Nixon. All rights reserved. // import UIKit class PokeCell: UICollectionViewCell { @IBOutlet weak var thumbImg: UIImageView! @IBOutlet weak var nameLbl: UILabel! var pokemon: Pokemon func configureCell(pokemon: Pokemon) { self.pokemon = pokemon thumbImg.image = UIImage(named: "\(pokemon.pokedexId)") nameLbl.text = pokemon.name } }
// // UIView+.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 02. 25.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import UIKit extension UIView { //MARK: blur func addBlurEffect() { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] blurEffectView.alpha = 0.8 self.addSubview(blurEffectView) } //MARK: drag drop func getSnapshotView() -> UIView { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() let snapshot : UIView = UIImageView(image: image) snapshot.layer.masksToBounds = false snapshot.layer.cornerRadius = 0.0 snapshot.setAppShadow() return snapshot } func isDragDropEnter(superView: UIView, gestureRecognizer: UIGestureRecognizer) -> Bool { return self.frame.contains(gestureRecognizer.location(in: superView)) } //MARK: shadow func setAppShadow() { layer.shadowOffset = CGSize(width: 2.0, height: 1.0) layer.shadowRadius = 2.0 layer.shadowOpacity = 0.4 layer.masksToBounds = false clipsToBounds = false } //MARK: border func showAppBorder() { layer.borderWidth = dashboardDividerWidth layer.borderColor = Colors.colorDashBoardDivider.cgColor } //MARK: gradient func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) -> Void { self.layer.addSublayer(getGradient(withColours: colours, gradientOrientation: orientation)) } func getGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) -> CAGradientLayer { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = self.bounds gradient.colors = colours.map { $0.cgColor } gradient.startPoint = orientation.startPoint gradient.endPoint = orientation.endPoint return gradient } } //MARK: gradient helper typealias GradientPoints = (startPoint: CGPoint, endPoint: CGPoint) enum GradientOrientation { case topRightBottomLeft case topLeftBottomRight case horizontal case vertical case verticalPortrait case verticalLandscape var startPoint : CGPoint { get { return points.startPoint } } var endPoint : CGPoint { get { return points.endPoint } } var points : GradientPoints { get { switch(self) { case .topRightBottomLeft: return (CGPoint.init(x: 0.0,y: 1.0), CGPoint.init(x: 1.0,y: 0.0)) case .topLeftBottomRight: return (CGPoint.init(x: 0.0,y: 0.0), CGPoint.init(x: 1,y: 1)) case .horizontal: return (CGPoint.init(x: 0.0,y: 0.5), CGPoint.init(x: 1.0,y: 0.5)) case .vertical: return (CGPoint.init(x: 0.0,y: 0.0), CGPoint.init(x: 0.0,y: 1.0)) case .verticalPortrait: return (CGPoint.init(x: 0.0,y: 0.25), CGPoint.init(x: 0.0,y: 0.45)) case .verticalLandscape: return (CGPoint.init(x: 0.0,y: 0.25), CGPoint.init(x: 0.0,y: 0.60)) } } } }
// // NewsModel.swift // NYTimes_Test // // Created by Руслан Кукса on 26.09.2019. // Copyright © 2019 Руслан Кукса. All rights reserved. // import Foundation struct NewsModel { let title: String let description: String let url: String let id: Int64 init(title: String, description: String, url: String, id: Int64) { self.title = title self.description = description self.url = url self.id = id } }
// // BusinessCollectionCell.swift // CrushAndLovelyCodingTest // // Created by Kervins Valcourt on 1/3/17. // Copyright © 2017 Crush and Lovely. All rights reserved. // import UIKit class BusinessCollectionCell: UICollectionViewCell { private var cellDivider: UIView var businessImage: UIImageView var titleLabel: UILabel override init (frame: CGRect) { cellDivider = UIView() cellDivider.translatesAutoresizingMaskIntoConstraints = false cellDivider.backgroundColor = UIColor.gray cellDivider.alpha = 0.5 businessImage = UIImageView() businessImage.translatesAutoresizingMaskIntoConstraints = false businessImage.backgroundColor = UIColor.gray businessImage.layer.cornerRadius = 3 titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.textColor = UIColor.gray titleLabel.text = "" super.init(frame: frame) backgroundColor = UIColor.white addSubview(cellDivider) addSubview(businessImage) addSubview(titleLabel) setupLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupLayout() { cellDivider.snp.makeConstraints { view in view.left.equalToSuperview() view.right.equalToSuperview() view.top.equalToSuperview() view.height.equalTo(0.7) } businessImage.snp.makeConstraints { view in view.left.equalTo(snp.left).offset(10.0) view.centerY.equalTo(snp.centerY) view.width.equalTo(50.0) view.height.equalTo(50.0) } titleLabel.snp.makeConstraints { view in view.bottom.equalTo(snp.centerY) view.left.equalTo(businessImage.snp.right).offset(10) view.right.equalToSuperview().offset(-42) } } }
// // UIView+Animation.swift // https://github.com/xinyzhao/ZXToolboxSwift // // Copyright (c) 2019-2020 Zhao Xin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public extension UIView { enum AnimateType { case bounce // 弹跳效果 case fade // 渐显渐隐 case top // 从顶部进入 case bottom // 从下部进入 case left // 从左边进入 case right // 从右边进入 } /// 显示view /// - Parameters: /// - from: 动画类型 /// - duration: 动画时间 func animate(from: AnimateType, duration: TimeInterval = 0.3) { let view = self if !view.isHidden { return } view.layer.removeAllAnimations() switch from { case .bounce: view.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) view.isHidden = false UIView.animateKeyframes(withDuration: duration, delay: 0, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) { view.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) } UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) { view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) } }) { (finished) in if finished { view.transform = CGAffineTransform.identity } } break case .fade: view.alpha = 0.0 view.isHidden = false UIView.animate(withDuration: duration, animations: { view.alpha = 1.0 }) { (finished) in if finished { view.alpha = 1.0 } } break default: var transform = view.transform switch from { case .top: transform = CGAffineTransform(translationX: 0, y: -view.frame.height) break case .bottom: transform = CGAffineTransform(translationX: 0, y: view.frame.height) break case .left: transform = CGAffineTransform(translationX: -view.frame.width, y: 0) break case .right: transform = CGAffineTransform(translationX: view.frame.width, y: 0) break default: break } view.transform = transform view.isHidden = false UIView.animate(withDuration: duration, animations: { view.transform = CGAffineTransform.identity }) { (finished) in if finished { view.transform = CGAffineTransform.identity } } break } } /// 隐藏view /// - Parameters: /// - from: 动画类型 /// - duration: 动画时间 func animate(to: AnimateType, duration: TimeInterval = 0.3) { let view = self if view.isHidden { return } view.layer.removeAllAnimations() switch to { case .bounce: UIView.animateKeyframes(withDuration: duration, delay: 0, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) { view.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) } UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) { view.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) } }) { (finished) in if finished { view.isHidden = true } } break case .fade: UIView.animate(withDuration: duration, animations: { view.alpha = 0.0 }) { (finished) in if finished { view.isHidden = true } } break default: var transform = view.transform switch to { case .top: transform = CGAffineTransform(translationX: 0, y: -view.frame.height) break case .bottom: transform = CGAffineTransform(translationX: 0, y: view.frame.height) break case .left: transform = CGAffineTransform(translationX: -view.frame.width, y: 0) break case .right: transform = CGAffineTransform(translationX: view.frame.width, y: 0) break default: break } UIView.animate(withDuration: duration, animations: { view.transform = transform }) { (finished) in if finished { view.isHidden = true } } break } } }
// // FranciumTests.swift // FranciumTests // // Created by Bas van Kuijck on 13/07/2018. // Copyright © 2018 E-sites. All rights reserved. // import XCTest @testable import Francium class FranciumTests: XCTestCase { override func setUp() { super.setUp() } private func _createTestDirectory() { } func testFile() { let file = File(path: "somenewfile.txt") XCTAssertEqual(file.isExisting, false) XCTAssertEqual(file.basename, "somenewfile.txt") XCTAssertEqual(file.name, "somenewfile") XCTAssertEqual(file.extensionName, "txt") XCTAssertNil(file.creationDate) XCTAssertNil(file.modificationDate) } func testDir() { let dir = Dir(path: "./") XCTAssertEqual(dir.isExisting, true) XCTAssertEqual(dir.isDirectory, true) XCTAssertNotNil(dir.creationDate) XCTAssertNotNil(dir.modificationDate) } func testCreation() { do { let dir = try Dir.create(path: "./SomeNewDirectory") XCTAssertNotNil(dir.creationDate) XCTAssertEqual(dir.permissions, 0o0777) XCTAssertEqual(dir.basename, "SomeNewDirectory") let file = try File.create(path: "./SomeNewDirectory/somenewfile.txt") XCTAssertEqual(file.permissions, 0o0777) XCTAssertNotNil(file.creationDate) XCTAssertEqual(file.basename, "somenewfile.txt") try file.write(string: "Some information") XCTAssertEqual(file.contents, "Some information") XCTAssertEqual(dir.glob("*").count, 1) XCTAssertEqual(dir.glob("some*").count, 1) XCTAssertEqual(dir.glob("*.txt").count, 1) XCTAssertEqual(dir.glob("*.md").count, 0) try file.delete() try dir.delete() } catch let error { XCTAssert(false, "\(error)") } } func testEmpty() { do { let dir = try Dir.create(path: "./SomeNewDirectory") let file = try File.create(path: "./SomeNewDirectory/somenewfile.txt") try dir.empty() XCTAssertEqual(dir.glob("*").count, 0) XCTAssertEqual(file.isExisting, false) try dir.delete() } catch let error { XCTAssert(false, "\(error)") } } func testAppend() { do { let file = try File.create(path: "./somenewfile.txt") try file.write(string: "Some information") XCTAssertEqual(file.contents, "Some information") try file.append(string: ">>>") XCTAssertEqual(file.contents, "Some information>>>") try file.delete() } catch let error { XCTAssert(false, "\(error)") } } }
// // ResturantDetailViewModel.swift // YelpMVVm // // Created by Dala on 8/29/21. // import UIKit class ResturantDetailViewModel { var business: Businesses! var name: String! var distance: Double! var rating: Double! var address: String! var phone: String! var phoneDisplay: String! var access: Bool! var location: Location! var addressText: String! var ratingText: String! var distanceText: String! var nameText: String! var phoneText: String! var accessText: String! init(business: Businesses) { self.business = business self.name = business.name self.distance = business.distance self.rating = business.rating self.address = business.location?.address1 self.phone = business.phone self.phoneDisplay = business.display_phone self.location = business.location nameText = name ?? "N//A" distanceText = "Distance: \(String(distance))" ratingText = "Rating: \(String(rating))" addressText = "Address: \(String(describing: address))" phoneText = "Phone: \(String(phone))" accessText = access ? "Is Closed" : "Is Open" } }
// // frenchKeyboardLayout.swift // KeyboardKit // // Created by Valentin Shergin on 3/31/16. // Copyright © 2016 AnchorFree. All rights reserved. // import Foundation public let frenchKeyboardLayout = frenchAzertyKeyboardLayout
// // webviewcontroller.swift // remoteios // // Created by Hasanul Isyraf on 21/07/2017. // Copyright © 2017 Hasanul Isyraf. All rights reserved. // import UIKit class webviewcontroller: UIViewController,UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var menutable: UITableView! @IBOutlet weak var webview: UIWebView! var menushowing = false @IBOutlet weak var leadingconstraint: NSLayoutConstraint! var parameters = ["building" : "" , "stopdate" : "", "migrationdate" : "", "targetcabinet" : "" , "oldcabinet" : "" , "state" : "", "sitename" : "" ] let arraydatasources = ["Aging","Summary","List TT","Schedule"] override func viewDidLoad() { super.viewDidLoad() AppUtility.lockOrientation(.landscapeLeft) webview.isUserInteractionEnabled = true webview.scalesPageToFit = true webview.scrollView.isScrollEnabled = true if(!menushowing){ leadingconstraint.constant = -140 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) menushowing = !menushowing } print(parameters) let urlComp = NSURLComponents(string: "http://58.27.84.166/mcconline/MCC%20Online%20V3/ipmsan_android_graph4.php")! var items = [URLQueryItem]() for (key,value) in parameters { items.append(URLQueryItem(name: key, value: value)) } items = items.filter{!$0.name.isEmpty} if !items.isEmpty { urlComp.queryItems = items } var urlRequest = URLRequest(url: urlComp.url!) urlRequest.httpMethod = "GET" self.navigationItem.title = "Graph Trend" webview.loadRequest(urlRequest) webview.delegate = self menutable.delegate = self } private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscapeLeft } private func shouldAutorotate() -> Bool { return true } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arraydatasources.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "menugraphcell", for: indexPath) as! menugraphcell cell.item.text = arraydatasources[indexPath.item] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { menutable.layer.opacity = 5 menutable.layer.shadowRadius = 10 let textselected = arraydatasources[indexPath.item] if(textselected=="Summary"){ let webVc = UIStoryboard(name:"Main",bundle:nil).instantiateViewController(withIdentifier: "summary1") as! ViewController navigationController?.pushViewController(webVc, animated: true) } if(textselected=="List TT"){ let myVC = storyboard?.instantiateViewController(withIdentifier: "listtt") print(textselected) navigationController?.pushViewController(myVC!, animated: true) } if(textselected=="Aging"){ let myVC = storyboard?.instantiateViewController(withIdentifier: "agingview") as! agingviewcontroller print(textselected) navigationController?.pushViewController(myVC, animated: true) } if(textselected=="Schedule"){ let myVC = storyboard?.instantiateViewController(withIdentifier: "scheduleview") as! scheduleviewcontroller print(textselected) navigationController?.pushViewController(myVC, animated: true) } } @IBAction func openmenu(_ sender: Any) { if(menushowing){ leadingconstraint.constant = -140 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) } else{ leadingconstraint.constant = 0 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) } menushowing = !menushowing } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Don't forget to reset when view is being removed AppUtility.lockOrientation(.all) } }
// // Places+CoreDataProperties.swift // // // Created by Dave on 5/20/21. // // import Foundation import CoreData extension Places { @nonobjc public class func fetchRequest() -> NSFetchRequest<Places> { return NSFetchRequest<Places>(entityName: "Places") } @NSManaged public var url: String? @NSManaged public var detail: String? @NSManaged public var titile: String? }
// // FitBitManager.swift // HealthSync // // Created by Girish Chaudhari on 11/22/15. // Copyright © 2015 SwiftStudio. All rights reserved. // import Foundation import Alamofire import OAuthSwift class FitBitManager { let BASE_AUTH_URL = "https://www.fitbit.com/oauth2/authorize?" let BASE_RESOURCE_URL = "https://api.fitbit.com/1/user/-" let scopes = "activity profile weight" let walking_activity_id = "90013" // FitBit walking activity id let running_activity_id = "90009" // FitBit running activity id var fitbitProfile: FitBitUserProfile? let OK = 200 func doFitBitOAuth(completion: (result: AnyObject) -> Void){ let authorizeURL = BASE_AUTH_URL+"client_id=" + (FitBitCredentials.sharedInstance.fitBitValueForKey("clientID")!) let scope = scopes.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) let oauthswift = OAuth2Swift( consumerKey: FitBitCredentials.sharedInstance.fitBitValueForKey("consumerKey")!, consumerSecret: FitBitCredentials.sharedInstance.fitBitValueForKey("consumerSecret")!, authorizeUrl: authorizeURL, responseType: "code" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "healthsync://oauth")!, scope: scope!, state:"", success: { (credential, response, parameters) -> Void in }, failure: {(error:NSError!) -> Void in print(error.localizedDescription) }) completion(result: "doFitBitOAuth") } func getAuthInformation(url: NSURL, completion:() -> Void) { let clientID = FitBitCredentials.sharedInstance.fitBitValueForKey("clientID") let code = (url.query!).characters.split{$0 == "="}.map(String.init) var parameter = Dictionary<String, AnyObject>() var headers = Dictionary<String, String>() headers["Authorization"] = "Basic MjI5UjZWOjFlNDkzOGVlMzA3ZDk4MmI2NWFmYmQyZGYwYTU1ZDBi" headers["Content-Type"] = "application/x-www-form-urlencoded" parameter["grant_type"] = "authorization_code" parameter["client_id"] = clientID parameter["redirect_uri"] = "healthsync://oauth" parameter["code"] = code[1] let fitbit_token_url = "https://api.fitbit.com/oauth2/token?"; Alamofire.request(.POST, fitbit_token_url,parameters: parameter, headers:headers).responseJSON{ response in guard response.result.error == nil else { return } if let value: AnyObject = response.result.value { let jsonObject = value as! NSDictionary if let accessToken = jsonObject["access_token"] { FitBitCredentials.sharedInstance.setFitbitValue((accessToken as? String)!, withKey: "accessToken") FitBitCredentials.sharedInstance.setFitbitValue(String(jsonObject["expires_in"]!), withKey: "expiresIn") let refreshToken = String(jsonObject["refresh_token"]!) FitBitCredentials.sharedInstance.setFitbitValue(refreshToken, withKey: "refreshToken") } } completion() } } func getProfileData(completion:(result:AnyObject?)->Void) { refereshRequest({(refreshToken, accessToken) -> Void in let fitbit_profile_url = self.BASE_RESOURCE_URL+"/profile.json" let header = ["Authorization":"Bearer " + accessToken] Alamofire.request(.GET, fitbit_profile_url,headers:header).responseJSON{ response in let statusCode = response.response?.statusCode guard statusCode == self.OK else{ completion(result:nil) return } if let result: AnyObject = response.result.value { let jsonObject = result as! NSDictionary let user = jsonObject["user"]! let age = user["age"]!?.integerValue let avatar_url = (user["avatar150"]! as! String) let fullName = (user["fullName"]! as! String) let gender = (user["gender"]! as! String) let height = user["height"]!?.doubleValue let weight = user["weight"]!?.doubleValue self.fitbitProfile = FitBitUserProfile(age: age!, avatar_url: avatar_url, fullName: fullName, gender: gender, height: height!, weight: weight!) completion(result:self.fitbitProfile!) } } }) } func refereshRequest(completion: (refreshToken: String, accessToken: String) -> Void) { let _refreshToken:URLStringConvertible = FitBitCredentials.sharedInstance.fitBitValueForKey("refreshToken")! let refreshTokenURL = "https://api.fitbit.com/oauth2/token?grant_type=refresh_token&refresh_token=\(_refreshToken)" var headers = Dictionary<String, String>() headers["Authorization"] = "Basic MjI5UjZWOjFlNDkzOGVlMzA3ZDk4MmI2NWFmYmQyZGYwYTU1ZDBi" headers["Content-Type"] = "application/x-www-form-urlencoded" let parameters = Dictionary<String, AnyObject>() Alamofire.request(.POST, refreshTokenURL, parameters: parameters, headers:headers).responseJSON{ response in guard response.result.error == nil else { print(response.result.error!) return } if let value: AnyObject = response.result.value { let jsonObject = value as! NSDictionary if let errorFound = jsonObject["errors"] { let errorType = errorFound as! NSArray let error = (errorType[0]["errorType"]) if error != nil && (error! as! String) == "invalid_grant" { if(isConnectedToNetwork()){ let fbManager = FitBitManager() fbManager.doFitBitOAuth({(result) -> Void in }) }else{ showAlertView("No Internet Access", message: "Please Connect to Internet and try again later.", view: self) } } } if let newAccessToken = jsonObject["access_token"] { let newRefreshToken = jsonObject["refresh_token"] FitBitCredentials.sharedInstance.setFitbitValue((newAccessToken as! String), withKey: "accessToken") FitBitCredentials.sharedInstance.setFitbitValue((newRefreshToken as! String), withKey: "refreshToken") completion(refreshToken: (newRefreshToken as! String), accessToken: (newAccessToken as! String)) } } } } func getFitbitSteps(completion:(result:Int?)->Void){ refereshRequest({(refreshToken, accessToken) -> Void in let fitbit_activity_steps_url = self.BASE_RESOURCE_URL+"/activities/steps/date/today/1d.json" let header = ["Authorization":"Bearer " + accessToken] Alamofire.request(.GET, fitbit_activity_steps_url,headers:header).responseJSON{ response in let statusCode = response.response?.statusCode guard statusCode == self.OK else{ completion(result:nil) return } if let result: AnyObject = response.result.value { let jsonObject = result as! NSDictionary let activitySteps = jsonObject["activities-steps"]! let activityArray = activitySteps as! NSArray let activity = activityArray[0] as! NSDictionary let steps = activity["value"]?.integerValue completion(result:steps) } } }) } func syncStepsWithFitbit(steps:Int,syncSource:String, completion:(result:AnyObject?)->Void){ refereshRequest({(refreshToken, accessToken) -> Void in let fitbit_activity_url = self.BASE_RESOURCE_URL+"/activities.json"; let header = ["Authorization":"Bearer " + accessToken] var parameter = Dictionary<String, AnyObject>() let durationMillis = self.getApproximateActivityTime(steps) let startTime = self.getStartTime() let activityDate = self.getActivityDate() let calories = self.getCalories(steps) parameter["activityId"] = self.walking_activity_id parameter["startTime"] = startTime parameter["durationMillis"] = durationMillis parameter["date"] = activityDate parameter["distance"] = steps parameter["manualCalories"]=calories parameter["distanceUnit"] = "Steps" Alamofire.request(.POST, fitbit_activity_url,parameters: parameter,headers:header).responseJSON{response in let statusCode = response.response?.statusCode guard statusCode == 201 else{ completion(result:nil) return } if let _ = response.result.value { completion(result: "success") let logger = SyncLogger.sharedInstance logger.storeSyncLogs(syncSource, steps: steps) } }}) } private func getCalories(steps:Int)->Int{ return Int(Double(steps) * 0.05) // steps to calories conversion 1 Cal/ 20 steps } private func getApproximateActivityTime(steps:Int)-> Int { return Int(steps*500); // approx 2 steps per sec } private func getStartTime()->String{ let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm:ss" return dateFormatter.stringFromDate(NSDate()) } private func getActivityDate()->String{ let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.stringFromDate(NSDate()) } }
// // MyInterestRecordViewController.swift // Sohulc // // Created by 李博武 on 2018/10/10. // Copyright © 2018年 linjing. All rights reserved. // import UIKit import KeychainSwift class MyInterestRecordViewController: UIViewController { //将用户敏感信息存入keychain let KeyChain = KeychainSwift.init(keyPrefix: "my_") let identifierCell = "interestRecordCell" @IBOutlet weak var mainView: UIView! @IBOutlet weak var navView: UIView! @IBOutlet weak var navViewHeight: NSLayoutConstraint! @IBOutlet weak var tableWrpView: UIView! @IBOutlet weak var tableView: UITableView! var user_apr:String = "0"//当前加息 var expired_list:[JSON] = []///已过期加息记录 var no_expire_list:[JSON] = []//未过期加息记录 override func viewDidLoad() { super.viewDidLoad() //iphoneX及有刘海的机型 if #available(iOS 11.0, *) { if (screenH >= 812) { navHeight = Int(UIApplication.shared.statusBarFrame.height) + 44 } } self.view.layoutIfNeeded() self.view.setNeedsLayout() setupLayout() self.view.layer.contents = UIImage(named: "my_interest_record_bg")?.cgImage self.view.contentMode = .scaleToFill addShadow(targetView: tableWrpView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //自定义导航栏按钮 let leftBarBtn = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: self, action: #selector(backToPrevious)) leftBarBtn.image = UIImage(named: "nav_back") self.navigationItem.leftBarButtonItem = leftBarBtn self.navigationItem.title = "加息明细" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension MyInterestRecordViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = UIColor.white let iconImg = UIImageView() iconImg.image = section == 0 ? UIImage(named: "my_interest_record_icon1") : UIImage(named: "my_interest_record_icon") let desLabel = UILabel() desLabel.text = section == 0 ? "当前加息\(user_apr)%" : "已过期" desLabel.textColor = UIColor(red: 188/255, green: 125/255, blue: 68/255, alpha: 1) desLabel.font = UIFont.systemFont(ofSize: 16.0) headerView.addSubview(iconImg) headerView.addSubview(desLabel) if section != 0 { let lineView = UIView(frame: CGRect(x: 2, y: 300, width: screenW-40, height: 1)) headerView.addSubview(lineView) lineView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(0) make.left.equalToSuperview().offset(10) make.right.equalToSuperview().offset(-10) make.height.equalTo(1) } drawDashLine(lineView: lineView, lineLength: 2, lineSpacing: 5, lineColor: UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 153/255)) } iconImg.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(10) make.centerY.equalToSuperview().offset(5) } desLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImg.snp.right).offset(10) make.centerY.equalToSuperview().offset(5) } return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return screenW*0.11 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return screenW*0.09 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? self.no_expire_list.count : self.expired_list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifierCell, for: indexPath) as! MyInterestRecordCell if indexPath.section == 0 { cell.configureWithBasic(apr: self.no_expire_list[indexPath.row]["apr"].doubleValue, sorce_title: self.no_expire_list[indexPath.row]["source_title"].stringValue, expire_time: self.no_expire_list[indexPath.row]["expire_time"].stringValue) }else{ cell.configureWithBasic(apr: self.expired_list[indexPath.row]["apr"].doubleValue, sorce_title: self.expired_list[indexPath.row]["source_title"].stringValue, expire_time: self.expired_list[indexPath.row]["expire_time"].stringValue) } cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } } extension MyInterestRecordViewController { fileprivate func setupLayout() { if self.navViewHeight != nil { navView.removeConstraint(self.navViewHeight) navView.snp.remakeConstraints { (make) in make.height.equalTo(CGFloat(navHeight)) } } } func addShadow(targetView: UIView) { targetView.layer.shadowColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.8).cgColor targetView.layer.shadowOpacity = 0.4 targetView.layer.shadowRadius = 3 //zero表示不偏移 targetView.layer.shadowOffset = CGSize.zero targetView.clipsToBounds = false } func drawDashLine(lineView : UIView,lineLength : Int ,lineSpacing : Int,lineColor : UIColor){ let shapeLayer = CAShapeLayer() shapeLayer.bounds = lineView.bounds // 只要是CALayer这种类型,他的anchorPoint默认都是(0.5,0.5) shapeLayer.anchorPoint = CGPoint(x: 0, y: 0) // shapeLayer.fillColor = UIColor.blue.cgColor shapeLayer.strokeColor = lineColor.cgColor shapeLayer.lineWidth = lineView.frame.size.height shapeLayer.lineJoin = kCALineJoinRound shapeLayer.lineDashPattern = [NSNumber(value: lineLength),NSNumber(value: lineSpacing)] let path = CGMutablePath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: lineView.frame.size.width, y: 0)) shapeLayer.path = path lineView.layer.addSublayer(shapeLayer) } @objc func backToPrevious() { self.navigationController?.popViewController(animated: true) } }
// Playground - noun: a place where people can play import UIKit // not tested func minimunCandies(ratings: [Int]) -> Int { var increment = [Int]() var inc = 1 for i in 1..<ratings.count { if ratings[i]>ratings[i-1] { increment[i] = max(inc++, increment[i]) } else { inc = 1 } } inc = 1 for i in 2..<ratings.count { var i = ratings.count-i if ratings[i]>ratings[i+1] { increment[i] = max(inc++, increment[i]) } else { inc = 1 } } return increment.reduce(0, combine: +) } /*: There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: • Each child must have at least one candy. • Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? */
// // HttpImage.swift // StoryReader // // Created by 020-YinTao on 2017/3/14. // Copyright © 2017年 020-YinTao. All rights reserved. // import Foundation import Kingfisher extension UIImageView { final func setImage(_ url: String?, _ type: ImageStrategy = .original, cacheFolder folder: KingfisherCacheFolder? = .canClear, forTransitionOptions transition: KingfisherOptionsInfoItem? = .transition(.fade(0.2)), forOption options: KingfisherOptionsInfo = [.cacheMemoryOnly]) { guard let turl: String = url else { PrintLog("图片地址为空!!!") image = type.placeholder return } // let dealURL = ImageCacheCenter.shared.imageURL(turl, type: type) if let memoryCache = ImageCacheCenter.shared.image(forKey: turl) { image = memoryCache return } if ValidateNum.URL(turl).isRight == false { return } if type != .userIcon { var _options = [KingfisherOptionsInfoItem]() if let _folder = folder { _options.append(.targetCache(ImageCacheCenter.shared.kingfisherCache(_folder))) }else { _options.append(contentsOf: options) } if let t = transition { _options.append(t) } _options.append(contentsOf: [.backgroundDecode]) kf_setImage(turl, type, _options) }else { kf_setImage(turl, type, nil) } } private func kf_setImage(_ url: String, _ type: ImageStrategy, _ options: KingfisherOptionsInfo?) { kf.setImage(with: URL(string: url), placeholder: type.placeholder, options: options, progressBlock: { (current, totle) in // PrintLog("当前进度 \(current), 总进度 \(totle)") }) { (image, error, cacheType, url) in if type != .userIcon { if let _image = image, let _url = url { KingfisherManager.shared.cache.store(_image, forKey: _url.absoluteString, toDisk: false) }else { PrintLog("图片加载出错:\(error)") } } } } final func downImage(url: String?) { guard let imageURL = url, let aURL = URL.init(string: imageURL) else { return } if let memoryCache = ImageCacheCenter.shared.image(forKey: imageURL) { image = memoryCache return } ImageDownloader.default.downloadImage(with: aURL, retrieveImageTask: nil, options: [.cacheMemoryOnly], progressBlock: { (receivedData, totalData) in }) { [weak self] (image, error, url, data) in if let _image = image, let _url = url { self?.image = image KingfisherManager.shared.cache.store(_image, forKey: _url.absoluteString, toDisk: false) } } } } extension UIButton { final func setImage(_ url: String?, _ type: ImageStrategy = .original, isBgImage: Bool = false, cacheFolder folder: KingfisherCacheFolder? = .canClear, forTransitionOptions transition: KingfisherOptionsInfoItem? = .transition(.fade(0.2)), forOption options: KingfisherOptionsInfo = [.cacheMemoryOnly]) { guard let turl: String = url else { PrintLog("图片地址为空!!!") if isBgImage { setBackgroundImage(type.placeholder, for: .normal) }else { setImage(type.placeholder, for: .normal) } return } let dealURL = ImageCacheCenter.shared.imageURL(turl, type: type) if let memoryCache = ImageCacheCenter.shared.image(forKey: dealURL) { if isBgImage { setBackgroundImage(memoryCache, for: .normal) }else { setImage(memoryCache, for: .normal) } return } if ValidateNum.URL(dealURL).isRight == false { return } if type != .userIcon { var _options = [KingfisherOptionsInfoItem]() if let _folder = folder { _options.append(.targetCache(ImageCacheCenter.shared.kingfisherCache(_folder))) }else { _options.append(contentsOf: options) } if let t = transition { _options.append(t) } _options.append(contentsOf: [.backgroundDecode]) kf_setImage(dealURL, isBgImage: isBgImage, type, _options) }else { kf_setImage(dealURL, isBgImage: isBgImage, type, nil) } } private func kf_setImage(_ url: String, isBgImage: Bool, _ type: ImageStrategy, _ options: KingfisherOptionsInfo?) { if isBgImage { kf.setBackgroundImage(with: URL(string: ImageCacheCenter.shared.imageURL(url, type: type)), for: .normal, placeholder: type.placeholder, options: options, progressBlock: { (current, totle) in // PrintLog("当前进度 \(current), 总进度 \(totle)") }) { (image, error, cacheType, url) in if type != .userIcon { if let _image = image, let _url = url { KingfisherManager.shared.cache.store(_image, forKey: _url.absoluteString, toDisk: false) } } } }else { kf.setImage(with: URL(string: ImageCacheCenter.shared.imageURL(url, type: type)), for: .normal, placeholder: type.placeholder, options: options, progressBlock: { (current, totle) in // PrintLog("当前进度 \(current), 总进度 \(totle)") }) { (image, error, cacheType, url) in if type != .userIcon { if let _image = image, let _url = url { KingfisherManager.shared.cache.store(_image, forKey: _url.absoluteString, toDisk: false) } } } } } }
// // UIView+Message305.swift // Message305 // // Created by Roberto Guzman on 7/1/19. // Copyright © 2019 Fortytwo Sports. All rights reserved. // import Foundation import UIKit extension UIView { //MARK: Layout Constraints //Adds constraints to a specific UIView relative to other UIViews. //Function handles the safeareaspaces introduced in iOS 11. func addConstraintsWithFormat(isVC: Bool = false, format: String, views: UIView...) { var viewsDictionary = [String: UIView]() for (index, view) in views.enumerated() { let key = "v\(index)" view.translatesAutoresizingMaskIntoConstraints = false viewsDictionary[key] = view } @available(iOS 11.0, *) func filterFormat(_ format: inout String) { guard let window = UIApplication.shared.keyWindow else { return } let newInsets = isVC ? window.safeAreaInsets as UIEdgeInsets : self.safeAreaInsets as UIEdgeInsets let leftMargin = newInsets.left > 0 ? newInsets.left : 0 let rightMargin = newInsets.right > 0 ? newInsets.right : 0 let topMargin = newInsets.top > 0 ? newInsets.top : 0 let bottomMargin = newInsets.bottom > 0 ? newInsets.bottom : 0 //left & top margins guard let colonIndex = format.firstIndex(of: ":") else { return } let charAfterColonIndex = format.index(after: colonIndex) if format[charAfterColonIndex] == "|" { guard let firstBracketIndex = format.firstIndex(of: "[") else { return } let stuckToWall: Bool = format[format.index(after: charAfterColonIndex)] == "[" ? true : false if stuckToWall { let extraMargin: Int = String(format.first ?? Character("")) == "H" ? Int(leftMargin) : Int(topMargin) format.insert(contentsOf: "-\(extraMargin)-", at: format.index(after: charAfterColonIndex)) } else { let rangeIndexOfMeasurements: ClosedRange<String.Index> = format.index(after: charAfterColonIndex)...format.index(before: firstBracketIndex) var measurements: String = stuckToWall ? "" : String(format[rangeIndexOfMeasurements]) measurements = measurements.replacingOccurrences(of: "-", with: "") if let number = NumberFormatter().number(from: measurements) { let extraMargin: Int = String(format.first ?? Character("")) == "H" ? Int(truncating: number) + Int(leftMargin) : (Int(truncating: number)) + Int(topMargin) format.replaceSubrange(rangeIndexOfMeasurements, with: "-\(extraMargin)-") } } } //right & bottom margins let lastIndex = format.index(before: format.endIndex) if format[lastIndex] == "|" { guard let lastBracketIndex = format.lastIndex(of: "]"), let lastIndex = format.lastIndex(of: "|") else { return } let stuckToWall: Bool = lastBracketIndex.utf16Offset(in: format) == (lastIndex.utf16Offset(in: format) - 1) ? true : false if stuckToWall { let extraMargin: Int = String(format.first ?? Character("")) == "H" ? Int(rightMargin) : Int(bottomMargin) format.insert(contentsOf: "-\(extraMargin)-", at: format.index(after: lastBracketIndex)) } else { let rangeIndexOfMeasurements: ClosedRange<String.Index> = format.index(after: lastBracketIndex)...format.index(before: lastIndex) var measurements: String = String(format[rangeIndexOfMeasurements]) measurements = measurements.replacingOccurrences(of: "-", with: "") if let number = NumberFormatter().number(from: measurements) { let extraMargin: Int = String(format.first ?? Character("")) == "H" ? Int(truncating: number) + Int(rightMargin) : Int(truncating: number) + Int(bottomMargin) format.replaceSubrange(rangeIndexOfMeasurements, with: "-\(extraMargin)-") } } } } var format: String = format if #available(iOS 11.0, *) { filterFormat(&format) } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDictionary)) } func removeAllConstraints() { for constraint in constraints { removeConstraint(constraint) } } //MARK: Corners & Shadows func roundCornersWithLayer(radius: CGFloat) { layer.roundCorners(radius: radius) } func addShadowWithLayer(color: UIColor = .black, opacity: Float = 0.2, offSet: CGSize = .zero, radius: CGFloat = 10) { layer.addShadow(color: color, opacity: opacity, offSet: offSet, radius: radius) } }
// // Constants.swift // DiaryIt // // Created by Rinni Swift on 10/16/18. // Copyright © 2018 Rinni Swift. All rights reserved. // import Foundation import UIKit extension UIColor { static let lightPinkMainColor = UIColor(red:0.98, green:0.78, blue:0.83, alpha:1.0) static let lightPurpleMainColor = UIColor(red:0.59, green:0.59, blue:0.94, alpha:1.0) static let brightWhite = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0) static let darkWhite = UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0) // text for the dates in the month and dates outside the month static let darkWhiteText = UIColor(red:0.97, green:0.97, blue:0.97, alpha:0.45) static let whiteText = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0) }
// // Game.swift // FizzBuzz // // Created by Daniel Zhang on 22/01/2016. // Copyright © 2016 Daniel Zhang. All rights reserved. // import UIKit class Game: NSObject { var score: Int let brain = Brain() override init() { score = 0 super.init() } func play(move: Move) -> (right: Bool, score: Int) { let result = brain.check(score+1) if move == result { score++ return (true,score) } else { return (false,score) } } }
// // manholeextrainfo.swift // idraw // // Created by Hasanul Isyraf on 20/04/2018. // Copyright © 2018 Hasanul Isyraf. All rights reserved. // import UIKit import GoogleMaps import Firebase class manholeextrainfo: UIViewController { var marker : GMSMarker = GMSMarker() var manholename: String = "" var createdby: String = "" @IBOutlet weak var trespassinglabel: UILabel! @IBOutlet weak var ownerlabel: UILabel! @IBOutlet weak var checkcelcom: DLRadioButton! @IBOutlet weak var radiounknown: DLRadioButton! @IBOutlet weak var radiodeveloper: DLRadioButton! @IBOutlet weak var radiono: DLRadioButton! @IBOutlet weak var radioyes: DLRadioButton! @IBOutlet weak var checkunknown: DLRadioButton! @IBOutlet weak var checkdigi: DLRadioButton! @IBOutlet weak var checkumobile: DLRadioButton! @IBOutlet weak var checkmaxis: DLRadioButton! @IBOutlet weak var checktime: DLRadioButton! @IBOutlet weak var tmradio: DLRadioButton! @IBOutlet weak var olnoslabel: UILabel! override func viewDidLoad() { super.viewDidLoad() manholename = marker.title! createdby = marker.userData as! String checkcelcom.isMultipleSelectionEnabled = true checkunknown.isMultipleSelectionEnabled = true checkdigi.isMultipleSelectionEnabled = true checkumobile.isMultipleSelectionEnabled = true checkmaxis.isMultipleSelectionEnabled = true checktime.isMultipleSelectionEnabled = true checkcelcom.isIconSquare = true checkunknown.isIconSquare = true checkdigi.isIconSquare = true checkumobile.isIconSquare = true checkmaxis.isIconSquare = true checktime.isIconSquare = true //hide the olnos olnoslabel.isHidden = true checkcelcom.isHidden = true checkunknown.isHidden = true checkdigi.isHidden = true checkumobile.isHidden = true checkmaxis.isHidden = true checktime.isHidden = true loadcheckboxdisplay(manhole: manholename) } @IBAction func trespassyes(_ sender: DLRadioButton) { olnoslabel.isHidden = false checkcelcom.isHidden = false checkunknown.isHidden = false checkdigi.isHidden = false checkumobile.isHidden = false checkmaxis.isHidden = false checktime.isHidden = false updatefirebasetrespass(trespass: "Yes") } @IBAction func trespassno(_ sender: DLRadioButton) { olnoslabel.isHidden = true checkcelcom.isHidden = true checkunknown.isHidden = true checkdigi.isHidden = true checkumobile.isHidden = true checkmaxis.isHidden = true checktime.isHidden = true updatefirebasetrespass(trespass: "No") } func updatefirebaseowner(owner:String){ let manholename = marker.title! let currentuser:String = (FIRAuth.auth()?.currentUser?.email)! if(currentuser == createdby){ var ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.child("manholeinfo").child(manholename).child("owner").setValue(owner) updateextrainfomysql(manholeid: manholename, indicator: "owner", item: owner) } } func updatefirebasetrespass(trespass:String){ let manholename = marker.title! let currentuser:String = (FIRAuth.auth()?.currentUser?.email)! if(currentuser == createdby){ var ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.child("manholeinfo").child(manholename).child("trespass").setValue(trespass) updateextrainfomysql(manholeid: manholename, indicator: "trespass", item: trespass) } } func updatefirebaseolnos(olnos:String){ let manholename = marker.title! let currentuser:String = (FIRAuth.auth()?.currentUser?.email)! if(currentuser == createdby){ var ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.child("manholeinfo").child(manholename).child("olnos").childByAutoId().setValue(olnos) updateextrainfomysql(manholeid: manholename, indicator: "olnos", item: olnos) } } func loadcheckboxdisplay(manhole:String){ let referencephotomarkerinitial = FIRDatabase.database().reference().child("manholeinfo").child(manhole) referencephotomarkerinitial.observeSingleEvent(of: .value, with: { (snapshot) in for rest2 in snapshot.children.allObjects as! [FIRDataSnapshot] {//owner,trepass,olnos level if(rest2.key == "owner"){ let ownerstr = rest2.value as! String if(ownerstr == "TM"){ self.tmradio.isSelected = true } if(ownerstr == "DEVELOPER"){ self.radiodeveloper.isSelected = true } if(ownerstr == "UNKNWON"){ self.radiounknown.isSelected = true } } if(rest2.key == "trespass") { let ownerstr = rest2.value as! String if(ownerstr == "Yes"){ self.radioyes.isSelected = true self.olnoslabel.isHidden = false self.checkcelcom.isHidden = false self.checkunknown.isHidden = false self.checkdigi.isHidden = false self.checkumobile.isHidden = false self.checkmaxis.isHidden = false self.checktime.isHidden = false } if(ownerstr == "No"){ self.radiono.isSelected = true } } //loop through the olnos child to get the value if(rest2.key == "olnos"){ for rest4 in rest2.children.allObjects as! [FIRDataSnapshot] { let olnosstr = rest4.value as! String if(olnosstr == "Celcom"){ self.checkcelcom.isMultipleSelectionEnabled = true self.checkcelcom.isSelected = true print("Celcom") } if(olnosstr == "Maxis"){ self.checkmaxis.isSelected = true } if(olnosstr == "Digi"){ self.checkdigi.isSelected = true } if(olnosstr == "Umobile"){ self.checkumobile.isMultipleSelectionEnabled = true self.checkumobile.isSelected = true } if(olnosstr == "Time"){ self.checktime.isSelected = true } if(olnosstr == "UNKNOWN"){ self.checkunknown.isSelected = true } } } } }) { (nil) in print("error firebase listner") } } func deleteolnosfirebase(manhole:String,olnos:String){ let currentuser:String = (FIRAuth.auth()?.currentUser?.email)! if(currentuser == self.createdby){ let referencephotomarkerinitial = FIRDatabase.database().reference().child("manholeinfo").child(manhole) referencephotomarkerinitial.observeSingleEvent(of: .value, with: { (snapshot) in for rest2 in snapshot.children.allObjects as! [FIRDataSnapshot] {//owner,trepass,olnos level //loop through the olnos child to get the value if(rest2.key == "olnos"){ for rest4 in rest2.children.allObjects as! [FIRDataSnapshot] { let olnosstr = rest4.value as! String let keyid = rest4.key if(olnosstr == olnos){ var ref: FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.child("manholeinfo").child(self.manholename).child("olnos").child(keyid).removeValue() } } } } }) { (nil) in print("error firebase listner") } //delete in mysql deleteolnosmysql(manholeid: manholename, indicator: "olnos", item: olnos) } } @IBAction func radioownertm(_ sender: DLRadioButton) { updatefirebaseowner(owner: "TM") } @IBAction func radioownerdeveloper(_ sender: DLRadioButton) { updatefirebaseowner(owner: "DEVELOPER") } @IBAction func radioownerunknown(_ sender: DLRadioButton) { updatefirebaseowner(owner: "UNKNOWN") } @IBAction func celcomcheckbox(_ sender: DLRadioButton) { if(checkcelcom.isSelected){ print("Celcom Check") updatefirebaseolnos(olnos: "Celcom") }else{ print("Celcom Uncheck") deleteolnosfirebase(manhole: manholename, olnos: "Celcom") } } @IBAction func timecheckbox(_ sender: DLRadioButton) { if(checktime.isSelected){ print("Time Check") updatefirebaseolnos(olnos: "Time") }else{ print("Time Uncheck") deleteolnosfirebase(manhole: manholename, olnos: "Time") } } @IBAction func maxischeckbox(_ sender: DLRadioButton) { if(checkmaxis.isSelected){ print("Maxis Check") updatefirebaseolnos(olnos: "Maxis") }else{ print("Maxis Uncheck") deleteolnosfirebase(manhole: manholename, olnos: "Maxis") } } @IBAction func umobilecheckbox(_ sender: DLRadioButton) { if(checkumobile.isSelected){ print("Umobile Check") updatefirebaseolnos(olnos: "Umobile") }else{ print("Umobile Uncheck") deleteolnosfirebase(manhole: manholename, olnos: "Umobile") } } @IBAction func digicheckbox(_ sender: DLRadioButton) { if(checkdigi.isSelected){ print("Digi Check") updatefirebaseolnos(olnos: "Digi") }else{ print("Digi Uncheck") deleteolnosfirebase(manhole: manholename, olnos: "Digi") } } @IBAction func unknowncheckbox(_ sender: DLRadioButton) { if(checkunknown.isSelected){ print("Uknown Check") updatefirebaseolnos(olnos: "UNKNOWN") }else{ print("Uknown Uncheck") deleteolnosfirebase(manhole: manholename, olnos: "UNKNOWN") } } func updateextrainfomysql(manholeid:String,indicator:String,item:String) { let parameters = ["manholeid" : manholeid , "item" : item, "indicator" : indicator, "createdby" : FIRAuth.auth()?.currentUser?.email! ?? "" ].map { "\($0)=\(String(describing: $1 ))" } let request = NSMutableURLRequest(url: NSURL(string: "http://58.27.84.188/updateextrainfo.php")! as URL) request.httpMethod = "POST" let postString = parameters.joined(separator: "&") request.httpBody = postString.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in guard error == nil && data != nil else { // check for fundamental networking error print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 { // check for http errors print("response = \(String(describing: response))") self.showToast(message: "Updated") } } task.resume() } func deleteolnosmysql(manholeid:String,indicator:String,item:String) { let parameters = ["manholeid" : manholeid , "item" : item, "indicator" : indicator, "createdby" : FIRAuth.auth()?.currentUser?.email! ?? "" ].map { "\($0)=\(String(describing: $1 ))" } let request = NSMutableURLRequest(url: NSURL(string: "http://58.27.84.188/deleteolnos.php")! as URL) request.httpMethod = "POST" let postString = parameters.joined(separator: "&") request.httpBody = postString.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in guard error == nil && data != nil else { // check for fundamental networking error print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 { // check for http errors print("response = \(String(describing: response))") self.showToast(message: "Updated") } } task.resume() } }
// // ViewController.swift // Welltech // // Created by Simon Liao on 2018/10/28. // Copyright © 2018年 Simon Liao. All rights reserved. // import UIKit import SwiftyJSON import Alamofire import AudioToolbox class ViewController: UIViewController { @IBOutlet weak var temLab: UILabel! @IBOutlet weak var goodImage: UIImageView! @IBOutlet weak var timerLab: UILabel! @IBOutlet weak var gifImage: UIImageView! func getJSON() { let url = "https://api.thingspeak.com/channels/147306/fields/2.json" Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) //print("JSON: \(json)") //取得temp值 let feeds = json["feeds"][99]["field2"].doubleValue print (feeds) //轉型 let tempData = String(format: "%.1f", feeds) //傳回Label self.temLab.text = tempData /* //取得所有值 for (key, subJson): (String, JSON) in json["feeds"] { print(key) if let field1 = subJson["field1"].string { print(field1) } } */ //計時器 var timer = NSTimer() var count = 0 func updateTime() { count += 1 self.timerLab.text = "\(count)" } let distance = feeds if distance <= 30 { //隱藏開心圖,顯示疲勞圖 self.goodImage.hidden = true //警告圖示 let loginFailWarnAlertController = UIAlertController(title: "警告", message: "距離螢幕太近!", preferredStyle: UIAlertControllerStyle.Alert) let okAlertAction = UIAlertAction(title: "矯正姿勢", style: UIAlertActionStyle.Default, handler: nil) loginFailWarnAlertController.addAction(okAlertAction) self.presentViewController(loginFailWarnAlertController, animated: true, completion: nil) //震動提示 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) //播放聲音 AudioServicesPlaySystemSound(1005) /* //時間計時開始 timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true) */ } else { //取消隱藏開心圖 self.goodImage.hidden = false //時間計時停止 timer.invalidate() count = 00 self.timerLab.text = "30" } if distance <= 0 { self.temLab.text = "Stay back!" } } case .Failure(let error): print(error) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.getJSON), userInfo: nil, repeats: true) // 設定起始頁時間 NSThread.sleepForTimeInterval(1) //輸入gif //let Gif = UIImage.gif(name: "eye_cut") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // OTMConstants.swift // OnTheMap // // Created by Jun.Yuan on 16/6/30. // Copyright © 2016年 Jun.Yuan. All rights reserved. // // MARK: - Constants extension OTMClient { // MARK: - API Constants struct Constants { // MARK: URL Components static let ApiScheme = "https" static let UdacityApiHost = "www.udacity.com" static let UdacityApiPath = "/api" static let ParseApiHost = "parse.udacity.com" static let ParseApiPath = "/parse" static let GoogleMapsApiHost = "maps.googleapis.com" static let GoogleMapsApiPath = "/maps/api" static let RobohashApiHost = "robohash.org" } // MARK: - Methods struct Methods { // MARK: Udacity API Methods static let Session = "/session" static let UserUniqueKey = "/users/{key}" // MARK: Parse API Methods static let StudentLocation = "/classes/StudentLocation" static let StudentLocationObjectId = "/classes/StudentLocation/{objectId}" // MARK: Google Maps API Methods static let GeoCode = "/geocode/json" } // MARK: - Request Header Keys struct HTTPHeaderKeys { static let ParseApplicationID = "X-Parse-Application-Id" static let ParseRESTApiKey = "X-Parse-REST-API-Key" } // MARK: - Request Header Values struct HTTPHeaderValues { static let ParseApplicationID = "QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr" static let ParseRESTApiKey = "QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY" } // MARK: - URL Keys struct URLKeys { static let UniqueKey = "{key}" static let ObjectId = "{objectId}" } // MARK: - Parameter Keys struct ParameterKeys { // MARK: Udacity Parameter Keys static let Username = "username" static let Password = "password" // MARK: Parse Parameter Keys static let Limit = "limit" static let Skip = "skip" static let Order = "order" static let Where = "where" // MARK: Google Maps GeoCode Parameter Keys static let Latlng = "latlng" static let Key = "key" static let ResultType = "result_type" static let Language = "language" // MARK: Robohash Parameter Keys static let Size = "size" } // MARK: - Parameter Values struct ParameterValues { // MARK: Parse Parameter Values static var Limit = "100" static let UniqueKeyPair = "{\"uniqueKey\":\"{key}\"}" // MARK: Google Maps GeoCode Parameter Values static let Key = "AIzaSyBNUI5NM4Nv8Ejqit5rZRwP48nWqCDipvg" static let Country = "country" static let English = "EN" // MARK: Robohash Parameter Values static let Size100 = "100x100" static let Size150 = "150x150" } // MARK: - JSON Body Keys struct JsonBodyKeys { // MARK: Udacity static let Udacity = "udacity" static let Username = "username" static let Password = "password" // MARK: Facebook static let FacebookMobile = "facebook_mobile" static let AccessToken = "access_token" // MARK: Parse static let UniqueKey = "uniqueKey" static let FirstName = "firstName" static let LastName = "lastName" static let MapString = "mapString" static let MediaURL = "mediaURL" static let Latitude = "latitude" static let Longitude = "longitude" } // MARK: - JSON Response Keys struct ResponseKeys { // MARK: Udacity Authorization static let Account = "account" static let Session = "session" static let Key = "key" static let ID = "id" static let StatusCode = "status" static let Error = "error" // MARK: Udacity Public User Info static let User = "user" static let UserFirstName = "first_name" static let UserLastName = "last_name" // MARK: Parse Student Info static let CreatedAt = "createdAt" static let FirstName = "firstName" static let LastName = "lastName" static let Latitude = "latitude" static let Longitude = "longitude" static let MapString = "mapString" static let MediaURL = "mediaURL" static let ObjectId = "objectId" static let UniqueKey = "uniqueKey" static let UpdatedAt = "updatedAt" static let StudentResults = "results" // MARK: Google Maps static let ErrorMessage = "error_message" static let GeoCodeStatus = "status" static let GeoCodeResults = "results" static let AddressComponents = "address_components" static let ShortName = "short_name" } // MARK: ResponseValues struct ResponseValues { // Google Maps static let OK = "OK" static let ZeroResults = "ZERO_RESULTS" } // MARK: - URL Constants struct Urls { static let UdacitySignUpUrl = "https://www.udacity.com/account/auth#!/signup" } // MARK: - Segue Identifier struct SegueId { static let UdacityLogin = "UdacityLogin" static let FacebookLogin = "FacebookLogin" static let PushDetailView = "pushDetailView" static let PinOnMap = "pinOnMap" static let PushWebView = "pushWebView" } struct TableCellId { static let TableCell = "tableCell" static let NameCell = "nameCell" static let MapViewCell = "mapViewCell" static let UrlCell = "urlCell" } } // MARK: - Identifier extension OTMClient { // MARK:- Host Indentifier enum HostIdentifier { case Udacity case Parse case Google case Robohash } // MARK: - Login Type enum LoginType { case Udacity case Facebook } }
// // Path.swift // SailingThroughHistory // // Created by Jason Chong on 18/3/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // import UIKit /** * Model for path to store two ends of the path as well as volatiles in the path. */ class Path: Hashable, Codable { let fromNode: Node let toNode: Node var modifiers = [Volatile]() init(from fromObject: Node, to toObject: Node) { self.fromNode = fromObject self.toNode = toObject } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) fromNode = try values.decode(Node.self, forKey: .fromNode) toNode = try values.decode(Node.self, forKey: .toNode) var volatilesArrayForType = try values.nestedUnkeyedContainer(forKey: CodingKeys.modifiers) while !volatilesArrayForType.isAtEnd { let volatile = try volatilesArrayForType.nestedContainer(keyedBy: VolatileTypeKey.self) let type = try volatile.decode(VolatileTypes.self, forKey: VolatileTypeKey.type) switch type { case .volatileMonsoom: let volatile = try volatile.decode(VolatileMonsoon.self, forKey: VolatileTypeKey.volatile) modifiers.append(volatile) case .weather: let volatile = try volatile.decode(Weather.self, forKey: VolatileTypeKey.volatile) modifiers.append(volatile) } } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(fromNode, forKey: .fromNode) try container.encode(toNode, forKey: .toNode) var volatileWithType = [VolatileWithType]() for volatile in modifiers { if volatile is VolatileMonsoon { volatileWithType.append(VolatileWithType(volatile: volatile, type: VolatileTypes.volatileMonsoom)) } if volatile is Weather { volatileWithType.append(VolatileWithType(volatile: volatile, type: VolatileTypes.weather)) } } try container.encode(volatileWithType, forKey: .modifiers) } static func == (lhs: Path, rhs: Path) -> Bool { return (lhs.fromNode, lhs.toNode) == (rhs.fromNode, rhs.toNode) } func hash(into hasher: inout Hasher) { hasher.combine(fromNode) hasher.combine(toNode) } /// Compute the steps required for a player to go through the path. Influenced by volatile modifiers. func computeCostOfPath(baseCost: Double, with ship: Pirate_WeatherEntity) -> Double { var result = baseCost for modifier in modifiers { result = Double(modifier.applyVelocityModifier(to: Float(result), with: Float(ship.getWeatherModifier()))) } return result } enum CodingKeys: String, CodingKey { case fromNode case toNode case modifiers } enum VolatileTypeKey: String, CodingKey { case type case volatile } enum VolatileTypes: String, Codable { case volatileMonsoom case weather } struct VolatileWithType: Codable { var volatile: Volatile var type: VolatileTypes init(volatile: Volatile, type: VolatileTypes) { self.volatile = volatile self.type = type } } }
import ComposableArchitecture import Foundation public struct FileClient { var load: (String) -> Effect<Data?> var save: (String, Data) -> Effect<Never> } extension FileClient { public static let live = FileClient( load: { fileName -> Effect<Data?> in .sync { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let documentsUrl = URL(fileURLWithPath: documentsPath) let favoritePrimesUrl = documentsUrl.appendingPathComponent(fileName) return try? Data(contentsOf: favoritePrimesUrl) } }, save: { fileName, data in return .fireAndForget { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let documentsUrl = URL(fileURLWithPath: documentsPath) let favoritePrimesUrl = documentsUrl.appendingPathComponent(fileName) try! data.write(to: favoritePrimesUrl) } } ) }
import CNIOOpenSSL import NIOOpenSSL import Foundation /// Represents an in-memory RSA key. public struct RSAKey { // MARK: Static /// Creates a new `RSAKey` from a private key pem file. public static func `private`(pem: LosslessDataConvertible) throws -> RSAKey { return try .init(type: .private, key: .make(type: .private, from: pem.convertToData())) } /// Creates a new `RSAKey` from a public key pem file. public static func `public`(pem: LosslessDataConvertible) throws -> RSAKey { return try .init(type: .public, key: .make(type: .public, from: pem.convertToData())) } /// Creates a new `RSAKey` from a public key certificate file. public static func `public`(certificate: LosslessDataConvertible) throws -> RSAKey { return try .init(type: .public, key: .make(type: .public, from: certificate.convertToData(), x509: true)) } // MARK: Properties /// The specific RSA key type. Either public or private. /// /// Note: public keys can only verify signatures. A private key /// is required to create new signatures. public var type: RSAKeyType /// The C OpenSSL key ref. internal let c: CRSAKey // MARK: Init /// Creates a new `RSAKey` from a public or private key. internal init(type: RSAKeyType, key: CRSAKey) throws { self.type = type self.c = key } } /// Supported RSA key types. public enum RSAKeyType { /// A public RSA key. Used for verifying signatures. case `public` /// A private RSA key. Used for creating and verifying signatures. case `private` } /// Reference pointer to an OpenSSL rsa_st key. /// This wrapper is important for ensuring the key is freed when it is no longer in use. final class CRSAKey { /// The wrapped pointer. let pointer: UnsafeMutablePointer<rsa_st> /// Creates a new `CRSAKey` from a pointer. private init(_ pointer: UnsafeMutablePointer<rsa_st>) { self.pointer = pointer } /// Creates a new `CRSAKey` from type, data. Specifying `x509` true will treat the data as a certificate. static func make(type: RSAKeyType, from data: Data, x509: Bool = false) throws -> CRSAKey { let bio = BIO_new(BIO_s_mem()) defer { BIO_free(bio) } let nullTerminatedData = data + Data(bytes: [0]) _ = nullTerminatedData.withUnsafeBytes { key in return BIO_puts(bio, key) } let maybePkey: UnsafeMutablePointer<EVP_PKEY>? if x509 { guard let x509 = PEM_read_bio_X509(bio, nil, nil, nil) else { throw CryptoError.openssl(identifier: "rsax509", reason: "Key creation from certificate failed") } defer { X509_free(x509) } maybePkey = X509_get_pubkey(x509) } else { switch type { case .public: maybePkey = PEM_read_bio_PUBKEY(bio, nil, nil, nil) case .private: maybePkey = PEM_read_bio_PrivateKey(bio, nil, nil, nil) } } guard let pkey = maybePkey else { throw CryptoError.openssl(identifier: "rsaPkeyNull", reason: "RSA key creation failed") } defer { EVP_PKEY_free(pkey) } guard let rsa = EVP_PKEY_get1_RSA(pkey) else { throw CryptoError.openssl(identifier: "rsaPkeyGet1", reason: "RSA key creation failed") } return .init(rsa) } deinit { RSA_free(pointer) } }
// // UIColor+Additions.swift // Lines // // Created by Mihai Costea on 26/09/14. // Copyright (c) 2014 mcostea. All rights reserved. // import Foundation import UIKit extension UIColor { private convenience init(hex: UInt32) { let r: CGFloat = CGFloat(CGFloat((hex >> 16) & 0xFF) / CGFloat(255)) let g: CGFloat = CGFloat(CGFloat((hex >> 8) & 0xFF) / CGFloat(255)) let b: CGFloat = CGFloat(CGFloat((hex) & 0xFF) / CGFloat(255)) self.init(red: r, green: g, blue: b, alpha: 1) } class func linesWhiteColor() -> UIColor { return UIColor(hex: 0xF7F7F7) } class func linesRedColor() -> UIColor { return UIColor(hex: 0xFF1300) } class func linesGreenColor() -> UIColor { return UIColor(hex: 0x0BD318) } class func linesBlueColor() -> UIColor { return UIColor(hex: 0x007AFF) } class func linesYellowColor() -> UIColor { return UIColor(hex: 0xFFCC00) } class func linesOrangeColor() -> UIColor { return UIColor(hex: 0xFF5E3A) } class func linesGrayColor() -> UIColor { return UIColor(hex: 0xC7C7CC) } }
// // Resource.swift // Symphony // // Created by Bradley Hilton on 6/23/16. // Copyright © 2016 Brad Hilton. All rights reserved. // public protocol AnyResource : class { var status: ResultFlag { get } func refresh() func refreshIfNeeded() func unload() } open class Resource<Model : DataInitializable> : Observable<Result<Model>>, AnyResource { public let request: () -> GET<Model> open var result: Result<Model> { get { return value } set { value = newValue } } open var status: ResultFlag { return result.flag } public init(request: @escaping () -> GET<Model>) { self.request = request super.init(value: .unloaded) } open func refresh() { if let value = result.value { result = .refreshing(value) makeNetworkRequest() } else { result = .loading makeCacheRequest() makeNetworkRequest() } } open func refreshIfNeeded() { if result.flag != .refreshed { refresh() } } open func unload() { result = .unloaded } func makeCacheRequest() { request().cachePolicy(.returnCacheDataDontLoad).success(callback: cacheSuccess).begin() } func cacheSuccess(_ response: Response<Model>) { if result.flag == .loading { result = .loadedCache(response.body) } else if result.flag == .failedLoad { result = .failedRefresh(response.body) } } func makeNetworkRequest() { request().cachePolicy(.reloadIgnoringLocalCacheData).success(callback: networkSuccess).failure(callback: networkFailure).begin() } func networkSuccess(_ response: Response<Model>) { result = .refreshed(response.body) } func networkFailure(_ error: Error, request: Request) { if let error = error as? ResponseError, error.response.statusCode == 404 { return result = .deleted } guard let value = result.value else { return result = .failedLoad } result = .failedRefresh(value) } }
// // DatabaseManager.swift // ActivitiesLog // // Created by Marek Poczatek on 11.04.2017. // Copyright © 2017 Marek Poczatek. All rights reserved. // import Foundation import SQLite open class DatabaseManager { fileprivate var db: Connection init() { try! db = Connection(DatabaseManager.getDatabasePath()) } // Check if database file is exists in the phone. If no, copy and create a new one open static func installDatabase() { let fileManager = FileManager() if (!fileManager.fileExists(atPath: getDatabasePath())) { do { let bundlePath = Bundle.main.path(forResource: getDatabaseName(), ofType: "sqlite")! try fileManager.copyItem(atPath: bundlePath, toPath: getDatabasePath()) } catch let ex { print("Failed to create writable database file with unknown error: \(ex)") } } } // Get database name fileprivate static func getDatabaseName() -> String { return "database_v1.0" } // Get database fullpath fileprivate static func getDatabasePath() -> String { let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return path.appending("/\(getDatabaseName()).sqlite") } }
// // SwiftViewController.swift // Example // // Created by Yoshimasa Niwa on 2/19/20. // Copyright © 2020 Yoshimasa Niwa. All rights reserved. // import Foundation import KeyboardGuide import UIKit protocol SwiftViewControllerDelegate: AnyObject { func swiftViewControllerDidTapDone(_ swiftViewController: SwiftViewController) } class SwiftViewController: UIViewController { weak var delegate: SwiftViewControllerDelegate? init() { super.init(nibName: nil, bundle: nil) initialize() } required init?(coder: NSCoder) { super.init(coder: coder) initialize() } private func initialize() { title = "Example" let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(didTapDone(_:))) navigationItem.rightBarButtonItems = [doneBarButtonItem] } // MARK: - UIViewController private var keyboardSafeAreaLayoutGuideView: UIView? private var keyboardFrameLabel: UILabel? private var localOnlySwitch: UISwitch? private var useContentInsetsSwitch: UISwitch? private var showKeyboardSafeAreaLayoutGuideSwitch: UISwitch? private var textView: UITextView? private var textViewBottomAnchorConstraint: NSLayoutConstraint? private var spacing: CGFloat { UIFont.systemFontSize * 0.8 } override func viewDidLoad() { super.viewDidLoad() KeyboardGuide.shared.addObserver(self) if #available(iOS 13.0, *) { view.backgroundColor = UIColor.systemBackground } else { view.backgroundColor = UIColor.white } var constraints = [NSLayoutConstraint]() let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = spacing stackView.translatesAutoresizingMaskIntoConstraints = false constraints.append(contentsOf: [ stackView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: spacing), stackView.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor), stackView.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor) ]) view.addSubview(stackView) let keyboardFrameLabel = UILabel() stackView.addArrangedSubview(keyboardFrameLabel) self.keyboardFrameLabel = keyboardFrameLabel let localOnlySwitchStackView = UIStackView() localOnlySwitchStackView.axis = .horizontal localOnlySwitchStackView.spacing = spacing stackView.addArrangedSubview(localOnlySwitchStackView) let localOnlySwitchLabel = UILabel() localOnlySwitchLabel.text = "Ignore keyboard for the other app" localOnlySwitchLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) localOnlySwitchStackView.addArrangedSubview(localOnlySwitchLabel) let localOnlySwitch = UISwitch() localOnlySwitch.addTarget(self, action: #selector(localOnlySwitchDidChange(_:)), for: .valueChanged) localOnlySwitchStackView.addArrangedSubview(localOnlySwitch) self.localOnlySwitch = localOnlySwitch let useContentInsetsSwitchStackView = UIStackView() useContentInsetsSwitchStackView.axis = .horizontal useContentInsetsSwitchStackView.spacing = spacing stackView.addArrangedSubview(useContentInsetsSwitchStackView) let useContentInsetsSwitchLabel = UILabel() useContentInsetsSwitchLabel.text = "Use text view content insets" useContentInsetsSwitchLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) useContentInsetsSwitchStackView.addArrangedSubview(useContentInsetsSwitchLabel) let useContentInsetsSwitch = UISwitch() useContentInsetsSwitch.addTarget(self, action: #selector(useContentInsetsSwitchDidChange(_:)), for: .valueChanged) useContentInsetsSwitchStackView.addArrangedSubview(useContentInsetsSwitch) self.useContentInsetsSwitch = useContentInsetsSwitch let showKeyboardSafeAreaLayoutGuideSwitchStackView = UIStackView() showKeyboardSafeAreaLayoutGuideSwitchStackView.axis = .horizontal showKeyboardSafeAreaLayoutGuideSwitchStackView.spacing = spacing stackView.addArrangedSubview(showKeyboardSafeAreaLayoutGuideSwitchStackView) let showKeyboardSafeAreaLayoutGuideSwitchLabel = UILabel() showKeyboardSafeAreaLayoutGuideSwitchLabel.text = "Show keyboard safe area" showKeyboardSafeAreaLayoutGuideSwitchLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) showKeyboardSafeAreaLayoutGuideSwitchStackView.addArrangedSubview(showKeyboardSafeAreaLayoutGuideSwitchLabel) let showKeyboardSafeAreaLayoutGuideSwitch = UISwitch() showKeyboardSafeAreaLayoutGuideSwitch.addTarget(self, action: #selector(showKeyboardSafeAreaSwitchDidChange(_:)), for: .valueChanged) showKeyboardSafeAreaLayoutGuideSwitchStackView.addArrangedSubview(showKeyboardSafeAreaLayoutGuideSwitch) self.showKeyboardSafeAreaLayoutGuideSwitch = showKeyboardSafeAreaLayoutGuideSwitch let textView = UITextView() textView.font = UIFont.systemFont(ofSize: UIFont.systemFontSize * 2.0) if #available(iOS 13.0, *) { textView.backgroundColor = .secondarySystemBackground } else { textView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) } textView.text = (0..<5).map { _ in """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ }.joined() textView.layer.cornerRadius = spacing textView.textContainerInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing) textView.scrollIndicatorInsets = UIEdgeInsets(top: spacing, left: 0.0, bottom: 0.0, right: 0.0) textView.contentInsetAdjustmentBehavior = .never if #available(iOS 13.0, *) { textView.automaticallyAdjustsScrollIndicatorInsets = false } textView.translatesAutoresizingMaskIntoConstraints = false constraints.append(textView.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: spacing)) constraints.append(textView.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor)) constraints.append(textView.bottomAnchor.constraint(greaterThanOrEqualTo: textView.topAnchor)) constraints.append(textView.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor)) view.addSubview(textView) self.textView = textView let keyboardSafeAreaLayoutGuideView = UIView() keyboardSafeAreaLayoutGuideView.backgroundColor = UIColor.red.withAlphaComponent(0.2) keyboardSafeAreaLayoutGuideView.layer.borderColor = UIColor.red.cgColor keyboardSafeAreaLayoutGuideView.layer.borderWidth = 2.0 keyboardSafeAreaLayoutGuideView.isUserInteractionEnabled = false keyboardSafeAreaLayoutGuideView.translatesAutoresizingMaskIntoConstraints = false constraints.append(contentsOf: [ keyboardSafeAreaLayoutGuideView.topAnchor.constraint(equalTo: view.keyboardSafeArea.layoutGuide.topAnchor), keyboardSafeAreaLayoutGuideView.leftAnchor.constraint(equalTo: view.keyboardSafeArea.layoutGuide.leftAnchor), keyboardSafeAreaLayoutGuideView.bottomAnchor.constraint(equalTo: view.keyboardSafeArea.layoutGuide.bottomAnchor), keyboardSafeAreaLayoutGuideView.rightAnchor.constraint(equalTo: view.keyboardSafeArea.layoutGuide.rightAnchor) ]) view.addSubview(keyboardSafeAreaLayoutGuideView) self.keyboardSafeAreaLayoutGuideView = keyboardSafeAreaLayoutGuideView NSLayoutConstraint.activate(constraints) updateKeyboardFrameLabel() updateKeyboardSafeAreaIsLocalOnly() updateTextViewLayoutConstraints() updateKeyboardSafeAreaLayoutGuideView() } private func updateKeyboardFrameLabel() { let text: String if let dockedKeyboardState = KeyboardGuide.shared.dockedKeyboardState { let frame = dockedKeyboardState.frame(in: view) text = frame?.debugDescription ?? "Invalid" } else { text = "Undocked" } keyboardFrameLabel?.text = text } private func updateKeyboardSafeAreaIsLocalOnly() { guard let localOnlySwitch = localOnlySwitch else { return } view.keyboardSafeArea.isLocalOnly = localOnlySwitch.isOn } private func updateTextViewLayoutConstraints() { guard let useContentInsetsSwitch = useContentInsetsSwitch, let textView = textView else { return } if let textViewBottomAnchorConstraint = textViewBottomAnchorConstraint { textViewBottomAnchorConstraint.isActive = false self.textViewBottomAnchorConstraint = nil } let textViewBottomAnchorConstraint = useContentInsetsSwitch.isOn ? textView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -spacing) : textView.bottomAnchor.constraint(equalTo: view.keyboardSafeArea.layoutGuide.bottomAnchor, constant: -spacing) textViewBottomAnchorConstraint.priority = .defaultLow textViewBottomAnchorConstraint.isActive = true self.textViewBottomAnchorConstraint = textViewBottomAnchorConstraint updateTextViewContentsBottomInset() } private func updateKeyboardSafeAreaLayoutGuideView() { guard let showKeyboardSafeAreaLayoutGuideSwitch = showKeyboardSafeAreaLayoutGuideSwitch, let keyboardSafeAreaLayoutGuideView = keyboardSafeAreaLayoutGuideView else { return } keyboardSafeAreaLayoutGuideView.isHidden = !showKeyboardSafeAreaLayoutGuideSwitch.isOn } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateTextViewContentsBottomInset() } private func updateTextViewContentsBottomInset() { guard let useContentInsetsSwitch = useContentInsetsSwitch, let textView = textView else { return } let bottomInset = useContentInsetsSwitch.isOn ? view.keyboardSafeArea.insets.bottom : 0.0 textView.contentInset.bottom = bottomInset textView.scrollIndicatorInsets.bottom = max(spacing, bottomInset) } // MARK: - Actions @objc private func didTapDone(_ sender: AnyObject) { delegate?.swiftViewControllerDidTapDone(self) } @objc private func localOnlySwitchDidChange(_ sender: AnyObject) { updateKeyboardSafeAreaIsLocalOnly() } @objc private func useContentInsetsSwitchDidChange(_ sender: AnyObject) { updateTextViewLayoutConstraints() } @objc private func showKeyboardSafeAreaSwitchDidChange(_ sender: AnyObject) { updateKeyboardSafeAreaLayoutGuideView() } } // MARK: - KeyboardGuideObserver extension SwiftViewController: KeyboardGuideObserver { func keyboardGuide(_ keyboardGuide: KeyboardGuide, didChangeDockedKeyboardState dockedKeyboardState: KeyboardState?) { updateKeyboardFrameLabel() } }
// RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: CPU=x86_64 // XFAIL: linux protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBoundMethod2() } protocol ClassBoundBinary : class, ClassBound { func classBoundBinaryMethod(_ x: Self) } @objc protocol ObjCClassBound { func objCClassBoundMethod() } @objc protocol ObjCClassBound2 { func objCClassBoundMethod2() } protocol NotClassBound { func notClassBoundMethod() func notClassBoundBinaryMethod(_ x: Self) } struct ClassGenericFieldStruct<T:ClassBound> { var x : Int var y : T var z : Int } struct ClassProtocolFieldStruct { var x : Int var y : ClassBound var z : Int } class ClassGenericFieldClass<T:ClassBound> { final var x : Int = 0 final var y : T final var z : Int = 0 init(t: T) { y = t } } class ClassProtocolFieldClass { var x : Int = 0 var y : ClassBound var z : Int = 0 init(classBound cb: ClassBound) { y = cb } } // CHECK: %C22class_bounded_generics22ClassGenericFieldClass = type <{ %swift.refcounted, %Si, %objc_object*, %Si }> // CHECK: %V22class_bounded_generics23ClassGenericFieldStruct = type <{ %Si, %objc_object*, %Si }> // CHECK: %V22class_bounded_generics24ClassProtocolFieldStruct = type <{ %Si, %P22class_bounded_generics10ClassBound_, %Si }> // CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics23class_bounded_archetype{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype<T : ClassBound>(_ x: T) -> T { return x } class SomeClass {} class SomeSubclass : SomeClass {} // CHECK-LABEL: define hidden %C22class_bounded_generics9SomeClass* @_TF22class_bounded_generics28superclass_bounded_archetype{{.*}}(%C22class_bounded_generics9SomeClass*, %swift.type* %T) func superclass_bounded_archetype<T : SomeClass>(_ x: T) -> T { return x } // CHECK-LABEL: define hidden { %C22class_bounded_generics9SomeClass*, %C22class_bounded_generics12SomeSubclass* } @_TF22class_bounded_generics33superclass_bounded_archetype_call{{.*}}(%C22class_bounded_generics9SomeClass*, %C22class_bounded_generics12SomeSubclass*) func superclass_bounded_archetype_call(_ x: SomeClass, y: SomeSubclass) -> (SomeClass, SomeSubclass) { return (superclass_bounded_archetype(x), superclass_bounded_archetype(y)); // CHECK: [[SOMECLASS_RESULT:%.*]] = call %C22class_bounded_generics9SomeClass* @_TF22class_bounded_generics28superclass_bounded_archetype{{.*}}(%C22class_bounded_generics9SomeClass* {{%.*}}, {{.*}}) // CHECK: [[SOMESUPERCLASS_IN:%.*]] = bitcast %C22class_bounded_generics12SomeSubclass* {{%.*}} to %C22class_bounded_generics9SomeClass* // CHECK: [[SOMESUPERCLASS_RESULT:%.*]] = call %C22class_bounded_generics9SomeClass* @_TF22class_bounded_generics28superclass_bounded_archetype{{.*}}(%C22class_bounded_generics9SomeClass* [[SOMESUPERCLASS_IN]], {{.*}}) // CHECK: bitcast %C22class_bounded_generics9SomeClass* [[SOMESUPERCLASS_RESULT]] to %C22class_bounded_generics12SomeSubclass* } // CHECK-LABEL: define hidden void @_TF22class_bounded_generics30class_bounded_archetype_method{{.*}}(%objc_object*, %objc_object*, %swift.type* %T, i8** %T.ClassBoundBinary) func class_bounded_archetype_method<T : ClassBoundBinary>(_ x: T, y: T) { x.classBoundMethod() // CHECK: [[INHERITED:%.*]] = load i8*, i8** %T.ClassBoundBinary, align 8 // CHECK: [[INHERITED_WTBL:%.*]] = bitcast i8* [[INHERITED]] to i8** // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[INHERITED_WTBL]], align 8 // CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**) // CHECK: call void [[WITNESS_FUNC]](%objc_object* %0, %swift.type* {{.*}}, i8** [[INHERITED_WTBL]]) x.classBoundBinaryMethod(y) // CHECK: [[WITNESS_ENTRY:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ENTRY]], align 8 // CHECK: call void @swift_unknownRetain(%objc_object* [[Y:%.*]]) // CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %objc_object*, %swift.type*, i8**) // CHECK: call void [[WITNESS_FUNC]](%objc_object* [[Y]], %objc_object* %0, %swift.type* %T, i8** %T.ClassBoundBinary) } // CHECK-LABEL: define hidden { %objc_object*, %objc_object* } @_TF22class_bounded_generics29class_bounded_archetype_tuple{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype_tuple<T : ClassBound>(_ x: T) -> (T, T) { return (x, x) } class ConcreteClass : ClassBoundBinary, NotClassBound { func classBoundMethod() {} func classBoundBinaryMethod(_ x: ConcreteClass) {} func notClassBoundMethod() {} func notClassBoundBinaryMethod(_ x: ConcreteClass) {} } // CHECK-LABEL: define hidden %C22class_bounded_generics13ConcreteClass* @_TF22class_bounded_generics28call_class_bounded_archetype{{.*}}(%C22class_bounded_generics13ConcreteClass*) {{.*}} { func call_class_bounded_archetype(_ x: ConcreteClass) -> ConcreteClass { return class_bounded_archetype(x) // CHECK: [[IN:%.*]] = bitcast %C22class_bounded_generics13ConcreteClass* {{%.*}} to %objc_object* // CHECK: [[OUT_ORIG:%.*]] = call %objc_object* @_TF22class_bounded_generics23class_bounded_archetype{{.*}}(%objc_object* [[IN]], {{.*}}) // CHECK: [[OUT:%.*]] = bitcast %objc_object* [[OUT_ORIG]] to %C22class_bounded_generics13ConcreteClass* // CHECK: ret %C22class_bounded_generics13ConcreteClass* [[OUT]] } // CHECK: define hidden void @_TF22class_bounded_generics27not_class_bounded_archetype{{.*}}(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.NotClassBound) func not_class_bounded_archetype<T : NotClassBound>(_ x: T) -> T { return x } // CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics44class_bounded_archetype_to_not_class_bounded{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound, i8** %T.NotClassBound) {{.*}} { func class_bounded_archetype_to_not_class_bounded <T:protocol<ClassBound, NotClassBound>>(_ x:T) -> T { // CHECK: alloca %objc_object*, align 8 return not_class_bounded_archetype(x) } /* TODO Abstraction remapping to non-class-bounded witnesses func class_and_not_class_bounded_archetype_methods <T:protocol<ClassBound, NotClassBound>>(_ x:T, y:T) { x.classBoundMethod() x.classBoundBinaryMethod(y) x.notClassBoundMethod() x.notClassBoundBinaryMethod(y) } */ // CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics21class_bounded_erasure{{.*}}(%C22class_bounded_generics13ConcreteClass*) {{.*}} { func class_bounded_erasure(_ x: ConcreteClass) -> ClassBound { return x // CHECK: [[INSTANCE_OPAQUE:%.*]] = bitcast %C22class_bounded_generics13ConcreteClass* [[INSTANCE:%.*]] to %objc_object* // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* [[INSTANCE_OPAQUE]], 0 // CHECK: [[T1:%.*]] = insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @_TWPC22class_bounded_generics13ConcreteClassS_10ClassBoundS_, i32 0, i32 0), 1 // CHECK: ret { %objc_object*, i8** } [[T1]] } // CHECK-LABEL: define hidden void @_TF22class_bounded_generics29class_bounded_protocol_method{{.*}}(%objc_object*, i8**) {{.*}} { func class_bounded_protocol_method(_ x: ClassBound) { x.classBoundMethod() // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getObjectType(%objc_object* %0) // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_TABLE:%.*]], align 8 // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**) // CHECK: call void [[WITNESS_FN]](%objc_object* %0, %swift.type* [[METADATA]], i8** [[WITNESS_TABLE]]) } // CHECK-LABEL: define hidden %C22class_bounded_generics13ConcreteClass* @_TF22class_bounded_generics28class_bounded_archetype_cast{{.*}}(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype_cast<T : ClassBound>(_ x: T) -> ConcreteClass { return x as! ConcreteClass // CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8* // CHECK: [[T0:%.*]] = call %swift.type* @_TMaC22class_bounded_generics13ConcreteClass() // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8* // CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]]) // CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %C22class_bounded_generics13ConcreteClass* // CHECK: ret %C22class_bounded_generics13ConcreteClass* [[OUT]] } // CHECK-LABEL: define hidden %C22class_bounded_generics13ConcreteClass* @_TF22class_bounded_generics27class_bounded_protocol_cast{{.*}}(%objc_object*, i8**) func class_bounded_protocol_cast(_ x: ClassBound) -> ConcreteClass { return x as! ConcreteClass // CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8* // CHECK: [[T0:%.*]] = call %swift.type* @_TMaC22class_bounded_generics13ConcreteClass() // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8* // CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]]) // CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %C22class_bounded_generics13ConcreteClass* // CHECK: ret %C22class_bounded_generics13ConcreteClass* [[OUT]] } // CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics35class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**, i8**) {{.*}} { func class_bounded_protocol_conversion_1(_ x: protocol<ClassBound, ClassBound2>) -> ClassBound { return x } // CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics35class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**, i8**) {{.*}} { func class_bounded_protocol_conversion_2(_ x: protocol<ClassBound, ClassBound2>) -> ClassBound2 { return x } // CHECK-LABEL: define hidden { %objc_object*, i8** } @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**) {{.*}} { func objc_class_bounded_protocol_conversion_1 (_ x:protocol<ClassBound, ObjCClassBound>) -> ClassBound { return x } // CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*, i8**) {{.*}} { func objc_class_bounded_protocol_conversion_2 (_ x:protocol<ClassBound, ObjCClassBound>) -> ObjCClassBound { return x } // CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*) func objc_class_bounded_protocol_conversion_3 (_ x:protocol<ObjCClassBound, ObjCClassBound2>) -> ObjCClassBound { return x } // CHECK-LABEL: define hidden %objc_object* @_TF22class_bounded_generics40objc_class_bounded_protocol_conversion{{.*}}(%objc_object*) func objc_class_bounded_protocol_conversion_4 (_ x:protocol<ObjCClassBound, ObjCClassBound2>) -> ObjCClassBound2 { return x } // CHECK-LABEL: define hidden { i64, %objc_object*, i64 } @_TF22class_bounded_generics33class_generic_field_struct_fields{{.*}}(i64, %objc_object*, i64, %swift.type* %T, i8** %T.ClassBound) func class_generic_field_struct_fields<T : ClassBound> (_ x:ClassGenericFieldStruct<T>) -> (Int, T, Int) { return (x.x, x.y, x.z) } // CHECK-LABEL: define hidden void @_TF22class_bounded_generics34class_protocol_field_struct_fields{{.*}}(<{ %Si, %P22class_bounded_generics10ClassBound_, %Si }>* noalias nocapture sret, %V22class_bounded_generics24ClassProtocolFieldStruct* noalias nocapture dereferenceable({{.*}})) func class_protocol_field_struct_fields (_ x:ClassProtocolFieldStruct) -> (Int, ClassBound, Int) { return (x.x, x.y, x.z) } // CHECK-LABEL: define hidden { i64, %objc_object*, i64 } @_TF22class_bounded_generics32class_generic_field_class_fields{{.*}}(%C22class_bounded_generics22ClassGenericFieldClass*) func class_generic_field_class_fields<T : ClassBound> (_ x:ClassGenericFieldClass<T>) -> (Int, T, Int) { return (x.x, x.y, x.z) // CHECK: getelementptr inbounds %C22class_bounded_generics22ClassGenericFieldClass, %C22class_bounded_generics22ClassGenericFieldClass* %0, i32 0, i32 1 // CHECK: getelementptr inbounds %C22class_bounded_generics22ClassGenericFieldClass, %C22class_bounded_generics22ClassGenericFieldClass* %0, i32 0, i32 2 // CHECK: getelementptr inbounds %C22class_bounded_generics22ClassGenericFieldClass, %C22class_bounded_generics22ClassGenericFieldClass* %0, i32 0, i32 3 } // CHECK-LABEL: define hidden void @_TF22class_bounded_generics33class_protocol_field_class_fields{{.*}}(<{ %Si, %P22class_bounded_generics10ClassBound_, %Si }>* noalias nocapture sret, %C22class_bounded_generics23ClassProtocolFieldClass*) func class_protocol_field_class_fields(_ x: ClassProtocolFieldClass) -> (Int, ClassBound, Int) { return (x.x, x.y, x.z) // CHECK: = call i64 %{{[0-9]+}} // CHECK: = call { %objc_object*, i8** } %{{[0-9]+}} // CHECK: = call i64 %{{[0-9]+}} } class SomeSwiftClass { class func foo() {} } // T must have a Swift layout, so we can load this metatype with a direct access. // CHECK-LABEL: define hidden void @_TF22class_bounded_generics22class_bounded_metatype // CHECK: [[T0:%.*]] = getelementptr inbounds %C22class_bounded_generics14SomeSwiftClass, %C22class_bounded_generics14SomeSwiftClass* {{%.*}}, i32 0, i32 0, i32 0 // CHECK-NEXT: [[T1:%.*]] = load %swift.type*, %swift.type** [[T0]], align 8 // CHECK-NEXT: [[T2:%.*]] = bitcast %swift.type* [[T1]] to void (%swift.type*)** // CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds void (%swift.type*)*, void (%swift.type*)** [[T2]], i64 10 // CHECK-NEXT: load void (%swift.type*)*, void (%swift.type*)** [[T3]], align 8 func class_bounded_metatype<T: SomeSwiftClass>(_ t : T) { t.dynamicType.foo() } class WeakRef<T: AnyObject> { weak var value: T? }
// // TKScore.swift // Firebase Playground // // Created by Marcel Hagmann on 06.04.18. // Copyright © 2018 Marcel Hagmann. All rights reserved. // import Foundation import CloudKit struct TKScore { var scoredUserRecordID: CKRecordID var scoreValue: Int var exerciseType: TKExerciseType }
// // DexListRepositoryRemote.swift // WavesWallet-iOS // // Created by Pavel Gubin on 12/17/18. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxSwift import Moya import WavesSDK import DomainLayer import Extensions final class DexPairsPriceRepositoryRemote: DexPairsPriceRepositoryProtocol { private let environmentRepository: EnvironmentRepositoryProtocols init(environmentRepository: EnvironmentRepositoryProtocols) { self.environmentRepository = environmentRepository } func search(by accountAddress: String, searchText: String) -> Observable<[DomainLayer.DTO.Dex.SimplePair]> { var kind: DataService.Query.PairsPriceSearch.Kind! var searchCompoments = searchText.components(separatedBy: "/") if searchCompoments.count == 1 { searchCompoments = searchText.components(separatedBy: "\\") } if searchCompoments.count == 1 { let searchWords = searchCompoments[0].components(separatedBy: " ").filter {$0.count > 0} if searchWords.count > 0 { kind = .byAsset(searchWords[0]) } else { return Observable.just([]) } } else if searchCompoments.count >= 2 { let searchAmountWords = searchCompoments[0].components(separatedBy: " ").filter {$0.count > 0} let searchPriceWords = searchCompoments[1].components(separatedBy: " ").filter {$0.count > 0} if searchAmountWords.count > 0 && searchPriceWords.count > 0 { kind = .byAssets(firstName: searchAmountWords[0], secondName: searchPriceWords[0]) } else if searchAmountWords.count > 0 { kind = .byAsset(searchAmountWords[0]) } else if searchPriceWords.count > 0 { kind = .byAsset(searchPriceWords[0]) } else { return Observable.just([]) } } return environmentRepository .servicesEnvironment() .flatMap({ (servicesEnvironment) -> Observable<[DomainLayer.DTO.Dex.SimplePair]> in return servicesEnvironment .wavesServices .dataServices .pairsPriceDataService .searchByAsset(query: .init(kind: kind)) .map({ (pairs) -> [DomainLayer.DTO.Dex.SimplePair] in var simplePairs: [DomainLayer.DTO.Dex.SimplePair] = [] for pair in pairs { if !simplePairs.contains(where: {$0.amountAsset == pair.amountAsset && $0.priceAsset == pair.priceAsset}) { simplePairs.append(.init(amountAsset: pair.amountAsset, priceAsset: pair.priceAsset)) } } return simplePairs }) }) } func list(pairs: [DomainLayer.DTO.Dex.Pair]) -> Observable<[DomainLayer.DTO.Dex.PairPrice]> { return environmentRepository .servicesEnvironment() .flatMapLatest({ (servicesEnvironment) -> Observable<[DomainLayer.DTO.Dex.PairPrice]> in let pairsForQuery = pairs.map { DataService.Query.PairsPrice.Pair(amountAssetId: $0.amountAsset.id, priceAssetId: $0.priceAsset.id) } let query = DataService.Query.PairsPrice(pairs: pairsForQuery) return servicesEnvironment .wavesServices .dataServices .pairsPriceDataService .pairsPrice(query: query) .map({ (list) -> [DomainLayer.DTO.Dex.PairPrice] in var listPairs: [DomainLayer.DTO.Dex.PairPrice] = [] for (index, pairElement) in list.enumerated() { let localPair = pairs[index] let priceAsset = localPair.priceAsset let firstPrice = Money(value: Decimal(pairElement?.firstPrice ?? 0), priceAsset.decimals) let lastPrice = Money(value: Decimal(pairElement?.lastPrice ?? 0), priceAsset.decimals) let pairPrice = DomainLayer.DTO.Dex.PairPrice(firstPrice: firstPrice, lastPrice: lastPrice, amountAsset: localPair.amountAsset, priceAsset: priceAsset) listPairs.append(pairPrice) } return listPairs }) }) } func searchPairs(_ query: DomainLayer.Query.Dex.SearchPairs) -> Observable<DomainLayer.DTO.Dex.PairsSearch> { return environmentRepository .servicesEnvironment() .flatMapLatest({ (servicesEnvironment) -> Observable<DomainLayer.DTO.Dex.PairsSearch> in //TODO: Others type kinds guard case let .pairs(pairs) = query.kind else { return Observable.never() } let pairsForQuery = pairs.map { DataService.Query.PairsPrice.Pair(amountAssetId: $0.amountAsset, priceAssetId: $0.priceAsset) } let query = DataService.Query.PairsPrice(pairs: pairsForQuery) return servicesEnvironment .wavesServices .dataServices .pairsPriceDataService .pairsPrice(query: query) .map({ (pairsSearch) -> DomainLayer.DTO.Dex.PairsSearch in let pairs = pairsSearch.map({ (pairPrice) -> DomainLayer .DTO .Dex .PairsSearch .Pair? in guard let pairPrice = pairPrice else { return nil } return DomainLayer .DTO .Dex .PairsSearch .Pair.init(firstPrice: pairPrice.firstPrice, lastPrice: pairPrice.lastPrice, volume: pairPrice.volume, volumeWaves: pairPrice.volumeWaves, quoteVolume: pairPrice.quoteVolume) }) return DomainLayer.DTO.Dex.PairsSearch(pairs: pairs) }) }) } }
// // WorkerView.swift // ApZoo // // Created by Mac on 18/06/2021. // import SwiftUI import Combine struct WorkerView: View { @EnvironmentObject var ObservedTM: TaskManager @ObservedObject var worker: Worker var t_list: [Task] { worker.Tasks } var body: some View { VStack{ HStack{ Spacer() Text("\(worker.Name)") .font(.system(size:30)) .fontWeight(.bold) .padding() Spacer() } HStack{ Text("Your tasks:") .fontWeight(.semibold) .padding(.leading, 40) Spacer() } ScrollView{ ForEach(0..<t_list.count, id:\.self) { task in TaskInteractiveBlock(t_owner: worker, task: t_list[task]) } } } } } struct TaskInteractiveBlock: View { @EnvironmentObject var ObservedTM: TaskManager @State var t_owner: Worker @ObservedObject var task: Task var body: some View { ZStack(alignment: Alignment(horizontal: .leading, vertical: .top)){ ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)){ Rectangle() .frame(width: 300, height: 100) .foregroundColor(.WhiteBlue) .cornerRadius(20) HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: { if(task.Status >= 100) { Button(action: { t_owner.Tasks.removeFirst() }, label: { Text("Set as finished") .fontWeight(.semibold) .font(.system(size: 30)) }) } else { VStack{ Text("Priority") Text(task.getPriority()) .foregroundColor(colors[task.Priority]) .fontWeight(.semibold) } VStack{ Text("Status") ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)){ Rectangle() .frame(width: 160, height: 13, alignment: .center) .foregroundColor(.salmon) Rectangle() .frame(width: CGFloat(task.Status * 1.6), height: 15, alignment: .leading) .foregroundColor(.mauve) .animation(.default) } } } }) .padding(.bottom, 3) } ZStack(alignment: Alignment(horizontal: .center, vertical: .center)){ Rectangle() .frame(width: 300, height: 50, alignment: .leading) .foregroundColor(.DarkBlue) .cornerRadius(20) HStack{ Text(task.getDescription()) .fontWeight(.semibold) .foregroundColor(.white) .padding(.leading, /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/) Spacer() Button(action: { if (task.Status < 100){ task.Status += 10.0 }}, label: { Image(systemName: "plus.circle") .foregroundColor(.yellow) .font(.system(size: 30, weight: .bold)) }) .padding(.trailing, /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/) } .frame(width: 300, height: 50, alignment: .leading) } } } } //struct WorkerView_Previews: PreviewProvider { // static var previews: some View { // WorkerView() // } //}
// // ViewController.swift // UMS_pay // // Created by 张桀硕 on 2019/2/13. // Copyright © 2019年 jieshuo.zhang. All rights reserved. // import Foundation import UIKit class Preferences { static let shared = Preferences() var enableTransitionAnimation = false } // Used by SideMenu tableview class SelectionCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var titleImage: UIImageView! } class MenuViewController: UIViewController { var isDarkModeEnabled = false @IBOutlet weak var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none } } @IBOutlet weak var selectionTableViewHeader: UILabel! @IBOutlet weak var selectionMenuTrailingConstraint: NSLayoutConstraint! private var themeColor = UIColor.white @IBOutlet weak var backTopView: UIView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var headImageView: UIImageView! @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var settingButton: UIButton! @IBOutlet weak var verLabel: UILabel! let cellHeight: CGFloat = 42 // MARK:- override func viewDidLoad() { super.viewDidLoad() setupViews() inputContentViews() } // use when scream transition override func viewWillTransition( to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let sidemenuBasicConfiguration = SideMenuController.preferences.basic let showPlaceTableOnLeft = (sidemenuBasicConfiguration.position == .under) != (sidemenuBasicConfiguration.direction == .right) selectionMenuTrailingConstraint.constant = showPlaceTableOnLeft ? SideMenuController.preferences.basic.menuWidth - size.width : 0 view.layoutIfNeeded() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } } extension MenuViewController { // setup sidemenu views func setupViews() { sideMenuController?.delegate = self isDarkModeEnabled = SideMenuController.preferences.basic.position == .under // dark model if isDarkModeEnabled { themeColor = UIColor(red: 0.03, green: 0.04, blue: 0.07, alpha: 1.00) selectionTableViewHeader.textColor = .white } else { selectionMenuTrailingConstraint.constant = 0 themeColor = UIColor(red: 0.98, green: 0.97, blue: 0.96, alpha: 1.00) } let sidemenuBasicConfiguration = SideMenuController.preferences.basic let showPlaceTableOnLeft = (sidemenuBasicConfiguration.position == .under) != (sidemenuBasicConfiguration.direction == .right) if showPlaceTableOnLeft { selectionMenuTrailingConstraint.constant = SideMenuController.preferences.basic.menuWidth - view.frame.width } // setup colors view.backgroundColor = themeColor tableView.backgroundColor = themeColor backTopView.backgroundColor = themeColor contentView.backgroundColor = themeColor // head let radius = headImageView.frame.height / 2 headImageView.layer.cornerRadius = radius headImageView.layer.borderWidth = 0 headImageView.layer.masksToBounds = false // head shadow headImageView.layer.shadowColor = UIColor.gray.cgColor headImageView.layer.shadowOpacity = 0.5 headImageView.layer.shadowRadius = 2.0 headImageView.layer.shadowOffset = CGSize.init(width: 2, height: 2) // infos label1.text = NSLocalizedString("Menu_Title", comment: "") label1.font = UIFont(name: "PingFangSC-Regular", size: 13) label2.text = NSLocalizedString("Menu_SubTitle", comment: "") label2.font = UIFont(name: "PingFangSC-Regular", size: 11) // version verLabel.text = Utils.getAppVersion() verLabel.font = UIFont(name: "PingFangSC-Regular", size: 13) // settings button settingButton.backgroundColor = UIColor.clear let buttonHeight = settingButton.frame.height // settings button image let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: buttonHeight, height: buttonHeight)) imageView.image = UIImage(named: "menu_setting") settingButton.addSubview(imageView) // settings button frame let labelX = imageView.frame.width + 20 let labelWidth = settingButton.frame.width - labelX let label = UILabel(frame: CGRect(x: labelX, y: 0, width: labelWidth, height: buttonHeight)) label.text = NSLocalizedString("Menu_Setting", comment: "") let settingSize: CGFloat = 13 label.font = UIFont(name: "PingFangSC-Regular", size: settingSize) settingButton.addSubview(label) } // input content views func inputContentViews() { // the second view: My Favorite sideMenuController?.cache(viewControllerGenerator: { self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") }, with: "1") // the third view: Settings sideMenuController?.cache(viewControllerGenerator: { self.storyboard?.instantiateViewController(withIdentifier: "ThirdViewController") }, with: "2") } @IBAction func tapSettingButton(_ sender: UIButton) { // set sidemenu flag Utils().setMenuInt(int: SelectedSideMenu.setting) tableView.reloadData() // push to settings view sideMenuController?.setContentViewController(with: "2", animated: Preferences.shared.enableTransitionAnimation) sideMenuController?.hideMenu() // print info if let identifier = sideMenuController?.currentCacheIdentifier() { print("[Example] View Controller Cache Identifier: \(identifier)") } } } // MARK:- SideMenuControllerDelegate extension MenuViewController: SideMenuControllerDelegate { func sideMenuController( _ sideMenuController: SideMenuController, animationControllerFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return BasicTransitionAnimator(options: .transitionFlipFromLeft, duration: 0.6) } func sideMenuController( _ sideMenuController: SideMenuController, willShow viewController: UIViewController, animated: Bool) { print("[Example] View controller will show [\(viewController)]") } func sideMenuController( _ sideMenuController: SideMenuController, didShow viewController: UIViewController, animated: Bool) { print("[Example] View controller did show [\(viewController)]") } func sideMenuControllerWillHideMenu(_ sideMenuController: SideMenuController) { print("[Example] Menu will hide") } func sideMenuControllerDidHideMenu(_ sideMenuController: SideMenuController) { print("[Example] Menu did hide.") } func sideMenuControllerWillRevealMenu(_ sideMenuController: SideMenuController) { print("[Example] Menu will reveal.") // send hide keyboard notification NotificationCenter.default.post(name: NSNotification.Name(NotificationName.hideKeyboard), object: nil, userInfo: nil) } func sideMenuControllerDidRevealMenu(_ sideMenuController: SideMenuController) { print("[Example] Menu did reveal.") } } // MARK:- UITableViewDelegate, UITableViewDataSource extension MenuViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // setup cell let cell = tableView.dequeueReusableCell( withIdentifier: "MenuCell", for: indexPath) as! SelectionCell cell.contentView.backgroundColor = themeColor let size: CGFloat = 16 cell.titleLabel.font = UIFont(name: "PingFangSC-Regular", size: size) // setup colors if indexPath.row == Utils().getMenuInt() { cell.textLabel?.textColor = UIColor.colorWith(hexString: "#007AFF") } else { cell.textLabel?.textColor = UIColor.black } // setup row let row = indexPath.row if row == 0 { cell.titleLabel?.text = NSLocalizedString("Menu_Search", comment: "") cell.titleImage?.image = UIImage(named: "menu_search") } else if row == 1 { cell.titleLabel?.text = NSLocalizedString("Menu_Liked", comment: "") cell.titleImage?.image = UIImage(named: "menu_liked") } // if dark mode cell.titleLabel?.textColor = isDarkModeEnabled ? .white : .black return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = indexPath.row // use sidemenu flag to know where to come Utils().setMenuInt(int: row) tableView.reloadData() tableView.deselectRow(at: indexPath, animated: true) // push to view selected sideMenuController?.setContentViewController( with: "\(row)", animated: Preferences.shared.enableTransitionAnimation) sideMenuController?.hideMenu() // print info if let identifier = sideMenuController?.currentCacheIdentifier() { print("[Example] View Controller Cache Identifier: \(identifier)") } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } }
// // APIDelegate.swift // diverCity // // Created by Lauren Shultz on 10/31/18. // Copyright © 2018 Lauren Shultz. All rights reserved. // import Foundation struct APIDelegate { static let basePath = "https://divircity-api.herokuapp.com/api/" static let currentVersion = "v2" static let path = "https://divircity-api.herokuapp.com/api/v2" static let usersPath = "/users" static let communitiesPath = "/communities" static let eventsPath = "/events" static let notificationsPath = "/notifications" static let mediaPath = "/media" static let postsPath = "/posts" // func basePath(withVersion version: String) -> String { // return path + version // } // // func usersPath(withId id: String) -> String { // return path + users + "/" + id // } // // func communitiesPath(withId id: String) -> String { // return path + communities + "/" + id // } // // func eventsPath(withId id: String) -> String { // return path + events + "/" + id // } } extension APIDelegate { static func requestBuilder(withPath localPath: String, withId id: String, methodType:String, postContent:String?) -> URLRequest? { print("Building Request...") var urlString = path + localPath if ((methodType == "GET" || methodType == "PATCH" || methodType == "DELETE") && id != "all") { urlString += "/" + id } let url = URL(string: urlString) var request = URLRequest(url: url!) if(methodType == "POST") { request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = methodType if (postContent != nil) { let postString = postContent!// "id=13&name=Jack" request.httpBody = postString.data(using: .utf8) //print("REQUEST: ", request) } else { print("THERE WAS AN ERROR") return nil } //request.httpBody = postString.data(using: .utf8) } else if (methodType == "PATCH") { request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = methodType if (postContent != nil) { let postString = postContent!// "id=13&name=Jack" request.httpBody = postString.data(using: .utf8) //print("REQUEST: ", request) } else { print("THERE WAS AN ERROR") return nil } } else if (methodType == "DELETE") { request.httpMethod = methodType } print("REQUEST: ", request) return request } static func buildPostString(body: [String]) -> String { var postString = body.count != 0 ? body[0] : "" if (body.count > 1) { for index in 1...body.count - 1 { postString += "&" + body[index] } } return postString } static func performTask(withRequest request: URLRequest, completion: @escaping ([[String:Any]]?) -> ()) { let task = URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in var returnedJson: [[String:Any]]? = nil if let data = data { do { print("data: ", data) if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] { print("JSON: ", json) returnedJson = [json] } else if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] { returnedJson = json } } catch { print("error getting info") print(error) } DispatchQueue.main.async { completion(returnedJson) } } }) task.resume() } static func addNewElemnentToValue(value: String, element: String) -> String { if (value == "") { return element } else { return value + "," + element } } }
// GitHubServerTests.swift // Buildasaur // // Created by Honza Dvorsky on 12/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Cocoa import XCTest import BuildaGitServer import BuildaUtils class GitHubSourceTests: XCTestCase { var github: GitHubServer! override func setUp() { super.setUp() self.github = GitHubFactory.server(nil) } override func tearDown() { self.github = nil super.tearDown() } func tryEndpoint(method: HTTP.Method, endpoint: GitHubEndpoints.Endpoint, params: [String: String]?, completion: (body: AnyObject!, error: NSError!) -> ()) { let expect = expectationWithDescription("Waiting for url request") let request = try! self.github.endpoints.createRequest(method, endpoint: endpoint, params: params) self.github.http.sendRequest(request, completion: { (response, body, error) -> () in completion(body: body, error: error) expect.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testGetPullRequests() { let params = [ "repo": "czechboy0/Buildasaur-Tester" ] self.tryEndpoint(.GET, endpoint: .PullRequests, params: params) { (body, error) -> () in XCTAssertNotNil(body, "Body must be non-nil") if let body = body as? NSArray { let prs: [PullRequest] = GitHubArray(body) XCTAssertGreaterThan(prs.count, 0, "We need > 0 items to test parsing") Log.verbose("Parsed PRs: \(prs)") } else { XCTFail("Body nil") } } } func testGetBranches() { let params = [ "repo": "czechboy0/Buildasaur-Tester" ] self.tryEndpoint(.GET, endpoint: .Branches, params: params) { (body, error) -> () in XCTAssertNotNil(body, "Body must be non-nil") if let body = body as? NSArray { let branches: [Branch] = GitHubArray(body) XCTAssertGreaterThan(branches.count, 0, "We need > 0 items to test parsing") Log.verbose("Parsed branches: \(branches)") } else { XCTFail("Body nil") } } } //manual parsing tested here, sort of a documentation as well func testUserParsing() { let dictionary = [ "login": "czechboy0", "name": "Honza Dvorsky", "avatar_url": "https://avatars.githubusercontent.com/u/2182121?v=3", "html_url": "https://github.com/czechboy0" ] let user = User(json: dictionary) XCTAssertEqual(user.userName, "czechboy0") XCTAssertEqual(user.realName!, "Honza Dvorsky") XCTAssertEqual(user.avatarUrl!, "https://avatars.githubusercontent.com/u/2182121?v=3") XCTAssertEqual(user.htmlUrl!, "https://github.com/czechboy0") } func testRepoParsing() { let dictionary = [ "name": "Buildasaur", "full_name": "czechboy0/Buildasaur", "clone_url": "https://github.com/czechboy0/Buildasaur.git", "ssh_url": "git@github.com:czechboy0/Buildasaur.git", "html_url": "https://github.com/czechboy0/Buildasaur" ] let repo = Repo(json: dictionary) XCTAssertEqual(repo.name, "Buildasaur") XCTAssertEqual(repo.fullName, "czechboy0/Buildasaur") XCTAssertEqual(repo.repoUrlHTTPS, "https://github.com/czechboy0/Buildasaur.git") XCTAssertEqual(repo.repoUrlSSH, "git@github.com:czechboy0/Buildasaur.git") XCTAssertEqual(repo.htmlUrl!, "https://github.com/czechboy0/Buildasaur") } func testCommitParsing() { let dictionary: NSDictionary = [ "sha": "08182438ed2ef3b34bd97db85f39deb60e2dcd7d", "url": "https://api.github.com/repos/czechboy0/Buildasaur/commits/08182438ed2ef3b34bd97db85f39deb60e2dcd7d" ] let commit = Commit(json: dictionary) XCTAssertEqual(commit.sha, "08182438ed2ef3b34bd97db85f39deb60e2dcd7d") XCTAssertEqual(commit.url!, "https://api.github.com/repos/czechboy0/Buildasaur/commits/08182438ed2ef3b34bd97db85f39deb60e2dcd7d") } func testBranchParsing() { let commitDictionary = [ "sha": "08182438ed2ef3b34bd97db85f39deb60e2dcd7d", "url": "https://api.github.com/repos/czechboy0/Buildasaur/commits/08182438ed2ef3b34bd97db85f39deb60e2dcd7d" ] let dictionary = [ "name": "master", "commit": commitDictionary ] let branch = Branch(json: dictionary) XCTAssertEqual(branch.name, "master") XCTAssertEqual(branch.commit.sha, "08182438ed2ef3b34bd97db85f39deb60e2dcd7d") XCTAssertEqual(branch.commit.url!, "https://api.github.com/repos/czechboy0/Buildasaur/commits/08182438ed2ef3b34bd97db85f39deb60e2dcd7d") } func testPullRequestBranchParsing() { let dictionary = [ "ref": "fb-loadNode", "sha": "7e45fa772565969ee801b0bdce0f560122e34610", "user": [ "login": "aleclarson", "avatar_url": "https://avatars.githubusercontent.com/u/1925840?v=3", "url": "https://api.github.com/users/aleclarson", "html_url": "https://github.com/aleclarson", ], "repo": [ "name": "AsyncDisplayKit", "full_name": "aleclarson/AsyncDisplayKit", "owner": [ "login": "aleclarson", "avatar_url": "https://avatars.githubusercontent.com/u/1925840?v=3", "url": "https://api.github.com/users/aleclarson", "html_url": "https://github.com/aleclarson", ], "html_url": "https://github.com/aleclarson/AsyncDisplayKit", "description": "Smooth asynchronous user interfaces for iOS apps.", "url": "https://api.github.com/repos/aleclarson/AsyncDisplayKit", "ssh_url": "git@github.com:aleclarson/AsyncDisplayKit.git", "clone_url": "https://github.com/aleclarson/AsyncDisplayKit.git", ] ] let prbranch = PullRequestBranch(json: dictionary) XCTAssertEqual(prbranch.ref, "fb-loadNode") XCTAssertEqual(prbranch.sha, "7e45fa772565969ee801b0bdce0f560122e34610") XCTAssertEqual(prbranch.repo.name, "AsyncDisplayKit") } }
// // StoriesTableViewController.swift // NewspaperExample // // Created by Maurin Arona on 2/10/19. // Copyright © 2019 Kyra Arona. All rights reserved. // import UIKit struct Headline { var id : Int var title : String var text : String //var image : String } class StoriesTableViewController: UITableViewController { var headlines = [ Headline(id: 1, title: "Algebra", text: "page 25, problems 1-17 odd"), Headline(id: 2, title: "English", text: "read \"Romeo and Juliet\" act 2"), Headline(id: 3, title: "Biology", text: "complete lab report"), ] // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return the number of rows return headlines.count } // override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // return "Section \(section)" // } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Label Cell", for: indexPath) // Configure the cell... //cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)" //cell.textLabel?.text = headlines[indexPath.row].title let headline = headlines[indexPath.row] cell.textLabel?.text = headline.title cell.detailTextLabel?.text = headline.text //cell.imageView?.image = UIImage(named: headline.image) return cell } }
// // AreaDetailViewController.swift // TermProject // // Created by kpugame on 2021/05/25. // import UIKit import MapKit import Contacts class AreaDetailViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var areaNameLabel: UILabel! @IBOutlet weak var telephoneLabel: UILabel! @IBOutlet weak var detailAddressLabel: UILabel! @IBOutlet weak var map: MKMapView! let regionRadius: CLLocationDistance = 3000 var name : String? var telephone : String? var detailAddress : String? var lat : Double = 0.0//latitude var lon : Double = 0.0//longitude func initloaddate(){ areaNameLabel.text! = name! telephoneLabel.text! = telephone! detailAddressLabel.text! = detailAddress! } func mapItem()->MKMapItem{ let addressDict = [CNPostalAddressStreetKey: name!] let placemark = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lon), addressDictionary: addressDict) let mapItem = MKMapItem(placemark: placemark) mapItem.name = title return mapItem } func centerMapOnLocation(location: CLLocation){ let coordinateRegion = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) map.setRegion(coordinateRegion, animated: true) } func pinSetting(){ let point = MKPointAnnotation() point.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon) point.title = areaNameLabel.text point.subtitle = detailAddressLabel.text map.addAnnotation(point) } override func viewDidLoad() { super.viewDidLoad() map.delegate = self initloaddate() let initialLocation = CLLocation(latitude: lat, longitude: lon) centerMapOnLocation(location: initialLocation) // 핀설정 pinSetting() } func mapView(_ mapView: MKMapView, annotationView view:MKAnnotationView, calloutAccessoryControlTapped control: UIControl){ let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] mapItem().openInMaps(launchOptions: launchOptions) } func mapView(_ mapView: MKMapView, viewFor annotation:MKAnnotation)->MKAnnotationView?{ let identifier = "marker" var view:MKMarkerAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView{ dequeuedView.annotation = annotation view = dequeuedView } else{ view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } return view } }
// // SearchViewController.swift // yandexKitTest // // Created by Artem Alekseev on 26/08/2017. // Copyright © 2017 Artem Alekseev. All rights reserved. // import UIKit class SearchViewController: UIViewController, UISearchBarDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: CustomSearchBar! private let apiManager = APIManager() private var places = [Place]() var tableViewRoutineDelegates: TableViewRoutineDelegates! //MARK: ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() setupViewController() } //MARK: Methods func setupViewController() { self.tableViewRoutineDelegates = TableViewRoutineDelegates(tableView: tableView, places: places, sender: self) searchBar.delegate = self searchBar.setShowsCancelButton(false, animated: false) tableView.keyboardDismissMode = .onDrag } func loadResults(text: String) { startSpinner() apiManager.loadPlaces(stringParameter: text) { (loadedPlaces) in self.tableViewRoutineDelegates.sectionsRowsArray = loadedPlaces self.stopSpinner() self.tableView.reloadData() } } //MARK: UISearchBarDelegate func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if !searchText.isEmpty { loadResults(text: searchText) } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() if let text = searchBar.text { loadResults(text: text) } } //MARK: UIButton Actions @IBAction func cancelButtonDidTapped(_ sender: Any) { //Setting this to false, because user dismissed ViewController LocationManager.shared.shouldSetAnnotation = false dismiss(animated: true, completion: nil) } } extension SearchViewController { func startSpinner() { tableView.addSubview(tableViewRoutineDelegates.spinner) tableViewRoutineDelegates.spinner.startAnimating() } func stopSpinner() { tableViewRoutineDelegates.spinner.stopAnimating() } }
// // GLInputPickerView.swift // GameleySDK // // Created by Fitz Leo on 2018/6/20. // Copyright © 2018年 Fitz Leo. All rights reserved. // import UIKit class GLInputPickerView: UITextView, UITextViewDelegate { lazy var characterNumLabel: UILabel = { let temp = UILabel(frame: CGRect(x: kScreen_W - 10 - 40, y: kScreen_H - 64 - 20 - 10, width: 40, height: 15)) temp.backgroundColor = UIColor.clear temp.font = UIFont.systemFont(ofSize: 12) return temp }() var maxCharacterNum: Int var warningColor: UIColor init(longText: String, maxCharacterNum: Int, warningColor: UIColor) { self.maxCharacterNum = maxCharacterNum self.warningColor = warningColor super.init(frame: CGRect(x: 0, y: 10, width: kScreen_W, height: kScreen_H - 64 - 20), textContainer: nil) characterNumLabel.text = longText backgroundColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // WebResource.swift // // // Created by Zaid Rahawi on 1/21/20. // import Foundation import Combine /// Generic SwiftUI-ready resource object open class WebResource<A> : ObservableObject, Resource { public let request: URLRequest public var service: Service public let parse: (Data) -> A public var cancellable: AnyCancellable? @Published public var value: A? public required init(request: URLRequest, parse: @escaping (Data) -> A) { self.request = request self.parse = parse self.service = WebService() } } /// WebResource subclass with on-disk cache open class CachedResource<A> : WebResource<A> { public required init(request: URLRequest, parse: @escaping (Data) -> A) { super.init(request: request, parse: parse) self.service = CachedWebService(cache: .onDisk) } }
// // SwiftUIView.swift // Basics // // Created by Venkatnarayansetty, Badarinath on 3/21/20. // Copyright © 2020 Badarinath Venkatnarayansetty. All rights reserved. // import SwiftUI struct CartView: View { @State private var taps: Int = 0 @State private var status: Bool = false var body: some View { VStack { Button(self.status ? "Fill Cart" : "Empty Cart") { withAnimation(.linear(duration: 0.5)) { self.taps += 1 self.status.toggle() } }.animation(nil) .padding() .font(.system(size: 16, weight: Font.Weight.heavy)) Image(self.status ? "cart_empty" : "cart_filled") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 40 , height: 40) .shake(times: (self.taps > 0 ) ? self.taps * 3 : 0) .padding() } } } struct CartView_Previews: PreviewProvider { static var previews: some View { CartView() } }
import Foundation class PriceAlert { let coin: Coin var state: AlertState var lastRate: Decimal? init(coin: Coin, state: AlertState, lastRate: Decimal? = nil) { self.coin = coin self.state = state self.lastRate = lastRate } }
// // Swift_ViewController2.swift // Swift教程 // // Created by ddsc on 2018/7/3. // Copyright © 2018年 ddsc. All rights reserved. // import UIKit class Swift_ViewController2: UIViewController ,UITableViewDelegate,UITableViewDataSource { var tableview : UITableView? var array : Array<String>? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.title = "30App" self.tableview = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain) self.tableview?.delegate = self self.tableview?.dataSource = self self.tableview?.register(UITableViewCell.self, forCellReuseIdentifier: "myCell") self.view.addSubview(self.tableview!) self.array = ["Project01-SimpleStopWatchVC","Project02-CustomFontVC","Project03-PlayLocalVedioVC","Project04-PictureScrollerVC","Project05-AlamofireVC","Project06-NetworkRequesrVC","Project07-PickerViewVC","Project08-AnimationOfVpnVC"] } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.array?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableview?.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) cell?.textLabel?.text = "123" cell?.textLabel?.text = self.array?[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //在swift中通过字符串转为类,需要在字符串名前加上项目的名称 let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String // 这是获取项目的名称 /** * 如果你的工程名字中带有“-” 符号 需要加上 replacingOccurrences(of: "-", with: "_") 这句代码把“-” 替换掉 不然还会报错 要不然系统会自动替换掉 这样就不是你原来的包名了 如果不包含“-” 这句代码 可以不加 */ let className = clsName! + "." + self.array![indexPath.row].replacingOccurrences(of: "-", with: "_") //拼接成字符串 let viewC = NSClassFromString(className)! as! UIViewController.Type let vc = viewC.init() //初始化 vc.title = className self.navigationController?.pushViewController(vc, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // 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.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // TableCellViewModelType.swift // SberbankTestTask // // Created by Михаил Разин on 13.11.2019. // Copyright © 2019 Михаил Разин. All rights reserved. // import Foundation protocol TableCellViewModelType: class { //MARK: - init init (publication: Publication?) //MARK: - public vars var title: String { get } var urlToImage: String { get } var isWatched: Bool { get } func setDelegate(delegate: LoadPhotoDelegate) func getAndUpdatePicture() }
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ import Foundation @testable import KittCore import XCTest class CookiesTests: XCTestCase { func testParser() { let date = Date().addingTimeInterval(3600) let dateString = cookieDateFormatter.string(from: date) let name = "name" let value = "value" let cookieString = "\(name)=\(value); expIres=\(dateString); domain=.example.com; pAth=/" let cookie = createHTTPCookie(from: URL(string: "http://example.com")!, cookie: cookieString) XCTAssert(cookie?.name == name) XCTAssert(cookie?.value == value) XCTAssert(cookieDateFormatter.string(from: date) == dateString) } class CookieStorage: CookieStorageProvider { var cookieStorage: HTTPCookieStorage? } func testGetterAndSetter() { let cookieStorage = CookieStorage() let configuration = URLSessionConfiguration.ephemeral cookieStorage.cookieStorage = configuration.httpCookieStorage let setter = cookieSetter(for: cookieStorage) let getter = cookieGetter(for: cookieStorage) let date = Date().addingTimeInterval(3600) let dateString = cookieDateFormatter.string(from: date) let url = "http://example.com" let cookies = [("name1", "value1"), ("name2", "value2"), ("name3", "value3")] for (name, value) in cookies { let cookieString = "\(name)=\(value); expIres=\(dateString); domain=.example.com; pAth=/" setter(url, cookieString) } let cookiesString = cookies .map { "\($0.0)=\($0.1)" } .joined(separator: "; ") let newCookiesString = getter(url) XCTAssert(newCookiesString == cookiesString) } }
import Foundation import TronKit import MarketKit class TronTransactionRecord: TransactionRecord { let transaction: Transaction let confirmed: Bool let ownTransaction: Bool let fee: TransactionValue? init(source: TransactionSource, transaction: Transaction, baseToken: Token, ownTransaction: Bool, spam: Bool = false) { self.transaction = transaction confirmed = transaction.confirmed let txHash = transaction.hash.hs.hex self.ownTransaction = ownTransaction if let feeAmount = transaction.fee { let feeDecimal = Decimal(sign: .plus, exponent: -baseToken.decimals, significand: Decimal(feeAmount)) fee = .coinValue(token: baseToken, value: feeDecimal) } else { fee = nil } super.init( source: source, uid: txHash, transactionHash: txHash, transactionIndex: 0, blockHeight: transaction.blockNumber, confirmationsThreshold: BaseTronAdapter.confirmationsThreshold, date: Date(timeIntervalSince1970: Double(transaction.timestamp / 1000)), failed: transaction.isFailed, spam: spam ) } private func sameType(_ value: TransactionValue, _ value2: TransactionValue) -> Bool { switch (value, value2) { case let (.coinValue(lhsToken, _), .coinValue(rhsToken, _)): return lhsToken == rhsToken case let (.tokenValue(lhsTokenName, lhsTokenCode, lhsTokenDecimals, _), .tokenValue(rhsTokenName, rhsTokenCode, rhsTokenDecimals, _)): return lhsTokenName == rhsTokenName && lhsTokenCode == rhsTokenCode && lhsTokenDecimals == rhsTokenDecimals case let (.nftValue(lhsNftUid, _, _, _), .nftValue(rhsNftUid, _, _, _)): return lhsNftUid == rhsNftUid default: return false } } func combined(incomingEvents: [TransferEvent], outgoingEvents: [TransferEvent]) -> ([TransactionValue], [TransactionValue]) { let values = (incomingEvents + outgoingEvents).map { $0.value } var resultIncoming = [TransactionValue]() var resultOutgoing = [TransactionValue]() for value in values { if (resultIncoming + resultOutgoing).contains(where: { sameType(value, $0) }) { continue } let sameTypeValues = values.filter { sameType(value, $0) } let totalValue = sameTypeValues.map { $0.decimalValue ?? 0 }.reduce(0, +) let resultValue: TransactionValue switch value { case let .coinValue(token, _): resultValue = .coinValue(token: token, value: totalValue) case let .tokenValue(tokenName, tokenCode, tokenDecimals, _): resultValue = .tokenValue(tokenName: tokenName, tokenCode: tokenCode, tokenDecimals: tokenDecimals, value: totalValue) case let .nftValue(nftUid, _, tokenName, tokenSymbol): resultValue = .nftValue(nftUid: nftUid, value: totalValue, tokenName: tokenName, tokenSymbol: tokenSymbol) case let .rawValue(value): resultValue = .rawValue(value: value) } if totalValue > 0 { resultIncoming.append(resultValue) } else { resultOutgoing.append(resultValue) } } return (resultIncoming, resultOutgoing) } override func status(lastBlockHeight: Int?) -> TransactionStatus { if failed { return .failed } if confirmed { return .completed } return .pending } } extension TronTransactionRecord { struct TransferEvent { let address: String let value: TransactionValue } }
// // UIColor+Extension.swift // TrackFinder // // Created by Niels Hoogendoorn on 21/06/2020. // Copyright © 2020 Nihoo. All rights reserved. // import Foundation extension UIColor { static let mainColor = UIColor(red: 1.00, green: 0.82, blue: 0.36, alpha: 1.00) }
import Combine import Foundation import UIKit import Chart import ThemeKit class CoinIndicatorViewItemFactory { static let sectionNames = ["coin_analytics.indicators.summary".localized] + ChartIndicator.Category.allCases.map { $0.title } private func advice(items: [TechnicalIndicatorService.Item]) -> Advice { let rating = items.map { $0.advice.rating }.reduce(0, +) let adviceCount = items.filter { $0.advice != .noData }.count let variations = 2 * adviceCount + 1 let baseDelta = variations / 5 let remainder = variations % 5 let neutralAddict = remainder % 3 // how much variations will be added to neutral zone let sideAddict = remainder / 3 // how much will be added to sell/buy zone let deltas = [baseDelta, baseDelta + sideAddict, baseDelta + sideAddict + neutralAddict, baseDelta + sideAddict, baseDelta] var current = -adviceCount var ranges = [Range<Int>]() for delta in deltas { ranges.append(current..<(current + delta)) current += delta } let index = ranges.firstIndex { $0.contains(rating) } ?? 0 return Advice(rawValue: index) ?? .neutral } } extension CoinIndicatorViewItemFactory { func viewItems(items: [TechnicalIndicatorService.SectionItem]) -> [ViewItem] { var viewItems = [ViewItem]() var allAdviceItems = [TechnicalIndicatorService.Item]() for item in items { allAdviceItems.append(contentsOf: item.items) viewItems.append(ViewItem(name: item.name, advice: advice(items: item.items))) } let viewItem = ViewItem(name: Self.sectionNames.first ?? "", advice: advice(items: allAdviceItems)) if viewItems.count > 0 { viewItems.insert(viewItem, at: 0) } return viewItems } func detailViewItems(items: [TechnicalIndicatorService.SectionItem]) -> [SectionDetailViewItem] { items.map { SectionDetailViewItem( name: $0.name, viewItems: $0.items.map { DetailViewItem(name: $0.name, advice: $0.advice.title, color: $0.advice.color) } ) } } } extension CoinIndicatorViewItemFactory { enum Advice: Int, CaseIterable { case strongSell case sell case neutral case buy case strongBuy var color: UIColor { switch self { case .strongSell: return UIColor(hex: 0xF43A4F) case .sell: return UIColor(hex: 0xF4503A) case .neutral: return .themeJacob case .buy: return UIColor(hex: 0xB5C405) case .strongBuy: return .themeRemus } } var title: String { switch self { case .strongBuy: return "coin_analytics.indicators.strong_buy".localized case .buy: return "coin_analytics.indicators.buy".localized case .neutral: return "coin_analytics.indicators.neutral".localized case .sell: return "coin_analytics.indicators.sell".localized case .strongSell: return "coin_analytics.indicators.strong_sell".localized } } } struct ViewItem { let name: String let advice: Advice } struct DetailViewItem { let name: String let advice: String let color: UIColor } struct SectionDetailViewItem { let name: String let viewItems: [DetailViewItem] } } extension TechnicalIndicatorService.Advice { var title: String { switch self { case .noData: return "coin_analytics.indicators.no_data".localized case .buy: return "coin_analytics.indicators.buy".localized case .neutral: return "coin_analytics.indicators.neutral".localized case .sell: return "coin_analytics.indicators.sell".localized } } var color: UIColor { switch self { case .noData: return .themeGray case .buy: return CoinIndicatorViewItemFactory.Advice.buy.color case .neutral: return CoinIndicatorViewItemFactory.Advice.neutral.color case .sell: return CoinIndicatorViewItemFactory.Advice.sell.color } } }
class Solution { func maxArea(_ height: [Int]) -> Int { var start = 0, end = height.count - 1 var result = 0 while start < end { let currentArea = min(height[start], height[end]) * (end - start) result = max(result, currentArea) if height[start] <= height[end] { start += 1 } else { end -= 1 } } return result } }
// // OTMConvenience.swift // OnTheMap // // Created by Jun.Yuan on 16/6/30. // Copyright © 2016年 Jun.Yuan. All rights reserved. // import Foundation import UIKit import CoreLocation // MARK: - Request Method Convenience extension OTMClient { // MARK: Login With Udacity Credential func loginWithUdacityCredential(username username: String, password: String, completionHandlerForLogin: (success: Bool, error: NSError?, errorMessage: String?) -> Void) { let method: String = Methods.Session let parameters = [String: AnyObject]() let jsonBody = "{\"\(JsonBodyKeys.Udacity)\": {\"\(JsonBodyKeys.Username)\": \"\(username)\", \"\(JsonBodyKeys.Password)\": \"\(password)\"}}" taskForPOSTMethod(method, parameters: parameters, jsonBody: jsonBody, host: .Udacity) { (results, error) in guard error == nil else { completionHandlerForLogin(success: false, error: error, errorMessage: "Connection timed out.") return } let errorDomain = "loginWithCredential" if let _ = results[ResponseKeys.StatusCode] as? Int, errorString = results[ResponseKeys.Error] as? String { completionHandlerForLogin(success: false, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: errorString]), errorMessage: errorString) return } guard let accountDictionary = results[ResponseKeys.Account] as? [String: AnyObject] else { completionHandlerForLogin(success: false, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.Account)' in \(results)"]), errorMessage: "Login failed.") return } guard let key = accountDictionary[ResponseKeys.Key] as? String else { completionHandlerForLogin(success: false, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.Key)' in \(accountDictionary)"]), errorMessage: "Login failed.") return } OTMModel.sharedInstance().userUniqueKey = key completionHandlerForLogin(success: true, error: nil, errorMessage: nil) } } // MARK: Logout of Udacity func logoutOfUdacity(completionHandlerForLogout: (success: Bool, error: NSError?) -> Void) { let method: String = Methods.Session let parameters = [String: AnyObject]() taskForDELETEMethod(method, parameters: parameters, host: .Udacity) { (results, error) in guard error == nil else { completionHandlerForLogout(success: false, error: error) return } completionHandlerForLogout(success: true, error: nil) } } // MARK: Login With Facebook Authentication func loginWithFacebookAuthentication(accessToken token: String, completionHandlerForLogin: (success: Bool, error: NSError?, errorMessage: String?) -> Void) { let method: String = Methods.Session let parameters = [String: AnyObject]() let jsonBody = "{\"\(JsonBodyKeys.FacebookMobile)\": {\"\(JsonBodyKeys.AccessToken)\": \"\(token)\"}}" taskForPOSTMethod(method, parameters: parameters, jsonBody: jsonBody, host: .Udacity) { (results, error) in guard error == nil else { completionHandlerForLogin(success: false, error: error, errorMessage: "Connection timed out.") return } let errorDomain = "loginWithFacebookAuthentication" if let _ = results[ResponseKeys.StatusCode] as? Int, errorString = results[ResponseKeys.Error] as? String { completionHandlerForLogin(success: false, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: errorString]), errorMessage: errorString) return } guard let accountDictionary = results[ResponseKeys.Account] as? [String: AnyObject] else { completionHandlerForLogin(success: false, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.Account)' in \(results)"]), errorMessage: "Login failed.") return } guard let key = accountDictionary[ResponseKeys.Key] as? String else { completionHandlerForLogin(success: false, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.Key)' in \(accountDictionary)"]), errorMessage: "Login failed.") return } OTMModel.sharedInstance().userUniqueKey = key completionHandlerForLogin(success: true, error: nil, errorMessage: nil) } } // MARK: Get Students Information func getStudentsInformation(completionHandlerForStudentsInformation: (result: [OTMStudentInformation]?, error: NSError?) -> Void) { let method = Methods.StudentLocation let parameters: [String: AnyObject] = [ ParameterKeys.Limit: ParameterValues.Limit, ParameterKeys.Order: "-" + ResponseKeys.UpdatedAt + "," + "-" + ResponseKeys.CreatedAt] taskForGETMethod(method, parameters: parameters, host: .Parse) { (results, error) in guard error == nil else { completionHandlerForStudentsInformation(result: nil, error: error) return } let errorDomain = "getStudentsInformation parsing" guard let studentResults = results[ResponseKeys.StudentResults] as? [[String: AnyObject]] else { completionHandlerForStudentsInformation(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.StudentResults)' in \(results)"])) return } let studentsInfo = OTMStudentInformation.studentsInformationFromResults(studentResults) completionHandlerForStudentsInformation(result: studentsInfo, error: nil) } } // MARK: Get Country Code func getCountryCodeWithStudentInfo(studentInfo: OTMStudentInformation, completionHandlerForCountryCode: (result: String?, error: NSError?) -> Void) { let method = Methods.GeoCode let parameters: [String: AnyObject] = [ ParameterKeys.Key: ParameterValues.Key, ParameterKeys.Latlng: "\(studentInfo.latitude),\(studentInfo.longitude)", ParameterKeys.ResultType: ParameterValues.Country, ParameterKeys.Language: ParameterValues.English ] let errorDomain = "getCountryCode parsing" guard -90 ... 90 ~= studentInfo.latitude && -180 ... 180 ~= studentInfo.longitude else { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Location coordinate: (\(studentInfo.latitude), \(studentInfo.longitude)) out of range: (-90 ~ +90, -180 ~ +180)."])) return } taskForGETMethod(method, parameters: parameters, host: .Google) { (results, error) in guard error == nil else { completionHandlerForCountryCode(result: nil, error: error) return } guard let stauts = results[ResponseKeys.StatusCode] as? String else { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.StatusCode)' in \(results)"])) return } if stauts == ResponseValues.ZeroResults { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "No corresponding country code returned from location coordinate: (\(studentInfo.latitude), \(studentInfo.longitude))."])) return } guard stauts == ResponseValues.OK else { guard let errorMessage = results[ResponseKeys.ErrorMessage] as? String else { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Server returned an error but could not find key '\(ResponseKeys.ErrorMessage)' in \(results)"])) return } completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Server returned an error: \(errorMessage)"])) return } guard let geoCodeResults = results[ResponseKeys.GeoCodeResults] as? [[String: AnyObject]] else { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.GeoCodeResults)' in \(results)"])) return } let targetGeoCodeResult = geoCodeResults[0] guard let addressComponents = targetGeoCodeResult[ResponseKeys.AddressComponents] as? [[String: AnyObject]] else { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.AddressComponents)' in \(targetGeoCodeResult)"])) return } let targetAddressComponent = addressComponents[0] guard let shortName = targetAddressComponent[ResponseKeys.ShortName] as? String else { completionHandlerForCountryCode(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.ShortName)' in \(targetAddressComponent)"])) return } completionHandlerForCountryCode(result: shortName, error: nil) } } // MARK: Get Avatar Image func getAvatarImageWithUniqueKey(uniqueKey: String, completionHandlerForAvatarImage: (image: UIImage?, error: NSError?) -> Void) { let urlExtension = "/udacity-\(uniqueKey)" let parameters: [String: AnyObject] = [ParameterKeys.Size: ParameterValues.Size150] let imageUrl = otmURLFromParameters(parameters, withHost: .Robohash, pathExtension: urlExtension) let errorDomain = "GetUserImage Parsing" OTMClient.sharedInstance().taskForGETImageData(imageUrl) { (data, error) in guard error == nil else { print(errorDomain + error!.localizedDescription) completionHandlerForAvatarImage(image: nil, error: error) return } let errorDomain = "GetImageData Parsing" guard let data = data else { completionHandlerForAvatarImage(image: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "No image data returned."])) return } guard let image = UIImage(data: data) else { completionHandlerForAvatarImage(image: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "No image from image data."])) return } completionHandlerForAvatarImage(image: image, error: nil) } } // MARK: Get User Name func getUserNameWithUniqueKey(uniqueKey: String, completionHandlerForUserName:(result:(String, String)?, error: NSError?) -> Void) { var mutableMethod: String = Methods.UserUniqueKey mutableMethod = subtituteKeyInString(mutableMethod, key: URLKeys.UniqueKey, withValue: uniqueKey)! let parameters = [String: AnyObject]() taskForGETMethod(mutableMethod, parameters: parameters, host: .Udacity) { (results, error) in guard error == nil else { completionHandlerForUserName(result: nil, error: error) return } let errorDomain = "getUserImage parsing" guard let user = results[ResponseKeys.User] as? [String: AnyObject] else { completionHandlerForUserName(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.User)' in \(results)"])) return } guard let firstName = user[ResponseKeys.UserFirstName] as? String else { completionHandlerForUserName(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.UserFirstName)' in \(user)"])) return } guard let lastName = user[ResponseKeys.UserLastName] as? String else { completionHandlerForUserName(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.UserLastName)' in \(user)"])) return } completionHandlerForUserName(result: (firstName, lastName), error: nil) } } // MARK: Query Student Info func queryStudentInfoWithUniqueKey(key: String, completionHandlerForStudentInfo: (result: OTMStudentInformation?, error: NSError?) -> Void) { let method = Methods.StudentLocation let parameters: [String: AnyObject] = [ ParameterKeys.Where: subtituteKeyInString(ParameterValues.UniqueKeyPair, key: URLKeys.UniqueKey, withValue: key)!] taskForGETMethod(method, parameters: parameters, host: .Parse) { (results, error) in guard error == nil else { completionHandlerForStudentInfo(result: nil, error: error) return } let errorDomain = "queryStudentInfo parsing" if let errorString = results[ResponseKeys.Error] as? String { completionHandlerForStudentInfo(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: errorString])) return } guard let studentResults = results[ResponseKeys.StudentResults] as? [[String: AnyObject]] else { completionHandlerForStudentInfo(result: nil, error: NSError(domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not find key '\(ResponseKeys.StudentResults)' in \(results)"])) return } guard !studentResults.isEmpty else { completionHandlerForStudentInfo(result: nil, error: NSError(domain: errorDomain, code: -2000, userInfo: [NSLocalizedDescriptionKey: "No entry in '\(studentResults)"])) return } let studentInfo = OTMStudentInformation(dictionary: studentResults[0]) completionHandlerForStudentInfo(result: studentInfo, error: nil) } } // MARK: Delete User Info func deleteStudentInfoWithObjectId(objectId: String, completionHandlerForDeleteStudentInfo: (success: Bool, error: NSError?) -> Void) { var mutableMethod: String = Methods.StudentLocationObjectId mutableMethod = subtituteKeyInString(mutableMethod, key: URLKeys.ObjectId, withValue: objectId)! let parameters = [String: AnyObject]() taskForDELETEMethod(mutableMethod, parameters: parameters, host: .Parse) { (results, error) in guard error == nil else { completionHandlerForDeleteStudentInfo(success: false, error: error) return } completionHandlerForDeleteStudentInfo(success: true, error: nil) } } // MARK: Post Student Location func postStudentLocation(WithUniqueKey uniqueKey: String, name: (String, String), mapString: String, mediaUrl: String, coordinate: CLLocationCoordinate2D, completionHandlerForPostStudentLocation: (success: Bool, error: NSError?) -> Void) { let method: String = Methods.StudentLocation let parameters = [String: AnyObject]() let jsonBody = "{\"\(JsonBodyKeys.UniqueKey)\": \"\(uniqueKey)\", \"\(JsonBodyKeys.FirstName)\": \"\(name.0)\", \"\(JsonBodyKeys.LastName)\": \"\(name.1)\",\"\(JsonBodyKeys.MapString)\": \"\(mapString)\", \"\(JsonBodyKeys.MediaURL)\": \"\(mediaUrl)\",\"\(JsonBodyKeys.Latitude)\": \(coordinate.latitude), \"\(JsonBodyKeys.Longitude)\": \(coordinate.longitude)}" taskForPOSTMethod(method, parameters: parameters, jsonBody: jsonBody, host: .Parse) { (results, error) in guard error == nil else { completionHandlerForPostStudentLocation(success: false, error: error) return } completionHandlerForPostStudentLocation(success: true, error: nil) } } // MARK: Put Student Location func putStudentLocation(WithStudentInfo studentInfo: OTMStudentInformation, mapString: String, mediaUrl: String, coordinate: CLLocationCoordinate2D, completionHandlerForPutStudentLocation: (success: Bool, error: NSError?) -> Void) { var mutableMethod: String = Methods.StudentLocationObjectId mutableMethod = subtituteKeyInString(mutableMethod, key: URLKeys.ObjectId, withValue: studentInfo.objectID)! let parameters = [String: AnyObject]() let jsonBody = "{\"\(JsonBodyKeys.UniqueKey)\": \"\(studentInfo.uniqueKey)\", \"\(JsonBodyKeys.FirstName)\": \"\(studentInfo.firstName)\", \"\(JsonBodyKeys.LastName)\": \"\(studentInfo.lastName)\",\"\(JsonBodyKeys.MapString)\": \"\(mapString)\", \"\(JsonBodyKeys.MediaURL)\": \"\(mediaUrl)\",\"\(JsonBodyKeys.Latitude)\": \(coordinate.latitude), \"\(JsonBodyKeys.Longitude)\": \(coordinate.longitude)}" taskForPUTMethod(mutableMethod, parameters: parameters, jsonBody: jsonBody, host: .Parse) { (results, error) in guard error == nil else { completionHandlerForPutStudentLocation(success: false, error: error) return } completionHandlerForPutStudentLocation(success: true, error: nil) } } }
// // KeyspaceQuery.swift // scale // // Created by Adrian Herridge on 01/05/2017. // // import Foundation class KeyspaceQuery { init(_ request: Request, params: KeyspaceParams) { } }
// // nav.swift // sample_test // // Created by Catalina Diaz on 12/17/19. // Copyright © 2019 CleverSolve. All rights reserved. // import Foundation import UIKit class nav: UINavigationController{ override func viewDidAppear(_ animated: Bool) { let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "id_main") self.pushViewController(vc, animated: false) } }
// // Constants.swift // Hero Guide // // Created by Thiago Ferrão on 08/07/18. // Copyright © 2018 Thiago Ferrão. All rights reserved. // import UIKit struct Constants { struct API { static let URL = "https://gateway.marvel.com/v1/public" struct KEY { static let PRIVATE = "aba4decb92afadfd60d2d414bb45bbe88110e137" static let PUBLIC = "7e6505c9d7f0e89fac001bb8b163b70a" } struct PATH { static let CHARACTERS = "/characters" } struct PARAMETER { static let LIMIT = "limit" static let OFFSET = "offset" static let API_KEY = "apikey" static let HASH = "hash" static let TIME_STAMP = "ts" static let NAME = "name" } struct LIMIT { static let DEFAULT = 15 } } struct SEGUE_IDENTIFIER { static let TO_CHARACTER = "SegueToCharacterVC" } struct REUSABLE_IDENTIFIER { static let GALLERY_CELL = "GalleryCell" static let GALLERY_SEARCH_CELL = "GallerySearchCell" static let COPYRIGHT_FOOTER_VIEW = "CopyrightFooterView" } struct STORYBOARD_IDENTIFIER { static let MAIN = "Main" } struct VIEW_CONTROLLER_IDENTIFIER { struct MAIN_STORYBOARD { static let GALLERY_SEARCH = "GallerySearchViewController" } } struct COLOR { static let PRIMARY = "color_primary" static let ACCENT = "color_accent" static let BACKGROUND = "color_background" } struct IMAGE { static let APP_ICON = "icon_app" struct MARVEL_PARAMETER { static let STANDARD = "/standard_amazing" static let LANDSCAPE = "/landscape_incredible" } } struct ALPHA { static let ENABLE : CGFloat = 1 static let DISABLE : CGFloat = 0.2 } }
// // GooogeReviewVC.swift // ReviewApp // // Created by Kondya on 13/03/19. // Copyright © 2019 Kondya. All rights reserved. // import UIKit import WebKit protocol GooogeReviewVCDelegate { func getGooogeReviewVCResultSuccess() } class GooogeReviewVC: UIViewController { var delegate: GooogeReviewVCDelegate? var count = 0 @IBOutlet weak var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() self.addBackButton() WebCacheCleaner.clean() webView.navigationDelegate = self webView.allowsBackForwardNavigationGestures = false let url = URL(string: "https:www.gmail.com")! webView.load(URLRequest(url: url)) } func addBackButton() { let backButton = UIButton(type: .custom) backButton.setTitle("Back", for: .normal) backButton.setTitleColor(backButton.tintColor, for: .normal) // You can change the TitleColor backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton) } @objc func backAction(_ sender: UIButton) { let _ = self.navigationController?.popViewController(animated: true) self.delegate?.getGooogeReviewVCResultSuccess() } } extension GooogeReviewVC: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == WKNavigationType.linkActivated { print("link") decisionHandler(WKNavigationActionPolicy.cancel) return } print("no link") print(webView.url ?? nil ?? "kkk") let uuu = "\(String(describing: webView.url ?? nil))" if uuu.contains("https://www.google.com/search?hl="){ self.count = count+1 if self.count >= 11 { // self.navigationController?.popViewController(animated: true) // self.delegate?.getViewControllerResultSuccess() } } print(count) decisionHandler(WKNavigationActionPolicy.allow) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if let host = webView.url?.host { self.navigationItem.title = host if host == "mail.google.com"{ if let url1 = URL(string:"https://search.google.com/local/writereview?placeid=ChIJrTLr-GyuEmsRBfy61i59si0"){ self.webView.load(URLRequest(url: url1)) } } } } } final class WebCacheCleaner { class func clean() { HTTPCookieStorage.shared.removeCookies(since: Date.distantPast) print("[WebCacheCleaner] All cookies deleted") WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in records.forEach { record in WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {}) print("[WebCacheCleaner] Record \(record) deleted") } } } }
// // PersonController.swift // 921 // // Created by Betty on 21/09/2018. // import Foundation import Vapor import FluentPostgreSQL import Leaf struct IndexContext: Encodable { let title: String let people: [Person]? } struct PersonController: RouteCollection { func boot(router: Router) throws { let personRoutes = router personRoutes.post(Person.self, at: "addPerson", use: createHandler) personRoutes.get("getPeople",use:getAllHandler) personRoutes.get("getPerson", Person.parameter, use: getHandler) personRoutes.put("updatePerson", Person.parameter, use: updateHandler) personRoutes.delete("deletePerson", Person.parameter, use: deleteHandler) personRoutes.get("getPersonInView", Person.parameter, use: getInViewHandler) personRoutes.get("getPeopleInView", use:getAllInViewHandler) } func createHandler(_ req: Request, person: Person) throws -> Future<Person> { return person.save(on: req) } func getHandler(_ req: Request) throws -> Future<Person> { return try req.parameters.next(Person.self) } func getAllHandler(_ req: Request) throws -> Future<[Person]> { return Person.query(on: req).all() } func updateHandler(_ req: Request) throws -> Future<Person> { return try flatMap(to: Person.self, req.parameters.next(Person.self), req.content.decode(Person.self)) { person, updatedPerson in person.name = updatedPerson.name person.age = updatedPerson.age return person.save(on: req) } } func deleteHandler(_ req: Request) throws -> Future<HTTPStatus> { return try req.parameters.next(Person.self) .delete(on: req) .transform(to: HTTPStatus.noContent) } func getInViewHandler(_ req: Request) throws -> Future<View> { return try req.parameters.next(Person.self).flatMap({ person in return try req.view().render("getperson", person) }) } func getAllInViewHandler(_ req: Request) throws -> Future<View> { return Person.query(on: req).all().flatMap({ people in let context = IndexContext(title: "People", people: people.isEmpty ? nil : people) return try req.view().render("getpeople", context) }) } }
// // TrackCell.swift // MyMusicApp // // Created by mac on 2020/10/25. // Copyright © 2020 Seokjin. All rights reserved. // import UIKit class TrackCell: UITableViewCell { let thumbnail = UIImageView() let titleLabel = UILabel() let artistLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(thumbnail) contentView.addSubview(titleLabel) contentView.addSubview(artistLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() artistLabel.textColor = .lightGray artistLabel.font = UIFont(name: "Arial", size: 14) artistLabel.frame = CGRect(x: self.frame.minX + 150, y: 45, width: 100, height: 20) titleLabel.font = UIFont.boldSystemFont(ofSize: 20) titleLabel.numberOfLines = 2 titleLabel.frame = CGRect(x: self.frame.minX + 150, y: 5, width: 190, height: 30) thumbnail.frame = CGRect(x: self.frame.minX + 10, y: 5, width: 110, height: 70) } }
// // List_1_00.swift // 100Views // // Created by Mark Moeykens on 6/17/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct List_WithData : View { var data = ["This is the simplest List", "Evans", "Lemuel James Guerrero", "Mark", "Durtschi", "Chase", "Adam", "Rodrigo", "Notice the automatic wrapping when the content is larger"] var body: some View { List(data, id: \.self) { datum in Text(datum) } .font(.largeTitle) // Apply this font style to all items in the list } } #if DEBUG struct List_WithData_Previews : PreviewProvider { static var previews: some View { List_WithData() } } #endif
// // WeatherScrollView.swift // TWeather // // Created by zhangkuo on 16/7/19. // Copyright © 2016年 zhangkuo. All rights reserved. // import UIKit import MJRefresh import Spring class WeatherScrollView: UIScrollView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ // var weatherInfo: WeatherResult? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.mybgclor() showsVerticalScrollIndicator = false setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateWeatherInfo(weatherResult: WeatherResult) { nowLabel1.text = weatherResult.weatherNowShow[0] nowLabel2.text = weatherResult.weatherNowShow[1] nowLabel3.text = weatherResult.weatherNowShow[2] poemLabel1.text = weatherResult.weatherPoem[0] poemLabel2.text = weatherResult.weatherPoem[1] todayLabel1.text = weatherResult.weatherForecasts[0][0] todayLabel2.text = weatherResult.weatherForecasts[0][1] todayLabel3.text = weatherResult.weatherForecasts[0][2] todayLabel4.text = weatherResult.weatherForecasts[0][3] todayLabel5.text = weatherResult.weatherForecasts[0][4] cityLabel.text = weatherResult.city timeLabel.text = weatherResult.time if weatherResult.city == "" { cityOval.hidden = true }else { cityOval.hidden = false } if weatherResult.time == "" { timeOval.hidden = true }else { timeOval.hidden = false } forecast1Label1.text = weatherResult.weatherDate[1] forecast1Label2.text = weatherResult.weatherForecasts[1][0] forecast1Label3.text = weatherResult.weatherForecasts[1][1] forecast1Label4.text = weatherResult.weatherForecasts[1][2] forecast1Label5.text = weatherResult.weatherForecasts[1][3] forecast2Label1.text = weatherResult.weatherDate[2] forecast2Label2.text = weatherResult.weatherForecasts[2][0] forecast2Label3.text = weatherResult.weatherForecasts[2][1] forecast2Label4.text = weatherResult.weatherForecasts[2][2] forecast2Label5.text = weatherResult.weatherForecasts[2][3] forecast3Label1.text = weatherResult.weatherDate[3] forecast3Label2.text = weatherResult.weatherForecasts[3][0] forecast3Label3.text = weatherResult.weatherForecasts[3][1] forecast3Label4.text = weatherResult.weatherForecasts[3][2] forecast3Label5.text = weatherResult.weatherForecasts[3][3] } func pageControl(pageFlag: Bool) { nowContainerView.hidden = !pageFlag poemContainerView.hidden = !pageFlag todayContainerView.hidden = !pageFlag forecastView1.hidden = pageFlag forecastView2.hidden = pageFlag forecastView3.hidden = pageFlag } func setupUI() { //添加子控件 // addSubview(containerView) addSubview(nowContainerView) addSubview(poemContainerView) addSubview(todayContainerView) addSubview(cityTimeContainerView) nowContainerView.addSubview(nowLabel1) nowContainerView.addSubview(nowLabel2) nowContainerView.addSubview(nowLabel3) poemContainerView.addSubview(poemLabel1) poemContainerView.addSubview(poemLabel2) todayContainerView.addSubview(todayLabel1) todayContainerView.addSubview(todayLabel2) todayContainerView.addSubview(todayLabel3) todayContainerView.addSubview(todayLabel4) todayContainerView.addSubview(todayLabel5) cityTimeContainerView.addSubview(cityOval) cityTimeContainerView.addSubview(timeOval) cityTimeContainerView.addSubview(cityLabel) cityTimeContainerView.addSubview(timeLabel) addSubview(forecastView1) addSubview(forecastView2) addSubview(forecastView3) forecastView1.addSubview(forecast1Label1) forecastView1.addSubview(forecast1Label2) forecastView1.addSubview(forecast1Label3) forecastView1.addSubview(forecast1Label4) forecastView1.addSubview(forecast1Label5) forecastView2.addSubview(forecast2Label1) forecastView2.addSubview(forecast2Label2) forecastView2.addSubview(forecast2Label3) forecastView2.addSubview(forecast2Label4) forecastView2.addSubview(forecast2Label5) forecastView3.addSubview(forecast3Label1) forecastView3.addSubview(forecast3Label2) forecastView3.addSubview(forecast3Label3) forecastView3.addSubview(forecast3Label4) forecastView3.addSubview(forecast3Label5) containerView.snp_makeConstraints { (make) in make.edges.equalTo(self) make.height.equalTo(UIScreen.mainScreen().bounds.height) make.width.equalTo(UIScreen.mainScreen().bounds.width) } nowContainerView.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize * 3 + margin * 2, height2)) make.right.equalTo(self).offset(-fontSize*3 - margin) make.top.equalTo(self).offset(height7) } poemContainerView.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize * 2 + margin * 1, height3)) make.right.equalTo(self).offset(-fontSize*3 - margin) make.top.equalTo(nowContainerView.snp_bottom).offset(height7) } todayContainerView.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize * 5 + margin * 4, height2)) make.right.equalTo(self).offset(-fontSize*3 - margin) make.top.equalTo(poemContainerView.snp_bottom).offset(height7) } nowLabel1.snp_makeConstraints { (make) in make.top.right.equalTo(nowContainerView) make.size.equalTo(CGSizeMake(fontSize, height2)) } nowLabel2.snp_makeConstraints { (make) in make.top.equalTo(nowContainerView) make.right.equalTo(nowLabel1.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height2)) } nowLabel3.snp_makeConstraints { (make) in make.top.equalTo(nowContainerView) make.right.equalTo(nowLabel2.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } poemLabel1.snp_makeConstraints { (make) in make.top.right.equalTo(poemContainerView) make.size.equalTo(CGSizeMake(fontSize, height3 + 0.5)) } poemLabel2.snp_makeConstraints { (make) in make.top.equalTo(poemContainerView) make.right.equalTo(poemLabel1.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height3 + 0.5)) } todayLabel1.snp_makeConstraints { (make) in make.top.right.equalTo(todayContainerView) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } todayLabel2.snp_makeConstraints { (make) in make.top.equalTo(todayContainerView) make.right.equalTo(todayLabel1.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } todayLabel3.snp_makeConstraints { (make) in make.top.equalTo(todayContainerView) make.right.equalTo(todayLabel2.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } todayLabel4.snp_makeConstraints { (make) in make.top.equalTo(todayContainerView) make.right.equalTo(todayLabel3.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } todayLabel5.snp_makeConstraints { (make) in make.top.equalTo(todayContainerView) make.right.equalTo(todayLabel4.snp_left).offset(-margin) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } cityTimeContainerView.snp_makeConstraints { (make) in make.bottom.equalTo(todayContainerView) make.left.equalTo(self).offset(margin) make.size.equalTo(CGSizeMake((fontSize - 6) * 2 + 5, height4)) } cityOval.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize - 6, fontSize - 5)) make.top.right.equalTo(cityTimeContainerView) } timeOval.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize - 6, fontSize - 5)) make.top.equalTo(cityTimeContainerView) make.right.equalTo(cityOval.snp_left).offset(-8) } cityLabel.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize - 6, height5 + 0.5)) make.top.equalTo(cityOval.snp_bottom) make.right.equalTo(cityTimeContainerView) } timeLabel.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize - 6, height5 + 0.5)) make.top.equalTo(timeOval.snp_bottom) make.right.equalTo(cityLabel.snp_left).offset(-8) } forecastView1.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize * 5 + margin * 4, height2)) make.right.equalTo(self).offset(-fontSize*3 - margin) make.top.equalTo(self).offset(height7) } forecastView2.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize * 5 + margin * 4, height2)) make.right.equalTo(self).offset(-fontSize*3 - margin) make.top.equalTo(forecastView1.snp_bottom).offset(height7) } forecastView3.snp_makeConstraints { (make) in make.size.equalTo(CGSizeMake(fontSize * 5 + margin * 4, height2)) make.right.equalTo(self).offset(-fontSize*3 - margin) make.top.equalTo(forecastView2.snp_bottom).offset(height7) } forecast1Label1.snp_makeConstraints { (make) in make.top.right.equalTo(forecastView1) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast1Label2.snp_makeConstraints { (make) in make.top.equalTo(forecastView1) make.right.equalTo(forecast1Label1.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast1Label3.snp_makeConstraints { (make) in make.top.equalTo(forecastView1) make.right.equalTo(forecast1Label2.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast1Label4.snp_makeConstraints { (make) in make.top.equalTo(forecastView1) make.right.equalTo(forecast1Label3.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast1Label5.snp_makeConstraints { (make) in make.top.equalTo(forecast1Label4) make.right.equalTo(forecast1Label4.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast2Label1.snp_makeConstraints { (make) in make.top.right.equalTo(forecastView2) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast2Label2.snp_makeConstraints { (make) in make.top.equalTo(forecastView2) make.right.equalTo(forecast2Label1.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast2Label3.snp_makeConstraints { (make) in make.top.equalTo(forecastView2) make.right.equalTo(forecast2Label2.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast2Label4.snp_makeConstraints { (make) in make.top.equalTo(forecastView2) make.right.equalTo(forecast2Label3.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast2Label5.snp_makeConstraints { (make) in make.top.equalTo(forecast2Label4) make.right.equalTo(forecast2Label4.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast3Label1.snp_makeConstraints { (make) in make.top.right.equalTo(forecastView3) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast3Label2.snp_makeConstraints { (make) in make.top.equalTo(forecastView3) make.right.equalTo(forecast3Label1.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast3Label3.snp_makeConstraints { (make) in make.top.equalTo(forecastView3) make.right.equalTo(forecast3Label2.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast3Label4.snp_makeConstraints { (make) in make.top.equalTo(forecastView3) make.right.equalTo(forecast3Label3.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } forecast3Label5.snp_makeConstraints { (make) in make.top.equalTo(forecast3Label4) make.right.equalTo(forecast3Label4.snp_left).offset(-margin+8) make.size.equalTo(CGSizeMake(fontSize, height2 + 0.5)) } } //MARK: - 懒加载 lazy var containerView: UIView = { let view = UIView() view.backgroundColor = UIColor.mybgclor() view.alpha = 0 return view }() lazy var nowContainerView: SpringView = { let view = SpringView() // view.backgroundColor = UIColor.yellowColor() // view.layer.animation = "Shake" // view.curve = "EaseOut" view.alpha = 1 return view }() lazy var poemContainerView: SpringView = { let view = SpringView() // view.backgroundColor = UIColor.greenColor() return view }() lazy var todayContainerView: SpringView = { let view = SpringView() // view.backgroundColor = UIColor.blueColor() return view }() lazy var cityTimeContainerView: SpringView = { let view = SpringView() // view.backgroundColor = UIColor.blueColor() return view }() //当天天气 lazy var nowLabel1: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var nowLabel2: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var nowLabel3: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() //诗句 lazy var poemLabel1: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor2() label.numberOfLines = 10 return label }() lazy var poemLabel2: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor2() label.numberOfLines = 10 return label }() //今日天气 lazy var todayLabel1: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var todayLabel2: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var todayLabel3: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var todayLabel4: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var todayLabel5: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var cityLabel: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize - 6) label.textColor = UIColor.mycolor2() label.numberOfLines = 3 return label }() lazy var timeLabel: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize - 6) label.textColor = UIColor.mycolor2() label.numberOfLines = 3 return label }() lazy var cityOval: UIImageView = { let image = UIImageView(image: UIImage(named: "oval")) image.hidden = true return image }() lazy var timeOval: UIImageView = { let image = UIImageView(image: UIImage(named: "oval")) image.hidden = true return image }() //第二页的控件 lazy var forecastView1: SpringView = { let view = SpringView() return view }() lazy var forecastView2: SpringView = { let view = SpringView() return view }() lazy var forecastView3: SpringView = { let view = SpringView() return view }() //今日天气 lazy var forecast1Label1: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast1Label2: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast1Label3: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast1Label4: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast1Label5: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast2Label1: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast2Label2: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast2Label3: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast2Label4: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast2Label5: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast3Label1: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast3Label2: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast3Label3: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast3Label4: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() lazy var forecast3Label5: TopLabel = { let label = TopLabel() label.font = UIFont(name: "FZLongZhaoT-R-GB", size: fontSize) label.textColor = UIColor.mycolor3() label.numberOfLines = 10 return label }() }
// // LogInView.swift // // Created by PW486 on 2019/09/14. // Copyright © 2019 PW486. All rights reserved. // import Alamofire import SwiftUI import SwiftyJSON struct LogInView: View { @EnvironmentObject private var globalState: GlobalState @Environment(\.presentationMode) private var presentation: Binding<PresentationMode> @State private var showModal = false var body: some View { VStack(alignment: .center, spacing: 20) { Divider() .background(Color("headline")) Text("H & F Scoring") .font(.custom("Poppins-SemiBold", size: 36)) .foregroundColor(Color("headline")) Divider() .background(Color("headline")) Spacer() // Button(action: {}) { // Text("Sign in with Google") // } Spacer() } .padding(48) .sheet(isPresented: $showModal, content: { RegisterView().environmentObject(self.globalState) }) } } struct LogInViewPreviews: PreviewProvider { static var previews: some View { LogInView().environmentObject(GlobalState()) } }
// // PrepareForSimulation.swift // Jupiter // // Created by adulphan youngmod on 18/8/18. // Copyright © 2018 goldbac. All rights reserved. // import Foundation import UIKit extension SimulateData: AccessFiles { func prepareForSimulation() { clearDocumentFolder() createDummyImage() } private func createDummyImage() { let image = UIImage(named: "photo") let ciImage = CIImage(image: image!) let colorSpace = CGColorSpaceCreateDeviceRGB() let recordID = UUID().uuidString let fileName = recordID + ".heic" let context = CIContext(options: nil) let heifData = context.heifRepresentation(of: ciImage!, format: CIFormat.ARGB8, colorSpace: colorSpace, options: [kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption: 0.4])! saveImageTo(data: heifData, fileName: fileName) SimulateData.dummyImageID = fileName } }
//: [Previous](@previous) import Foundation class BitMap { var array:[Int64] let bitPerUnit:Int = 64 let shift:Int = 6 let mask:Int = 0x3F var size: Int = 0 init(_ capcity: Int) { size = capcity array = [Int64](repeating: 0, count: 1 + capcity / bitPerUnit) } /*: * 定位Bitmap某一位所对应的word * @param bitIndex 位图的第bitIndex位 */ func getIndex(num:Int) -> Int { return num >> shift ///右移6位,相当于除以64 } func setBit(bitIndex: Int) { guard bitIndex < size else { print("超过bitmap有效范围") return } let index = getIndex(num: bitIndex) array[index] |= (1 << (bitIndex & mask )) } func getBit(bitIndex: Int) -> Bool { guard bitIndex < size else { print("超过bitmap有效范围") return false } let index = getIndex(num: bitIndex) return array[index] & (1<<(bitIndex & mask)) != 0 } func clear(bitIndex: Int) { guard bitIndex < size else { print("超过bitmap有效范围") return } let index = getIndex(num: bitIndex) array[index] &= ~(1<<(bitIndex & mask)) } } let bitMap = BitMap(400) bitMap.setBit(bitIndex: 20) bitMap.getBit(bitIndex: 20) bitMap.array bitMap.setBit(bitIndex: 21) bitMap.getBit(bitIndex: 21) bitMap.array bitMap.setBit(bitIndex: 99) bitMap.getBit(bitIndex: 99) bitMap.array bitMap.setBit(bitIndex: 98) bitMap.getBit(bitIndex: 88) bitMap.array bitMap.clear(bitIndex: 20) bitMap.array bitMap.clear(bitIndex: 21) bitMap.array for index in (0..<200) { bitMap.setBit(bitIndex: index * 2) } for index in 0..<500 { print("\(bitMap.getBit(bitIndex: index )) \t") } //: [Next](@next)
// // LoginController.swift // Lakefield Library // // Created by Faraaz Khan on 12/27/17. // Copyright © 2017 Faraaz. All rights reserved. // import UIKit class LoginController: UIViewController { @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // make the corners round loginButton.layer.cornerRadius = 5 loginButton.clipsToBounds = true self.hideKeyboardWhenTappedAround() } // function called when the user hits the forgot password @IBAction func handleForgot(_ sender: Any) { show(ViewController: "ForgotScene") } // function called when the user hits the hneed an account button @IBAction func handleRequest(_ sender: Any) { show(ViewController: "RequestScene") } // function called when the user hits the sign in button @IBAction func handleLogin(_ sender: Any) { let spinner = displaySpinner(onView: self.view) guard let email = self.email.text else {print("There was no email entered"); return} guard let password = self.password.text else {print("There was no password entered"); return} // make sure the given input is an email if email.contains("@") && email.contains(".") { // make sure the password is six or more digits if password.count >= 6 { // sign in the user fAuth.signIn(withEmail: email, password: password, completion: { (user, err) in if err == nil { guard let uid = user?.uid else {print("Cannot get UID"); return} fData.child("users").child(uid).observeSingleEvent(of: .value) { (snapshot) in // update the database with the new values guard let values = snapshot.value as? NSDictionary else {print("Cannot get values"); return} guard let id = values["ID"] as? String else {print("Cannot get ID"); return} guard let firstname = values["firstname"] as? String else {print("Cannot get first name"); return} guard let type = values["type"] as? String else {print("Cannot get type"); return} fUser = User(id: id, firstname: firstname, type: type) self.dismiss(animated: true, completion: nil) let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainScene") let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.setRootViewController(vc, animated: true) print("User successfully signed into the system") self.removeSpinner(spinner: spinner) } } else { self.alert(title: "Invalid Credentials", message: "The given email or password is incorrect or there is no internet connection.") self.removeSpinner(spinner: spinner) } }) } else { alert(title: "Password too short", message: "The password must be at least six characters.") self.removeSpinner(spinner: spinner) } } else { alert(title: "Invalid email", message: "The given input is not an email.") self.removeSpinner(spinner: spinner) } } }
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// import Cocoa import SwiftyDropbox class ViewController: NSViewController { @IBOutlet weak var oauthCodeFlowLinkButton: NSButton! @IBOutlet weak var oauthUnlinkButton: NSButton! @IBOutlet weak var runApiTestsButton: NSButton! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear() { } @IBAction func oauthCodeFlowLinkButtonPressed(_ sender: AnyObject) { if DropboxClientsManager.authorizedClient == nil && DropboxClientsManager.authorizedTeamClient == nil { let scopeRequest: ScopeRequest // note if you add new scopes, you need to relogin to update your token switch(appPermission) { case .fullDropboxScoped: scopeRequest = ScopeRequest(scopeType: .user, scopes: DropboxTester.scopes, includeGrantedScopes: false) case .fullDropboxScopedForTeamTesting: scopeRequest = ScopeRequest(scopeType: .team, scopes: DropboxTeamTester.scopes, includeGrantedScopes: false) } DropboxClientsManager.authorizeFromControllerV2( sharedApplication: NSApplication.shared, controller: self, loadingStatusDelegate: nil, openURL: {(url: URL) -> Void in NSWorkspace.shared.open(url)}, scopeRequest: scopeRequest ) } } @IBAction func oauthUnlinkButtonPressed(_ sender: AnyObject) { DropboxClientsManager.unlinkClients() checkButtons() } @IBAction func runApiTestsButtonPressed(_ sender: AnyObject) { let unlink = { DropboxClientsManager.unlinkClients() self.checkButtons() exit(0) } switch(appPermission) { case .fullDropboxScoped: DropboxTester().testAllUserEndpoints(asMember: false, nextTest:unlink) case .fullDropboxScopedForTeamTesting: DropboxTeamTester().testTeamMemberFileAcessActions({ DropboxTeamTester().testTeamMemberManagementActions(unlink) }) } } func checkButtons() { if DropboxClientsManager.authorizedClient != nil || DropboxClientsManager.authorizedTeamClient != nil { oauthCodeFlowLinkButton.isHidden = true oauthUnlinkButton.isHidden = false runApiTestsButton.isHidden = false } else { oauthCodeFlowLinkButton.isHidden = false oauthUnlinkButton.isHidden = true runApiTestsButton.isHidden = true } } /** To run these unit tests, you will need to do the following: Navigate to TestSwifty/ and run `pod install` to install AlamoFire dependencies. There are three types of unit tests here: 1.) Regular Dropbox User API tests (requires app with 'Full Dropbox' permissions) 2.) Dropbox Business API tests (requires app with 'Team member file access' permissions) 3.) Dropbox Business API tests (requires app with 'Team member management' permissions) To run all of these tests, you will need three apps, one for each of the above permission types. You must test these apps one at a time. Once you have these apps, you will need to do the following: 1.) Fill in user-specific data in `TestData` and `TestTeamData` in TestData.swift 2.) For each of the above apps, you will need to add a user-specific app key. For each test run, you will need to call `DropboxClientsManager.setupWithAppKey` (or `DropboxClientsManager.setupWithTeamAppKey`) and supply the appropriate app key value, in AppDelegate.swift 3.) Depending on which app you are currently testing, you will need to toggle the `appPermission` variable in AppDelegate.swift to the appropriate value. 4.) For each of the above apps, you will need to add a user-specific URL scheme in Info.plist > URL types > Item 0 (Editor) > URL Schemes > click '+'. URL scheme value should be 'db-<APP KEY>' where '<APP KEY>' is value of your particular app's key To create an app or to locate your app's app key, please visit the App Console here: https://www.dropbox.com/developers/apps */ // Test user app with 'Full Dropbox' permission }
import UIKit class MSettingsMenuItem { weak var cell:VSettingsCell! weak var controller:CSettings! let reusableIdentifier:String let cellHeight:CGFloat init(reusableIdentifier:String, cellHeight:CGFloat) { self.reusableIdentifier = reusableIdentifier self.cellHeight = cellHeight } //MARK: public func config(cell:VSettingsCell, controller:CSettings) { self.cell = cell self.controller = controller } func selected() { } }
// // FaceTrackingManager.swift // ARWig // // Created by Esteban Arrúa on 11/12/18. // Copyright © 2018 Hattrick It. All rights reserved. // import Foundation import Vision class FaceTrackingManager { // MARK: - Singleton static let sharedInstance = FaceTrackingManager() // MARK: - Properties private let faceDetectionRequest: VNDetectFaceLandmarksRequest private let faceDetectionHandler: VNSequenceRequestHandler init() { faceDetectionRequest = VNDetectFaceLandmarksRequest() faceDetectionHandler = VNSequenceRequestHandler() } func trackFaces(pixelBuffer: CVPixelBuffer) -> [VNFaceObservation] { try? faceDetectionHandler.perform([faceDetectionRequest], on: pixelBuffer, orientation: .right) guard let bondingBoxes = faceDetectionRequest.results as? [VNFaceObservation] else { return [] } return bondingBoxes } func getFaces(_ faceObservations: [VNFaceObservation], resolution: CGSize) -> [Face2D] { var faces: [Face2D?] = [] for faceObservation in faceObservations { faces.append(Face2D(for: faceObservation, displaySize: resolution)) } return faces.compactMap({ $0 }) } }
// // TamiyaRequest.swift // Mini4wdPaymentManager // // Created by beryu on 2017/05/06. // Copyright © 2017年 blk. All rights reserved. // import APIKit protocol TamiyaRequest: Request { } extension TamiyaRequest { var baseURL: URL { return URL(string: "http://www.tamiya.com")! } } struct TamiyaResponse { var id: String var name: String? var description: String? var price: Int = 0 init?(id: String, htmlString: String) { // id self.id = id let targetString = htmlString.replacingOccurrences(of: "\n", with: "") // name do { let regex = try NSRegularExpression(pattern: "<title>(.*)</title>", options: []) let targetStringRange = NSRange(location: 0, length: targetString.characters.count) let matches = regex.matches(in: targetString, options: [], range: targetStringRange) if matches.count > 0 { self.name = (targetString as NSString).substring(with: matches[0].rangeAt(1)) } } catch let error { print("[ERROR] \(error)") } // description do { let regex = try NSRegularExpression(pattern: "<td><font size=\"2\" style=\"line-height:140%;\">(.*)(</font></td></tr></table>)", options: []) let targetStringRange = NSRange(location: 0, length: targetString.characters.count) let matches = regex.matches(in: targetString, options: [], range: targetStringRange) if matches.count > 0 { self.description = (targetString as NSString).substring(with: matches[0].rangeAt(1)).replacingOccurrences(of: "<br>", with: "\n") } } catch let error { print("[ERROR] \(error)") } // price do { let regex = try NSRegularExpression(pattern: "([0-9,]+)円", options: []) let targetStringRange = NSRange(location: 0, length: targetString.characters.count) let matches = regex.matches(in: targetString, options: [], range: targetStringRange) if matches.count > 0 { self.price = Int((targetString as NSString).substring(with: matches[0].rangeAt(1)).replacingOccurrences(of: ",", with: "")) ?? 0 } } catch let error { print("[ERROR] \(error)") } } } struct GetPartRequest: TamiyaRequest { typealias Response = TamiyaResponse var method: HTTPMethod { return .get } var id: String var path: String { return "/japan/products/\(self.id)/index.htm" } var dataParser: DataParser = StringDataParser() init(id: String) { self.id = id } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { guard let htmlString = object as? String, let response = TamiyaResponse(id: self.id, htmlString: htmlString) else { throw ResponseError.unexpectedObject(object) } return response } }
// // AddToCartButton.swift // Plantza // // Created by Satya Prakash Sahu on 19/09/21. // import SwiftUI struct AddToCartButton: View { var body: some View { HStack(alignment: .center, spacing: 5.0) { LinearGradient(gradient: Gradient(colors: [Color("AccentColor"), Color("Primary")]), startPoint: .leading, endPoint: .trailing) .mask( Group { Spacer() Image(systemName: "bag.badge.plus") .font(.title3.weight(.light)) .padding(.horizontal, 4) Text("Add to Cart") .font(.subheadline) .fontWeight(.semibold) Spacer() } .offset(x:-10) ) // .frame(width:300, height: 44.0) } .padding(.vertical, 12) .background(Color("Background 1 Light").opacity(0.2)) .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) .overlay( RoundedRectangle(cornerRadius: 20, style: .continuous) .stroke(Color.black.opacity(0.2),lineWidth: 1.0) ) .frame(width:145) } } struct AddToCartButton_Previews: PreviewProvider { static var previews: some View { AddToCartButton() } }
// // TextManager.swift // Enzo's Sorrow // // Created by Felipe Borges on 29/08/16. // Copyright © 2016 Felipe Borges. All rights reserved. // import Foundation import SpriteKit class TextManager: NSObject { var text: String? var textTimer: NSTimer? var currentCharacter: Int? var labels : [SKLabelNode] = [SKLabelNode]() var currentLabel = 0 var allowedWidth: CGFloat? var completionHandler: ()->()? = {return} func exhibitText(labels: [SKLabelNode], text: String, time: Double, allowedWidth: CGFloat? = nil, completionHandler: ()->()?) { currentCharacter = -1 currentLabel = 0 self.completionHandler = completionHandler self.text = text self.labels = labels let timePerCharacter = time / Double(text.characters.count) textTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(timePerCharacter), target: self, selector: #selector(TextManager.nextCharacter), userInfo: nil, repeats: true) } func nextCharacter() { if currentCharacter >= text!.characters.count - 1 { stop() completionHandler() currentCharacter = -1 } else { currentCharacter = currentCharacter! + 1 labels[currentLabel].text?.append(self.text![currentCharacter!]) } if labels[currentLabel].frame.width >= allowedWidth && labels.count >= currentLabel + 1 && labels[currentLabel].text?.characters.last == " " { currentLabel += 1 } } func stop() { textTimer?.invalidate() } } extension String { subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = startIndex.advancedBy(r.startIndex) let end = start.advancedBy(r.endIndex - r.startIndex) return self[Range(start ..< end)] } }
// // ProductsRepository.swift // B&W // // Created by Dalia on 17/09/2020. // Copyright © 2020 Artemis Simple Solutions Ltd. All rights reserved. // import Foundation protocol ProductsRepository { func fetchProductsList(query: ProductQuery, completion: @escaping (Result<Products, Error>) -> Void) -> Cancellable? }
// // GistEntity.swift // GistsApp // // Created by Nik on 28.07.2020. // Copyright © 2020 Nik. All rights reserved. // import Foundation class GistEntity: NSObject { var idItem: String? var user: UserEntity? var descript: String? var files = [FileEntity]() var comments = [CommitEntity]() }
// // UIViewController+CJToast.m // CJUIKitDemo // // Created by ciyouzen on 2019/4/19. // Copyright © 2019 dvlproad. All rights reserved. // import UIKit private var cjChrysanthemumHUDKey: Void? extension UIViewController { //@property (nonatomic, assign, readonly) BOOL isCJChrysanthemumHUDShowing; /**< 是否"菊花HUD"在显示中 */ /// "菊花HUD" var cjChrysanthemumHUD: MBProgressHUD { get { var hud = objc_getAssociatedObject(self, &cjChrysanthemumHUDKey) as? MBProgressHUD if hud == nil { hud = MBProgressHUD.init(view: self.view) hud?.backgroundView.style = .solidColor hud?.backgroundView.color = UIColor(white: 0, alpha: 0.1) hud?.contentColor = UIColor.white //等待框文字颜色 hud?.bezelView.backgroundColor = UIColor(white: 0, alpha: 0.76) //等待框背景色 hud?.removeFromSuperViewOnHide = true objc_setAssociatedObject(self, &cjChrysanthemumHUDKey, hud, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return hud! } } /// 显示"菊花HUD"视图 func cj_showChrysanthemumHUD(startProgressMessage: String, animated: Bool) { self.cjChrysanthemumHUD.label.text = startProgressMessage self.view.addSubview(self.cjChrysanthemumHUD) self.cjChrysanthemumHUD.show(animated: animated) } /// 更新"菊花HUD"文本 func cj_updateChrysanthemumHUD(progressingMessage: String) { self.cjChrysanthemumHUD.label.text = progressingMessage } /// 隐藏"菊花HUD"视图 func cj_hideChrysanthemumHUD(animated:Bool, afterDelay:TimeInterval) { self.cjChrysanthemumHUD.hide(animated: animated, afterDelay: afterDelay) } }
// // Vertex.swift // HelloMetal // // Created by Andrew Bowers on 8/17/15. // Copyright (c) 2015 Razeware LLC. All rights reserved. // /* This is a structure that will store the position and color of each vertetx. floatBuffer() is a method that returns the vertex data as an array of floats in strict order */ struct Vertex { var x, y, z: Float // position data var r, g, b, a: Float // color data var s, t: Float // texture coordinates func floatBuffer() -> [Float] { return [x, y, z, r, g, b, a, s, t] } };
// // YouTubeAPI+Videolist.swift // YouTubeAPI // // Created by Shlykov Danylo on 6/18/20. // Copyright © 2020 Shlykov Danylo. All rights reserved. // import Moya extension BackendAPI { class Videolist: BaseTokenApi { private struct VideolistResponse: Decodable { let videolist: [VideoListItem] enum CodingKeys: String, CodingKey { case videolist = "items" } } private let provider = MoyaProvider<YouTubeService>() func getVideolist(id: [String], onComplete: @escaping () -> Void, onSuccess: @escaping ([VideoListItem]) -> Void, onError: @escaping OnErrorCompletion) { request = provider.request(.getVideolist(token: token, videoIds: id), completion: { result in onComplete() BaseApi.mapResult(result, intoItemOfType: VideolistResponse.self, onSuccess: { messagesResponse in onSuccess(messagesResponse.videolist) }, onError: onError) }) } } }
// // ViewController.swift // SafariTNG-Swift // // Created by Peter Hitchcock on 10/1/14. // Copyright (c) 2014 Peter Hitchcock. All rights reserved. // import UIKit class ViewController: UIViewController, UIWebViewDelegate, UITextFieldDelegate { //IBOutlets @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() self.loadURL() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webViewDidStartLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webViewDidFinishLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func webView(webView: UIWebView, didFailLoadWithError error: NSError) { var alert = UIAlertView(title: "title", message: "message", delegate: self, cancelButtonTitle: "cancel") alert.show() } func textFieldShouldReturn(textField: UITextField) -> Bool { let urlString = textField.text loadHomePage(urlString) return true } func loadHomePage(urlString: NSString) { let url = NSURL(string: urlString) let urlRequest = NSURLRequest(URL: url) self.webView.loadRequest(urlRequest) } func loadURL() { self.loadHomePage("http://www.google.com") } }
// // AppView.swift // Ursus Chat // // Created by Daniel Clelland on 29/06/20. // Copyright © 2020 Protonome. All rights reserved. // import SwiftUI struct AppView: View { @EnvironmentObject var store: AppStore var body: some View { ErrorView(error: store.state.errors.first) { RootView() } } }
import Foundation protocol PinCodeScreenInteractorInput: class { func verify(pinCode: String) func save(pinCode: String) }
// // Star.swift // Colorspin // // Created by Anand Kumar on 7/29/18. // Copyright © 2018 Anand Kumar. All rights reserved. // import Foundation import UIKit enum StarType: String { case bronze case silver case gold var color: UIColor { return UIColor(name: self.rawValue) ?? .black } } struct Star { var scoreToReach: Int var type: StarType } // MARK: - JSON extension Star: JSONParser { init(json: JSON?) throws { guard let json = json else { throw JSONParseError.empty } guard let scoreToReach = json["scoreThreshold"] as? Int, let typeValue = json["type"] as? String, let type = StarType(rawValue: typeValue) else { throw JSONParseError.fail } self.init(scoreToReach: scoreToReach, type: type) } } // MARK: - Equatable extension Star: Equatable { static func == (lhs: Star, rhs: Star) -> Bool { return lhs.scoreToReach == rhs.scoreToReach && lhs.type == rhs.type } }
// // LoginViewController.swift // AWSUserPoolsSwift3 // // Created by Matthew Pileggi on 10/25/16. // Copyright © 2016 Matthew Pileggi. All rights reserved. // import UIKit import AWSCognitoIdentityProvider class LoginViewController: UIViewController, AWSCognitoIdentityPasswordAuthentication { //MARK: Outlets @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! //MARK: Actions @IBAction func login() { let authDetails = AWSCognitoIdentityPasswordAuthenticationDetails(username: username.text ?? "", password: password.text ?? "") self.passwordAuthenticationCompletion!.trySetResult(authDetails) } @IBAction func signUp() { self.performSegue(withIdentifier: "sign up", sender: nil) } @IBAction func forgotPassword() { handleForgotPassword() } //MARK: AWSCognitoIdentityPasswordAuthentication var passwordAuthenticationCompletion: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>? func getDetails(_ authenticationInput: AWSCognitoIdentityPasswordAuthenticationInput, passwordAuthenticationCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>) { self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource } func didCompleteStepWithError(_ error: Error) { //the following is necessary because somehow error is coming back nil even though it's not listed as an optional. AWS will probably fix this before the beta ends let optionalError: Error? optionalError = error if optionalError != nil { let AWSError = optionalError!.getAWSError() if AWSError.type == "UserNotConfirmedException" { handleUnverifiedUser() return } let alertController = UIAlertController(title: "Error", message: AWSError.message, preferredStyle: .alert) alertController.addDismissAction() self.presentOnMain(viewController: alertController) } else { self.presentingViewController?.dismiss(animated: true, completion: nil) } } //MARK: Unverified fileprivate func handleUnverifiedUser(){ AppDelegate.instance.pool?.getUser(username.text!).resendConfirmationCode() let helper = VerificationHelper(viewController: self, username: username.text!) { result in if result == .verified { self.login() }//else do nothing } helper.verify(message: "\(username.text!) is unverified. We've resent the verification code to your email on file. Please enter it below.") } //MARK: Forgot Password fileprivate func handleForgotPassword(){ let forgotPasswordHelper = ForgotPasswordHelper(viewController: self) { result in } forgotPasswordHelper.promptForUsername() } }
// // PC_Bullet.swift // TwinStick_Shooter // // Created by William Leet on 2/2/20. // Copyright © 2020 William Leet. All rights reserved. // // Basic 'Bullet' class used by enemies and player alike. import UIKit import SpriteKit import GameplayKit class Bullet: SKSpriteNode{ var alive = true var damage: Int! private var bounces = false var hitbox: CGSize! var game_scene: GameScene! convenience init(scale: CGFloat, sprite: String, dmg: Int, type: String, game_world: GameScene){ self.init(imageNamed: sprite) self.setScale(scale) damage = dmg game_scene = game_world game_world.addChild(self) //Physicsbodies from textures appear to go off of the original sprite size unless specified //Ergo, I have created a "hitbox" CGsize that scales with the sprite to build the body from hitbox = self.texture!.size() hitbox.width *= scale hitbox.height *= scale self.physicsBody = SKPhysicsBody(circleOfRadius: hitbox.height * 0.5) self.physicsBody!.affectedByGravity = false // 'Restitution' determines how much momentum is gained or lost upon collision. // I have set it to 1, meaning that velocity is neither gained nor lost when a bullet hits a wall. Lets them ricochet semi-usefully, if I want a bullet to do that. self.physicsBody!.restitution = 1.0 if type == "PC"{ self.physicsBody!.categoryBitMask = CollisionType.Player_Bullet.rawValue self.physicsBody!.collisionBitMask = CollisionType.Wall.rawValue self.physicsBody!.contactTestBitMask = CollisionType.Enemy.rawValue | CollisionType.Wall.rawValue } else if type == "Enemy"{ self.physicsBody!.categoryBitMask = CollisionType.Enemy_Bullet.rawValue self.physicsBody!.collisionBitMask = CollisionType.Wall.rawValue self.physicsBody!.contactTestBitMask = CollisionType.Player.rawValue | CollisionType.Wall.rawValue | CollisionType.Blank.rawValue } //Sets zposition as "Bullet" type self.zPosition = ZPositions.Bullet.rawValue } func impact(){ self.physicsBody = nil self.removeFromParent() } //I don't really want anything changing these variables. Ergo, they're private with getters. func can_bounce() -> Bool { return bounces } func get_damage() -> Int{ return damage } //Called when the bullet bounces off of something. Might well need this at some point. func bounced(){ return } }
// // DefViewController.swift // Emojinary // // Created by Wade Winright on 11/01/2018. // Copyright © 2018 Fuquov Jackazh. All rights reserved. // import UIKit class DefViewController: UIViewController { @IBOutlet weak var defLabel: UILabel! @IBOutlet weak var emojizzLabel: UILabel! var emoji = "NO EMOJI" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. emojizzLabel.text = emoji if emoji == "💩" { defLabel.text = "This is shit!" } else if emoji == "⚓️" { defLabel.text = "The anchor that holds us near to land" } else if emoji == "🐋" { defLabel.text = "The Majestic whale should be honored" } else if emoji == "😕" { defLabel.text = "Everything is wierd in it's own way" } else if emoji == "🙁" { defLabel.text = "This to shall pass" } else if emoji == "🤬" { defLabel.text = "You are not to be f**ked with" } else if emoji == "👾" { defLabel.text = "They will reveal themselves" } else if emoji == "🤷‍♀️" { defLabel.text = "I have no idea" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // ShadowView.swift // App Store // // Created by Chidi Emeh on 1/12/18. // Copyright © 2018 Chidi Emeh. All rights reserved. // import UIKit class ShadowView: UIView { override func awakeFromNib() { super.awakeFromNib() } func setUpShadow(){ self.clipsToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.5 self.layer.shadowOffset = CGSize(width: 0.9, height: 9.5) //11 self.layer.shadowRadius = 10 //18 self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10).cgPath } }
// // Background.swift // Inspiration // // Created by Konstantin Khokhlov on 10.05.17. // Copyright © 2017 Konstantin Khokhlov. All rights reserved. // import UIKit struct Background { // MARK: - Properties var image: UIImage // MARK: - Methods /// Requests a image. /// /// - Parameters: /// - url: - The URL to be retrieved. /// - completion: - Completion handler. static func getImage(from url: URL, completion: @escaping ((Background) -> Void)) { URLSession(configuration: .ephemeral).dataTask(with: url) { (data, _, error) in guard error == nil else { return } guard let data = data, let image = UIImage(data: data) else { return } completion(Background(image: image)) }.resume() } }
// // TextCell.swift // TTGXApp // // Created by 汪红亮 on 2017/7/19. // Copyright © 2017年 rekuu. All rights reserved. // import UIKit class TextCell: UITableViewCell { @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblText: UILabel! @IBOutlet weak var lblComment: UILabel! 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 } }