text stringlengths 8 1.32M |
|---|
import Foundation
import XCTest
import Autometry
class DashboardTests: XCTestCase {
let dashboard = Dashboard()
let refuelA = Refuel()
let refuelB = Refuel()
let refuelC = Refuel()
let refuelD = Refuel()
let refuelE = Refuel()
let refuelF = Refuel()
let refuelG = Refuel()
let refuelH = Refuel()
var refuelsA : [Refuel] = []
var refuelsB : [Refuel] = []
var refuelsC : [Refuel] = []
var refuelsD : [Refuel] = []
override func setUp() {
refuelA.odometer = 10000
refuelA.gallons = 10
refuelA.pricePerGallon = 3.499
refuelB.odometer = 10300
refuelB.gallons = 10
refuelB.pricePerGallon = 3.459
refuelC.odometer = 10500
refuelC.gallons = 10
refuelC.pricePerGallon = 2.899
refuelD.odometer = 10900
refuelD.gallons = 10
refuelD.pricePerGallon = 2.399
refuelE.odometer = 10950
refuelE.gallons = 10
refuelE.pricePerGallon = 4.699
refuelF.odometer = 10350
refuelF.gallons = 2.5
refuelF.pricePerGallon = 3.999
refuelF.partial = true
refuelG.odometer = 10600
refuelG.gallons = 10
refuelG.pricePerGallon = 3.999
refuelH.odometer = 10400
refuelH.gallons = 2.5
refuelH.pricePerGallon = 3.999
refuelH.partial = true
refuelsA = [refuelC, refuelB, refuelA]
refuelsB = [refuelE, refuelD, refuelC, refuelB, refuelA]
refuelsC = [refuelG, refuelC, refuelF, refuelB, refuelA]
refuelsD = [refuelG, refuelC, refuelH, refuelF, refuelB, refuelA]
super.setUp()
}
func testMpgAverage() {
XCTAssertEqual(dashboard.mpgAverage(refuelsA), "25")
XCTAssertEqual(dashboard.mpgBest(refuelsA), "30")
XCTAssertEqual(dashboard.mpgWorst(refuelsA), "20")
XCTAssertEqual(dashboard.mpgAverage(refuelsB), "23")
XCTAssertEqual(dashboard.mpgBest(refuelsB), "40")
XCTAssertEqual(dashboard.mpgWorst(refuelsB), "5")
}
func testPricePerGallon() {
XCTAssertEqual(dashboard.averagePPG([]), "N/A")
XCTAssertEqual(dashboard.averagePPG(refuelsA), "$3.29")
XCTAssertEqual(dashboard.pricePerGallonBest(refuelsA), "$2.90")
XCTAssertEqual(dashboard.pricePerGallonWorst(refuelsA), "$3.50")
XCTAssertEqual(dashboard.averagePPG(refuelsB), "$3.39")
XCTAssertEqual(dashboard.pricePerGallonBest(refuelsB), "$2.40")
XCTAssertEqual(dashboard.pricePerGallonWorst(refuelsB), "$4.70")
}
func testTotalSpent() {
XCTAssertEqual(dashboard.totalSpent(refuelsA), "$98.57")
XCTAssertEqual(dashboard.totalSpent(refuelsB), "$169.55")
XCTAssertEqual(dashboard.totalSpentBest(refuelsA), "$28.99")
XCTAssertEqual(dashboard.totalSpentBest(refuelsB), "$23.99")
XCTAssertEqual(dashboard.totalSpentWorst(refuelsA), "$34.99")
XCTAssertEqual(dashboard.totalSpentWorst(refuelsB), "$46.99")
}
func testTotalMiles() {
XCTAssertEqual(dashboard.totalMiles([refuelA]), "0")
XCTAssertEqual(dashboard.totalMiles(refuelsA), "500")
XCTAssertEqual(dashboard.totalMiles(refuelsB), "950")
XCTAssertEqual(dashboard.totalMilesLongest([refuelA]), "0")
XCTAssertEqual(dashboard.totalMilesLongest(refuelsA), "300")
XCTAssertEqual(dashboard.totalMilesLongest(refuelsB), "400")
XCTAssertEqual(dashboard.totalMilesShortest([refuelA]), "0")
XCTAssertEqual(dashboard.totalMilesShortest(refuelsA), "200")
XCTAssertEqual(dashboard.totalMilesShortest(refuelsB), "50")
}
func testCostPerMile() {
XCTAssertEqual(dashboard.costPerMile([]), "$0.00")
XCTAssertEqual(dashboard.costPerMile(refuelsA), "$0.14")
XCTAssertEqual(dashboard.costPerMile(refuelsB), "$0.21")
XCTAssertEqual(dashboard.costPerMileBest(refuelsA), "$0.12")
XCTAssertEqual(dashboard.costPerMileBest(refuelsB), "$0.07")
XCTAssertEqual(dashboard.costPerMileWorst(refuelsA), "$0.17")
XCTAssertEqual(dashboard.costPerMileWorst(refuelsB), "$0.48")
}
func testMilesPerTrip() {
let milesPerTripA = dashboard.milesPerTrip(refuelsA)
XCTAssertEqual(milesPerTripA.count, 2)
XCTAssertEqual(milesPerTripA[0], 200)
XCTAssertEqual(milesPerTripA[1], 300)
let milesPerTripB = dashboard.milesPerTrip(refuelsB)
XCTAssertEqual(milesPerTripB.count, 4)
XCTAssertEqual(milesPerTripB[0], 50)
XCTAssertEqual(milesPerTripB[1], 400)
XCTAssertEqual(milesPerTripB[2], 200)
XCTAssertEqual(milesPerTripB[3], 300)
}
func testMpgs() {
let mpgsA = dashboard.mpgs(refuelsA)
XCTAssertEqual(mpgsA.count, refuelsA.count - 1)
XCTAssertEqual(mpgsA[0], 20)
XCTAssertEqual(mpgsA[1], 30)
let mpgsB = dashboard.mpgs(refuelsB)
XCTAssertEqual(mpgsB.count, refuelsB.count - 1)
XCTAssertEqual(mpgsB[0], 5)
XCTAssertEqual(mpgsB[1], 40)
XCTAssertEqual(mpgsB[2], 20)
XCTAssertEqual(mpgsB[3], 30)
let refuel1 = Refuel()
refuel1.odometer = 10000
refuel1.gallons = 10
let refuel2 = Refuel()
refuel2.odometer = 10300
refuel2.gallons = 15
let refuelsC = [refuel2, refuel1]
let mpgsC = dashboard.mpgs(refuelsC)
XCTAssertEqual(mpgsC.count, refuelsC.count - 1)
XCTAssertEqual(mpgsC[0], 20)
}
func testMpgsWithPartialInside() {
let mpgs = dashboard.mpgs(refuelsC)
// 10600, 10500, 10350 (partial), 10300, 10000
XCTAssertEqual(refuelsC.count, 5)
XCTAssertEqual(mpgs.count, refuelsC.count - 1)
XCTAssertEqual(mpgs[0], 10)
XCTAssertEqual(mpgs[1], 16)
XCTAssertEqual(mpgs[2], 16)
XCTAssertEqual(mpgs[3], 30)
}
func testMpgsWithPartialNewest() {
let refuels = [refuelF, refuelB, refuelA]
let mpgs = dashboard.mpgs(refuels)
// 10350 (partial), 10300, 10000
XCTAssertEqual(refuels.count, 3)
XCTAssertEqual(mpgs.count, 1)
XCTAssertEqual(mpgs[0], 30)
}
func testMpgsWithPartialOldest() {
let refuels = [refuelC, refuelF]
let mpgs = dashboard.mpgs(refuels)
// 10500, 10350 (partial)
XCTAssertEqual(refuels.count, 2)
XCTAssertEqual(mpgs.count, 1)
XCTAssertEqual(mpgs[0], 15)
}
func testMpgsWithMultiPartials() {
let mpgs = dashboard.mpgs(refuelsD)
XCTAssertEqual(refuelsD.count, 6)
XCTAssertEqual(mpgs.count, refuelsD.count - 1)
XCTAssertEqual(mpgs[0], 10)
XCTAssertEqual(mpgs[1], 13)
XCTAssertEqual(mpgs[2], 13)
XCTAssertEqual(mpgs[3], 13)
XCTAssertEqual(mpgs[4], 30)
}
} |
//
// MapRouter.swift
// carWash
//
// Created by Juliett Kuroyan on 19.11.2019.
// Copyright ยฉ 2019 VooDooLab. All rights reserved.
//
import UIKit
class MapRouter {
weak var view: MapViewController?
weak var tabBarController: MainTabBarController?
init(view: MapViewController?) {
self.view = view
}
}
// MARK: - MapRouterProtocol
extension MapRouter: MapRouterProtocol {
func presentCityView(cityChanged: (() -> ())? = nil) {
guard let view = view else { return }
let configurator = CitiesConfigurator(cityChanged: cityChanged)
let vc = configurator.viewController
view.navigationController?.pushViewController(vc, animated: true)
}
func presentSaleInfoView(id: Int) {
guard let view = view else { return }
let configurator = SaleInfoConfigurator(id: id)
let vc = configurator.viewController
view.navigationController?.pushViewController(vc, animated: true)
}
func popView() {
view?.navigationController?.popViewController(animated: true)
}
func popToAuthorization() {
tabBarController?.navigationController?.popViewController(animated: true)
}
}
|
//
// ListCell.swift
// government_park
//
// Created by YiGan on 27/09/2017.
// Copyright ยฉ 2017 YiGan. All rights reserved.
//
import UIKit
import gov_sdk
class ListCell: UITableViewCell {
@IBOutlet weak var markButton: UIButton!
@IBOutlet weak var mainLabel: UILabel!
@IBOutlet weak var originalLabel: UILabel!
@IBOutlet weak var copyLabel: UILabel!
@IBOutlet weak var remarksLabel: UILabel!
var applyId = 0
var attachmentId = 0
var isChecked = false{
didSet{
markButton.isSelected = isChecked
}
}
var closure: (()->())?
override func didMoveToSuperview() {
remarksLabel.textColor = .lightGray
}
@IBAction func click(_ sender: UIButton) {
isChecked = !isChecked
NetworkHandler.share().attachment.markStuff(withApplyId: applyId, withStuffId: attachmentId, withMarked: isChecked) { (resultCode, message, data) in
DispatchQueue.main.async {
guard resultCode == .success else{
return
}
self.closure?()
}
}
}
}
|
//
// HomeViewController.swift
// ParisWeather
//
// Created by Xav Mac on 11/03/2020.
// Copyright ยฉ 2020 ParisWeather. All rights reserved.
//
import UIKit
// MARK: - HomeViewController
class HomeViewController: ViewController {
// MARK: - IBOutlet
@IBOutlet weak var cityImageView: UIImageView!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var citySunriseLabel: UILabel!
@IBOutlet weak var citySunsetLabel: UILabel!
@IBOutlet weak var dayPageControl: UIPageControl!
@IBOutlet weak var dayPageControlTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var dayForecastCollectionView: UICollectionView!
// MARK: - IBAction
@IBAction func dayPageControlAction(_ sender: Any) {
DispatchQueue.main.async {
self.dayForecastCollectionView.scrollToItem(at: IndexPath(row: self.dayPageControl.currentPage,
section: 0),
at: .top,
animated: false)
}
}
// MARK: - Variables
var cityID : Int = 2968815 // Here Paris ID
var cityForecast : Forecast?
var cityForecastPerDay = [Day]()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.cityImageView.image = getDynamicBackground()
dayPageControl.transform = self.dayPageControl.transform.rotated(by: .pi/2)
dayPageControlTrailingConstraint.constant -= dayPageControl.frame.width
self.getForecasts()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
guard let forecast = self.cityForecast else {
return
}
actualizeDataOnScreen(forecast: forecast)
}
}
|
//
// first.swift
// siderHW
//
// Created by User15 on 2020/4/12.
// Copyright ยฉ 2020 test. All rights reserved.
//
import SwiftUI
struct first: View {
var body: some View {
NavigationView {
ZStack{
NavigationLink(destination: seperate()){
Image("introduction")
.renderingMode(.original)//็ถๆ้ๆๆ่ฎๅฎไธ่่ฒ,็บไบ่ฟๅๅๅ็
.resizable()
.scaledToFit()
.offset(y: 50)//็
ง็ไฝ็ฝฎ
.frame(width:350,height:900)//ๅๅคงๅฐ
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 3))
.shadow(radius: 80)//้ฐๅฝฑ
.offset(y: -80)//ๅไฝ็ฝฎ
.frame(width:400,height:1000)
.padding()
}
.background(LinearGradient(gradient: Gradient(colors:[Color(red:252/255,green:227/255,blue:220/255),Color(red:252/255,green:182/255,blue:159/255)]), startPoint: UnitPoint(x: 0, y: 1), endPoint: UnitPoint(x:1,y:0)))
Text("SHE")
.offset(y: 140)
.font(.custom("Snell Roundhand",size:60))
}
.navigationBarTitle("Welcome", displayMode: .inline)
}
}
}
struct first_Previews: PreviewProvider {
static var previews: some View {
first()
}
}
|
enum KeyAPI {
case getKey(id: String, teamId: String)
case downloadKey(id: String, teamId: String)
case createKey(teamId: String, params: [String: String])
case revokeKey(id: String, teamId: String)
}
|
//
// ProfileViewController.swift
// Skoolivin
//
// Created by Namrata A on 4/29/18.
// Copyright ยฉ 2018 Namrata A. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase
class ProfileViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var dobField: UITextField!
@IBOutlet weak var imageSelector: UIImageView!
@IBOutlet weak var universityField: UITextField!
@IBOutlet weak var logoutButton: UIBarButtonItem!
let picker = UIImagePickerController()
var databaseReference: DatabaseReference?
var storageReference: StorageReference?
@IBAction func selectImage(_ sender: UIButton) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
self.imageSelector.image = image
let chosen = UIImageJPEGRepresentation(image, 0.8)
self.storePhotoInStorage(imageData: chosen!)
}
self.dismiss(animated: true, completion: nil)
}
func storePhotoInStorage(imageData: Data) {
let imagePath = "user_photos/" + Auth.auth().currentUser!.uid + "/\(Auth.auth().currentUser!.uid).jpg"
// set content type to โimage/jpegโ in firebase storage metadata
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
// create a child node at imagePath with imageData and metadata
storageReference?.child(imagePath).putData(imageData, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
return
}
// use sendMessage to add imageURL to database
self.storeImageDataOnDatabase(imageData: ["profileImageUrl":(self.storageReference?.child((metadata?.path)!).description)!])
}
}
func storeImageDataOnDatabase(imageData: [String: String]) {
let imagePath = "users/" + Auth.auth().currentUser!.uid + "/"
databaseReference?.child(imagePath).setValue(imageData)
}
@IBAction func updateInfo(_ sender: UIButton) {
if (nameField.text == nil) {
showAlert(withAlertMessage: "Empty Name Field")
return
}
if (dobField.text == nil) {
showAlert(withAlertMessage: "Empty DOB Field")
return
}
if (universityField.text == nil) {
showAlert(withAlertMessage: "Empty University Field")
return
}
//extract values from fields
let name = nameField.text!
let dob = dobField.text!
let university = universityField.text!
// Store the user data
storeUserDataOnDatabase(withName: name, dob: dob, university: university)
// Navigate to Main Screen
showAlert(withAlertMessage: "Updated!")
}
func storeUserDataOnDatabase(withName name: String, dob: String, university: String) {
print("function Called")
databaseReference?.child("users").child(Auth.auth().currentUser!.uid).child("name").setValue(name)
databaseReference?.child("users").child(Auth.auth().currentUser!.uid).child("dob").setValue(dob)
databaseReference?.child("users").child(Auth.auth().currentUser!.uid).child("university").setValue(university)
}
func showAlert(withAlertMessage alertMessage: String) {
let alert = UIAlertController(title: "Message", message: alertMessage, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
nameField.delegate = self
dobField.delegate = self
universityField.delegate = self
databaseReference = Database.database().reference()
storageReference = Storage.storage().reference()
let font = UIFont(name: "Sinhala Sangam MN", size: 13)
logoutButton.setTitleTextAttributes([NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): font as Any], for: .normal)
}
@IBAction func logout(_ sender: UIBarButtonItem) {
handleLogout()
}
func handleLogout(){
do {
try Auth.auth().signOut()
} catch let logoutError {
print(logoutError)
}
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let signInVC = storyBoard.instantiateViewController(withIdentifier: "LoginViewController")
self.present(signInVC, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true,completion: nil)
}
// When Return key is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// when tapped elsewhere than fields
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
|
//
// FlashcardTableViewCell.swift
// flashcards
//
// Created by Bryan Workman on 7/24/20.
// Copyright ยฉ 2020 Bryan Workman. All rights reserved.
//
import UIKit
class FlashcardTableViewCell: UITableViewCell {
//MARK: - Outlets
@IBOutlet weak var frontLabel: UILabel!
@IBOutlet weak var backLabel: UILabel!
@IBOutlet weak var frontImageView: UIImageView!
@IBOutlet weak var backImageView: UIImageView!
//MARK: - Properties
var flashcard: Flashcard? {
didSet {
updateViews()
}
}
//MARK: - Helper Methods
func updateViews() {
guard let flashcard = flashcard else {return}
if let frontString = flashcard.frontString {
frontLabel.isHidden = false
frontImageView.isHidden = true
frontLabel.text = frontString
} else if let frontPhoto = flashcard.frontPhoto {
frontLabel.isHidden = true
frontImageView.isHidden = false
frontImageView.image = frontPhoto
} else {
frontLabel.isHidden = true
frontImageView.isHidden = true
}
if let backString = flashcard.backString {
backLabel.isHidden = false
backImageView.isHidden = true
backLabel.text = backString
} else if let backPhoto = flashcard.backPhoto {
backLabel.isHidden = true
backImageView.isHidden = false
backImageView.image = backPhoto
} else {
backLabel.isHidden = true
backImageView.isHidden = true
}
}
} //End of class
|
//
// AboutCanadaViewModelTests.swift
// AboutCanadaTests
//
// Created by Vivek Goswami on 2/8/21.
// Copyright ยฉ 2021 Vivek Goswami. All rights reserved.
//
import XCTest
@testable import AboutCanada
class AboutCanadaViewModelTests: XCTestCase {
var mockAPIService: Networking?
var sut: AboutCanadaViewModel?
override func setUp() {
super.setUp()
sut = AboutCanadaViewModel()
mockAPIService = Networking()
}
override func tearDown() {
mockAPIService = nil
sut = nil
super.tearDown()
}
func test_fetch_record() {
let expect = XCTestExpectation(description: "callback")
let request: Services = .aboutCanada
mockAPIService?.requestObject(request, completion: { (records: AboutCanada) in
expect.fulfill()
XCTAssertEqual( records.rows?.count, 14)
})
wait(for: [expect], timeout: 3.1)
}
func test_cell_view_model() {
// Given photos
let rowWithData = Rows()
rowWithData.title = "Demo"
rowWithData.description = "Description will come here"
rowWithData.photoUrl = "https://picsum.photos/200"
let rowWithoutDescription = Rows()
rowWithoutDescription.title = "Demo"
rowWithoutDescription.description = nil
rowWithoutDescription.photoUrl = "https://picsum.photos/200"
let rowWithoutTitle = Rows()
rowWithoutTitle.title = nil
rowWithoutTitle.description = "Test message"
rowWithoutTitle.photoUrl = "https://picsum.photos/200"
let rowWithoutData = Rows()
rowWithoutData.title = nil
rowWithoutData.description = nil
rowWithoutData.photoUrl = nil
let cellViewModelWithoutDesc = sut?.record?.rows?.first
let cellViewModelWithoutTitle = sut?.record?.rows?.first
let cellViewModelWithoutData = sut?.record?.rows?.first
XCTAssertEqual(cellViewModelWithoutDesc?.description, rowWithoutDescription.description )
XCTAssertEqual(cellViewModelWithoutTitle?.title, rowWithoutTitle.title )
XCTAssertEqual(cellViewModelWithoutData?.photoUrl, nil)
}
}
|
#if canImport(UIKit)
import UIKit
internal final class CircleIndicatorView: UIView {
// for Focus
override internal func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
override internal func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
let color = #colorLiteral(red: 0.9568627477, green: 0.8340871711, blue: 0.5, alpha: 1)
ctx.setStrokeColor(color.cgColor)
ctx.setLineWidth(1.0)
ctx.addEllipse(in: rect.insetBy(dx: 4.0, dy: 4.0))
ctx.strokePath()
}
}
internal final class SquareIndicatorView: UIView {
// for Exposure
override internal func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
override internal func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
let color = #colorLiteral(red: 0.9568627477, green: 0.8340871711, blue: 0.5, alpha: 1)
ctx.setStrokeColor(color.cgColor)
ctx.setLineWidth(1.0)
ctx.addRect(rect.insetBy(dx: 1.0, dy: 1.0))
ctx.strokePath()
let margin: CGFloat = 1.0
let length: CGFloat = 6.0
// ไธใฎ็ธฆ็ท
ctx.move(to: CGPoint(x: rect.midX, y: 0.0 + margin))
ctx.addLine(to: CGPoint(x: rect.midX, y: 0.0 + margin + length))
ctx.strokePath()
// ๅณใฎๆจช็ท
ctx.move(to: CGPoint(x: rect.maxX - margin, y: rect.midY))
ctx.addLine(to: CGPoint(x: rect.maxX - margin - length, y: rect.midY))
ctx.strokePath()
// ไธใฎ็ธฆ็ท
ctx.move(to: CGPoint(x: rect.midX, y: rect.maxY - margin))
ctx.addLine(to: CGPoint(x: rect.midX, y: rect.maxY - margin - length))
ctx.strokePath()
// ๅทฆใฎๆจช็ท
ctx.move(to: CGPoint(x: 0.0 + margin, y: rect.midY))
ctx.addLine(to: CGPoint(x: 0.0 + margin + length, y: rect.midY))
ctx.strokePath()
}
}
#endif
|
//
// TimeStampHelper.swift
// Chat
//
// Created by Vahagn Manasyan on 6/13/20.
// Copyright ยฉ 2020 Vahagn Manasyan. All rights reserved.
//
import Foundation
class TimeStampHelper {
let formatter = DateFormatter()
func getTimeStamp() -> String {
let now = Date()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: now)
return dateString
}
func convertTimeStamp (_ timeStampString: String) -> Date? {
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let timeStamp = formatter.date(from: timeStampString)
return timeStamp
}
}
|
//
// GoingOnMatch.swift
// CuidooApp
//
// Created by Jรบlio John Tavares Ramos on 04/12/19.
// Copyright ยฉ 2019 Jรบlio John Tavares Ramos. All rights reserved.
//
import UIKit
class GoingOnMatchView: UIView, Nibable {
@IBOutlet weak var momImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var aboutLabel: UILabel!
@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var detailsTextLabel: UILabel!
@IBOutlet weak var kidsLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var remunerationLabel: UILabel!
@IBOutlet weak var topView: UIView!
@IBOutlet weak var bottomView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
loadNib()
setInformations()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadNib()
setInformations()
}
func setInformations() {
topView.roundCorners(corners: [.topLeft, .topRight], radius: 12)
bottomView.roundCorners(corners: [.bottomRight, .bottomLeft], radius: 12)
momImageView.layer.cornerRadius = momImageView.frame.height/2
}
}
|
//
// RVImageDetailViewController.swift
// RevlImageSearch
//
// Created by Michael Dautermann on 4/10/17.
// Copyright ยฉ 2017 Michael Dautermann. All rights reserved.
//
import UIKit
import SDWebImage
class RVImageDetailViewController: UIViewController {
@IBOutlet weak var imageView : UIImageView!
var imageObject : ImageObject?
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
imageView.sd_setImage(with: imageObject?.contentURL)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// MoreVariablesController.swift
// MoodIndex
//
// Created by Malik Graham on 4/29/16.
// Copyright ยฉ 2016 Malik Graham. All rights reserved.
//
import Foundation
import UIKit
class MoreVariablesController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Received from ViewController
var selectedCell: UITableViewCell?
var date: String?
var events: [String : Int] = [:]
var selectedCellImageWeather: UIImageView?
var selectedCellMoodImage: UIImageView?
var selectedCellWeatherDescription: UILabel?
var selectedCellMoodDescription: UILabel?
@IBOutlet weak var variableName: UITextField!
@IBOutlet weak var variableRating: UISlider!
@IBOutlet weak var eventTable: UITableView!
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("variableCell", forIndexPath: indexPath)
if let events = NSUserDefaults.standardUserDefaults().objectForKey(self.date!) as? NSData {
if let eventData = NSKeyedUnarchiver.unarchiveObjectWithData(events) as? Dictionary<String, Int> {
var rowLevel = 0
var labelText = ""
for index in eventData.keys {
if (rowLevel == indexPath.row) {
labelText = index
break
}
rowLevel += 1
}
if let nameOfEvent = cell.viewWithTag(100) as? UILabel {
nameOfEvent.text = labelText
}
if let ratingOfEvent = cell.viewWithTag(101) as? UILabel {
if let _: Int = eventData[labelText] {
ratingOfEvent.text = String(eventData[labelText]!)
}
else {
ratingOfEvent.text = ""
}
}
}
}
return cell
}
@IBAction func submitEvent(sender: AnyObject) {
if (variableName.text! == "") {
let alert = UIAlertController(title: "Input Error", message: "You need to type an event name to submit it.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) in
// Doing nothing here since I just want to warn users
}))
self.presentViewController(alert, animated: true, completion: nil)
return
}
else if ((variableName.text!).characters.count > 35) {
let alert = UIAlertController(title: "Input Error", message: "Your input is too long, please shorten it to submit it.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) in
// Doing nothing here since I just want to warn users
}))
self.presentViewController(alert, animated: true, completion: nil)
return
}
let nameOfEvent: String = variableName.text!
let ratingOfEvent: Int = Int(variableRating.value)
events[nameOfEvent] = ratingOfEvent
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(events), forKey: date!)
if let table = eventTable {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
table.reloadData()
})
}
}
// This code must be run in viewDidLayoutSubviews because the subviews aren't loaded in ViewDidLoad
override func viewDidLayoutSubviews() {
// A controller knows which view it is responsible for based on "self.view"
// Connection is made through listing a class with a controller
// Framing each image and label within the controller and then
// adding it as a subView
let weatherImage: UIImageView = selectedCellImageWeather!
weatherImage.frame = CGRect(x: 0, y: 64, width: 135, height: 109)
self.view.addSubview(weatherImage)
let moodImage: UIImageView = selectedCellMoodImage!
moodImage.frame = CGRect(x: 225, y: 64, width: 135, height: 109)
self.view.addSubview(moodImage)
let weatherLabel: UILabel = selectedCellWeatherDescription!
weatherLabel.frame = CGRect(x: 0, y: 166, width: 167, height: 46)
self.view.addSubview(weatherLabel)
let moodDescription: UILabel = selectedCellMoodDescription!
moodDescription.frame = CGRect(x: 208, y: 166, width: 167, height: 46)
self.view.addSubview(moodDescription)
}
// SelectedCell still has it's contents in viewDidLoad()
// Grabbing content through it's tags
override func viewDidLoad() {
super.viewDidLoad()
if let events = NSUserDefaults.standardUserDefaults().objectForKey(date!) as? NSData {
if let eventData = NSKeyedUnarchiver.unarchiveObjectWithData(events) as? Dictionary<String, Int> {
self.events = eventData
}
}
self.eventTable.delegate = self
self.eventTable.dataSource = self
// Checking to see if selectedCell has a value
if let passedCell = selectedCell {
selectedCellImageWeather = passedCell.viewWithTag(100) as? UIImageView
selectedCellWeatherDescription = passedCell.viewWithTag(101) as? UILabel
selectedCellMoodImage = passedCell.viewWithTag(102) as? UIImageView
selectedCellMoodDescription = passedCell.viewWithTag(103) as? UILabel
}
// Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// Configuration.swift
// StetsonScene
//
// Created by Madison Gipson on 5/11/20.
// Copyright ยฉ 2020 Madison Gipson. All rights reserved.
//
import Foundation
import SwiftUI
import UIKit
import Combine
var color:String = UserDefaults.standard.object(forKey: "accent") != nil ? UserDefaults.standard.string(forKey: "accent")! : "indigo"
class Configuration: ObservableObject {
let objectWillChange = PassthroughSubject<Configuration,Never>()
var eventViewModel:EventViewModel
init(_ viewModel: EventViewModel) {
self.eventViewModel = viewModel
}
//true=events | false=buildings
var appEventMode: Bool = true {
didSet {
objectWillChange.send(self)
}
}
var accent: Color = Color(UserDefaults.standard.object(forKey: "accent") != nil ? setColor(color).1 : UIColor.systemIndigo) {
didSet {
UserDefaults.standard.set(color, forKey: "accent")
objectWillChange.send(self)
}
}
var accentUIColor: UIColor = UserDefaults.standard.object(forKey: "accent") != nil ? setColor(color).1 : UIColor.systemIndigo {
didSet {
UserDefaults.standard.set(color, forKey: "accent")
objectWillChange.send(self)
}
}
}
struct Constants {
static let width = UIScreen.main.bounds.width
static let height = UIScreen.main.bounds.height
}
extension Color {
static var label: Color { return Color(UIColor.label) }
static var secondaryLabel: Color { return Color(UIColor.secondaryLabel) }
static var secondarySystemBackground: Color { return Color(UIColor.secondarySystemBackground) }
static var tertiarySystemBackground: Color { return Color(UIColor.tertiarySystemBackground) }
}
|
//
// userDefaultslabTests.swift
// userDefaultslabTests
//
// Created by Ahad Islam on 11/19/19.
// Copyright ยฉ 2019 Ahad Islam. All rights reserved.
//
import XCTest
@testable import userDefaultslab
class userDefaultslabTests: XCTestCase {
func testURL() {
let urlString = "http://sandipbgt.com/theastrologer/api/horoscope/gemini/today"
guard let url = URL(string: urlString) else {
print("Bad url")
return
}
guard let data = try? Data(contentsOf: url) else {
print("Data doesn't work.")
return
}
print(data)
XCTAssert(data != nil, "Data should exist")
}
func testURLAGAIN() {
let urlString = "http://sandipbgt.com/theastrologer/api/horoscope/gemini/today/"
var horoscope = Horoscope(sunsign: "w", credit: "w", date: "w", horoscope: "w", meta: Meta(mood: "w", keywords: "w", intensity: "w"))
let exp = XCTestExpectation(description: "Succesfully decoded object")
GenericCoderAPI.manager.getJSON(objectType: Horoscope.self, with: urlString) { (result) in
switch result {
case .failure(let error):
XCTFail("\(error)")
case .success(let horoscopeFromAPI):
horoscope = horoscopeFromAPI
exp.fulfill()
}
}
wait(for: [exp], timeout: 5)
}
func testDateFormatter() {
let dateformat = DateFormatter()
dateformat.dateFormat = "LLdd"
let number = Int(dateformat.string(from: UserDefaultsWrapper.helper.getBirthDate()!)) ?? -1
print(dateformat.string(from: UserDefaultsWrapper.helper.getBirthDate()!))
}
}
|
//
// HandlerThread.swift
//
// Created by thcomp on 2016/02/18.
// Copyright ยฉ 2016ๅนด thcomp. All rights reserved.
//
import Foundation
public class HandlerThread {
private var mOperationQueue: NSOperationQueue;
public convenience init(){
self.init(name: "", qos: NSQualityOfService.Background);
}
public convenience init(name: String, qos: NSQualityOfService){
mOperationQueue = NSOperationQueue();
mOperationQueue.name = name;
mOperationQueue.qualityOfService = qos;
}
public init(operationQueue: NSOperationQueue){
mOperationQueue = operationQueue;
}
public func getHandler() -> Handler {
return Handler(operationQueue: mOperationQueue);
}
} |
//
// BasicAuthRoutes.swift
// Application
//
// Created by Denis Bystruev on 26.12.2019.
//
import Foundation
import KituraContracts
import LoggerAPI
func initializeBasicAuthRoutes(app: App) {
app.router.get("/login/basic", handler: app.basicAuthLogin)
}
// MARK: - Basic Authentication
extension App {
func basicAuthLogin(user: BasicAuth, respondWith: ([User]?, RequestError?) -> Void) {
Log.info("User \(user.id) logged in")
let users = [User(id: 0, username: "admin", password: "admin", salt: "", isadmin: 1)]
respondWith(users, nil)
}
}
|
//
// test.swift
// MaintenanceTracker
//
// Created by Zach Pate on 5/27/20.
// Copyright ยฉ 2020 Zach Pate. All rights reserved.
//
import Foundation
//struct ContentView: View {
//
// @ObservedObject var viewRouter = ViewRouter()
// @State var showPopUp = false
// @State private var selectedTabIndex = 0
//
// var body: some View {
// TabView(selection: $selectedTabIndex) {
// Text("PAGE 1")
// .onTapGesture {
// self.selectedTabIndex = 0
// }
// .tabItem {
// Image(systemName: "list.bullet")
// Text("Records")
// }.tag(0)
//
// PlusMenu()
//// .offset(y: -geometry.size.height/6)
// .tabItem {
// Image(systemName: "plus")
// Text("Add Log")
// }.tag(1)
//
// Text("Three")
// .onTapGesture {
// self.selectedTabIndex = 2
// }
// .tabItem {
// Image(systemName: "car")
// Text("Vehicles")
// }.tag(2)
// }
// }
//
//}
// FANCY TAB VIEW
//import SwiftUI
//
//struct ContentView: View {
//
// @ObservedObject var viewRouter = ViewRouter()
//
// @State var showPopUp = false
//
// var body: some View {
// GeometryReader { geometry in
// VStack {
// Spacer()
// if self.viewRouter.currentView == "home" {
// Text("Home")
// } else if self.viewRouter.currentView == "settings" {
// Text("Settings")
// }
// Spacer()
// ZStack {
// if self.showPopUp {
// PlusMenu()
// .offset(y: -geometry.size.height/6)
// }
// HStack {
// Image(systemName: "car")
// .resizable()
// .aspectRatio(contentMode: .fit)
// .padding(20)
// .frame(width: geometry.size.width/3, height: 75)
// .foregroundColor(self.viewRouter.currentView == "home" ? .black : .gray)
// .onTapGesture {
// self.viewRouter.currentView = "home"
// }
// ZStack {
// Circle()
// .foregroundColor(Color.white)
// .frame(width: 75, height: 75)
// Image(systemName: "plus.circle.fill")
// .resizable()
// .aspectRatio(contentMode: .fit)
// .frame(width: 75, height: 75)
// .foregroundColor(.blue)
// .rotationEffect(Angle(degrees: self.showPopUp ? 90 : 0))
// }
// .offset(y: -geometry.size.height/10/2)
// .onTapGesture {
// withAnimation {
// self.showPopUp.toggle()
// }
// }
// Image(systemName: "list.bullet")
// .resizable()
// .aspectRatio(contentMode: .fit)
// .padding(20)
// .frame(width: geometry.size.width/3, height: 75)
// .foregroundColor(self.viewRouter.currentView == "settings" ? .black : .gray)
// .onTapGesture {
// self.viewRouter.currentView = "settings"
// }
// }
// .frame(width: geometry.size.width, height: geometry.size.height/10)
// .background(Color.white.shadow(radius: 2))
// }
// }.edgesIgnoringSafeArea(.bottom)
// }
// }
//}
//
//struct ContentView_Previews: PreviewProvider {
// static var previews: some View {
// ContentView()
// }
//}
//
//struct PlusMenu: View {
// var body: some View {
// HStack(spacing: 50) {
// ZStack {
// Circle()
// .foregroundColor(Color.blue)
// .frame(width: 70, height: 70)
// Image(systemName: "car")
// .resizable()
// .aspectRatio(contentMode: .fit)
// .padding(20)
// .frame(width: 70, height: 70)
// .foregroundColor(.white)
// }
// ZStack {
// Circle()
// .foregroundColor(Color.blue)
// .frame(width: 70, height: 70)
// Image(systemName: "wrench")
// .resizable()
// .aspectRatio(contentMode: .fit)
// .padding(20)
// .frame(width: 70, height: 70)
// .foregroundColor(.white)
// }
// }
// .transition(.scale)
// }
//}
//
|
//
// Home.swift
// Pokedex Plus
//
// Created by Iskierka, Julia on 29/05/2020.
// Copyright ยฉ 2020 Iskierka Lipiec. All rights reserved.
//
import SwiftUI
struct CategoryHome: View {
var items: [MenuItem] = [
MenuItem(id: 1, name: "Kanto", color: "lightblue", image: "kanto"),
MenuItem(id: 2, name: "Johto", color: "lightblue", image: "johto"),
MenuItem(id: 3, name: "Hoenn", color: "lightblue", image: "hoenn"),
MenuItem(id: 4, name: "Sinnoh", color: "lightblue", image: "sinnoh"),
MenuItem(id: 5, name: "Unova", color: "lightblue", image: "unova"),
MenuItem(id: 6, name: "Kalos", color: "lightblue", image: "kalos"),
]
var body: some View {
NavigationView {
List {
VStack(alignment: .leading) {
Text("Menu")
.font(.headline)
.padding(.leading, 15)
.padding(.top, 5)
ScrollView(.horizontal, showsIndicators: false) {
HStack {
NavigationLink(destination: PokemonList(genId: 0, genName: "Favs")) {
RoundedImageWithText(image: Image("favs"), text: "Favs", color: Color.white)
}
.buttonStyle(PlainButtonStyle())
NavigationLink(destination: Camera()) {
RoundedImageWithText(image: Image("photo"), text: "Photo", color: Color.white)
}
.buttonStyle(PlainButtonStyle())
}
}
Text("Generations")
.font(.headline)
.padding(.leading, 15)
.padding(.top, 5)
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(items) { item in
NavigationLink(destination: PokemonList(genId: item.id, genName: item.name)) {
RoundedImageWithText(image: Image(item.image), text: item.name, color: Color(item.color))
}
.buttonStyle(PlainButtonStyle())
}
}
}
.listRowInsets(EdgeInsets())
}
}
.navigationBarTitle(Text("Pokรฉdex Plus"))
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct CategoryHome_Previews: PreviewProvider {
static var previews: some View {
CategoryHome()
}
}
|
//
// LoadingView.swift
// NTGTags
//
// Created by Mena Gamal on 2/17/20.
// Copyright ยฉ 2020 Mena Gamal. All rights reserved.
//
import UIKit
public class LoadingView: UIView {
static var loadingSize: Int = 100
var imageView: UIImageView!// = UIImageView(image: UIImage(named: "loading"))
var viewFrame = UIScreen.main.bounds
static var str:String!
static let shared = LoadingView(name: str)
private init(name:String) {
super.init(frame:viewFrame)
imageView = UIImageView(image: UIImage(named: name))
self.backgroundColor = UIColor.white.withAlphaComponent(0.8)
self.isHidden = true
imageView.frame = CGRect(x: self.frame.width / 2 - CGFloat(LoadingView.loadingSize / 2), y: self.frame.height / 2 - CGFloat(LoadingView.loadingSize / 2), width: CGFloat(LoadingView.loadingSize), height: CGFloat(LoadingView.loadingSize))
addSubview(imageView)
UIApplication.shared.keyWindow?.addSubview(self)
}
private override init(frame:CGRect) {
super.init(frame: frame)
}
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func startLoading() {
isHidden = false
superview?.bringSubviewToFront(self)
imageView.startAnimating()
if !imageView.isAnimating {
let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.fromValue = 0
rotation.toValue = (2 * Double.pi)
rotation.duration = 1.5
rotation.repeatCount = Float.greatestFiniteMagnitude
imageView.layer.removeAllAnimations()
imageView.layer.add(rotation, forKey: "rotation")
}
}
public func stopLoading() {
isHidden = true
imageView.stopAnimating()
}
}
|
//
// API+DropletTests.swift
// Sealion
//
// Copyright (c) 2016 Dima Bart
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
import XCTest
import Sealion
class API_DropletTests: APITestCase {
func testDropletList() {
let handle = self.api.droplets { result in }
self.assertType(handle, type: [Droplet].self)
self.assertMethod(handle, method: .get)
self.assertBody(handle, data: nil)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .droplets)
self.assertKeyPath(handle, keyPath: "droplets")
self.assertParameters(handle, parameters: nil)
}
func testDropletListByTag() {
let tag = "production"
let handle = self.api.droplets(tag: tag) { result in }
self.assertType(handle, type: [Droplet].self)
self.assertMethod(handle, method: .get)
self.assertBody(handle, data: nil)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .droplets)
self.assertKeyPath(handle, keyPath: "droplets")
self.assertParameters(handle, parameters: ["tag_name" : tag])
}
func testDropletWithID() {
let id = 123
let handle = self.api.dropletWith(id: 123) { result in }
self.assertType(handle, type: Droplet.self)
self.assertMethod(handle, method: .get)
self.assertBody(handle, data: nil)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .dropletWithID(id))
self.assertKeyPath(handle, keyPath: "droplet")
self.assertParameters(handle, parameters: nil)
}
func testDropletCreate() {
let request = Droplet.CreateRequest(name: "test.example.com", region: "nyc3", size: "512mb", image: "ubuntu-14.04")
let handle = self.api.create(droplet: request) { result in }
self.assertType(handle, type: Droplet.self)
self.assertMethod(handle, method: .post)
self.assertBody(handle, object: request)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .droplets)
self.assertKeyPath(handle, keyPath: "droplet")
self.assertParameters(handle, parameters: nil)
}
func testDropletCreateMultiple() {
let request = Droplet.CreateRequest(names: ["test1", "test2"], region: "nyc3", size: "512mb", image: "ubuntu-14.04")
let handle = self.api.create(droplets: request) { result in }
self.assertType(handle, type: [Droplet].self)
self.assertMethod(handle, method: .post)
self.assertBody(handle, object: request)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .droplets)
self.assertKeyPath(handle, keyPath: "droplets")
self.assertParameters(handle, parameters: nil)
}
func testDropletDeleteByID() {
let id = 123
let handle = self.api.delete(droplet: id) { result in }
self.assertType(handle, type: Droplet.self)
self.assertMethod(handle, method: .delete)
self.assertBody(handle, data: nil)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .dropletWithID(id))
self.assertKeyPath(handle, keyPath: nil)
self.assertParameters(handle, parameters: nil)
}
func testDropletDeleteByTag() {
let tag = "production"
let handle = self.api.delete(droplets: tag) { result in }
self.assertType(handle, type: Droplet.self)
self.assertMethod(handle, method: .delete)
self.assertBody(handle, data: nil)
self.assertHeaders(handle)
self.assertEndpoint(handle, endpoint: .droplets)
self.assertKeyPath(handle, keyPath: nil)
self.assertParameters(handle, parameters: ["tag_name" : tag])
}
}
|
//
// ToggleReConstructionView.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 11/11/19.
// Copyright ยฉ 2019 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import SwiftUI
struct ToggleReConstructionView : View {
@State private var toggleState = false
@State private var toggleState1 = false
var body: some View {
Group {
Toggle("", isOn: $toggleState)
.toggleStyle(ColoredToggleStyle(label: "My Colored Toggle", onColor: .purple, offColor: .red, thumbColor: .white))
.padding()
Toggle("", isOn: $toggleState)
.toggleStyle(ColoredToggleStyle(label: "Second Colored Toggle", onColor: .purple))
.padding()
}
}
}
struct ColoredToggleStyle: ToggleStyle {
var label = ""
var onColor = Color.green
var offColor = Color(UIColor.systemGray5)
var thumbColor = Color.white
func makeBody(configuration: Self.Configuration) -> some View {
HStack {
Text(label)
Spacer()
Button(action: {
configuration.isOn.toggle()
} ) {
RoundedRectangle(cornerRadius: CGFloat(16.0), style: .circular)
.fill(configuration.isOn ? onColor : offColor)
.frame(width: 50, height: 29)
.overlay(Circle()
.fill(thumbColor)
.shadow(radius: 1, x:0 , y:1)
.padding(1.5) // padding all sidesof the thumb.
.offset(x: configuration.isOn ? 10: -10)) // thumn shifting between left and right.
.animation(Animation.easeInOut(duration: 0.1))
}
}
}
}
|
//
// ViewController.swift
// MyNotes
//
// Created by li on 2017/7/4.
// Copyright ยฉ 2017ๅนด li. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
let appMain = UIApplication.shared.delegate as! AppDelegate
var notes:[String] = Array()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return notes.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = notes[indexPath.row]
return cell!
}
// ้ปๆ tableView ็ cell ๅๅป็ทจ่ผฏ่จไบๆฌ
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let title = notes[indexPath.row]
let sql = "SELECT * FROM notes WHERE title = '\(title)'"
var point:OpaquePointer? = nil
if sqlite3_prepare(appMain.db, sql, -1, &point, nil) == SQLITE_OK {
print("tableView Update Select OK")
}
while sqlite3_step(point) == SQLITE_ROW {
let nid = sqlite3_column_text(point, 0)
let title = sqlite3_column_text(point, 1)
let phone = sqlite3_column_text(point, 2)
let address = sqlite3_column_text(point, 3)
let contents = sqlite3_column_text(point, 4)
let date = sqlite3_column_text(point, 5)
appMain.appnid = String(cString: nid!)
appMain.appTitle = String(cString: title!)
appMain.appPhone = String(cString: phone!)
appMain.appAddress = String(cString: address!)
appMain.appContents = String(cString: contents!)
appMain.appDate = String(cString: date!)
}
if let editPage = storyboard?.instantiateViewController(withIdentifier: "editPage"){
show(editPage, sender: self)
}
}
@IBAction func addText(_ sender: Any) {
if let textVC = self.storyboard?.instantiateViewController(withIdentifier: "editPage"){
appMain.appnid = nil
appMain.appTitle = nil
appMain.appPhone = nil
appMain.appAddress = nil
appMain.appContents = nil
appMain.appDate = nil
show(textVC, sender: self)
}
}
@IBAction func editPageLeave(for segue: UIStoryboardSegue) {
print("text leave")
appMain.appnid = nil
appMain.appTitle = nil
appMain.appPhone = nil
appMain.appAddress = nil
appMain.appContents = nil
appMain.appDate = nil
}
func showTableView() {
self.appMain.appnid = nil
self.appMain.appTitle = nil
self.appMain.appContents = nil
self.appMain.appDate = nil
let sql = "SELECT * FROM notes"
var point:OpaquePointer? = nil
if sqlite3_prepare(appMain.db, sql, -1, &point, nil) == SQLITE_OK {
print("Select OK")
}
while sqlite3_step(point) == SQLITE_ROW {
let title = sqlite3_column_text(point, 1) // ๆๆๅฎๆฌไฝ
let str = String(cString: title!)
notes += [str]
}
}
@IBAction func searchBarBtn(_ sender: Any) {
//let sqlTitle = "SELECT * FROM notes WHERE title = "
// var selectAlertField: String?
//
// let alert = UIAlertController(title: "่ซ่ผธๅ
ฅ่ฆๆๅฐ็่จไบๆจ้ก", message:
// nil, preferredStyle: UIAlertControllerStyle.alert)
//
// alert.addTextField(configurationHandler: {(textField: UITextField) -> Void in
// textField.placeholder = "่ซ่ผธๅ
ฅ่ฆๆฅ่ฉข็่จไบๆจ้ก"
// })
//
//
// alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: {(action) -> Void in
//
// print(selectAlertField!)
//
// }))
// self.present(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
// ่ฟๅๆญก่ฟ้ ๆ๏ผtableView้่ผ
override func viewWillAppear(_ animated: Bool) {
notes = [] // ้ฃๅๆธ
็ฉบ๏ผไธ็ถๆๆไธไธๆฌก่ผๅ
ฅ็้ฃๅ
self.tableView.reloadData(showTableView())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// ViewController.swift
// Series
//
// Created by Buka Cakrawala on 3/14/17.
// Copyright ยฉ 2017 Buka Cakrawala. All rights reserved.
//
import UIKit
import UPCarouselFlowLayout
import Material
let title1 = TitleSlide(label: "Title 1", image: #imageLiteral(resourceName: "william-iven-19844"))
let title2 = TitleSlide(label: "Title 2", image: #imageLiteral(resourceName: "william-iven-19843"))
let title3 = TitleSlide(label: "Title 3", image: #imageLiteral(resourceName: "data_science01"))
class ViewController: UIViewController {
@IBOutlet weak var topCollectionView: UICollectionView!
@IBOutlet weak var newCollectionView: UICollectionView!
let titles = [title1, title2, title3]
override func viewDidLoad() {
super.viewDidLoad()
//MARK: -UPCaraouselFlowLayout
let layout = UPCarouselFlowLayout()
layout.itemSize = CGSize(width: (view.bounds.width / 2) + 80, height: (view.bounds.height / 2) - 40)
layout.scrollDirection = .horizontal
topCollectionView.collectionViewLayout = layout
topCollectionView.showsHorizontalScrollIndicator = false
// Set Datasource to self
topCollectionView.dataSource = self
newCollectionView.dataSource = self
// Set Delegate to self
newCollectionView.delegate = self
topCollectionView.delegate = self
}
}
//MARK: - CollectionView Data Source
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == topCollectionView {
return titles.count
} else {
return 8
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == topCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "titleCell", for: indexPath) as! TopCollectionViewCell
cell.title = titles[indexPath.item]
cell.loveImage.image = #imageLiteral(resourceName: "heart")
cell.likeCountLabel.text = "300"
return cell
} else {
let newTopicCell = collectionView.dequeueReusableCell(withReuseIdentifier: "newTopicCell", for: indexPath) as! NewTopicCell
newTopicCell.loveImage.image = #imageLiteral(resourceName: "heart")
newTopicCell.titleLabel.text = "label"
return newTopicCell
}
}
//MARK: - Cell Sizing and Spacing
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//Set the size of each cell
if collectionView == newCollectionView {
return CGSize(width: (view.frame.width / 2) - 20, height: (view.frame.height / 8) + 52)
} else {
return CGSize(width: (view.bounds.width / 2) + 80, height: (view.bounds.height / 2) - 40)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//Set the spacing between each cell
if collectionView == newCollectionView {
return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
} else {
return UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 20)
}
}
}
|
//
// ViewController.swift
// Crime Reporting
//
// Created by Kashif Rizwan on 7/17/19.
// Copyright ยฉ 2019 Kashif Rizwan. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController,signInFill {
func fillFields(email: String, password: String) {
self.emailField.text = email
self.passwordField.text = password
}
@IBOutlet weak var emailField: textFieldDesign!
@IBOutlet weak var passwordField: textFieldDesign!
@IBOutlet weak var signBtnOut: ButtonDesign!
@IBOutlet weak var loader: UIActivityIndicatorView!
private var loginObj:loginRequest!
var hidden = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
self.loader.isHidden = true
self.loader.hidesWhenStopped = true
self.navigationItem.hidesBackButton = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.isNavigationBarHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.isNavigationBarHidden = hidden
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toSignUp"{
let signUpVc = segue.destination as! SignUpViewController
signUpVc.signUpDel = self
}
}
@IBAction func signUpBtn(_ sender: Any) {
self.performSegue(withIdentifier: "toSignUp", sender: nil)
}
@IBAction func signInBtn(_ sender: Any) {
hidden = true
self.loader.startAnimating()
self.signBtnOut.isEnabled = false
if let email = self.emailField.text, let password = self.passwordField.text{
self.loginObj = loginRequest(email: email, password: password)
self.loginObj.loginRequest(completion: {(error, isLogin) in
self.loader.stopAnimating()
self.signBtnOut.isEnabled = true
if error != nil{
let alert = UIAlertController(title: "Error", message: error, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "Success", message: "You are logged into your account.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(_) in
// setting the login status to true
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()
RouteManager.shared.showHome()
}))
self.present(alert, animated: true, completion: nil)
let userActivityObj = user_activity()
userActivityObj.isUserActive(isActive: true, completion: {(error) in
if let err = error{
print(err)
}
})
}
})
}else{
let alert = UIAlertController(title: "Alert", message: "Please fill all fields", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright ยฉ 2018 Daniel Heredia. All rights reserved.
//
// Triple Step
import Foundation
func calculateWays(n: Int, memo: inout [Int]) -> Int {
if n < 0 {
return 0
}
if memo[n] == -1 {
if n == 0 {
memo[n] = 1
} else {
memo[n] = calculateWays(n: n - 3, memo: &memo) +
calculateWays(n: n - 2, memo: &memo) +
calculateWays(n: n - 1, memo: &memo)
}
}
return memo[n]
}
func calculateAllPossibleWays(staircase: Int) -> Int? {
if staircase <= 0 {
return nil
} else {
var memo = [Int](repeating: -1, count: staircase + 1)
return calculateWays(n: staircase, memo: &memo)
}
}
let n = 20
if let ways = calculateAllPossibleWays(staircase: n) {
print("Number of ways to run up the stairs (\(n)): \(ways)")
} else {
print("Invalid input: \(n)")
}
|
//
// Video.swift
// App04-TMDB
//
// Created by David Cantรบ Delgado on 28/10/21.
//
import SwiftUI
struct Video: Identifiable {
var id: Int
var name: String
var key: String
var site: String
var type: String
}
extension Video {
static let dummy = Video(id: 01, name: "Free Guy", key: "jRn48HxssPI", site: "YouTube", type: "Clip")
}
|
//
// ViewController.swift
// Animations
//
// Created by admin on 06/01/20.
// Copyright ยฉ 2020 Nihilent. All rights reserved.
//
import UIKit
final class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "iOS Animations"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func animateWithDurationAction(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let animationVC = storyboard.instantiateViewController(withIdentifier: "animatewithduration") as! AnimateWithDurationViewController
animationVC.title = (sender as! UIButton).titleLabel?.text
self.navigationController?.pushViewController(animationVC, animated: true)
}
@IBAction func transitionsAction(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let transitionVC = storyboard.instantiateViewController(withIdentifier: "transitions") as! TransitionsViewController
transitionVC.title = (sender as! UIButton).titleLabel?.text
self.navigationController?.pushViewController(transitionVC, animated:true)
}
@IBAction func transformButtonAction(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let transitionVC = storyboard.instantiateViewController(withIdentifier: "transforms") as! TransformViewController
transitionVC.title = (sender as! UIButton).titleLabel?.text
self.navigationController?.pushViewController(transitionVC, animated:true)
}
}
|
//
// Task.swift
// TeamworkTest
//
// Created by Oscar Alvarez on 30/7/17.
// Copyright ยฉ 2017 Oscar Alvarez. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Task {
var content: String
var responsablePartySummary: String
var userFollowingChanges: Bool
var startDate: Date?
var dueDate: Date?
var priority: String
init(with data: Dictionary <String, AnyObject>) {
let json = JSON(jsonObject: data)
content = json[TaskKey.content].stringValue
responsablePartySummary = json[TaskKey.responsibleSum].stringValue
priority = json[TaskKey.priority].stringValue
userFollowingChanges = json[TaskKey.following].boolValue
startDate = Date.from(string: json[TaskKey.startDate].stringValue)
dueDate = Date.from(string: json[TaskKey.dueDate].stringValue)
}
}
|
//
// NewAlarmViewController.swift
// MidtermApp
//
// Created by User on 12.03.2021.
// Copyright ยฉ 2021 User. All rights reserved.
//
import UIKit
protocol SaveDelegate{
func saveAlarm(_ alarm: Alarm?)
}
class NewAlarmViewController: UIViewController {
@IBOutlet weak var descrText: UITextView!
@IBOutlet weak var timePicker: UIDatePicker!
var saveDelegate: SaveDelegate?
var alarm: Alarm?
var timeText: String?
override func viewDidLoad() {
super.viewDidLoad()
formatter.dateFormat = "HH:mm"
timeText = "12:00"
timePicker.datePickerMode = .time
timePicker.locale = Locale(identifier: "ru_KZ")
timePicker.date = formatter.date(from: (timeText)!)!
timePicker.addTarget(self, action: #selector(timePickerValueChanged(sender:)), for: UIControl.Event.valueChanged)
alarm = Alarm(timeText, "Default", true)
}
@objc func timePickerValueChanged(sender: UIDatePicker){
timeText = formatter.string(from: sender.date)
}
@IBAction func saveAlarm(_ sender: Any) {
alarm = Alarm(timeText, descrText.text, true)
saveDelegate?.saveAlarm(alarm!)
navigationController?.popViewController(animated: true)
}
}
|
import Quick
import Nimble
import AVKit
import AVFoundation
@testable import BestPractices
class PlayerSpec: QuickSpec {
override func spec() {
var subject: Player!
var engineBuilder: MockEngineBuilder!
var shiftTranslator: MockShiftTranslator!
var audioBox: MockAudioBox!
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: "maneater", ofType: "mp3")!
let sampleFileURL = URL(fileURLWithPath: path)
let audioFile = try! AVAudioFile.init(forReading: sampleFileURL)
beforeEach {
subject = Player()
engineBuilder = MockEngineBuilder()
subject.engineBuilder = engineBuilder
shiftTranslator = MockShiftTranslator()
subject.shiftTranslator = shiftTranslator
audioBox = MockAudioBox(file: audioFile, engine: MockAVAudioEngine(), player: MockAVAudioPlayerNode(), pitchShift: AVAudioUnitVarispeed(), delays: [], reverb: AVAudioUnitReverb(), eq: AVAudioUnitEQ())
}
describe(".loadSound") {
it("does not initialize an audio box until we have a sound file") {
expect(subject.audioBox).to(beNil())
}
context("With a good URL") {
beforeEach {
engineBuilder.returnAudioBoxValueForBuildEngine = audioBox
}
context("When the engine throws an exception") {
beforeEach {
audioBox.startShouldThrow = true
subject.loadSound(filePath: path)
}
it("calls the engine builder") {
expect(engineBuilder.calledBuildEngine).to(beTruthy())
expect(engineBuilder.capturedAudioFile!.url).to(equal(sampleFileURL))
}
it("starts the audio box") {
expect(audioBox.calledStart).to(beTruthy())
}
it("does not store the audio box") {
expect(subject.audioBox).to(beNil())
}
}
context("When the engine starts successfully") {
beforeEach {
audioBox.startShouldThrow = false
subject.loadSound(filePath: path)
}
it("calls the engine builder") {
expect(engineBuilder.calledBuildEngine).to(beTruthy())
expect(engineBuilder.capturedAudioFile!.url).to(equal(sampleFileURL))
}
it("starts the audio box") {
expect(audioBox.calledStart).to(beTruthy())
}
it("stores the audio box") {
expect(subject.audioBox).toNot(beNil())
expect(subject.audioBox).to(beIdenticalTo(audioBox))
}
}
}
context("With a bad URL") {
beforeEach {
subject.loadSound(filePath: "")
}
it("does not store the audio box") {
expect(subject.audioBox).to(beNil())
}
}
}
describe(".clearSound") {
context("When a sound has been loaded") {
beforeEach {
subject.audioBox = audioBox
subject.clearSound()
}
it("stops playing any sound") {
expect(audioBox.calledStop).to(beTruthy())
}
it("wipes out all references to engine components") {
expect(subject.audioBox).to(beNil())
}
}
context("When a sound has not been loaded") {
beforeEach {
subject.audioBox = nil
}
it("does not raise an exception") {
expect(subject.clearSound()).toNot(throwError())
}
}
}
describe(".play") {
context("When a sound has been loaded") {
beforeEach {
subject.audioBox = audioBox
}
context("With delay") {
context("With reverb") {
beforeEach {
subject.play(delay: true, reverb: true)
}
it("plays the audio box with delay") {
expect(audioBox.calledPlay).to(beTruthy())
expect(audioBox.capturedDelay).to(beTruthy())
expect(audioBox.capturedReverb).to(beTruthy())
}
}
context("Without reverb") {
beforeEach {
subject.play(delay: true, reverb: false)
}
it("plays the audio box with delay") {
expect(audioBox.calledPlay).to(beTruthy())
expect(audioBox.capturedDelay).to(beTruthy())
expect(audioBox.capturedReverb).to(beFalsy())
}
}
}
context("Without delay") {
context("With reverb") {
beforeEach {
subject.play(delay: false, reverb: true)
}
it("plays the audio box with delay") {
expect(audioBox.calledPlay).to(beTruthy())
expect(audioBox.capturedDelay).to(beFalsy())
expect(audioBox.capturedReverb).to(beTruthy())
}
}
context("Without reverb") {
beforeEach {
subject.play(delay: false, reverb: false)
}
it("plays the audio box with delay") {
expect(audioBox.calledPlay).to(beTruthy())
expect(audioBox.capturedDelay).to(beFalsy())
expect(audioBox.capturedReverb).to(beFalsy())
}
}
}
}
context("When a sound has not been loaded") {
beforeEach {
subject.audioBox = nil
}
it("does not raise an exception") {
expect(subject.play(delay: true, reverb: true)).toNot(throwError())
}
}
}
describe(".pitchShift") {
context("When a sound has been loaded") {
beforeEach {
subject.audioBox = audioBox
subject.clearSound()
}
it("stops playing any sound") {
expect(audioBox.calledStop).to(beTruthy())
}
it("wipes out all references to engine components") {
expect(subject.audioBox).to(beNil())
}
}
context("When a sound has not been loaded") {
beforeEach {
subject.audioBox = nil
}
it("does not raise an exception") {
expect(subject.clearSound()).toNot(throwError())
}
}
}
describe(".pitchShift") {
context("When a sound is loaded") {
beforeEach {
subject.audioBox = audioBox
shiftTranslator.returnValueForTranslation = 3.5
subject.pitchShift(amount: 1.2)
}
it("calls the shift translator") {
expect(shiftTranslator.calledTranslate).to(beTruthy())
expect(shiftTranslator.capturedInputValue).to(equal(1.2))
}
it("sets the shift node to the translated value") {
expect(audioBox.calledPitchShift).to(beTruthy())
expect(audioBox.capturedPitchShiftAmount).to(equal(3.5))
}
}
context("When a sound is not loaded") {
beforeEach {
subject.audioBox = nil
subject.pitchShift(amount: 1.2)
}
it("does not call the shift translator") {
expect(shiftTranslator.calledTranslate).to(beFalsy())
}
}
}
}
}
|
//
// Copyright ยฉ 2018 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
/// List of possible general Bluetooth failures.
public enum BluetoothError: Error {
case bluetoothUnavailable
case incompatibleDevice
case unauthorized
}
/// List of possible errors during advertisement.
public enum AdvertisementError: Error {
case bluetoothError(BluetoothError)
case deviceNotAdvertising
case incorrectUpdateData
case otherError(Error)
}
/// List of possible errors during connection.
public enum ConnectionError: Error {
case bluetoothError(BluetoothError)
case deviceConnectionLimitExceed
case deviceAlreadyConnected
}
|
//
// ViewController.swift
// Lecture20Project
//
// Created by Egor Lass on 11.06.2021.
//
import UIKit
import MyFramework
class ViewController: UIViewController {
let myClass = MyClass()
override func viewDidLoad() {
super.viewDidLoad()
print("This framework was made by \(myClass.name)")
myClass.sayHello()
}
}
|
import UIKit
import ThemeKit
class DerivationSettingsRouter {
weak var viewController: UIViewController?
}
extension DerivationSettingsRouter: IDerivationSettingsRouter {
func showChangeConfirmation(coinTitle: String, setting: DerivationSetting, delegate: IDerivationSettingConfirmationDelegate) {
let module = DerivationSettingConfirmationRouter.module(coinTitle: coinTitle, setting: setting, delegate: delegate)
viewController?.present(module, animated: true)
}
}
extension DerivationSettingsRouter {
static func module() -> UIViewController {
let router = DerivationSettingsRouter()
let interactor = DerivationSettingsInteractor(derivationSettingsManager: App.shared.derivationSettingsManager, walletManager: App.shared.walletManager)
let presenter = DerivationSettingsPresenter(router: router, interactor: interactor)
let viewController = DerivationSettingsViewController(delegate: presenter)
presenter.view = viewController
router.viewController = viewController
return viewController
}
}
|
//
// ViewController.swift
// TestCView
//
// Created by nathan on 2019/5/10.
// Copyright ยฉ 2019 nathan. All rights reserved.
//
import UIKit
import BTCaptchaView
class ViewController: UIViewController {
@IBOutlet weak var codeView: BTCaptchaView! {
didSet{
codeView.code = "123"
}
}
lazy var codeView1: BTCaptchaView = {
let view = BTCaptchaView.init()
view.font = UIFont.systemFont(ofSize: 30)
view.interferenceLineCount = 20
view.interferenceLineWidth = 10
view.code = "1234"
view.frame = CGRect.init(x: 0, y: 50, width: 100, height: 50)
view.onTouch = {
print("touch")
}
return view
}()
lazy var codeView2: BTCaptchaView = {
let view = BTCaptchaView.init(frame: CGRect.init(x: 0, y: 150, width: 100, height: 50), code: "12345")
view.font = UIFont.systemFont(ofSize: 30)
view.onTouch = {
print("touch")
}
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(codeView1)
view.addSubview(codeView2)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
codeView.code = "321"
codeView1.code = "4321"
codeView2.code = "54321"
}
}
|
//
// ItemSelectorVC.swift
// ItemSelector
//
// Created by Amzad Khan on 19/10/19.
// Copyright ยฉ 2019 Amzad Khan. All rights reserved.
//
import UIKit
extension Selectable {
var subtitle:String? { return nil }
var avatarURL:String? { return nil }
var image:UIImage? { return nil }
}
protocol Selectable {
var id:String { get }
var title:String { get }
var subtitle:String? { get }
var avatarURL:String? { get }
var image:UIImage? { get }
}
//selectionScrollView
class ItemSelectorVC: UIViewController {
let kBatchSize:Int = 20
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar:UISearchBar!
@IBOutlet var selectionScrollView: UICollectionView!
var pageNo:Int = 0
var searchString = ""
var items = [SearchUser]()
var selectedItems = [Selectable]()
@objc var selectedIds:[String] {
let ids = selectedItems.map { return $0.id }
return ids
}
lazy var cellRemoveTap:UserCollectionCell.CellTapHandler? = { (cell) in
guard let indexPath = self.selectionScrollView.indexPath(for: cell) else {return}
//remove item
self.reloadAndPositionScroll(selectItem: self.selectedItems[indexPath.row], remove: true)
if self.selectedItems.count <= 0 {
//Comunicate deselection to delegate
self.toggleSelectionScrollView(show: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.navigationBar.tintColor = UIColor.orange
configureTableView()
configureUI()
}
func configureUI() {
self.title = "Multi Selection"
let rightBtn = self.postButton(title: "Done")
self.navigationItem.rightBarButtonItem = rightBtn
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
func reloadData() {
//self.apiGetContacts(searchString: searchString)
self.tableView.reloadData()
}
}
// MARK : - TableviewDatasource
extension ItemSelectorVC : UITableViewDataSource {
@objc fileprivate func postButton(title:String) -> UIBarButtonItem {
let infoButton = UIButton(type: .custom)
infoButton.frame = CGRect(x: 0, y: 0, width: 50, height: 22)
infoButton.setTitle(title, for: .normal)
infoButton.tintColor = UIColor.orange
infoButton.setTitleColor(UIColor.orange, for: .normal)
infoButton.addTarget(self, action: #selector(self.didTapPost), for: .touchUpInside)
let btn = UIBarButtonItem(customView: infoButton)
btn.tintColor = UIColor.orange
return btn
}
@objc fileprivate func didTapPost() {
//self.forwardMessage()
}
func configureTableView() {
self.tableView.tableFooterView = UIView()
searchBar.placeholder = "Search items..."
toggleSelectionScrollView(show: false)
// self.apiGetContacts(searchString: searchString)
}
func numberOfSections(in tableView: UITableView) -> Int {
return self.items.count > 0 ? 1 : 0
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let returnValue = self.items.count
return returnValue
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserSearchCell", for: indexPath) as! UserSearchCell
var item:SearchUser! = self.items[indexPath.row]
self.configureCell(cell: cell, user:item )
if self.selectedItems.contains(where: { (itm) -> Bool in
itm.id == item.id
}) {
//item.color = cell.initials.backgroundColor!
cell.accessoryType = UITableViewCell.AccessoryType.checkmark
}else {
cell.accessoryType = UITableViewCell.AccessoryType.none
}
return cell
}
func configureCell(cell:UserSearchCell, user:SearchUser) {
cell.nameLabel.text = user.name
cell.avatarView.image = user.image
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.section == 0 ? 65 : 65//UITableViewAutomaticDimension
}
}
// MARK : - TableviewDelegate
extension ItemSelectorVC : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
let cell = tableView.cellForRow(at: indexPath) as! UserSearchCell
var item:Selectable = self.items[indexPath.row]
//Multi user selection
//Save item data
//item.color = cell.initials.backgroundColor!
//Check if cell is already selected or not
if cell.accessoryType == UITableViewCell.AccessoryType.checkmark {
//Set accessory type
cell.accessoryType = UITableViewCell.AccessoryType.none
//Comunicate deselection to delegate
//SwiftMultiSelect.delegate?.swiftMultiSelect(didUnselectItem: item)
//Reload collectionview
self.reloadAndPositionScroll(selectItem: item, remove:true)
}
else{
//Set accessory type
cell.accessoryType = UITableViewCell.AccessoryType.checkmark
//Add current item to selected
selectedItems.append(item)
//Comunicate selection to delegate
//SwiftMultiSelect.delegate?.swiftMultiSelect(didSelectItem: item)
//Reload collectionview
self.reloadAndPositionScroll(selectItem: item, remove:false)
}
//Reset search
if searchString != ""{
searchBar.text = ""
searchString = ""
//SwiftMultiSelect.delegate?.userDidSearch(searchString: "")
self.tableView.reloadData()
}
//[self shareSendSwift:message.content];
}
/*
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
}else if indexPath.section == 1 {
if selectedTab == .contacts {
searchUsers[indexPath.row].isSelected = false
}else {
searchGroups[indexPath.row].isSelected = false
}
}
}*/
}
extension ItemSelectorVC: UISearchBarDelegate {
// MARK: - UISearchBarDelegate
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.searchString = searchText
pageNo = 0
// Get items from for search keyword
//self.apiGetContacts(searchString: searchText)
if (searchText.isEmpty) {
self.perform(#selector(self.hideKeyboardWithSearchBar(_:)), with: searchBar, afterDelay: 0)
self.searchString = ""
}
//API Search
self.tableView.reloadData()
}
@objc func hideKeyboardWithSearchBar(_ searchBar:UISearchBar){
searchBar.resignFirstResponder()
}
public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool{
return true
}
}
extension ItemSelectorVC {
@objc class func instantiate() ->ItemSelectorVC {
let storyboard = UIStoryboard(name:"ItemSelection", bundle: Bundle.main)
return storyboard.instantiateViewController(withIdentifier: "ItemSelectorVC") as! ItemSelectorVC
}
@objc public func show(to: UIViewController) {
// Create instance of selector
self.modalPresentationStyle = .overFullScreen
self.modalTransitionStyle = .crossDissolve
//Create navigation controller
let navController = UINavigationController(rootViewController: self)
// Present selectora
to.present(navController, animated: true, completion: nil)
}
@objc public class func show(to: UIViewController) -> ItemSelectorVC {
// Create instance of selector
let vc = ItemSelectorVC.instantiate()
vc.show(to: to)
return vc
}
}
extension ItemSelectorVC:UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.selectedItems.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserCollectionCell", for: indexPath as IndexPath) as! UserCollectionCell
//Try to get item from delegate
let item = self.selectedItems[indexPath.row]
//Add target for the button
cell.nameLabel.text = item.title
cell.avatarView.isHidden = false
cell.didTapRemove = self.cellRemoveTap
cell.avatarView.image = item.image
//cell.delegate = self
//Test if items it's CNContact
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: CGFloat(80),height: CGFloat(80))
}
/// Remove item from collectionview and reset tag for button
///
/// - Parameter index: id to remove
func removeItemAndReload(index:Int){
//if no selection reload all
if selectedItems.count == 0{
self.selectionScrollView.reloadData()
}else{
//reload current
self.selectionScrollView.deleteItems(at: [IndexPath(item: index, section: 0)])
}
}
/// Reaload collectionview data and scroll to last position
///
/// - Parameters:
/// - idp: is the tableview position index
/// - remove: true if you have to remove item
func reloadAndPositionScroll(selectItem:Selectable, remove:Bool){
//Identify the item inside selected array
let item = selectedItems.filter { (itm) -> Bool in
itm.id == selectItem.id
}.first
//Remove
if remove {
//For remove from collection view and create IndexPath, i need the index posistion in the array
let id = selectedItems.index { (itm) -> Bool in
return itm.id == selectItem.id
}
//Filter array removing the item
selectedItems = selectedItems.filter({ (itm) -> Bool in
return selectItem.id != itm.id
})
//Reload collectionview
if id != nil{
removeItemAndReload(index: id!)
}
//SwiftMultiSelect.delegate?.swiftMultiSelect(didUnselectItem: item!)
//Reload cell state
reloadCellState(selectItem:selectItem , selected: false)
if selectedItems.count <= 0{
//Toggle scrollview
toggleSelectionScrollView(show: false)
}
//Add
}else{
toggleSelectionScrollView(show: true)
//Reload data
self.selectionScrollView.insertItems(at: [IndexPath(item: selectedItems.count-1, section: 0)])
let lastItemIndex = IndexPath(item: self.selectedItems.count-1, section: 0)
//Scroll to selected item
self.selectionScrollView.scrollToItem(at: lastItemIndex, at: .right, animated: true)
reloadCellState(selectItem: self.selectedItems.last!, selected: true)
}
}
}
extension ItemSelectorVC {
/// Toggle de selection view
///
/// - Parameter show: true show scroller, false hide the scroller
func toggleSelectionScrollView(show:Bool) {
UIView.animate(withDuration: 0.2, animations: {
self.selectionScrollView.isHidden = !show
})
}
func reloadCellState(selectItem:Selectable, selected:Bool) {
//get item index from datasource
guard let indexpaths = self.tableView.indexPathsForVisibleRows else { return }
self.tableView.beginUpdates()
self.tableView.reloadRows(at: indexpaths, with: UITableView.RowAnimation.none)
self.tableView.endUpdates()
}
}
|
//
// InterfaceController.swift
// SocialWatch WatchKit Extension
//
// Created by Francisco Caro Diaz on 10/03/15.
// Copyright (c) 2015 AreQua. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet weak var tableView: WKInterfaceTable!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
NSFileCoordinator.addFilePresenter(self)
fetchTodoItems()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: Helper method
private func setupTable() {
var rowTypesList = [String]()
for friend in _friendsData {
var typeFound = false
let friendImage = friend.friendImageName
if strlen(friendImage) > 0 {
rowTypesList.append("FriendWithImageRow")
typeFound = true
}
if typeFound == false {
rowTypesList.append("OrdinaryFriendRow")
}
}
tableView.setRowTypes(rowTypesList)
for var i = 0; i < tableView.numberOfRows; i++ {
let row: AnyObject? = tableView.rowControllerAtIndex(i)
let friend = _friendsData[i]
if row is FriendWithImageRow {
let importantRow = row as FriendWithImageRow
let url = NSURL(string: friend.friendImageName);
let picData = NSData(contentsOfURL: url!);
let img = UIImage(data: picData!);
importantRow.friendImage.setImage(img)
importantRow.titleLabel.setText(friend.friendTitle)
importantRow.subTitleLabel.setText(friend.friendSubtitle)
} else {
let ordinaryRow = row as OrdinaryFriendRow
ordinaryRow.titleLabel.setText(friend.friendTitle)
ordinaryRow.subtitleLabel.setText(friend.friendSubtitle)
}
}
}
// MARK: Populate Table From File Coordinator
var friendsList :NSArray = []
var _friendsData:[Friend] = []
private func fetchTodoItems() {
let fileCoordinator = NSFileCoordinator()
if let presentedItemURL = presentedItemURL {
fileCoordinator.coordinateReadingItemAtURL(presentedItemURL, options: nil, error: nil)
{ [unowned self] (newURL) -> Void in
if let savedData = NSData(contentsOfURL: newURL) {
self.friendsList = NSKeyedUnarchiver.unarchiveObjectWithData(savedData) as [NSArray]
self._friendsData = Friend.friendList(self.friendsList)
self.setupTable()
}
}
}
}
}
// MARK: NSFilePresenter Protocol
extension InterfaceController: NSFilePresenter {
var presentedItemURL: NSURL? {
let groupURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(
"group.arequa.socialwatch")
let fileURL = groupURL?.URLByAppendingPathComponent("friendsList.bin")
return fileURL
}
var presentedItemOperationQueue: NSOperationQueue {
return NSOperationQueue.mainQueue()
}
func presentedItemDidChange() {
fetchTodoItems()
}
}
|
//
// BusinessesViewCell.swift
// Fixee
//
// Created by Haydn Joel Gately on 31/03/2017.
// Copyright ยฉ 2017 Fixee. All rights reserved.
//
import UIKit
class BusinessesViewCell: UITableViewCell {
//this custom cell is to to load the businesses in the diectory
@IBOutlet weak var businessImage: UIImageView!
@IBOutlet weak var businessNameLabel: UILabel!
@IBOutlet weak var businessCategoryLabel: UILabel!
@IBOutlet weak var businessRatingLabel: UILabel!
@IBOutlet weak var businessDistanceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
import UIKit
import Down
import libcmark
protocol MarkdownBlock: CustomStringConvertible {}
class MarkdownVisitor {
private let attributedStringVisitor: AttributedStringVisitor
private let styler: Styler
init(attributedStringVisitor: AttributedStringVisitor, styler: Styler) {
self.attributedStringVisitor = attributedStringVisitor
self.styler = styler
}
}
extension MarkdownVisitor: Visitor {
public typealias Result = MarkdownBlock
public func visit(document node: Document) -> MarkdownBlock {
DocumentBlock(blocks: visitChildren(of: node))
}
public func visit(blockQuote node: BlockQuote) -> MarkdownBlock {
BlockQuoteBlock(blocks: visitChildren(of: node))
}
public func visit(list node: List) -> MarkdownBlock {
var startOrder: Int?
if case .ordered(let start) = node.listType {
startOrder = start
}
return ListBlock(blocks: visitChildren(of: node), tight: node.isTight, startOrder: startOrder)
}
public func visit(item node: Item) -> MarkdownBlock {
ItemBlock(blocks: visitChildren(of: node))
}
public func visit(codeBlock node: CodeBlock) -> MarkdownBlock {
UnhandledBlock(type: "CodeBlock")
}
public func visit(htmlBlock node: HtmlBlock) -> MarkdownBlock {
UnhandledBlock(type: "HtmlBlock")
}
public func visit(customBlock node: CustomBlock) -> MarkdownBlock {
UnhandledBlock(type: "CustomBlock")
}
public func visit(paragraph node: Paragraph) -> MarkdownBlock {
// handle paragraph with single image
if node.children.count == 1, let image = node.children.first as? Image {
return visit(image: image)
}
let s = attributedStringVisitor.visitChildren(of: node).joined
styler.style(paragraph: s)
return ParagraphBlock(attributedString: s)
}
public func visit(heading node: Heading) -> MarkdownBlock {
let s = attributedStringVisitor.visitChildren(of: node).joined
styler.style(heading: s, level: node.headingLevel)
return HeadingBlock(attributedString: s, level: node.headingLevel)
}
public func visit(thematicBreak node: ThematicBreak) -> MarkdownBlock {
UnhandledBlock(type: "ThematicBreak")
}
public func visit(text node: Text) -> MarkdownBlock {
UnhandledBlock(type: "Text")
}
public func visit(softBreak node: SoftBreak) -> MarkdownBlock {
UnhandledBlock(type: "SoftBreak")
}
public func visit(lineBreak node: LineBreak) -> MarkdownBlock {
UnhandledBlock(type: "LineBreak")
}
public func visit(code node: Code) -> MarkdownBlock {
UnhandledBlock(type: "Code")
}
public func visit(htmlInline node: HtmlInline) -> MarkdownBlock {
UnhandledBlock(type: "HtmlInline")
}
public func visit(customInline node: CustomInline) -> MarkdownBlock {
UnhandledBlock(type: "CustomInline")
}
public func visit(emphasis node: Emphasis) -> MarkdownBlock {
UnhandledBlock(type: "Emphasis")
}
public func visit(strong node: Strong) -> MarkdownBlock {
UnhandledBlock(type: "Strong")
}
public func visit(link node: Link) -> MarkdownBlock {
UnhandledBlock(type: "Link")
}
public func visit(image node: Image) -> MarkdownBlock {
ImageBlock(title: node.title, url: node.url)
}
}
extension MarkdownVisitor {
struct DocumentBlock: MarkdownBlock {
let blocks: [MarkdownBlock]
var description: String {
"DocumentBlock: \(blocks.count) blocks:\n\(blocks.map { "\($0)" }.joined(separator: "\n"))\n\n"
}
}
struct HeadingBlock: MarkdownBlock {
let attributedString: NSAttributedString
let level: Int
var description: String {
"Heading Block: level: \(level): \(attributedString.string)"
}
}
struct ParagraphBlock: MarkdownBlock {
let attributedString: NSAttributedString
var description: String {
"Paragraph Block: \(attributedString.string)"
}
}
struct ImageBlock: MarkdownBlock {
let title: String?
let url: String?
var description: String {
"Image Block: title: \(title ?? "nil"), url: \(url ?? "nil")"
}
}
struct ListBlock: MarkdownBlock {
let blocks: [MarkdownBlock]
let tight: Bool
var startOrder: Int?
var itemBlocks: [ItemBlock] {
blocks.compactMap { $0 as? ItemBlock }
}
var description: String {
"List Block: [tight=\(tight), startOrder=\(startOrder.map { "\($0)" } ?? "nil")] \(blocks.count) blocks:\n\(blocks.map { "\($0)" }.joined(separator: "\n"))\n\n"
}
}
struct ItemBlock: MarkdownBlock {
let blocks: [MarkdownBlock]
var paragraphBlocks: [ParagraphBlock] {
blocks.compactMap { $0 as? ParagraphBlock }
}
var description: String {
"Item Block: \(blocks.count) block(s)"
}
}
struct BlockQuoteBlock: MarkdownBlock {
let blocks: [MarkdownBlock]
var paragraphBlocks: [ParagraphBlock] {
blocks.compactMap { $0 as? ParagraphBlock }
}
var description: String {
"BlockQuote Block: \(blocks.count) block(s)"
}
}
struct UnhandledBlock: MarkdownBlock {
let type: String
var description: String {
"Unhandled Block: \(type)"
}
}
}
private extension Sequence where Iterator.Element == NSMutableAttributedString {
var joined: NSMutableAttributedString {
reduce(into: NSMutableAttributedString()) { $0.append($1) }
}
}
|
//
// AboutPageJson.swift
// GWDrawEngine
//
// Created by CQ on 2020/6/28.
// Copyright ยฉ 2020 Chen. All rights reserved.
//
import Foundation
let HelpPageJson: [String: Any] = [
"viewType": "StackView",
"property": ["axis":"vertical", "distribution": "fill", "alignment": "fill", "space": 0, "height":-1, "width": -1, "margin":[0, 0, 0, 0], "color": "#0C0E13"],
"templates": [
"templates_1": ["viewType": "View",
"property": ["height":-1,"margin":[0, 0, 0, 0], "backgroundColor": "#20222E", "action": ["name": "showPage", "params": ["pageId": "0"]], "expressionSetters": ["action": "params"]],
// actionParams ไธบ้่ฆๅๆฐๅฏนๅบ็ state ่็น็ถๆ ้ไธญใๆช้ไธญใ้่
"subViews": [
[
"viewType": "StackView",
"property": ["axis":"horizontal", "distribution": "fill", "alignment": "center", "space": 10, "margin":[10, 10, 16, 16]],
"subViews": [
["viewType": "ImageView",
"property":["height": 60,"width": 60, "id": "1",
"content": "icon_myhome_qiye.png", "expressionSetters": ["content": "headerIcon", "height": "height", "width": "width"]]],
["viewType": "Text",
"property":["size": 16, "alignment": "left", "color": "#ffffff", "height": 20, "content":"ๆ็่ถ
็บงไผไธ", "id": "2", "expressionSetters": ["content": "name", "isBold": "isBold"]]],
["viewType": "Text",
"property":["size": 16, "alignment": "left", "color": "#ffffff", "height": 20, "content":"3", "id": "3", "expressionSetters": ["content": "subTitle", "size": "minSize"]]],
["viewType": "ImageView",
"property":["size": 16, "alignment": "left", "color": "#97A0B4", "height": 24,"width": 24, "id": "4", "content": "iocn_my_home_back.png"]]
]
]
]
]
],
"subViews": [
// header
["viewType": "View",
"subViews": [
["viewType": "Text",
"property":["size": 26, "isBold": 1, "alignment": "left", "color": "#ffffff", "height": 60, "content":" ๆ็", "margin":[0, 0, 10, 10], "id": "10", "expressionSetters": ["content": "header.title"]]]
]
],
// body
[
"viewType": "TableView",
"property": ["style": "group", "color": "#0C0E13", "separatorColor": "#333333", "separatorStyle": "singleLine"],
"subViews": [
]
],
// bootom
[
"viewType": "View",
"property": ["height":44],
"subViews": [
["viewType": "StackView",
"property": ["axis":"horizontal", "distribution": "equalSpacing", "alignment": "center", "space": 0, "margin":[0, 0, 10, 10], "width": -1],
"subViews": [
["viewType": "ImageView",
"property":["size": 13, "alignment": "center", "color": "#ffffff", "height": 20, "width": 40, "content":"arrow_left.png", "id": "12", "action": ["name": "pop", "params": ["key": "value"]]],
],
["viewType": "Button",
"property":["size": 16, "alignment": "center", "color": "#FF5454", "height": 20, "width": 40, "content":"", "id": "13"]]
]
]
]
]
]
]
let HelpPageDataSource2: [String : Any] = [
"header": ["title": "ๅธฎๅฉ"],
"sections": [
["header": "", "list": [
["headerIcon":"bz_rgfw_icon.png","name": "ไบบๅทฅๅฎขๆ", "subTitle": "", "4": "iocn_my_home_back.png", "params":["pageId": "1"], "identifier": "templates_1"],
["headerIcon":"bz_appjc_icon.png", "name": "APPๆฃๆต", "subTitle": "", "4": "iocn_my_home_back.png", "identifier": "templates_1"],
["headerIcon":"bz_appjc_icon.png", "name": "็จๆทๆๅ", "subTitle": "", "4": "iocn_my_home_back.png", "identifier": "templates_1"]
] ]
]
]
|
// UIStoryboardExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit) && !os(watchOS)
import UIKit
// MARK: - Methods
public extension UIStoryboard {
/// SwifterSwift: Get main storyboard for application.
static var main: UIStoryboard? {
let bundle = Bundle.main
guard let name = bundle.object(forInfoDictionaryKey: "UIMainStoryboardFile") as? String else { return nil }
return UIStoryboard(name: name, bundle: bundle)
}
/// SwifterSwift: Instantiate a UIViewController using its class name.
///
/// - Parameter name: UIViewController type.
/// - Returns: The view controller corresponding to specified class name.
func instantiateViewController<T: UIViewController>(withClass name: T.Type) -> T? {
return instantiateViewController(withIdentifier: String(describing: name)) as? T
}
}
#endif
|
//
// StarMarkView.swift
// someDemo
//
// Created by wanwu on 2017/5/24.
// Copyright ยฉ 2017ๅนด wanwu. All rights reserved.
//
import UIKit
class StarMarkView: UIView {
var isPanGestureEnable = true
var isTapGestureEnable = true
var isFullStar = false
var score: CGFloat = 5.0 {
didSet {
setLength()
}
}
var starCount = 5 {
didSet {
setup()
}
}
var sadImg: UIImage? {
didSet {
if let img = sadImg {
for iv in sadStarList {
iv.image = img
}
}
}
}
var likeImg: UIImage? {
didSet {
if let img = likeImg {
for iv in likeStarList {
iv.image = img
}
}
}
}
private var likeBackView = UIView()
var margin: CGFloat = 10.0
var sadStarList = [UIImageView]()
var likeStarList = [UIImageView]()
let maskLayer = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
for i in 0..<sadStarList.count {
sadStarList[i].removeFromSuperview()
likeStarList[i].removeFromSuperview()
}
sadStarList.removeAll()
likeStarList.removeAll()
for _ in 0..<starCount {
let sadImgV = UIImageView()
let likeImgV = UIImageView()
sadImgV.contentMode = .scaleAspectFit
likeImgV.contentMode = .scaleAspectFit
addSubview(sadImgV)
sadStarList.append(sadImgV)
likeStarList.append(likeImgV)
}
addSubview(likeBackView)
likeBackView.isUserInteractionEnabled = false
for l in likeStarList {
likeBackView.addSubview(l)
}
let pan = UIPanGestureRecognizer(target: self, action: #selector(StarMarkView.ac_pan(sender:)))
let tap = UITapGestureRecognizer(target: self, action: #selector(StarMarkView.ac_tap(sender:)))
self.addGestureRecognizer(pan)
self.addGestureRecognizer(tap)
likeBackView.layer.mask = maskLayer
maskLayer.backgroundColor = UIColor.red.cgColor
}
func ac_pan(sender: UIPanGestureRecognizer) {
if !isPanGestureEnable {
return
}
let point = sender.location(in: self)
// let length = sadStarList.last?.frame.maxX ?? 1
calculateScore(point: point)
}
func ac_tap(sender: UITapGestureRecognizer) {
if !isTapGestureEnable {
return
}
let point = sender.location(in: self)
// let length = sadStarList.last?.frame.maxX ?? 1
calculateScore(point: point)
}
func calculateScore(point: CGPoint) {
if sadStarList.isEmpty {
score = 0
return
}
if point.x < 0 {
score = 0
} else if point.x > sadStarList.last?.frame.maxX ?? 0 {
score = CGFloat(sadStarList.count)
} else {
let x = point.x
for i in 0..<sadStarList.count {
let star = sadStarList[i]
let maxX = star.frame.maxX
let w = star.frame.width
if maxX < x && maxX + margin > x {
score = isFullStar ? ceil(CGFloat(i + 1)) : CGFloat(i + 1)
return
} else if maxX >= x {
let s = CGFloat(i + 1) - (maxX - x) / w
score = isFullStar ? ceil(s) : s
return
}
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
likeBackView.frame = self.bounds
if sadStarList.isEmpty {
setup()
}
var w = (self.frame.width - margin * CGFloat(starCount - 1)) / CGFloat(starCount)
w = w < self.frame.height ? w : self.frame.height
// let y = (self.frame.height - w) / 2
for i in 0..<starCount {
let f = CGRect(x: CGFloat(i) * (margin + w), y: 0, width: w, height: self.frame.height)
sadStarList[i].frame = f
likeStarList[i].frame = f
}
setLength()
}
func setLength() {
let length = sadStarList.last?.frame.maxX ?? 1
maskLayer.frame = likeBackView.frame
maskLayer.frame.size.width = score / CGFloat(sadStarList.count) * length
}
}
|
//
// ProfileTableViewCell.swift
// goFit
//
// Created by Olivia Gregory on 12/8/17.
// Copyright ยฉ 2017 CS147. All rights reserved.
//
import UIKit
class ProfileTableViewCell: UITableViewCell {
@IBOutlet weak var challengeName: UILabel!
@IBOutlet weak var challengeQuantity: UILabel!
@IBOutlet weak var challengeIcon: UIImageView!
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
}
}
|
//
// WagnerFischerTest.swift
// DiffInSwiftTests
//
// Created by xurunkang on 2019/7/31.
// Copyright ยฉ 2019 xurunkang. All rights reserved.
import XCTest
private extension String {
var toArray: [String] {
return self.map( String.init )
}
}
class WagnerFischerTest: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testAllInsert() {
let o = "".toArray
let n = "abc".toArray
let res = diff(o, n)
let exp = [
Change.insert((0, "a")),
Change.insert((1, "b")),
Change.insert((2, "c"))
]
XCTAssert(res == exp)
}
func testAllDelete() {
let o = "abc".toArray
let n = "".toArray
let res = diff(o, n)
let exp = [
Change.delete((0, "a")),
Change.delete((1, "b")),
Change.delete((2, "c"))
]
XCTAssert(res == exp)
}
func testAllSubstitute() {
let o = "ABC".toArray
let n = "abc".toArray
let res = diff(o, n)
let exp = [
Change.substitute((0, "A", "a")),
Change.substitute((1, "B", "b")),
Change.substitute((2, "C", "c"))
]
XCTAssert(res == exp)
}
func testSamePrefix() {
let o = "aBc".toArray
let n = "ab".toArray
let res = diff(o, n)
let exp = [
Change.substitute((1, "B", "b")),
Change.delete((2, "c"))
]
XCTAssert(res == exp)
}
func testReversed() {
let o = "abc".toArray
let n = "cba".toArray
let res = diff(o, n)
let exp = [
Change.substitute((0, "a", "c")),
Change.substitute((2, "c", "a"))
]
XCTAssert(res == exp)
}
func testSmallChangesAtEdges() {
let o = "sitting".toArray
let n = "kitten".toArray
let res = diff(o, n)
let exp = [
Change.substitute((0, "s", "k")),
Change.substitute((4, "i", "e")),
Change.delete((6, "g"))
]
XCTAssert(res == exp)
}
func testSamePostfix() {
let o = "abcdef".toArray
let n = "def".toArray
let res = diff(o, n)
let exp = [
Change.delete((0, "a")),
Change.delete((1, "b")),
Change.delete((2, "c"))
]
XCTAssert(res == exp)
}
func testKitKat() {
let o = "kit".toArray
let n = "kat".toArray
let res = diff(o, n)
let exp = [
Change.substitute((1, "i", "a")),
]
XCTAssert(res == exp)
}
func testShift() {
let o = "abcd".toArray
let n = "cdef".toArray
let res = diff(o, n)
let exp = [
Change.delete((0, "a")),
Change.delete((1, "b")),
Change.insert((2, "e")),
Change.insert((3, "f"))
]
XCTAssert(res == exp)
}
func testReplaceWholeNewWord() {
let o = "abc".toArray
let n = "d".toArray
let res = diff(o, n)
let exp = [
Change.substitute((0, "a", "d")),
Change.delete((1, "b")),
Change.delete((2, "c"))
]
XCTAssert(res == exp)
}
func testExample() {
let o = "ABCE".toArray
let n = "ACDF".toArray
let res = diff(o, n)
let exp = [
Change.delete((1, "B")),
Change.substitute((2, "E", "D")),
Change.insert((3, "F")),
]
XCTAssert(res == exp)
}
func testLargeData() {
// let largeRange = (0..<10000)
// let o = largeRange.map(String.init)
// let n = largeRange.reversed().map(String.init)
//
// let res = diff(o, n)
}
private func diff<T: Hashable>(_ o: [T], _ n: [T]) -> [Change<T>] {
let wagnerFischer = WagnerFischer<T>()
return wagnerFischer.diff(o: o, n: n)
}
}
|
//
// Task.swift
// WorkAndAnalyse
//
// Created by Ruslan Khanov on 25.03.2021.
//
import Foundation
import FirebaseFirestoreSwift
class Task: Codable {
@DocumentID var id: String?
var title: String
var startTime: Date
var subtasks: [Subtask]
var completed: Bool {
subtasks.allSatisfy { $0.completed }
}
var duration: TimeInterval {
subtasks.map { $0.duration }.reduce(TimeInterval(0), +)
}
var durationString: String {
duration.stringFromTimeInterval()
}
var endTime: Date {
Date(timeInterval: duration, since: startTime)
}
init(title: String, startTime: Date, subtasks: [Subtask]) {
self.title = title
self.startTime = startTime
self.subtasks = subtasks
}
}
class Subtask: Codable {
var title: String
var duration: TimeInterval
var completed: Bool
weak var parent: Task?
var durationString: String {
duration.stringFromTimeInterval()
}
init(title: String, duration: TimeInterval, completed: Bool) {
self.title = title
self.duration = duration
self.completed = completed
}
}
|
//
// AlbumGalleryViewController.swift
// Electro
//
// Created by John Davis on 5/22/16.
// Copyright ยฉ 2016 John Davis. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class AlbumGalleryViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private var galleryDataSource:AlbumGalleryDataSource? = nil
var album:Album? = nil
///Web Data Manager instance used to download images for the album gallery
var webDataManager:WebDataManager! = nil
convenience init( withWebDataManager webDataManager:WebDataManager ){
let layout = UICollectionViewFlowLayout()
self.init( collectionViewLayout: layout )
self.webDataManager = webDataManager
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = self.album?.id?.stringValue ?? "No Album ID"
// Register cell classes
self.collectionView!.registerClass(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "ImageCell")
self.refreshData()
}
func refreshData()
{
if let collectionView = self.collectionView
{
self.galleryDataSource = AlbumGalleryDataSource(withAlbum: self.album, forCollectionView: collectionView, withWebManager:self.webDataManager)
self.collectionView?.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
// Configure the cell
return cell
}
// MARK: UICollectionViewDelegate
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
//MARK: - FlowLayout Delegate
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
//The thumbnails are 150 each in size. see how any times we can divide the width by 150, and round up so we can fit them all without stretching.
let width = self.view.frame.size.width
let numberOfItemsPerRow = ceil(width/150)
//subtract from the size in order to place a 1px line between the images
let size = ceil(width / CGFloat(numberOfItemsPerRow) ) - (numberOfItemsPerRow-2)
return CGSize(width: size, height: size)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
}
|
//
// MapViewAnnotation.swift
// blueunicorn
//
// Created by Thomas Blom on 5/3/15.
// Copyright (c) 2015 Thomas Blom. All rights reserved.
//
import Foundation
import MapKit
extension MapViewController: MKMapViewDelegate {
// 1
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? UnicornMapInfo {
let identifier = "unicorn"
var view: MKAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
as? MKPinAnnotationView { // 2
dequeuedView.annotation = annotation
view = dequeuedView
} else {
// 3
view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) as UIView
view.image = UIImage( named: "unicorn_icon40x49.png" )
}
return view
}
return nil
}
} |
//
// VisConstraintMaker.swift
// Viscosity
//
// Created by WzxJiang on 16/7/21.
// Copyright ยฉ 2016ๅนด WzxJiang. All rights reserved.
//
import UIKit
class VisConstraintMaker: NSObject {
enum VisConstraintMakerType {
case normal
case replace
case update
}
var constraints: [VisConstraint] = []
var view: UIView!
var superView: UIView!
var type: VisConstraintMakerType = .normal
init(view: UIView) {
super.init()
guard view.superview != nil else {
return
}
if view.translatesAutoresizingMaskIntoConstraints {
view.translatesAutoresizingMaskIntoConstraints = false
}
self.view = view
self.superView = view.superview
}
func install() -> Void {
if type == .replace {
self.removeAllConstraints()
}
if type == .update {
for constraint in constraints {
self.removeConstraint(constraint)
self.addConstraint(constraint: constraint)
}
} else {
for constraint in constraints {
self.addConstraint(constraint: constraint)
}
}
}
//MARK: - Add
private func addConstraint(constraint: VisConstraint) -> Void {
let toItem = constraint.toItem
if toItem is UIView {
self.addConstraintWithView(toItem as! UIView,
constraint: constraint)
} else if toItem is VisConstraint {
self.addConstraintWithConstraint(toItem as! VisConstraint,
constraint: constraint)
} else if toItem is NSNumber {
self.addConstraintWithNumber(toItem as! NSNumber,
constraint: constraint)
}
}
private func addConstraintWithView(_ toItem: UIView, constraint: VisConstraint) -> Void {
let layoutConstraint: NSLayoutConstraint
= NSLayoutConstraint(item: view,
attribute: constraint.attribute,
relatedBy: constraint.relation,
toItem: toItem,
attribute: constraint.attribute,
multiplier: constraint.multiplier,
constant: constraint.offset)
layoutConstraint.identifier =
String(format: "%@_%d",
Unmanaged.passUnretained(view).toOpaque().debugDescription,
constraint.attribute.rawValue)
self.superView?.addConstraint(layoutConstraint)
}
private func addConstraintWithConstraint(_ toConstraint: VisConstraint, constraint: VisConstraint) -> Void {
let layoutConstraint: NSLayoutConstraint
= NSLayoutConstraint(item: view,
attribute: constraint.attribute,
relatedBy: constraint.relation,
toItem: toConstraint.toItem,
attribute: toConstraint.attribute,
multiplier: constraint.multiplier,
constant: constraint.offset)
layoutConstraint.identifier =
String(format: "%@_%d",
Unmanaged.passUnretained(view).toOpaque().debugDescription,
constraint.attribute.rawValue)
self.superView?.addConstraint(layoutConstraint)
}
private func addConstraintWithNumber(_ toItem: NSNumber, constraint: VisConstraint) -> Void {
let layoutConstraint: NSLayoutConstraint
= NSLayoutConstraint(item: view,
attribute: constraint.attribute,
relatedBy: constraint.relation,
toItem: nil,
attribute: .notAnAttribute,
multiplier: constraint.multiplier,
constant: CGFloat(toItem.floatValue))
layoutConstraint.identifier =
String(format: "%@_%d",
Unmanaged.passUnretained(view).toOpaque().debugDescription,
constraint.attribute.rawValue)
self.superView?.addConstraint(layoutConstraint)
}
//MARK: - Remove
private func removeAllConstraints() -> Void {
let identifier =
String.init(format: "%@",
Unmanaged.passUnretained(view).toOpaque().debugDescription)
var constraints: [NSLayoutConstraint] = []
for constraint in self.superView.constraints {
if constraint.identifier?.contains(identifier) == true {
constraints.append(constraint)
}
}
self.superView.removeConstraints(constraints)
}
private func removeConstraint(_ vis_constraint: VisConstraint) -> Void {
let identifier =
String.init(format: "%@_%d",
Unmanaged.passUnretained(view).toOpaque().debugDescription,
vis_constraint.attribute.rawValue)
for constraint in self.superView.constraints {
if constraint.identifier == identifier {
self.superView.removeConstraint(constraint)
return
}
}
}
//MARK: - lazy load
lazy var left: VisConstraint = {
var left = VisConstraint()
left.attribute = .left
self.constraints.append(left)
return left
}()
lazy var right: VisConstraint = {
var right = VisConstraint()
right.attribute = .right
self.constraints.append(right)
return right
}()
lazy var top: VisConstraint = {
var top = VisConstraint()
top.attribute = .top
self.constraints.append(top)
return top
}()
lazy var bottom: VisConstraint = {
var bottom = VisConstraint()
bottom.attribute = .bottom
self.constraints.append(bottom)
return bottom
}()
lazy var width: VisConstraint = {
var width = VisConstraint()
width.attribute = .width
self.constraints.append(width)
return width
}()
lazy var height: VisConstraint = {
var height = VisConstraint()
height.attribute = .height
self.constraints.append(height)
return height
}()
lazy var centerX: VisConstraint = {
var centerX = VisConstraint()
centerX.attribute = .centerX
self.constraints.append(centerX)
return centerX
}()
lazy var centerY: VisConstraint = {
var centerY = VisConstraint()
centerY.attribute = .centerY
self.constraints.append(centerY)
return centerY
}()
// TODO: - []
// lazy var center: [VisConstraint] = {
// return [self.centerX, self.centerY]
// }()
}
|
//
// MovieCollectionViewCell.swift
// ZexiLiu-Lab4
//
// Created by Mike Liu on 7/11/20.
// Copyright ยฉ 2020 Mike Liu. All rights reserved.
//
import UIKit
class MovieCollectionViewCell: UICollectionViewCell {
}
func setImage(_ image: UIImage) {
}
func setTitle(_ title: String) {
}
|
//
// GImageFilterType.swift
// MetalImageFilter
//
// Created by LEE CHUL HYUN on 4/15/19.
// Copyright ยฉ 2019 LEE CHUL HYUN. All rights reserved.
//
import Foundation
enum GImageFilterType {
case gaussianBlur2D
case saturationAdjustment
case rotation
case colorGBR
case sepia
case pixellation
case luminance
case normalMap
case invert
case centerMagnification
case swellingUp
case slimming
case `repeat`
case redEmphasis
case greenEmphasis
case blueEmphasis
case rgbEmphasis
case divide
case mpsUnaryImageKernel(type: GMPSUnaryImageFilterType)
case binaryImageKernel(type: BinaryImageFilterType)
case carnivalMirror
case kuwahara
var name: String {
switch self {
case .gaussianBlur2D:
return "GaussianBlur2D"
case .saturationAdjustment:
return "SaturationAdjustment"
case .rotation:
return "Rotation"
case .colorGBR:
return "ColorGBR"
case .sepia:
return "Sepia"
case .pixellation:
return "Pixellation"
case .luminance:
return "Luminance"
case .normalMap:
return "Normal Map"
case .invert:
return "Invert"
case .centerMagnification:
return "Maganifying glass "
case .swellingUp:
return "Swelling up"
case .slimming:
return "Slimming"
case .repeat:
return "Repeat"
case .redEmphasis:
return "Red Emphasis"
case .greenEmphasis:
return "Green Emphasis"
case .blueEmphasis:
return "Blue Emphasis"
case .rgbEmphasis:
return "RGB Emphasis"
case .divide:
return "Divide"
case .carnivalMirror:
return "Carnival Mirror"
case .kuwahara:
return "Kuwahara"
case .mpsUnaryImageKernel(let type):
return type.name
case .binaryImageKernel(let type):
return type.name
}
}
func createImageFilter(context: GContext) -> GImageFilter? {
switch self {
case .gaussianBlur2D:
return GGaussianBlur2DFilter(context: context, filterType: self)
case .saturationAdjustment:
return GSaturationAdjustmentFilter(context: context, filterType: self)
case .rotation:
return GRotationFilter(context: context, filterType: self)
case .colorGBR:
return GColorGBRFilter(context: context, filterType: self)
case .sepia:
return GSepiaFilter(context: context, filterType: self)
case .pixellation:
return GPixellationFilter(context: context, filterType: self)
case .luminance:
return GLuminanceFilter(context: context, filterType: self)
case .normalMap:
return GNormalMapFilter(context: context, filterType: self)
case .invert:
return GImageFilter(functionName: "invert", context: context, filterType: self)
case .centerMagnification:
return GCenterMagnificationFilter(context: context, filterType: self)
case .swellingUp:
return GWeightedCenterMagnificationFilter(context: context, filterType: self)
case .slimming:
return GSlimmingFilter(context: context, filterType: self)
case .repeat:
return GImageFilter(functionName: "repeat", context: context, filterType: self)
case .redEmphasis:
return GImageFilter(functionName: "emphasizeRed", context: context, filterType: self)
case .greenEmphasis:
return GImageFilter(functionName: "emphasizeGreen", context: context, filterType: self)
case .blueEmphasis:
return GImageFilter(functionName: "emphasizeBlue", context: context, filterType: self)
case .rgbEmphasis:
return GImageFilter(functionName: "emphasizeRGB", context: context, filterType: self)
case .divide:
return GDivideFilter(context: context, filterType: self)
case .carnivalMirror:
return GCarnivalMirrorFilter(context: context, filterType: self)
case .kuwahara:
return GKuwaharaFilter(context: context, filterType: self)
case .mpsUnaryImageKernel(let type):
return GMPSUnaryImageFilter(type: type, context: context, filterType: self)
case .binaryImageKernel(let type):
return BinaryImageFilter(type: type, functionName: "oneStepLaplacianPyramid", context: context, filterType: self)
}
}
var inputMipmapped: Bool {
switch self {
case .mpsUnaryImageKernel(let type):
return type.inputMipmapped
case .binaryImageKernel(let type):
return type.inputMipmapped
default:
return false
}
}
var outputMipmapped: Bool {
switch self {
case .mpsUnaryImageKernel(let type):
return type.outputMipmapped
case .binaryImageKernel(let type):
return type.outputMipmapped
default:
return false
}
}
var inPlaceTexture: Bool {
switch self {
case .mpsUnaryImageKernel(let type):
return type.inPlaceTexture
case .binaryImageKernel(let type):
return type.inPlaceTexture
default:
return false
}
}
var output2Required: Bool {
switch self {
case .mpsUnaryImageKernel(let type):
return type.output2Required
case .binaryImageKernel(let type):
return type.output2Required
default:
return false
}
}
}
|
//
// TutorialContentViewController.swift
// prkng-ios
//
// Created by Cagdas Altinkaya on 26/05/15.
// Copyright (c) 2015 PRKNG. All rights reserved.
//
import UIKit
class TutorialContentViewController: GAITrackedViewController {
var backgroundImageView : UIImageView //used in TutorialViewController
var imageView : UIImageView //used in TutorialViewController
var textLabel : UILabel
var pageIndex : Int
private var SMALL_SCREEN_IMAGE_HEIGHT_DIFFERENCE = UIScreen.mainScreen().bounds.height == 480 ? 30 : 0
init(backgroundImage : UIImage, image : UIImage, text : String, index : Int) {
backgroundImageView = UIImageView()
imageView = UIImageView()
textLabel = UILabel()
pageIndex = index
super.init(nibName: nil, bundle: nil)
backgroundImageView.image = backgroundImage
imageView.image = image
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 6.5
let attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
textLabel.attributedText = attrString
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func loadView() {
self.view = UIView()
setupViews()
setupConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
self.screenName = "Intro - Tutorial Single Page View"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupViews() {
// backgroundImageView.contentMode = .ScaleAspectFill
// view.addSubview(backgroundImageView)
imageView.clipsToBounds = true
imageView.alpha = 0
imageView.contentMode = UIViewContentMode.ScaleAspectFit
view.addSubview(imageView)
textLabel.textColor = Styles.Colors.cream1
textLabel.font = Styles.FontFaces.light(17)
textLabel.numberOfLines = 0
textLabel.textAlignment = NSTextAlignment.Center
view.addSubview(textLabel)
}
func setupConstraints () {
// backgroundImageView.snp_makeConstraints { (make) -> () in
// make.edges.equalTo(self.view)
// }
imageView.snp_makeConstraints { (make) -> () in
make.top.lessThanOrEqualTo(self.view).offset(60)
make.left.equalTo(self.view).offset(35)
make.right.equalTo(self.view).offset(-35)
make.height.lessThanOrEqualTo(self.imageView.snp_width).offset(0 - self.SMALL_SCREEN_IMAGE_HEIGHT_DIFFERENCE)
}
textLabel.snp_makeConstraints { (make) -> () in
make.top.lessThanOrEqualTo(self.imageView.snp_bottom).offset(20)
make.left.equalTo(self.view).offset(40)
make.right.equalTo(self.view).offset(-40)
make.bottom.lessThanOrEqualTo(self.view).offset(-40 - TutorialViewController.PAGE_CONTROL_BOTTOM_OFFSET)
}
}
}
|
//
// ViewController.swift
// TecStubDemo
//
// Created by Apple on 02/01/21.
// Copyright ยฉ 2021 Tita. All rights reserved.
//
import UIKit
import AlamofireImage
class DogListViewController: UIViewController {
var presentor: DogListViewToPresenterProtocol?
var dogs : [Dog]?
@IBOutlet weak var tblDogs: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
presentor?.getDogList()
tblDogs.rowHeight = UITableView.automaticDimension
tblDogs.estimatedRowHeight = 60
}
}
extension DogListViewController: DogListPresenterToViewProtocol{
func didRecieved(dogs: [Dog]) {
self.dogs = dogs
self.tblDogs.reloadData()
}
}
extension DogListViewController : UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return dogs?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let strIdentifier = "DogListCell"
var cell: DogListCell! = tableView.dequeueReusableCell(withIdentifier: strIdentifier) as? DogListCell
if cell == nil
{
tableView.register(UINib(nibName: strIdentifier, bundle: nil), forCellReuseIdentifier: strIdentifier)
cell = tableView.dequeueReusableCell(withIdentifier: strIdentifier) as? DogListCell
}
cell.name.text = self.dogs![indexPath.row].name
cell.lifeSpan.text = self.dogs![indexPath.row].lifeSpan
cell.imageView?.setImageWithUrl(strUrl: self.dogs![indexPath.row].image ?? "", placeholderImage: nil,tableView: tableView)
return cell
}
}
import Foundation
extension UIImageView {
func setImageWithUrl(strUrl: String, placeholderImage: String?, tableView : UITableView) {
var strDefaultImage = "img-noimage"
if placeholderImage != nil, placeholderImage != "" {
strDefaultImage = placeholderImage!
}
if let tmpUrl = URL(string: strUrl) {
let filter = AspectScaledToFillSizeFilter(size: CGSize(width: 100, height: 100))
af.setImage(withURL: tmpUrl, placeholderImage: UIImage(named: strDefaultImage), filter: filter, imageTransition: .crossDissolve(0.3), completion: { (response) in
// tableView.reloadData()
})
} else {
image = UIImage(named: strDefaultImage)
}
}
}
|
//
// Activities.swift
// The Vibe
//
// Created by Shuailin Lyu on 4/7/17.
// Copyright ยฉ 2017 Shuailin Lyu. All rights reserved.
//
import Foundation
import MapKit
class Activities{
var title: String
var type: ActivityType
var organizer: String
var location: CLLocationCoordinate2D
var startTime : Date
var description: String
var attendee: [String]
init() {
self.title = ""
self.type = .Academic
self.organizer = ""
self.location = CLLocationCoordinate2D()
self.startTime = Date()
self.description = "No description"
self.attendee = []
}
enum ActivityType {
case Academic
case StudentOrganization
case Personal
}
func activityToString() -> String {
if (self.type == .Academic) {
return "Academic"
}
else if (self.type == .StudentOrganization) {
return "Student Organization"
}
else {
return "Personal"
}
}
}
|
//
// AppDelegate.swift
// 02_ๅๅปบTabBarๅทฅ็จ
//
// Created by ้ฉฌ่ฃๅ on 2017/7/7.
// Copyright ยฉ 2017ๅนด ้ฉฌ่ฃๅ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let rootC = TabBarC()
window = UIWindow(frame:UIScreen.main.bounds)
window?.rootViewController = rootC
window?.makeKeyAndVisible()
return true
}
}
|
//
// NHImageView.swift
// Registradores-Arisp
//
// Created by Nathan Hegedus on 30/06/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
class NHImageView: UIImageView {
@IBInspectable var streachSize: Int = 0 {
didSet {
let backgroundImage = self.image?.stretchableImageWithLeftCapWidth(streachSize, topCapHeight: streachSize)
self.image = backgroundImage
}
}
}
|
//
// MySort.swift
// LeetCode
//
// Created by 360JR on 2021/2/6.
// Copyright ยฉ 2021 liangqili.com. All rights reserved.
//
import Foundation
class MySort {
// ๅๆณกๆๅบ
static func bubbleSort(_ arr:inout [Int]) {
for i in 0..<arr.count-1 {
for j in 0..<arr.count-i-1 {
if arr[j] > arr[j+1] {
arr.swapAt(j, j+1)
}
}
}
}
// ๆๅ
ฅๆๅบ
static func insertionSort(_ arr: inout [Int]) {
if arr.count <= 1 {
return
}
// ไป็ฌฌไธไธชๅผๅงๆฏ่พ
for i in 1..<arr.count {
// ่ฆๆๅ
ฅ็ๅ
็ด
let value = arr[i]
var j = i - 1
// ็งปๅจๅ
็ด ๅฏปๆพๆๅ
ฅไฝ็ฝฎ
while j >= 0 {
if arr[j] > value {
arr[j+1] = arr[j]
} else {
break
}
j -= 1
}
arr[j+1] = value
}
}
// ้ๆฉๆๅบ
static func selectionSort(_ arr:inout [Int]) {
for i in 0..<arr.count {
var minIndex = i
for j in i..<arr.count {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
arr.swapAt(i, minIndex)
}
}
// ๅฝๅนถๆๅบ
static func mergeSort(_ arr:inout [Int]) {
self.merge_sort_c(&arr, 0, arr.count - 1)
}
static func merge_sort_c(_ arr:inout [Int],_ startIndex: Int,_ endIndex:Int) {
guard startIndex < endIndex else {
return
}
let midIndex = (startIndex + endIndex) / 2
merge_sort_c(&arr, startIndex, midIndex)
merge_sort_c(&arr, midIndex + 1, endIndex)
self.merge(&arr,startIndex,midIndex,endIndex)
}
static func merge(_ arr:inout [Int],_ startIndex: Int,_ midIndex: Int,_ endIndex:Int) {
var i = startIndex, j = midIndex + 1, k = 0
let count = endIndex - startIndex + 1
var tmp = Array(repeating: 0, count: count)
while i <= midIndex && j <= endIndex {
if arr[i] <= arr[j] {
tmp[k] = arr[i]
i += 1
} else {
tmp[k] = arr[j]
j += 1
}
k += 1
}
// ๅคๆญๆฐ็ปๅฉไฝ
var start = i, end = midIndex
if j <= endIndex {
start = j
end = endIndex
}
// ๅฐๅฉไฝ็ๆฐๆฎๆท่ดๅฐไธดๆถๆฐ็ปtmp
while start <= end {
tmp[k] = arr[start]
k += 1
start += 1
}
// ๅฐtmpไธญ็ๆฐ็ปๆท่ดๅA[p...r]
for index in 0..<count {
arr[startIndex + index] = tmp[index]
}
}
// ๅฟซ้ๆๅบ
static func quickSort(_ arr:inout [Int]) {
self.quick_sort_c(&arr, 0, arr.count - 1)
}
static func quick_sort_c(_ arr:inout [Int],_ startIndex:Int,_ endIndex:Int) {
guard startIndex < endIndex else {
return
}
let p = self.partition(&arr, startIndex, endIndex)
quick_sort_c(&arr, startIndex, p - 1)
quick_sort_c(&arr, p + 1, endIndex)
}
// ๅๅบ ๅนถ่ฟๅๅๅบ็น
// ๆไผ่งฃ ไบคๆข ๅๅฐๆๅบ
static func partition(_ arr:inout [Int],_ startIndex:Int,_ endIndex:Int) -> Int {
var i = startIndex
let pValue = arr[endIndex]
for j in startIndex...endIndex {
if arr[j] <= pValue {
arr.swapAt(i, j)
i += 1
}
}
return i - 1
}
// ็ฌฌไธ็งๅ็ปๆนๆณ๏ผๅฉ็จไธดๆถๆฐ็ป
static func partition_1(_ arr:inout [Int],_ startIndex:Int,_ endIndex:Int) -> Int {
var tmpLittle = [Int]()
var tmpLarge = [Int]()
let pValue = arr[endIndex]
for i in startIndex..<endIndex {
if arr[i] <= pValue {
tmpLittle.append(arr[i])
} else {
tmpLarge.append(arr[i])
}
}
let tmp = tmpLittle + [pValue] + tmpLarge
for (index,value) in tmp.enumerated() {
arr[startIndex + index] = value
}
return startIndex + tmpLittle.count
}
// ่ฎกๆฐๆๅบ
static func countingSort(_ arr:inout [Int]) {
guard arr.count > 1 else {
return
}
// ๆฅๆพๆฐๆฎ่ๅด
var max = arr[0]
for i in arr {
if max < i {
max = i
}
}
// ็ณ่ฏทไธไธช่ฎกๆฐๆฐ็ปc๏ผไธๆ ๅคงๅฐ[0,max]
var countingArr = Array(repeating:0,count:max+1)
// ่ฎก็ฎๆฏไธชๅ
็ด ็ไธชๆฐ๏ผๆพๅ
ฅcไธญ
for i in arr {
countingArr[i] = countingArr[i] + 1
}
//ไพๆฌก็ดฏๅ
for i in 1..<countingArr.count {
countingArr[i] = countingArr[i] + countingArr[i - 1]
}
// ็ณ่ฏทไธดๆถๆฐ็ปr๏ผๅญๅจๆๅบไนๅ็็ปๆ
var tmp = Array(repeating: 0, count: arr.count)
// ๆ นๆฎ่ฎกๆฐๆฐ็ป๏ผๅฐๆฐๆฎๆพๅ
ฅtmpไธญ
var index = arr.count - 1
while index >= 0 {
tmp[countingArr[arr[index]] - 1] = arr[index]
countingArr[arr[index]] = countingArr[arr[index]] - 1
index -= 1
}
// ้ๅtmp๏ผๅฐๅ
็ด ๆพๅ
ฅarrไธญ
for (index,value) in tmp.enumerated() {
arr[index] = value
}
}
}
|
//
// AdminTimesTableViewCell.swift
// Bloom
//
// Created by Nassyrkhan Seitzhapparuly on 6/22/17.
// Copyright ยฉ 2017 asamasa. All rights reserved.
//
import UIKit
class AdminTimesTableViewCell: UITableViewCell {
@IBOutlet weak var timeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
timeLabel.textColor = UIColor(hex: "929292")
timeLabel.font = UIFont(name: "Comfortaa-Regular", size: 20)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
//
// Bundle+Extension.swift
// JatApp-Utils-iOS
//
// Created by Developer on 2/25/19.
// Copyright ยฉ 2019 JatApp. All rights reserved.
//
import Foundation
public extension Bundle {
func bundleObject() -> String {
let nsObject = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
return nsObject
}
var appVersion: Int {
let infoDictionary = Bundle.main.infoDictionary
let majorVersion = infoDictionary?["CFBundleShortVersionString"] as? String
let minorVersion = infoDictionary?["CFBundleVersion"] as? String
let trim = CharacterSet(charactersIn: ".")
let cleanString = majorVersion?.components(separatedBy: trim).joined(separator: "")
let majorVersionInteger = Int(cleanString ?? "") ?? 0 * 10
let minorVersionInteger = Int(minorVersion ?? "") ?? 0
let appVersion: Int = majorVersionInteger + minorVersionInteger
return appVersion
}
var appMajorVersion: String? {
let infoDictionary = Bundle.main.infoDictionary
let majorVersion = infoDictionary?["CFBundleShortVersionString"] as? String
return majorVersion
}
var appIdentifier: String? {
let infoDictionary = Bundle.main.infoDictionary
let identifier = infoDictionary?["CFBundleIdentifier"] as? String
return identifier
}
var shortAppVersion: String? {
let infoDictionary = Bundle.main.infoDictionary
let majorVersion = infoDictionary?["CFBundleShortVersionString"] as? String
let appMajorVersionString = "Version: \(majorVersion ?? "")"
return appMajorVersionString
}
var bundleVersion: String? {
let infoDictionary = Bundle.main.infoDictionary
let minorVersion = infoDictionary?["CFBundleVersion"] as? String
return minorVersion
}
}
|
import Foundation
indirect enum Expression: Hashable {
case assign(name: Token, value: Expression)
case binary(left: Expression, operator: Token, right: Expression)
case call(callee: Expression, paren: Token, arguments: [Expression])
case grouping(expression: Expression)
case literal(value: AnyHashable?)
case logical(left: Expression, operator: Token, right: Expression)
case unary(operator: Token, right: Expression)
case variable(name: Token)
}
|
//
// PDFViewController.swift
// Algorithms
//
// Created by Loc Tran on 4/17/17.
// Copyright ยฉ 2017 LocTran. All rights reserved.
//
import UIKit
class PDFViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
AppUtility.lockOrientation(.portrait)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Don't forget to reset when view is being removed
AppUtility.lockOrientation(.all)
}
override func viewWillAppear(_ animated: Bool) {
let pdfTitle = PDF_TITLE
let url = Bundle.main.url(forResource: pdfTitle, withExtension: "pdf")
let webView = UIWebView(frame: CGRect(x: 0, y: (navigationController?.navigationBar.frame.maxY)!, width: view.frame.width, height: view.frame.height))
let urlRequest = URLRequest(url: url!)
webView.loadRequest(urlRequest as URLRequest)
webView.scalesPageToFit = true
view.addSubview(webView)
title = pdfTitle
}
override func viewDidLoad() {
super.viewDidLoad()
addBackButton()
}
func addBackButton(){
let backButton = UIBarButtonItem(image: #imageLiteral(resourceName: "back"), style: .plain, target: self, action: #selector(popToRootView(sender:)))
backButton.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem = backButton
}
@objc func popToRootView(sender: UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
}
|
//
// QRCodeScanVC.swift
// YYDeviceScanning
//
// Created by daoquan on 2018/2/23.
// Copyright ยฉ 2018ๅนด deerdev. All rights reserved.
//
import UIKit
import AVFoundation
class QRCodeScanVC: UIViewController {
/// ไบ็ปด็ ๆซๆไผ่ฏ
private var session: AVCaptureSession?
/// ไบ็ปด็ ๆซๆ็ชๅฃ
private var scanWindow: UIView!
/// ไบ็ปด็ ๆซๆๅจ็ปๅพ็
private var scanNetImageView: UIImageView!
/// ไบ็ปด็ ๆซๆ็ปๆๅญ็ฌฆไธฒ
private var qrCodeString: String?
/// Controller็ๆ ้ข
private var controllerTitle = ""
/// ๆฏๅฆๆพ็คบ็ธๅ
private var isShowAlbum = false
/// ๆฏๅฆๆพ็คบ้ชๅ
็ฏ
private var isShowFlash = false
/// ้ชๅ
็ฏๆฏๅฆๅจไบฎ
private var isFlashOn = false
var scanResult: ((_ result: String) -> Void)?
convenience init(with title: String, isShowAlbum: Bool, isShowFlash: Bool) {
self.init()
self.controllerTitle = title
self.isShowAlbum = isShowAlbum
self.isShowFlash = isShowFlash
}
override func viewDidLoad() {
super.viewDidLoad()
// ่ฟไธชๅฑๆงๅฟ
้กปๆๅผๅฆๅ่ฟๅ็ๆถๅไผๅบ็ฐ้ป่พน
self.view.clipsToBounds = true
self.title = controllerTitle
// 1.่ฎพ็ฝฎ้ฎ็ฝฉๅๆ็คบๆๆฌ
setupMaskAndTitleView()
// 2.้กถ้จๅฏผ่ช
setupNavView()
// 3.ๆซๆๅบๅ
setupScanWindowView()
// 4.ๆฃๆฅๆ้
verifyCameraAccess()
// 5.ๅผๅงๅจ็ป
// [self beginScanning];
NotificationCenter.default.addObserver(self, selector: #selector(self.qrScanAnimation), name: .UIApplicationWillEnterForeground, object: nil)
print("code0: \(qrCodeString ?? "")")
NotificationCenter.default.addObserver(self, selector: #selector(self.backBecomeActive), name: .UIApplicationDidBecomeActive, object: nil)
}
/// ๆฃๆฅ็ธๆบๆฏๅฆๆๆ
func verifyCameraAccess() {
let AVstatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
//็ธๆบๆ้
switch AVstatus {
case .authorized:
beginScanning()
case .notDetermined:
requireCameraAccess()
case .denied, .restricted:
showAccessAlert()
}
}
/// ็ฌฌไธๆฌก่ฏทๆฑๆๆ
func requireCameraAccess() {
AVCaptureDevice.requestAccess(for: .video) { (isGranted) in
//็ธๆบๆ้
if isGranted {
DispatchQueue.main.async {
self.beginScanning()
self.qrScanAnimation()
}
}
}
}
/// ่ฏทๆฑ็จๆทๅผๅฏๆ้็ๅผน็ช
func showAccessAlert() {
showAlert(title: "ๆ็คบ", message: "่ฎพๅคไธๆฏๆ่ฎฟ้ฎ็ธๆบ๏ผ\n่ฏทๅจ่ฎพ็ฝฎไธญๆๅผ็ธๆบ่ฎฟ้ฎ๏ผ", cancelBlock: {}, isNeedConfirm: true, confirmTitle: "ๅๅพ่ฎพ็ฝฎ") {
let appSettings = URL(string: UIApplicationOpenSettingsURLString)
UIApplication.shared.open(appSettings!)
}
}
/// ๅๅฐ่ฟๅๅฐ๏ผๆฟๆดปๅจ็ป
@objc func backBecomeActive() {
// ๅๅฐ่ฟๅๅฐ๏ผๆฟๆดปๅจ็ป
qrScanAnimation()
if let session = session, !session.isRunning {
session.startRunning()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// ๅผๅฏๅจ็ป
qrScanAnimation()
if let session = session, !session.isRunning {
session.startRunning()
}
}
override func viewWillDisappear(_ animated: Bool) {
scanNetImageView.layer.removeAnimation(forKey: "translationAnimation")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let session = session {
session.stopRunning()
}
closeFlash()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// ่ฎพ็ฝฎไบ็ปด็ ๆซๆๆกๅๆ็คบๆๅญ
func setupMaskAndTitleView() {
// 1.่ฎพ็ฝฎ้ฎ็ฝฉ
let windowSize: CGSize = UIScreen.main.bounds.size
let scanSize = CGSize(width: windowSize.width * 3 / 4, height: windowSize.width * 3 / 4)
let maskView = UIView()
maskView.bounds = CGRect(x: 0, y: 0, width: windowSize.height, height: windowSize.height)
// ้ฎ็ฝฉไฝฟ็จ่พนๆก็้ข่ฒ้ฎ็๏ผไฟ่ฏไธญ้ดๆฏ้ๆ็
maskView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6).cgColor
maskView.layer.borderWidth = (windowSize.height - scanSize.height) / 2.0
maskView.center = CGPoint(x: view.bounds.size.width * 0.5, y: view.frame.size.height * 0.5)
view.addSubview(maskView)
// ๅฎ้
็ไบ็ปด็ ๆซๆ็ชๅฃ
let scanView = UIView(frame: CGRect(x: 0, y: 0, width: scanSize.width, height: scanSize.height))
scanView.backgroundColor = UIColor.clear
scanView.center = CGPoint(x: view.bounds.size.width * 0.5, y: view.frame.size.height * 0.5)
scanWindow = scanView
view.addSubview(scanWindow)
// 2.ไบ็ปด็ ๆซๆๆ็คบ
let tipLabel = UILabel(frame: CGRect(x: 0, y: scanWindow.frame.origin.y + scanWindow.frame.size.height, width: view.bounds.size.width, height: 50))
tipLabel.text = "ๅฐๅๆฏๆกๅฏนๅไบ็ปด็ /ๆก็ ๏ผๅณๅฏ่ชๅจๆซๆ"
tipLabel.textColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.6)
tipLabel.textAlignment = .center
tipLabel.lineBreakMode = .byWordWrapping
tipLabel.numberOfLines = 2
tipLabel.font = UIFont.systemFont(ofSize: 14)
tipLabel.backgroundColor = UIColor.clear
view.addSubview(tipLabel)
}
/// ่ฎพ็ฝฎๅฏผ่ชๆ ๆ้ฎ--่ฟๅ--็ธๅ--้ชๅ
็ฏ๏ผๅพ
ๅฎ๏ผ--
func setupNavView() {
//1.่ฟๅๆ้ฎ
let backBtn = UIButton(type: .custom)
backBtn.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
backBtn.contentHorizontalAlignment = .left
backBtn.setBackgroundImage(UIImage(named: "nav_back_orange"), for: .normal)
//backBtn.contentMode=UIViewContentModeScaleAspectFit;
backBtn.addTarget(self, action: #selector(self.backToPop), for: .touchUpInside)
let leftItem = UIBarButtonItem(customView: backBtn)
//leftItem.imageInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
self.navigationItem.leftBarButtonItem = leftItem
if isShowAlbum {
//2.็ธๅๆ้ฎ
let albumBtn = UIButton(type: .custom)
albumBtn.frame = CGRect(x: 0, y: 0, width: 50, height: 35)
albumBtn.setTitle("็ธๅ", for: .normal)
albumBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
albumBtn.setTitleColor(UIColor.orange, for: .normal)
albumBtn.contentHorizontalAlignment = .right
//albumBtn.contentMode=UIViewContentModeScaleAspectFit;
albumBtn.addTarget(self, action: #selector(self.readAlbum), for: .touchUpInside)
let rightItem = UIBarButtonItem(customView: albumBtn)
self.navigationItem.rightBarButtonItem = rightItem
}
if isShowFlash {
//3.้ชๅ
็ฏ
let flashBtn = UIButton(type: .custom)
let flashImage = UIImage(named: "scan_flash")!
flashBtn.frame = CGRect(x: 0, y: 0, width: 50, height: flashImage.size.height * (50 / flashImage.size.width))
flashBtn.center = CGPoint(x: view.center.x, y: view.center.y + scanWindow.frame.size.height / 2 + 100)
flashBtn.setBackgroundImage(flashImage, for: .normal)
flashBtn.contentMode = .scaleAspectFit
flashBtn.addTarget(self, action: #selector(self.openFlash), for: .touchUpInside)
view.addSubview(flashBtn)
}
}
/// ๆๅผ้ชๅ
็ฏ
@objc func openFlash() {
let device: AVCaptureDevice? = AVCaptureDevice.default(for: .video)
// ๆฏๅฆๆLED
if device?.hasTorch ?? false {
if isFlashOn {
try? device?.lockForConfiguration()
device?.torchMode = .off
//ๅ
ณ
device?.unlockForConfiguration()
}
else {
try? device?.lockForConfiguration()
device?.torchMode = .on
//ๅผ
device?.unlockForConfiguration()
}
isFlashOn = !isFlashOn
}
else {
showAlert(title: "ๆ็คบ", message: "่ฏฅๆๆบไธๆฏๆๅผๅฏ้ชๅ
็ฏ")
}
}
/// ๅ
ณ้ญ้ชๅ
็ฏ
func closeFlash() {
if isShowFlash {
let device: AVCaptureDevice? = AVCaptureDevice.default(for: .video)
if device?.hasTorch ?? false {
if isFlashOn {
try? device?.lockForConfiguration()
device?.torchMode = .off
//ๅ
ณ
device?.unlockForConfiguration()
isFlashOn = false
}
}
}
}
/// ่ฎพ็ฝฎๆกๅไธช่พน่ง็ๅพ็
func setupScanWindowView() {
let scanWindowH: CGFloat = scanWindow.frame.size.width
let scanWindowW: CGFloat = scanWindow.frame.size.width
scanWindow.clipsToBounds = true
// ๅๅงๅๅจ็ปๅพ็
scanNetImageView = UIImageView(image: UIImage(named: "scan_net"))
// ่ฎพ็ฝฎ่พน่งๅพ็็้ซๅฎฝ
let image = UIImage(named: "scan_1")!
let buttonWH: CGFloat = image.size.width
// ๆทปๅ ๅไธช่พน่งๅพ็
let topLeft = UIButton(frame: CGRect(x: 0, y: 0, width: buttonWH, height: buttonWH))
topLeft.setImage(UIImage(named: "scan_1"), for: .normal)
scanWindow.addSubview(topLeft)
let topRight = UIButton(frame: CGRect(x: scanWindowW - buttonWH, y: 0, width: buttonWH, height: buttonWH))
topRight.setImage(UIImage(named: "scan_2"), for: .normal)
scanWindow.addSubview(topRight)
let bottomLeft = UIButton(frame: CGRect(x: 0, y: scanWindowH - buttonWH, width: buttonWH, height: buttonWH))
bottomLeft.setImage(UIImage(named: "scan_3"), for: .normal)
scanWindow.addSubview(bottomLeft)
let bottomRight = UIButton(frame: CGRect(x: topRight.frame.origin.x, y: scanWindowH - buttonWH, width: buttonWH, height: buttonWH))
bottomRight.setImage(UIImage(named: "scan_4"), for: .normal)
//[bottomLeft.layer setBorderWidth:1.0];
scanWindow.addSubview(bottomRight)
}
/// ๅๅงๅไบ็ปด็ ๆซๆ
func beginScanning() {
// ่ทๅๆๅ่ฎพๅค, ๅๅปบ่พๅ
ฅๆต
guard let device = AVCaptureDevice.default(for: .video),
let input = try? AVCaptureDeviceInput(device: device) else {
// ๆฒกๆๆๅๅคด--่ฟๅ
return
}
// ๅๅปบ่พๅบๆต
let output = AVCaptureMetadataOutput()
// ่ฎพ็ฝฎไปฃ็ ๅจไธป็บฟ็จ้ๅทๆฐ
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// ่ฎพ็ฝฎๆๆๆซๆๅบๅ
let scanCrop: CGRect = getScanCrop(scanWindow.bounds, readerViewBounds: view.frame)
output.rectOfInterest = scanCrop
// ๅๅงๅไผ่ฏๅฏน่ฑก
let session = AVCaptureSession()
// ้ซ่ดจ้้้็
session.sessionPreset = .high
// ๅ
ณ่่พๅ
ฅ่พๅบ
session.addInput(input)
session.addOutput(output)
// ่ฎพ็ฝฎๆซ็ ๆฏๆ็็ผ็ ๆ ผๅผ(ๅฆไธ่ฎพ็ฝฎๆกๅฝข็ ๅไบ็ปด็ ๅ
ผๅฎน)
output.metadataObjectTypes = [.qr, .ean13, .ean8, .code128]
// ๅๅงๅๆๅๅคดๆตไฟกๆฏๆพ็คบๅพๅฑ
let layer = AVCaptureVideoPreviewLayer(session: session)
layer.videoGravity = .resizeAspectFill
layer.frame = view.layer.bounds
view.layer.insertSublayer(layer, at: 0)
// ๅผๅงๆ่ท
session.startRunning()
self.session = session
}
/// ่ฟๅๅฐไธไธไธช่งๅพ
@objc func backToPop() {
navigationController?.popViewController(animated: true)
}
/// ่ฏปๅๆฌๅฐๅพ็
@objc func readAlbum() {
print("ๆ็็ธๅ")
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
// 1.ๅๅงๅ็ธๅๆพๅๅจ
let photoPicker = UIImagePickerController()
// 2.่ฎพ็ฝฎไปฃ็
photoPicker.delegate = self
// 3.่ฎพ็ฝฎ่ตๆบ๏ผ
/**
UIImagePickerControllerSourceTypePhotoLibrary,็ธๅ
UIImagePickerControllerSourceTypeCamera,็ธๆบ
UIImagePickerControllerSourceTypeSavedPhotosAlbum,็
ง็ๅบ
*/
photoPicker.sourceType = .photoLibrary
// 4.้ไพฟ็ปไปไธไธช่ฝฌๅบๅจ็ป
photoPicker.modalTransitionStyle = .flipHorizontal
present(photoPicker, animated: true) {() -> Void in }
}
else {
showAlert(title: "ๆ็คบ", message: "่ฎพๅคไธๆฏๆ่ฎฟ้ฎ็ธๅ๏ผ่ฏทๅจ่ฎพ็ฝฎ->้็ง->็
ง็ไธญ่ฟ่ก่ฎพ็ฝฎ๏ผ", cancelBlock: backToPop)
}
}
// MARK: - ๅจ็ป
/// ไบ็ปด็ ๆซๆๅจ็ป
@objc func qrScanAnimation() {
if let session = session, !session.isRunning {
return
}
let anim: CAAnimation? = scanNetImageView.layer.animation(forKey: "translationAnimation")
if anim != nil {
// 1.ๅฐๅจ็ป็ๆถ้ดๅ็งป้ไฝไธบๆๅๆถ็ๆถ้ด็น
let pauseTime: CFTimeInterval = scanNetImageView.layer.timeOffset
// 2.ๆ นๆฎๅชไฝๆถ้ด่ฎก็ฎๅบๅ็กฎ็ๅฏๅจๅจ็ปๆถ้ด๏ผๅฏนไนๅๆๅๅจ็ป็ๆถ้ด่ฟ่กไฟฎๆญฃ
let beginTime: CFTimeInterval = CACurrentMediaTime() - pauseTime
// 3.่ฆๆๅ็งปๆถ้ดๆธ
้ถ
scanNetImageView.layer.timeOffset = 0.0
// 4.่ฎพ็ฝฎๅพๅฑ็ๅผๅงๅจ็ปๆถ้ด
scanNetImageView.layer.beginTime = beginTime
scanNetImageView.layer.speed = 2.5
}
else {
let scanNetImageViewW: CGFloat = scanWindow.frame.size.width
scanNetImageView.frame = CGRect(x: 0, y: 0, width: scanNetImageViewW, height: 2)
let scanNetAnimation = CABasicAnimation()
scanNetAnimation.keyPath = "transform.translation.y"
scanNetAnimation.byValue = scanNetImageViewW
scanNetAnimation.duration = 2
scanNetAnimation.repeatCount = MAXFLOAT
scanNetImageView.layer.add(scanNetAnimation, forKey: "translationAnimation")
scanWindow.addSubview(scanNetImageView)
}
}
// MARK: - ่ทๅๆซๆๅบๅ็ๆฏไพๅ
ณ็ณป
/// ่ฎพ็ฝฎไบ็ปด็ ๆซๆ็ๆๆๅบๅ๏ผๅณๆซๆ้ฎ็ฝฉ็ๅคงๅฐ๏ผ
///
/// - Parameters:
/// - rect: ๆซๆ้ฎ็ฝฉ็ๅคงๅฐ
/// - readerViewBounds: ๅ
จๅฑ๏ผๆๅๅคด็ป้ข๏ผ่งๅพๅคงๅฐ
/// - Returns: ไบ็ปด็ ๆซๆ็ๅฎ้
ๅบๅ๏ผไธไธชๆฏไพ็ณปๆฐ็็ฉๅฝข๏ผ
func getScanCrop(_ rect: CGRect, readerViewBounds: CGRect) -> CGRect {
var x: CGFloat
var y: CGFloat
var width: CGFloat
var height: CGFloat
x = (readerViewBounds.height - rect.height) / 2 / readerViewBounds.height
y = (readerViewBounds.width - rect.width) / 2 / readerViewBounds.width
width = rect.height / readerViewBounds.height
height = rect.width / readerViewBounds.width
return CGRect(x: x, y: y, width: width, height: height)
}
/// ๅผน็ช
func showAlert(title: String,
message: String,
cancelBlock: @escaping (() -> Void) = {},
isNeedConfirm: Bool = false,
confirmTitle: String = "็กฎๅฎ",
confirmBlock: @escaping (() -> Void) = {}) {
let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
var cancelTitle = "็ฅ้ไบ"
if isNeedConfirm {
cancelTitle = "ๅๆถ"
let okAction = UIAlertAction.init(title: confirmTitle, style: .default) { (_) in
confirmBlock()
}
alert.addAction(okAction)
}
let cancelAction = UIAlertAction.init(title: cancelTitle, style: .cancel) { (_) in
cancelBlock()
}
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
func showResult(text: String?) {
let alert = UIAlertController.init(title: "็กฎ่ฎค", message: "่ฏทๆๅจ็กฎ่ฎค็ปๆ", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = text
}
let okAction = UIAlertAction(title: "็กฎ่ฎค", style: .default) { (action) in
guard let textField = alert.textFields?.first, let confirmedText = textField.text else {
return
}
self.scanResult?(confirmedText)
self.backToPop()
}
let cancelAction = UIAlertAction(title: "้ๆฐๆซๆ", style: .cancel) { (action) in
self.qrScanAnimation()
if let session = self.session, !session.isRunning {
session.startRunning()
}
}
alert.addAction(cancelAction)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
extension QRCodeScanVC: AVCaptureMetadataOutputObjectsDelegate {
/// ่ทๅไบ็ปด็ ๆซๆ็ปๆ
///
/// - Parameters:
/// - output: ๆต่พๅบ
/// - metadataObjects: ๅ
ๆฐๆฎ
/// - connection: ๆต่ฟๆฅ
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if (metadataObjects.count == 0) {
return
}
if metadataObjects.count > 0 {
// ๅๆญขไผ่ฏ
session?.stopRunning()
// ่ทๅๆซๆๆฐๆฎ
guard let metadataObject = metadataObjects[0] as? AVMetadataMachineReadableCodeObject, let str = metadataObject.stringValue else {
return
}
// ่ตๅผๅญ็ฌฆไธฒ
qrCodeString = str
showResult(text: str)
}
}
}
extension QRCodeScanVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: - imagePickerController delegate
/**
* ่ฏปๅ้ๆฉ็ๅพ็่ฟ่กไบ็ปด็ ่ฏๅซ
*
* @param picker ๅพ็้ๆฉๆงๅถๅจ
* @param info ้ๆฉๆฐๆฎ
*/
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// 1.่ทๅ้ๆฉ็ๅพ็
guard let srcImage = info[UIImagePickerControllerOriginalImage] as? UIImage, let cgImage = srcImage.cgImage else {
return
}
// 2.ๅๅงๅไธไธช็ๆตๅจ
guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) else {
return
}
picker.dismiss(animated: true, completion: {
// ็ๆตๅฐ็็ปๆๆฐ็ป
let features = detector.features(in: CIImage(cgImage: cgImage))
if features.count >= 1 {
// ็ปๆๅฏน่ฑก
let feature = features[0] as? CIQRCodeFeature
let scannedResult: String? = feature?.messageString
// ่ตๅผๅญ็ฌฆไธฒ
self.qrCodeString = scannedResult
self.showAlert(title: "ๆซๆ็ปๆ", message: self.qrCodeString ?? "")
} else {
self.showAlert(title: "ๆ็คบ", message: "่ฏฅๅพ็ๆฒกๆๅ
ๅซไบ็ปด็ ๏ผ")
}
})
}
}
|
//
// Thumbnail.swift
// PlumTestTask
//
// Created by Adrian ลliwa on 24/06/2020.
// Copyright ยฉ 2020 sliwa.adrian. All rights reserved.
//
import Foundation
struct Thumbnail: Codable {
let path: String
let `extension`: String
}
|
import Flutter
import UIKit
import WeScan
public class SwiftEdgeDetectionPlugin: NSObject, FlutterPlugin, UIApplicationDelegate {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "edge_detection", binaryMessenger: registrar.messenger())
let instance = SwiftEdgeDetectionPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
registrar.addApplicationDelegate(instance)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if (call.method == "edge_detect")
{
if let viewController = UIApplication.shared.delegate?.window??.rootViewController as? FlutterViewController {
let destinationViewController = HomeViewController()
destinationViewController._result = result
viewController.present(destinationViewController,animated: true,completion: nil);
}
}
}
}
|
//
// ForecastCollectionViewCell.swift
// Weather Plus
//
// Created by joe_mac on 01/31/2021.
//
import UIKit
class ForecastCollectionViewCell: UICollectionViewCell {
// MARK:- IBOutlets
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var weatherIconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func generateCell(weather: HourlyForecast) {
timeLabel.text = weather.date.time()
weatherIconImageView.image = getWeatherIcon(for: weather.weatherIcon)
tempLabel.text = String(format: "%.0f%@", weather.temp, returnTempFormatFromUserDefaults())
}
}
|
//
// AppDelegate.swift
// MacQQ
//
// Created by sycf_ios on 2017/4/19.
// Copyright ยฉ 2017ๅนด shibiao. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var mainWindowController: NSWindowController?
func applicationDidFinishLaunching(_ aNotification: Notification) {
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
self.mainWindowController?.window?.makeKeyAndOrderFront(self)
return true
}
}
|
//: [Previous](@previous)
//:
//: ## Properties
//:
//: Properties associate values with a particular class, structure, or enumeration.
//:
//: ----
//: ### Stored Properties
//:
//: In its simplest form, a stored property is a constant or variable that is stored as part of an instance of a particular class or structure.
//: ----
//: ### Stored Properties of Constant Structure Instances
//:
//: If you create an instance of a structure and assign that instance to a constant, you cannot modify the instanceโs properties, even if they were declared as variable properties
//:
//: When an instance of a value type is marked as a constant, so are all of its properties
//:
//: If you assign an instance of a reference type to a constant, you can still change that instanceโs variable properties
//: ----
//: ### Lazy Stored Properties
//:
//: A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.
//: ----
//: ### Stored Properties and Instance Variables
//:
//: A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.
//: ----
//: ### Computed Properties
//:
//: In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value.
//: ----
//: ### Shorthand Setter Declaration
//:
//: If a computed propertyโs setter does not define a name for the new value to be set, a default name of newValue is used.
//: ----
//: ### Read-Only Computed Properties
//:
//: A computed property with a getter but no setter is known as a read-only computed property.
//:
//: You must declare computed propertiesโincluding read-only computed propertiesโas variable properties with the var keyword, because their value is not fixed.
//: ----
//: ### Property Observers
//:
//: Property observers observe and respond to changes in a propertyโs value.
//:
//: If you implement a willSet observer, itโs passed the new property value as a constant parameter.
//:
//: Similarly, if you implement a didSet observer, itโs passed a constant parameter containing the old property value.
//: ----
//: ### Global and Local Variables
//:
//: Global variables are variables that are defined outside of any function, method, closure, or type context.
//:
//: Local variables are variables that are defined within a function, method, or closure context.
//:
//: Stored variables, like stored properties, provide storage for a value of a certain type and allow that value to be set and retrieved.
//:
//: You can also define computed variables and define observers for stored variables, in either a global or local scope.
//:
//: Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties (No need for lazy keyword).
//:
//: Local constants and variables are never computed lazily.
//: ----
//: ### Type properties
//:
//: You can also define properties that belong to the type itself, not to any one instance of that type.
//: ----
//: ### Type Property Syntax
//:
//: You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclassโs implementation.
//: ----
//: ### Querying and Setting Type properties
//:
//: Type properties are queried and set with dot syntax, just like instance properties.
//:
//: [Next](@next)
|
//
// ImageCollectionViewCell.swift
// PersistantImageGallery
//
// Created by Geoffry Gambling on 7/23/19.
// Copyright ยฉ 2019 Geoffry Gambling. All rights reserved.
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
var imageInfo: ImageInfo? {
didSet {
imageURL = URL(string: (imageInfo?.imageUrl)!)
}
}
var imageURL: URL? {
didSet {
if imageURL != nil {
fetchImage(url: imageURL!)
}
}
}
var image: UIImage? {
didSet {
cellImageView.image = image
}
}
@IBOutlet weak var cellImageView: UIImageView!
func fetchImage(url: URL) {
//Activity Indicator
let activityIndicator = UIActivityIndicatorView(style: .gray)
cellImageView.addSubview(activityIndicator)
activityIndicator.frame = cellImageView.bounds
activityIndicator.center = cellImageView.center
activityIndicator.startAnimating()
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
let imageData = try? Data(contentsOf: url)
let fetchedImage = UIImage(data: imageData!)
DispatchQueue.main.async {
self?.image = fetchedImage
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
}
}
}
}
|
var s = readLine()?
var dic : s.split(separator: " ")
print((dic.map{Int($0)!}.reduce(0) {$0 + $1})!)
|
//
// ReposTableViewController.swift
// github-repo-starring-swift
//
// Created by Haaris Muneer on 6/28/16.
// Copyright ยฉ 2016 Flatiron School. All rights reserved.
//
import UIKit
class ReposTableViewController: UITableViewController {
let store = ReposDataStore.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer))
self.tableView.accessibilityLabel = "tableView"
self.tableView.accessibilityIdentifier = "tableView"
store.getRepositoriesWithCompletion {
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.store.repositories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "repoCell", for: indexPath)
let repository:GithubRepository = self.store.repositories[(indexPath as NSIndexPath).row]
cell.textLabel?.text = repository.fullName
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let repository = self.store.repositories[(indexPath).row]
let repoName = repository.fullName
store.toggleStarStatus(name: repository) { (isStarred) in
switch isStarred {
case true:
let alertController = UIAlertController(title: "๐Starred!๐", message: "You just starred \(repoName)", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Okey Doke", style: .default, handler: nil)
alertController.addAction(alertAction)
self.present(alertController, animated: true, completion: nil)
case false:
let alertController = UIAlertController(title: "Unstarred ๐", message: "You just unstarred \(repoName)", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Okey Doke", style: .default, handler: nil)
alertController.addAction(alertAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
func testFunctionInsideTVC(passedString: String) {
}
func promptForAnswer() {
let alert = UIAlertController(title: "Search", message: "What are you looking for?", preferredStyle: .alert)
alert.addTextField()
let submitAction = UIAlertAction(title: "Submit", style: .default) { [unowned self, alert] (action: UIAlertAction!) in
let answer = alert.textFields![0]
print("search query = \(answer.text!)")
// self.testFunctionInsideTVC(passedString: answer.text!)
self.store.getSearchRepo(search: answer.text!) {
OperationQueue.main.addOperation {
self.tableView.reloadData()
}
}
}
alert.addAction(submitAction)
self.present(alert, animated: true) {
print("\n\npresent completion\n\n")
}
}
}
|
//
// ContentViewTests.swift
// InstaframeTests
//
// Created by Jean-Baptiste Waring on 2021-03-18.
//
import Foundation
import XCTest
import ViewInspector
import SwiftUI
@testable import Instaframe
class ContentViewTests: XCTestCase {
func testHome() throws {
let currentUser = Instaframe.InstaUser(context: (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)
let sut = ContentView(showSettings: .constant(false), currentUser: .constant(currentUser))
let exp = XCTestExpectation(description: #function)
sut.inspection.inspect(after: 0) {view in
try view.actualView().currentUser = InstaUser(context: try view.actualView().managedObjectContext)
XCTAssertEqual(try view.actualView().inspect().vStack(0).hStack(0).text(0).string(), "Instaframe")
try view.vStack(0).hStack(0).button(3).tap()
exp.fulfill()
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.1)
}
}
extension ContentView: Inspectable { }
extension InspectionContentView: InspectionEmissary where ContentView: Inspectable { }
|
//
// BaseViewController.swift
// HISmartPhone
//
// Created by MACOS on 12/19/17.
// Copyright ยฉ 2017 MACOS. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = Theme.shared.defaultBGColor
self.setupView()
}
func setupView() {
}
}
|
//
// ContentView.swift
// CoursesModelView
//
// Created by Abilio Gambim Parada on 09/12/2019.
// Copyright ยฉ 2019 Abilio Gambim Parada. All rights reserved.
//
import UIKit
import SwiftUI
struct ContentView: View{
@EnvironmentObject var settings: UserSettings
@ObservedObject var coursersVM = CoursesViewModel()
@State private var isPressed = false
var body: some View{
NavigationView{
ListOrEmpthy(coursersVM: coursersVM)
.navigationBarTitle("Courses")
.navigationBarItems(trailing:
HStack{
Button(action: {
self.coursersVM.fetchCourses()
self.isPressed = !self.isPressed
self.settings.score += 1
}, label: {
Text("Fetch \(self.settings.score)")
})
.foregroundColor(.white)
.padding(6)
.background(isPressed ? Color.green : Color.red)
.cornerRadius(12)
if(coursersVM.courses.isEmpty == false){
Button(action: {
self.coursersVM.orderCoursesByLowerPrice()
}) {
Text("Sort")
}
EditButton()
}
}
).animation(.easeIn)
}
}
}
struct ListOrEmpthy: View {
@ObservedObject var coursersVM = CoursesViewModel()
var body: some View{
Group{
if(coursersVM.courses.isEmpty){
VStack{
Text("Press Fetch")
}
} else{
List {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 10) {
ForEach(coursersVM.courses) { course in
NavigationLink(destination: DetailContentView(course: course)) {
HorizontalCardCell(course: course)
}.buttonStyle(PlainButtonStyle())
}
}.padding(.horizontal, 16)
}.padding(.horizontal, -16)
ForEach(coursersVM.courses){ course in
NavigationLink(destination: DetailContentView(course: course)) {
CardCell(course: course)
}
}.onDelete(perform: delete)
.onMove(perform: move)
}
}
}
}
func move(from source: IndexSet, to destination: Int) {
coursersVM.courses.move(fromOffsets: source, toOffset: destination)
}
func delete(at offsets: IndexSet) {
coursersVM.courses.remove(atOffsets: offsets)
}
}
struct HorizontalCardCell: View {
var course: Course!
var body: some View{
VStack{
ImageView(withURL: course.bannerUrl)
.scaledToFill()
.clipShape(Circle())
.overlay(Circle().stroke(Color.gray, lineWidth: 4))
.frame(width: 150, height: 150, alignment: .center)
VStack{
Text(course.name)
.bold()
.font(.callout)
.lineLimit(1)
.frame(width: 120, height: 20, alignment: .center)
.truncationMode(.tail)
PriceCell(price: course.price)
}
}.padding(10)
.background(Color(UIColor(red:0.76, green:0.76, blue:0.78, alpha:1.0)))
.cornerRadius(4, antialiased: true)
}
}
struct CardCell: View {
var course: Course!
var body: some View{
HStack {
VStack(alignment: .leading){
Text(course.name)
.foregroundColor(.primary)
.font(.headline)
.padding(4)
Divider()
PriceCell(price: course.price)
}
ImageView(withURL: course.bannerUrl)
.frame(width: 100, height: 100, alignment: .center)
}.padding(10)
.background(Color.secondary, alignment:.leading)
.cornerRadius(12)
}
}
struct PriceCell: View {
var price = 0
var body: some View{
Group{
if(price > 75){
TextPrice(price: price, color: Color.red)
} else if(price > 50){
TextPrice(price: price, color: Color.orange)
} else if(price > 25){
TextPrice(price: price, color: Color.yellow)
} else{
TextPrice(price: price, color: Color.green)
}
}
}
}
struct TextPrice: View {
var price: Int
var color: Color
var body: some View{
Text("Price: $\(price)")
.font(.subheadline)
.foregroundColor(.secondary)
.background(color, alignment: .leading)
.cornerRadius(4)
.padding(4)
}
}
struct ImageView: View {
@ObservedObject var imageLoader: ImageLoader
init(withURL url:String) {
imageLoader = ImageLoader(urlString:url)
}
var body: some View {
Group {
if imageLoader.data != nil{
Image(uiImage: UIImage(data:imageLoader.data!) ?? UIImage())
.resizable()
.aspectRatio(contentMode: .fit)
} else{
ActivityIndicator()
}
}
}
}
struct ActivityIndicator: UIViewRepresentable {
typealias UIView = UIActivityIndicatorView
fileprivate var configuration = { (indicator: UIView) in }
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIView {
UIView()
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<Self>) {
uiView.startAnimating()
configuration(uiView)
}
}
|
//
// ZoomViewController.swift
// BlackStarWearProject
//
// Created by ะะปะฐะดะธัะปะฐะฒ ะะธัะฝัะบะพะฒ on 13.07.2021.
//
import UIKit
class ZoomViewController: UIViewController, UICollectionViewDelegate {
var itemData: SubCategoryItems? = nil
var imagesCell = Network.networkAccess.cardResourse
var placeHold = Network.networkAccess.placeHolder
@IBAction func cancelButton(_ sender: Any) {
dismiss(animated: true)
}
@IBOutlet weak var zoomCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
zoomCollectionView.delegate = self
zoomCollectionView.dataSource = self
}
}
extension ZoomViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if itemData?.productImages?.isEmpty == true {
return 1
} else {
return itemData?.productImages?.count ?? 1
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "zoomCell", for: indexPath) as! ZoomCollectionViewCell
cell.zoomCell.kf.indicatorType = .activity
if itemData?.productImages?.isEmpty == true {
let itmData = itemData?.mainImage ?? ""
Network.networkAccess.getImage(url: API.mainURL + itmData , complition: { resourse in
self.placeHold = resourse
cell.zoomCell.kf.setImage(with: self.placeHold, options: [.transition(.fade(0.7))])
})
} else {
let indexImg = itemData?.productImages?[indexPath.row].imageURL ?? ""
Network.networkAccess.getImage(url: API.mainURL + indexImg) { resourse in
self.imagesCell.append(resourse)
cell.zoomCell.kf.setImage(with: self.imagesCell[indexPath.row], options: [.transition(.fade(0.7))])
}
}
CategoriesCell.access.cornerRadius(view: cell.zoomCell)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frameVC = collectionView.frame
let wCell = frameVC.width
let hCell = frameVC.height
return CGSize(width: wCell, height: hCell)
}
}
|
//
// AddPublicTransportDelegate.swift
// Travel Companion
//
// Created by Stefan Jaindl on 17.09.18.
// Copyright ยฉ 2018 Stefan Jaindl. All rights reserved.
//
import CodableFirebase
import Firebase
import Foundation
import UIKit
class AddPublicTransportDelegate: NSObject, AddTransportDelegate {
var weekDayToDayFlagMap: [Int: Int] = [1: 0x01, /* Sunday */
2: 0x02, /* Monday */
3: 0x04, /* Tuesday */
4: 0x08, /* Wednesday */
5: 0x10, /* Thursday */
6: 0x20, /* Friday */
7: 0x40] /* Saturday */
struct CellData {
var opened = Bool()
var route: Route?
var segment: Segment?
var agency: SurfaceAgency?
var surfaceStops = [SurfaceStop]()
}
var cellData = [CellData]()
func initCellData(searchResponse: SearchResponse, date: Date) {
for route in searchResponse.routes {
for segment in route.segments {
if let stops = segment.stops, let agencies = segment.agencies {
for agency in agencies {
if dateIsRelevant(date, in: agency) {
cellData.append(CellData(opened: false, route: route, segment: segment, agency: agency, surfaceStops: stops))
}
}
} else {
//there are no stops or agencies --> it's potentially a car drive
cellData.append(CellData(opened: false, route: route, segment: segment, agency: nil, surfaceStops: []))
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return cellData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellData[section].opened ? cellData[section].surfaceStops.count + 1 : 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, searchResponse: SearchResponse) -> UITableViewCell {
let agency = cellData[indexPath.section].agency
let segment = cellData[indexPath.section].segment!
var cellReuseId = Constants.ReuseIds.transportDetailWithoutImageCell
if let agency = agency, searchResponse.agencies[agency.agency].icon?.url != nil {
cellReuseId = Constants.ReuseIds.transportDetailWithImageCell
}
if indexPath.row == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId) else {
return UITableViewCell()
}
let route = cellData[indexPath.section].route!
let depPlace = searchResponse.places[route.depPlace]
let arrPlace = searchResponse.places[route.arrPlace]
cell.imageView?.image = nil
cell.textLabel?.text = "\(route.name): \(depPlace.shortName) - \(arrPlace.shortName)"
var detailText = String(format: "km".localized(), segment.distance)
if let agency = agency {
detailText = searchResponse.agencies[agency.agency].name + ", " + detailText
if let agencyUrl = searchResponse.agencies[agency.agency].icon?.url, let url = URL(string: "\(Rome2RioConstants.UrlComponents.urlProtocol)://\(Rome2RioConstants.UrlComponents.domain)\(agencyUrl)") {
((try? cell.imageView?.image = UIImage(data: Data(contentsOf: url))) as ()??)
}
}
cell.detailTextLabel?.text = detailText
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId) else {
return UITableViewCell()
}
cell.imageView?.image = nil
let stop = cellData[indexPath.section].surfaceStops[indexPath.row - 1]
var duration = 0
if let stopDuration = stop.stopDuration {
duration += Int(stopDuration)
}
if let transitDuration = stop.transitDuration {
duration += Int(transitDuration)
}
if duration == 0 {
duration = segment.transitDuration + segment.transferDuration
}
let place = searchResponse.places[stop.place]
cell.textLabel?.text = place.shortName
var detailText = String(format: "duration".localized(), duration / 60, duration % 60)
if let prices = segment.indicativePrices, prices.count > 0 {
if let name = prices[0].name {
detailText += " (\(name): "
} else {
detailText += " ("
}
if let minPrice = prices[0].nativePriceLow, let maxPrice = prices[0].nativePriceHigh {
detailText += "\(minPrice) - \(maxPrice) \(prices[0].currency))"
} else {
detailText += "โ\(prices[0].price) \(prices[0].currency))"
}
}
cell.detailTextLabel?.text = detailText
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath, searchResponse: SearchResponse, date: Date, firestoreDbReference: CollectionReference, plan: Plan, controller: UIViewController, popToController: UIViewController) {
let stops = cellData[indexPath.section].surfaceStops
let route = self.cellData[indexPath.section].route!
let segment = self.cellData[indexPath.section].segment!
let agency = self.cellData[indexPath.section].agency
if indexPath.row == 0 {
let sections = IndexSet.init(integer: indexPath.section)
if cellData[indexPath.section].surfaceStops.count > 0 { //only expand/collapse if there are stops
cellData[indexPath.section].opened = !cellData[indexPath.section].opened
tableView.reloadSections(sections, with: .fade)
} else {
let alert = UIAlertController(title: "addPublicTransport".localized(), message: "addRoute?".localized(), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "addRoute".localized(), style: .default, handler: { _ in
self.persistPublicTransport(nil, segment: segment, agency: agency, route: route, searchResponse: searchResponse, date: date, firestoreDbReference: firestoreDbReference, plan: plan, controller: popToController)
controller.navigationController?.popToViewController(popToController, animated: true)
}))
alert.addAction(UIAlertAction(title: "cancel".localized(), style: .default, handler: { _ in
controller.dismiss(animated: true, completion: nil)
}))
controller.present(alert, animated: true, completion: nil)
}
} else {
//choose single flight or whole leg?
let alert = UIAlertController(title: "addPublicTransport".localized(), message: "addStopOrRoute?".localized(), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "singleStop".localized(), style: .default, handler: { _ in
let stop = self.cellData[indexPath.section].surfaceStops[indexPath.row - 1]
self.persistPublicTransport(stop, segment: segment, agency: agency, route: route, searchResponse: searchResponse, date: date, firestoreDbReference: firestoreDbReference, plan: plan, controller: popToController)
controller.navigationController?.popToViewController(popToController, animated: true)
UiUtils.showToast(message: "addedRoute".localized(), view: popToController.view)
}))
alert.addAction(UIAlertAction(title: "wholeRoute".localized(), style: .default, handler: { _ in
for stop in stops {
self.persistPublicTransport(stop, segment: segment, agency: agency, route: route, searchResponse: searchResponse, date: date, firestoreDbReference: firestoreDbReference, plan: plan, controller: popToController)
}
controller.navigationController?.popToViewController(popToController, animated: true)
UiUtils.showToast(message: "addedRoute".localized(), view: popToController.view)
}))
alert.addAction(UIAlertAction(title: "cancel".localized(), style: .default, handler: { _ in
controller.dismiss(animated: true, completion: nil)
}))
controller.present(alert, animated: true, completion: nil)
}
}
func dateIsRelevant(_ date: Date, in agency: SurfaceAgency) -> Bool {
let weekdayToTravel = Calendar.current.component(.weekday, from: date)
guard let operatingDays = agency.operatingDays else {
return true //this is potentially a rideshare or similar, where no fixed operating days are available. This is ok.
}
guard let weekdayBitMask = weekDayToDayFlagMap[weekdayToTravel] else {
return false
}
return weekdayBitMask & operatingDays > 0
}
func persistPublicTransport(_ stop: SurfaceStop?, segment: Segment, agency: SurfaceAgency?, route: Route, searchResponse: SearchResponse, date: Date, firestoreDbReference: CollectionReference, plan: Plan, controller: UIViewController) {
let depPlace = searchResponse.places[route.depPlace].shortName
let arrPlace = searchResponse.places[route.arrPlace].shortName
var agencyName: String?
var agencyUrl: String?
var stopDuration: Double?
var transitDuration: Double?
var stopPlace: String?
if let agency = agency {
agencyName = searchResponse.agencies[agency.agency].name
if let url = searchResponse.agencies[agency.agency].icon?.url {
agencyUrl = url
}
}
if let stop = stop {
stopPlace = searchResponse.places[stop.place].shortName
stopDuration = stop.stopDuration
transitDuration = stop.transitDuration
}
let vehicle = searchResponse.vehicles[segment.vehicle].name
let publicTransport = PublicTransport(date: Timestamp(date: date), vehicle: vehicle, depPlace: depPlace, arrPlace: arrPlace, agencyName: agencyName, agencyUrl: agencyUrl, stopDuration: stopDuration, transitDuration: transitDuration, stopPlace: stopPlace)
let docData = try! FirestoreEncoder().encode(publicTransport)
FirestoreClient.addData(collectionReference: firestoreDbReference, documentName: publicTransport.id, data: docData) { (error) in
if let error = error {
debugPrint("Error adding document: \(error)")
} else {
debugPrint("Document added")
plan.publicTransport.append(publicTransport)
if let controller = controller as? PlanDetailViewController {
//we have to reload the data here as we have already popped the stack back to PlanDetailViewController
//and we add data asynchronously here
controller.tableView.reloadData()
}
}
}
}
func description() -> String {
return "publicTransport".localized()
}
}
|
//
// CommitDetails.swift
// Gopher
//
// Created by Dane Acena on 8/15/21.
//
import SwiftUI
struct CommitDetails: View {
var body: some View{
Text()
}
}
struct CommitDetails_Previews: PreviewProvider {
static var previews: some View {
CommitDetails()
}
}
|
public protocol MediaType {
associatedtype Entity: RawRepresentable where Entity.RawValue == String
associatedtype Attribute: RawRepresentable where Attribute.RawValue == String
}
public struct All: MediaType {
public enum Entity: String {
case movie
case album
case artist = "allArtist"
case podcast
case musicVideo
case mix
case audiobook
case tvSeason
case track = "allTrack"
}
public enum Attribute: String {
case actor = "actorTerm"
case language = "languageTerm"
case allArtist = "allArtistTerm"
case episode = "tvEpisodeTerm"
case shortFilm = "shortFilmTerm"
case director = "directorTerm"
case releaseYear = "releaseYearTerm"
case title = "titleTerm"
case featureFilm = "featureFilmTerm"
case ratingIndex = "ratingIndex"
case keywords = "keywordsTerm"
case description = "descriptionTerm"
case author = "authorTerm"
case genre = "genreIndex"
case mix = "mixTerm"
case track = "allTrackTerm"
case artist = "artistTerm"
case composer = "composerTerm"
case season = "tvSeasonTerm"
case producer = "producerTerm"
case ratingTerm = "ratingTerm"
case song = "songTerm"
case movieArtist = "movieArtistTerm"
case show = "showTerm"
case movie = "movieTerm"
case album = "albumTerm"
}
}
public enum Movie: MediaType {
public enum Entity: String {
case movie
case artist = "movieArtist"
}
public enum Attribute: String {
case actor = "actorTerm"
case genre = "genreIndex"
case artist = "artistTerm"
case shortFilm = "shortFilmTerm"
case producer = "producerTerm"
case ratingTerm = "ratingTerm"
case director = "directorTerm"
case releaseYear = "releaseYearTerm"
case featureFilm = "featureFilmTerm"
case movieArtist = "movieArtistTerm"
case movie = "movieTerm"
case ratingIndex = "ratingIndex"
case description = "descriptionTerm"
}
}
public struct Music: MediaType {
public enum Entity: String {
case artist = "musicArtist"
case track = "musicTrack"
case album
case musicVideo
case mix
case song
}
public enum Attribute: String {
case mix = "mixTerm"
case genre = "genreIndex"
case artist = "artistTerm"
case composer = "composerTerm"
case album = "albumTerm"
case rating = "ratingIndex"
case song = "songTerm"
}
}
public struct MusicVideo: MediaType {
public enum Entity: String {
case musicVideo
case artist = "musicArtist"
}
public enum Attribute: String {
case genre = "genreIndex"
case artist = "artistTerm"
case album = "albumTerm"
case rating = "ratingIndex"
case song = "songTerm"
}
}
public struct Podcast: MediaType {
public enum Entity: String {
case podcast
case author = "podcastAuthor"
}
public enum Attribute: String {
case title = "titleTerm"
case language = "languageTerm"
case author = "authorTerm"
case genre = "genreIndex"
case artist = "artistTerm"
case rating = "ratingIndex"
case keywords = "keywordsTerm"
case description = "descriptionTerm"
}
}
public struct ShortFilm: MediaType {
public enum Entity: String {
case shortFilm
case artist = "shortFilmArtist"
}
public enum Attribute: String {
case genre = "genreIndex"
case artist = "artistTerm"
case shortFilm = "shortFilmTerm"
case rating = "ratingIndex"
case description = "descriptionTerm"
}
}
public struct Software: MediaType {
public enum Entity: String {
case software
case iPadSoftware
case macSoftware
}
public enum Attribute: String {
case softwareDeveloper
}
}
public struct TVShow: MediaType {
public enum Entity: String {
case episode = "tvEpisode"
case season = "tvSeason"
}
public enum Attribute: String {
case genre = "genreIndex"
case episode = "tvEpisodeTerm"
case show = "showTerm"
case season = "tvSeasonTerm"
case rating = "ratingIndex"
case description = "descriptionTerm"
}
}
public struct AudioBook: MediaType {
public enum Entity: String {
case audiobook
case author = "audiobookAuthor"
}
public enum Attribute: String {
case title = "titleTerm"
case author = "authorTerm"
case genre = "genreIndex"
case rating = "ratingIndex"
}
}
public struct EBook: MediaType {
public enum Entity: String {
case ebook
}
// FIXME: Speculative
public enum Attribute: String {
case title = "titleTerm"
case author = "authorTerm"
case genre = "genreIndex"
case rating = "ratingIndex"
}
}
|
//
// User.swift
// iOS-MVVMC-Architecture
//
// Created by Nishinobu.Takahiro on 2017/04/24.
// Copyright ยฉ 2017ๅนด hachinobu. All rights reserved.
//
import Foundation
import ObjectMapper
struct User {
let createdAt: String
let isDefaultProfile: Bool
let defaultProfileImage: Bool
let description: String?
let favouritesCount: Int
let following: Bool?
let followersCount: Int
let friendsCount: Int
let id: Int
let idStr: String
let lang: String
let listedCount: Int
let location: String?
let name: String
let profileBackgroundColor: String
let profileBackgroundImageHttpsUrl: String?
let profileBannerUrl: String?
let profileImageHttpsUrl: String
let profileTextColor: String
let protected: Bool
let screenName: String
let statusesCount: Int
let url: String?
let utcOffset: Int?
}
extension User: ImmutableMappable {
public init(map: Map) throws {
createdAt = try map.value("created_at")
isDefaultProfile = try map.value("default_profile")
defaultProfileImage = try map.value("default_profile_image")
description = try? map.value("description")
favouritesCount = try map.value("favourites_count")
following = try? map.value("following")
followersCount = try map.value("followers_count")
friendsCount = try map.value("friends_count")
id = try map.value("id")
idStr = try map.value("id_str")
lang = try map.value("lang")
listedCount = try map.value("listed_count")
location = try? map.value("location")
name = try map.value("name")
profileBackgroundColor = try map.value("profile_background_color")
profileBackgroundImageHttpsUrl = try? map.value("profile_background_image_url_https")
profileBannerUrl = try? map.value("profile_banner_url")
profileImageHttpsUrl = try map.value("profile_image_url_https")
profileTextColor = try map.value("profile_text_color")
protected = try map.value("protected")
screenName = try map.value("screen_name")
statusesCount = try map.value("statuses_count")
url = try? map.value("url")
utcOffset = try? map.value("utc_offset")
}
}
|
//
// ListAndNavigation.swift
// SwiftUIEx
//
// Created by ์กฐ์ค์ on 2020/08/20.
// Copyright ยฉ 2020 ์กฐ์ค์. All rights reserved.
//
import SwiftUI
struct ListAndNavigation: View {
let cats = Cats.all() //๋๋ฏธ๋ก ๋ง๋ ๋ฐ์ดํฐ๋ฅผ ๋ชจ๋ ๊ฐ์ ธ์ต๋๋ค.
var body: some View {
NavigationView {
List(self.cats, id: \.name) { cat in
NavigationLink(destination: CatDetail(cats: cat)) {
CatCell(cat: cat)
}
}.navigationBarTitle("๊ณ ์์ด์ ๋ค์ํ ์ข
")
}
}
}
struct CatCell: View {
let cat: Cats
var body: some View {
HStack {
Image(cat.imageURL)
.resizable()
.frame(width: 100, height: 100)
.cornerRadius(16)
VStack(alignment: .leading) {
Text(cat.name).font(.largeTitle)
Text("\(cat.number)")
}
}
}
}
struct ListAndNavigation_Previews: PreviewProvider {
static var previews: some View {
ListAndNavigation()
}
}
|
//
// CTFStudyConstants.swift
// Impulse
//
// Created by James Kizer on 2/23/17.
// Copyright ยฉ 2017 James Kizer. All rights reserved.
//
import UIKit
class CTFStudyConstants {
static let k1MinuteInterval: TimeInterval = 60.0
static let k1HourInterval: TimeInterval = CTFStudyConstants.k1MinuteInterval * 60.0
static let k1DayInterval: TimeInterval = 24.0 * CTFStudyConstants.k1HourInterval
static let kNumberOfDaysForFinalSurvey = 21
static let k21DaySurveyDelayInterval: TimeInterval = Double(CTFStudyConstants.kNumberOfDaysForFinalSurvey) * CTFStudyConstants.k1DayInterval
static let kDailySurveyNotificationWindowBeforeInterval: TimeInterval = 0.0
static let kDailySurveyNotificationWindowAfterInterval: TimeInterval = 30.0 * CTFStudyConstants.k1MinuteInterval
static let kDailySurveyTimeBeforeInterval: TimeInterval = 2.0 * CTFStudyConstants.k1HourInterval
static let kDailySurveyTimeAfterInterval: TimeInterval = 6.0 * CTFStudyConstants.k1HourInterval
static let kDailySurveyDelaySinceBaselineTimeInterval: TimeInterval = 0.0
static let kSecondaryNotificationDelay: TimeInterval = 2.0 * CTFStudyConstants.k1HourInterval
static let kMorningNotificationIdentifer: String = "MorningNotification"
static let kMorningNotificationIdentifer2nd: String = "MorningNotification2nd"
static let kEveningNotificationIdentifer: String = "EveningNotification"
static let kEveningNotificationIdentifer2nd: String = "EveningNotification2nd"
static let k21DayNotificationIdentifier: String = "21DayNotification"
static let k21DayNotificationIdentifier2nd: String = "21DayNotification2nd"
static let NotificationIdentifiers = [kMorningNotificationIdentifer, kMorningNotificationIdentifer2nd,
kEveningNotificationIdentifer, kEveningNotificationIdentifer2nd,
k21DayNotificationIdentifier, k21DayNotificationIdentifier2nd]
static let kMorningNotificationText: String = "Hey, it's time to take your morning survey!"
static let kEveningNotificationText: String = "Hey, it's time to take your evening survey!"
static let k21DayNotificationText: String = "Hey, it's time to take your 21 day survey!"
static let kSessionTokenKey: String = "SessionToken"
static let kPasswordKey: String = "Password"
static let kEmailKey: String = "Email"
static let kBaselineBehaviorResults: String = "BaselineBehaviorResults"
}
|
//
// LUTFilter.swift
// LUTFilter
//
// Created by ็ๆๆฐ on 2019/7/20.
// Copyright ยฉ 2019 wangwenjie. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import OpenGLES
import GLKit
private var vertices: [GLfloat] = [
-1, -1, 0,
1, -1, 0,
-1, 1, 0,
1, 1, 0
]
private var coords: [GLfloat] = [
0, 0,
1, 0,
0, 1,
1, 1
]
//Extensions to pass arguments to GL land
extension Array {
func size () -> Int {
return self.count * MemoryLayout.size(ofValue: self[0])
}
}
extension Int32 {
func __conversion() -> GLenum {
return GLuint(self)
}
func __conversion() -> GLboolean {
return GLboolean(UInt8(self))
}
}
extension Int {
func __conversion() -> Int32 {
return Int32(self)
}
func __conversion() -> GLubyte {
return GLubyte(self)
}
}
public final class LUTFilter {
private var context: EAGLContext!
private var positionSlot: GLuint = GLuint()
private var colorSlot: GLuint = GLuint()
private var programHandle: GLuint = GLuint()
private var offscreenFrameBuffer: GLuint = GLuint()
private var image: UIImage!
private var volume: Float = 1.0;
public init(image: UIImage) {
self.image = image
setupContext()
setUpOffScreenFrameBuffer(image: image)
compileShaders()
}
internal func filteredImage(LUT: UIImage?, volume: Float = 1.0) -> UIImage {
self.volume = min(1.0, max(volume, 0.0))
if let lutImage = LUT {
setTexture(image: image, LUTImage: lutImage)
renderToOFB()
return getImageFromBuffer(width: Int(image.size.width), height: Int(image.size.height))
} else {
return image
}
}
private func setupContext() {
// Just like with CoreGraphics, in order to do much with OpenGL, we need a context.
// Here we create a new context with the version of the rendering API we want and
// tells OpenGL that when we draw, we want to do so within this context.
let api: EAGLRenderingAPI = EAGLRenderingAPI.openGLES2
self.context = EAGLContext(api: api)
if (self.context == nil) {
print("Failed to initialize OpenGLES 2.0 context!")
exit(1)
}
if (!EAGLContext.setCurrent(self.context)) {
print("Failed to set current OpenGL context!")
exit(1)
}
}
private func setUpOffScreenFrameBuffer(image: UIImage) {
glGenFramebuffers(1, &offscreenFrameBuffer)
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), offscreenFrameBuffer)
var texture = GLuint()
glGenTextures(1, &texture)
glBindTexture(GLenum(GL_TEXTURE_2D), texture)
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, GLsizei(image.size.width), GLsizei(image.size.height), 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), nil)
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLfloat(GL_LINEAR))
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLfloat(GL_LINEAR))
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLfloat(GL_CLAMP_TO_EDGE))
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLfloat(GL_CLAMP_TO_EDGE))
glFramebufferTexture2D(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_TEXTURE_2D), texture, 0)
let stauts = glCheckFramebufferStatus(GLenum(GL_FRAMEBUFFER))
if stauts != GLenum(GL_FRAMEBUFFER_COMPLETE) {
print("failed to make complete framebuffer object \(stauts)")
}
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), 0)
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
glViewport(0, 0, GLsizei(image.size.width), GLsizei(image.size.height))
}
private func compileShader(shaderString: String, shaderType: GLenum) -> GLuint {
// Tell OpenGL to create an OpenGL object to represent the shader, indicating if it's a vertex or a fragment shader.
let shaderHandle: GLuint = glCreateShader(shaderType)
if shaderHandle == 0 {
NSLog("Couldn't create shader")
}
// Conver shader string to CString and call glShaderSource to give OpenGL the source for the shader.
var shaderStringUTF8 = (shaderString as NSString).utf8String
var shaderStringLength: GLint = GLint(Int32((shaderString as NSString).length))
glShaderSource(shaderHandle, 1, &shaderStringUTF8, &shaderStringLength)
// Tell OpenGL to compile the shader.
glCompileShader(shaderHandle)
// But compiling can fail! If we have errors in our GLSL code, we can here and output any errors.
var compileSuccess: GLint = GLint()
glGetShaderiv(shaderHandle, GLenum(GL_COMPILE_STATUS), &compileSuccess)
if (compileSuccess == GL_FALSE) {
print("Failed to compile shader!")
// TODO: Actually output the error that we can get from the glGetShaderInfoLog function.
exit(1);
}
return shaderHandle
}
private func compileShaders() {
// Compile our vertex and fragment shaders.
let vertexShader: GLuint = self.compileShader(shaderString: Shaders.vertex, shaderType: GLenum(GL_VERTEX_SHADER))
let fragmentShader: GLuint = self.compileShader(shaderString: Shaders.fragement, shaderType: GLenum(GL_FRAGMENT_SHADER))
// Call glCreateProgram, glAttachShader, and glLinkProgram to link the vertex and fragment shaders into a complete program.
programHandle = glCreateProgram()
glAttachShader(programHandle, vertexShader)
glAttachShader(programHandle, fragmentShader)
glLinkProgram(programHandle)
// Check for any errors.
var linkSuccess: GLint = GLint()
glGetProgramiv(programHandle, GLenum(GL_LINK_STATUS), &linkSuccess)
if (linkSuccess == GL_FALSE) {
print("Failed to create shader program!")
// TODO: Actually output the error that we can get from the glGetProgramInfoLog function.
exit(1);
}
// Call glUseProgram to tell OpenGL to actually use this program when given vertex info.
glUseProgram(programHandle)
glDeleteShader(vertexShader)
glDeleteShader(fragmentShader)
// Finally, call glGetAttribLocation to get a pointer to the input values for the vertex shader, so we
// can set them in code. Also call glEnableVertexAttribArray to enable use of these arrays (they are disabled by default).
self.positionSlot = GLuint(glGetAttribLocation(programHandle, "position"))
self.colorSlot = GLuint(glGetAttribLocation(programHandle, "a_texCoordIn"))
glVertexAttribPointer(self.positionSlot, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 0, vertices)
glVertexAttribPointer(self.colorSlot, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 0, coords)
glEnableVertexAttribArray(self.positionSlot)
glEnableVertexAttribArray(self.colorSlot)
}
private func setTexture(image: UIImage, LUTImage: UIImage) {
glActiveTexture(GLenum(GL_TEXTURE0))
let textName = getTextureFromImage(sourceImage: image, translate: true)
glBindTexture(GLenum(GL_TEXTURE_2D), textName)
glUniform1i(glGetUniformLocation(programHandle,"inputImageTexture"), 0)
glActiveTexture(GLenum(GL_TEXTURE1))
let LUTName = getTextureFromImage(sourceImage: LUTImage, translate: false)
glBindTexture(GLenum(GL_TEXTURE_2D), LUTName)
glUniform1i(glGetUniformLocation(programHandle, "inputImageTexture2"), 1)
glUniform1f(glGetUniformLocation(programHandle, "volume"), self.volume)
}
private func renderToOFB() {
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), offscreenFrameBuffer)
glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, 4)
}
private func getTextureFromImage(sourceImage: UIImage, translate: Bool) -> GLuint {
guard let textureImage = sourceImage.cgImage else {
print("Failed to load image")
return 0
}
let width = textureImage.width
let height = textureImage.height
let rect = CGRect(x: 0, y: 0, width: width, height: height)
/*
it will write one byte each for red, green, blue, and alpha โ so 4 bytes in total.
*/
let textureData = calloc(width * height * 4, MemoryLayout<GLubyte>.size) //4 components per pixel (RGBA)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue|CGBitmapInfo.byteOrder32Big.rawValue
let spriteContext = CGContext(data: textureData,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo)
if translate {
spriteContext?.translateBy(x: 0, y: CGFloat(height))
spriteContext?.scaleBy(x: 1, y: -1)
}
spriteContext?.clear(rect)
spriteContext?.draw(textureImage, in: rect)
glEnable(GLenum(GL_TEXTURE_2D))
var textName = GLuint()
glGenTextures(1, &textName)
glBindTexture(GLenum(GL_TEXTURE_2D), textName)
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLfloat(GL_LINEAR));
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLfloat(GL_LINEAR));
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLfloat(GL_CLAMP_TO_EDGE));
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLfloat(GL_CLAMP_TO_EDGE));
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, GLsizei(width),
GLsizei(height), 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), textureData)
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
free(textureData)
return textName
}
private func getImageFromBuffer(width: Int, height: Int) -> UIImage {
let x: GLint = 0
let y: GLint = 0
let dataLength = width * height * 4
let data = UnsafeMutablePointer<GLubyte>.allocate(capacity: dataLength * MemoryLayout<GLubyte>.size)
glPixelStorei(GLenum(GL_PACK_ALIGNMENT), 4)
glReadPixels(x, y, GLsizei(width), GLsizei(height), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), data)
let ref = CGDataProvider(dataInfo: nil, data: data, size: dataLength, releaseData: {_,_,_ in
})
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue) as UInt32)
let iref = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: bitmapInfo, provider: ref!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
let cgcontext = UIGraphicsGetCurrentContext()
cgcontext?.setBlendMode(.copy)
cgcontext?.draw(iref!, in: CGRect(x: 0, y: 0, width: width, height: height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
free(data)
return image!
}
}
extension UIImage {
public func applyLUTFilter(LUT: UIImage?, volume: Float) -> UIImage {
return LUTFilter(image: self).filteredImage(LUT: LUT, volume: volume)
}
}
|
/**
* OTP
* Copyright (c) 2017 Alexis Aubry. Licensed under the MIT license.
*/
import XCTest
@testable import OTP
/**
* Tests the OTP generation APIs.
*/
class OTPGenerationTests: XCTestCase {
// MARK: - Requests
/**
* Tests that HOTP requests are correctly configured.
*/
func testHOTPRequestValues() {
let request = OTPGenerationRequest.hotp(counter: 1, sharedSecret: "a2", codeLength: 8)
XCTAssertEqual(request.movingFactor, "0000000000000001")
XCTAssertEqual(request.sharedSecret, "a2")
XCTAssertEqual(request.codeLength, 8)
XCTAssertEqual(request.hmac, .sha1)
}
/**
* Tests that TOTP requests are correctly configured.
*/
func testTOTPRequestValues() {
let totpVectors = OTPTestSuite.totp()
for totpVector in totpVectors {
let request = totpVector.makeRequest()
XCTAssertEqual(request.movingFactor, totpVector.movingFactor)
XCTAssertEqual(request.sharedSecret, totpVector.sharedSecret)
XCTAssertEqual(request.codeLength, totpVector.codeLength)
XCTAssertEqual(request.hmac, totpVector.hmac)
}
}
// MARK: - Generation
/**
* Tests that the moving factor is correctly authenticated with HMAC.
*/
func testMovingFactorHMAC() {
let testHashes = OTPTestSuite.movingFactorHash()
for testHash in testHashes {
let digest = OTPGenerator.authenticate(testHash.0)
XCTAssertEqual(digest, testHash.1)
}
}
/**
* Tests the truncation method.
*/
func testTruncation() {
let truncationVectors = OTPTestSuite.truncation()
for truncationVector in truncationVectors {
let truncatedDigest = OTPGenerator.truncateDigest(truncationVector.1, length: truncationVector.0)
XCTAssertEqual(truncatedDigest, truncationVector.2)
}
}
/**
* Tests generating TOTPs.
*/
func testTOTP() {
let totpVectors = OTPTestSuite.totp()
for totpVector in totpVectors {
let request = totpVector.makeRequest()
let code = OTPGenerator.generateCode(for: request)
let hash = OTPGenerator.authenticate(request)
XCTAssertEqual(hash, totpVector.expectedHash)
XCTAssertEqual(code, totpVector.expectedTOTP)
}
}
}
|
//
// DBCategory+CoreDataClass.swift
// TaskManager
//
// Created by Tomas Sykora, jr. on 22/12/2019.
// Copyright ยฉ 2019 AJTY. All rights reserved.
//
//
import Foundation
import CoreData
@objc(DBCategory)
public class DBCategory: NSManagedObject {
func category() -> Category {
return Category(categoryID: objectID, name: name ?? "", color: color ?? "")
}
}
|
//
// SecondViewController.swift
// Assigment2
//
// Created by ๆพๆๆด on 2021/5/6.
//
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var InfoImage: UIImageView!
@IBOutlet weak var infoname: UILabel!
@IBOutlet weak var infolocation: UILabel!
@IBOutlet weak var infoiata: UILabel!
@IBOutlet weak var infoshortname: UILabel!
var airport: Airport?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = airport?.IATA
InfoImage.image = UIImage(named: (airport?.imageName)!)
infoname.text = airport?.name
infolocation.text = airport?.country
infoiata.text = airport?.IATA
infoshortname.text = airport?.shortName
// 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.
}
*/
}
|
import UIKit
class MenuSettingsViewController: UIViewController, Presentable {
// MARK: - Presentable
static var storyboardName = "MenuSettings"
var store: Store!
// MARK: - Interface Builder
@IBOutlet weak var containerView: UIView!
@IBAction func tapClose(_ sender: Any) {
store.dispatch(DismissLastScreenFamilyAction())
}
@IBAction func tapReset(_ sender: Any) {
store.dispatch(PresentResetScreenAction())
}
// MARK: - Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let settingsView = UIStoryboard(name: "Settings", bundle: nil).instantiateInitialViewController() as! SettingsViewController
settingsView.setStore(store: store)
addChildViewController(settingsView)
settingsView.view.frame = containerView.frame
settingsView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(settingsView.view)
settingsView.didMove(toParentViewController: self)
}
}
|
//
// Rectangle.swift
// AreaAndPerimeter
//
// Created by Sam Dindyal on 2018-07-28.
// Copyright ยฉ 2018 Sam Dindyal. All rights reserved.
//
import UIKit
class Rectangle: Shape {
var area: Float
var perimeter: Float
var height: Float {
didSet {
self.calculateShapePaths()
}
}
var width: Float {
didSet {
self.calculateShapePaths()
}
}
var shapePaths: [UIBezierPath]
var bounds: CGRect!
let formulae:[String:String] = [
"area": "l โข w",
"perimeter": "2 โขย (l + w)"
]
init(width: Float, height: Float) {
self.height = height
self.width = width
self.perimeter = 0.0
self.area = 0.0
self.shapePaths = []
}
func getArea() -> Float {
self.area = self.height * self.width
return self.area
}
func getPerimeter() -> Float {
self.perimeter = 2 * ( self.width + self.height )
return self.perimeter
}
func calculateShapePaths(bounds: CGRect) {
var shapePaths:[UIBezierPath] = []
let lineWidth:CGFloat = 5.0
let heightRatio = self.height / Float(bounds.height)
let widthRatio = self.width / Float(bounds.width)
let sizeRatio = max(heightRatio, widthRatio)
let width = CGFloat(self.width / sizeRatio) - lineWidth - 10.0
let height = CGFloat(self.height / sizeRatio) - lineWidth - 10.0
let x = (bounds.width - CGFloat(width)) / 2.0
let y = (bounds.height - CGFloat(height)) / 2.0
let shapePath = UIBezierPath(rect: CGRect(x: x, y: y, width: width, height: height))
shapePath.lineWidth = lineWidth
shapePaths.append(shapePath)
self.shapePaths = shapePaths
self.bounds = bounds
}
func calculateShapePaths() {
self.calculateShapePaths(bounds: self.bounds)
}
}
|
//
// SSLCertificate.swift
//
//
// Created by Martin Prusa on 4/30/20.
//
import Foundation
import Security
public struct SSLCertificate {
private let fileName: String
private let suffix: String
public private(set) var certificate: SecCertificate!
/**
Creates representation of your DER type SSL public certificate
- Author: Martin Prusa
- Parameters:
- fileName: name of the file eg when filename is (server.crt) you enter server
- suffix: suffix of the file eg when filename is (server.crt) you enter crt
- Returns: optional SSLCertificate when possible to create from your file name and suffix
*/
public init?(fileName: String, suffix: String) {
self.fileName = fileName
self.suffix = suffix
guard let cert = createCertificate() else { return nil }
certificate = cert
}
private func createCertificate() -> SecCertificate? {
do {
guard let filePath = Bundle.main.path(forResource: fileName, ofType: suffix) else { return nil }
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
guard let certificate = SecCertificateCreateWithData(nil, data as CFData) else { return nil }
return certificate
} catch (let e) {
assert(false, e.localizedDescription)
return nil
}
}
}
|
import Foundation
let ShramFileManager = ShramFileService()
internal class ShramFileService: FileManager
{
internal func checkPathForResource(_ pathForResource: AnyObject) -> String?
{
guard
pathForResource is String &&
fileExists(atPath: pathForResource as! String)
else
{
guard
let path = (pathForResource as? URL)?.path,
fileExists(atPath: path)
else
{
return nil
}
return path
}
return pathForResource as? String
}
}
|
//
// SettingListViewController.swift
// GREApp
//
// Created by ํ์ฐฝ๋จ on 2017. 9. 10..
// Copyright ยฉ 2017๋
ํ์ฐฝ๋จ. All rights reserved.
//
import UIKit
class SettingListViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor(red: 78/255, green: 186/255, blue: 74/255, alpha: 1.0)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MyTalkSegue" {
if let destination = segue.destination as? SettingMyTalkViewController {
destination.myString = "์๋
ํ์ธ์, ์ฑ ๊ฐ๋ฐ์์
๋๋ค. ๋จผ์ ๊ตณ์ด ์ธ์ฌ๋ง์ ๋ด์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค. ๐\n\n ์ด ์ฑ์ GRE ๋จ์ด๋ฅผ ๊ณต๋ถํ์๋ ๋ถ๋ค์ด ์ข ๋ ์์ํ๊ฒ ๋จ์ด ๊ณต๋ถ๋ฅผ ํ ์ ์์์ผ๋ฉด ํ๋ ๋ง์์์ ์ ์ํ ์ฑ์
๋๋ค.(์ค์์ ์ด ์ฑ์ ๋์์ด๋๊ฐ GRE๋ฅผ ๊ณต๋ถํด์ ๋ง๋ค์์ต๋๋ค. ๐) ์ฑ์ ๋ค์ด๊ฐ ์๋ ๋จ์ด ๋ฐ์ดํฐ๋ ๋์์ด๋๋ถ์ด ๋ชจ๋ฅด๋ ๋จ์ด๋ค์ ํ๋์ฉ ์ ๋ฆฌํ ์๋ฃ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๊ตฌ์ฑ๋์ด ์์ผ๋ฉฐ, ํ์ฌ๋ 1500๊ฐ์ ๋จ์ด๊ฐ ์ฑ์ ๋ค์ด๊ฐ ์์ต๋๋ค.๐\n\n์ด ์ฑ์ GRE ๋จ์ด๋ฅผ ๊ณต๋ถํ๋ ๋ถ๋ค์ด ๋จ์ด๋ฅผ ์ ์๊ธฐํ ์ ์๋๋ก ๋งค์ผ๋งค์ผ ๊ณต๋ถํ๊ณ , ๊ณต๋ถํ ๋จ์ด๋ฅผ ํ
์คํธํ๋ ํํ๋ก ๊ตฌ์ฑ๋์ด ์์ต๋๋ค. ๋จ์ด์ ์๋ก์ด ๊ธฐ๋ฅ๋ค์ ์ง์์ ์ผ๋ก ์ถ๊ฐ๋ ์์ ์
๋๋ค. ์ฑ ๊ฐ๋ฐ์ ๋ํ ์๊ฒฌ์ด๋ ์ถ๊ฐ๋์์ผ๋ฉด ํ๋ ๋ด์ฉ๋ค์ ์ฑ ๋ฆฌ๋ทฐ์ ๋จ๊ฒจ์ฃผ์๋ฉด, ํ์ธํ์ฌ ๋น ๋ฅธ ์์ผ๋ด์ ์
๋ฐ์ดํธํ๋๋ก ๋
ธ๋ ฅํ๊ฒ ์ต๋๋ค. ๊ฐ๋ฏธ๋ ๋๋ ๐....๐.... . . ."
}
} else if segue.identifier == "UpdateScheduleSegue" {
if let destination = segue.destination as? SettingMyTalkViewController {
destination.myString = "Comming Soon\n\n๊ณต๋ถํ ๋จ์ด๋ค์ ๋ํด ํ
์คํธ๋ฅผ ๋ณผ ์ ์๋ ํญ์ด ๊ณง ์
๋ฐ์ดํธ ๋ ์์ ์
๋๋ค. ๊ฐ๋ฏธ๋ ๋๋ ๐....๐.... . . ."
}
}
}
}
extension SettingListViewController {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ""
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
}
|
class Solution {
func findRelativeRanks(_ nums: [Int]) -> [String] {
let num = nums.sorted(by: >)
var result = [String]()
var ranks = [Int](repeating: -1, count: num.max()! + 1)
for i in 0..<num.count {
ranks[num[i]] = i + 1
}
for num in nums {
switch ranks[num] {
case 1:
result.append("Gold Medal")
case 2:
result.append("Silver Medal")
case 3:
result.append("Bronze Medal")
default:
result.append(ranks[num].description)
}
}
return result
}
}
|
//
// SearchNewPlayersTVCell.swift
// Etbaroon
//
// Created by dev tl on 2/11/18.
// Copyright ยฉ 2018 dev tl. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class SearchNewPlayersTVCell: UITableViewCell {
@IBOutlet weak var playerImg: UIImageView!
@IBOutlet weak var playerNameLbl: UILabel!
@IBOutlet weak var invitePlayerBtn: UIButton!
var photo: AllPlayers? {
didSet {
guard let photo = photo else { return }
// download image
Alamofire.request(photo.url).response { response in
if let data = response.data, let image = UIImage(data: data) {
self.playerImg.image = image
}
else
{
self.playerImg.image = UIImage(named: "person")
}
}
}
}
var inviteObj : (() -> Void)? = nil
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
}
@IBAction func invitePlayer(_ sender: UIButton) {
if let btnAction = inviteObj{
btnAction()
}
}
}
|
//
// FlickrPagingLookup.swift
// FlickrLookup
//
// Created by Alexander Lonsky on 5/22/16.
// Copyright ยฉ 2016 HomeSweetHome. All rights reserved.
//
import Foundation
import UIKit
class FlickrPagingLookup {
typealias ResultsHandler = (([Photo], NSError?) -> Void)
private var lookupText: String?
private var lookupResults: ResultsHandler?
private var currentPage: Int = 1
private var numberOfPages: Int = 0
private let itemsPerPage: Int = 50
private let dataLoader: FlickrDataLoader
init(dataLoader: FlickrDataLoader) {
self.dataLoader = dataLoader
}
func lookup(text: String, results: ResultsHandler) {
cancel()
lookupResults = results
lookupText = text
doLookup()
}
func next() -> Bool {
if !canRequestNextPage() {
return false
}
currentPage += 1
doLookup()
return true
}
func cancel() {
lookupText = nil
lookupResults = nil
currentPage = 1
numberOfPages = 0
}
private func doLookup() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dataLoader.searchPhotos(lookupText ?? "", page: currentPage, itemsPerPage: itemsPerPage) { [weak self] photos, numberOfPages, error in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self?.numberOfPages = numberOfPages
if let photos = photos {
self?.lookupResults?(photos, nil)
} else {
self?.lookupResults?([], error)
}
}
}
private func canRequestNextPage() -> Bool {
return (currentPage + 1) <= numberOfPages
}
}
|
import Foundation
enum AnalyticTag: String {
case twitterButtonTap = "twitter"
case instagramButtonTap = "instagram"
case websiteButtonTap = "website"
case facebookButtonTap = "facebook"
case logout = "logout"
case login = "login"
case dashboard = "dashboard"
case navigateButtonTap = "navigate"
case callButtonTap = "call"
case emailButtonTap = "email"
case contact = "contact_us"
case none
}
|
//
// newBasicFlake.swift
// Flake
//
// Created by Kendall Lewis on 7/4/18.
// Copyright ยฉ 2018 Kendall Lewis. All rights reserved.
//
import UIKit
import Firebase
import FBSDKCoreKit
import FBSDKLoginKit
import FirebaseDatabase
import FirebaseAuth
import MapKit
class userCell: UITableViewCell{
@IBOutlet weak var userName: UILabel!
}
class usersFlake {
var flakeIds = ""
var flakeUserAccount = ""
init(flakeIds: String, flakeUserAccount: String) {
self.flakeIds = flakeIds
self.flakeUserAccount = flakeUserAccount
}
}
var flakeTitle:String = ""
var flakeDetails:String = ""
var flakeDate:String = ""
var flakeLocation:String = ""
var flakeDuration:String = ""
var flakePrice:Int = 0
var ID = pageID + 1
var flakeID:Int = 0
var flakeParty:Int = 0
var current = flakeList.count-1
var flakePartyAmount:String = ""
var flakeHolder = ""
var flakeUsers = [String]()
var flakeIdsList = [usersFlake]()
var flakeIds:String = ""
var flakeUserAccounts:String = ""
class newBasicFlake: UIViewController, UITextFieldDelegate, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var basicFlakeTitle: UITextField!
@IBOutlet weak var basicFlakeLocation: UITextField!
@IBOutlet weak var basicFlakeDate: UITextField!
@IBOutlet weak var basicFlakeDuration: UITextField!
@IBOutlet weak var basicFlakePrice: UITextField!
@IBOutlet weak var basicFlakeDetails: UITextView!
@IBOutlet weak var basicFlakePartyAmount: UITextField!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var myMapView: MKMapView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var backgroundImage: UIImageView!
var ref:DatabaseReference?
var databaseHandle: DatabaseHandle?
var currentIndex = 1
var newName:String = "flake1"
var firebaseDataIndex: String = ""
var postID = 0
var postIndex = 0
var newPost = 0
var chrInteger:Int = 0
var firebaseData1:Int = 0, firebaseData2:String = "", firebaseData3:String = "", firebaseData4:Int = 0, firebaseData5:String = "", firebaseData6:Int = 0, firebaseData7:Int = 0, firebaseData8:String = "", firebaseData9:Int = 0
var Identification:String = ""
var addUsers = ""
var userFlakes:String = ""
var flakeString:String = ""
override func viewDidLoad() {
super.viewDidLoad()
loadBackground()
/***************** user table view *****************/
if tableView != nil{
self.tableView.allowsMultipleSelection = true
self.tableView.allowsMultipleSelectionDuringEditing = true
self.tableView.delegate = self
self.tableView.dataSource = self
definesPresentationContext = true
tableView.backgroundColor = UIColor.clear
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
/***************** firebase database ***************/
ref = Database.database().reference()
}
func loadBackground(){
//print("bg \(bg)")
backgroundImage.backgroundColor = UIColor(patternImage: UIImage(named: "background\(bg).png")!)
}
@IBAction func continueToUsersButton(_ sender: Any) {
if basicFlakeDate.text != "" || basicFlakeDuration.text != "" || basicFlakePrice.text != "" {
flakeDate = basicFlakeDate.text!
flakeDuration = basicFlakeDuration.text!
flakePrice = Int(basicFlakePrice.text!)!
}
}
@IBAction func continueToSubmitButton(_ sender: Any) {
if let list = tableView.indexPathsForSelectedRows as [NSIndexPath]? {
flakeParty = Int(list.count) + 1
//print(list.count)
}
}
@IBAction func searchButton(_ sender: Any) {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.delegate = self
present(searchController, animated: true, completion: nil)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
UIApplication.shared.beginIgnoringInteractionEvents()
//Activy Indicator
let activityIndicator = UIActivityIndicatorView()
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
//Hide search Bar
searchBar.resignFirstResponder()
dismiss(animated: true, completion: nil)
//Create the search request
let searchRequest = MKLocalSearchRequest()
searchRequest.naturalLanguageQuery = searchBar.text
flakeLocation = searchBar.text!
let activeSearch = MKLocalSearch(request: searchRequest)
activeSearch.start { (response, error) in
activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if response == nil{
print("Error")
}else{
//remove annotations
let annotations = self.myMapView.annotations
self.myMapView.removeAnnotations(annotations)
//getting Data
let latitude = response?.boundingRegion.center.latitude
let longitude = response?.boundingRegion.center.longitude
//create annotations
let annotation = MKPointAnnotation()
annotation.title = searchBar.text
annotation.coordinate = CLLocationCoordinate2DMake(latitude!, longitude!)
self.myMapView.addAnnotation(annotation)
//Zoming in on annotation
let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude!, longitude!)
let span = MKCoordinateSpanMake(0.1, 0.1)
let region = MKCoordinateRegionMake(coordinate, span)
self.myMapView.setRegion(region, animated: true)
}
}
}
@IBAction func submitButtonPressed(_ sender: Any) {
print ("flakeLocation \(flakeLocation)")
print ("flakeDate \(flakeDate)")
print ("flakeDuration \(flakeDuration)")
print ("flakePrice \(flakePrice)")
print ("flakeParty \(flakeParty)")
print ("flakePartyAmount \(flakePartyAmount)")
print ("flakeMembers \(flakeUsers)")
flakeTitle = String(basicFlakeTitle.text!)
flakeDetails = String(basicFlakeDetails.text!)
ID = pageID + 1
flakeID = flakeIdentification
current = flakeList.count-1
let anotherUser = flakeUsers.joined(separator: ",")
/************* Firebase database ****************/
ref = Database.database().reference()
let postFlake = [
"flakeID": "\(flakeID)", //add username to database
"flakeTitle": "\(flakeTitle)",
"flakeDetails": "\(flakeDetails)", //add password to database
"flakeDate": "\(flakeDate)", //add empty flakes to database
"flakeLocation": "\(flakeLocation)", //add username to database
"flakePrice": "\(String(flakePrice))", //add password to database
"flakeParty": "\(flakeParty)", //add empty flakes to database
"amountPaid": "0",
"totalAmountPaid": "0",
"flakeMembers": "\(anotherUser)" //add all flakeMembers to flake
] as [String : Any]
ref?.child("flakes/flake\(flakeIdentification)").setValue(postFlake) //post all account info into UserAccount database
if flakeTitle != "" || flakeDate != "" || flakeLocation != "" || flakePrice != 0 {
/*********************** Do NOT touch (Adding to Fire DB) ***********************/
newFlakes = "" //clear new flakes
//print("flakeHolder \(flakeHolder)")
newFlakes = flakeHolder + "," + String(flakeID)
//print("new flakeID to add \(String(flakeID))")
//print("the new flake \(newFlakes)")
ref?.child("userAccounts/\(uid)/flakeIds").setValue(newFlakes)
flakeID += 1 //update date to new flake
ref?.child("flakeIdentification/flakeIdentification").setValue(String(flakeID))
//dump(newFlakes)
flakeHolder = newFlakes //save flakes
newFlakes = "" //clear new flakes
/***********************Do NOT touch***********************/
flakeListHolder.removeAll()
flakeList.removeAll()
tempList.removeAll()
currentFlake = ""
flakeListLength += 1
let postPaid = [
"pricePaid": "0" //add username to database
] as [String : Any]
self.ref?.child("flakePots/\("flake" + String(flakeID - 1))/members/\(uid)").updateChildValues(postPaid) //post all account info into UserAccount database
addUserDB()
}
}
func addUserDB(){
for (index,usr) in flakeUsers.enumerated() { //for loop for all friends added
print(index)
let user = String(usr)
ref?.child("userAccounts").observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
for artists in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let artistObject = artists.value as? [String: AnyObject]
flakeIds = artistObject?["flakeIds"] as! String
flakeUserAccounts = artistObject?["userID"] as! String
let flakeHolder:String = flakeIds + "," + String(flakeID - 1)
if (flakeUserAccounts == user){
//print("current user \(user)")
let postIds = [
"flakeIds": "\(flakeHolder)" //add username to database
] as [String : Any]
self.ref?.child("userAccounts/\(flakeUserAccounts)").updateChildValues(postIds) //post all account info into UserAccount database
let postPaid = [
"pricePaid": "0" //add username to database
] as [String : Any]
self.ref?.child("flakePots/\("flake" + String(flakeID - 1))/members/\(flakeUserAccounts)").setValue(postPaid) //post all account info into UserAccount database
let postTotalAmountPaid = [
"pot": "0" //add username to database
] as [String : Any]
self.ref?.child("flakePots/\("flake" + String(flakeID - 1))/totalAmountPaid").setValue(postTotalAmountPaid) //post all account info into UserAccount database
return
}else{
print("\(user)")
}
}
})
}
flakeUsers.removeAll()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{//displays cells
var cell = tableView.dequeueReusableCell(withIdentifier: "userCell") as! userCell?
if cell == nil {
tableView.register(userCell.classForCoder(), forCellReuseIdentifier: "userCell")
cell = userCell(style: UITableViewCellStyle.default, reuseIdentifier: "userCell")
}
if let label = cell?.userName{
label.text = userList[indexPath.row].userName
}
else{
cell?.userName?.text = userList[indexPath.row].userName
}
return(cell)!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //add user if clicked
addUsers = String(userList[indexPath.row].userID)
flakeUsers.append(addUsers)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { //Remove user if clicked
addUsers = String(userList[indexPath.row].userID)
flakeUsers.removeAll { $0 == addUsers }
}
//Hide keyboard when the users touches outside keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
extension UITextField{
func underlined(){
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor.lightGray.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
extension UITextField{
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
}
}
}
|
//
// TableDataSource.swift
// fileTable
//
// Created by Jz D on 2020/3/15.
// Copyright ยฉ 2020 Jz D. All rights reserved.
//
import Cocoa
//MARK: - NSTableViewSectionDataSource
protocol TableSectionDataSource: NSTableViewDataSource {
func numberOfSectionsInTable(tb: NSTableView) -> Int
func table(tb: NSTableView, numberOfRowsInSection section: Int) -> Int
func tableProxySectionAndRow(tb: NSTableView, transformedBy stdRowIdx: Int) -> (section: Int, row: Int)
}
//MARK: - TableSectionDelegate
protocol TableSectionDelegate: NSTableViewDelegate {
func table(tb: NSTableView, headerForSection section: Int) -> NSView?
}
|
//
// CoreDataController.swift
// CoreDataSample
//
// Created by sudarshan shetty on 4/7/15.
// Copyright (c) 2015 Sudarshan Shetty. All rights reserved.
//
import WatchKit
import Foundation
import CoreData
class CoreDataController: WKInterfaceController {
@IBOutlet weak var theTable: WKInterfaceTable!
var clubs = [NSManagedObject]()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
func loadthetableview()
{
var request = NSFetchRequest()
var entity = NSEntityDescription.entityForName("Clubs", inManagedObjectContext: self.managedObjectContext!)
request.entity = entity
var error: NSError? = nil
let fetchedResults =
self.managedObjectContext?.executeFetchRequest(request, error: &error) as [NSManagedObject]?
clubs=fetchedResults!
let count = clubs.count
theTable.setNumberOfRows(count, withRowType: "therows")
for (index, value) in enumerate(clubs) {
if let row = theTable.rowControllerAtIndex(index) as? CoreDatarowcontroller
{
let club = clubs[index]
row.theLabel.setText(club.valueForKey("clubname") as String?)
}
}
}
private lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.projectds.CoreDataWatch" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
private lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let containerPath = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.techendeavour.watchkit")?.path
let sqlitePath = NSString(format: "%@/%@", containerPath!, "test.sqlite")
let url = NSURL(fileURLWithPath: sqlitePath)
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
private lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
private func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
}
// override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
//
// return thecontroller[rowIndex];
// }
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
self.loadthetableview();
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
//
// MapViewModel.swift
// Fusion
//
// Created by Abhishek Jaykrishna Khapare on 8/14/17.
// Copyright ยฉ 2017 Mohammad Irteza Khan. All rights reserved.
//
import Foundation
import Alamofire
class MapViewModel{
var theatreDetails = [[String:String]]()
func NetworkCall(urlString:String, compHandler:@escaping([[String:String]])->Void){
Alamofire.request(urlString).responseJSON{
response in
let json = response.result.value as! [String:Any]
print(json)
if let query = json["query"] as? [String : Any]{
print(query)
if let results = query["results"] as? [String : Any]{
let result = results["Result"] as! [[String : Any]]
for theatre in result{
let title = theatre["Title"] as! String
let address = theatre["Address"] as! String
let city = theatre["City"] as! String
let state = theatre["State"] as! String
let phone = theatre["Phone"] as! String
print(phone)
let latitude = theatre["Latitude"] as! String
let longitude = theatre["Longitude"] as! String
let url = theatre["Url"] as! String
let rating = theatre["Rating"] as! [String: Any]
let averageRating = rating["AverageRating"] as! String
self.theatreDetails.append(["Title":title,"Address":address,"City":city,"State":state,"Phone":phone,"Latitude":latitude,"Longitude":longitude,"Url":url,"AverageRating":averageRating])
}
}
}
compHandler(self.theatreDetails)
}
}
}
|
import Fluent
import FluentPostgresDriver
import Leaf
import Vapor
import FluentMongoDriver
//import LeafMarkdown
// configures your application
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.middleware.use(app.sessions.middleware)
// Serves files from `Public/` directory
// let fileMiddleware = FileMiddleware(
// publicDirectory: app.directory.publicDirectory
// )
// app.middleware.use(fileMiddleware)
// MARK: - Config http server.
// app.http.server.configuration.hostname = "localhost"
// app.http.server.configuration.port = 8081
// MARK: - Config DB.
let databaseName: String
let databasePort: Int
if (app.environment == .testing) {
databaseName = "vapor-test"
if let testPort = Environment.get("DATABASE_PORT") {
databasePort = Int(testPort) ?? 5433
} else {
databasePort = 5433
}
} else {
databaseName = "vapor_database"
databasePort = 5432
}
// default port for psql
// port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? PostgresConfiguration.ianaPortNumber,
app.databases.use(.postgres(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: databasePort,
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
database: Environment.get("DATABASE_NAME") ?? databaseName
), as: .psql)
//
// try app.databases.use(.mongo(connectionString: "<connection string>"), as: .mongo)
// MARK: - Table of DB.
app.migrations.add(CreateTodo())
app.migrations.add(CreateUser())
app.migrations.add(CreateAcronym())
app.migrations.add(CreateCategory())
app.migrations.add(CreateAcronymCategoryPivot())
app.migrations.add(CreateToken())
app.migrations.add(CreateAdminUser())
app.logger.logLevel = .debug
try app.autoMigrate().wait()
app.views.use(.leaf)
// app.leaf.tags["markdown"] = Markdown() //
// MARK: - Change the encoders and decoders.
// Global
// create a new JSON encoder that uses unix-timestamp dates
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
// override the global encoder used for the `.json` media type
ContentConfiguration.global.use(encoder: encoder, for: .json)
// register routes
try routes(app)
}
|
//
// ViewController.swift
// Shapes
//
// Created by GEORGE QUENTIN on 05/09/2018.
// Copyright ยฉ 2018 Geo Games. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
import AppCore
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
let scene = SCNScene(named: "art.scnassets/table.scn")!
// Set the scene to the view
sceneView.scene = scene
//createShapes()
addLights()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
func createShapes() {
let pyramid = SCNPyramid(width: 0.2, height: 0.2, length: 0.2)
pyramid.firstMaterial?.diffuse.contents = UIColor.green
let pyramidNode = SCNNode(geometry: pyramid)
pyramidNode.position = SCNVector3(0.5, 0, -0.8)
sceneView.scene.rootNode.addChildNode(pyramidNode)
let box = SCNBox(width: 0.2, height: 0.2, length: 0.2, chamferRadius: 0)
box.firstMaterial?.diffuse.contents = UIColor.yellow
let boxNode = SCNNode(geometry: box)
boxNode.position = SCNVector3(-0.5, 0, -0.8)
sceneView.scene.rootNode.addChildNode(boxNode)
let sphere = SCNSphere(radius: 0.15)
sphere.firstMaterial?.diffuse.contents = UIColor.red
let sphereNode = SCNNode(geometry: sphere)
sphereNode.position = SCNVector3(0, 0, -0.8)
sceneView.scene.rootNode.addChildNode(sphereNode)
}
func addLights() {
let directional = SCNLight()
directional.type = SCNLight.LightType.directional
let directionalLightNode = SCNNode()
let angle: Float = 45
directionalLightNode.light = directional
directionalLightNode.eulerAngles.x = angle.toRadians
sceneView.scene.rootNode.addChildNode(directionalLightNode)
let ambient = SCNLight()
let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
ambient.type = .ambient
ambient.color = color
let ambientLightNode = SCNNode()
ambientLightNode.light = ambient
sceneView.scene.rootNode.addChildNode(ambientLightNode)
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
|
//
// RenderProtocols.swift
// Authority
//
// Created by VassilyChi on 2020/8/10.
//
import Foundation
import Combine
import MetalKit
import CoreMedia
//public protocol RenderCustomer: ObserverType where Element == RenderTexture {}
public enum ImageOrientation {
case portrait
case portraitUpsideDown
case landscapeLeft
case landscapeRight
}
public struct RenderTexture {
public let width: Int
public let height: Int
public let sourceImage: CIImage
public let timeStamp: CMTime
public let format: CMFormatDescription
public init(sourceImage: CIImage, formatDesc: CMFormatDescription, timeStamp: CMTime = .now()) {
self.sourceImage = sourceImage
format = formatDesc
self.timeStamp = timeStamp
let videoFormat = CMVideoFormatDescriptionGetDimensions(formatDesc)
width = Int(videoFormat.width)
height = Int(videoFormat.height)
}
}
public protocol RenderSource {
var textureBufferPublisher: AnyPublisher<RenderTexture, Never> { get }
}
public extension CMTime {
static func now() -> CMTime {
return CMTimeMake(value: Int64(CACurrentMediaTime() * Double(NSEC_PER_SEC)), timescale: Int32(NSEC_PER_SEC))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.