text
stringlengths
8
1.32M
// // HealthKitTests.swift // Pulmonis // // Created by Manivannan Solan on 25/12/2016. // Copyright © 2016 Manivannan Solan. All rights reserved. // import XCTest import HealthKit class HealthKitTests: XCTestCase { var healthStore : HKHealthStore? override func setUp() { super.setUp() healthStore = HKHealthStore() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSaveAndRetreivePeakFlowDataFromHealthApp() { var count : Int? if let peakFlowType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate) { let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let query = HKSampleQuery(sampleType: peakFlowType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in XCTAssert(error == nil) count = tmpResult?.count } healthStore?.execute(query) } if let peakFlowType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate) { let object = HKQuantitySample(type: peakFlowType, quantity: HKQuantity.init(unit: HKUnit.liter().unitDivided(by: HKUnit.minute()), doubleValue: 2.5), start: Date(), end: Date()) healthStore?.save(object, withCompletion: { (success, error) -> Void in XCTAssert(error == nil) XCTAssert(success) }) } if let peakFlowType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate) { let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let query = HKSampleQuery(sampleType: peakFlowType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in if error != nil { XCTFail() return } XCTAssert(count!+1 == tmpResult?.count) self.healthStore?.delete((tmpResult?.first)!, withCompletion: { (success, error) in XCTAssert(success) XCTAssert(error == nil) }) } healthStore?.execute(query) } } }
/* * Copyright (c) 2012-2020 MIRACL UK Ltd. * * This file is part of MIRACL Core * (see https://github.com/miracl/core). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public struct CONFIG_CURVE{ static public let WEIERSTRASS=0 static public let EDWARDS=1 static public let MONTGOMERY=2 static public let NOT=0 static public let BN=1 static public let BLS12=2 static public let BLS24=3 static public let BLS48=4 static public let D_TYPE=0 static public let M_TYPE=1 static public let POSITIVEX=0 static public let NEGATIVEX=1 static public let CURVETYPE = @CT@ static public let CURVE_A = @CA@ static public let CURVE_PAIRING_TYPE = @PF@ static public let SEXTIC_TWIST = @ST@ static public let SIGN_OF_X = @SX@ static public let ATE_BITS = @AB@ static public let HTC_ISO = @HC@ static public let HTC_ISO_G2 = @HC2@ static public let HASH_TYPE = @HT@ static public let AESKEY = @AK@ static let ALLOW_ALT_COMPRESS = false static let USE_GLV = true static let USE_GS_G2 = true static let USE_GS_GT = true }
// // FilterControllCell.swift // GV24 // // Created by dinhphong on 8/30/17. // Copyright © 2017 admin. All rights reserved. // import Foundation import UIKit class FilterControllCell : UITableViewCell { var title: String = "Vị trí" { didSet{ labelTitle.text = title } } var status: String = "Hiện tại" { didSet{ labelStatus.text = status } } private let labelTitle: UILabel = { let lb = UILabel() lb.translatesAutoresizingMaskIntoConstraints = false lb.font = UIFont(name: "SFUIText-Light", size: 15) lb.textColor = .lightGray return lb }() private let labelStatus: UILabel = { let lb = UILabel() lb.translatesAutoresizingMaskIntoConstraints = false lb.font = UIFont(name: "SFUIText-Light", size: 13) lb.textColor = .lightGray return lb }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.accessoryType = .disclosureIndicator self.selectionStyle = .none setupView() } override func layoutSubviews() { super.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupView() { self.addSubview(labelTitle) self.addSubview(labelStatus) labelTitle.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true labelTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true labelStatus.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true labelStatus.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -30).isActive = true } }
// // GoodButton.swift // CheTamUHohlov // // Created by Roman.Safin on 1/17/16. // Copyright © 2016 Roman.Safin. All rights reserved. // import UIKit @IBDesignable class GoodButton: UIButton { @IBInspectable var borderWidth:CGFloat = 0.0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor:UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var highlightedBackgroundColor :UIColor? @IBInspectable var nonHighlightedBackgroundColor :UIColor? override var highlighted :Bool { get { return super.highlighted } set { if newValue { self.backgroundColor = highlightedBackgroundColor } else { self.backgroundColor = nonHighlightedBackgroundColor } super.highlighted = newValue } } }
// // UploadToCloud.swift // Jupiter // // Created by adulphan youngmod on 14/9/18. // Copyright © 2018 goldbac. All rights reserved. // import Foundation import CloudKit class UploadOperation: CKModifyRecordsOperation { override func main() { name = "uploadOperation" setupRecords() super.main() } override func cancel() { if let recordsTosave = recordsToSave, let recordIDsTodelete = recordIDsToDelete { let returningRecordNames = recordsTosave.map{$0.recordID.recordName} + recordIDsTodelete.map{$0.recordName} CloudKit.pendingRecordNames = CloudKit.pendingRecordNames.union(returningRecordNames) } super.cancel() } private func setupRecords() { let count = CloudKit.pendingRecordNames.count let maxRecords = 300 var recordNames: Set<String> = Set() if count <= maxRecords { recordNames = CloudKit.pendingRecordNames CloudKit.pendingRecordNames.removeAll() } else { recordNames = Set(CloudKit.pendingRecordNames.dropLast(count - maxRecords)) CloudKit.pendingRecordNames = CloudKit.pendingRecordNames.subtracting(recordNames) } var records: [CKRecord] = [] var recordIDs: [CKRecord.ID] = [] writeContext.performAndWait { cloudContext.refreshAllObjects() for recordName in recordNames { if let object = cloudContext.existingObject(recordName: recordName) { if let record = object.recordToUpload() { records.append(record) } else { CloudKit.nilDataCount += 1 print("Found record but data is nil, count: ", CloudKit.nilDataCount) let recordID = CKRecord.ID(recordName: recordName, zoneID: CloudKit.financialDataZoneID) recordIDs.append(recordID) } } else { let recordID = CKRecord.ID(recordName: recordName, zoneID: CloudKit.financialDataZoneID) recordIDs.append(recordID) } } } recordsToSave = records recordIDsToDelete = recordIDs } } extension OperationCloudKit { func uploadToCloud() { let operation = UploadOperation() operation.isAtomic = true //operation.clientChangeTokenData = UserDefaults.standard.financialDataChangeTokenData operation.modifyRecordsCompletionBlock = { (savedRecords, deletedIDs, error) in if let error = error as? CKError { if let retry = error.retryAfterSeconds { print("\nSuspend operationQueue: retryable error - waiting \(retry + 5) seconds to continue\n") CloudKit.operationQueue.isSuspended = true DispatchQueue.main.asyncAfter(deadline: .now() + retry + 5) { if let recordsTosave = operation.recordsToSave, let recordIDsTodelete = operation.recordIDsToDelete { let returningRecordNames = recordsTosave.map{$0.recordID.recordName} + recordIDsTodelete.map{$0.recordName} CloudKit.pendingRecordNames = CloudKit.pendingRecordNames.union(returningRecordNames) } CloudKit.operationQueue.isSuspended = false self.fetchRecords(completion: { _ in }) print("\nRetry operationQueue\n") return } } if error.code == CKError.partialFailure { if let recordsTosave = operation.recordsToSave, let recordIDsTodelete = operation.recordIDsToDelete { let returningRecordNames = recordsTosave.map{$0.recordID.recordName} + recordIDsTodelete.map{$0.recordName} CloudKit.pendingRecordNames = CloudKit.pendingRecordNames.union(returningRecordNames) } print("\nRetry operationQueue - partial error\n") self.fetchRecords(completion: { _ in }) return } print(error.localizedDescription) operation.cancel() } else { for recordID in deletedIDs! { print("\(recordID.recordName) is deleted from Cloud") } for record in savedRecords! { print("\(record.recordID.recordName) is saved on Cloud") } self.updateChageTag(by: savedRecords!) print("------------------------------") if CloudKit.pendingRecordNames.count != 0 { self.uploadToCloud() } else { self.fetchRecords(completion: { _ in }) //print("End session, nilDatacount: ", CloudKit.nilDataCount) } } } let operationQueue = CloudKit.operationQueue if let lastOperation = operationQueue.operations.last { operation.addDependency(lastOperation) } operationQueue.addOperations([operation], waitUntilFinished: false) } // private func handleRetryable(retryAfterSeconds: TimeInterval) { // // print("Suspend operationQueue: retryable error - waiting \(retryAfterSeconds + 5) seconds to continue") // CloudKit.operationQueue.cancelAllOperations() // DispatchQueue.main.asyncAfter(deadline: .now() + retryAfterSeconds + 5) { // self.fetchRecords(completion: { _ in }) // print("Continue operationQueue") // // } // // } private func updateChageTag(by: [CKRecord]) { writeContext.performAndWait { for record in by { if let object = cloudContext.existingObject(recordName: record.recordID.recordName) { object.updateRecordDataBy(record: record) } } cloudContext.saveData() } } } // // // //private func handlePartiaError(record: CKRecord, error: Error?) { // // let recordName = record.recordID.recordName // if let error = error as? CKError { // // if error.code == CKError.serverRecordChanged { // let serverRecord = error.serverRecord! // let clientRecord = error.clientRecord! // // let serverDate = serverRecord.value(forKey: "modifiedLocal") as! Date // let clientDate = clientRecord.value(forKey: "modifiedLocal") as! Date // if clientDate > serverDate { // print("Retry with client record") // writeContext.performAndWait { // let object = cloudContext.existingObject(recordName: recordName) // object?.updateRecordDataBy(record: serverRecord) // // } // CloudKit.pendingRecordNames.insert(recordName) // // } else { // print("Update with server record") // writeContext.performAndWait { // let object = cloudContext.existingObject(recordName: recordName) // object?.downloadFrom(record: serverRecord) // // } // } // // } // // if error.code == CKError.unknownItem { // print("\(recordName) is NOT saved on Cloud: UnknownItem (mostlikely deleted) - coreData will delete object") // writeContext.performAndWait { // if let object = cloudContext.existingObject(recordName: recordName) { // cloudContext.delete(object) // // } // } // } // // // } // // //}
// // Mage.swift // IOSWars // // Created by Younggi Kim on 2020-04-17. // Copyright © 2020 CoderDroids. All rights reserved. // import SpriteKit class Mage : Unit { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init( parent : SKNode, pos : CGPoint, owner : Owner ) { super.init( parent : parent, pos: pos, type : UnitType.Mage, damage : 15, health : 8, movement : 3,attack: 2, owner : owner ) } }
import Foundation /** https:adventofcode.com/2019/day/7 */ enum Day07 { static func solve() { let input = Input.get("07-Input.txt") print("Result Day 7 - Part One & Two: \(intcodeProgram(input: input))") } private static func intcodeProgram(input: String) -> String { let originalInputAsNumbers = input.components(separatedBy: ",") .compactMap { Int($0) } var possibleOutputs: Set<Int> = [] for feedbackPhaseSettings in permutations([5, 6, 7, 8, 9]) { print("--------- Next permutation Feedback Loop ---------") let amplifiers = [ Computer(name: "A", memory: originalInputAsNumbers), Computer(name: "B", memory: originalInputAsNumbers), Computer(name: "C", memory: originalInputAsNumbers), Computer(name: "D", memory: originalInputAsNumbers), Computer(name: "E", memory: originalInputAsNumbers) ] print("Prepare Feedback Loop Phase Settings") for (index, amplifier) in amplifiers.enumerated() { amplifier.phaseSetting = feedbackPhaseSettings[index] } print("Run Feedback Loop") var currentOutput = 0 while amplifiers.last!.hit99 == false { for amplifier in amplifiers { currentOutput = amplifier.runProgramm(input: currentOutput)! } } possibleOutputs.insert(currentOutput) } let result = possibleOutputs.max()! assert(result == 25534964)//18812) return String(result) } } //https://www.objc.io/blog/2014/12/08/functional-snippet-10-permutations/ private extension Array { func decompose() -> (Iterator.Element, [Iterator.Element])? { guard let x = first else { return nil } return (x, Array(self[1..<count])) } } private func between<T>(_ x: T, _ ys: [T]) -> [[T]] { guard let (head, tail) = ys.decompose() else { return [[x]] } return [[x] + ys] + between(x, tail).map { [head] + $0 } } private func permutations<T>(_ xs: [T]) -> [[T]] { guard let (head, tail) = xs.decompose() else { return [[]] } return permutations(tail).flatMap { between(head, $0) } }
// // TicTackToeApp.swift // TicTackToe // // Created by alex-babich on 22.12.2020. // import SwiftUI @main struct TicTackToeApp: App { var body: some Scene { WindowGroup { ContentView() } } }
// // Created by Przemysław Stasiak on 16.05.2017. // Copyright © 2017 Tooploox. All rights reserved. // import UIKit public struct DeviceInfo { public enum Orientation: String { case portrait = "Portrait" case landscape = "Landscape" } public let portraitScreenSize: CGSize public let name: String public let scale: CGFloat public let orientation: Orientation public var landscape: DeviceInfo { return withOrientation(.landscape) } public var portrait: DeviceInfo { return withOrientation(.portrait) } public var landscapeScreenSize: CGSize { return CGSize(width: portraitScreenSize.height, height: portraitScreenSize.width) } public var orientedScreenSize: CGSize { return orientation == .portrait ? portraitScreenSize : landscapeScreenSize } public init(portraitScreenSize: CGSize, name: String, scale: CGFloat = UIScreen.main.scale, orientation: Orientation = .portrait) { self.portraitScreenSize = portraitScreenSize self.name = name self.scale = scale self.orientation = orientation } private func withOrientation(_ newOrientation: Orientation) -> DeviceInfo { return DeviceInfo( portraitScreenSize: portraitScreenSize, name: name, scale: scale, orientation: newOrientation ) } } extension Sequence where Iterator.Element == DeviceInfo { public var landscape: [DeviceInfo] { return map { $0.landscape } } public var portrait: [DeviceInfo] { return map { $0.portrait } } public var uniqueWidths: [DeviceInfo] { return unique { (lhs, rhs) -> Bool in lhs.orientedScreenSize.width == rhs.orientedScreenSize.width } } public var uniqueHeights: [DeviceInfo] { return unique { (lhs, rhs) -> Bool in lhs.orientedScreenSize.height == rhs.orientedScreenSize.height } } func unique(_ equalityTest: (DeviceInfo, DeviceInfo) -> Bool) -> [DeviceInfo] { var unique = [DeviceInfo]() for info in self { if !unique.contains(where: { equalityTest($0, info) }) { unique.append(info) } } return unique } } extension DeviceInfo: Snap { public var identifier: String { return "\(name)_\(orientation.rawValue)" } public var frameSize: CGSize { return orientedScreenSize } public var deviceOrientation: UIDeviceOrientation { switch orientation { case .portrait: return .portrait case .landscape: return .landscapeLeft } } }
// // WhatsappLoginButton.swift // NotpSDK // // Created by Notp on 06/02/23. // import UIKit /// This class inherits all the properties of the button public final class WhatsappLoginButton: UIButton, onVerifyWaidDelegate { var notpUrl: String = "" var apiRoute = "metaverse" var redirectURI = "" // var buttonText = HippoStrings.continue_to_whatsapp private var loader = NotpLoader() public weak var delegate: onCallbackResponseDelegate? override init(frame: CGRect) { super.init(frame: frame) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) setImageAndTitle() } required init?(coder: NSCoder) { super.init(coder: coder) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) setImageAndTitle() } func setImageAndTitle() { Notp.sharedInstance.delegateOnVerify = self // if Notp.sharedInstance.buttonImage != ""{ // if let image = UIImage(named: Notp.sharedInstance.buttonImage, in: Bundle(for: type(of: self)), compatibleWith: nil) { // setImage(image, for: .normal) // } // }else{ if let image = UIImage(named: "notpwhatsapp.png", in: Bundle(for: type(of: self)), compatibleWith: nil) { setImage(image, for: .normal) } // } checkWaidExistsAndVerified() setTitle(Notp.sharedInstance.buttonText, for: .normal) addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside) backgroundColor = NotpHelper.UIColorFromRGB(rgbValue: 0x23D366) setTitleColor(UIColor.white, for: UIControl.State.normal) titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) } func starifyNumber(number: String) -> String { let intLetters = number.prefix(3) let endLetters = number.suffix(2) let numberOfStars = number.count - (intLetters.count + endLetters.count) var starString = "" for _ in 1...numberOfStars { starString += "*" } let finalNumberToShow: String = intLetters + starString + endLetters return finalNumberToShow } public func onVerifyWaid(mobile: String?, countryCode:String?, waId: String?, name: String?, message: String?, error: String?) { // let number = starifyNumber(number: mobile ?? Notp.sharedInstance.buttonText) Notp.sharedInstance.buttonText = Notp.sharedInstance.buttonText self.loader.hide() manageLabelAndImage() if((self.delegate) != nil){ if error == nil{ delegate?.onCallbackResponse(waId: waId, message: message, name: name, phone: mobile, countryCode: countryCode, error: error) }else{ delegate?.errorCallback(message: error ?? "") } } } @objc private func buttonClicked(){ if !Notp.sharedInstance.isWhatsappInstalled() { self.delegate?.errorCallback(message: "Please Install Whatsapp") }else{ let waIdExists = NotpHelper.checkValueExists(forKey: NotpHelper.waidDefaultKey) if (waIdExists){ } else { self.generateQrCode() } } } public func removeWaidAndContinueToWhatsapp (){ NotpHelper.removeUserMobileAndWaid() Notp.sharedInstance.continueToWhatsapp(url: notpUrl) } public func show(){ self.isHidden = false } public func hide(){ self.isHidden = true } public override func layoutSubviews() { super.layoutSubviews() manageLabelAndImage() } func manageLabelAndImage(){ let imgVwWidthAndHeight = self.frame.height/2 let expectedHeightForView = imgVwWidthAndHeight * 7 let marginBetweenImgVwAndLabel = self.frame.height/8 let marginLeftAndRight = self.frame.height/4 var labelWidth = self.frame.width - imgVwWidthAndHeight - marginBetweenImgVwAndLabel - (marginLeftAndRight * 2) if labelWidth > expectedHeightForView { labelWidth = expectedHeightForView } let yForImgVw = (self.frame.height - imgVwWidthAndHeight)/2 if let titleLabel = self.titleLabel ,let imageView = self.imageView { if titleLabel.text != Notp.sharedInstance.buttonText{ setTitle(Notp.sharedInstance.buttonText, for: .normal) } titleLabel.textAlignment = .center titleLabel.numberOfLines = 1 titleLabel.sizeToFit() if titleLabel.frame.width > labelWidth { titleLabel.frame = CGRect(x: (self.frame.width - labelWidth + imgVwWidthAndHeight + marginBetweenImgVwAndLabel)/2 , y: yForImgVw, width: labelWidth , height: imgVwWidthAndHeight) } titleLabel.frame = CGRect(x: (self.frame.width - titleLabel.frame.width + imgVwWidthAndHeight + marginBetweenImgVwAndLabel)/2 , y: yForImgVw, width: titleLabel.frame.width , height: imgVwWidthAndHeight) imageView.frame = CGRect(x:(self.frame.width - titleLabel.frame.width - imgVwWidthAndHeight - marginBetweenImgVwAndLabel)/2, y: yForImgVw, width: imgVwWidthAndHeight, height:imgVwWidthAndHeight) titleLabel.adjustsFontSizeToFitWidth = true titleLabel.minimumScaleFactor=0.001 } layer.cornerRadius = self.frame.height * 0.14 layer.masksToBounds = true } func checkWaidExistsAndVerified (){ let waIdExists = NotpHelper.checkValueExists(forKey: NotpHelper.waidDefaultKey); if (waIdExists){ let waId = NotpHelper.getValue(forKey:NotpHelper.waidDefaultKey) as String? let headers = ["Content-Type": "application/json","Accept":"application/json"] let bodyParams = ["userId": waId, "api": "getUserDetail"] NotpNetworkHelper.shared.fetchData(method: "POST", headers: headers, bodyParams:bodyParams as [String : Any]) { (data, response, error) in guard let data = data else { // handle error if (error != nil) { NotpHelper.removeUserMobileAndWaid() } return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) // process the JSON data let jsonDictionary = json as? [String: Any] if let jsonData = jsonDictionary?["data"] as? [String: Any]{ if let mobile = jsonData["userMobile"] as? String { DispatchQueue.main.async { Notp.sharedInstance.buttonText = mobile self.manageLabelAndImage() } } } } catch { NotpHelper.removeUserMobileAndWaid() // handle error } } } } func generateQrCode(){ if let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]] { for urlType in urlTypes { if let urlSchemes = urlType["CFBundleURLSchemes"] as? [String], let identifier = urlType["CFBundleURLName"] as? String { if urlSchemes.count == 1 && urlSchemes[0].contains("notp") && identifier.contains("notp") { let scheme = urlSchemes[0] let completeUrl = scheme + "://" + identifier self.redirectURI = completeUrl } } } } var params = [String : Any]() params = ["app_secret_key":HippoConfig.shared.whatsappSecretKey, "get_session": true, "device_type": 2, "redirect_uri":redirectURI] as [String : Any] print(params) HTTPClient.makeConcurrentConnectionWith(method: .POST, showActivityIndicator: true, para: params, extendedUrl: AgentEndPoints.generateQrCode.rawValue) { (response, error, _, statusCode) in print("generateQrCode \(String(describing: response))") if error == nil{ if let messageDict = ((response) as? [String:Any]){ if let data = messageDict["data"] as? [String:Any]{ print(data) let url = data["url"] as? String let sessionId = data["session_id"] as? String NotpHelper.link2 = url?.lastPathComponent ?? "" NotpHelper.link = url ?? "" NotpHelper.session_ID = sessionId ?? "" // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now(), execute: { if let completeUrl = NotpHelper.getCompleteUrl() { self.notpUrl = NotpHelper.addEventDetails(url: completeUrl) NotpNetworkHelper.shared.setBaseUrl(url: self.notpUrl) } // }) self.loader.show() Notp.sharedInstance.continueToWhatsapp(url: self.notpUrl) self.loader.hide() } } }else{ self.delegate?.errorCallback(message: "generateQrCode API Failure") } } } } // Implement this protocol to recieve waid in your view controller class when using WhatsappLoginButton public protocol onCallbackResponseDelegate: AnyObject { func onCallbackResponse(waId : String?, message: String?,name:String?,phone: String?,countryCode:String?, error : String?) func errorCallback(message:String) }
// // DungeonModel.swift // floatios // // Created by Alexander Skorulis on 20/7/18. // Copyright © 2018 Skorulis. All rights reserved. // import GameplayKit public class DungeonModel: Codable { enum CodingKeys: String, CodingKey { case width case height case overlandOffset case name case nodes } public let name:String public var nodes:[MapHexModel] = [] public var width:Int public var height:Int public var graph:GKGraph = GKGraph([]) public var overlandOffset:SCNVector3 = SCNVector3(0,0,0) public var size:vector_int2 { return vector_int2(Int32(width),Int32(height)) } public init(width:Int,height:Int,name:String) { self.width = width self.height = height self.name = name let baseTerrain = ReferenceController.instance.getTerrain(type: .grass) for y in 0..<height { for x in 0..<width { nodes.append(MapHexModel(terrain: baseTerrain,position:vector_int2(Int32(x),Int32(y)))) } } graph.add(nodes) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) width = try container.decode(Int.self, forKey: .width) height = try container.decode(Int.self, forKey: .height) overlandOffset = try container.decode(SCNVector3.self, forKey: .overlandOffset) nodes = try container.decodeIfPresent([MapHexModel].self, forKey: .nodes) ?? [] graph.add(nodes) } public func updateConnectionGraph() { for node in nodes { node.removeAllConnections() } for y in 0..<height { for x in 0..<width { let node = self.nodeAt(x: x, y: y)! let adjacent = self.adjacentNodes(node: node).filter { $0.canPass()} node.addConnections(to: adjacent, bidirectional: false) } } } func adjacentNodes(position:vector_int2) -> [MapHexModel] { guard let node = self.nodeAt(vec: position) else { return []} return adjacentNodes(node: node) } func adjacentNodes(node:MapHexModel) -> [MapHexModel] { let x = Int(node.gridPosition.x) let y = Int(node.gridPosition.y) var nodes:[MapHexModel?] = [self.nodeAt(x: x+1, y: y),self.nodeAt(x: x-1, y: y)] nodes.append(self.nodeAt(x: x, y: y+1)) nodes.append(self.nodeAt(x: x, y: y-1)) if y % 2 == 1 { nodes.append(self.nodeAt(x: x+1, y: y+1)) nodes.append(self.nodeAt(x: x+1, y: y-1)) //Maybe wrong } else { nodes.append(self.nodeAt(x: x-1, y: y+1)) nodes.append(self.nodeAt(x: x-1, y: y-1)) //Maybe wrong } return nodes.filter { $0 != nil}.map { $0!} } func isDirectlyAdjacent(pos1:vector_int2,pos2:vector_int2) -> Bool { let adjacentNodes = self.adjacentNodes(node: nodeAt(vec: pos1)!) return adjacentNodes.filter { $0.gridPosition == pos2}.count > 0 } func tryConnect(node:MapHexModel,x:Int,y:Int) { if let other = self.nodeAt(x: x, y: y) { if (other.canPass()) { node.addConnections(to: [other], bidirectional: false) } if (node.canPass()) { other.addConnections(to: [node], bidirectional: false) } } } public func nodeAt(point:CGPoint) -> MapHexModel? { return nodeAt(x: Int(point.x), y: Int(point.y)) } public func nodeAt(vec:vector_int2) -> MapHexModel? { return nodeAt(x: Int(vec.x), y: Int(vec.y)) } public func nodeAt(x:Int,y:Int) -> MapHexModel? { if (!isInMap(x: x, y: y)) { return nil } let index = y * width + x return nodes[index] } public func isInMap(point:CGPoint) -> Bool { return isInMap(x: Int(point.x), y: Int(point.y)) } public func isInMap(x:Int,y:Int) -> Bool { return x >= 0 && y >= 0 && x < width && y < height } public func fixture(at:CGPoint) -> FixtureType? { let node = self.nodeAt(point: at) return node?.fixture?.ref.type } public func path(to:vector_int2,from:vector_int2) -> [MapHexModel] { guard let node = self.nodeAt(vec: to) else { return [] } guard let fromNode = self.nodeAt(vec: from) else { return [] } return findPath(from: fromNode, to: node) } public func path(to:CGPoint,from:CGPoint) -> [MapHexModel] { guard let node = self.nodeAt(point: to) else { return [] } guard let fromNode = self.nodeAt(point: from) else { return [] } return findPath(from: fromNode, to: node) } func findPath(from:MapHexModel,to:MapHexModel) -> [MapHexModel] { if !to.canPass() { if self.isDirectlyAdjacent(pos1: from.gridPosition, pos2: to.gridPosition) { return [] //Trying to move to a square that cannot be entered and already next to it } } let missingConnections = to.connectedNodes.filter { (otherNode) -> Bool in return !otherNode.connectedNodes.contains(to) } //Add extra connections to make this node accessible for node in missingConnections { node.addConnections(to: [to], bidirectional: false) } let path = graph.findPath(from: from, to: to) as! [MapHexModel] //Remove additional connections for node in missingConnections { node.removeConnections(to: [to], bidirectional: false) } if !to.canPass() { return Array(path.prefix(upTo: path.count - 1)) } return path } public func addBeing(entity:GridEntity) { let node = self.nodeAt(x: entity.x, y: entity.y)! node.beings.append(entity) } public func removeBeing(entity:GridEntity) { let node = self.nodeAt(x: entity.x, y: entity.y)! node.beings = node.beings.filter { $0 !== entity } } public func allMonsters() -> [GridEntity] { var all:[GridEntity] = [] for node in self.nodes { all.append(contentsOf: node.beings) } return all } public func metaData() -> [String:Any] { var dict = [String:Any]() dict[CodingKeys.name.rawValue] = name dict[CodingKeys.width.rawValue] = width dict[CodingKeys.height.rawValue] = height dict[CodingKeys.overlandOffset.rawValue] = overlandOffset.jsonDict() return dict } func randomEmptySquare() -> MapHexModel { let x = RandomHelpers.rand(max: self.width) let y = RandomHelpers.rand(max: self.height) guard let node = self.nodeAt(x: x, y: y) else { return randomEmptySquare() } if node.canPass() { return node } else { return randomEmptySquare() } } func findNearby(type:TerrainType,position:vector_int2) -> MapHexModel? { var best:MapHexModel? var bestDistance:Int32 = 0 for n in nodes { guard n.terrain.type == type else { continue } let distance = abs(position.x - n.gridPosition.x) + abs(position.y - n.gridPosition.y) if best == nil || distance < bestDistance { best = n bestDistance = distance } } return best } }
// // FriendCell.swift // SwiftNetwork // // Created by Дэвид Бердников on 05.05.2021. // import UIKit class FriendCell: UITableViewCell { @IBOutlet weak var friendNameLabel: UILabel! @IBOutlet weak var friendSkillLabel: UILabel! @IBOutlet weak var friendImage: UIImageView! func configure(with result: Friend?) { friendNameLabel.text = result?.name DispatchQueue.global().async { guard let stringUrl = result?.photo else { return } guard let imageUrl = URL(string: stringUrl) else { return } guard let imageData = try? Data(contentsOf: imageUrl) else { return } DispatchQueue.main.async { self.friendImage.image = UIImage(data: imageData) } } } }
import SwiftUI struct TitleView: View { let text: String var body: some View { Text(text) .bold() .textCase(.uppercase) .formatted(fontSize: 45) .padding() } } struct TitleView_Previews: PreviewProvider { static var previews: some View { ZStack { BackgroundView() TitleView(text: "Example Title") } } }
// // Film.swift // Liste // // Created by Thomas on 20/06/2021. // import Foundation public struct Film: Codable { let title, year, imdbID, type, poster: String enum CodingKeys: String, CodingKey { case title = "Title" case year = "Year" case imdbID case type = "Type" case poster = "Poster" } }
// // ChartView.swift // // Created by Mikhail Kirillov on 27/12/2017. // Copyright © 2017 Y Media Labs. All rights reserved. // import UIKit enum ChartType { case curve case bars } class ChartView: UIView { var gridView: GridView var graphView: UIView func show(with chartType: ChartType) { switch chartType { case .curve: graphView = BezierCurveView(frame: gridView.usableSpace(), points: []) case .bars: var points: [Float] = [] for i in 0..<100 { points.append(Float(i)) } graphView = BarView(frame: gridView.usableSpace(), points: points) } } override init(frame: CGRect) { gridView = GridView(frame: frame) graphView = UIView(frame: gridView.usableSpace()) super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { gridView = GridView(frame: CGRect.zero) graphView = UIView(frame: CGRect.zero) super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() if gridView.superview == nil { self.addSubview(gridView) } if graphView.superview == nil { gridView.addSubview(graphView) } gridView.frame = self.bounds graphView.frame = gridView.usableSpace() gridView.setNeedsDisplay() graphView.setNeedsDisplay() } }
// // View.swift // bowtie2 // // Created by Jake Runzer on 2020-11-22. // import SwiftUI extension View { public func gradientForeground(gradient: LinearGradient) -> some View { self.overlay(gradient) .mask(self) } @ViewBuilder func `if`<Transform: View>( _ condition: Bool, transform: (Self) -> Transform ) -> some View { if condition { transform(self) } else { self } } func hideKeyboard() { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } func onReceive(_ name: Notification.Name, center: NotificationCenter = .default, object: AnyObject? = nil, perform action: @escaping (Notification) -> Void) -> some View { self.onReceive( center.publisher(for: name, object: object), perform: action ) } }
// // items.swift // boba // // Created by Tracy Ma on 7/25/17. // Copyright © 2017 Tracy Ma. All rights reserved. // import SpriteKit import GameplayKit class Item: SKSpriteNode { }
// // PublicListModel.swift // NewSwift // // Created by gail on 2019/6/12. // Copyright © 2019 NewSwift. All rights reserved. // import UIKit import ObjectMapper class PublicListModel: Mappable { var page : Page? var publicArray : [PublicModel]? var code = "" required init?(map: Map){} func mapping(map: Map){ page <- map["Page"] publicArray <- map["Data"] code <- map["Code"] } } class PublicModel: Mappable { var InfoId = "" var InfoTitle = "" var InfoFrom = "" var FileUrl = "" var InfoType = 0 var PublishTime = "" var IsTop = 0 var InfoIcon = "" var InfoContent = "" required init?(map: Map) {} func mapping(map: Map) { InfoId <- map["InfoId"] InfoTitle <- map["InfoTitle"] InfoFrom <- map["InfoFrom"] FileUrl <- map["FileUrl"] InfoType <- map["InfoType"] PublishTime <- map["PublishTime"] IsTop <- map["IsTop"] InfoIcon <- map["InfoIcon"] InfoContent <- map["InfoContent"] } }
// // BussInessView.swift // Project // // Created by 张凯强 on 2019/8/2. // Copyright © 2019年 HHCSZGD. All rights reserved. // import UIKit class BussInessView: UIView { let myTitleLabel = UILabel.configlabel(font: GDFont.systemFont(ofSize: 14), textColor: UIColor.colorWithHexStringSwift("333333"), text: "") let leftImage: UIImageView = UIImageView.init() let countLabel = UILabel.configlabel(font: GDFont.systemFont(ofSize: 14), textColor: UIColor.colorWithHexStringSwift("ff8302"), text: "") let company = UILabel.configlabel(font: GDFont.systemFont(ofSize: 14), textColor: UIColor.colorWithHexStringSwift("333333"), text: "") let lineView = UIView.init() init(frame: CGRect, title: String, image: String, count: String, des: String) { super.init(frame: frame) self.addSubview(myTitleLabel) self.addSubview(self.leftImage) self.addSubview(countLabel) self.addSubview(self.company) self.addSubview(lineView) let img = UIImage.init(named: image) self.leftImage.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(20) make.centerY.equalToSuperview() make.width.equalTo(img?.size.width ?? 0) make.height.equalTo(img?.size.height ?? 0) } self.leftImage.image = img self.myTitleLabel.sizeToFit() self.myTitleLabel.snp.makeConstraints { (make) in make.left.equalTo(self.leftImage.snp.right).offset(15) make.centerY.equalToSuperview() } self.myTitleLabel.text = title self.countLabel.text = count self.countLabel.sizeToFit() self.countLabel.snp.makeConstraints { (make) in make.right.equalTo(self.company.snp.left).offset(-20) make.centerY.equalToSuperview() } self.company.snp.makeConstraints { (make) in make.right.equalToSuperview().offset(-30) make.centerY.equalToSuperview() } self.company.sizeToFit() self.company.text = des self.lineView.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(20) make.right.equalToSuperview().offset(-20) make.bottom.equalToSuperview() make.height.equalTo(1) } self.lineView.backgroundColor = UIColor.colorWithHexStringSwift("f2f2f2") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class DDCircleButton: UIControl { let numberLable = UILabel() let titleLable = UILabel() let backImage = UIImageView(image: UIImage(named: "money_ring")) override init(frame: CGRect ) { super.init(frame: frame) self.addSubview(numberLable) self.addSubview(titleLable) self.addSubview(backImage) numberLable.textAlignment = .center titleLable.textAlignment = .center } override func layoutSubviews() { super.layoutSubviews() let padding : CGFloat = 20 let imageWH : CGFloat = self.bounds.width - padding * 2 let ImageX = padding let ImageY = padding let titleH : CGFloat = 30 let titleY : CGFloat = self.bounds.height - titleH - padding backImage.frame = CGRect(x: ImageX, y: ImageY, width: imageWH, height: imageWH) numberLable.bounds = CGRect(x: 0, y: 0, width: self.bounds.width, height: 44) numberLable.center = backImage.center titleLable.frame = CGRect(x: 0, y: titleY, width: self.bounds.width, height: titleH) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // ParamsHeaders.swift // OSOM_app // // Created by Miłosz Bugla on 26.11.2017. // import Foundation import Foundation struct Endpoints { static let baseUrl = "https://carrierviewer.azurewebsites.net/" static let register = "api/accounts/create" static let login = "oauth/token" static let refreshToken = "oauth/token" static let session = "session" static let teams = "teams" static let addTeam = "team/assign" static let emailValidator = "api/accounts/email" static let personal = "api/accounts/data/personal" static let education = "api/data/school" static let skill = "api/data/skill" static let work = "api/data/work" static let works = "api/data/works" static let schools = "api/data/schools" static let section = "api/data/section" static let sections = "api/data/sections" } struct SuccessCodes { static let ok = 200 static let created = 201 } struct ErrorCodes { static let notConnectedToInternet = -1009 static let authorization = 401 static let badRequest = 400 static let invalidCredentials = 422 } struct HeadersKeys { struct ContentType { static let name = "Content-Type" static let value = "application/json" } struct ContentDataType { static let name = "Content-type" static let value = "multipart/form-data" } struct Accept { static let name = "Accept" static let value = "application/json" } struct Authorization { static let name = "Authorization" static let value = "Bearer " } struct GrantType { static let name = "grant_type" static let clientCredentials = "client_credentials" static let password = "password" } struct ClientId { static let name = "client_id" static let value = "iOSApp" } struct ClientSecret { static let name = "client_secret" static let value = "qMCdFDQuF23RV1Y-1Gq9L3cF3VmuFwVbam4fMTdAfpo" } }
// // CartViewController.swift // textbook // // Created by Zuhao Hua on 12/3/20. // Copyright © 2020 Anya Ji. All rights reserved. // import UIKit class CartViewController: UIViewController { // let pink: UIColor = UIColor(red: 1, green: 0.479, blue: 0.479, alpha: 1) // // var cartTableView: UITableView! // var cartTotalLabelLeft: LeftLabel! // var cartTotalLabelRight: RightLabel! // var blackLine: UILabel! // var confirmButton: UIButton! // let sidePadding:CGFloat = 25 // // var totalValue:Double = 0 // // var booksInCart: [Book] = [] // // var cartFromBackend : [Book] = [] // var retrievedUserInfo: userInfoResponseDataStruct! // // // override func viewDidLoad() { // super.viewDidLoad() // // // Do any additional setup after loading the view. // view.backgroundColor = .white // // //Initialize tableView // cartTableView = UITableView() // cartTableView.translatesAutoresizingMaskIntoConstraints = false // cartTableView.dataSource = self // cartTableView.delegate = self // cartTableView.register(CartTableViewCell.self, forCellReuseIdentifier: CartTableViewCell.cartTableViewCellIdentifier) // cartTableView.backgroundColor = .white // cartTableView.layer.cornerRadius = 20 // cartTableView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner] // cartTableView.clipsToBounds = true // cartTableView.showsVerticalScrollIndicator = false // cartTableView.frame.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)) // cartTableView.bounces = false // cartTableView.separatorStyle = .none // view.addSubview(cartTableView) // // blackLine = UILabel() // blackLine.translatesAutoresizingMaskIntoConstraints = false // blackLine.backgroundColor = .black // blackLine.isUserInteractionEnabled = false // view.addSubview(blackLine) // // cartTotalLabelLeft = LeftLabel() // cartTotalLabelLeft.translatesAutoresizingMaskIntoConstraints = false // cartTotalLabelLeft.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1) // cartTotalLabelLeft.layer.cornerRadius = 20 // cartTotalLabelLeft.layer.maskedCorners = [.layerMinXMaxYCorner] // cartTotalLabelLeft.clipsToBounds = true // cartTotalLabelLeft.text = "Total" // cartTotalLabelLeft.isUserInteractionEnabled = false // cartTotalLabelLeft.font = .systemFont(ofSize: 20) // view.addSubview(cartTotalLabelLeft) // // cartTotalLabelRight = RightLabel() // cartTotalLabelRight.translatesAutoresizingMaskIntoConstraints = false // cartTotalLabelRight.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1) // cartTotalLabelRight.layer.cornerRadius = 20 // cartTotalLabelRight.layer.maskedCorners = [.layerMaxXMaxYCorner] // cartTotalLabelRight.clipsToBounds = true // cartTotalLabelRight.text = "$ 0" // cartTotalLabelRight.textAlignment = .right // cartTotalLabelRight.isUserInteractionEnabled = false // cartTotalLabelRight.font = .systemFont(ofSize: 20) // view.addSubview(cartTotalLabelRight) // // confirmButton = UIButton() // confirmButton.layer.cornerRadius = 20 // confirmButton.clipsToBounds = true // confirmButton.setTitle("Confirm Purchase", for: .normal) // //confirmButton.titleLabel?.font = UIFont.systemFont(ofSize: 20) // confirmButton.setTitleColor(.white, for: .normal) // confirmButton.translatesAutoresizingMaskIntoConstraints = false // confirmButton.backgroundColor = pink // confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside) // view.addSubview(confirmButton) // // //retrieveUserCart() // setupConstraints() // } // // override func viewDidAppear(_ animated: Bool){ // retrieveUserCart() // } // // func setupConstraints(){ // NSLayoutConstraint.activate([ // cartTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: sidePadding), // cartTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -sidePadding), // cartTableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 10), // cartTableView.heightAnchor.constraint(equalToConstant: view.frame.height*0.5) // ]) // // NSLayoutConstraint.activate([ // blackLine.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: sidePadding), // blackLine.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -sidePadding), // blackLine.topAnchor.constraint(equalTo: cartTableView.bottomAnchor), // blackLine.heightAnchor.constraint(equalToConstant: 1) // ]) // // NSLayoutConstraint.activate([ // cartTotalLabelLeft.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: sidePadding), // cartTotalLabelLeft.topAnchor.constraint(equalTo: blackLine.bottomAnchor), // cartTotalLabelLeft.heightAnchor.constraint(equalToConstant: 50), // cartTotalLabelLeft.widthAnchor.constraint(equalToConstant: (view.frame.width-sidePadding*2)/2) // ]) // // NSLayoutConstraint.activate([ // cartTotalLabelRight.leadingAnchor.constraint(equalTo: cartTotalLabelLeft.trailingAnchor), // cartTotalLabelRight.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -sidePadding), // cartTotalLabelRight.topAnchor.constraint(equalTo: blackLine.bottomAnchor), // cartTotalLabelRight.heightAnchor.constraint(equalToConstant: 50) // ]) // // NSLayoutConstraint.activate([ // confirmButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30), // confirmButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: sidePadding), // confirmButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -sidePadding), // confirmButton.heightAnchor.constraint(equalToConstant: 40) // ]) // } // // private func retrieveUserCart(){ // // let sellerID :Int = LoginViewController.currentUser.id //this is correct now // // var cartFromBackend : [Book] = [] // self.booksInCart = [] // self.totalValue = 0 // self.cartTotalLabelRight.text = String(format: "%.2f", self.totalValue) // // self.cartTableView.reloadData() // // NetworkManager.getUserCart(currentUserId: sellerID){ books in // cartFromBackend = books // for item in cartFromBackend{ // let newItem = item // self.booksInCart.append(newItem) // self.totalValue += Double(newItem.price)! // self.cartTotalLabelRight.text = String(format: "%.2f", self.totalValue) // // } // // //reload // DispatchQueue.main.async { // self.cartTableView.reloadData() // } // } // // // } // // private func updateCartAfterDelete(deletedBookID:Int){ // // let books = booksInCart // booksInCart = [] // for b in books{ // if b.id != deletedBookID{ // booksInCart.append(b) // } // else{ // self.totalValue -= Double(b.price)! // self.cartTotalLabelRight.text = String(format: "%.2f", self.totalValue) // } // } // // //reload // DispatchQueue.main.async { // self.cartTableView.reloadData() // } // // } // // // @objc func confirmButtonTapped(){ // let newViewController = SuccessViewController() // navigationController?.pushViewController(newViewController, animated: true) // } // // //} // //extension CartViewController:UITableViewDataSource{ // // func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // return "Items" // } // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // //return currentCart.count // return booksInCart.count // } // // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // return 200 // } // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: CartTableViewCell.cartTableViewCellIdentifier, for: indexPath) as! CartTableViewCell // //let oneBook = currentCart[indexPath.row] // let oneBook = booksInCart[indexPath.row] // cell.configure(inputbookData: oneBook) // cell.delegate = self // return cell // } // // //} // //extension CartViewController:UITableViewDelegate{ // //} // //extension UIView { // // func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { // let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) // let mask = CAShapeLayer() // mask.path = path.cgPath // self.layer.mask = mask // } // //} // //extension CartViewController:deleteFromCart{ // // func deleteFromCartAction(bookId: Int) { // // let sellerID :Int = LoginViewController.currentUser.id // let updateToken:String = LoginViewController.currentUser.update_token // // //call network manager to delete the book // NetworkManager.deleteOneBookFromCart(currentUserId: sellerID, bookId: bookId,updateToken: updateToken){ books in //returned cart is not used // //call retrieve user cart to update cart information // self.updateCartAfterDelete(deletedBookID: bookId) // } // // // // // } }
// // ReportViewController.swift // RootsCapstoneProj // // Created by Abby Allen on 7/18/20. // Copyright © 2020 Abby Allen. All rights reserved. // import UIKit import CoreData class ReportViewController: UIViewController, UITextFieldDelegate { var isCancel = false; @IBOutlet weak var dayLabel: UILabel! @IBOutlet weak var todaysDate: UIDatePicker! @IBOutlet weak var selfHarmUrge: UISegmentedControl! @IBOutlet weak var selfHarmAction: UISegmentedControl! @IBOutlet weak var suicidalUrge: UISegmentedControl! @IBOutlet weak var suicidalAction: UISegmentedControl! @IBOutlet weak var alcoholUrge: UISegmentedControl! @IBOutlet weak var alcoholAction: UISegmentedControl! @IBOutlet weak var drugUrge: UISegmentedControl! @IBOutlet weak var drugAction: UISegmentedControl! @IBOutlet weak var otherTextField: UITextField! @IBOutlet weak var otherUrge: UISegmentedControl! @IBOutlet weak var otherAction: UISegmentedControl! @IBOutlet weak var medsAction: UISegmentedControl! @IBOutlet weak var sexAction: UISegmentedControl! @IBOutlet weak var cutClassAction: UISegmentedControl! @IBOutlet weak var wentToBed: UIDatePicker! @IBOutlet weak var wokeUp: UIDatePicker! @IBOutlet weak var emotionAnger: UISegmentedControl! @IBOutlet weak var emotionFear: UISegmentedControl! @IBOutlet weak var emotionHappy: UISegmentedControl! @IBOutlet weak var emotionSad: UISegmentedControl! @IBOutlet weak var emotionAnxious: UISegmentedControl! @IBOutlet weak var emotionShame: UISegmentedControl! @IBOutlet weak var emotionMisery: UISegmentedControl! @IBOutlet weak var skillsRange: UISegmentedControl! @IBOutlet weak var skill1Response: UISegmentedControl! @IBOutlet weak var skill2Response: UISegmentedControl! @IBOutlet weak var skill3Response: UISegmentedControl! @IBOutlet weak var skill4Response: UISegmentedControl! @IBOutlet weak var skill5Response: UISegmentedControl! @IBOutlet weak var skill6Response: UISegmentedControl! @IBOutlet weak var skill7Response: UISegmentedControl! @IBOutlet weak var skill8Response: UISegmentedControl! @IBOutlet weak var skill9Response: UISegmentedControl! @IBOutlet weak var skill10Response: UISegmentedControl! @IBOutlet weak var skill11Response: UISegmentedControl! @IBOutlet weak var skill12Response: UISegmentedControl! @IBOutlet weak var skill13Response: UISegmentedControl! @IBOutlet weak var skill14Response: UISegmentedControl! @IBOutlet weak var skill15Response: UISegmentedControl! @IBOutlet weak var skill16Response: UISegmentedControl! @IBOutlet weak var skill17Response: UISegmentedControl! @IBOutlet weak var skill18Response: UISegmentedControl! @IBOutlet weak var skill19Response: UISegmentedControl! @IBOutlet weak var skill20Response: UISegmentedControl! @IBOutlet weak var skill21Response: UISegmentedControl! @IBOutlet weak var skill22Response: UISegmentedControl! @IBOutlet weak var skill23Response: UISegmentedControl! @IBOutlet weak var skill24Response: UISegmentedControl! @IBOutlet weak var skill25Response: UISegmentedControl! @IBOutlet weak var skill26Response: UISegmentedControl! @IBOutlet weak var skill27Response: UISegmentedControl! @IBOutlet weak var skill28Response: UISegmentedControl! @IBOutlet weak var skill29Response: UISegmentedControl! @IBOutlet weak var skill30Response: UISegmentedControl! @IBOutlet weak var skill31Response: UISegmentedControl! @IBOutlet weak var start: UIView! @IBOutlet weak var cancel: UIView! var day = 0 var today = "" var bedtime = "" var awake = "" override func viewDidLoad() { super.viewDidLoad() (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .portrait start.layer.cornerRadius = 3.0 start.layer.shadowOffset = CGSize(width: 0.0, height: 5.0) start.layer.shadowOpacity = 0.3 start.layer.shadowRadius = 1.0 cancel.layer.cornerRadius = 3.0 cancel.layer.shadowOffset = CGSize(width: 0.0, height: 5.0) cancel.layer.shadowOpacity = 0.3 cancel.layer.shadowRadius = 1.0 switch day { case 1: dayLabel.text = "Monday" case 2: dayLabel.text = "Tuesday" case 3: dayLabel.text = "Wednesday" case 4: dayLabel.text = "Thursday" case 5: dayLabel.text = "Friday" case 6: dayLabel.text = "Saturday" case 7: dayLabel.text = "Sunday" default: dayLabel.text = "" } otherTextField.delegate = self } func textFieldShouldReturn(_ textField: UITextField) -> Bool { otherTextField.resignFirstResponder() return true } @IBAction func cancelPressed(_ sender: Any) { isCancel = true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "tipp" { let dest = segue.destination as! TippViewController dest.report = true } else if segue.identifier == "please" { let dest = segue.destination as! PleaseSkillViewController dest.report = true } else if segue.identifier == "pros" { let dest = segue.destination as! ProsViewController dest.report = true } else if segue.identifier == "facts" { let dest = segue.destination as! FactsViewController dest.report = true } else if segue.identifier == "improve" { let dest = segue.destination as! ImproveViewController dest.report = true } else if segue.identifier == "dearman" { let dest = segue.destination as! DearManViewController dest.report = true } else if segue.identifier == "fast" { let dest = segue.destination as! FastViewController dest.report = true } else if segue.identifier == "give" { let dest = segue.destination as! GiveViewController dest.report = true } else if segue.identifier == "radical" { let dest = segue.destination as! RadicalAcceptViewController dest.report = true } else if segue.identifier == "wise" { let dest = segue.destination as! WiseMindViewController dest.report = true } else if segue.identifier == "soothe"{ let dest = segue.destination as! SootheViewController dest.report = true } else if segue.identifier == "observe" { let dest = segue.destination as! ObserveViewController dest.report = true } else if segue.identifier == "describe" { let dest = segue.destination as! DescribeViewController dest.report = true } else if segue.identifier == "judge" { let dest = segue.destination as! NonjudgementalViewController dest.report = true } else if segue.identifier == "longterm" { let dest = segue.destination as! LongTermViewController dest.report = true } else if segue.identifier == "mastery" { let dest = segue.destination as! BuildViewController dest.report = true } else if segue.identifier == "cope" { let dest = segue.destination as! CopingViewController dest.report = true } else if segue.identifier == "pleasant" { let dest = segue.destination as! PleasantViewController dest.report = true } else if segue.identifier == "participate" { let dest = segue.destination as! ParticipateViewController dest.report = true } else if segue.identifier == "solve" { let dest = segue.destination as! SolveViewController dest.report = true } else if segue.identifier == "effective" { let dest = segue.destination as! EffectiveViewController dest.report = true } else if segue.identifier == "onemind" { let dest = segue.destination as! OneMindViewController dest.report = true } else if segue.identifier == "values" { let dest = segue.destination as! ValsAndPriorsViewController dest.report = true } else if segue.identifier == "emotions" { let dest = segue.destination as! EmotionsViewController dest.report = true } else if segue.identifier == "reinforce" { let dest = segue.destination as! PosReinforceViewController dest.report = true } else if segue.identifier == "validate1" || segue.identifier == "validate2" { let dest = segue.destination as! ValidateViewController dest.report = true } else if segue.identifier == "thinkdia" || segue.identifier == "actdia" { let dest = segue.destination as! DialecticViewController dest.report = true } else if segue.identifier == "accepts" { let dest = segue.destination as! AcceptsViewController dest.report = true } else if !isCancel { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Day\(day)", in: context) let saveThis = NSManagedObject(entity: entity!, insertInto: context) let dateFormatter = DateFormatter() let dateFormatter1 = DateFormatter() dateFormatter.dateStyle = DateFormatter.Style.none dateFormatter.timeStyle = DateFormatter.Style.short dateFormatter1.dateStyle = DateFormatter.Style.short dateFormatter1.timeStyle = DateFormatter.Style.none bedtime = dateFormatter.string(from: wentToBed.date) awake = dateFormatter.string(from: wokeUp.date) today = dateFormatter1.string(from: todaysDate.date) //for yes/no values, 0 = yes and 1 = no saveThis.setValue(alcoholUrge.selectedSegmentIndex, forKey: "alcoholUrge") saveThis.setValue(alcoholAction.selectedSegmentIndex, forKey: "alcoholAction") saveThis.setValue(emotionAnger.selectedSegmentIndex, forKey: "anger") saveThis.setValue(emotionSad.selectedSegmentIndex, forKey: "sad") saveThis.setValue(emotionFear.selectedSegmentIndex, forKey: "fear") saveThis.setValue(emotionHappy.selectedSegmentIndex, forKey: "happy") saveThis.setValue(emotionShame.selectedSegmentIndex, forKey: "shame") saveThis.setValue(emotionMisery.selectedSegmentIndex, forKey: "misery") saveThis.setValue(emotionAnxious.selectedSegmentIndex, forKey: "anxious") saveThis.setValue(awake, forKey: "awake") saveThis.setValue(bedtime, forKey: "bedtime") saveThis.setValue(today, forKey: "date") saveThis.setValue(drugAction.selectedSegmentIndex, forKey: "drugsAction") saveThis.setValue(drugUrge.selectedSegmentIndex, forKey: "drugsUrge") saveThis.setValue(medsAction.selectedSegmentIndex, forKey: "meds") saveThis.setValue(cutClassAction.selectedSegmentIndex, forKey: "missClass") if otherTextField.text != "" { saveThis.setValue(otherAction.selectedSegmentIndex, forKey: "otherAction") saveThis.setValue(otherUrge.selectedSegmentIndex, forKey: "otherRank") saveThis.setValue(otherTextField?.text, forKey: "other") } saveThis.setValue(selfHarmAction.selectedSegmentIndex, forKey: "selfHarmAction") saveThis.setValue(selfHarmUrge.selectedSegmentIndex, forKey: "selfHarmUrge") saveThis.setValue(sexAction.selectedSegmentIndex, forKey: "sex") saveThis.setValue(suicidalAction.selectedSegmentIndex, forKey: "suicidalAction") saveThis.setValue(suicidalUrge.selectedSegmentIndex, forKey: "suicidalUrge") saveThis.setValue(skillsRange.selectedSegmentIndex, forKey: "skills") saveThis.setValue(skill1Response.selectedSegmentIndex, forKey: "skill1") saveThis.setValue(skill2Response.selectedSegmentIndex, forKey: "skill2") saveThis.setValue(skill3Response.selectedSegmentIndex, forKey: "skill3") saveThis.setValue(skill4Response.selectedSegmentIndex, forKey: "skill4") saveThis.setValue(skill5Response.selectedSegmentIndex, forKey: "skill5") saveThis.setValue(skill6Response.selectedSegmentIndex, forKey: "skill6") saveThis.setValue(skill7Response.selectedSegmentIndex, forKey: "skill7") saveThis.setValue(skill8Response.selectedSegmentIndex, forKey: "skill8") saveThis.setValue(skill9Response.selectedSegmentIndex, forKey: "skill9") saveThis.setValue(skill10Response.selectedSegmentIndex, forKey: "skill10") saveThis.setValue(skill11Response.selectedSegmentIndex, forKey: "skill11") saveThis.setValue(skill12Response.selectedSegmentIndex, forKey: "skill12") saveThis.setValue(skill13Response.selectedSegmentIndex, forKey: "skill13") saveThis.setValue(skill14Response.selectedSegmentIndex, forKey: "skill14") saveThis.setValue(skill15Response.selectedSegmentIndex, forKey: "skill15") saveThis.setValue(skill16Response.selectedSegmentIndex, forKey: "skill16") saveThis.setValue(skill17Response.selectedSegmentIndex, forKey: "skill17") saveThis.setValue(skill18Response.selectedSegmentIndex, forKey: "skill18") saveThis.setValue(skill19Response.selectedSegmentIndex, forKey: "skill19") saveThis.setValue(skill20Response.selectedSegmentIndex, forKey: "skill20") saveThis.setValue(skill21Response.selectedSegmentIndex, forKey: "skill21") saveThis.setValue(skill22Response.selectedSegmentIndex, forKey: "skill22") saveThis.setValue(skill23Response.selectedSegmentIndex, forKey: "skill23") saveThis.setValue(skill24Response.selectedSegmentIndex, forKey: "skill24") saveThis.setValue(skill25Response.selectedSegmentIndex, forKey: "skill25") saveThis.setValue(skill26Response.selectedSegmentIndex, forKey: "skill26") saveThis.setValue(skill27Response.selectedSegmentIndex, forKey: "skill27") saveThis.setValue(skill28Response.selectedSegmentIndex, forKey: "skill28") saveThis.setValue(skill29Response.selectedSegmentIndex, forKey: "skill29") saveThis.setValue(skill30Response.selectedSegmentIndex, forKey: "skill30") saveThis.setValue(skill31Response.selectedSegmentIndex, forKey: "skill31") do{ try context.save() }catch{ print("Save failed: \(error)") } } } @IBAction func unwindReport(_ sender: UIStoryboardSegue){} }
// // ViewController.swift // TestTeamGitHub // // Created by Nazar on 14.02.17. // Copyright © 2017 Nazar. All rights reserved. // import UIKit class ViewController: UIViewController, PassDataProtocol, SendDataDelegate { @IBOutlet weak var labelNazar: UILabel! @IBOutlet weak var labelDima: UILabel! let secondVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DimaID") as! DimaViewController let thirdVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NazarID") as! NazarViewController @IBOutlet weak var segContOutlet: UISegmentedControl! @IBAction func segmentController(_ sender: UISegmentedControl, forEvent event: UIEvent) { switch segContOutlet.selectedSegmentIndex { case 0: self.present(secondVC, animated: true, completion: nil) case 1: self.present(thirdVC, animated: true, completion: nil) default: break } } override func viewDidLoad() { super.viewDidLoad() thirdVC.delegatic = self secondVC.delegate = self } func passData(data: String) { labelNazar.text = data } func textSendData(data: AnyObject) { labelDima.text = data as? String } }
// // TriviaViewController.swift // Examen // // Created by macbook on 4/29/19. // Copyright © 2019 nidem. All rights reserved. // import UIKit class TriviaViewController: UIViewController { var state = 0 @IBOutlet weak var switch2: UISwitch! @IBOutlet weak var switch3: UISwitch! @IBOutlet weak var switch4: UISwitch! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(switch4.isOn && switch2.isOn && switch3.isOn){ state = 1 } else{ state = 0 } if(segue.identifier == "passSegue"){ let nextView = segue.destination as! Trvie2ViewController nextView.estado = state } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // AvatarPickerCell.swift // Chatter // import UIKit class AvatarPickerCell: UICollectionViewCell { private var avatarImageView = UIImageView() override init(frame: CGRect) { super.init(frame: .zero) setupView() } @available(*, unavailable, message: "Use init(frame:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToWindow() { super.didMoveToWindow() constructHierarchy() activateConstraints() } private func constructHierarchy() { addSubview(avatarImageView) } private func activateConstraints() { avatarImageView.translatesAutoresizingMaskIntoConstraints = false let top = avatarImageView.topAnchor.constraint(equalTo: contentView.topAnchor) let bottom = avatarImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) let leading = avatarImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor) let trailing = avatarImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) NSLayoutConstraint.activate([top, bottom, leading, trailing]) } func configureCell(index: Int, avatarType: AvatarType) { switch avatarType { case .dark: avatarImageView.image = UIImage(named: "dark\(index)") backgroundColor = .lightGray case .light: avatarImageView.image = UIImage(named: "light\(index)") backgroundColor = .gray } } private func setupView() { contentMode = .center clipsToBounds = true backgroundColor = .lightGray layer.cornerRadius = 10 } }
// // LayoutStackView.swift // vear-poser // // Created by Tomoya Hirano on 2020/03/31. // Copyright © 2020 Tomoya Hirano. All rights reserved. // import UIKit class LayoutStackView: UIStackView { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let hitView = super.hitTest(point, with: event) if hitView == self { return nil } else { return hitView } } }
// // SettingModel.swift // TrainingNote // // Created by Mizuki Kubota on 2020/02/17. // Copyright © 2020 MizukiKubota. All rights reserved. // import Foundation import RxSwift import RxCocoa //import RxDataSources struct SettingModelInput { let swipeCell: ControlEvent<IndexPath> let addItemTextRelay: PublishRelay<String> } protocol SettingModelOutput { var exerciseObservable: Observable<[String]?> {get} } protocol SettingModelType { var outputs: SettingModelOutput? { get } func setup(input: SettingModelInput) } final class SettingModel: Injectable, SettingModelType { struct Dependency {} var outputs: SettingModelOutput? private let disposeBag = DisposeBag() init(with dependency: Dependency) { self.outputs = self } func setup(input: SettingModelInput) { input.swipeCell.subscribe(onNext: { [weak self] indexPath in guard let self = self else { return } self.remove(at: indexPath) }) .disposed(by: disposeBag) input.addItemTextRelay.subscribe(onNext: { [weak self] addItemText in guard let self = self else { return } self.add(add: addItemText) }) .disposed(by: disposeBag) } func add(add addItemText: String) { var userDefaultsExercises = UserDefault.exercises userDefaultsExercises.append(addItemText) UserDefault.exercises = userDefaultsExercises } func remove(at indexPath: IndexPath) { var userDefaultsExercises = UserDefault.exercises userDefaultsExercises.remove(at: indexPath.row) UserDefault.exercises = userDefaultsExercises } } extension SettingModel: SettingModelOutput { var exerciseObservable: Observable<[String]?> { return UserDefault.userDefault.rx .observe(Array<String>.self, UserDefault.Key.exercise) } }
// // BoldAttributesProvider.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit class BoldAttributesProvider: CIOHighlightingAttributesProvider { var fontNormal: UIFont var fontBold: UIFont init(fontNormal: UIFont, fontBold: UIFont) { self.fontNormal = fontNormal self.fontBold = fontBold } func defaultSubstringAttributes() -> [String: Any] { return [NSFontAttributeName: self.fontNormal] } func highlightedSubstringAttributes() -> [String: Any] { return [NSFontAttributeName: self.fontBold] } }
import Foundation import Bow /// MonadDefer is a `Monad` that provides the ability to delay the evaluation of a computation. public protocol MonadDefer: MonadError { /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter fa: Function returning a computation to be deferred. /// - Returns: A computation that defers the execution of the provided function. static func `defer`<A>(_ fa: @escaping () -> Kind<Self, A>) -> Kind<Self, A> } // MARK: Related functions public extension MonadDefer { /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter f: Function returning a value. /// - Returns: A computation that defers the execution of the provided function. static func later<A>(_ f: @escaping () throws -> A) -> Kind<Self, A> { self.defer { do { return try pure(f()) } catch { return raiseError(error as! E) } } } /// Provides a computation that evaluates the provided computation on every run. /// /// - Parameter fa: A value describing a computation to be deferred. /// - Returns: A computation that defers the execution of the provided value. static func later<A>(_ fa: Kind<Self, A>) -> Kind<Self, A> { self.defer { fa } } /// Provides a lazy computation that returns void. /// /// - Returns: A deferred computation of the void value. static func lazy() -> Kind<Self, Void> { later { } } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter f: A function that provides a value or an error. /// - Returns: A computation that defers the execution of the provided value. static func laterOrRaise<A>(_ f: @escaping () -> Either<E, A>) -> Kind<Self, A> { self.defer { f().fold({ e in self.raiseError(e) }, { a in self.pure(a) }) } } } // MARK: Syntax for MonadDefer public extension Kind where F: MonadDefer { /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter fa: Function returning a computation to be deferred. /// - Returns: A computation that defers the execution of the provided function. static func `defer`(_ fa: @escaping () -> Kind<F, A>) -> Kind<F, A> { F.defer(fa) } /// Provides a computation that evaluates the provided function on every run. /// /// - Returns: A computation that defers the execution of the provided function. static func later(_ f: @escaping () throws -> A) -> Kind<F, A> { F.later(f) } /// Provides a computation that evaluates this computation on every run. /// /// - Returns: A computation that defers the execution of the provided value. func later() -> Kind<F, A> { F.later(self) } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter f: A function that provides a value or an error. /// - Returns: A computation that defers the execution of the provided value. static func laterOrRaise(_ f: @escaping () -> Either<F.E, A>) -> Kind<F, A> { F.laterOrRaise(f) } } public extension Kind where F: MonadDefer, A == Void { /// Provides a lazy computation that returns void. /// /// - Returns: A deferred computation of the void value. static func lazy() -> Kind<F, Void> { F.lazy() } }
// // HSCYBridgeInfoTableViewController.swift // hscy // // Created by dingjianxin on 2017/9/4. // Copyright © 2017年 melodydubai. All rights reserved. // import Alamofire import SwiftyJSON protocol BridgeCoordinateProperty { var bridgeName:String{get set} } class HSCYBridgeInfoTableViewController: UITableViewController { var delegate:BridgeCoordinateProperty! var bridgeInfoDic:Dictionary<String,String>! let nameOfBridgeInfo=["桥梁名称","桥梁地址","经度","纬度","桥梁类型","通航孔数","桥墩数量","最高通航水位","最低通航水位","净高","长度","建成时间","使用年限","使用状态","负责人姓名","所属单位","负责人电话","负责人手机","备注"] let keysOfBridgeInfo=["bridgeName","bridge_address","lng","lat","bridge_type","hole_count","pier_count","max_waterlevel","min_waterlevel","net_height","bridge_len","build_time","use_year","use_state","mgr_name","mgr_depart","mgr_phone","mgr_mobile","remark"] override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title="桥梁信息" // 设置代理 self.tableView.delegate = self // 设置数据源 self.tableView.dataSource = self self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.register(UINib.init(nibName: "HSCYLeftRightTableCellView", bundle: nil), forCellReuseIdentifier: "cell") self.tableView.tableFooterView=UIView() // self.delegate.bridgeName let param = [ "bridgeName":self.delegate.bridgeName ] Alamofire.request("http://218.94.74.231:9999/SeaProject/getBridgeInfo", method: .post, parameters: param).responseJSON{ (returnResult) in if let response=returnResult.result.value{ var info=JSON(response).dictionaryObject! as Dictionary<String, AnyObject> if !info.isEmpty { print("-----info\(info)") let lng=info["lng"] as! Double info["lng"]=String(format:"%.6f",lng) as AnyObject let lat=info["lat"] as! Double info["lat"]=String(format:"%.6f",lat) as AnyObject if let max_waterlevel=info["max_waterlevel"] as? Float{ info["max_waterlevel"]=String(format: "%.1f", max_waterlevel) as AnyObject } else if let max_waterlevel=info["max_waterlevel"] as? Int{ info["max_waterlevel"]=String(format: "%.1f", max_waterlevel) as AnyObject }else{ info["max_waterlevel"]=nil } if let min_waterlevel=info["min_waterlevel"]as?Float{ info["min_waterlevel"]=String(format: "%.1f", min_waterlevel) as AnyObject }else{ info["min_waterlevel"]=nil } if let net_height=info["net_height"]as?Int{ info["net_height"]=String(net_height) as AnyObject }else{ info["net_height"]=nil } if let bridge_len=info["bridge_len"]as?Float{ info["bridge_len"]=String(format: "%.2f",bridge_len) as AnyObject }else{ info["bridge_len"]=nil } if let hole_count = info["hole_count"]as?Int{ info["hole_count"]=String(hole_count) as AnyObject }else{ info["hole_count"]=nil } if let pier_count = info["pier_count"]as?Int{ info["pier_count"]=String(pier_count) as AnyObject }else{ info["pier_count"]=nil } if let use_year = info["use_year"]as?Int{ info["use_year"]=String(use_year) as AnyObject }else{ info["use_year"]=nil } self.bridgeInfoDic=info as! Dictionary<String, String> self.tableView.reloadData() } } } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if bridgeInfoDic==nil { return 0 } return nameOfBridgeInfo.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! HSCYLeftRightTableCellView cell.selectionStyle=UITableViewCellSelectionStyle.none cell.leftLabel?.text=nameOfBridgeInfo[indexPath.row] let key=keysOfBridgeInfo[indexPath.row] if bridgeInfoDic[key] != nil&&bridgeInfoDic[key] != ""{ cell.rightLabel?.text=bridgeInfoDic[key]! }else { cell.rightLabel?.text="暂无数据" } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } }
// // ManagerHistoryViewController.swift // GV24 // // Created by admin on 6/9/17. // Copyright © 2017 admin. All rights reserved. // import UIKit class ManagerHistoryViewController: BaseViewController { @IBOutlet weak var sSegment: UIView! @IBOutlet weak var toLabel: UILabel! @IBOutlet weak var toDateButton: UIButton! @IBOutlet weak var fromDateButton: UIButton! @IBOutlet weak var containerView: UIView! var firstFromDate: Date? = nil var firstToDate: Date = Date() var secondFromDate : Date? = nil var secondToDate : Date = Date() var currentSelectedIndex: Int = 0 var isFirstTime: Bool = true var isDisplayAlert:Bool = false var billId:String? var workListVC = HistoryViewController() var ownerListVC = OwnerHistoryViewController() var selectIndex: Int = 0 { didSet{ print(selectIndex) } } var segmentControl = SegmentedControl(frame: .zero, titles: ["CompleteW".localize, "Formerpartners".localize]) var vIndex = UIViewController() var index: Int = 0 var indexCell: Int?{ didSet{ guard let indexPage = indexCell else {return} UIView.animate(withDuration: 1, animations: { self.pageController.setViewControllers([self.page[indexPage]], direction: .forward, animated: true, completion: nil) }) } } lazy var pageController: UIPageViewController = { let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) return pageViewController }() lazy var page: [UIViewController] = { return [HistoryViewController(), OwnerHistoryViewController()] }() override func viewDidLoad() { super.viewDidLoad() customNavigationController() setupContainerView() setupConstrains() pageController.dataSource = self pageController.delegate = self if let first = page.first { pageController.setViewControllers([first], direction: .forward, animated: false, completion: nil) } sSegment.addSubview(segmentControl) segmentControl.translatesAutoresizingMaskIntoConstraints = false view.addConstraintWithFormat(format: "H:|[v0]|", views: segmentControl) view.addConstraintWithFormat(format: "V:|[v0(30)]", views: segmentControl) segmentControl.delegate = self } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() containerView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: height) containerView.addSubview(pageController.view) addChildViewController(pageController) sSegment.layer.cornerRadius = 8 sSegment.layer.masksToBounds = true sSegment.layer.borderColor = AppColor.backButton.cgColor sSegment.layer.borderWidth = 1 fromDateButton.tintColor = AppColor.backButton toDateButton.tintColor = AppColor.backButton } func customNavigationController() { navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController?.navigationBar.shadowImage = UIImage() //self.automaticallyAdjustsScrollViewInsets = false } func setupContainerView() { containerView.addSubview((workListVC.view)!) workListVC.view.tag = 0 } func setupOwnerHistory() { containerView.addSubview((ownerListVC.view)!) ownerListVC.view.tag = 1 ownerListVC.view.isHidden = true ownerListVC.myParent = self } func setupConstrains() { workListVC.myParent = self toDateButton.setTitle(Date.convertDateToString(date: Date()), for: .normal) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) title = "WorkHistory".localize } @IBAction func fromDateButtonClicked(_ sender: Any) { selectIndex == 0 ? showPopup(isFromDate: true, fromDate: firstFromDate, toDate: firstToDate) : showPopup(isFromDate: true, fromDate: secondFromDate, toDate: secondToDate) } @IBAction func toDateButtonClicked(_ sender: UIButton) { selectIndex == 0 ? showPopup(isFromDate: false, fromDate: firstFromDate, toDate: firstToDate) : showPopup(isFromDate: false, fromDate: secondFromDate, toDate: secondToDate) } fileprivate func showPopup(isFromDate: Bool, fromDate: Date?, toDate: Date?) { let popup = PopupViewController() popup.delegate = self popup.isFromDate = isFromDate popup.fromDate = fromDate popup.toDate = toDate popup.show() } func listHistory() { workListVC.workList.removeAll() workListVC.historyTableView.reloadData() workListVC.startAtDate = firstFromDate workListVC.endAtDate = firstToDate workListVC.page = 1 workListVC.getWorkList(startAt: firstFromDate, endAt: firstToDate) } func listOwnerHistory() { ownerListVC.ownerList.removeAll() ownerListVC.tableView.reloadData() ownerListVC.startAtDate = secondFromDate ownerListVC.endAtDate = secondToDate ownerListVC.getOwnerList(startAt: secondFromDate, endAt: secondToDate) } // MARK: - notification when recieved push from owner to yayment in cash override func setupViewBase() { super.setupViewBase() guard let token = UserDefaultHelper.getToken() else {return} let alert = AlertStandard.sharedInstance let header = ["Content-Type":"application/x-www-form-urlencoded","hbbgvauth": token] guard let bill = billId else{return} let param = ["billId":bill] let apiClient = APIService.shared if isDisplayAlert == true { self.isDisplayAlert = false alert.showAlertCt(controller: self,pushVC: nil, title: "WorkCompleted".localize, message: "confirmReceive".localize, completion: { apiClient.postRequest(url: APIPaths().paymentPayDirectConfirm(), method: .post, parameters: param, header: header, completion: { (json, error) in }) }) } } } extension ManagerHistoryViewController: PopupViewControllerDelegate { func selectedDate(date: Date, isFromDate: Bool) { if isFromDate { if selectIndex == 0 { fromDateButton.setTitle(Date.convertDateToString(date: date), for: .normal) firstFromDate = date } else { fromDateButton.setTitle(Date.convertDateToString(date: date), for: .normal) secondFromDate = date } } else { if selectIndex == 0 { toDateButton.setTitle(Date.convertDateToString(date: date), for: .normal) firstToDate = date } else { toDateButton.setTitle(Date.convertDateToString(date: date), for: .normal) secondToDate = date } } if selectIndex == 0 { self.listHistory() }else { self.listOwnerHistory() } } } extension ManagerHistoryViewController: UIPageViewControllerDelegate{ func presentationCount(for pageViewController: UIPageViewController) -> Int { return page.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let first = page.first, let firstIndex = page.index(of: first) else { return 0 } return firstIndex } } extension ManagerHistoryViewController: UIPageViewControllerDataSource{ func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = page.index(of: viewController) else{return nil} if index == 0 { return nil } let previousIndex = abs((index - 1) % page.count) return page[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = page.index(of: viewController) else{return nil} if index == page.count-1 { return nil } let nextIndex = abs((index + 1) % page.count) return page[nextIndex] } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed == false { guard let targetPage = previousViewControllers.first else {return} guard let targetIndex = page.index(of: targetPage) else {return} segmentControl.selectItem(at: targetIndex, withAnimation: true) pageController.setViewControllers(previousViewControllers, direction: .reverse, animated: true, completion: nil) } } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { guard let targetPage = pendingViewControllers.first else {return} guard let targetIndex = page.index(of: targetPage) else {return} segmentControl.selectItem(at: targetIndex, withAnimation: true) } } extension ManagerHistoryViewController: SegmentedControlDelegate{ func segmentedControl(_ segmentedControl: SegmentedControl, willPressItemAt index: Int){} func segmentedControl(_ segmentedControl: SegmentedControl, didPressItemAt index: Int){ vIndex = page[index] selectIndex = index if selectIndex == 1 { workListVC.view.isHidden = true ownerListVC.view.isHidden = false if let date = secondFromDate { fromDateButton.setTitle(Date.convertDateToString(date: date), for: .normal) } toDateButton.setTitle(Date.convertDateToString(date: secondToDate), for: .normal) self.listOwnerHistory() }else { workListVC.view.isHidden = false ownerListVC.view.isHidden = true if let date = firstFromDate { fromDateButton.setTitle(Date.convertDateToString(date: date), for: .normal) } toDateButton.setTitle(Date.convertDateToString(date: firstToDate), for: .normal) self.listHistory() } var direction: UIPageViewControllerNavigationDirection = .forward if index == 0 { direction = .reverse }else{ direction = .forward } pageController.setViewControllers([vIndex], direction: direction, animated: true, completion: nil) } }
// SwiftUIPlayground // https://github.com/ralfebert/SwiftUIPlayground/ import SwiftUI struct SliderExampleView: View { @State var value = 50.0 var body: some View { Slider(value: $value, in: 1.0 ... 100.0) { Text("Value \(value)") } } } struct SliderExample_Previews: PreviewProvider { static var previews: some View { SliderExampleView() } }
// // CoreDataProjectApp.swift // CoreDataProject // // Created by Martin Rist on 20/08/2021. // import CoreData import SwiftUI @main struct CoreDataProjectApp: App { let persistenceController = PersistenceController.shared var body: some Scene { let managedObjectContext = persistenceController.container.viewContext managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return WindowGroup { ContentView() .environment(\.managedObjectContext, managedObjectContext) } } }
// // SearchViewController.swift // Books List // // Created by Vuk Radosavljevic on 8/20/18. // Copyright © 2018 Vuk. All rights reserved. // import UIKit class SearchViewController: UIViewController { // MARK: - Methods // MARK: - Properites let bookController = BookController.shared @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var collectionView: UICollectionView! } // MARK: - Search Bar Delegate extension SearchViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let searchTerm = searchBar.text else {return} bookController.searchForBook(with: searchTerm) { (error) in guard error == nil else {return} DispatchQueue.main.async { searchBar.resignFirstResponder() self.collectionView.reloadData() } } bookController.retriveBookshelves { (error) in guard error == nil else {return} } } } // MARK: - Collection View Data Source extension SearchViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BookCell", for: indexPath) as! SearchedBookCollectionViewCell let book = bookController.searchedBooks[indexPath.item] guard let volumeInfo = book.volumeInfo else {return cell} cell.titleLabel.text = volumeInfo.title if let url = URL(string: (volumeInfo.imageLinks?.thumbnail)!) { do { let data = try Data(contentsOf: url) cell.imageView.image = UIImage(data: data) } catch let err { print("Error: \(err.localizedDescription)") } } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return bookController.searchedBooks.count } }
// // User_TestCase.swift // Mozark_UsersTests // // Created by khushboo patel on 15/03/21. // Copyright © 2021 khushboo patel. All rights reserved. // import XCTest import UIKit @testable import Mozark_Users class User_TestCase: XCTestCase { var viewControllerUnderTest: User_ViewController! override func setUp() { super.setUp() let storyboard = UIStoryboard(name: "Main", bundle: nil) self.viewControllerUnderTest = storyboard.instantiateViewController(withIdentifier: "User_ViewController") as? User_ViewController // in view controller, menuItems = ["one", "two", "three"] self.viewControllerUnderTest.loadView() self.viewControllerUnderTest.viewDidLoad() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testHasATableView() { XCTAssertNotNil(viewControllerUnderTest.Table_Users) } func testTableViewHasDelegate() { XCTAssertNotNil(viewControllerUnderTest.Table_Users.delegate) } func testTableViewConfromsToTableViewDelegateProtocol() { XCTAssertTrue(viewControllerUnderTest.conforms(to: UITableViewDelegate.self)) XCTAssertTrue(viewControllerUnderTest.responds(to: #selector(viewControllerUnderTest.tableView(_:didSelectRowAt:)))) } func testTableViewHasDataSource() { XCTAssertNotNil(viewControllerUnderTest.Table_Users.dataSource) } func testTableViewConformsToTableViewDataSourceProtocol() { XCTAssertTrue(viewControllerUnderTest.conforms(to: UITableViewDataSource.self)) XCTAssertTrue(viewControllerUnderTest.responds(to: #selector(viewControllerUnderTest.tableView(_:numberOfRowsInSection:)))) XCTAssertTrue(viewControllerUnderTest.responds(to: #selector(viewControllerUnderTest.tableView(_:cellForRowAt:)))) } func testTableViewCellHasReuseIdentifier() { let cell = viewControllerUnderTest.tableView(viewControllerUnderTest.Table_Users, cellForRowAt: IndexPath(row: 0, section: 0)) as? user_TVC let actualReuseIdentifer = cell?.reuseIdentifier let expectedReuseIdentifier = "user_TVC" XCTAssertEqual(actualReuseIdentifer, expectedReuseIdentifier) } }
// // ExploreView.swift // app_library // // Created by juan on 9/24/20. // import SwiftUI struct ExploreView: View { @State var showClassic = true @State var showHistory = false @State var showCrime = false @State var showCsifi = false @State var showFantasty = false var body: some View { VStack{ HStack{ Text("Explore") .font(.system(size: 35, weight: .bold)) Spacer() Image("search") .padding(.horizontal, 10) Image("subtraction") .padding(.horizontal,10) } .padding(.horizontal) HStack{ Text("Classic") .foregroundColor(showClassic ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) .overlay( Rectangle() .frame(width: 79, height: 1) .offset(y: 10) .foregroundColor(showClassic ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) , alignment: .bottom ) .padding(.horizontal, 10) .onTapGesture{ if !self.showClassic { self.showClassic = true self.showHistory = false self.showCrime = false self.showCsifi = false self.showFantasty = false } } Spacer() Text("History") .foregroundColor(showHistory ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) .overlay( Rectangle() .frame(width: 86, height: 1) .offset(y: 10) .foregroundColor(showHistory ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) , alignment: .bottom ) .padding(.horizontal, 10) .onTapGesture{ if !self.showHistory { self.showHistory = true self.showClassic = false self.showCrime = false self.showCsifi = false self.showFantasty = false } } Spacer() Text("Crime") .foregroundColor(showCrime ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) .overlay( Rectangle() .frame(width: 70.5, height: 1) .offset(y: 10) .foregroundColor(showCrime ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) , alignment: .bottom ) .padding(.horizontal, 10) .onTapGesture{ if !self.showCrime { self.showHistory = false self.showClassic = false self.showCrime = true self.showCsifi = false self.showFantasty = false } } Spacer() Text("Sci-fi") .foregroundColor(showCsifi ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) .overlay( Rectangle() .frame(width: 71, height: 1) .offset(y: 10) .foregroundColor(showCsifi ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) , alignment: .bottom ) .padding(.horizontal, 10) .onTapGesture{ if !self.showCsifi { self.showHistory = false self.showClassic = false self.showCrime = false self.showCsifi = true self.showFantasty = false } } Spacer() Text("Fantasty") .foregroundColor(showFantasty ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) .overlay( Rectangle() .frame(width: 80, height: 1) .offset(y: 10) .foregroundColor(showFantasty ? Color(#colorLiteral(red: 0.9294117647, green: 0.1450980392, blue: 0.4039215686, alpha: 1)) : Color(#colorLiteral(red: 0.6768393517, green: 0.6769362688, blue: 0.6768088937, alpha: 1))) , alignment: .bottom ) .padding(.horizontal, 5) .onTapGesture{ if !self.showFantasty { self.showHistory = false self.showClassic = false self.showCrime = false self.showCsifi = false self.showFantasty = true } } } .padding() ScrollView{ VStack{ HStack{ Text("Featured Books") .font(.system(size: 18, weight: .bold)) Spacer() } .padding(.horizontal) .padding(.top) HStack(spacing: 20){ BookView() BookView() } .padding(.bottom) HStack(spacing: 20){ BookView() BookView() } .padding(.bottom) HStack(spacing: 20){ BookView() BookView() } .padding(.bottom) HStack(spacing: 20){ BookView() BookView() } .padding(.bottom) } } } } } struct ExploreView_Previews: PreviewProvider { static var previews: some View { ExploreView() } }
// // TopGamesViewModel.swift // Top Games // // Created by Everson Trindade on 08/05/18. // Copyright © 2018 Everson Trindade. All rights reserved. // import UIKit import AudioToolbox import CoreData protocol LoadContent: class { func didLoadContent(error: String?) func didLoadImage(identifier: Int) } protocol TopGamesViewModelPresentable: class { var canLoad: Bool { get } func getGames() func numberOfSections() -> Int func numberOfItemsInSection() -> Int func gameDTO(row: Int) -> GameDTO func sizeForItems(with width: CGFloat, height: CGFloat) -> CGSize func minimumInteritemSpacingForSectionAt() -> CGFloat func imageFromCache(identifier: Int) -> UIImage? func updateSearchResults(for searchController: UISearchController) func getGameDetailDTO(row: Int) -> GameDetailDTO func refresh() func didFavorite(with id: Int, shouldFavorite: Bool, imageData: Data?) func getFavorites() func eraseData() func setSearchBarActive() } class TopGamesViewModel: TopGamesViewModelPresentable { // MARK: properties weak var delegate: LoadContent? var interactor: TopGamesInteractorPresentable? var games = [Game]() var filteredGames = [Game]() var favorites = [Game]() private var cache = NSCache<NSString, UIImage>() var canLoad = true var searchBarIsActive = false // MARK: Init init(delegate: LoadContent?, interactor: TopGamesInteractorPresentable = TopGamesInteractor()) { self.delegate = delegate self.interactor = interactor } init() { } // MARK: Functions func getGames() { if canLoad && !searchBarIsActive{ canLoad = false interactor?.getGames(offset: self.games.count, completion: { (result, error) in guard let games = result else { self.delegate?.didLoadContent(error: error) return } self.games = self.games + games self.canLoad = true self.delegate?.didLoadContent(error: nil) self.saveDataToWidget() }) } } func refresh() { games = [Game]() filteredGames = [Game]() canLoad = true getGames() getFavorites() searchBarIsActive = false } func getImage(urlString: String, id: Int) -> UIImage { let placeholder = UIImage(named: "icon-placeholder") placeholder?.accessibilityIdentifier = "placeholder" if urlString.isEmpty { cache.setObject(placeholder ?? UIImage(), forKey: NSString(string: urlString)) } if let cachedImage = cache.object(forKey: NSString(string: "\(id)")) { return cachedImage } if let url = URL(string: urlString) { URLSession.shared.dataTask(with: url, completionHandler: { data, _, _ in if let data = data, let image = UIImage(data: data) { DispatchQueue.main.async { self.cache.setObject(image, forKey: NSString(string: "\(id)")) self.delegate?.didLoadImage(identifier: id) } } }).resume() } return UIImage() } func imageFromCache(identifier: Int) -> UIImage? { return cache.object(forKey: NSString(string: "\(identifier)")) } func saveDataToWidget() { let sharedDefaults = UserDefaults(suiteName: "group.sharingDataForTodayWidget") for index in 0...2 { let name = games.object(index: index)?.game?.name let image = games.object(index: index)?.game?.box?.medium sharedDefaults?.setValue(name, forKey: "gameName\(index)") sharedDefaults?.setValue(image, forKey: "gameImage\(index)") } } func didFavorite(with id: Int, shouldFavorite: Bool, imageData: Data?) { let pop = SystemSoundID(1520) AudioServicesPlaySystemSound(pop) let array = games.filter { id == $0.game?._id } guard let game = array.first else { return } var favorite = game favorite.game?.imageData = imageData ?? Data().base64EncodedData() if shouldFavorite { FavoriteManager.save(favorite: favorite) } else { FavoriteManager.remove(favorite: favorite) } } func getFavorites() { favorites = FavoriteManager().loadGames() } func isFavorite(id: Int) -> Bool { return favorites.filter { $0.game?._id == id }.count > 0 } private func prepareImageData(image: UIImage?) -> Data? { guard let image = image, let imageData = UIImagePNGRepresentation(image) else { return nil } return imageData } func eraseData() { games = [Game]() filteredGames = [Game]() favorites = [Game]() } func setSearchBarActive() { searchBarIsActive = false } } // MARK: UICollectionViewDTO extension TopGamesViewModel { func numberOfSections() -> Int { return 1 } func numberOfItemsInSection() -> Int { return searchBarIsActive ? filteredGames.count : games.count } func gameDTO(row: Int) -> GameDTO { if searchBarIsActive { guard let game = filteredGames.object(index: row) else { return GameDTO() } return GameDTO(name: game.game?.name ?? "", image: getImage(urlString: game.game?.box?.large ?? "", id: game.game?._id ?? 0), identifier: game.game?._id ?? 0, favorite: isFavorite(id: game.game?._id ?? 0)) } else { guard let game = games.object(index: row) else { return GameDTO() } return GameDTO(name: game.game?.name ?? "", image: getImage(urlString: game.game?.box?.large ?? "", id: game.game?._id ?? 0), identifier: game.game?._id ?? 0, favorite: isFavorite(id: game.game?._id ?? 0)) } } func getGameDetailDTO(row: Int) -> GameDetailDTO { if searchBarIsActive { guard let game = filteredGames.object(index: row) else { return GameDetailDTO() } return GameDetailDTO(name: game.game?.name ?? "", large: game.game?.box?.large ?? "", viewers: game.viewers ?? 0, channels: game.channels ?? 0, popularity: game.game?.popularity ?? 0, id: game.game?._id ?? 0, giantbomb_id: game.game?.giantbomb_id ?? 0, imageData: prepareImageData(image: getImage(urlString: game.game?.box?.large ?? "", id: game.game?._id ?? 0)) ?? Data(), medium: game.game?.box?.medium ?? "") } else { guard let game = games.object(index: row) else { return GameDetailDTO() } return GameDetailDTO(name: game.game?.name ?? "", large: game.game?.box?.large ?? "", viewers: game.viewers ?? 0, channels: game.channels ?? 0, popularity: game.game?.popularity ?? 0, id: game.game?._id ?? 0, giantbomb_id: game.game?.giantbomb_id ?? 0, imageData: prepareImageData(image: getImage(urlString: game.game?.box?.large ?? "", id: game.game?._id ?? 0)) ?? Data(), medium: game.game?.box?.medium ?? "") } } func sizeForItems(with width: CGFloat, height: CGFloat) -> CGSize { return CGSize(width: ((width / 2) - 12), height: ((height / 2) - 12)) } func minimumInteritemSpacingForSectionAt() -> CGFloat { return 8.0 } } // MARK Search Bar extension TopGamesViewModel { func updateSearchResults(for searchController: UISearchController) { if searchController.isActive { searchBarIsActive = true if let searchText = searchController.searchBar.text { self.filteredGames = searchText.isEmpty ? games : games.filter({ (item) -> Bool in print(self.filteredGames.count) return item.game?.name?.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil }) } } else { searchBarIsActive = false } } }
// // LaunchScene.swift // newblackjack // // Created by Kohei Nakai on 2017/03/09. // Copyright © 2017年 NakaiKohei. All rights reserved. // import UIKit import SpriteKit import GameplayKit class LaunchScene: SKScene { let bjButton=UIButton() let sjButton=UIButton() let comButton=UIButton() let pvpButton=UIButton() let netButton=UIButton() let scomButton=UIButton() let cancelButton=UIButton() let logo=SKSpriteNode(imageNamed:"Blackjack") override func didMove(to view: SKView) { //ロゴの設定及び設置 let logowidth=self.view!.frame.width/6*5 let logoheight=logowidth/5*2 logo.size=CGSize(width:logowidth,height:logoheight) logo.position=CGPoint(x:self.view!.frame.width/2, y:self.view!.frame.height/4*3) self.addChild(logo) backgroundColor=SKColor.init(red: 0, green: 0.5, blue: 0, alpha: 0.1) //ボタンの設定 bjButton.frame = CGRect(x: 0,y: 0,width: 180,height: 40) //大きさ bjButton.backgroundColor = UIColor.brown; //背景色 bjButton.layer.masksToBounds = true //角丸に合わせて画像をマスク(切り取る) bjButton.setTitle("blackjackで遊ぶ", for: UIControlState()) bjButton.setTitleColor(UIColor.white, for: UIControlState()) bjButton.setTitle("blackjackで遊ぶ", for: UIControlState.highlighted) bjButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) bjButton.layer.cornerRadius = 20.0 //角丸を適用 bjButton.layer.position = CGPoint(x: self.view!.frame.width/2, y:self.view!.frame.height/2+40) bjButton.addTarget(self, action: #selector(LaunchScene.onClickbjButton(_:)), for: .touchUpInside) bjButton.addTarget(self, action: #selector(LaunchScene.touchDownbjButton(_:)), for: .touchDown) bjButton.addTarget(self, action: #selector(LaunchScene.enableButtons2(_:)), for: .touchUpOutside) self.view!.addSubview(bjButton) sjButton.frame = CGRect(x: 0,y: 0,width: 180,height: 40) //大きさ sjButton.backgroundColor = UIColor.darkGray; //背景色 sjButton.layer.masksToBounds = true //角丸に合わせて画像をマスク(切り取る) sjButton.setTitle("shadowjackで遊ぶ", for: UIControlState()) sjButton.setTitleColor(UIColor.white, for: UIControlState()) sjButton.setTitle("shadowjackで遊ぶ", for: UIControlState.highlighted) sjButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) sjButton.layer.cornerRadius = 20.0 //角丸を適用 sjButton.layer.position = CGPoint(x: self.view!.frame.width/2, y:self.view!.frame.height/2+120) sjButton.addTarget(self, action: #selector(LaunchScene.onClicksjButton(_:)), for: .touchUpInside) sjButton.addTarget(self, action: #selector(LaunchScene.touchDownsjButton(_:)), for: .touchDown) sjButton.addTarget(self, action: #selector(LaunchScene.enableButtons2(_:)), for: .touchUpOutside) self.view!.addSubview(sjButton) comButton.frame = CGRect(x: 0,y: 0,width: 180,height: 40) //大きさ comButton.backgroundColor = UIColor.brown; //背景色 comButton.layer.masksToBounds = true //角丸に合わせて画像をマスク(切り取る) comButton.setTitle("CPUと対戦", for: UIControlState()) comButton.setTitleColor(UIColor.white, for: UIControlState()) comButton.setTitle("CPUと対戦", for: UIControlState.highlighted) comButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) comButton.layer.cornerRadius = 20.0 //角丸を適用 comButton.layer.position = CGPoint(x: self.view!.frame.width/2, y:self.view!.frame.height/2) comButton.addTarget(self, action: #selector(LaunchScene.onClickCOMButton(_:)), for: .touchUpInside) comButton.addTarget(self, action: #selector(LaunchScene.touchDownCOMButton(_:)), for: .touchDown) comButton.addTarget(self, action: #selector(LaunchScene.enableButtons(_:)), for: .touchUpOutside) self.view!.addSubview(comButton) comButton.isHidden=true pvpButton.frame = CGRect(x: 0,y: 0,width: 180,height: 40) //大きさ pvpButton.backgroundColor = UIColor.brown; //背景色 pvpButton.layer.masksToBounds = true //角丸に合わせて画像をマスク(切り取る) pvpButton.setTitle("2人で対戦", for: UIControlState()) pvpButton.setTitleColor(UIColor.white, for: UIControlState()) pvpButton.setTitle("2人で対戦", for: UIControlState.highlighted) pvpButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) pvpButton.layer.cornerRadius = 20.0 //角丸を適用 pvpButton.layer.position = CGPoint(x: self.view!.frame.width/2, y:self.view!.frame.height/2+80) pvpButton.addTarget(self, action: #selector(LaunchScene.onClickPVPButton(_:)), for: .touchUpInside) pvpButton.addTarget(self, action: #selector(LaunchScene.touchDownPVPButton(_:)), for: .touchDown) pvpButton.addTarget(self, action: #selector(LaunchScene.enableButtons(_:)), for: .touchUpOutside) self.view!.addSubview(pvpButton) pvpButton.isHidden=true netButton.frame = CGRect(x: 0,y: 0,width: 180,height: 40) //大きさ netButton.backgroundColor = UIColor.brown; //背景色 netButton.layer.masksToBounds = true //角丸に合わせて画像をマスク(切り取る) netButton.setTitle("ネットで対戦", for: UIControlState()) netButton.setTitleColor(UIColor.white, for: UIControlState()) netButton.setTitle("ネットで対戦", for: UIControlState.highlighted) netButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) netButton.layer.cornerRadius = 20.0 //角丸を適用 netButton.layer.position = CGPoint(x: self.view!.frame.width/2, y:self.view!.frame.height/2+160) netButton.addTarget(self, action: #selector(LaunchScene.onClickNetButton(_:)), for: .touchUpInside) netButton.addTarget(self, action: #selector(LaunchScene.touchDownNetButton(_:)), for: .touchDown) netButton.addTarget(self, action: #selector(LaunchScene.enableButtons(_:)), for: .touchUpOutside) self.view!.addSubview(netButton) netButton.isHidden=true scomButton.frame = CGRect(x: 0,y: 0,width: 180,height: 40) //大きさ scomButton.backgroundColor = UIColor.darkGray; //背景色 scomButton.layer.masksToBounds = true //角丸に合わせて画像をマスク(切り取る) scomButton.setTitle("CPUと対戦", for: UIControlState()) scomButton.setTitleColor(UIColor.white, for: UIControlState()) scomButton.setTitle("CPUと対戦", for: UIControlState.highlighted) scomButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) scomButton.layer.cornerRadius = 20.0 //角丸を適用 scomButton.layer.position = CGPoint(x: self.view!.frame.width/2, y:self.view!.frame.height/2) scomButton.addTarget(self, action: #selector(LaunchScene.onClicksCOMButton(_:)), for: .touchUpInside) scomButton.addTarget(self, action: #selector(LaunchScene.touchDownsCOMButton(_:)), for: .touchDown) scomButton.addTarget(self, action: #selector(LaunchScene.enableButtons(_:)), for: .touchUpOutside) self.view!.addSubview(scomButton) scomButton.isHidden=true cancelButton.frame = CGRect(x: 0,y: 0,width: 160,height: 30) cancelButton.backgroundColor = UIColor.gray cancelButton.layer.masksToBounds = true cancelButton.setTitle("キャンセル", for: UIControlState()) cancelButton.setTitleColor(UIColor.white, for: UIControlState()) cancelButton.setTitle("キャンセル", for: UIControlState.highlighted) cancelButton.setTitleColor(UIColor.black, for: UIControlState.highlighted) cancelButton.layer.position = CGPoint(x: 100, y:self.view!.frame.height-20) cancelButton.addTarget(self, action: #selector(self.onClickCancelButton(_:)), for: .touchUpInside) cancelButton.addTarget(self, action: #selector(self.touchDownCancelButton(_:)), for: .touchDown) cancelButton.addTarget(self, action: #selector(self.enableButtons(_:)), for: .touchUpOutside) self.view!.addSubview(cancelButton) cancelButton.isHidden=true } @objc func onClickbjButton(_ sender : UIButton){ bjButton.isHidden=true sjButton.isHidden=true cancelButton.isHidden=false comButton.isHidden=false pvpButton.isHidden=false netButton.isHidden=false sjButton.isEnabled=true //cancel用に戻しておく } @objc func onClicksjButton(_ sender : UIButton){ bjButton.isHidden=true sjButton.isHidden=true cancelButton.isHidden=false scomButton.isHidden=false bjButton.isEnabled=true } @objc func onClickCOMButton(_ sender : UIButton){ //クラス変数を初期化(不要?) Game.pcards.removeAll() Game.deckCards.removeAll() Game.ccards.removeAll() //ボタンを隠す comButton.isHidden=true pvpButton.isHidden=true netButton.isHidden=true cancelButton.isHidden=true Game.mode = .com let gameScene:GameScene = GameScene(size: self.view!.bounds.size) // create your new scene let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions) gameScene.scaleMode = SKSceneScaleMode.fill self.view!.presentScene(gameScene, transition: transition) //GameSceneに移動 } @objc func onClickPVPButton(_ sender : UIButton){ //クラス変数を初期化(不要?) Game.pcards.removeAll() Game.deckCards.removeAll() Game.ccards.removeAll() //ボタンを隠す comButton.isHidden=true pvpButton.isHidden=true netButton.isHidden=true cancelButton.isHidden=true Game.mode = .pvp let gameScene:GameScene = GameScene(size: self.view!.bounds.size) // create your new scene let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions) gameScene.scaleMode = SKSceneScaleMode.fill self.view!.presentScene(gameScene, transition: transition) //GameSceneに移動 } @objc func onClickNetButton(_ sender : UIButton){ //クラス変数を初期化(不要?) Game.pcards.removeAll() Game.deckCards.removeAll() Game.ccards.removeAll() //ボタンを隠す comButton.isHidden=true pvpButton.isHidden=true netButton.isHidden=true cancelButton.isHidden=true Game.mode = .netp1 //setcardでの認識に必要 let gameScene:waitingScene = waitingScene(size: self.view!.bounds.size) // create your new scene let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions) gameScene.scaleMode = SKSceneScaleMode.fill self.view!.presentScene(gameScene, transition: transition) //waitingSceneに移動 } @objc func onClicksCOMButton(_ sender : UIButton){ //クラス変数を初期化(不要?) Game.pcards.removeAll() Game.deckCards.removeAll() Game.ccards.removeAll() //ボタンを隠す scomButton.isHidden=true cancelButton.isHidden=true Game.mode = .scom let gameScene:GameScene = GameScene(size: self.view!.bounds.size) // create your new scene let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions) gameScene.scaleMode = SKSceneScaleMode.fill self.view!.presentScene(gameScene, transition: transition) //GameSceneに移動 } @objc func onClickCancelButton(_ sender : UIButton){ bjButton.isHidden=false sjButton.isHidden=false pvpButton.isHidden=true comButton.isHidden=true netButton.isHidden=true scomButton.isHidden=true cancelButton.isHidden=true pvpButton.isEnabled=true comButton.isEnabled=true netButton.isEnabled=true scomButton.isEnabled=true } //同時押し対策 @objc func touchDownbjButton(_ sender: UIButton){ sjButton.isEnabled=false } @objc func touchDownsjButton(_ sender: UIButton){ bjButton.isEnabled=false } @objc func touchDownCOMButton(_ sender: UIButton){ pvpButton.isEnabled=false netButton.isEnabled=false } @objc func touchDownPVPButton(_ sender: UIButton){ comButton.isEnabled=false netButton.isEnabled=false } @objc func touchDownNetButton(_ sender: UIButton){ comButton.isEnabled=false pvpButton.isEnabled=false } @objc func touchDownsCOMButton(_ sender: UIButton){ } @objc func touchDownCancelButton(_ sender: UIButton){ comButton.isEnabled=false pvpButton.isEnabled=false netButton.isEnabled=false scomButton.isEnabled=false } @objc func enableButtons(_ sender:UIButton){ pvpButton.isEnabled=true comButton.isEnabled=true netButton.isEnabled=true scomButton.isEnabled=true cancelButton.isEnabled=true } @objc func enableButtons2(_ sender:UIButton){ sjButton.isEnabled=true bjButton.isEnabled=true } }
// // _LearningCardNode.swift // Cardify // // Created by Vu Tiep on 2/15/15. // Copyright (c) 2015 Tiep Vu Van. All rights reserved. // import UIKit /** * This is private class, do not use directly */ class _LearningCardNode: ASDisplayNode { var shuffleButton: UIButton! { get { return _shuffleButtonNode.view as UIButton } } private var _shuffleButtonNode: ASDisplayNode! var languageButton: UIButton! { get { return _languageButtonNode.view as UIButton } } private var _languageButtonNode: ASDisplayNode! var textNode: ASTextNode! { get { return _textNode } } private var _textNode: ASTextNode! var speakButton: UIButton! { get { return _speakButtonNode.view as UIButton } } private var _speakButtonNode: ASDisplayNode! var tickButton: UIButton! { get { return _tickButtonNode.view as UIButton } } private var _tickButtonNode: ASDisplayNode! var flipButton: UIButton! { get { return _flipButtonNode.view as UIButton } } private var _flipButtonNode: ASDisplayNode! var numberOfCardsTextNode: ASTextNode!{ get { return _numberOfCardsTextNode } } private var _numberOfCardsTextNode: ASTextNode! var text: String = "" { didSet { setText(text) } } override init!() { super.init() loadNodeHierarchy() loadNodeProperties() } // MARK: - UI Setup func loadNodeHierarchy() { _shuffleButtonNode = ASDisplayNode(viewClass: UIButton.classForCoder()) _languageButtonNode = ASDisplayNode(viewClass: UIButton.classForCoder()) _speakButtonNode = ASDisplayNode(viewClass: UIButton.classForCoder()) _tickButtonNode = ASDisplayNode(viewClass: UIButton.classForCoder()) _flipButtonNode = ASDisplayNode(viewClass: UIButton.classForCoder()) _textNode = ASTextNode() _textNode.layerBacked = true _numberOfCardsTextNode = ASTextNode() _numberOfCardsTextNode.layerBacked = true addSubnode(_shuffleButtonNode) addSubnode(_languageButtonNode) addSubnode(_speakButtonNode) addSubnode(_tickButtonNode) addSubnode(_flipButtonNode) addSubnode(_textNode) addSubnode(_numberOfCardsTextNode) } func loadNodeProperties() { languageButton.setBackgroundImage(UIImage(named: "flag"), forState: .Normal) shuffleButton.setBackgroundImage(UIImage(named: "shuffe_button_icon"), forState: .Normal) speakButton.setBackgroundImage(UIImage(named: "speak_button_icon"), forState: .Normal) tickButton.setBackgroundImage(UIImage(named: "tick_button_icon"), forState: .Normal) flipButton.setBackgroundImage(UIImage(named: "flip_button_icon"), forState: .Normal) _textNode.truncationMode = .ByTruncatingTail flipButton.addTarget(self, action: "handleFlip", forControlEvents: .TouchUpInside) _numberOfCardsTextNode.attributedString = NSAttributedString(string: "18 / 150", attributes: [NSFontAttributeName: UIFont.latoFontWithSize(17), NSForegroundColorAttributeName: UIColor.rgba(0, green: 0, blue: 0, alpha: 0.7)]) } func handleFlip() { } // MARK: - Accessor private func setText(text: String) { let textNodeParagraphStyle = NSMutableParagraphStyle() textNodeParagraphStyle.alignment = .Center _textNode.attributedString = NSAttributedString(string: text, attributes: [NSFontAttributeName: UIFont.latoFontWithSize(25, fontStyle: .Light), NSForegroundColorAttributeName: UIColor.rgba(0, green: 0, blue: 0, alpha: 0.7), NSParagraphStyleAttributeName: textNodeParagraphStyle]) } // MARK: - UI Layout, Sizing // // override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize { // let numberOfCardsTextNodeCalculatedSize = _numberOfCardsTextNode.measure(CGSizeMake(bounds.width, 20)) // return CGSizeMake(0, 0) // } override func layout() { _languageButtonNode.frame = CGRectMake(bounds.maxX - 50, 3, 44, 44) _shuffleButtonNode.frame = CGRectMake(_languageButtonNode.frame.minX - 48, 3, 44, 44) _tickButtonNode.frame = CGRectMake(0, bounds.maxY - 120.5, 62.5, 62.5) _tickButtonNode.position = CGPointMake(bounds.midX, _tickButtonNode.position.y) _speakButtonNode.frame = CGRectMake(29.5, _tickButtonNode.frame.minY, 62.5, 62.5) _flipButtonNode.frame = CGRectMake(bounds.maxX - 92, _tickButtonNode.frame.minY, 62.5, 62.5) let numberOfCardsTextNodeCalculatedSize = _numberOfCardsTextNode.calculateSizeThatFits(CGSizeMake(bounds.width, 20)) _numberOfCardsTextNode.frame = CGRectMake(0, bounds.maxY - (18 + numberOfCardsTextNodeCalculatedSize.height), numberOfCardsTextNodeCalculatedSize.width, numberOfCardsTextNodeCalculatedSize.height) _numberOfCardsTextNode.position = CGPointMake(bounds.midX, _numberOfCardsTextNode.position.y) rePositionTextNode() } private func rePositionTextNode() { let textNodePadding: CGFloat = 20 setText(text) let textNodeRect = rectForTextNode() let textNodeCalculatedSize = _textNode.calculateSizeThatFits(CGRectInset(textNodeRect, textNodePadding, textNodePadding).size) _textNode.frame = CGRectMake(0, 0, CGRectInset(textNodeRect, textNodePadding, textNodePadding).size.width, textNodeCalculatedSize.height) _textNode.position = CGPointMake(bounds.midX, textNodeRect.minY + textNodeRect.height / 2) } func rectForTextNode() -> CGRect { return CGRectMake(0, _shuffleButtonNode.frame.maxY, bounds.width, _speakButtonNode.frame.minY - _shuffleButtonNode.frame.maxY) } }
// // Serializable.swift // Skunk // // Created by Josh on 9/22/15. // Copyright © 2015 CS408. All rights reserved. // import Foundation protocol Serializable { func serialize() -> AnyObject }
// // XMCLockViewController.swift // dojo-homekit // // Created by Forrest Zhao on 10/27/16. // Copyright © 2016 David McGraw. All rights reserved. // import UIKit import HomeKit class XMCLockViewController: UIViewController, HMAccessoryDelegate { @IBOutlet weak var lockCurrentStateSwitch: UISwitch! @IBOutlet weak var lockTargetStateSwitch: UISwitch! @IBOutlet weak var unlockedImage: UIImageView! @IBOutlet weak var lockedImage: UIImageView! var lockImage: UIImageView! var lockCurrentStateValue: HMCharacteristicValueLockMechanismState? // var lockTargetStateValue: // --- Find type for this var accessory: HMAccessory? var lockService: HMService? var lockTargetState: HMCharacteristic? var lockCurrentState: HMCharacteristic? override func viewDidLoad() { super.viewDidLoad() unlockedImage.isHidden = true for service in accessory!.services { if service.serviceType == HMServiceTypeLockMechanism { lockService = service } } currentLockStatus() accessory?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeLockCurrentState(_ sender: UISwitch) { if sender.isOn { lockTargetState?.writeValue(1, completionHandler: { (error) in if error != nil { print("Error during attempt to update service") } else { self.animatelock() } }) } else { lockTargetState?.writeValue(0, completionHandler: { (error) in if error != nil{ print("Error during attempt to update service") } else { self.animateUnlock() } }) } } func currentLockStatus() { for item in (lockService?.characteristics)!{ let characteristic = item as HMCharacteristic if let metadata = characteristic.metadata as HMCharacteristicMetadata? { if metadata.manufacturerDescription == "Lock Target State" { lockTargetState = characteristic } } if let metadata = characteristic.metadata as HMCharacteristicMetadata? { if metadata.manufacturerDescription == "Lock Current State" { lockCurrentState = characteristic } } } } func animatelock() { UIView.animate(withDuration: 10, delay: 0, options: .curveEaseInOut, animations: { self.unlockedImage.isHidden = true self.lockedImage.isHidden = false }, completion: nil) } func animateUnlock() { UIView.animate(withDuration: 10, delay: 0, options: .curveEaseInOut, animations: { self.unlockedImage.isHidden = false self.lockedImage.isHidden = true }, completion: nil) } }
// // ViewController.swift // Exercise2 // // Created by Dinesh on 9/13/17. // Copyright © 2017 cpl. All rights reserved. // import UIKit class ViewController: UIViewController, RegisterViewControllerDelegate { var usersDict:[String:String] = ["admin":"admin"] var enteredUsername:String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { lblError.isHidden = true lblUsername.text = "" lblPassword.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var lblUsername: UITextField! @IBOutlet weak var lblPassword: UITextField! @IBOutlet weak var lblError: UILabel! @IBAction func checkValidUser(_ sender: Any) { enteredUsername = self.lblUsername.text if ( usersDict[enteredUsername!] == self.lblPassword.text! ) { lblError.isHidden = true self.performSegue(withIdentifier: "login2Home", sender: self) } else { lblError.isHidden = false } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "login2Home") { let dvc = segue.destination as! HomeViewController dvc.user = enteredUsername! } else if(segue.identifier == "login2Register") { let dvc = segue.destination as! RegisterViewController dvc.delegate = self } } func registerViewControllerResponse(username:String, password:String) { usersDict[username] = password } }
// // BatchNormRelu.swift // paddle-mobile // // Created by zhangxinjun on 2018/8/23. // Copyright © 2018年 orange. All rights reserved. // import Foundation class BatchNormReluParam<P: PrecisionType>: BatchNormParam<P> { } class BatchNormReluKernel<P: PrecisionType>: Kernel, Computable{ typealias ParamType = BatchNormReluParam<P> var newScale: MTLBuffer var newBias: MTLBuffer required init(device: MTLDevice, testParam: BatchNormReluTestParam) { newScale = testParam.newScaleBuffer newBias = testParam.newBiaseBuffer super.init(device: device, inFunctionName: "batch_norm_relu_3x3") } required init(device: MTLDevice, param: BatchNormReluParam<P>) { guard let newScale = device.makeBuffer(length: param.inputScale.buffer.length) else { fatalError() } guard let newBias = device.makeBuffer(length: param.inputBias.buffer.length) else { fatalError() } self.newScale = newScale self.newBias = newBias super.init(device: device, inFunctionName: "batch_norm_relu_3x3") let varianceBuffer : MTLBuffer = param.inputVariance.buffer var invStd: [Float32] = Array(repeating: 0, count: varianceBuffer.length) let varianceContents = varianceBuffer.contents().assumingMemoryBound(to: P.self) for i in 0..<(varianceBuffer.length / MemoryLayout<P>.stride) { invStd[i] = 1 / (Float32(varianceContents[i]) + param.epsilon).squareRoot() } let newScaleContents = newScale.contents().assumingMemoryBound(to: P.self) let newBiasContents = newBias.contents().assumingMemoryBound(to: P.self) let scale : MTLBuffer = param.inputScale.buffer let scaleContents = scale.contents().assumingMemoryBound(to: P.self) let bias : MTLBuffer = param.inputBias.buffer let biasContents = bias.contents().assumingMemoryBound(to: P.self) let meanContents = param.inputMean.buffer.contents().assumingMemoryBound(to: P.self) for i in 0..<(newScale.length / MemoryLayout<P>.stride) { newScaleContents[i] = P(invStd[i] * Float32(scaleContents[i])) newBiasContents[i] = P(Float32(biasContents[i]) - Float32(meanContents[i]) * invStd[i] * Float32(scaleContents[i])) } } func compute(commandBuffer: MTLCommandBuffer, param: BatchNormReluParam<P>) throws { guard let encoder = commandBuffer.makeComputeCommandEncoder() else { fatalError() } encoder.setTexture(param.input as? MTLTexture, index: 0) encoder.setTexture(param.output as? MTLTexture, index: 1) encoder.setBuffer(newScale, offset: 0, index: 1) encoder.setBuffer(newBias, offset: 0, index: 1) encoder.dispatch(computePipline: pipline, outTexture: param.output as! MTLTexture) encoder.endEncoding() } func testCompute(commandBuffer: MTLCommandBuffer, testParam: BatchNormReluTestParam) throws { guard let encoder = commandBuffer.makeComputeCommandEncoder() else { fatalError() } encoder.setTexture(testParam.inputTexture, index: 0) encoder.setTexture(testParam.outputTexture, index: 1) encoder.setBuffer(newScale, offset: 0, index: 0) encoder.setBuffer(newBias, offset: 0, index: 1) encoder.dispatch(computePipline: pipline, outTexture: testParam.outputTexture) encoder.endEncoding() } }
// // NetworkService.swift // Puzzles // // Created by Leonid Serebryanyy on 18.11.2019. // Copyright © 2019 Leonid Serebryanyy. All rights reserved. // import Foundation import UIKit class NetworkService { let session: URLSession init() { session = URLSession(configuration: .default) } var results = [UIImage]() // MARK:- Первое задание public func loadPuzzle(completion: @escaping (Result<UIImage, Error>) -> ()) { let firstURL = URL(string: "https://storage.googleapis.com/ios_school/tu.png")! let secondURL = URL(string: "https://storage.googleapis.com/ios_school/pik.png")! let thirdURL = URL(string: "https://storage.googleapis.com/ios_school/cm.jpg")! let fourthURL = URL(string: "https://storage.googleapis.com/ios_school/apple.jpeg")! let urls = [firstURL, secondURL, thirdURL, fourthURL] let myGroup = DispatchGroup() for url in urls { myGroup.enter() let task = self.session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in if let error = error { print(error) myGroup.leave() return } if let data = data { if let image = UIImage(data: data) { self.results.append(image) myGroup.leave() } } } task.resume() } myGroup.notify(queue: DispatchQueue.main) { if let merged = ImagesServices.image(byCombining: self.results) { completion(.success(merged)) } } } // MARK:- Второе задание public func loadQuiz(completion: @escaping(Result<UIImage, Error>) -> ()) { let keyURL = URL(string: "https://sberschool-c264c.firebaseio.com/enigma.json?avvrdd_token=AIzaSyDqbtGbRFETl2NjHgdxeOGj6UyS3bDiO-Y")! self.session.dataTask(with: keyURL) { data, response, error in if let error = error { completion(.failure(error)) return } if let data = data, let str = String(data: data, encoding: .utf8) { let newStr = str.replacingOccurrences(of: "\"", with: "") guard let newUrl = URL(string: newStr) else { return } self.session.dataTask(with: newUrl) { data, response, error in if let error = error { completion(.failure(error)) return } if let data = data { if let image = UIImage(data: data) { completion(.success(image)) } } } .resume() } } .resume() } }
// // CustomTableViewCell.swift // SpinerViewiOS // // Created by SumitKumar on 01/06/18. // Copyright © 2018 SumitKumar. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } open override func awakeFromNib() { } }
// // WordCountCell.swift // FileAnalyzer // // Created by Carlos Gonzalez on 24/4/21. // import UIKit class WordCountCell: UITableViewCell { static let TAG = String(describing: WordCountCell.self) @IBOutlet weak var tv_word: UILabel! @IBOutlet weak var tv_count: UILabel! override func awakeFromNib() { super.awakeFromNib() } public func setCell(word: String, count: Int) { tv_word.text = word tv_count.text = String(count) } }
// // SearchUserTableViewCell.swift // The MIT License (MIT) // // Copyright (c) 2020 Kyujin Kim // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import SnapKit import Kingfisher final class SearchUserTableViewCell: UITableViewCell { private let avatarImageView: UIImageView = UIImageView() private let userNameLabel: UILabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initialize() } required init?(coder: NSCoder) { super.init(coder: coder) initialize() } private func initialize() { addSubview() layout() style() } private func addSubview() { addSubview(avatarImageView) addSubview(userNameLabel) } private func layout() { avatarImageView.snp.makeConstraints { $0.top.leading.bottom.equalToSuperview().inset(8.0) $0.width.equalTo(avatarImageView.snp.height).multipliedBy(1 / 1) } userNameLabel.snp.makeConstraints { $0.leading.equalTo(avatarImageView.snp.trailing).offset(8.0) $0.trailing.equalToSuperview().inset(8.0) $0.centerY.equalToSuperview() } } private func style() { avatarImageView.backgroundColor = .lightGray avatarImageView.kf.indicatorType = .activity } func configuration(imageUrl: String, userName: String) { avatarImageView.kf.setImage(with: URL(string: imageUrl)!) userNameLabel.text = userName } }
// // MapView.swift // sfu_commute_V.2 // // Created by jyotsna jaswal on 2016-10-30. // Copyright © 2016 jyotsna jaswal. All rights reserved. // import Foundation import UIKit import CoreLocation import FontAwesome_swift import SwiftyButton import GoogleMaps import DGRunkeeperSwitch import Alamofire import SwiftyJSON /* var maximumSpeed:Double = 0.0 let lineColours = [ UIColor.red, UIColor.orange, UIColor.white, UIColor.green, UIColor.blue ] extension CLLocation { func lineColour() -> UIColor{ let normalisedSpeed = self.speed / maximumSpeed if normalisedSpeed < 0.2 {return lineColours[0];} else if normalisedSpeed < 0.4 {return lineColours[1];} else if normalisedSpeed < 0.6 {return lineColours[2] } else if normalisedSpeed < 0.8 {return lineColours[3]} else {return lineColours[4]} } } class ColourPolyline: MGLPolyline { // Because this is a subclass of MGLPolyline, there is no need to redeclare its properties. // Custom property that we will use when drawing the polyline. var color = UIColor.darkGray } extension Double { func format(f: String) -> String { return String(format: "%.\(f)f", self) } } enum speedUnit { case knotsPerHour case metersPerSecond case kilometersPerHour case milesPerHour case feetPerSecond } struct SpeedDisplay { var metersPerSecond = 0.0 var kilometersPerHour: Double { get { return 3.6 * self.metersPerSecond } } var milesPerHour: Double { get { return 2.23694 * self.metersPerSecond } } var knotsPerHour: Double { get { return 1.94384 * self.metersPerSecond } } var feetPerSecond: Double { get { return 3.28084 * self.metersPerSecond } } init(speedMetersPerSecond:Double){ self.metersPerSecond = speedMetersPerSecond } func speedInUnits(units:speedUnit) -> Double{ switch units{ case .metersPerSecond: return self.metersPerSecond case .feetPerSecond: return self.feetPerSecond case .kilometersPerHour: return self.kilometersPerHour case .milesPerHour: return self.milesPerHour default: return 0.0 } } func speedInLabel(units:speedUnit) -> String{ return self.speedInUnits(units: units).format(f: "1") } func labelForUnit(units:speedUnit) -> String{ switch units{ case .metersPerSecond: return "m/s" case .feetPerSecond: return "ft/s" case .kilometersPerHour: return "kph" case .milesPerHour: return "mph" default: return "" } } }*/ enum mapViewSteps { case toSetStartLocation case toSetDestination case toTapCreateButton } enum role : String{ case request case offer } class MapView: UIViewController, GMSMapViewDelegate { /* let manager = CLLocationManager() var firstPoint = true var lastCoordinate: CLLocation? var lastSpeed = SpeedDisplay(speedMetersPerSecond: 0) var currentUnits = speedUnit.metersPerSecond @IBOutlet weak var header2View: UIView! @IBOutlet weak var currentUnitsLabel: UILabel! @IBOutlet weak var currentSpeedLabel: UILabel! */ var role : role = .request var status : mapViewSteps = .toSetStartLocation // UI @IBOutlet var locationBox: UIView! @IBOutlet var navItem: UINavigationItem! @IBOutlet var mapView: UIView! var googlemap : GMSMapView = GMSMapView() var createTripButton : FlatButton = FlatButton() var locationBoxSearchButton: FlatButton! = FlatButton() let locationBoxIcon = UILabel() let locationBoxLabel = UILabel() let startLocation = UILabel() var locationBox2 = UIView() var locationBox2SearchButton: FlatButton! = FlatButton() let locationBoxIcon2 = UILabel() let locationBoxLabel2 = UILabel() let destination = UILabel() let roleSwitch = DGRunkeeperSwitch(titles: ["Request a ride" , "Offer a ride"]) var offerStart = GMSMarker() var offerDestination = GMSMarker() var offerRoute = GMSPolyline() var emptyMarker = GMSMarker() override func viewDidLoad() { super.viewDidLoad() initNavBar() initLocationBox() initButton() initMap() initSwitch() } override func viewWillAppear(_ animated: Bool) { updateStatus() } override func viewDidAppear(_ animated: Bool) { if (offerStart.position.latitude != emptyMarker.position.latitude && offerDestination.position.latitude == emptyMarker.position.latitude){ animateStart() } if (offerStart.position.latitude != emptyMarker.position.latitude && offerDestination.position.latitude != emptyMarker.position.latitude){ drawRoute() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initMap() { mapView.snp.makeConstraints{(make) -> Void in make.top.equalTo(locationBox.snp.bottom) make.left.right.bottom.equalTo(self.view) } mapView.clipsToBounds = true let camera = GMSCameraPosition.camera(withLatitude: 49.253480, longitude: -122.918631, zoom: 12) googlemap = GMSMapView.map(withFrame: CGRect.zero, camera: camera) googlemap.delegate = self googlemap.settings.myLocationButton = true googlemap.isMyLocationEnabled = true // move my location button up googlemap.padding = UIEdgeInsets(top: 0, left: 0, bottom: 70, right: 0) do { if let styleURL = Bundle.main.url(forResource: "style-flat", withExtension: "json") { googlemap.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL) } else { NSLog("Unable to find style.json") } } catch { NSLog("The style definition could not be loaded: \(error)") } renderPreDeterminedLocations() mapView.addSubview(googlemap) googlemap.snp.makeConstraints{(make) -> Void in make.left.right.top.bottom.equalTo(mapView) } } func updateStatus() { infoWindow.removeFromSuperview() if (status == .toSetStartLocation) { self.navigationItem.prompt = "Please search for start location" } else if (status == .toSetDestination) { appendLocationBox() self.navigationItem.prompt = "Please search for destination" } else if (status == .toTapCreateButton) { self.navigationItem.prompt = nil createTripButton.isEnabled = true } } func animateStart(){ googlemap.animate(with: GMSCameraUpdate.setTarget(offerStart.position, zoom: 13)) } func drawRoute() { offerRoute.map = nil let parameters : Parameters = [ "origin": "\(offerStart.position.latitude),\(offerStart.position.longitude)", "destination": "\(offerDestination.position.latitude),\(offerDestination.position.longitude)", "key": "AIzaSyAJF2MhJpuiPLRB9l_o7Zlp2v9Wj6Hv0rU" ] Alamofire.request("https://maps.googleapis.com/maps/api/directions/json", method: .get, parameters: parameters).responseJSON { response in switch response.result{ case .success(let value): let json = JSON(value) if (json["status"] == "OK") { self.offerRoute = GMSPolyline.init(path: GMSPath.init(fromEncodedPath: json["routes"][0]["overview_polyline"]["points"].stringValue)) self.offerRoute.strokeColor = Colors.SFUBlue self.offerRoute.strokeWidth = 2.5 self.offerRoute.map = self.googlemap self.googlemap.animate(with: GMSCameraUpdate.fit(GMSCoordinateBounds.init(path: GMSPath.init(fromEncodedPath: json["routes"][0]["overview_polyline"]["points"].stringValue)!), with: UIEdgeInsetsMake(120, 50, 120, 50))) } case .failure(let error): print(error) } } } func initSwitch(){ roleSwitch.backgroundColor = Colors.SFUBlue roleSwitch.selectedBackgroundColor = .white roleSwitch.titleColor = .white roleSwitch.selectedTitleColor = Colors.SFUBlue roleSwitch.titleFont = UIFont(name: "Futura-Medium", size: 13.0) roleSwitch.frame = CGRect(x: 30.0, y: 40.0, width: 200.0, height: 30.0) roleSwitch.addTarget(self, action: #selector(self.switchRole(_:)), for: .valueChanged) navigationItem.titleView = roleSwitch } func renderPreDeterminedLocations() { googlemap.clear() if (roleSwitch.selectedIndex == 0){ for location in preDeterminedLocations { let marker = GMSMarker() marker.position = CLLocationCoordinate2DMake(location.lat, location.lon) marker.appearAnimation = kGMSMarkerAnimationPop marker.icon = UIImage(named: "map-man-red-64") marker.userData = location marker.infoWindowAnchor = CGPoint(x: 0.5, y: -0.5) marker.opacity = 0.8 marker.map = googlemap } } } func switchRole(_ sender: Any?){ startLocation.text = "" destination.text = "" googlemap.clear() infoWindow.removeFromSuperview() renderPreDeterminedLocations() if (role == .request) { role = .offer } else { role = .request } } func initLocationBox() { // initialize button locationBoxSearchButton.tag = 1 locationBoxSearchButton.setTitle(String.fontAwesomeIcon(code: "fa-search"), for: .normal) locationBoxSearchButton.titleLabel?.font = UIFont.fontAwesome(ofSize: 32) locationBoxSearchButton.color = Colors.SFURed locationBoxSearchButton.highlightedColor = Colors.SFURedHighlight locationBoxSearchButton.cornerRadius = 10.0 locationBoxSearchButton.addTarget(self, action: #selector(self.search(_:)), for: .touchUpInside) self.locationBox.addSubview(locationBoxSearchButton) locationBoxSearchButton.snp.makeConstraints{(make) -> Void in make.height.width.equalTo(locationBox.snp.height).offset(-10) make.right.equalTo(locationBox).offset(-10) make.centerY.equalTo(locationBox) } // initialize icon locationBoxIcon.font = UIFont.fontAwesome(ofSize: 32) locationBoxIcon.text = String.fontAwesomeIcon(code: "fa-map-marker") locationBoxIcon.textColor = Colors.SFURed self.locationBox.addSubview(locationBoxIcon) locationBoxIcon.snp.makeConstraints{(make) -> Void in make.height.width.equalTo(locationBox.snp.height).offset(-32) make.left.equalTo(locationBox).offset(12) make.centerY.equalTo(locationBox) } // initialize label locationBoxLabel.text = "START LOCATION" locationBoxLabel.textAlignment = .left locationBoxLabel.font = UIFont(name: "Futura-Medium", size: 16)! locationBoxLabel.textColor = Colors.SFURed self.locationBox.addSubview(locationBoxLabel) locationBoxLabel.snp.makeConstraints{(make) -> Void in make.width.equalTo(150) make.height.equalTo(30) make.left.equalTo(locationBoxIcon.snp.right) make.top.equalTo(locationBox) } // initialize label startLocation.text = "" startLocation.textAlignment = .left startLocation.font = UIFont(name: "Futura-Medium", size: 18)! startLocation.textColor = UIColor.black self.locationBox.addSubview(startLocation) startLocation.snp.makeConstraints{(make) -> Void in make.left.equalTo(locationBoxIcon.snp.right) make.right.equalTo(locationBoxSearchButton.snp.left) make.top.equalTo(locationBoxLabel.snp.bottom).offset(-10) make.bottom.equalTo(locationBox) } } // append second location box programatically // the second location box has the same height and background as the first one func appendLocationBox(){ locationBox2 = UIView(frame: CGRect(x: 0, y: locationBox.frame.maxY, width: self.view.frame.width, height: locationBox.frame.height)) locationBox2.backgroundColor = locationBox.backgroundColor locationBox2.bottomBorder = 1.0 locationBox2.VborderColor = UIColor.darkGray self.view.addSubview(locationBox2) mapView.snp.remakeConstraints{(make) -> Void in make.top.equalTo(locationBox2.snp.bottom) make.left.right.bottom.equalTo(self.view) } locationBox2.snp.makeConstraints{(make) -> Void in make.left.right.equalTo(self.view) make.top.equalTo(locationBox.snp.bottom) make.height.equalTo(locationBox.frame.height) } // initialize button locationBox2SearchButton.tag = 2 locationBox2SearchButton.setTitle(String.fontAwesomeIcon(code: "fa-search"), for: .normal) locationBox2SearchButton.titleLabel?.font = UIFont.fontAwesome(ofSize: 32) locationBox2SearchButton.color = Colors.SFUBlue locationBox2SearchButton.highlightedColor = Colors.SFUBlueHighlight locationBox2SearchButton.cornerRadius = 10.0 locationBox2SearchButton.addTarget(self, action: #selector(self.search(_:)), for: .touchUpInside) locationBox2.addSubview(locationBox2SearchButton) locationBox2SearchButton.snp.makeConstraints{(make) -> Void in make.height.width.equalTo(locationBox2.snp.height).offset(-10) make.right.equalTo(locationBox2).offset(-10) make.centerY.equalTo(locationBox2) } // initialize icon locationBoxIcon2.font = UIFont.fontAwesome(ofSize: 32) locationBoxIcon2.text = String.fontAwesomeIcon(code: "fa-map-marker") locationBoxIcon2.textColor = Colors.SFUBlue locationBox2.addSubview(locationBoxIcon2) locationBoxIcon2.snp.makeConstraints{(make) -> Void in make.height.width.equalTo(locationBox2.snp.height).offset(-32) make.left.equalTo(locationBox2).offset(12) make.centerY.equalTo(locationBox2) } // initialize label locationBoxLabel2.text = "DESTINATION" locationBoxLabel2.textAlignment = .left locationBoxLabel2.font = UIFont(name: "Futura-Medium", size: 16)! locationBoxLabel2.textColor = Colors.SFUBlue locationBox2.addSubview(locationBoxLabel2) locationBoxLabel2.snp.makeConstraints{(make) -> Void in make.width.equalTo(150) make.height.equalTo(30) make.left.equalTo(locationBoxIcon2.snp.right) make.top.equalTo(locationBox2) } // initialize label destination.text = "" destination.textAlignment = .left destination.font = UIFont(name: "Futura-Medium", size: 18)! destination.textColor = UIColor.black locationBox2.addSubview(destination) destination.snp.makeConstraints{(make) -> Void in make.left.equalTo(locationBoxIcon2.snp.right) make.right.equalTo(locationBox2SearchButton.snp.left) make.top.equalTo(locationBoxLabel2.snp.bottom).offset(-10) make.bottom.equalTo(locationBox2) } } func search(_ sender: Any?) { let data = dataForSearchController(status: self.status, role: self.role, button: (sender as! FlatButton).tag) self.performSegue(withIdentifier: "showSearchAddress", sender: data) } func initNavBar() { let leftBarIconButton = UIBarButtonItem() let attributes = [NSFontAttributeName: UIFont.fontAwesome(ofSize: 24)] as [String: Any] leftBarIconButton.setTitleTextAttributes(attributes, for: .normal) leftBarIconButton.title = String.fontAwesomeIcon(code: "fa-bars") leftBarIconButton.target = self.revealViewController() leftBarIconButton.action = #selector(SWRevealViewController.revealToggle(_:)) navItem.leftBarButtonItem = leftBarIconButton self.mapView.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) revealViewController().rearViewRevealWidth = view.frame.width - 80 } func initButton() { createTripButton.SFURedDefault("Create a trip") createTripButton.isEnabled = false //createTripButton.addTarget(self, action: #selector(self.signUpTapped(_:)), for: .touchUpInside) self.view.addSubview(createTripButton) createTripButton.wideBottomConstraints(superview: self.view) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showSearchAddress") { let data = sender as! dataForSearchController let search = segue.destination as! addressSearchViewController search.status = data.status search.role = data.role search.triggerButton = data.button print(search.status) print(search.role) print(search.triggerButton) } } @IBAction func unwindToMapView(segue: UIStoryboardSegue) { } // MARK: google map delegate // initialize and keep a marker var tappedMarker = GMSMarker() var infoWindow = mapMarkerInfoWindow(frame: CGRect(x: 0, y: 0, width: 200, height: 100), status: .toSetStartLocation) //empty the default infowindow func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { return UIView() } // create custom infowindow whenever marker is tapped func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { if (role == .request){ let location = CLLocationCoordinate2D(latitude: (marker.userData as! location).lat, longitude: (marker.userData as! location).lon) tappedMarker = marker infoWindow.removeFromSuperview() infoWindow = mapMarkerInfoWindow(frame: CGRect(x: 0, y: 0, width: 200, height: 100), status: self.status) infoWindow.Name.text = (marker.userData as! location).name infoWindow.Price.text = (marker.userData as! location).price.description infoWindow.Zone.text = (marker.userData as! location).zone.rawValue infoWindow.center = mapView.projection.point(for: location) if (status == .toSetStartLocation) { infoWindow.center.y += 80 infoWindow.onlyButton.addTarget(self, action: #selector(setStartLocation(_:)), for: .touchUpInside) } else { if (status == .toSetDestination) { infoWindow.center.y += 140 } else { infoWindow.center.y += 110 } infoWindow.leftButton.addTarget(self, action: #selector(setStartLocation(_:)), for: .touchUpInside) infoWindow.rightButton.addTarget(self, action: #selector(setDestination(_:)), for: .touchUpInside) } self.view.addSubview(infoWindow) } return false } func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) { if (tappedMarker.userData != nil){ let location = CLLocationCoordinate2D(latitude: (tappedMarker.userData as! location).lat, longitude: (tappedMarker.userData as! location).lon) infoWindow.center = mapView.projection.point(for: location) // weird offset if (status == .toSetStartLocation) { infoWindow.center.y += 80 } else if (status == .toSetDestination){ infoWindow.center.y += 140 } else { infoWindow.center.y += 110 } } } func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) { infoWindow.removeFromSuperview() } func setStartLocation(_ sender: Any?) { startLocation.text = (tappedMarker.userData as! location).name if(status == .toSetStartLocation) { status = .toSetDestination updateStatus() } else { infoWindow.removeFromSuperview() } } func setDestination(_ sender: Any?) { destination.text = (tappedMarker.userData as! location).name if(status == .toSetDestination) { status = .toTapCreateButton updateStatus() } else { infoWindow.removeFromSuperview() } } /* @IBAction func hiDidGetPressed(_ sender: UIButton) { print("hi \(mapView)") } private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .authorizedAlways || status == .authorizedWhenInUse { manager.startUpdatingLocation() // ... } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if firstPoint { lastCoordinate = locations.first! mapView.setCenter(locations.last!.coordinate, zoomLevel: 11, animated: true) firstPoint = false } drawPolyline(locations: locations,colour: locations.last!.lineColour()) lastCoordinate = locations.last! lastSpeed = SpeedDisplay(speedMetersPerSecond: locations.last!.speed) self.currentSpeedLabel.text = lastSpeed.speedInLabel(units: self.currentUnits) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } func setupMap(){ mapView.delegate = self //MGLStyle.darkStyleURL(withVersion: 1) mapView.styleURL = MGLStyle.streetsStyleURL(withVersion: 9) } func setupLocationManager(){ // Do any additional setup after loading the view, typically from a nib. if CLLocationManager.locationServicesEnabled() { manager.startUpdatingLocation() }else if CLLocationManager.authorizationStatus() == .notDetermined { manager.requestAlwaysAuthorization() } manager.delegate = self manager.requestLocation() manager.requestWhenInUseAuthorization() manager.requestAlwaysAuthorization() manager.desiredAccuracy = kCLLocationAccuracyBest manager.startUpdatingLocation() mapView.showsUserLocation = true } func blurTitleViews(){ let degrees:Double = -45; //the value in degrees let rotation = CGFloat( degrees * M_PI/180.0) let rotate = CGAffineTransform(rotationAngle: rotation); let translate = CGAffineTransform(translationX: 48, y: 100) header2View.transform = translate.concatenating(rotate); header2View.clipsToBounds = true if !UIAccessibilityIsReduceTransparencyEnabled() { self.header2View.backgroundColor = UIColor.clear let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let header2BlurEffectView = UIVisualEffectView(effect: blurEffect) header2BlurEffectView.frame = self.header2View.bounds header2BlurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.header2View.insertSubview(header2BlurEffectView, at: 0) } else { self.header2View.backgroundColor = UIColor.black } } func shouldChangeSpeedUnits(){ } func drawPolyline(locations: [CLLocation], colour:UIColor) { var coordinates:[CLLocationCoordinate2D] = [] coordinates.append(lastCoordinate!.coordinate) // Parsing GeoJSON can be CPU intensive, do it on a background thread DispatchQueue.global(qos: .userInitiated).async { for location in locations{ coordinates.append(location.coordinate) } let line = ColourPolyline(coordinates: &coordinates, count: UInt(coordinates.count)) line.color = colour // Bounce back to the main thread to update the UI DispatchQueue.main.async { self.mapView.addAnnotation(line) } } } func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor { print("Drawing map view") if let annotation = annotation as? ColourPolyline { // Return orange if the polyline does not have a custom color. return annotation.color } // Fallback to the default tint color. return mapView.tintColor } */ }
// // Created by 和泉田 領一 on 2020/02/02. // import Foundation import Combine import SwiftSphere import CombineAsync enum GitHubSearchSphere: SphereProtocol { struct Model { var repos: [GitHubRepo] = [] var selectedRepo: GitHubRepo? = .none var error: String? = .none } enum Event { case search(String) case selectRepo(GitHubRepo?) } static func update(event: Event, context: Context<Model, GitHubReposRepositoryProtocol>) -> Async<Model> { async { yield in switch event { case .search(let text): if text.isEmpty { yield(Model(repos: [])) } else { yield(context .coordinator .search(text.trimmingCharacters(in: .whitespaces)) .map { Model(repos: $0) } .catch { Just(Model(error: $0.localizedDescription)) }) } case .selectRepo(let repo): yield(Model(repos: context.coordinator.searchedRepos, selectedRepo: repo)) } } } static func makeModel(coordinator: GitHubReposRepositoryProtocol) -> Async<Model> { async { yield in yield(Model()) } } }
// // ProductTableViewCell.swift // TesteLazaroOpa // // Created by Lazaro Neto on 06/11/2018. // Copyright © 2018 opateste. All rights reserved. // import UIKit class ProductTableViewCell: UITableViewCell { @IBOutlet weak var labelName: UILabel! @IBOutlet weak var labelPrice: UILabel! @IBOutlet weak var btFavorite: UIButton! var listDelegate: ProductsFavoritesTableViewProtocol? var product: Product!{ didSet { self.fillLabels() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func fillLabels() { self.labelName?.text = self.product.name if let price = self.product.price { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "pt_BR") formatter.currencyCode = "BRL" formatter.numberStyle = .currency let numberPrice = NSNumber(value: price) self.labelPrice.text = formatter.string(from: numberPrice) } self.btFavorite.setImage(UIImage(named: "favorite_empty"), for: .normal) if let _ = LocalData.findById(product: self.product) { self.btFavorite.setImage(UIImage(named: "favorite_filled"), for: .normal) } } @IBAction func didTapOnFavorite(_ sender: Any) { self.listDelegate?.favorite(product: self.product) } }
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. // // PerfectPython.swift // Perfect-Python // // Created by Rockford Wei on 2017-08-18. // Copyright © 2017 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2017 - 2018 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PackageDescription let package = Package( name: "PerfectPython", products: [ .library( name: "PerfectPython", targets: ["PerfectPython"]), ], targets: [ .target(name: "PythonAPI", dependencies: []), .target(name: "PerfectPython", dependencies: ["PythonAPI"]), .testTarget(name: "PerfectPythonTests", dependencies: ["PerfectPython"]) ] )
// // UIStoryboard+Coordinators.swift // coordinators // // Created by Lutz Müller on 31.12.16. // Copyright © 2016 Cubinea. All rights reserved. // import UIKit extension UIStoryboard { /// Convenience initializer which omits the bundle name. Loads the storyboard from the main bundle. /// /// - parameter name: the storyboard name /// /// - returns: the new storyboard instance convenience init(name: String) { self.init(name: name, bundle: nil) } }
@testable import TMDb import XCTest final class GenreTests: XCTestCase { func testDecodeReturnsGenre() throws { let result = try JSONDecoder.theMovieDatabase.decode(Genre.self, fromResource: "genre") XCTAssertEqual(result.id, genre.id) XCTAssertEqual(result.name, genre.name) } private let genre = Genre( id: 28, name: "Action" ) }
// // UserRoot.swift // BeeHive // // Created by HyperDesign-Gehad on 7/18/18. // Copyright © 2018 HyperDesign-Gehad. All rights reserved. // import Foundation class UserRoot : Codable { var user :User? var message : String? }
// // PillsVC.swift // Pills // // Created by NG on 12/4/17. // Copyright © 2017 NG. All rights reserved. // import UIKit import Firebase import Foundation class PillsVC: UIViewController, UITableViewDataSource , UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var menuButton: UIButton! override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.async { self.tableView.reloadData() } tableView.insertRows(at: [IndexPath(row: SaveUserSignInfo.mainUser.getPillsNum() - 1, section: 0)], with: .automatic) dismiss(animated: true, completion: nil) menuButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) tableView.dataSource = self tableView.delegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView : UITableView, numberOfRowsInSection section : Int ) -> Int { return SaveUserSignInfo.mainUser.getPillsNum() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "PillCell") as? PillCell { let label = cell.viewWithTag(1000) as! UILabel label.text = SaveUserSignInfo.mainUser.getPills()[indexPath.row].getPillName() let pill = SaveUserSignInfo.mainUser.getPills()[indexPath.row] cell.updateView(pill: pill) return cell }else { return PillCell() } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { var userPills = SaveUserSignInfo.mainUser.getPills() userPills.remove(at: indexPath.row) SaveUserSignInfo.mainUser.setPills(pills: userPills) tableView.deleteRows(at: [indexPath], with: .fade) } } }
// // TimelineAnimationKeyPathExtensions.swift // TimelineAnimations // // Created by Georges Boumis on 11/01/2017. // Copyright © 2017 AbZorba Games. All rights reserved. // import Foundation public enum AnimationKeyPath: String { // CALayer case position = "position" // CGPoint case positionX = "position.x" // CGFloat case positionY = "position.y" // CGFloat case zPosition = "zPosition" // CGFloat case anchorPoint = "anchorPoint" // CGPoint case anchorPointZ = "anchorPointZ" // CGPoint case bounds = "bounds" // CGRect case boundsSize = "bounds.size" // CGSize case width = "bounds.size.width" // CGFloat case height = "bounds.size.height" // CGFloat case frame = "frame" // CGRect case frameSize = "frame.size" // CGSize case transform = "transform" // CATransform3D case sublayerTransform = "sublayerTransform" // CATransform3D case rotation = "transform.rotation" // CGFloat in radians case rotationY = "transform.rotation.y" // CGFloat in radians case scale = "transform.scale" // CGFloat case scaleX = "transform.scale.x" // CGFloat case scaleY = "transform.scale.y" // CGFloat case opacity = "opacity" // CGFloat case shadowOpacity = "shadowOpacity" // CGFloat case shadowRadius = "shadowRadius" // CGFloat case shadowOffset = "shadowOffset" // CGSize case shadowColor = "shadowColor" // CGColor case shadowPath = "shadowPath" // CGPath case contents = "contents" // Any case contentsRect = "contentsRect" // CGRect case contentsCenter = "contentsCenter" // CGRect case masksToBounds = "masksToBounds" // Bool case isDoubleSided = "doubleSided" // Bool case cornerRadius = "cornerRadius" // CGFloat case borderWidth = "borderWidth" // CGFloat case borderColor = "borderColor" // CGColor case isHidden = "hidden" // Bool case backgroundColor = "backgroundColor" // CGColor case filters = "filters" // [CIFilter] case compositingFilter = "compositingFilter" // CIFilter case backgroundFilters = "backgroundFilters" // [CIFilter] case shouldRasterize = "shouldRasterize" // Bool // CAEmitterLayer case emitterPosition = "emitterPosition" // CGPoint case emitterZposition = "emitterZPosition" // CGFloat case emitterSize = "emitterSize" // CGSize case spin = "spin" // Float case velocity = "velocity" // Float case birthRate = "birthRate" // Float case lifetime = "lifetime" // Float // CAShapeLayer properties case fillColor = "fillColor" // CGColor case strokeColor = "strokeColor" // CGColor case lineDashPhase = "lineDashPhase" // CGFloat case lineWidth = "lineWidth" // CGFloat case misterLimit = "misterLimit" // CGFloat case strokeEnd = "strokeEnd" // CGFloat case strokeStart = "strokeStart" // CGFloat case path = "path" // CGPath // CATextLayer properties case fontSize = "fontSize" // CGFloat case foregroundColor = "foregroundColor" // CGColor } public extension AnimationsFactory { final public class func animate(keyPath: AnimationKeyPath, toValue: AnimationsFactory.TypedValue?, duration: TimeInterval = TimeInterval(1.0), timingFunction tf: ECustomTimingFunction = ECustomTimingFunction.linear) -> CAPropertyAnimation { return self.animate(keyPath: keyPath, fromValue: nil, toValue: toValue, duration: duration, timingFunction: tf) } final public class func animate(keyPath: AnimationKeyPath, fromValue: AnimationsFactory.TypedValue?, duration: TimeInterval = TimeInterval(1.0), timingFunction tf: ECustomTimingFunction = ECustomTimingFunction.linear) -> CAPropertyAnimation { return self.animate(keyPath: keyPath, fromValue: fromValue, toValue: nil, duration: duration, timingFunction: tf) } }
//: Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" //********************************************************************* print("Swift Variables") var Vquestion1: Int = 15 var Vquestion2: Int = 5 var Vquestion3: Int = Vquestion1 + Vquestion2 var Vquestion4: Int = Vquestion1 * Vquestion2 var Vquestion5: Int = Vquestion1 - Vquestion2 var Vquestion6: Int = Vquestion1 / Vquestion2 var Vquestion7: String = "Hello" var Vquestion8: String = "World" var Vquestion9: String = Vquestion7 + Vquestion8 //********************************************************************* print("Swift Functions") func add(first: Double, second: Double) -> Double{ return first + second } func subtract(first: Int, second: Int) -> Int { return first - second } func multiply(first: Float, second: Float) -> Float { return first * second } add(first: 1.0, second: 5.0) subtract(first: 5, second: 1) multiply(first: 2.0, second: 5.0) //******************************************************************** print("Swift Arrays") var emptyArray: [String] = [] var doubleArray: [Double] = [1.0, 2.0, 3.0, 4.0] var anyTypeArray = [1, 2, 3, 4, 5] emptyArray.append("a") emptyArray.append("b") emptyArray.append("c") doubleArray.append(5.0) doubleArray.append(6.0) doubleArray.append(7.0) anyTypeArray.append(6) anyTypeArray.append(7) anyTypeArray.append(8) emptyArray.remove(at: 2) doubleArray.remove(at: 3) anyTypeArray.remove(at: 4) anyTypeArray.remove(at: Int(arc4random_uniform(UInt32(anyTypeArray.count)))) doubleArray.removeAll() //******************************************************************* print("Swift Loop") var oddNumbers: [Int] = [] for odd in 1...100 { oddNumbers.append(odd) } var sums: [Int] = [] for odd in oddNumbers { sums.append(odd + 5) } var count = 0 repeat { print("The sum is: \(sums[count])") count += 1 }while count < sums.count //******************************************************************** print("Swift Condition") func fridge(milkAge: Int, eggsAge: Int) { if milkAge <= 21 { if eggsAge <= 10 { print("you can still use your milk and eggs") } else { print("you should throw away the eggs") } } else { if eggsAge <= 10 { print("you should throw away the milk") } else { print("you should throw away the milk and eggs") } } } func identifier(first: Int, second: Int, third: Int) { if first != second { if second != third { if third != first { print("the values are different") return } } } print("two values are at least identical") } //******************************************************************* print("Swift Dictionaries") var dictionaryArray: [[String: String]] = [] var dictionary = [String: String]() dictionary["firstName"] = "Zihan1" dictionary["lastName"] = "Zhang1" dictionaryArray.append(dictionary) dictionary["firstName"] = "Zihan2" dictionary["lastName"] = "Zhang2" dictionaryArray.append(dictionary) dictionary["firstName"] = "Zihan3" dictionary["lastName"] = "Zhang3" dictionaryArray.append(dictionary) var result1: [String] = [] for onedictionary in dictionaryArray { if var presult = onedictionary["firstName"] { result1.append(presult) } } var result2: [String] = [] for onedictionary in dictionaryArray { if var firstName = onedictionary["firstName"], var lastName = onedictionary["lastName"] { result2.append(firstName + "*" + lastName) } } //******************************************************************* print("Swift Tuple - Enum") enum CoinType: Int{ case Penny = 1 case Nickel = 5 case Dime = 10 case Quarter = 25 case HalfDollar = 50 case Dollar = 100 } var money: [(Int, CoinType)] = [(4, .Penny), (3, .Nickel), (5, .Dime), (9, .Quarter), (3, .HalfDollar), (1, .Dollar)] var total: Int = 0 for (num, value) in money { total += num * value.rawValue } print(total)
// // UserResult.swift // TinderApp // // Created by Serg on 13.02.2020. // Copyright © 2020 Sergey Gladkiy. All rights reserved. // import Foundation struct TinderUserResult: Decodable { let user: TinderUserInfo let distanceMi: Int let teaser: TinderUserTeaser let teasers: [TinderUserTeaser] let sNumber: Int }
// // DayTen2022Tests.swift // AdventOfCodeTests // // Created by Shawn Veader on 12/10/22. // import XCTest final class DayTen2022Tests: XCTestCase { let sampleInput = """ noop addx 3 addx -5 """ let largerSampleInput = """ addx 15 addx -11 addx 6 addx -3 addx 5 addx -1 addx -8 addx 13 addx 4 noop addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx -35 addx 1 addx 24 addx -19 addx 1 addx 16 addx -11 noop noop addx 21 addx -15 noop noop addx -3 addx 9 addx 1 addx -3 addx 8 addx 1 addx 5 noop noop noop noop noop addx -36 noop addx 1 addx 7 noop noop noop addx 2 addx 6 noop noop noop noop noop addx 1 noop noop addx 7 addx 1 noop addx -13 addx 13 addx 7 noop addx 1 addx -33 noop noop noop addx 2 noop noop noop addx 8 noop addx -1 addx 2 addx 1 noop addx 17 addx -9 addx 1 addx 1 addx -3 addx 11 noop noop addx 1 noop addx 1 noop noop addx -13 addx -19 addx 1 addx 3 addx 26 addx -30 addx 12 addx -1 addx 3 addx 1 noop noop noop addx -9 addx 18 addx 1 addx 2 noop noop addx 9 noop noop noop addx -1 addx 2 addx -37 addx 1 addx 3 noop addx 15 addx -21 addx 22 addx -6 addx 1 noop addx 2 addx 1 noop addx -10 noop noop addx 20 addx 1 addx 2 addx 2 addx -6 addx -11 noop noop noop """ func testInstructionParsing() { let cpu = SimpleCPU(sampleInput) XCTAssertEqual(3, cpu.instructions.count) XCTAssertEqual(.noop, cpu.instructions[0]) XCTAssertEqual(.addx(3), cpu.instructions[1]) XCTAssertEqual(.addx(-5), cpu.instructions[2]) } func testLargerInstructionParsing() { let cpu = SimpleCPU(largerSampleInput) XCTAssertEqual(146, cpu.instructions.count) } func testSimpleRun() { let cpu = SimpleCPU(sampleInput) XCTAssertEqual(3, cpu.instructions.count) cpu.run() XCTAssertEqual(6, cpu.cycles.count) print(cpu.cycles) XCTAssertEqual(1, cpu.cycles[0]) XCTAssertEqual(1, cpu.cycles[1]) // read: no-op XCTAssertEqual(1, cpu.cycles[2]) // read: addx 3 XCTAssertEqual(4, cpu.cycles[3]) // execute: addx 3 XCTAssertEqual(4, cpu.cycles[4]) // read: addx -5 XCTAssertEqual(-1, cpu.cycles[5]) // execute: addx -5 XCTAssertEqual(1, cpu.value(during: 3)) XCTAssertEqual(4, cpu.value(after: 3)) } func testLargerRun() { let cpu = SimpleCPU(largerSampleInput) XCTAssertEqual(146, cpu.instructions.count) cpu.run() XCTAssertEqual(241, cpu.cycles.count) print(cpu.cycles) XCTAssertEqual(21, cpu.value(during: 20)) XCTAssertEqual(19, cpu.value(during: 60)) XCTAssertEqual(18, cpu.value(during: 100)) XCTAssertEqual(21, cpu.value(during: 140)) XCTAssertEqual(16, cpu.value(during: 180)) XCTAssertEqual(18, cpu.value(during: 220)) } func testPartOne() { let answer = DayTen2022().partOne(input: largerSampleInput) XCTAssertEqual(13140, answer as! Int) } func testOutputRow() { let cpu = SimpleCPU(largerSampleInput) cpu.run() let firstRow = "##..##..##..##..##..##..##..##..##..##.." var displayedRow = cpu.outputRow(start: 1, width: 40) XCTAssertEqual(firstRow, displayedRow) let secondRow = "###...###...###...###...###...###...###." displayedRow = cpu.outputRow(start: 41, width: 40) XCTAssertEqual(secondRow, displayedRow) let thirdRow = "####....####....####....####....####...." displayedRow = cpu.outputRow(start: 81, width: 40) XCTAssertEqual(thirdRow, displayedRow) let fourthRow = "#####.....#####.....#####.....#####....." displayedRow = cpu.outputRow(start: 121, width: 40) XCTAssertEqual(fourthRow, displayedRow) let fifthRow = "######......######......######......####" displayedRow = cpu.outputRow(start: 161, width: 40) XCTAssertEqual(fifthRow, displayedRow) let sixthRow = "#######.......#######.......#######....." displayedRow = cpu.outputRow(start: 201, width: 40) XCTAssertEqual(sixthRow, displayedRow) } func testDisplayOutput() { let cpu = SimpleCPU(largerSampleInput) cpu.run() cpu.draw() } }
// // GZEBackUIBarButtonItem.swift // Gooze // // Created by Yussel on 2/23/18. // Copyright © 2018 Gooze. All rights reserved. // import UIKit class GZEBackUIBarButtonItem: GZENavButton { override init() { super.init() button.frame = CGRect(x: 0.0, y: 0.0, width: 20, height: 40) button.setImage(#imageLiteral(resourceName: "nav-back-button"), for: .normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // Quak.swift // Contly // // Created by Moses Adeoye Ayankoya on 26/06/2017. // Copyright © 2017 Flint. All rights reserved. // import Foundation extension String { public var isWhiteSpace: Bool { return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } public var isNotEmpty: Bool { return !self.isWhiteSpace } func abbrevate() -> String { guard self.characters.count > 0 else { return "" } let strs = self.components(separatedBy: " ") let first = strs.first! guard strs.count > 1 else { return "\(first.characters.first!)".uppercased() } let last = strs.last! return first.isEmpty ? "" : "\(first.characters.first!)".uppercased() + (last.isEmpty ? "" : "\(last.characters.first!)".uppercased()) } } public enum QueryOperator : String { case or = "OR", and = "AND" } open class Quak{ private var _query:String = "" public init(){} public convenience init(query: String = ""){ self.init() self._query = query } open func toString() -> String{ return _query } open func isNil(key:String) -> Quak{ _query = _query + "\(key) == nil" return self } open func isNotNil(key:String) -> Quak{ _query = _query + "\(key) != nil" return self } open func isNotBetween(key:String, leftValue:Any, rightValue:Any) -> Quak { return not(isBetween(key: key, leftValue: leftValue, rightValue: rightValue)) } open func isBetween(key:String, leftValue:Any, rightValue:Any) -> Quak{ _query = _query + " \(key) BETWEEN \(leftValue) AND \(rightValue)" return self } open func isNotIn(key:String, values:[Any]) -> Quak{ return not(isIn(key: key, values: values)) } open func isIn(key:String, values:[Any]) -> Quak{ var temp = "" values.forEach { (val) in temp = temp + (temp.isWhiteSpace ? "" : ",") + "'\(val)'" } _query = _query + " \(key) IN {\(temp)}" return self } open func notEqual(key:String, value:Any) -> Quak{ return not(equal(key: key, value: value)) } open func equal(key:String, value:Any) -> Quak{ _query = _query + "\(key) == \((value is String) ? "'\(value)'" : "\(value)")" return self } open func beginsWith(key:String, value:Any) -> Quak{ _query = _query + " \(key) BEGINSWITH \((value is String) ? "'\(value)'" : "\(value)")" return self } open func endsWith(key:String, value:Any) -> Quak{ _query = _query + " \(key) ENDSWITH \((value is String) ? "'\(value)'" : "\(value)")" return self } open func notBeginsWith(key:String, value:Any) -> Quak{ return not(beginsWith(key: key, value: value)) } open func notEndsWith(key:String, value:Any) -> Quak{ return not(endsWith(key: key, value: value)) } open func notContains(key:String, value:Any) -> Quak{ return not(contains(key: key, value: value)) } open func contains(key:String, value:Any) -> Quak{ _query = _query + " \(key) CONTAINS \((value is String) ? "'\(value)'" : "\(value)")" return self } open func notLike(key:String, value:Any) -> Quak{ return not(like(key: key, value: value)) } open func like(key:String, value:Any) -> Quak{ _query = _query + " \(key) LIKE \((value is String) ? "'\(value)'" : "\(value)")" return self } open func any(_ operand:Quak) -> Quak { _query = _query + " ANY (\(operand.toString()))" return self } open func greaterThan(key:String, value:Any) -> Quak{ _query = _query + " \(key) > \((value is String) ? "'\(value)'" : "\(value)")" return self } open func lessThan(key:String, value:Any) -> Quak{ _query = _query + " \(key) < \((value is String) ? "'\(value)'" : "\(value)")" return self } open func greaterThanOrEqual(key:String, value:Any) -> Quak{ _query = _query + " \(key) >= \((value is String) ? "'\(value)'" : "\(value)")" return self } open func lessThanOrEqual(key:String, value:Any) -> Quak{ _query = _query + " \(key) <= \((value is String) ? "'\(value)'" : "\(value)")" return self } open func notGreaterThan(key:String, value:Any) -> Quak{ return not(greaterThan(key: key, value: value)) } open func notLessThan(key:String, value:Any) -> Quak{ return not(lessThan(key: key, value: value)) } open func notGreaterThanOrEqual(key:String, value:Any) -> Quak{ return not(greaterThanOrEqual(key: key, value: value)) } open func notLessThanOrEqual(key:String, value:Any) -> Quak{ return not(lessThanOrEqual(key: key, value: value)) } open func not(_ operand: Quak) -> Quak { _query = _query + " NOT (\(operand.toString()))" return self } open func or() -> Quak{ _query = _query + " OR " return self } open func and() -> Quak{ _query = _query + " AND " return self } fileprivate func or(left:Quak, right: Quak) -> Quak{ _query = _query + " \(left.toString()) OR \(right.toString())" return self } fileprivate func and(left:Quak, right:Quak) -> Quak{ _query = _query + " \(left.toString()) AND \(right.toString())" return self } }
// // Extension_Date.swift // C0766343_MidTerm_MAD3115F2019 // // Created by Simranjit Singh Johal on 2019-11-08. // Copyright © 2019 MacStudent. All rights reserved. // import Foundation extension Date { public func DateFormat() -> String { let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "EEEE, dd MMMM, yyyy" let formattedDate = dateFormatterPrint.string(from: self) return formattedDate } }
// // masterViewController.swift // sailPower // // Created by MARYANNE WEISS on 12/23/18. // Copyright © 2018 WSE. All rights reserved. // import UIKit class masterViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. updateView(value: 0) } @IBAction func indexChanged(_ sender: UISegmentedControl) { updateView(value: sender.selectedSegmentIndex) } lazy var manualViewController: manualViewController = { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) var viewController = storyboard.instantiateViewController(withIdentifier: "manualViewController") as! manualViewController addViewControllerAsChildViewController(childViewController: viewController) return viewController }() lazy var autoViewController: autoViewController = { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) var viewController = storyboard.instantiateViewController(withIdentifier: "autoViewController") as! autoViewController addViewControllerAsChildViewController(childViewController: viewController) return viewController }() //Mark: - View Methods private func updateView(value:Int){ autoViewController.view.isHidden = !(value == 0) manualViewController.view.isHidden = (value == 0) } private func addViewControllerAsChildViewController(childViewController: UIViewController){ addChild(childViewController) view.addSubview(childViewController.view) childViewController.view.frame = view.bounds childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] childViewController.didMove(toParent: self) } }
// // Error.swift // Analytics // // Created by Fredrik Sjöberg on 2017-07-17. // Copyright © 2017 emp. All rights reserved. // import Foundation import iOSClientExposure extension Playback { /// Playback stopped because of an error. internal struct Error: AnalyticsEvent { internal let eventType: String = "Playback.Error" internal let bufferLimit: Int64 = 3000 internal let timestamp: Int64 /// Human readable error message /// Example: "Unable to parse HLS manifest" internal let message: String /// Error Domain internal let domain: String /// Platform-dependent error code internal let code: Int /// Additional detailed error information internal let info: String? internal init(timestamp: Int64, message: String, code: Int, domain: String, info: String? = nil) { self.timestamp = timestamp self.message = message self.code = code self.domain = domain self.info = info } } } extension Playback.Error { internal var jsonPayload: [String : Any] { var json: [String: Any] = [ JSONKeys.eventType.rawValue: eventType, JSONKeys.timestamp.rawValue: timestamp, JSONKeys.message.rawValue: message, JSONKeys.code.rawValue: code, JSONKeys.domain.rawValue: domain ] if let info = info { json[JSONKeys.info.rawValue] = info } return json } internal enum JSONKeys: String { case eventType = "EventType" case timestamp = "Timestamp" case message = "Message" case code = "Code" case domain = "Domain" case info = "Info" } }
// // CoreDataManager.swift // Places // // Created by Алексей Воронов on 03/11/2018. // Copyright © 2018 Алексей Воронов. All rights reserved. // import UIKit import CoreData //MARK: - Creating an array containing storage data var places: [Place] { let request = NSFetchRequest<Place>(entityName: "Place") let sd = NSSortDescriptor(key: "date", ascending: false) request.sortDescriptors = [sd] let array = try? CoreDataManager.sharedInstance.managedObjectContext.fetch(request) return array ?? [] } //MARK: - Working with local storage class CoreDataManager { static let sharedInstance = CoreDataManager() var managedObjectContext: NSManagedObjectContext { return persistentContainer.viewContext } lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "Places") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
// // DeviceSize.swift // Instagram // // Created by saito-takumi on 2018/01/02. // Copyright © 2018年 saito-takumi. All rights reserved. // import UIKit struct DeviseSize { //CGRectを取得 static func bounds()->CGRect{ return UIScreen.main.bounds; } //画面の横サイズを取得 static func screenWidth()->CGFloat{ return CGFloat( UIScreen.main.bounds.size.width ); } //画面の縦サイズを取得 static func screenHeight()->CGFloat{ return CGFloat( UIScreen.main.bounds.size.height ); } }
// // SortSelection.swift // BeastlySearch // // Created by Trevor Beasty on 11/9/17. // Copyright © 2017 Trevor Beasty. All rights reserved. // import Foundation protocol SortSelection: class { var sortSelectors: [SortSelectable] { get } }
// // EventsTableViewController.swift // Coordinate // // Created by James Wilkinson on 20/01/2016. // Copyright © 2016 James Wilkinson. All rights reserved. // import UIKit import CoreLocation public struct Event { let name: String let members: [Member] } class EventsTableViewController: UITableViewController { var data: [Event] required init?(coder aDecoder: NSCoder) { let john = Member(name: "John", location: CLLocationCoordinate2D(latitude: 51.515372, longitude: -0.141880)) let joe = Member(name: "Joe", location: CLLocationCoordinate2D(latitude: 51.521958, longitude: -0.046652)) let bob = Member(name: "Bob", location: CLLocationCoordinate2D(latitude: 51.522525, longitude: -0.041899)) data = [Event(name: "Photon", members: [john, joe, bob])] super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("EventCell", forIndexPath: indexPath) as! EventTableViewCell let event = self.data[indexPath.row] cell.imageView?.image = UIImage(named: event.name) cell.textLabel?.text = event.name if cell.contactImages.count < event.members.count { var referenceContactImage: UIImageView! = nil for imageView in cell.contactImages { if imageView.tag == 1 { referenceContactImage = imageView break } } let referenceIndex = cell.contentView.subviews.indexOf(referenceContactImage) for var i = cell.contactImages.count; i < event.members.count; i++ { let newFrame = referenceContactImage.frame.offsetBy(dx: CGFloat(i) * (2*referenceContactImage.frame.width/3), dy: 0.0) let newContactImage = RoundedImageView(frame: newFrame) cell.contactImages.append(newContactImage) cell.contentView.insertSubview(newContactImage, atIndex: referenceIndex! + i) } } cell.contactImages.sortInPlace { $0.tag < $1.tag } for (index, member) in event.members.enumerate() { cell.contactImages[index].image = UIImage(named: member.name) } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // if UIDevice.currentDevice().userInterfaceIdiom == .Pad { // self.performSegueWithIdentifier("ShowSimulatorSegue", sender: nil) // } else { self.performSegueWithIdentifier("ShowEventSegue", sender: tableView.cellForRowAtIndexPath(indexPath)) // } } override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("ShowSimulatorSegue", sender: tableView.cellForRowAtIndexPath(indexPath)) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "ShowEventSegue" { let destinationVC = segue.destinationViewController as! ViewController if let cell = sender as? UITableViewCell { let indexSelected = self.tableView.indexPathForCell(cell)! destinationVC.title = self.data[indexSelected.row].name destinationVC.data = self.data[indexSelected.row].members } else { fatalError("segue from \(self) not initiated by UITableViewCell") } } } }
// // MainWindowController.swift // SlackClone // // Created by Brian D Keane on 9/25/17. // Copyright © 2017 Brian D Keane. All rights reserved. // import Cocoa class MainWindowController: NSWindowController { var activeVC:ViewController? override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } func moveToVC(identifier:String) { self.activeVC = storyboard?.instantiateController(withIdentifier: identifier) as? ViewController self.window?.contentView = self.activeVC?.view } }
// // NewMessageViewController.swift // Amarosa // // Created by Andrew Foghel on 7/10/17. // Copyright © 2017 SeanPerez. All rights reserved. // import UIKit import Firebase var chosenUser = User() class NewMessageViewController: UITableViewController { var users = [User]() override func viewDidLoad() { super.viewDidLoad() tableView.widthAnchor.constraint(equalToConstant: 200).isActive = true navigationItem.title = "Compose" fetchUser() } func fetchUser(){ Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject]{ let user = User() user.uid = snapshot.key //if use this setter app will crash is class properties dont exactly match up with actual fb keys //safer user.name = dictionary["name"] user.name = dictionary["name"] as? String user.email = dictionary["email"] as? String user.profileImageUrl = dictionary["profileImageUrl"] as? String self.users.append(user) //this will crash because of background thread so use dispatch_async DispatchQueue.main.async { self.tableView.reloadData() } } }) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return users.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let user = users[indexPath.row] cell.textLabel?.text = user.name cell.detailTextLabel?.text = user.email return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { chosenUser = users[indexPath.row] performSegue(withIdentifier: "chatLog", sender: nil) } }
// // MockCustomField.swift // HippoAgent // // Created by Vishal on 19/11/19. // Copyright © 2019 Socomo Technologies Private Limited. All rights reserved. // import Foundation struct MockCustomField { let defaultFields: [[String: Any]] = [[ "field_name": "Enter User Name", "field_type": "Text", "display_name": "User Name", "is_required": true, "placeholder": "User Name", "id": "abcd", "show_to_customer": false, "can_agent_edit": false, "value": "" ], [ "field_name": "Enter About yourself", "field_type": "TextArea", "display_name": "Bio", "is_required": true, "placeholder": "Enter About yourself", "id": "abcd", "show_to_customer": false, "can_agent_edit": false, "value": "" ], [ "field_name": "Enter your age", "field_type": "Number", "display_name": "Age", "is_required": true, "placeholder": "Enter Age", "id": "abcd", "show_to_customer": false, "can_agent_edit": false, "value": "" ], [ "field_name": "Enter Email", "field_type": "Email", "display_name": "Email", "is_required": true, "placeholder": "Enter Email", "id": "abcd", "show_to_customer": false, "can_agent_edit": false, "value": "" ], [ "field_name": "Enter Contact Number", "field_type": "Telephone", "display_name": "Contact", "is_required": true, "placeholder": "Phone number", "id": "abcd", "show_to_customer": false, "can_agent_edit": false, "value": "" ], [ "field_name": "Add your photo", "field_type": "Document", "display_name": "User Photo", "is_required": true, "placeholder": "Photo", "id": "abcd", "show_to_customer": true, "can_agent_edit": false, "value": "" ]] }
// // ViewController.swift // CRUDPhotoAlbum // // Created by Vui Nguyen on 1/20/20. // Copyright © 2020 SunfishEmpire. All rights reserved. // import UIKit class ScrollViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var middleView: UIView! var images = [UIImage]() var photos = ["schnoodle1", "schnoodle2", "schnoodle3", "schnoodle4"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. loadImages() if images.count == 0 { print("there are no pictures!") return } for i in 0..<images.count { let imageView = UIImageView() let x = middleView.frame.size.width * CGFloat(i) //imageView.center = middleView.center imageView.frame = CGRect(x: x, y: 0, width: middleView.frame.width, height: middleView.frame.height) // imageView.frame.height = middleView.frame.height // imageView.frame.width = middleView.frame.width imageView.contentMode = .scaleAspectFit //imageView.contentMode = .center imageView.image = images[i] scrollView.contentSize.width = scrollView.frame.size.width * CGFloat(i + 1) //imageView.center = middleView.center /* imageView.contentMode = .center; if (imageView.bounds.size.width > (images[i]).size.width && imageView.bounds.size.height > (images[i]).size.height) { imageView.contentMode = .scaleAspectFit; } */ scrollView.addSubview(imageView) } } func loadImages() { for i in 0..<photos.count { if let image = UIImage(named: photos[i]) { images.append(image) } } } }
// // Lesson1Unit1Table.swift // Automotive English Program // // Created by Tyler Stone on 6/15/16. // Copyright © 2016 Honda+OSU. All rights reserved. // import UIKit import Foundation class UnitTable: UITableViewController{ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print("Unit Embedded Table loaded.") } var data = ["Pronunciation","Conversations","Speaking Assessment"] override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UnitCell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = data[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row{ case 0: print("Pronunciations Pressed.") case 1: let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ConversationsStartController") self.presentViewController(vc! as UIViewController, animated: true, completion: nil) case 2: print("Speaking Assessment Pressed.") default: print("How did you get here?") } } }
// // CollectionCollectionViewCell.swift // TabBarItem // // Created by apple on 2/26/20. // Copyright © 2020 apple. All rights reserved. // import UIKit class CollectionCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imgview: UIImageView! }
// // MutableTableViewKitRow.swift // TableViewKit // // Created by Shane Whitehead on 28/2/18. // Copyright © 2018 Beam Communications. All rights reserved. // import Foundation public protocol MutableTableViewKitRow: TableViewKitRow { func delete() // Determines if the row can actually be deleted or not var isDeletable: Bool { get } }
// // DetailType.swift // Symphony // // Created by Bradley Hilton on 11/18/16. // Copyright © 2016 Brad Hilton. All rights reserved. // public protocol DetailType : DataConvertible, Hashable { var id: Int { get } } extension DetailType { public func hash(into hasher: inout Hasher) { hasher.combine(id) } } public func ==<T : DetailType>(lhs: T, rhs: T) -> Bool { return lhs.id == rhs.id }
// // ApiServices.swift // DailyLifeV2 // // Created by Lý Gia Liêm on 6/26/19. // Copyright © 2019 LGL. All rights reserved. // //Linh: 3d152c6733e14015b46c1418d7567434 //Lam: d5b74e34a5d84c6e975e1cfe78f4803d //Long: 2173e6f5b41e4cb7b3892eb3ace459c5 //Liem: c3aa57a429a6432a9485160edf25e526 import Foundation import Alamofire import ObjectMapper import AlamofireObjectMapper class NewsApiService { static var instance = NewsApiService() var TOPIC_NEWSAPI = ["General", "Entertainment", "Health", "Science", "Sports", "Technology", "Business", "World", "Style", "Arts", "Travel", "Food", "Politics", "Opinion"] func getArticles(topic: String, page: Int, numberOfArticles: Int, completion: @escaping (NewsApi) -> Void) { let totalUrl = "\(URL_API.NewsAPI.keyAndPath.path)\(topic)&language=en&pageSize=\(numberOfArticles)&apiKey=\(URL_API.NewsAPI.keyAndPath.key)&sortBy=publishedAt&page=\(page)&sources=ars-technica,ary-news,time,bbc-news,espn,financial-post,bloomberg,business-insider,cbc-news,cbs-news,daily-mail,entertainment-weekly,fox-news,mtv-news,national-geographic,new-york-magazine,the-new-york-times,the-verge" Alamofire.request(totalUrl).validate().responseJSON { (response) in if response.result.error == nil { guard let data = response.data else {return} do { let dataDecode = try JSONDecoder().decode(NewsApi.self, from: data) completion(dataDecode) } catch let jsonDecodeError { debugPrint(jsonDecodeError.localizedDescription) } } else { debugPrint(response.result.error?.localizedDescription ?? "") } } } func getSearchArticles(topic: String, page: Int, numberOfArticles: Int, completion: @escaping (NewsApi) -> Void) { let totalUrl = "\(URL_API.SearchNewsAPI.keyAndPath.path)\(topic)&language=en&pageSize=\(numberOfArticles)&apiKey=\(URL_API.SearchNewsAPI.keyAndPath.key)&sortBy=publishedAt&page=\(page)" guard let url = URL(string: totalUrl) else {return} URLSession.shared.dataTask(with: url) {(dataApi, _, _) in guard let data = dataApi else {return} do { let dataDecode = try JSONDecoder().decode(NewsApi.self, from: data) completion(dataDecode) } catch let jsonError { debugPrint("API Key for NewsApi is Out Of Date: ", jsonError) } }.resume() } }
import Foundation struct Person: Codable { let name: String let birthdayDate: Date } let jsonEncoder = JSONEncoder() jsonEncoder.dateEncodingStrategy = .iso8601 jsonEncoder.keyEncodingStrategy = .convertToSnakeCase jsonEncoder.outputFormatting = .prettyPrinted let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .iso8601 jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase let data = try jsonEncoder.encode(Person(name: "Bob", birthdayDate: Date())) let str = String(data: data, encoding: .utf8)! print(str) try jsonDecoder.decode(Person.self, from: data)
// // NewsSource.swift // GoodNews // // Created by Muhammad Osama Naeem on 3/15/20. // Copyright © 2020 Muhammad Osama Naeem. All rights reserved. // import UIKit struct NewsSource: Codable, Hashable { let id : String let name: String let country: String let description: String let url: String let category: String } struct Source : Codable { let sources: [NewsSource] }
// // WelcomeTableViewController.swift // HealthAppDemo // // Created by Amit C Rote on 12/2/18. // Copyright © 2018 Amit C Rote. All rights reserved. // import UIKit import HealthKit class WelcomeTableViewController: UITableViewController { let viewModel = WelcomeViewModel() override func viewDidLoad() { super.viewDidLoad() tableView?.tableFooterView = UIView() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.supportedFeatures.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) cell.textLabel?.text = viewModel.supportedFeatures[indexPath.row].title return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "showFeatureLanding", sender: indexPath) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "showFeatureLanding": if let destinationVC = segue.destination as? FeatureLandingViewController { if let indexPath = sender as? IndexPath { destinationVC.currentFeatures = viewModel.supportedFeatures[indexPath.row] } } default: break } } }
// // FavoritesCell.swift // Church // // Created by Edvin Lellhame on 8/12/17. // Copyright © 2017 Edvin Lellhame. All rights reserved. // import UIKit class FavoritesCell: UITableViewCell { @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configureCell(church: Church) { nameLabel.text = church.name addressLabel.text = church.fullAddress } }
// // RootViewController.swift // FluffyWinner_iOS // // Created by Ariel Rodriguez on 27/04/2020. // Copyright © 2020 Ariel Rodriguez. All rights reserved. // import UIKit import FluffyWinnerUIKit public class RootViewController: NiblessNavigationController { let schoolsViewController: SchoolsViewController init(schoolsViewController: SchoolsViewController) { self.schoolsViewController = schoolsViewController super.init() } override public func viewDidLoad() { super.viewDidLoad() self.pushViewController(self.schoolsViewController, animated: false) } }
import UIKit import SnapKit import ThemeKit class FullTransactionInfoTextCell: TitleCell { private let label = UILabel() private let button = ThemeButton() private var onTap: (() -> ())? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleLabel.font = .subhead2 titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal) titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal) iconImageView.tintColor = .themeGray contentView.addSubview(label) label.snp.makeConstraints { maker in maker.leading.equalTo(titleLabel.snp.trailing).offset(CGFloat.margin4x) maker.centerY.equalToSuperview() maker.trailing.equalTo(disclosureImageView.snp.leading) } label.textAlignment = .right label.font = .subhead1 label.textColor = .themeLeah contentView.addSubview(button) button.snp.makeConstraints { maker in maker.leading.equalTo(titleLabel.snp.trailing).offset(CGFloat.margin4x) maker.centerY.equalToSuperview() maker.trailing.equalTo(disclosureImageView.snp.leading) } button.apply(style: .secondaryDefault) button.addTarget(self, action: #selector(onTapButton), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func onTapButton() { onTap?() } func bind(item: FullTransactionItem, selectionStyle: SelectionStyle = .none, showDisclosure: Bool = false, last: Bool = false, onTap: (() -> ())? = nil) { super.bind(titleIcon: item.icon.flatMap { UIImage(named: $0) }, title: item.title, titleColor: .themeGray, showDisclosure: showDisclosure, last: last) self.selectionStyle = selectionStyle if onTap != nil { label.isHidden = true label.text = nil button.isHidden = false button.setTitle(item.value, for: .normal) button.snp.remakeConstraints { maker in maker.leading.equalTo(titleLabel.snp.trailing).offset(CGFloat.margin4x) maker.centerY.equalToSuperview() maker.trailing.equalTo(disclosureImageView.snp.leading).offset(showDisclosure ? -CGFloat.margin2x : 0) } } else { button.isHidden = true button.setTitle(nil, for: .normal) label.isHidden = false label.text = item.value label.snp.remakeConstraints { maker in maker.leading.equalTo(titleLabel.snp.trailing).offset(CGFloat.margin4x) maker.centerY.equalToSuperview() maker.trailing.equalTo(disclosureImageView.snp.leading).offset(showDisclosure ? -CGFloat.margin2x : 0) } } self.onTap = onTap } }
import Foundation struct List: Codable { public private(set) var dt : Int? public private(set) var temperature: Temperature? public private(set) var weather: [Weather]? public private(set) var clouds: Clouds? public private(set) var wind: Wind? public private(set) var rain: Rain? public private(set) var rainfall: Rainfall? public private(set) var dt_txt: String? enum CodingKeys: String, CodingKey { case dt = "dt" case temperature = "main" case weather = "weather" case clouds = "clouds" case wind = "wind" case rain = "rain" case rainfall = "sys" case dt_txt = "dt_txt" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) dt = try values.decodeIfPresent(Int.self, forKey: .dt) temperature = try values.decodeIfPresent(Temperature.self, forKey: .temperature) weather = try values.decodeIfPresent([Weather].self, forKey: .weather) clouds = try values.decodeIfPresent(Clouds.self, forKey: .clouds) wind = try values.decodeIfPresent(Wind.self, forKey: .wind) rain = try values.decodeIfPresent(Rain.self, forKey: .rain) rainfall = try values.decodeIfPresent(Rainfall.self, forKey: .rainfall) dt_txt = try values.decodeIfPresent(String.self, forKey: .dt_txt) } }
/****************************************************************************** * * ADOBE CONFIDENTIAL * ___________________ * * Copyright 2016 Adobe Systems Incorporated * All Rights Reserved. * * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. ******************************************************************************/ import CoreImage import CoreGraphics import UIKit class ImageEditorController : UIViewController, UIViewControllerPreviewingDelegate, PeekPanCoordinatorDelegate, PeekPanCoordinatorDataSource, PeekPanViewControllerDelegate { @IBOutlet var brightnessSlider: UISlider! @IBOutlet var contrastSlider: UISlider! @IBOutlet var sharpnessSlider: UISlider! @IBOutlet var brightnessLabel: UILabel! @IBOutlet var contrastLabel: UILabel! @IBOutlet var sharpnessLabel: UILabel! let coreImage = CIImage(image: UIImage(named: "color_image")!) var brightnessValue: CGFloat = 0.0 var contrastValue: CGFloat = 1.0 var sharpnessValue: CGFloat = 0.4 weak var selectedSlider: UISlider? @IBOutlet var imageView: UIImageView! var peekPanCoordinator: PeekPanCoordinator! let peekPanVC = PeekPanViewController() // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() brightnessLabel.text = String(describing: brightnessValue) contrastLabel.text = String(describing: contrastValue) sharpnessLabel.text = String(describing: sharpnessValue) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) peekPanCoordinator = PeekPanCoordinator(sourceView: view) peekPanCoordinator.delegate = peekPanVC peekPanCoordinator.dataSource = self peekPanVC.delegate = self } } } // MARK: Methods @IBAction func didSetBrightness(_ sender: UISlider) { brightnessValue = CGFloat(sender.value) brightnessLabel.text = NSString(format: "%.2f", sender.value) as String updateImageWithCurrentValues(imageView) } @IBAction func didSetContrast(_ sender: UISlider) { contrastValue = CGFloat(sender.value) contrastLabel.text = NSString(format: "%.2f", sender.value) as String updateImageWithCurrentValues(imageView) } @IBAction func didSetSharpness(_ sender: UISlider) { sharpnessValue = CGFloat(sender.value) sharpnessLabel.text = NSString(format: "%.2f", sender.value) as String updateImageWithCurrentValues(imageView) } func updateSelected() { if selectedSlider == nil { return } if selectedSlider == brightnessSlider { selectedSlider!.value = Float(brightnessValue) brightnessLabel!.text = NSString(format: "%.2f", brightnessValue) as String } else if selectedSlider == contrastSlider { selectedSlider!.value = Float(contrastValue) contrastLabel!.text = NSString(format: "%.2f", contrastValue) as String } else if selectedSlider == sharpnessSlider { selectedSlider!.value = Float(sharpnessValue) sharpnessLabel!.text = NSString(format: "%.2f", sharpnessValue) as String } } func revertSelected() { if selectedSlider == nil { return } if selectedSlider == brightnessSlider { brightnessValue = CGFloat(selectedSlider!.value) } else if selectedSlider == contrastSlider { contrastValue = CGFloat(selectedSlider!.value) } else if selectedSlider == sharpnessSlider { sharpnessValue = CGFloat(selectedSlider!.value) } } func updateImageWithCurrentValues(_ imageView: UIImageView) { let context = CIContext(options: nil) var extent = CGRect.zero let colorFilter = CIFilter(name: "CIColorControls")! // brightness & contrast colorFilter.setValue(coreImage, forKey: kCIInputImageKey) colorFilter.setValue(brightnessValue, forKey: kCIInputBrightnessKey) colorFilter.setValue(contrastValue, forKey: kCIInputContrastKey) var outputImage = colorFilter.value(forKey: kCIOutputImageKey) as! CIImage let sharpnessFilter = CIFilter(name: "CISharpenLuminance")! sharpnessFilter.setValue(outputImage, forKey: kCIInputImageKey) sharpnessFilter.setValue(sharpnessValue, forKey: kCIInputSharpnessKey) outputImage = sharpnessFilter.value(forKey: kCIOutputImageKey) as! CIImage extent = outputImage.extent imageView.image = UIImage(cgImage: context.createCGImage(outputImage, from: extent)!) } // MARK: PeekPanCoordinatorDataSource func maximumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Int { return 0 } func shouldStartFromMinimumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Bool { return false } func minimumPoint(for peekPanCoordinator: PeekPanCoordinator) -> CGPoint { if let slider = selectedSlider { return slider.frame.origin } return CGPoint.zero } func maximumPoint(for peekPanCoordinator: PeekPanCoordinator) -> CGPoint { if let slider = selectedSlider { return CGPoint(x: slider.frame.maxX, y: slider.frame.maxY) } return CGPoint.zero } // MARK: PeekPanViewControllerDelegate func peekPanCoordinatorEnded(_ peekPanCoordinator: PeekPanCoordinator) { if peekPanCoordinator.state == .popped { updateSelected() updateImageWithCurrentValues(imageView) } else { revertSelected() } selectedSlider = nil } func view(for peekPanViewController: PeekPanViewController, atPercentage percentage: CGFloat) -> UIView? { let imageView = UIImageView() let valueLabel = UILabel() valueLabel.textColor = .white valueLabel.frame.origin = CGPoint(x: 20, y: 20) valueLabel.font = UIFont.systemFont(ofSize: 38) valueLabel.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3) imageView.addSubview(valueLabel) if selectedSlider == brightnessSlider { brightnessValue = CGFloat(brightnessSlider.maximumValue - brightnessSlider.minimumValue) * percentage + CGFloat(brightnessSlider.minimumValue) valueLabel.text = NSString(format: "%.2f", brightnessValue) as String } else if selectedSlider == contrastSlider { let range = CGFloat(contrastSlider.maximumValue - contrastSlider.minimumValue) * 0.3 let startingValue = (CGFloat(peekPanCoordinator.startingPoint.x) - selectedSlider!.frame.minX) / selectedSlider!.bounds.width * CGFloat(contrastSlider.maximumValue - contrastSlider.minimumValue) contrastValue = min(max(range * percentage + (startingValue - range/2), CGFloat(contrastSlider.minimumValue)), CGFloat(contrastSlider.maximumValue)) valueLabel.text = NSString(format: "%.2f", contrastValue) as String } else if selectedSlider == sharpnessSlider { sharpnessValue = CGFloat(sharpnessSlider.maximumValue - sharpnessSlider.minimumValue) * percentage + CGFloat(sharpnessSlider.minimumValue) valueLabel.text = NSString(format: "%.2f", sharpnessValue) as String let zoomRatio: CGFloat = 0.3 imageView.layer.contentsRect = CGRect( x: 0.5 - (self.imageView.bounds.width*zoomRatio/2)/self.imageView.bounds.width, y: 0.5 - (self.imageView.bounds.height*zoomRatio)/self.imageView.bounds.height, width: zoomRatio, height: zoomRatio) } valueLabel.sizeToFit() updateImageWithCurrentValues(imageView) return imageView } // MARK: UIViewControllerPreviewingDelegate @available (iOS 9.0, *) func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { if brightnessSlider.frame.contains(location) { selectedSlider = brightnessSlider } else if contrastSlider.frame.contains(location) { selectedSlider = contrastSlider } else if sharpnessSlider.frame.contains(location) { selectedSlider = sharpnessSlider } else { selectedSlider = nil return nil } peekPanCoordinator.setup() previewingContext.sourceRect = selectedSlider!.frame return peekPanVC } @available (iOS 9.0, *) func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { peekPanCoordinator.end(true) } }
// // Lexer.swift // WarriorLangSwiftCompiler // // Created by Rafael Guerreiro on 2018-09-27. // Copyright © 2018 Rafael Rubem Rossi Souza Guerreiro. All rights reserved. // import Foundation public class Lexer { private static let BUFFER_SIZE: Int = 8.kilobyte private static let TOKENS_CAPACITY: Int = 1024 private let inputStream: InputStream public private(set) var tokens: [Token] private let builder: TokenBuilder private var currentCharacter: String = "" private var states: [LexerState] = [.start] init(reading inputStream: InputStream) throws { self.inputStream = inputStream self.builder = TokenBuilder(file: "file-name.wl") self.tokens = [Token]() tokens.reserveCapacity(Lexer.TOKENS_CAPACITY) try parse() } } // MARK: - Parser public extension Lexer { private func parse() throws { try read { utf8BufferString in let endIndex = utf8BufferString.endIndex var index = utf8BufferString.startIndex var readNextCharacter = true while true { if readNextCharacter { if index == endIndex { break; } currentCharacter = String(utf8BufferString[index]) } guard let state = self.state else { break; } parseState(state, &readNextCharacter) index = utf8BufferString.index(after: index) } } appendEndOfFileToken() } private func parseState(_ state: LexerState, _ readNextCharacter: inout Bool) { switch state { case .stringLiteralInterpolation: lexerStateStart(&readNextCharacter) case .openParenthesis: lexerStateStart(&readNextCharacter) case .start: lexerStateStart(&readNextCharacter) case .symbol: lexerStateSymbol(&readNextCharacter) case .identifier: lexerStateIdentifier(&readNextCharacter) case .numberLiteralZero: lexerStateZero(&readNextCharacter) case .numberLiteral: lexerStateNumber(&readNextCharacter) case .numberLiteralExponential: lexerStateNumberExponential(&readNextCharacter) case .compilerDirective: lexerStateCompilerDirective(&readNextCharacter) case .slash: lexerStateSlash(&readNextCharacter) case .inlineComment: lexerStateInlineComment(&readNextCharacter) case .blockComment: lexerStateBlockComment(&readNextCharacter) case .dot: lexerStateDot(&readNextCharacter) case .dash: lexerStateDash(&readNextCharacter) case .stringLiteral: lexerStateStringLiteral(&readNextCharacter) case .stringLiteralEscape: lexerStateStringLiteralEscape(&readNextCharacter) case .characterLiteral: lexerStateCharacterLiteral(&readNextCharacter) case .characterLiteralEscape: lexerStateCharacterLiteralEscape(&readNextCharacter) } } } // MARK: - Lexer state methods fileprivate extension Lexer { private func lexerStateStart(_ readNextCharacter: inout Bool) { readNextCharacter = true if currentCharacter.isWhiteSpaceCharacter { if !isLastToken(category: .space) { appendSingleCharacterToken(category: .space) } } else if currentCharacter == "0" { tokenStart(state: .numberLiteralZero) } else if currentCharacter.isDigitCharacter { tokenStart(state: .numberLiteral) } else if currentCharacter.isSymbolCharacter { tokenStart(state: .symbol) } else if currentCharacter == "\"" { tokenStart(state: .stringLiteral, appendCurrentCharacter: false) } else if currentCharacter == "'" { tokenStart(state: .characterLiteral, appendCurrentCharacter: false) } else if currentCharacter == "/" { tokenStart(state: .slash) } else if currentCharacter == "-" { tokenStart(state: .dash) } else if currentCharacter == "#" { tokenStart(state: .compilerDirective) } else if currentCharacter == "`" { tokenStart(state: .identifier, appendCurrentCharacter: false) } else if currentCharacter == "(" { appendSingleCharacterToken(category: .punctuationLeftParenthesis) tokenStart(state: .openParenthesis) } else if currentCharacter == ")" { let oldState: LexerState? = leaveState() if oldState == nil || oldState == .openParenthesis { appendSingleCharacterToken(category: .punctuationRightParenthesis) } } else if currentCharacter == "." { tokenStart(state: .dot) } // Single char tokens else if currentCharacter == "{" { appendSingleCharacterToken(category: .punctuationLeftCurlyBrace); } else if currentCharacter == "}" { appendSingleCharacterToken(category: .punctuationRightCurlyBrace); } else if currentCharacter == "[" { appendSingleCharacterToken(category: .punctuationLeftSquareBrackets); } else if currentCharacter == "]" { appendSingleCharacterToken(category: .punctuationRightSquareBrackets); } else if currentCharacter == "<" { appendSingleCharacterToken(category: .punctuationLeftAngleBrackets); } else if currentCharacter == ">" { appendSingleCharacterToken(category: .punctuationRightAngleBrackets); } else if currentCharacter == "," { appendSingleCharacterToken(category: .punctuationComma); } else if currentCharacter == ":" { appendSingleCharacterToken(category: .punctuationColon); } else if currentCharacter == ";" { appendSingleCharacterToken(category: .punctuationSemicolon); } else if currentCharacter == "+" { appendSingleCharacterToken(category: .punctuationPlus); } else if currentCharacter == "*" { appendSingleCharacterToken(category: .punctuationAsterisk); } else if currentCharacter == "^" { appendSingleCharacterToken(category: .punctuationXor); } else if currentCharacter == "|" { appendSingleCharacterToken(category: .punctuationPipe); } else if currentCharacter == "%" { appendSingleCharacterToken(category: .punctuationPercent); } else if currentCharacter == "~" { appendSingleCharacterToken(category: .punctuationTilde); } else if currentCharacter == "=" { appendSingleCharacterToken(category: .punctuationEqual); } else if currentCharacter == "@" { appendSingleCharacterToken(category: .punctuationAt); } else if currentCharacter == "&" { appendSingleCharacterToken(category: .punctuationAmpersand); } else if currentCharacter == "\\" { appendSingleCharacterToken(category: .punctuationBackslash); } else if currentCharacter == "!" { appendSingleCharacterToken(category: .punctuationExclamation); } else if currentCharacter == "?" { appendSingleCharacterToken(category: .punctuationQuestion); } else { #warning("Add more details on this error. Don't make it a fatalError, but a diagnostic reporter.") fatalError("Unknown character: \(currentCharacter)") } } private func lexerStateSymbol(_ readNextCharacter: inout Bool) { // First char is alpha. if currentCharacter.isSymbolCharacter { builder.increment(char: currentCharacter) } else { if let category = Keyword.keywords[builder.value] { tokenEnd(category: category) } else { tokenEnd(category: .identifier) } readNextCharacter = false } } private func lexerStateIdentifier(_ readNextCharacter: inout Bool) { // First char is `. readNextCharacter = true if currentCharacter.isSymbolCharacter { builder.increment(char: currentCharacter) } else if !builder.value.isEmpty && currentCharacter.isDigitCharacter { builder.increment(char: currentCharacter) } else if currentCharacter == "`" { tokenEnd(category: .identifier) } else { #warning("Add more details on this error. Don't make it a fatalError, but a diagnostic reporter.") fatalError("Invalid token currentCharacter: \"\(currentCharacter)\", builder: \(builder)") } } private func lexerEndNumberToken(_ readNextCharacter: inout Bool) { let category: TokenCategory = builder.isFloatingPoint == true ? .literalFloat : .literalInteger tokenEnd(category: category) readNextCharacter = false } private func lexerStateZero(_ readNextCharacter: inout Bool) { // First char is 0. readNextCharacter = true switchState(.numberLiteral) if currentCharacter == "x" { builder.radix(16) builder.increment(char: currentCharacter) } else if currentCharacter == "o" { builder.radix(8) builder.increment(char: currentCharacter) } else if currentCharacter == "b" { builder.radix(2) builder.increment(char: currentCharacter) } else if !builder.isFloatingPoint && currentCharacter == "." { builder.isFloatingPoint(true) builder.increment(char: currentCharacter) } else if currentCharacter == "_" || currentCharacter.isDigitCharacter { builder.increment(char: currentCharacter) } else { readNextCharacter = false builder.radix(10) builder.isFloatingPoint(false) tokenEnd(category: .literalInteger) } } private func lexerStateNumber(_ readNextCharacter: inout Bool) { // First char is a digit different than zero. let radix = builder.radix ?? 10 builder.radix(radix) readNextCharacter = true if currentCharacter == "_" { builder.increment(char: currentCharacter) } else if !builder.isFloatingPoint && currentCharacter == "." { #warning("implement here: this->tryToReadNextCharacter();") if currentCharacter.isDigitCharacter || currentCharacter == "_" { builder.isFloatingPoint(true) builder.increment(char: ".") builder.increment(char: currentCharacter) readNextCharacter = true } else { lexerEndNumberToken(&readNextCharacter) readNextCharacter = false tokenStart(state: .dot, appendCurrentCharacter: false) builder.increment(char: ".") } } else if currentCharacter.isValidDigitCharacter(radix: radix) { builder.increment(char: currentCharacter) } else if currentCharacter.isExponentialIdentifierCharacter(radix: radix) { builder.increment(char: currentCharacter) builder.isFloatingPoint(true) enterState(.numberLiteralExponential) } else { lexerEndNumberToken(&readNextCharacter) } } private func lexerStateNumberExponential(_ readNextCharacter: inout Bool) { // last digit was e or p. readNextCharacter = true if currentCharacter.isValidDigitCharacter(radix: builder.radix ?? 10) || currentCharacter == "+" || currentCharacter == "-" { builder.increment(char: currentCharacter) leaveState() } else { lexerEndNumberToken(&readNextCharacter) } } private func lexerStateCompilerDirective(_ readNextCharacter: inout Bool) { // First char is # readNextCharacter = true if currentCharacter.isSymbolCharacter { builder.increment(char: currentCharacter) } else { if let category = Keyword.compilerDirectiveKeywords[builder.value] { tokenEnd(category: category) } else { if builder.value == "#" { tokenEnd(category: .punctuationPound) } else { tokenEnd(category: .identifier) } } readNextCharacter = false; } } private func lexerStateSlash(_ readNextCharacter: inout Bool) { // First char is / // This could be an inline comment, a block comment or a slash. readNextCharacter = true if currentCharacter == "/" { switchState(.inlineComment) builder.increment(char: currentCharacter) } else if currentCharacter == "*" { switchState(.blockComment) builder.increment(char: currentCharacter) } else { tokenEnd(category: .punctuationSlash) readNextCharacter = false } } private func lexerStateInlineComment(_ readNextCharacter: inout Bool) { readNextCharacter = true if currentCharacter.isLineFeedCharacter { tokenEnd(category: .comment) readNextCharacter = false } else { builder.increment(char: currentCharacter) } } private func lexerStateBlockComment(_ readNextCharacter: inout Bool) { readNextCharacter = true if builder.value.ends(with: "*/") { tokenEnd(category: .comment) readNextCharacter = false } else { builder.increment(char: currentCharacter) } } private func lexerStateDot(_ readNextCharacter: inout Bool) { // First char is . not part of a number. // ... // ..< // .method | .variable readNextCharacter = true if currentCharacter == "." && (builder.value == "." || builder.value == "..") { builder.increment(char: currentCharacter) if builder.value == "..." { tokenEnd(category: .composedClosedRange) } } else if currentCharacter == "<" && builder.value == ".." { builder.increment(char: currentCharacter) if builder.value == "..<" { tokenEnd(category: .composedHalfOpenRange) } } else { tokenEnd(category: .punctuationDot) readNextCharacter = false } } private func lexerStateDash(_ readNextCharacter: inout Bool) { // First char is - readNextCharacter = true if currentCharacter == ">" { builder.increment(char: currentCharacter) tokenEnd(category: .composedPunctuationArrow) } else { tokenEnd(category: .punctuationMinus) readNextCharacter = false } } private func lexerStateStringLiteral(_ readNextCharacter: inout Bool) { readNextCharacter = true if currentCharacter == "\\" { enterState(.stringLiteralEscape) } else if currentCharacter == "\"" { tokenEnd(category: .literalString) } else { builder.increment(char: currentCharacter) } } private func lexerStateStringLiteralEscape(_ readNextCharacter: inout Bool) { // Previous character was a \ . readNextCharacter = true leaveState() if currentCharacter == "(" { tokenEnd(category: .literalString) enterState(.stringLiteral) enterState(.stringLiteralInterpolation) } else if currentCharacter == "n" { builder.increment(char: "\n") } else if currentCharacter == "\"" { builder.increment(char: "\"") } else if currentCharacter == "'" { builder.increment(char: "'") } else if currentCharacter == "t" { builder.increment(char: "\t") } else if currentCharacter == "r" { builder.increment(char: "\r") } else if currentCharacter == "\\" { builder.increment(char: "\\") } else { #warning("Add more details on this error. Don't make it a fatalError, but a diagnostic reporter.") fatalError("Unkown escaping character: '\\\(currentCharacter)'") } } private func lexerStateCharacterLiteral(_ readNextCharacter: inout Bool) { readNextCharacter = true if currentCharacter == "\\" { enterState(.characterLiteralEscape) } else if currentCharacter == "'" { tokenEnd(category: .literalCharacter) } else { builder.increment(char: currentCharacter) } } private func lexerStateCharacterLiteralEscape(_ readNextCharacter: inout Bool) { // Previous character was a \ . readNextCharacter = true leaveState() if currentCharacter == "n" { builder.increment(char: "\n") } else if currentCharacter == "\"" { builder.increment(char: "\"") } else if currentCharacter == "'" { builder.increment(char: "'") } else if currentCharacter == "t" { builder.increment(char: "\t") } else if currentCharacter == "r" { builder.increment(char: "\r") } else if currentCharacter == "\\" { builder.increment(char: "\\") } else { #warning("Add more details on this error. Don't make it a fatalError, but a diagnostic reporter.") fatalError("Unkown escaping character: '\\\(currentCharacter)'") } } private func enterState(_ state: LexerState) { states.append(state) } private func switchState(_ state: LexerState) { leaveState() enterState(state) } private var state: LexerState? { return states.last } @discardableResult private func leaveState() -> LexerState? { return states.popLast() } } // MARK: - Append tokens fileprivate extension Lexer { private func isLastToken(category: TokenCategory) -> Bool { guard let last = tokens.last else { return false } return last.isCategory(category) } private func append(token: Token) { if isLastToken(category: .endOfFile) { return } tokens.append(token) } private func appendSingleCharacterToken(category: TokenCategory) { appendSingleCharacterToken(character: currentCharacter, category: category) } private func appendSingleCharacterToken(character: String, category: TokenCategory) { builder.reset() builder.increment(char: character) append(token: builder.build(category: category)) builder.reset() } private func appendEndOfFileToken() { builder.reset() append(token: builder.build(category: .endOfFile)) } private func tokenStart(state: LexerState, appendCurrentCharacter: Bool = true) { builder.reset() if appendCurrentCharacter { builder.increment(char: currentCharacter) } enterState(state) } private func tokenEnd(category: TokenCategory) { leaveState() append(token: builder.build(category: category)) builder.reset() } } // MARK: - InputStream reader fileprivate extension Lexer { private func read(consumer: (String) -> Void) throws { inputStream.open() let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Lexer.BUFFER_SIZE) defer { buffer.deallocate() inputStream.close() } while inputStream.hasBytesAvailable { let read = inputStream.read(buffer, maxLength: Lexer.BUFFER_SIZE) guard read > 0 else { throw LexerError.unableToReadInputStream(streamError: inputStream.streamError) } var data = Data.init(capacity: Lexer.BUFFER_SIZE) data.append(buffer, count: read) guard let string = String(data: data, encoding: .utf8) else { throw LexerError.unableToConvertDataToString(data: data) } consumer(string); } } } // MARK: - public enum LexerError: Error { case unableToReadInputStream(streamError: Error?) case unableToConvertDataToString(data: Data) }
// // PTDeleteSession.swift // Prayer Times Reminder // // Created by Hussein Al-Ryalat on 9/14/18. // Copyright © 2018 SketchMe. All rights reserved. // import Foundation class PTDeleteReminderSession: PTSession { private(set) var reminder: PTReminder private(set) var dateComponents: DateComponents private(set) var persistance: PTPersistanceManager var identifier: String? init(reminder: PTReminder, dateComponents: DateComponents){ self.reminder = reminder self.dateComponents = dateComponents self.persistance = .shared } func start(){ // print("*** DELETING ACTION REQUEST ***") // print("*** \(reminder.contents) || \(reminder.prayer.text) || \(reminder.repeatDaysValue) ***") // print("*** Activities Count: \(reminder.activities.count) ***") if reminder.activities.count <= 1 { // the reminder has only one activity, so delete it permenetly. delete(reminder: reminder) return } // up to now we assume that the reminder activities count is more than one ( it has repeat days ). if let activity = reminder.activity(for: dateComponents){ // in case the user chooses to delete a completed activity reminder, delete only the activity if activity.action == .completed { delete(activity: activity) } else { // the activity is not completed, archive the reminder. archive(reminder: reminder) } return } // we didn't found an activity for that day, so archive the reminder, same beahvior. archive(reminder: reminder) } func cancel() { // no canceling :) } } extension PTDeleteReminderSession { private func delete(reminder: PTReminder){ // print("*** DELETE REMINDER ***") persistance.delete(reminder: reminder) } private func delete(activity: PTReminderActivity){ // print("*** DELETE ACTIVITY ***") persistance.delete(activity: activity) } private func archive(reminder: PTReminder){ // print("*** ARCHIVING REMINDER ***") persistance.archive(reminder: reminder) // print("*** Activities Count after archiving: \(reminder.activities.count) ***") } }
// // CharacterizationViewController.swift // CurveCharacterization // // Created by Shenyao Ke on 2/22/20. // Copyright © 2020 Shenyao Ke. All rights reserved. // import Cocoa class CharacterizationViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(onCurveChanged), name: .didChangeCurve, object: nil) } @objc func onCurveChanged(_ notification: Notification) { // process charaterizationProcessor.process(curve: (notification.userInfo!["Curve"] as! CubicBezierCurve)) NotificationCenter.default.post(name: .didComputeCurveCharacterization, object: self, userInfo: ["Type": charaterizationProcessor.charaterization as Any, "T1": charaterizationProcessor.t1 as Any, "T2": charaterizationProcessor.t2 as Any]) view.setNeedsDisplay(view.frame) } func rectAt(point: NSPoint) -> NSRect { return NSMakeRect(point.x - CharacterizationViewController.pointRadius, point.y - CharacterizationViewController.pointRadius, CharacterizationViewController.pointRadius * 2, CharacterizationViewController.pointRadius * 2) } func b3() -> NSPoint { return charaterizationProcessor.b3! } static let pointRadius = CGFloat(3) var charaterizationProcessor = CurveCharacterizationProcessor() }
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import StdlibCollectionUnittest import CoreAudio // Used in tests below. extension AudioBuffer : Equatable {} public func == (lhs: AudioBuffer, rhs: AudioBuffer) -> Bool { return lhs.mNumberChannels == rhs.mNumberChannels && lhs.mDataByteSize == rhs.mDataByteSize && lhs.mData == rhs.mData } var CoreAudioTestSuite = TestSuite("CoreAudio") // The size of the non-flexible part of an AudioBufferList. #if arch(i386) || arch(arm) let ablHeaderSize = 4 #elseif arch(x86_64) || arch(arm64) let ablHeaderSize = 8 #endif CoreAudioTestSuite.test("UnsafeBufferPointer.init(_: AudioBuffer)") { do { let audioBuffer = AudioBuffer( mNumberChannels: 0, mDataByteSize: 0, mData: nil) let result: UnsafeBufferPointer<Float> = UnsafeBufferPointer(audioBuffer) expectEqual(nil, result.baseAddress) expectEqual(0, result.count) } do { let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) let result: UnsafeBufferPointer<Float> = UnsafeBufferPointer(audioBuffer) expectEqual( UnsafePointer<Float>(audioBuffer.mData!), result.baseAddress) expectEqual(256, result.count) } } CoreAudioTestSuite.test("UnsafeMutableBufferPointer.init(_: AudioBuffer)") { do { let audioBuffer = AudioBuffer( mNumberChannels: 0, mDataByteSize: 0, mData: nil) let result: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(audioBuffer) expectEqual(nil, result.baseAddress) expectEqual(0, result.count) } do { let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) let result: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(audioBuffer) expectEqual( UnsafeMutablePointer<Float>(audioBuffer.mData!), result.baseAddress) expectEqual(256, result.count) } } CoreAudioTestSuite.test( "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)") { do { // NULL pointer. let buffer = UnsafeMutableBufferPointer<Float>(start: nil, count: 0) let result = AudioBuffer(buffer, numberOfChannels: 2) expectEqual(2, result.mNumberChannels) expectEqual(0, result.mDataByteSize) expectEqual(nil, result.mData) } do { // Non-NULL pointer. let buffer = UnsafeMutableBufferPointer<Float>( start: UnsafeMutablePointer<Float>(bitPattern: 0x1234_5678), count: 0) let result = AudioBuffer(buffer, numberOfChannels: 2) expectEqual(2, result.mNumberChannels) expectEqual(0, result.mDataByteSize) expectEqual(buffer.baseAddress, result.mData) } } CoreAudioTestSuite.test( "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)/trap") { #if arch(i386) || arch(arm) let overflowingCount = Int.max #elseif arch(x86_64) || arch(arm64) let overflowingCount = Int(UInt32.max) #endif let buffer = UnsafeMutableBufferPointer<Float>( start: UnsafeMutablePointer<Float>(bitPattern: 0x1234_5678), count: overflowingCount) expectCrashLater() // An overflow happens when we try to compute the value for mDataByteSize. _ = AudioBuffer(buffer, numberOfChannels: 2) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { expectEqual(ablHeaderSize + strideof(AudioBuffer), AudioBufferList.sizeInBytes(maximumBuffers: 1)) expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer), AudioBufferList.sizeInBytes(maximumBuffers: 16)) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count<0") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count==0") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/overflow") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: Int.max) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { do { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 1) expectEqual(1, ablPtrWrapper.count) free(ablPtrWrapper.unsafeMutablePointer) } do { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) expectEqual(16, ablPtrWrapper.count) free(ablPtrWrapper.unsafeMutablePointer) } } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count==0") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: 0) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count<0") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/overflow") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: Int.max) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/AssociatedTypes") { typealias Subject = UnsafeMutableAudioBufferListPointer expectRandomAccessCollectionAssociatedTypes( collectionType: Subject.self, iteratorType: IndexingIterator<Subject>.self, subSequenceType: MutableRandomAccessSlice<Subject>.self, indexType: Int.self, indexDistanceType: Int.self, indicesType: CountableRange<Int>.self) } CoreAudioTestSuite.test( "UnsafeMutableAudioBufferListPointer.init(_: UnsafeMutablePointer<AudioBufferList>)," + "UnsafeMutableAudioBufferListPointer.unsafePointer," + "UnsafeMutableAudioBufferListPointer.unsafeMutablePointer") { do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(nil) expectEmpty(ablPtrWrapper) } do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( UnsafeMutablePointer<AudioBufferList>(bitPattern: 0x1234_5678)!) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper.unsafePointer) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper.unsafeMutablePointer) } do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( UnsafeMutablePointer<AudioBufferList>(bitPattern: 0x1234_5678)) expectNotEmpty(ablPtrWrapper) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper!.unsafePointer) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper!.unsafeMutablePointer) } } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.count") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) let ablPtr = UnsafeMutablePointer<AudioBufferList>( UnsafeMutablePointer<UInt8>(allocatingCapacity: sizeInBytes)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the 'count' property has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) // Test getter. UnsafeMutablePointer<UInt32>(ablPtr).pointee = 0x1234_5678 expectEqual(0x1234_5678, ablPtrWrapper.count) // Test setter. ablPtrWrapper.count = 0x7765_4321 expectEqual(0x7765_4321, UnsafeMutablePointer<UInt32>(ablPtr).pointee) ablPtr.deallocateCapacity(sizeInBytes) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) let ablPtr = UnsafeMutablePointer<AudioBufferList>( UnsafeMutablePointer<UInt8>(allocatingCapacity: sizeInBytes)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the subscript has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) do { // Test getter. let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) UnsafeMutablePointer<AudioBuffer>( UnsafeMutablePointer<UInt8>(ablPtr) + ablHeaderSize ).pointee = audioBuffer ablPtrWrapper.count = 1 expectEqual(2, ablPtrWrapper[0].mNumberChannels) expectEqual(1024, ablPtrWrapper[0].mDataByteSize) expectEqual(audioBuffer.mData, ablPtrWrapper[0].mData) } do { // Test setter. let audioBuffer = AudioBuffer( mNumberChannels: 5, mDataByteSize: 256, mData: UnsafeMutablePointer<Void>(bitPattern: 0x8765_4321 as UInt)) ablPtrWrapper.count = 2 ablPtrWrapper[1] = audioBuffer let audioBufferPtr = UnsafeMutablePointer<AudioBuffer>( UnsafeMutablePointer<UInt8>(ablPtr) + ablHeaderSize) + 1 expectEqual(5, audioBufferPtr.pointee.mNumberChannels) expectEqual(256, audioBufferPtr.pointee.mDataByteSize) expectEqual(audioBuffer.mData, audioBufferPtr.pointee.mData) } ablPtr.deallocateCapacity(sizeInBytes) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)/trap") { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 4) ablPtrWrapper[0].mNumberChannels = 42 ablPtrWrapper[1].mNumberChannels = 42 ablPtrWrapper[2].mNumberChannels = 42 ablPtrWrapper[3].mNumberChannels = 42 expectCrashLater() ablPtrWrapper[4].mNumberChannels = 42 } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/Collection") { var ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) expectType(UnsafeMutableAudioBufferListPointer.self, &ablPtrWrapper) var expected: [AudioBuffer] = [] for i in 0..<16 { let audioBuffer = AudioBuffer( mNumberChannels: UInt32(2 + i), mDataByteSize: UInt32(1024 * i), mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678 + i * 10)) ablPtrWrapper[i] = audioBuffer expected.append(audioBuffer) } // FIXME: use checkMutableRandomAccessCollection, when we have that function. checkRandomAccessCollection(expected, ablPtrWrapper) free(ablPtrWrapper.unsafeMutablePointer) } runAllTests()
// // ViewController.swift // WikiSearch // // Created by user142467 on 9/29/18. // Copyright © 2018 user142467. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var searchTableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var wikkiVM: WikiViewModel! var selectedIndex:Int? var selectedSection:Int? override func viewDidLoad() { super.viewDidLoad() searchTableView.delegate = self searchTableView.dataSource = self wikkiVM = WikiViewModel() searchTableView.register(SearchTableViewCell.nib, forCellReuseIdentifier: SearchTableViewCell.reuseIndentifier) // Do any additional setup after loading the view, typically from a nib } override func viewWillAppear(_ animated: Bool) { refreshData() searchBar.resignFirstResponder() searchTableView.reloadData() } func refreshData(){ wikkiVM.fetchPersitedData { (bool) in DispatchQueue.main.sync { self.searchTableView.reloadData() } } } @objc func clearHistoryAction(_ sender:UIButton){ wikkiVM.clearPersistedData { (bool) in DispatchQueue.main.async { self.refreshData() self.searchTableView.reloadData() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "send"{ let destination = segue.destination as! WikiWebViewController if let wikiVM = wikkiVM, let wikiData = wikiVM.wikiModel, let query = wikiData.query , let pages = query.pages, pages.count > 0 && selectedIndex == 0{ destination.strText = pages[selectedIndex!].title } if let wikiVm = wikkiVM, let pageData = wikiVm.pageData, pageData.count > 0 && selectedSection == 1{ destination.strText = pageData[pageData.count - 1 - selectedIndex!].title ?? "" } } } } //Mark:- TableView Delegate, DataSource Method extension ViewController:UITableViewDataSource, UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 1{ return 40 } return 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 1{ let view = UINib(nibName: "HeaderView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! HeaderView view.clearButton.addTarget(self, action: #selector(ViewController.clearHistoryAction), for: .touchUpInside) return view } return nil } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let wikiVm = wikkiVM, let pageData = wikiVm.pageData, pageData.count > 0 && section == 1{ return pageData.count } if let wikiVm = wikkiVM, let wikiData = wikiVm.wikiModel, let query = wikiData.query, let pages = query.pages, pages.count > 0 && section == 0{ return pages.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return wikkiVM.cellInstanceLoadData(tableView,indexPath) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let wikiVm = wikkiVM, let wikiData = wikiVm.wikiModel, let query = wikiData.query, let pages = query.pages, pages.count > 0{ wikkiVM.saveDataToDisk(page: pages[indexPath.row]) { (bool) in print(bool) } } selectedSection = indexPath.section selectedIndex = indexPath.row performSegue(withIdentifier: "send", sender: self) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 110 } } //Mark:- Search Delegate Method extension ViewController:UISearchBarDelegate{ func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { wikkiVM.loadData(serachText: searchText) { (bool) in if bool{ DispatchQueue.main.async{ self.searchTableView.reloadData() } } } } }
// // WalletDetailInfoCell.swift // EEPCShop // // Created by Mac Pro on 2019/4/4. // Copyright © 2019年 CHENNIAN. All rights reserved. // import UIKit class WalletDetailInfoCell: SNBaseTableViewCell { let name = UILabel().then{ $0.text = "转出USDT" $0.textColor = Color(0x2a3457) $0.font = Font(30) } let timeLable = UILabel().then{ $0.text = "2019/02/23 13:05:01" $0.textColor = Color(0xa9aebe) $0.font = Font(24) } let money = UILabel().then{ $0.text = "+362.6552" $0.textColor = Color(0x0e7d28) $0.font = BoldFont(32) } override func setupView() { contentView.addSubviews(views: [name,timeLable,money]) name.snp.makeConstraints { (make) in make.left.equalToSuperview().snOffset(34) make.top.equalToSuperview().snOffset(33) } timeLable.snp.makeConstraints { (make) in make.left.equalToSuperview().snOffset(34) make.top.equalTo(name.snp.bottom).snOffset(19) } money.snp.makeConstraints { (make) in make.centerY.equalTo(name.snp.centerY) make.right.equalToSuperview().snOffset(-34) } } } extension WalletDetailInfoCell{ func setData(_ type:String,_ num:String,_ time:String) { name.text = type timeLable.text = time money.text = num } }
// // SearchPage.swift // SearchPage // // Created by Gautam on 09/08/21. // Copyright © 2021 orgName. All rights reserved. // import SwiftUI import shared struct SearchPage: View { @State private var username: String = "" @State private var isEditing = false @StateObject var viewModel = SearchViewModel() var body: some View { VStack(alignment: .leading) { HStack(alignment: .center) { TextField( "User name (email address)", text: $username ) { isEditing in self.isEditing = isEditing } onCommit: { print("username") }.autocapitalization(.none) .disableAutocorrection(true) .frame(height: 56) Button("Search", action: { viewModel.searchArticles(query: username) }) }.padding(16) List(viewModel.articles) { article in HStack(alignment: .top) { AsyncImage(url: URL(string: article.urlToImage ?? "")) { image in image .resizable() .aspectRatio(contentMode: .fill) } placeholder: { ProgressView() }.frame(width: 80, height: 120) VStack(alignment: .leading, spacing: 10) { Text(article.title) .font(.system(size: 15, weight: .bold, design: .default)) .foregroundColor(.black) .lineLimit(2) Text(article.description_ ?? "") .font(.system(size: 14)) .foregroundColor(.gray) .lineLimit(1) Text(article.source.name) .font(.system(size: 14)) .foregroundColor(.gray) .lineLimit(1) } }.frame(height: 120) .padding(16) } }.onAppear { }.onDisappear { } } func search() { } } struct SearchPage_Previews: PreviewProvider { static var previews: some View { SearchPage() } }
// // BLEExtensions.swift // TCP // // Created by salam on 25/04/16. // Copyright © 2016 Cabot. All rights reserved. // import Foundation extension NSData { func hexRepresentationWithSpaces(spaces:Bool) ->NSString { var byteArray = [UInt8](count: self.length, repeatedValue: 0x0) // The Test Data is moved into the 8bit Array. self.getBytes(&byteArray, length:self.length) var hexBits = "" as String for value in byteArray { let newHex = NSString(format:"0x%2X", value) as String hexBits += newHex.stringByReplacingOccurrencesOfString(" ", withString: "0", options: NSStringCompareOptions.CaseInsensitiveSearch) if spaces { hexBits += " " } } return hexBits } func hexRepresentation()->String { let dataLength:Int = self.length let string = NSMutableString(capacity: dataLength*2) let dataBytes:UnsafePointer<Void> = self.bytes for idx in 0..<dataLength { string.appendFormat("%02x", [UInt(dataBytes[idx])] ) } return string as String } }
// // FullPlan.swift // EasyMeals // // Created by Alex Grimes on 5/7/20. // Copyright © 2020 Alex Grimes. All rights reserved. // import Foundation import Firebase public let calendarDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] public let calendarMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"] public let mealNames = ["Breakfast", "Lunch", "Dinner", "Snacks", "Fluids"] enum MealName: String, CaseIterable { case breakfast = "Breakfast" case lunch = "Lunch" case dinner = "Dinner" case snacks = "Snacks" case fluids = "Fluids" } let formatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter }() let fullFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE, MMM dd, yyyy" return dateFormatter }() struct FullPlan { var plan: [Date : DayPlan] = [:] // [date: DayPlan] public init() {} public init(snapshot: DataSnapshot) { for dateChild in snapshot.children { guard let dateSnapshot = dateChild as? DataSnapshot, let date = formatter.date(from: dateSnapshot.key) else { return } plan[date] = DayPlan() MealName.allCases.forEach { plan[date]?.day[$0] = [] } for mealChild in dateSnapshot.children { guard let mealSnapshot = mealChild as? DataSnapshot else { return } let meal = mealSnapshot.key var newMeal : [String] = [] for itemChild in mealSnapshot.children { guard let itemSnapshot = itemChild as? DataSnapshot else { return } let item = itemSnapshot.key newMeal.append(item) } if let mealName = MealName(rawValue: meal) { plan[date]?.day[mealName] = newMeal } } } } } struct PlanCurrent { var plan: [Date: DayPlan] = [:] public init() {} public init(fullPlan: FullPlan) { for date in fullPlan.plan.keys { let currentDate = formatter.date(from: formatter.string(from: Date()))! if date >= currentDate { plan[date] = fullPlan.plan[date] } } } } struct PlanHistory { var plan: [Date: DayPlan] = [:] public init() {} public init(fullPlan: FullPlan) { for date in fullPlan.plan.keys { let currentDate = formatter.date(from: formatter.string(from: Date()))! if date < currentDate { plan[date] = fullPlan.plan[date] } } } } struct DayPlan { var day: [MealName : [String]] = [:] // [mealName: listof foods] }
// // ArtworkCell.swift // AssignmentTwo // // Created by Jahan on 07/05/2019. // Copyright © 2019 Jahan. All rights reserved. // import UIKit class ArtworkCell: UITableViewCell { 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 } }
// // ImageOpeningTransitioning.swift // CollectionTransition // // Created by Alexander Blokhin on 13.01.16. // Copyright © 2016 Alexander Blokhin. All rights reserved. // import UIKit class ImageOpeningTransitioning: NSObject, UIViewControllerTransitioningDelegate { let imagePresent = ImagePresentTransitioning() let imageDismiss = ImageDismissTransitioning() // MARK: - UIViewControllerTransitioningDelegate func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return imagePresent } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return imageDismiss } func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return imageDismiss.interactive ? imageDismiss : nil } }
import UIKit class MainViewController: UIViewController { @IBOutlet weak var foundImageTextField: UITextField! @IBOutlet weak var contentModeSegmentControl: UISegmentedControl! let segueID = "segmentShowImage" let segueIDError = "notFoundImage" override func viewDidLoad() { super.viewDidLoad() } @IBAction func foundImageButtonDidClick(_ sender: UIButton) { let textFieldText = foundImageTextField.text let image = UIImage(named: textFieldText!) if image != nil { self.performSegue(withIdentifier: segueID, sender: nil) } else { self.performSegue(withIdentifier: segueIDError, sender: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let textFieldText = foundImageTextField.text if segue.identifier == segueID { let image = getImege() let contentMode = getContentMode() let ShowImageViewController = segue.destination as! ShowImageViewController ShowImageViewController.imageToPresent = image ShowImageViewController.imageViewContentMode = contentMode } else if segue.identifier == segueIDError { let NotFoundInageViewController = segue.destination as! NotFoundInageViewController NotFoundInageViewController.notFoundlabelText = "Can not find an image with name: \(textFieldText ?? "")" } } } extension MainViewController { func getImege() -> UIImage? { let imageName = foundImageTextField.text! let image = UIImage.init(named: imageName) return image } func getContentMode () -> UIView.ContentMode { switch contentModeSegmentControl.selectedSegmentIndex { case 0: return .scaleToFill case 1: return .scaleAspectFit case 2: return .scaleAspectFill default: fatalError() } } }
// // Secrets.swift // blyp // // Created by Hayden Hong on 4/17/20. // Copyright © 2020 Team Sonar. All rights reserved. // import Foundation /// DO NOT commit secrets in here struct Secrets { static var ALGOLIA_APP_ID = "" static var ALGOLIA_API_KEY = "" }
// // AnswersSnippets.swift // // // Created by Vladislav Fitc on 13/01/2021. // import Foundation import AlgoliaSearchClient struct AnswersSnippets: SnippetsCollection {} extension AnswersSnippets { func findAnswers() { let query = AnswersQuery(query: "when do babies start learning", queryLanguages: [.english]) .set(\.attributesForPrediction, to: ["description", "title", "transcript"]) .set(\.nbHits, to: 20) index.findAnswers(for: query) { result in if case .success(let response) = result { print("Response: \(response)") } } } }
// // CocktailListViewController.swift // Cocktail // // Created by Luciano Schillagi on 28/09/2018. // Copyright © 2018 luko. All rights reserved. // /* Controller */ import UIKit /* Abstract: Una pantalla que contiene un listado de cocktails. Cada celda contiene el nombre, los ingredientes y la foto del trago. */ class CocktailListViewController: UIViewController { //***************************************************************** // MARK: - Properties //***************************************************************** var cocktail: Cocktail? var cocktailArray = [Cocktail]() //***************************************************************** // MARK: - IBOutlets //***************************************************************** // la lista de tragos @IBOutlet weak var cocktailTableView: UITableView! @IBOutlet weak var networkActivity: UIActivityIndicatorView! //***************************************************************** // MARK: - VC Life Cycle //***************************************************************** override func viewDidLoad() { super.viewDidLoad() print("hola") debugPrint("🧛🏻‍♂️🧛🏻‍♂️\(self.cocktailArray.count)") navigationItem.title = "Cocktail List" //TODO: luego mudar // networking ⬇ : Cocktails CocktailApiClient.getCocktails { (success, resultCocktail, error) in DispatchQueue.main.async { if success { // comprueba si el 'resultMedia' recibido contiene algún valor if let resultCocktail = resultCocktail { self.cocktailArray = resultCocktail // 🔌 👏 self.networkActivity.stopAnimating() self.cocktailTableView.reloadData() //test for item in self.cocktailArray { // las urls para obtener la imagenes de los tragos debugPrint("la imagen del trago: \(item.drinkThumb!)") } } } else { // si devuelve un error //self.displayAlertView(title: "Error Request", message: error) } } } } } // end class extension CocktailListViewController: UITableViewDataSource { //***************************************************************** // MARK: - Table View Data Source Methods //***************************************************************** // task: determinar la cantidad de filas que tendrá la tabla func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cocktailArray.count } // task: configurar la celda de la tabla func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let preImageDrink = UIImage(named: "preImageDrink") let cellReuseId = "cell" let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId, for: indexPath) as UITableViewCell cocktail = cocktailArray[(indexPath as NSIndexPath).row] cell.textLabel?.text = cocktail?.drinkName cell.imageView?.image = preImageDrink if let drinkId = cocktail?.idDrink { let _ = CocktailApiClient.getCocktailImage((cocktail?.drinkThumb)!) { (imageData, error) in if let image = UIImage(data: imageData!) { DispatchQueue.main.async { print("🧙🏽‍♀️ datos de la imagen\(imageData!), uimage: \(image)") cell.imageView!.image = image print("🔎\(image)") } } else { print(error ?? "empty error") } } } return cell } } extension CocktailListViewController: UITableViewDelegate { //***************************************************************** // MARK: - Table View Delegate Methods //***************************************************************** // task: navegar hacia el detalle de la película (de acuerdo al listado de películas actual) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboardId = "Detail" let controller = storyboard!.instantiateViewController(withIdentifier: storyboardId) as! CocktailDetailViewController controller.selecteCocktail = cocktailArray[(indexPath as NSIndexPath).row] navigationController!.pushViewController(controller, animated: true) } }