blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
e1de5b2cd9d0d2e6d68bf5abcf3693a8269f94c4
|
Swift
|
nguyendinhtrieu1996/ZaloraTest_Tweeter
|
/Tweeter/TweeterTests/Extensions/CGSizeTests.swift
|
UTF-8
| 616
| 2.625
| 3
|
[] |
no_license
|
//
// CGSizeTests.swift
// TweeterTests
//
// Created by MACOS on 3/10/19.
// Copyright © 2019 MACOS. All rights reserved.
//
import XCTest
@testable import Tweeter
class CGSizeTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
}
// MARK: - Tests outsetBy
extension CGSizeTests {
func testOutsetByReturnCorrectValue() {
let size = CGSize(width: 100, height: 100)
let expectSize = CGSize(width: 110, height: 120)
let dx: CGFloat = 10
let dy: CGFloat = 20
XCTAssertEqual(size.outsetBy(dx: dx, dy: dy), expectSize)
}
}
| true
|
bd5caae2dd96253ad75c883dc778b6da199ba0d7
|
Swift
|
mohahghamdi/ToDoey
|
/ToDoey/Data Model/Item.swift
|
UTF-8
| 272
| 2.671875
| 3
|
[] |
no_license
|
//
// Item.swift
// ToDoey
//
// Created by mohammed alghamdi on 27/11/2018.
// Copyright © 2018 mohammed alghamdi. All rights reserved.
//
import Foundation
class Item: Encodable, Decodable { // or just right codable
var title: String = ""
var done: Bool = false
}
| true
|
86ac231e2f5442d411533766a3a2f15dbe6b6634
|
Swift
|
Luch0/AC-iOS-Unit4Week1-HW
|
/AC-iOS-Unit4-Week1-HW/Models/GoogleBook.swift
|
UTF-8
| 1,699
| 2.890625
| 3
|
[] |
no_license
|
//
// GoogleBook.swift
// AC-iOS-Unit4-Week1-HW
//
// Created by Luis Calle on 12/18/17.
// Copyright © 2017 C4Q . All rights reserved.
//
import Foundation
struct GoogleBookResponse: Codable {
let items: [GoogleBook]
}
struct GoogleBook: Codable {
let volumeInfo: VolumeInfoWrapper
}
struct VolumeInfoWrapper: Codable {
let title: String
let subtitle: String?
let authors: [String]
let description: String
let imageLinks: ImagesWrapper?
}
struct ImagesWrapper: Codable {
let smallThumbnail: String
let thumbnail: String
}
struct GoogleBookAPIClient {
private init() {}
static let manager = GoogleBookAPIClient()
let apiKey = "AIzaSyAnbRfnkNiDr6ZusJ5eT2VAnseUm0dano8"
let endpointUrlStr = "https://www.googleapis.com/books/v1/volumes?"
func getGoogleBook(with isbn: String, completionHandler: @escaping (GoogleBook) -> Void, errorHandler: @escaping (Error) -> Void) {
let fullUrl = "\(endpointUrlStr)key=\(apiKey)&q=+isbn:\(isbn)"
guard let url = URL(string: fullUrl) else {
errorHandler(AppError.badURL(str: fullUrl))
return
}
let urlRequest = URLRequest(url: url)
let completion: (Data) -> Void = {(data: Data) in
do {
let googleBookResponse = try JSONDecoder().decode(GoogleBookResponse.self, from: data)
completionHandler(googleBookResponse.items[0])
}
catch {
errorHandler(AppError.couldNotParseJSON(rawError: error))
}
}
NetworkHelper.manager.performDataTask(with: urlRequest, completionHandler: completion, errorHandler: errorHandler)
}
}
| true
|
4058eceb6f8f2add02f4e4ec1ac04997f215fb55
|
Swift
|
topcoderinc/timobile-ios
|
/src/ThoroughbredInsider/ThoroughbredInsider/ViewControllers/Menu/MenuTableViewCell.swift
|
UTF-8
| 813
| 2.703125
| 3
|
[] |
no_license
|
//
// MenuTableViewCell.swift
// ThoroughbredInsider
//
// Created by TCCODER on 30/10/17.
// Modified by TCCODER on 2/23/18.
// Copyright © 2018 topcoder. All rights reserved.
//
import UIKit
/**
* Side menu cell
*
* - author: TCCODER
* - version: 1.0
*/
class MenuTableViewCell: UITableViewCell {
/// menu
var menu : Menu? {
didSet {
if let menu = menu {
configure(menu)
}
}
}
/// outlets
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var selectionView: UIView!
/**
Configure the cell
- parameter menu: menu
*/
func configure(_ menu: Menu) {
nameLabel.text = menu.name
iconImage.image = menu.icon
}
}
| true
|
c1acd09a05043a315549a99d4ba62b64377910bc
|
Swift
|
jiho-s/DrinkProjectSwift
|
/DrinkProjectSwift/Containers/CustomButton.swift
|
UTF-8
| 789
| 3.09375
| 3
|
[] |
no_license
|
//
// CustomButton.swift
// DrinkProjectSwift
//
// Created by 신지호 on 2020/11/08.
// Copyright © 2020 jiho. All rights reserved.
//
import SwiftUI
struct CustomButton<Label>: View where Label : View {
let action: () -> Void
let label: () -> Label
public init(action: @escaping () -> Void, @ViewBuilder label: @escaping () -> Label) {
self.label = label
self.action = action
}
var body: some View {
Button(action: self.action, label: self.label)
.frame(width: 300.0, height: 15)
.foregroundColor(.black)
.fieldStyle()
.padding(10)
}
}
struct CustomButton_Previews: PreviewProvider {
static var previews: some View {
CustomButton(action: {}) {
Text("tdd")
}
}
}
| true
|
8ffeea0d8588cb6ba58963dedbffeec892c0d0b6
|
Swift
|
msystang/Pursuit-Core-Persistence-Lab
|
/Persistence-FileManager/Persistence-FileManager/Controllers/PhotoDetailViewController.swift
|
UTF-8
| 1,257
| 2.796875
| 3
|
[] |
no_license
|
//
// PhotoDetailViewController.swift
// Persistence-FileManager
//
// Created by Sunni Tang on 9/30/19.
// Copyright © 2019 Sunni Tang. All rights reserved.
//
import UIKit
class PhotoDetailViewController: UIViewController {
var photo: Photo!
@IBOutlet weak var photoImage: UIImageView!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var tagLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
configureLabels()
loadImage()
}
@IBAction func saveFavoriteButtonPressed(_ sender: UIButton) {
do {
try PhotoPersistenceHelper.manager.save(newPhoto: photo)
} catch {
print(error)
}
}
func configureLabels() {
idLabel.text = "\(photo.id)"
tagLabel.text = photo.tags
}
func loadImage() {
ImageHelper.manager.getImage(urlStr: photo.imageURL) { (result) in
DispatchQueue.main.async {
switch result {
case .failure (let error):
print(error)
case .success (let imageFromOnline):
self.photoImage.image = imageFromOnline
}
}
}
}
}
| true
|
5b613aa18cee087087a9f9683bef0e7def976a6a
|
Swift
|
audreylrnt/NMCNews
|
/NMCNews/AddNewsViewController.swift
|
UTF-8
| 2,829
| 2.703125
| 3
|
[] |
no_license
|
//
// AddNewsViewController.swift
// NMCNews
//
// Created by Laurentia Audrey on 17/11/20.
// Copyright © 2020 Matheus. All rights reserved.
//
import UIKit
class AddNewsViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var arrCategory = ["Entertainment", "Politic", "Sport", "Finance", "Automotive"]
@IBOutlet weak var pickerCategory: UIPickerView!
@IBAction func btnBack(_ sender: Any) {
alertMe(message: "Save to draft before leaving?")
}
@IBAction func btnSelectCategory(_ sender: UIButton) {
pickerCategory.isHidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
pickerCategory.isHidden = true
pickerCategory.dataSource = self
pickerCategory.delegate = self
}
func alertMe(message:String) -> Void {
let alertOn = UIAlertController(title: "Save to Draft", message: message, preferredStyle: .alert)
alertOn.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.destructive, handler: {action in
self.performSegue(withIdentifier: "segueBackFromAddNews", sender: self)
}))
alertOn.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {action in
//save data here
self.notificationAlert(message: "Data saved to draft!")
}))
self.present(alertOn, animated: true, completion: nil)
}
func notificationAlert(message:String) -> Void {
let alertOn = UIAlertController(title: "Save Success", message: message, preferredStyle: .alert)
alertOn.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {action in
self.performSegue(withIdentifier: "segueBackFromAddNews", sender: self)
}))
self.present(alertOn, animated: true, completion: nil)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return arrCategory.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return arrCategory[row]
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 50
}
/*
// 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.
}
*/
}
| true
|
5944966ca3cb06127f93ccb1ffb3cbe664d2c69c
|
Swift
|
tornikegomareli/RickAndMortyWiki
|
/RIckAndMortyWiki/Core/Domain/Models/CharacterLocations.swift
|
UTF-8
| 569
| 2.546875
| 3
|
[] |
no_license
|
//
// CharacterLocations.swift
// RIckAndMortyWiki
//
// Created by Tornike Gomareli on 16.06.21.
//
import Foundation
// MARK: - CharacterLocations
struct CharacterLocations: Codable {
let info: CharacterLocationInfo
let results: [CharacterLocation]
}
// MARK: - Info
struct CharacterLocationInfo: Codable {
let count, pages: Int
let next: String
let prev: JSONNull?
}
// MARK: - Result
struct CharacterLocation: Codable {
let id: Int
let name, type, dimension: String
let residents: [String]
let url: String
let created: String
}
| true
|
4ee93139bbcde8e5831290f2020449bdc573a4c1
|
Swift
|
murentsev/VK_app
|
/VK_app/Views/TabViewController.swift
|
UTF-8
| 790
| 2.515625
| 3
|
[] |
no_license
|
//
// TabViewController.swift
// VK_app
//
// Created by Алексей Муренцев on 26.07.2020.
// Copyright © 2020 Алексей Муренцев. All rights reserved.
//
import UIKit
class TabViewController: UITabBarController{
override func viewDidLoad() {
super.viewDidLoad()
// tabBar.backgroundColor = .white
// tabBar.barTintColor = .white
delegate = self
// Do any additional setup after loading the view.
}
}
extension TabViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return AnimationController(viewControllers: tabBarController.viewControllers)
}
}
| true
|
fec6003e60489c71be647bc65d3ce3b29fa01bf3
|
Swift
|
nkaffine/pandemic-solver
|
/PandemicSolver/model/GameState.swift
|
UTF-8
| 5,669
| 3.546875
| 4
|
[] |
no_license
|
//
// GameState.swift
// PandemicSolver
//
// Created by Nicholas Kaffine on 4/12/19.
// Copyright © 2019 Nicholas Kaffine. All rights reserved.
//
import Foundation
enum GameStatus: Equatable
{
//TODO: reasons should probably be an enum
case notStarted, inProgress, win(reason: String), loss(reason: String)
var isInProgress: Bool
{
switch self
{
case .notStarted, .win, .loss:
return false
case .inProgress:
return true
}
}
static func ==(lhs: GameStatus, rhs: GameStatus) -> Bool
{
switch lhs
{
case .notStarted:
switch rhs
{
case .notStarted:
return true
case .win, .loss, .inProgress:
return false
}
case .inProgress:
switch rhs
{
case .inProgress:
return true
case .notStarted, .loss, .win:
return false
}
case .win:
switch rhs
{
case .win:
return true
case .notStarted, .loss, .inProgress:
return false
}
case .loss:
switch rhs
{
case .loss:
return true
case .win, .inProgress, .notStarted:
return false
}
}
}
}
enum BoardError: Error
{
case invalidMove, invalidPawn
}
protocol GameState
{
/**
A list of pawns in the game.
*/
var pawns: [Pawn] { get }
/**
The deck the players draw from at the end of each turn.
*/
var playerDeck: Deck { get }
/**
The deck that is drawn from after players draw to determine what should be infected
*/
var infectionPile: Deck { get }
/**
The number of cards that will be drawn from the infection pile after each player draws.
*/
var infectionRate: InfectionRate { get }
/**
The number of outbreaks that have occurred in the game so far.
*/
var outbreaksSoFar: Int { get }
/**
The maximum number of outbreaks that can occur before without losing the game.
*/
var maxOutbreaks: Int { get }
/**
A dictinoary of disease cubes to the number of cubes of that color that
can be placed on the board.
*/
var cubesRemaining: [DiseaseColor : Int] { get }
/**
List of diseases that are not cured.
*/
var uncuredDiseases: [DiseaseColor] { get }
/**
List of diseases that are cured
*/
var curedDiseases: [DiseaseColor] { get }
/**
Whether the game is still in progress, lost, or won.
*/
var gameStatus: GameStatus { get }
/**
The locations for the game.
*/
var locations: [BoardLocation] { get }
/**
The pawn who is currently executing their turn and how many actions they have left.
*/
var currentPlayer: Pawn { get }
/**
The number of actions remaining in this turn.
*/
var actionsRemaining: Int { get }
/**
Returns the current location of the given pawn on the board.
- Parameters:
- pawn: the pawn being queried.
- Returns: the location of the pawn on the board.
- Throws: `BoardError.invalidpawn` when the pawn is not in the game
*/
func location(of pawn: Pawn) -> BoardLocation
/**
Get all the legal moves for the current state of the game.
- Returns: a list of legal actions for the current state.
- Note: these actions are for the pawn whose turn it is currently.
*/
func legalActions() -> [Action]
/**
Executes the given action on the game state.
- Parameters:
- action: the action being executed
- Throws: `BoardError.invalidMove` when the move is invalid
- Returns: the gamestate after the action is executed
- Note: this executes the action as the pawn whose turn it is currently.
*/
func execute(action: Action) throws -> (GameState, Reward)
/**
Returns all the legal actions in the current state for the given pawn.
- Parameters:
- pawn: the pawn being queried.
- Returns: the actions that the pawn can legally make.
- Throws: `BoardError.invalidpawn` when the pawn is not in the game
*/
func legalActions(for pawn: Pawn) -> [Action]
/**
Moves the given pawn by doing the given action.
- Parameters:
- pawn: the pawn that is performing the action.
- action: the action that is being performed.
- Throws: `BoardError.invalidMove` if the move is invalid.
- `BoardError.invalidPawn` when the pawn is not in the game
- Returns: the state of the game after the transition and the reward
correlated with the action taken.
*/
func transition(pawn: Pawn, for action: Action) throws -> (GameState, Reward)
/**
Returns the current hand for the given pawn.
- Parameters:
- pawn: the pawn that is the subject of the query.
- Returns: the hand of the given pawn.
- Throws: `BoardError.invalidpawn` when the pawn is not in the game
*/
func hand(for pawn: Pawn) throws -> HandProtocol
/**
Does the first round of infecting and changes the game status to inProgress.
- Returns: the new gameboard with the updated state.
*/
func startGame() -> GameState
}
| true
|
689f6d63262375379cdc1069624e12b60b50f0de
|
Swift
|
Ashotovich1990/algorithms
|
/leetCode/993.swift
|
UTF-8
| 1,103
| 3.25
| 3
|
[] |
no_license
|
class Solution {
func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool {
if root == nil {
return false
} else {
let firstValue = self.traverse(root: root, parent: root!, value: x, depth: 1)
let secondValue = self.traverse(root: root, parent: root!, value: y, depth: 1)
if firstValue != nil && secondValue != nil {
return firstValue![0] == secondValue![0] && firstValue![1] != secondValue![1]
} else {
return false
}
}
}
func traverse(root: TreeNode?, parent: TreeNode, value: Int, depth: Int) -> [Int]? {
if root == nil {
return nil
} else if root!.val == value {
return [depth, parent.val]
} else {
if let res = self.traverse(root: root!.left, parent: root!, value: value, depth: depth + 1) {
return res;
} else {
return self.traverse(root: root!.right, parent: root!, value: value, depth: depth + 1)
}
}
}
}
| true
|
226395c7061489227884f4028e4fd50e15d44980
|
Swift
|
brokenhandsio/admin-panel
|
/Sources/AdminPanel/Models/AdminPanelUserRole/AdminPanelUserRole.swift
|
UTF-8
| 2,134
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
import Fluent
import Vapor
public protocol RoleType: LosslessStringConvertible, Comparable, Codable {
var menuPath: String { get }
}
extension AdminPanelUser {
public enum Role: String {
static let schema = "admin_panel_user_role"
case superAdmin
case admin
case user
public var weight: UInt {
switch self {
case .superAdmin: return 3
case .admin: return 2
case .user: return 1
}
}
public typealias RawValue = String
public init?(rawValue: String?) {
switch rawValue {
case Role.superAdmin.rawValue: self = .superAdmin
case Role.admin.rawValue: self = .admin
case Role.user.rawValue: self = .user
default: return nil
}
}
}
}
extension AdminPanelUser.Role: RoleType {
public var menuPath: String {
switch self {
case .superAdmin:
return "Layout/Partials/Sidebars/superadminMenu"
case .admin:
return "Layout/Partials/Sidebars/adminMenu"
case .user:
return "Layout/Partials/Sidebars/userMenu"
}
}
public init?(_ description: String) {
guard let role = AdminPanelUser.Role(rawValue: description) else {
return nil
}
self = role
}
public var description: String {
return self.rawValue
}
public static func < (lhs: AdminPanelUser.Role, rhs: AdminPanelUser.Role) -> Bool {
return lhs.weight < rhs.weight
}
public static func == (lhs: AdminPanelUser.Role, rhs: AdminPanelUser.Role) -> Bool {
return lhs.weight == rhs.weight
}
}
extension AdminPanelUser {
func requireRole(role: AdminPanelUser.Role?) throws -> AdminPanelUser.Role {
guard
let selfRole = self.role,
let role = role,
selfRole >= role
else {
throw Abort(.unauthorized)
}
return role
}
}
extension AdminPanelUser.Role: CaseIterable {}
extension AdminPanelUser.Role: Content {}
| true
|
6cbce12d931708528a5893132ed3ed252bc530a7
|
Swift
|
Arcovv/CalendarUtility
|
/Sources/CalendarUtility/Separator.swift
|
UTF-8
| 2,178
| 2.828125
| 3
|
[] |
no_license
|
public enum Separator {
public static func separating(rawValue contexts: ArraySlice<DateContext>) -> DateContextSeparating {
let daysOfWeek = 7
var result = Array(repeating: DateContext.placeholder, count: daysOfWeek)
for context in contexts {
// Fill the weekly days array by weekday index.
result[context.weekdayIndex] = context
// When context is SAT, the result is whole filled.
if context.weekdayIndex == result.count - 1 {
break
}
// When context is the last day, should ignore the remained elements.
if context.isLastDayOfThisMonth {
break
}
}
let remainedContexts = contexts.dropFirst(result.filter(isNotFake).count)
return DateContextSeparating(
extracted: ArraySlice(result),
remained: remainedContexts
)
}
public static func weekContexts(
rawValue dateContexts: ArraySlice<DateContext>
) -> [WeekContext]
{
var result: [WeekContext] = []
var separating = Separator.separating(rawValue: dateContexts)
result.append(WeekContext(days: Array(separating.extracted)))
while !separating.remained.isEmpty {
separating = Separator.separating(rawValue: separating.remained)
result.append(WeekContext(days: Array(separating.extracted)))
}
return result
}
public static func monthContexts(weekContexts: [WeekContext], monthInfos: [MonthInfo]) -> [MonthContext] {
var monthContexts: [MonthContext] = []
var weekContextsSlice = ArraySlice(weekContexts)
for monthInfo in monthInfos {
let weeks = weekContextsSlice.prefix(monthInfo.weeksCount)
let context = MonthContext(
info: monthInfo,
weeks: applyMonthInfo(monthInfo)(Array(weeks))
)
monthContexts.append(context)
weekContextsSlice = weekContextsSlice.dropFirst(monthInfo.weeksCount)
}
return monthContexts
}
}
public struct DateContextSeparating {
public var extracted: ArraySlice<DateContext>
public var remained: ArraySlice<DateContext>
public var usefulExtracted: ArraySlice<DateContext> {
extracted.filter { !$0.isPlaceholder }
}
}
| true
|
57d0a489fb0d7df6cf20f8ff0007c617ea1abea3
|
Swift
|
arifmh18/iosChatFirebase
|
/Chat Firebase/Resource/DatabaseManagement.swift
|
UTF-8
| 1,908
| 2.984375
| 3
|
[] |
no_license
|
//
// DatabaseManagement.swift
// Chat Firebase
//
// Created by algostudio on 21/07/20.
// Copyright © 2020 algostudio. All rights reserved.
//
import Foundation
import FirebaseDatabase
final class DatabaseManagement{
static let shared = DatabaseManagement()
private let database = Database.database().reference()
static func safeEmail(emailAddress: String) -> String {
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
return safeEmail
}
}
extension DatabaseManagement{
public func userExists(with email:String, completion: @escaping((Bool) -> Void) ){
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
database.child("users/\(safeEmail)").observeSingleEvent(of: .value) { (snapshot) in
guard snapshot.value as? String != nil else {
completion(false)
return
}
completion(true)
}
}
public func insertUser(with user: ChatUser){
database.child("users/\(user.safeEmail)").setValue([
"nameFull":user.namaLengkap,
"streetAddress":user.streetAddress,
"email":user.emailAddress,
"avatar":user.avatar
])
}
}
struct ChatUser {
let namaLengkap: String
let emailAddress: String
let avatar : String
let streetAddress: String
var safeEmail: String{
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
return safeEmail
}
var profilePictureFileName: String {
//afraz9-gmail-com_profile_picture.png
return "\(safeEmail)_profile_picture.png"
}
}
| true
|
22da0af4198fbc7940d92d971ed320bf15672fab
|
Swift
|
possel/chomp-ios
|
/Chomp/Classes/RootNavigationManager.swift
|
UTF-8
| 1,698
| 2.8125
| 3
|
[
"ISC"
] |
permissive
|
//
// RootNavigationManager.swift
// Chomp
//
// Created by Sky Welch on 09/10/2015.
// Copyright © 2015 Sky Welch. All rights reserved.
//
import UIKit
class RootNavigationManager {
let authManager: AuthManager
let session: SessionManager
let websocket: ChompWebsocket
var rootNavigationController: UINavigationController?
init(authManager: AuthManager, session: SessionManager, websocket: ChompWebsocket) {
self.authManager = authManager
self.session = session
self.websocket = websocket
self.makeControllers()
}
func makeControllers() {
var rootViewController: UIViewController
if self.authManager.doesUserHaveTokenStored() {
print("user has token stored, setting root view controller to overview")
rootViewController = self.constructOverviewViewController()
} else {
print("user has no token stored, setting root view controller to login")
rootViewController = self.constructLoginViewController()
}
self.rootNavigationController = UINavigationController(rootViewController: rootViewController)
Styling.styleNavigationBar(self.rootNavigationController!.navigationBar)
}
func constructOverviewViewController() -> OverviewViewController {
let (user, token) = self.authManager.getUserAndToken()!
return OverviewViewController(user: User(id: 1, name: user, token: token), session: self.session, websocket: self.websocket)
}
func constructLoginViewController() -> LoginViewController {
return LoginViewController(authManager: self.authManager)
}
}
| true
|
dc31aa9939a6f856e851610f1fbfcdbf2946c677
|
Swift
|
jeffc0216/iOS-Swift-GuessNumbers
|
/TestPlayground.playground/Contents.swift
|
UTF-8
| 2,564
| 3.796875
| 4
|
[
"MIT"
] |
permissive
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class GuessNumberbase {
let MAX_NUMBERS = 4
func isValidNumber(input:String) -> Bool {
// check length
let inputLength = input.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
guard inputLength == MAX_NUMBERS else {
return false
}
// check if it is a number
guard Int(input) != nil else {
return false
}
// check if there is any duplicate number
let inputSet = Set(input.characters)
guard inputSet.count == MAX_NUMBERS else {
return false
}
return true
}
func checkAB(testInput:String,answerInput:String) -> (A:Int,B:Int)? {
// check if inputs are valid
guard isValidNumber(testInput) && isValidNumber(answerInput) else {
return nil
}
// check A and B
let testArray = Array(testInput.characters)
let answerArray = Array(answerInput.characters)
var resultA = 0
var resultB = 0
for i in 0..<MAX_NUMBERS {
for j in 0..<MAX_NUMBERS {
if testArray[i] == answerArray[j] {
if i == j {
resultA += 1
}else{
resultB += 1
}
}
}
}
return (A:resultA,B:resultB)
}
}
let base = GuessNumberbase()
base.isValidNumber("123")
base.isValidNumber("123a")
base.isValidNumber("1234")
base.isValidNumber("1233")
base.checkAB("1234", answerInput: "5678")
base.checkAB("1234", answerInput: "4321")
base.checkAB("1234", answerInput: "2134")
class GuessNumberHost:GuessNumberbase {
private var appNumberString = ""
var userGuessCounter = 0
override init() {
super.init()
generateAppNumberString()
}
private func generateAppNumberString() {
var availables = ["0","1","2","3","4","5","6","7","8","9"]
for _ in 1...MAX_NUMBERS {
let tmpIndex = Int(arc4random() % UInt32(availables.count))
let tmpNumber = availables[tmpIndex]
appNumberString += tmpNumber
availables.removeAtIndex(tmpIndex)
}
print("appNumberString: \(appNumberString)")
}
}
let host1 = GuessNumberHost()
host1.appNumberString
| true
|
88315cf95ff8f63da89230de265e3d0b1663a727
|
Swift
|
tyork/spectrogeddon
|
/CommonCode/ColumnRenderer.swift
|
UTF-8
| 3,613
| 2.609375
| 3
|
[] |
no_license
|
//
// ColumnRenderer.swift
// SpectrogeddonOSX
//
// Created by Tom York on 24/05/2019.
// Copyright © 2019 Spectrogeddon. All rights reserved.
//
import GLKit
/// Renders a column, a single measurement set.
public class ColumnRenderer {
public var useLogFrequencyScale: Bool {
didSet {
hasInvalidatedVertices = true
}
}
public var colorMapImage: CGImage? {
didSet {
texture = nil
}
}
public var positioning: GLKMatrix4
private var texture: GLKTextureInfo?
private var mesh: ShadedMesh?
private var hasInvalidatedVertices: Bool
init() {
self.positioning = GLKMatrix4Identity
self.hasInvalidatedVertices = false
self.useLogFrequencyScale = false
}
func render() {
guard let colorMap = colorMapImage, let mesh = mesh else {
return
}
if texture == nil {
texture = try? GLKTextureLoader.texture(with: colorMap, options: nil)
}
guard let texture = texture else {
return
}
glBindTexture(GLenum(GL_TEXTURE_2D), texture.name)
mesh.render()
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
}
private func loadTexture() {
}
func updateVertices(timeSequence: TimeSequence, offset: Float, width: Float) {
guard !timeSequence.values.isEmpty else {
return
}
let vertexCountForSequence = Int(timeSequence.values.count * 2)
if mesh == nil {
mesh = ShadedMesh(numberOfVertices: vertexCountForSequence)
hasInvalidatedVertices = true
} else if mesh?.numberOfVertices != vertexCountForSequence {
mesh?.resize(vertexCountForSequence)
hasInvalidatedVertices = true
}
if hasInvalidatedVertices {
mesh?.updateVertices { storage in
self.generateVertexPositions(vertices: storage)
}
hasInvalidatedVertices = false
}
mesh?.updateVertices { storage in
for valueIndex in (0..<timeSequence.values.count) {
let vertexIndex = Int(valueIndex << 1)
let value = timeSequence.values[valueIndex]
storage[vertexIndex].t = value
storage[vertexIndex+1].t = value
}
}
let translation = GLKMatrix4MakeTranslation(offset, 0, 0)
mesh?.transform = GLKMatrix4Multiply(GLKMatrix4Scale(translation, width, 1, 1), positioning)
}
private func generateVertexPositions(vertices: UnsafeMutableBufferPointer<TexturedVertexAttribs>) {
guard let count = mesh?.numberOfVertices else {
return
}
let numberOfVertices = Int(count)
let logOffset: Float = 0.001 // Safety margin to ensure we don't try taking log2(0)
let logNormalization = 1/log2(logOffset)
let yScale = 1 / Float(numberOfVertices/2 - 1)
for valueIndex in (0..<numberOfVertices/2) {
let vertexIndex = valueIndex << 1
let y: Float
if useLogFrequencyScale {
y = 1.0 - logNormalization * log2(Float(valueIndex) * yScale + logOffset)
} else {
y = Float(valueIndex)*yScale
}
vertices[vertexIndex] = TexturedVertexAttribs(x: 0, y: y, s: 0, t: 0)
vertices[vertexIndex+1] = TexturedVertexAttribs(x: 1, y: y, s: 0, t: 0)
}
}
}
| true
|
a53568161f02e78dc0b6c761c27ee9dc832ce893
|
Swift
|
pitt500/ActorsDemo
|
/Starter/ActorsDemo/Views/ChatTextfield.swift
|
UTF-8
| 953
| 3.046875
| 3
|
[] |
no_license
|
//
// ChatTextfield.swift
// ChatTextfield
//
// Created by Pedro Rojas on 22/07/21.
//
import SwiftUI
struct ChatTextfield: View {
@ObservedObject var viewModel: GroupChatViewModel
var body: some View {
HStack {
TextField("Enter your message", text: $viewModel.text)
.padding([.leading, .trailing], 10)
Button {
viewModel.addNewMessageFromTextField()
} label: {
Image(systemName: buttonImageName)
.resizable()
.frame(width: 20, height: 20)
}
.disabled(viewModel.isTextfieldEmpty)
}
}
}
extension ChatTextfield {
var buttonImageName: String {
viewModel.isTextfieldEmpty ? "paperplane" : "paperplane.fill"
}
}
struct ChatTextfield_Previews: PreviewProvider {
static var previews: some View {
ChatTextfield(viewModel: GroupChatViewModel())
}
}
| true
|
75005b60dbb0209288c81b4ade32c98a6358cb67
|
Swift
|
SecSaul/IP-Locator
|
/IP Locator/ViewControllers/ViewController.swift
|
UTF-8
| 823
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// IP Locator
//
// Created by Saular Raffi on 5/7/19.
// Copyright © 2019 SaularRaffi. All rights reserved.
//
// https://ipstack.com/documentation
// https://ipstack.com/quickstart
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var IP_Address: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func searchButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "goToSecondViewController", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToSecondViewController" {
let destinationVC = segue.destination as! SecondViewController
destinationVC.ip_address = IP_Address.text!
}
}
}
| true
|
f92585bd6e14e5e78abd48d703ed0c29bb6368d1
|
Swift
|
yaojiqian/Swift-Programming-Learning
|
/Table and Collection Views/ProvidingHeaderAndFooterInaCollectionView/ProvidingHeaderAndFooterInaCollectionView/ViewController.swift
|
UTF-8
| 3,898
| 3.125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ProvidingHeaderAndFooterInaCollectionView
//
// Created by Yao Jiqian on 20/09/2017.
// Copyright © 2017 BigBit Corp. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController {
let allImages = [
UIImage(named: "1"),
UIImage(named: "2"),
UIImage(named: "3")
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
/* Register the nib with the collection view for easy retrieval */
let nib = UINib(nibName: "MyCollectionViewCell", bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: "cell")
/* Register the header's nib */
let headerNib = UINib(nibName: "Header", bundle: nil)
collectionView?.register(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
/* Register the footer's nib */
let footerNib = UINib(nibName: "Footer", bundle: nil)
collectionView?.register(footerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer")
collectionView?.backgroundColor = .white
}
required convenience init?(coder aDecoder: NSCoder) {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = 20
flowLayout.minimumInteritemSpacing = 10
flowLayout.itemSize = CGSize(width: 80, height: 80)
flowLayout.scrollDirection = .vertical
flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
/* Set the reference size for the header and the footer views */
flowLayout.headerReferenceSize = CGSize(width: 300, height: 50)
flowLayout.footerReferenceSize = CGSize(width: 300, height: 50)
self.init(collectionViewLayout : flowLayout)
}
func randomImage() -> UIImage{
return allImages[Int(arc4random_uniform(UInt32(allImages.count)))]!
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Int(3 + arc4random_uniform(5))
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return Int(2 + arc4random_uniform(4))
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let viewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
viewCell.backgroundImage.image = randomImage()
return viewCell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var identifier = "header"
if kind == UICollectionElementKindSectionFooter{
identifier = "footer"
}
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)
if kind == UICollectionElementKindSectionHeader {
if let header = view as? Header {
header.label.text = "Header \(indexPath.section + 1)"
}
}
else if kind == UICollectionElementKindSectionFooter {
if let footer = view as? Footer {
let t = "Section Footer \(indexPath.section + 1)"
footer.button.setTitle(t, for: .normal)
}
}
return view
}
}
| true
|
8acf25cc846226395e3c30e21f219de53aa9f28d
|
Swift
|
jemmons/BagOfTricks
|
/Tests/BagOfTricksTests/MaybeMemoTests.swift
|
UTF-8
| 1,367
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
import BagOfTricks
class MaybeMemoTests: XCTestCase {
func testSingleInit() {
let expectedInit = expectation(description: "Waiting for single init.")
var memo = MaybeMemo<Int> {
defer { expectedInit.fulfill() }
return 26 + 16
}
XCTAssertEqual(42, memo.value())
XCTAssertEqual(42, memo.value())
XCTAssertEqual(42, memo.value())
wait(for: [expectedInit], timeout: 1)
}
func testNilFactory() {
let memo = MaybeMemo<Int> { nil }
XCTAssertNil(memo.value())
XCTAssertNil(memo.value())
XCTAssertNil(memo.value())
}
func testInvalidation() {
var state = 42
let memo = MaybeMemo<Int> { state }
XCTAssertEqual(42, memo.value())
XCTAssertEqual(42, memo.value())
memo.invalidate()
XCTAssertEqual(42, memo.value())
state = 64
XCTAssertEqual(42, memo.value())
memo.invalidate()
XCTAssertEqual(64, memo.value())
}
func testMaybeFactoryDoesNotCacheNil() {
var state = true
let memo = MaybeMemo<Int> { state ? 42 : nil }
XCTAssertEqual(42, memo.value())
XCTAssertEqual(42, memo.value())
state = false
memo.invalidate()
XCTAssertNil(memo.value())
XCTAssertNil(memo.value())
state = true
//No invalidate!
XCTAssertEqual(42, memo.value())
XCTAssertEqual(42, memo.value())
}
}
| true
|
26fa104f88c0918cd74bd75fef998db7bf4d7fa0
|
Swift
|
Nicholas-Swift/VaporServer
|
/Sources/App/Extensions/PasswordCredentials.swift
|
UTF-8
| 526
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// PasswordCredentials.swift
// VaporServer
//
// Created by Alex Aaron Peña on 4/19/17.
//
//
import Foundation
import Turnstile
/**
PasswordCredentials represents a password.
*/
public class PasswordCredentials: Credentials {
/// Username (set once user is created)
public var username: String
/// Password (unhashed)
public let password: String
/// Initializer for PasswordCredentials
public init(password: String) {
self.username = ""
self.password = password
}
}
| true
|
9f89a5d36c7d58d83eb6508d520a05321d6587cc
|
Swift
|
emckee4/IntensityAttributingKit
|
/Sources/PressureView.swift
|
UTF-8
| 5,469
| 2.640625
| 3
|
[] |
no_license
|
//
// PressureView.swift
// IntensityAttributingKit
//
// Created by Evan Mckee on 11/6/15.
// Copyright © 2015 McKeeMaKer. All rights reserved.
//
import UIKit
///The PressureView is basically the same as PressureKey except that its base class is UIView instead of UILabel.
class PressureView:UIView, PressureControl {
lazy var rawIntensity:RawIntensity = RawIntensity()
weak var delegate:PressureKeyActionDelegate?
var contentView:UIView!
var actionName:String!
override var backgroundColor:UIColor? {
didSet{contentView?.backgroundColor = self.backgroundColor}
}
fileprivate var contentConstraints:[NSLayoutConstraint] = []
///Color for background of selected cell if 3dTouch (and so our dynamic selection background color) are not available.
var selectionColor = UIColor.darkGray
fileprivate func setBackgroundColorForIntensity(){
guard !IAKitPreferences.deviceResourcesLimited else {return}
guard self.backgroundColor != nil else {return}
//guard forceTouchAvailable else {contentView?.backgroundColor = selectionColor; return}
let intensity = rawIntensity.currentIntensity
guard intensity! > 0 else {contentView.backgroundColor = self.backgroundColor; return}
var white:CGFloat = -1.0
var alpha:CGFloat = 1.0
self.backgroundColor!.getWhite(&white, alpha: &alpha)
let newAlpha:CGFloat = max(alpha * CGFloat(1 + intensity!), 1.0)
let newWhite:CGFloat = white * CGFloat(1 - intensity!)
contentView?.backgroundColor = UIColor(white: newWhite, alpha: newAlpha)
}
///When the touch ends this sets the background color to normal
fileprivate func resetBackground(){
contentView.backgroundColor = self.backgroundColor
}
init() {
super.init(frame: CGRect.zero)
setupKey()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupKey()
}
func setupKey(){
self.translatesAutoresizingMaskIntoConstraints = false
//set default background
self.backgroundColor = UIColor.lightGray
self.isMultipleTouchEnabled = false
self.clipsToBounds = true
}
func setAsSpecialKey(_ contentView:UIView, actionName:String){
_ = contentConstraints.map({$0.isActive = false})
contentConstraints = []
self.contentView = contentView
contentView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(contentView)
contentConstraints.append(contentView.topAnchor.constraint(equalTo: self.topAnchor))
contentConstraints.append(contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor))
contentConstraints.append(contentView.leftAnchor.constraint(equalTo: self.leftAnchor))
contentConstraints.append(contentView.rightAnchor.constraint(equalTo: self.rightAnchor))
_ = contentConstraints.map({$0.isActive = true})
contentView.backgroundColor = self.backgroundColor
self.actionName = actionName
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard contentView != nil else {return}
//there should be one and only one touch in the touches set in touchesBegan since we have multitouch disabled
if let touch = touches.first {
//rawIntensity = RawIntensity(withValue: touch.force,maximumPossibleForce: touch.maximumPossibleForce)
rawIntensity.updateIntensity(withTouch: touch)
setBackgroundColorForIntensity()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard contentView != nil else {return}
if let touch = touches.first {
if point(inside: touch.location(in: self), with: event){
//rawIntensity.append(touch.force)
rawIntensity.updateIntensity(withTouch: touch)
setBackgroundColorForIntensity()
} else {
//rawIntensity.reset()
rawIntensity.cancelInteraction()
resetBackground()
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard contentView != nil else {return}
let lastVal = rawIntensity.endInteraction(withTouch: touches.first)
if let touch = touches.first {
if point(inside: touch.location(in: self), with: event){
//rawIntensity.append(touch.force)
if actionName != nil {
self.delegate?.pressureKeyPressed(self, actionName: self.actionName, intensity: lastVal)
if self.delegate == nil {
print("delegate not set for PressureView with action \(actionName)")
}
}
}
}
self.resetBackground()
//rawIntensity.reset()
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
self.resetBackground()
//rawIntensity.reset()
rawIntensity.cancelInteraction()
}
}
| true
|
602bb4ec0834fd2c171f3aec4034c588fef8eeb9
|
Swift
|
rubensantiago/elsa-programming-challenge
|
/Voice Memo/ElsaCore/Sources/ElsaCore/VoiceRecorder.swift
|
UTF-8
| 1,579
| 2.75
| 3
|
[] |
no_license
|
//
// VoiceRecorder.swift
// Voice Memo
//
// Created by Rubén on 10/21/20.
//
import AVFoundation
import Foundation
public class VoiceRecorder: ObservableObject {
fileprivate var audioRecorder: AVAudioRecorder!
fileprivate var recordingSession: AVAudioSession = AVAudioSession.sharedInstance()
fileprivate var audioRecordingAllowed = false
public var recordingID = UUID()
public init() { }
public func start() {
setupRecordingSession()
}
public func stop() {
audioRecorder.stop()
try? recordingSession.setCategory(.playback, mode: .default)
}
public func archiveRecording() {
let memo = Memo(title: nil,
text: SpeechRecognizer.shared.outputStream,
audio: File(id: self.recordingID))
DataStore.save(object: memo, with: memo.id.uuidString)
}
}
fileprivate extension VoiceRecorder {
func setupRecordingSession() {
do {
try recordingSession.setCategory(.record, mode: .default)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission { allowed in
if allowed {
self.audioRecordingAllowed = true
self.startVoiceRecorder()
} else {
self.audioRecordingAllowed = false
}
}
} catch {
print(error)
}
}
func startVoiceRecorder() {
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: recordingID.recordingURL, settings: settings)
audioRecorder.record()
} catch {
stop()
}
}
}
| true
|
bd98a0b8201e02d019a66f9f11ebcd90b9ef3c0a
|
Swift
|
dubeboy/IoGInfrastructure-iOS
|
/IoG InfrastructureTests/IoGDataParsingTests.swift
|
UTF-8
| 2,346
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// IoGDataParsingTests.swift
// IoG InfrastructureTests
//
// Created by Eric Crichlow on 1/16/19.
// Copyright © 2018 Infusions of Grandeur. All rights reserved.
//
import XCTest
@testable import IoGInfrastructure
class IoGDataParsingTests: XCTestCase
{
override func setUp()
{
super.setUp()
}
override func tearDown()
{
super.tearDown()
}
func testParseSingleObject()
{
let computer = IoGDataObjectManager.sharedManager.parseObject(objectString: IoGTestConfigurationManager.parsingObjectData, toObject: TestComputerObject.self)
XCTAssertNotNil(computer)
XCTAssertEqual(computer.model, "TRS-80 Color Computer 2")
XCTAssertEqual(computer.processor, "6809")
}
func testFailedObjectParse()
{
let computer = IoGDataObjectManager.sharedManager.parseObject(objectString: "", toObject: TestComputerObject.self)
XCTAssertNotNil(computer)
XCTAssertEqual(computer.model, "")
XCTAssertEqual(computer.processor, "")
}
func testParseObjectArray()
{
let computerArray = IoGDataObjectManager.sharedManager.parseArray(arrayString: IoGTestConfigurationManager.parsingObjectArrayData, forObject: TestComputerObject.self)
XCTAssertEqual(computerArray.count, 3)
var index = 0
for nextComputer in computerArray
{
switch index
{
case 0:
XCTAssertNotNil(nextComputer)
XCTAssertEqual(nextComputer.model, "TRS-80 Color Computer 2")
XCTAssertEqual(nextComputer.processor, "6809")
case 1:
XCTAssertNotNil(nextComputer)
XCTAssertEqual(nextComputer.model, "TRS-80 Color Computer 3")
XCTAssertEqual(nextComputer.processor, "68B09E")
case 2:
XCTAssertNotNil(nextComputer)
XCTAssertEqual(nextComputer.model, "MM/1")
XCTAssertEqual(nextComputer.processor, "68070")
default:
break
}
index += 1
}
}
func testFailedArrayParse()
{
let computerArray = IoGDataObjectManager.sharedManager.parseArray(arrayString: "", forObject: TestComputerObject.self)
XCTAssertEqual(computerArray.count, 0)
}
func testRetrieveUnlabeledProperty()
{
let computer = IoGDataObjectManager.sharedManager.parseObject(objectString: IoGTestConfigurationManager.parsingObjectData, toObject: TestComputerObject.self)
let year = computer.getValue("year") as! String
XCTAssertNotNil(computer)
XCTAssertEqual(year, "1980")
}
}
| true
|
0525c74b2ae10d88d70c0260cadb913f54447b28
|
Swift
|
oper0960/CoinCraft
|
/CoinCraft/CoinCraft/Presentation/RIBs/News/NewsViewController.swift
|
UTF-8
| 2,579
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// NewsViewController.swift
// CoinCraft
//
// Created by Gilwan Ryu on 2020/02/11.
// Copyright © 2020 Gilwan Ryu. All rights reserved.
//
import RIBs
import RxSwift
import RxCocoa
import UIKit
import SafariServices
import Domain
protocol NewsPresentableListener: class {
// MARK: - To Interactor
func getNewsList()
func getSelectedNews(index: Int)
}
final class NewsViewController: UIViewController {
weak var listener: NewsPresentableListener?
@IBOutlet weak var newsTableView: UITableView!
private let indicator = IndicatorView(type: .loading)
private var news = [NewsViewable]() {
didSet {
newsTableView.reloadData()
}
}
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
indicator.play(view: self.view)
setup()
setRx()
listener?.getNewsList()
}
}
// MARK: - Setup
extension NewsViewController {
private func setup() {
newsTableView.register(UINib(nibName: "NewsCardCell", bundle: nil), forCellReuseIdentifier: "newsCell")
newsTableView.delegate = self
newsTableView.dataSource = self
}
private func setRx() {
newsTableView.rx
.itemSelected
.subscribe (onNext: { [weak self] indexPath in
guard let self = self else { return }
self.indicator.play(view: self.view)
self.listener?.getSelectedNews(index: indexPath.row)
}).disposed(by: disposeBag)
}
}
// MARK: - NewsPresentable
extension NewsViewController: NewsPresentable {
func setNews(news: [NewsViewable]) {
self.news = news
indicator.stop()
}
func stopIndicator() {
indicator.stop()
}
}
// MARK: - NewsViewControllable
extension NewsViewController: NewsViewControllable {
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension NewsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return news.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let newsCell = tableView.dequeueReusableCell(withIdentifier: "newsCell", for: indexPath) as! NewsCardCell
newsCell.bind(news: news[indexPath.row])
return newsCell
}
}
| true
|
141186e8b8750d3b35d9eb509e1d2185c90ac4ec
|
Swift
|
jamirdurham/LeetCode
|
/Math/Integer to Roman/Solution/integer-to-roman.playground/Contents.swift
|
UTF-8
| 1,248
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
import Foundation
// https://leetcode.com/problems/integer-to-roman/
class Solution {
func intToRoman(_ num: Int) -> String {
let decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
let numerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
var result = "", number = num
while number > 0 {
for (i, d) in decimals.enumerated() {
if number - d >= 0 {
number -= d
result += numerals[i]
break
}
}
}
return result
}
}
import XCTest
// Executed 5 tests, with 0 failures (0 unexpected) in 0.033 (0.035) seconds
class Tests: XCTestCase {
private let s = Solution()
func testExample1() { XCTAssert(s.intToRoman(3) == "III") } // success
func testExample2() { XCTAssert(s.intToRoman(4) == "IV") } // success
func testExample3() { XCTAssert(s.intToRoman(9) == "IX") } // success
func testExample4() { XCTAssert(s.intToRoman(58) == "LVIII") } // success
func testExample5() { XCTAssert(s.intToRoman(1994) == "MCMXCIV") } // success
}
Tests.defaultTestSuite.run()
| true
|
cb96368f4070fdb972ae56af9bfc1987e255a409
|
Swift
|
Glovo/Caishen
|
/Pod/Classes/Cards/CardType.swift
|
UTF-8
| 12,465
| 3.234375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// CardType.swift
// Caishen
//
// Created by Sagar Natekar on 11/23/15.
// Copyright © 2015 Prolific Interactive. All rights reserved.
//
import Foundation
private enum Constants {
static let defaultGrouping = [4, 4, 4, 4]
}
/**
A `CardType` is a predefined type for different bank cards. Examples include "Visa" or "American Express", each of which have slightly different formats for their payment card information. Card types are determined by the Issuer Identification Number (IIN) of a card number, which is equal to the first six digits of a card number.
*/
public protocol CardType {
/**
- returns: The card type name (e.g.: Visa, MasterCard, ...)
*/
var name: String { get }
/**
- returns: The number of digits expected in the Card Validation Code.
*/
var CVCLength: Int { get }
/**
The card number grouping is used to format the card number when typing in the card number text field.
For Visa Card types for example, this grouping would be [4,4,4,4], resulting in a card number format like
0000-0000-0000-0000.
- returns: The grouping of digits in the card number.
*/
var numberGroupings: [[Int]] { get }
/**
Card types are typically identified by their first n digits. In compliance to ISO/IEC 7812, the first digit is the *Major industry identifier*, which is equal to:
- 1, 2 for airlines
- 3 for Travel & Entertainment (non-banks like American Express, DinersClub, ...)
- 4, 5 for banking and financial institutions
- 6 for merchandising and banking/financial (Discover Card, Laser, China UnionPay, ...)
- 7 for petroleum and other future industry assignments
- 8 for healthcare, telecommunications and other future industry assignments
- 9 for assignment by national standards bodies
The first 6 digits also are the *Issuer Identification Number*, indicating the issuer of the card.
In order to identify the card issuer, this function returns a Set of integers which indicate the card issuer. In case of Discover for example, this is the set of [(644...649),(622126...622925),(6011)], which contains different Issuer Identification Number ranges which are reserved for Discover.
- important: When creating custom card types, you should make sure, that there are no conflicts in the Issuer Identification Numbers you provide. For example, using [309] to detect a Diners Club card and using [3096] to detect a JCB card will not cause issues as IINs are parsed with the highest numbers first, i.e. the numbers that provide the most context possible, which will return a JCB card in this case. However, no two card types should provide the exact same number (like [309] to detect both a Diners Club card and a JCB card)!
- returns: A set of numbers which, when being found in the first digits of the card number, indicate the card issuer.
*/
var identifyingDigits: Set<Int> { get }
/**
Validates the card verification code.
- important: This validation does not mean that the CVC will be accepted by the card issuer! In order to validate the card with the card issuer, you should opt for the integration of a [Payment Gateway](https://en.wikipedia.org/wiki/Payment_gateway) to confirm the authenticity of the entered CVC.
- parameter cvc: The card verification code as indicated on the payment card.
- returns: The validation result for the CVC, taking the current card type into account, as different card issuers can provide CVCs in different formats.
*/
func validate(cvc: CVC) -> CardValidationResult
/**
A boolean flag that indicates whether CVC validation is required for this card type or not.
Setting this value to false will hide the CVC text field from the `CardTextField` and remove the required validation routine.
*/
var requiresCVC: Bool { get }
/**
A boolean flag that indicates whether expiry validation is required for this card type or not.
Setting this value to false will hide the month and year text field from the `CardTextField` and remove the required
validation routine.
*/
var requiresExpiry: Bool { get }
/**
Validates the card number.
- important: This validation incorporates the validation of the card number length, a test for the [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) and a check, whether or not the card number only contains numeric digits. Within *Caishen*, no validation with a card issuer takes place and you should opt for the integration of a [Payment Gateway](https://en.wikipedia.org/wiki/Payment_gateway) to confirm the authenticity of the entered card number.
- parameter number: The card number.
- returns: The result of the card number validation.
*/
func validate(number: Number) -> CardValidationResult
/**
Validates the card's expiry date, checking whether the card has expired or not.
- parameter expiry: The card's expiry.
- returns: The result of the card expiration date validation.
*/
func validate(expiry: Expiry) -> CardValidationResult
/**
Returns whether or not `self` is equal to another `CardType`.
- parameter cardType: Another card type to check equality with.
- returns: Whether or not `self` is equal to the provided `cardType`.
*/
func isEqual(to cardType: CardType) -> Bool
}
extension CardType {
public func isEqual(to cardType: CardType) -> Bool {
return cardType.name == self.name
}
public var requiresExpiry: Bool {
return true
}
public var requiresCVC: Bool {
return true
}
public var numberGroupings: [[Int]] {
return [Constants.defaultGrouping]
}
public var maxLength: Int {
return numberGroupings
.map { $0.reduce(0, +) }
.max() ?? 0
}
public func numberGrouping(for length: Int) -> [Int] {
let closestGroupingIndex = self.expectedCardNumberLengths()
.map { abs($0 - maxLength) }
.enumerated()
.min { $0.element < $1.element }?
.offset
guard let closestGroupingIndex = closestGroupingIndex else {
return Constants.defaultGrouping
}
return self.numberGroupings[closestGroupingIndex]
}
public func validate(cvc: CVC) -> CardValidationResult {
guard requiresCVC else {
return .Valid
}
guard let _ = cvc.toInt() else {
return .InvalidCVC
}
if cvc.length > CVCLength {
return .InvalidCVC
} else if cvc.length < CVCLength {
return .CVCIncomplete
}
return .Valid
}
public func validate(number: Number) -> CardValidationResult {
return lengthMatchesType(number.length)
.union(numberIsNumeric(number))
.union(numberIsValidLuhn(number))
}
public func validate(expiry: Expiry) -> CardValidationResult {
guard requiresExpiry else {
return .Valid
}
guard expiry != Expiry.invalid else {
return .InvalidExpiry
}
let currentDate = Date()
let expiryDate = expiry.rawValue
if expiryDate.timeIntervalSince1970 < currentDate.timeIntervalSince1970 {
return CardValidationResult.CardExpired
} else {
return CardValidationResult.Valid
}
}
/**
You can implicitly set this property by providing `numberGrouping` when implementing this protocol.
- returns: The number of digits that are contained in a card number of card type `self`.
*/
public func expectedCardNumberLengths() -> [Int] {
return self.numberGroupings.map { grouping in
grouping.reduce(0) { $0 + $1 }
}
}
/**
- parameter number: A card number which should be checked for compliance to the [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm).
- returns: True if the card number complies to the Luhn algorithm. False if it does not.
*/
public func numberIsValidLuhn(_ number: Number) -> CardValidationResult {
var odd = true
var sum = 0
let digits = NSMutableArray(capacity: number.length)
for i in 0..<number.length {
// If the number is not long enough, fail the Luhn test
guard let digit = number.description[i,i+1] else {
return CardValidationResult.LuhnTestFailed
}
digits.add(NSString(string: digit))
}
for obj in digits.reverseObjectEnumerator() {
let digitString = obj as! NSString
var digit = digitString.integerValue
odd = !odd
if odd {
digit = digit * 2
}
if digit > 9 {
digit = digit - 9
}
sum += digit
}
if sum % 10 == 0 {
return CardValidationResult.Valid
} else {
return CardValidationResult.LuhnTestFailed
}
}
/**
Checks whether or not a card number is partially valid.
- parameter cardNumber: The card number which should be checked for partial validity.
- returns: Valid, if
- the card validation succeeded
- or the card validation failed because of the Luhn test or insufficient card number length (both of which are irrelevant for incomplete card numbers).
*/
public func checkCardNumberPartiallyValid(_ cardNumber: Number) -> CardValidationResult {
let validationResult = validate(number: cardNumber)
let completeNumberButLuhnTestFailed = !validationResult.isSuperset(of: CardValidationResult.NumberIncomplete) && validationResult.isSuperset(of: CardValidationResult.LuhnTestFailed)
if completeNumberButLuhnTestFailed {
return validationResult
} else {
return
self.validate(number: cardNumber)
.subtracting(.NumberIncomplete)
.subtracting(.LuhnTestFailed)
}
}
/**
Helper method for `lengthMatchesType` to check the actual length of a card number against the expected length.
- parameter actualLength: The length of a card number that is to be validated.
- parameter expectedLength: The expected length for the card number's card type.
- returns: CardValidationResult.Valid if the lengths match, CardValidationResult.NumberDoesNotMatchType otherwise.
*/
private func testLength(_ actualLength: Int, assumingLengths expectedLengths: [Int]) -> CardValidationResult {
if expectedLengths.contains(actualLength) {
return .Valid
} else if actualLength < expectedLengths.min() ?? 0 {
return .NumberIncomplete
} else if actualLength > maxLength {
return .NumberTooLong
} else {
return .NumberDoesNotMatchType
}
}
/**
Checks the length of a card number against `self`.
- parameter length: The count of the card number's digits.
- returns: `CardValidationResult.Valid` if the card number has the right amount of digits for `self`
- `.NumberIncomplete`: The card number is too short
- `.NumberTooLong`: The card number is too long
- `.NumberDoesNotMatchType`: The card number's Issuer Identification Number does not match `self`
*/
public func lengthMatchesType(_ length: Int) -> CardValidationResult {
return testLength(length, assumingLengths: expectedCardNumberLengths())
}
/**
Checks whether or not the card number only contains numeric digits.
- parameter number: The card number.
- returns: `CardValidationResult.Valid` if the card number contains only numeric characters.
- `.NumberIsNotNumeric`: Otherwise.
*/
public func numberIsNumeric(_ number: Number) -> CardValidationResult {
for c in number.description {
if !["0","1","2","3","4","5","6","7","8","9"].contains(c) {
return CardValidationResult.NumberIsNotNumeric
}
}
return CardValidationResult.Valid
}
}
| true
|
6d778b8bfe1230a230eb83cb319e01f9ef8bd2cd
|
Swift
|
Tornquist/Time-Client
|
/Shared/Tests/Test_DateHelper.swift
|
UTF-8
| 7,815
| 3
| 3
|
[] |
no_license
|
//
// Test_DateHelper.swift
// Shared-Tests
//
// Created by Nathan Tornquist on 2/25/19.
// Copyright © 2019 nathantornquist. All rights reserved.
//
import XCTest
@testable import TimeSDK
class Test_DateHelper: XCTestCase {
// MARK: - Iso In/Out
func test_stringFromDateWithMilliseconds() {
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = DateComponents(
year: 2018,
month: 3,
day: 12,
hour: 8,
minute: 32,
second: 53,
nanosecond: 342000000
)
let date = calendar.date(from: components)!
let dateStringExplicit = DateHelper.isoStringFrom(date: date, includeMilliseconds: true)
let dateStringDefault = DateHelper.isoStringFrom(date: date)
XCTAssertEqual(dateStringExplicit, "2018-03-12T08:32:53.342Z")
XCTAssertEqual(dateStringExplicit, dateStringDefault)
}
func test_stringFromDateWithoutMilliseconds() {
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = DateComponents(
year: 2018,
month: 3,
day: 12,
hour: 8,
minute: 32,
second: 53
)
let date = calendar.date(from: components)!
let dateString = DateHelper.isoStringFrom(date: date, includeMilliseconds: false)
XCTAssertEqual(dateString, "2018-03-12T08:32:53Z")
}
func test_dateFromStringWithMilliseconds() {
let dateString = "2019-02-25T03:09:53.394Z"
let date = DateHelper.dateFrom(isoString: dateString)
XCTAssertNotNil(date)
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date!)
XCTAssertEqual(dateComponents.year, 2019)
XCTAssertEqual(dateComponents.month, 2)
XCTAssertEqual(dateComponents.day, 25)
XCTAssertEqual(dateComponents.hour, 3)
XCTAssertEqual(dateComponents.minute, 9)
XCTAssertEqual(dateComponents.second, 53)
XCTAssertEqual(Double(dateComponents.nanosecond ?? 0) * 0.000001, 394.0, accuracy: 0.1)
}
func test_dateFromStringWithoutMilliseconds() {
let dateString = "2019-02-25T03:09:53Z"
guard let date = DateHelper.dateFrom(isoString: dateString) else {
XCTFail("Parsed date not found.")
return
}
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date)
XCTAssertEqual(dateComponents.year, 2019)
XCTAssertEqual(dateComponents.month, 2)
XCTAssertEqual(dateComponents.day, 25)
XCTAssertEqual(dateComponents.hour, 3)
XCTAssertEqual(dateComponents.minute, 9)
XCTAssertEqual(dateComponents.second, 53)
XCTAssertEqual(dateComponents.nanosecond, 0)
}
func test_badIsoString() {
let dateString = "March 3rd, 2019"
let date = DateHelper.dateFrom(isoString: dateString)
XCTAssertNil(date)
}
// MARK: - Timezones
func test_safeTimezoneRealTimezone() {
let realTimezoneIdentifier = "Europe/Zurich"
let safeTimezone = DateHelper.getSafeTimezone(identifier: realTimezoneIdentifier)
XCTAssertEqual(safeTimezone.identifier, realTimezoneIdentifier)
}
func test_safeTimezoneFakeTimezone() {
let realTimezoneIdentifier = "America/Zurich"
let safeTimezone = DateHelper.getSafeTimezone(identifier: realTimezoneIdentifier)
let currentTimezone = TimeZone.autoupdatingCurrent
XCTAssertEqual(safeTimezone.identifier, currentTimezone.identifier)
}
// MARK: - Date Ranges
static func getStartOf(range: TimeRange, with incomingDateString: String) -> Date? {
// Shared defaults of gregorian calendar in Chicago for all date range tests
let calendarIdentifier: Calendar.Identifier = .gregorian
let outputTimezone = "America/Chicago"
var calendar = Calendar(identifier: calendarIdentifier)
calendar.timeZone = DateHelper.getSafeTimezone(identifier: outputTimezone)
guard
let incomingDate = DateHelper.dateFrom(isoString: incomingDateString) else {
return nil
}
let startOfRange = DateHelper.getStartOf(range, with: incomingDate, for: calendar)
return startOfRange
}
static func evalute(incoming: String, against expected: String, with range: TimeRange) {
guard
let startOfRange = Test_DateHelper.getStartOf(range: range, with: incoming),
let expectedResult = DateHelper.dateFrom(isoString: expected)
else {
XCTFail("Could not build test dates")
return
}
XCTAssertEqual(startOfRange.timeIntervalSince1970, expectedResult.timeIntervalSince1970, accuracy: 1.0)
}
func test_getStartOfDay() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2021-01-15T06:00:00+00:00"
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: TimeRange(current: .day))
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: TimeRange(rolling: .day))
}
func test_startOfCurrentWeek() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2021-01-10T06:00:00+00:00"
let timeRange = TimeRange(current: .week)
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: timeRange)
}
func test_startOfRollingWeek() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2021-01-08T06:00:00+00:00"
let timeRange = TimeRange(rolling: .week)
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: timeRange)
}
func test_startOfCurrentMonth() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2021-01-01T06:00:00+00:00"
let timeRange = TimeRange(current: .month)
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: timeRange)
}
func test_startOfRollingMonth() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2020-12-15T06:00:00+00:00"
let timeRange = TimeRange(rolling: .month)
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: timeRange)
}
func test_startOfCurrentYear() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2021-01-01T06:00:00+00:00"
let timeRange = TimeRange(current: .year)
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: timeRange)
}
func test_startOfRollingYear() {
let incomingDateString = "2021-01-15T12:35:00-06:00"
let expectedResultString = "2020-01-15T06:00:00+00:00"
let timeRange = TimeRange(rolling: .year)
Test_DateHelper.evalute(incoming: incomingDateString, against: expectedResultString, with: timeRange)
}
}
| true
|
4d40bb806508024ccdd7c1023847d01100a9333e
|
Swift
|
grantsingleton/Reporter
|
/Reporter/Utility/PDFBuilder.swift
|
UTF-8
| 41,585
| 3.046875
| 3
|
[] |
no_license
|
//
// PDFBuilder.swift
// Reporter
//
// Created by Grant Singleton on 12/1/19.
// Copyright © 2019 Grant Singleton. All rights reserved.
//
import UIKit
import CoreLocation
extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ jpegQuality: JPEGQuality) -> Data? {
return jpegData(compressionQuality: jpegQuality.rawValue)
}
}
class PDFBuilder {
//MARK: Data Properties
var job: Job
var jobLocationName: String
var jobDescription: String
//MARK: Page Properties
let topMargin: CGFloat = 18.0
let verticalSpace: CGFloat = 10.0 // distance between lines
let doubleVerticalSpace: CGFloat = 20.0
let sideMargin: CGFloat = 50.0
var center: CGFloat = 0.0
let centerMargin: CGFloat = 20
let spaceBar: CGFloat = 5.0
// I dont know if I like this variable but here it is
// Height of a paragraph word
let wordHeight: CGFloat = 0.0
// Set the font for the title
let titleFont = UIFont(name: "Helvetica Bold", size: 14)
let titleBackupFont = UIFont.systemFont(ofSize: 14, weight: .bold)
// set font for smaller title
let smallTitleFont = UIFont(name: "Helvetica Bold", size: 12)
let smallTitleBackupFont = UIFont.systemFont(ofSize: 12, weight: .bold)
// Set font for paragraphs
let paragraphFont = UIFont(name: "Helvetica", size: 12)
let paragraphBackupFont = UIFont.systemFont(ofSize: 12, weight: .regular)
init(job: Job, jobLocationName: String, jobDescription: String) {
self.job = job
self.jobLocationName = jobLocationName
self.jobDescription = jobDescription
}
func buildPDF() -> Data {
/*
SET PAGE CONTENT PROPERTIESiop;[']
*/
let locationTitle = self.jobLocationName
let jobDescription = self.jobDescription
let jobNumber = self.job.jobNumber!
let reportNumber = "Daily Field Report " + String(self.job.reportNumber!)
let dayOfVisit = "Day of Visit: " + self.job.date
// get the current date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
let todaysDate = Date()
let dateString = dateFormatter.string(from: todaysDate)
// Set the issue date to be todays date
let issueDate = "Issued: " + dateString
let issuedBy = "Issued by: " + self.job.issuedBy!
let purposeTitle = "Purpose of Visit:"
let purposeOfVisit = self.job.purposeOfVisit!
// Count the number of flags
let redFlagsCount = countFlags(type: JobContentItem.Severity.RED)
let yellowFlagsCount = countFlags(type: JobContentItem.Severity.YELLOW)
let greenFlagsCount = countFlags(type: JobContentItem.Severity.GREEN)
// This is where we list the flags that are in the report
let findingsTitle = "Findings of Visit:"
let redFlags = "Red Flags - " + String(redFlagsCount)
let yellowFlags = "Yellow Flags - " + String(yellowFlagsCount)
let greenFlags = "Green Flags - " + String(greenFlagsCount)
/*
SET PAGE FORMATTING PROPERTIES
*/
let pageWidth = 612 // 8.5 * 72
let pageHeight = 11 * 72
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
// calculate center
self.center = pageRect.size.width / 2
// Create a pdf renderer with those dimensions
let renderer = UIGraphicsPDFRenderer(bounds: pageRect)
// set attributes (font) of pdf text
let data = renderer.pdfData { (context) in
context.beginPage()
//MARK: Begin Cover Page
// **FIXME** temp hardcode of logo image
let logoImage = UIImage(named: "Zero6Logo")
let logoImageData = logoImage?.jpeg(.lowest)
let compressedLogoImage = UIImage(data: logoImageData!)
let bottomOfLogo = addLogoImage(pageRect: pageRect, imageTop: topMargin, image: compressedLogoImage!)
//MARK: Centered Title
// Job Location Title
var bottomOfTitle = addTitle(pageRect: pageRect, titleTop: bottomOfLogo + 18, title: locationTitle, titleFont: titleFont ?? titleBackupFont)
// Job Description Title
bottomOfTitle = addTitle(pageRect: pageRect, titleTop: bottomOfTitle + verticalSpace, title: jobDescription, titleFont: titleFont ?? titleBackupFont)
// Job Number Title
bottomOfTitle = addTitle(pageRect: pageRect, titleTop: bottomOfTitle + verticalSpace, title: jobNumber, titleFont: titleFont ?? titleBackupFont)
// Report Number Title
bottomOfTitle = addTitle(pageRect: pageRect, titleTop: bottomOfTitle + verticalSpace, title: reportNumber, titleFont: titleFont ?? titleBackupFont)
//MARK: Small title
// Day of Visit Title
bottomOfTitle = addTitle(pageRect: pageRect, titleTop: bottomOfTitle + verticalSpace, title: dayOfVisit, titleFont: smallTitleFont ?? smallTitleBackupFont)
//MARK: Left Title
// Issue Date Title
var bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitle + doubleVerticalSpace, title: issueDate, font: (smallTitleFont ?? smallTitleBackupFont))
// Issued By Title
bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + verticalSpace, title: issuedBy, font: (smallTitleFont ?? smallTitleBackupFont))
/*
Draw In Attendance Here (On the left)
*/
var bottomOfAttendanceTuple = bottomOfTitleTuple
var bottomOfWeatherTuple = bottomOfTitleTuple
let attendanceTitle = "In Attendance:"
bottomOfAttendanceTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + doubleVerticalSpace, title: attendanceTitle, font: (smallTitleFont ?? smallTitleBackupFont))
let attendance = self.job.inAttendance!
for person in attendance {
bottomOfAttendanceTuple = addAttendanceLineLeft(pageRect: pageRect, lineTop: bottomOfAttendanceTuple.bottom + verticalSpace, person: person, font: (paragraphFont ?? paragraphBackupFont))
}
/*
Draw Weather Here (On the right)
*/
/*
Temperature Low/High (°F) 00/00
Rain (inches) 0.00”
Humidity Min/Max 00/00
Wind Speed (MPH) Direction Avg/Gust
*/
/*
WEATHER
*/
let lowTemp = self.job.weather?.temperatureLow
let highTemp = self.job.weather?.temperatureHigh
let rainfall = self.job.weather?.rainFall
let minHumidity = self.job.weather?.humidityMin
let maxHumidity = self.job.weather?.humidityMax
let windDirection = self.job.weather?.windBearing
let avgWindSpeed = self.job.weather?.windSpeedAvg
let windGust = self.job.weather?.windGust
let tempString = String(round1Decimal(number: lowTemp!)) + "/" + String(round1Decimal(number: highTemp!))
let rainString = String(round2Decimal(number: rainfall!)) + "\""
let humidityString = String(round2Decimal(number: minHumidity!)) + "/" + String(round2Decimal(number: maxHumidity!))
let windString = degreesToDirection(degrees: windDirection!) + " @ " + String(round1Decimal(number: avgWindSpeed!)) + "/" + String(round1Decimal(number: windGust!))
let eventsString = "None"
let weatherTitle = "Weather Summary for: " + self.job.date
bottomOfWeatherTuple = addSectionTitleRight(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + doubleVerticalSpace, title: weatherTitle, font: (smallTitleFont ?? smallTitleBackupFont))
var weatherStrings: [(title: String, value: String)] = []
weatherStrings += [("Temperature Low/High (°F)", tempString)]
weatherStrings += [("Rain (inches)", rainString)]
weatherStrings += [("Humidity Min/Max", humidityString)]
weatherStrings += [("Wind Speed (MPH) Avg/Gust", windString)]
weatherStrings += [("Events", eventsString)]
for line in weatherStrings {
bottomOfWeatherTuple = addWeatherLineRight(pageRect: pageRect, lineTop: bottomOfWeatherTuple.bottom + verticalSpace, data: line, font: (paragraphFont ?? paragraphBackupFont))
}
/*
DRAW DISTRIBUTION HERE
*/
let distributionTitle = "Distribution:"
// let bottom of distribution tuple be the greater between bottom of weather and bottom of attendance
var bottomOfDistributionTuple = (bottomOfWeatherTuple.bottom > bottomOfAttendanceTuple.bottom) ? bottomOfWeatherTuple : bottomOfAttendanceTuple
bottomOfDistributionTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfDistributionTuple.bottom, title: distributionTitle, font: (smallTitleFont ?? smallTitleBackupFont))
var topForRightDistTuple = bottomOfDistributionTuple
let distribution = self.job.distribution!
var index: Int = 1
for person in distribution {
if ((index % 2) == 0) { // if even
// print on the right side of page
topForRightDistTuple = addAttendanceLineRight(pageRect: pageRect, lineTop: topForRightDistTuple.bottom + verticalSpace, person: person, font: (paragraphFont ?? paragraphBackupFont))
} else {
// print on the left side of the page
bottomOfDistributionTuple = addAttendanceLineLeft(pageRect: pageRect, lineTop: bottomOfDistributionTuple.bottom + verticalSpace, person: person, font: (paragraphFont ?? paragraphBackupFont))
}
index += 1
}
bottomOfTitleTuple = bottomOfDistributionTuple
//MARK: Purpose of Visit
// Purpose Title
bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + doubleVerticalSpace, title: purposeTitle, font: (smallTitleFont ?? smallTitleBackupFont))
// Purpose of Visit Content
let bottomOfParagraph = addParagraph(pageRect: pageRect, textTop: bottomOfTitleTuple.bottom + verticalSpace, paragraphText: purposeOfVisit, font: (paragraphFont ?? paragraphBackupFont))
//MARK: Findings of Visit (Flags)
// Finding of Visit Title
bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfParagraph + verticalSpace, title: findingsTitle, font: (smallTitleFont ?? smallTitleBackupFont))
// Flag Count
bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + verticalSpace + 10, title: redFlags, font: (smallTitleFont ?? smallTitleBackupFont))
bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + verticalSpace, title: yellowFlags, font: (smallTitleFont ?? smallTitleBackupFont))
bottomOfTitleTuple = addSectionTitleLeft(pageRect: pageRect, titleTop: bottomOfTitleTuple.bottom + verticalSpace, title: greenFlags, font: (smallTitleFont ?? smallTitleBackupFont))
//MARK: Begin Content
context.beginPage()
var bottomOfContent: CGFloat = topMargin
var photoNumber = 1
for item in self.job.content {
// draw a photo content item
if (item.photo != UIImage(named: "defaultPhoto")) {
photoNumber += 1
var compressedPhoto: UIImage;
if ((item.editedPhoto) != nil) {
// not really compressed but oh well -_-
compressedPhoto = item.editedPhoto!
}
else {
let photoData = item.photo?.jpeg(.lowest)
compressedPhoto = UIImage(data: photoData!)!
}
// If the image and three lines can fit on the page then draw it on the page, otherwise start a new page (Add an AI which resizes image if it barely doesnt fit)
if imageCanFitOnPage(pageRect: pageRect, imageTop: bottomOfContent, image: compressedPhoto, font: (smallTitleFont ?? smallTitleBackupFont)) {
// The next line adds the photo and the three lines (photo#, flag, title) under it. The description is drawn below
bottomOfContent = addContentItem(pageRect: pageRect, item: item, photoNumber: photoNumber, contentTop: bottomOfContent)
bottomOfContent += verticalSpace
}
// if it cant fit on the page then start a new page
else {
// begin a new page
context.beginPage()
bottomOfContent = addContentItem(pageRect: pageRect, item: item, photoNumber: photoNumber, contentTop: topMargin)
bottomOfContent += verticalSpace
}
}
// draw a text content item
else {
// draw a content only item
}
//MARK: Draw Paragraph
// if there is a long description then write it... word... by... painful... word...
if (item.longDescription != "") {
let wordArray = item.longDescription.components(separatedBy: " ")
var wordEdge = (right: sideMargin, bottom: bottomOfContent)
// Start a new line if needed
if (!newlineFits(pageRect: pageRect, edge: wordEdge, word: "Test", font: (paragraphFont ?? paragraphBackupFont))) {
context.beginPage()
wordEdge = (right: sideMargin, bottom: topMargin)
wordEdge.right = wordEdge.right - spaceBar
}
for word in wordArray {
// if word fits in row, then draw it there
if (wordFitsInRow(pageRect: pageRect, edge: wordEdge, word: word, font: (paragraphFont ?? paragraphBackupFont))) {
wordEdge = addWordToLine(pageRect: pageRect, edge: wordEdge, word: word, font: (paragraphFont ?? paragraphBackupFont))
}
// If it doesnt fit in row, then start a new line
else {
if (newlineFits(pageRect: pageRect, edge: wordEdge, word: word, font: (paragraphFont ?? paragraphBackupFont))) {
wordEdge = addNewLine(pageRect: pageRect, edge: wordEdge, word: word, font: (paragraphFont ?? paragraphBackupFont))
}
// else start a new page
else {
context.beginPage()
wordEdge = (right: sideMargin, bottom: topMargin)
// subtract spacebar from edge.right since the function addWordToLine will add spacebar. This only matters for the first word in a new line
wordEdge.right = wordEdge.right - spaceBar
wordEdge = addWordToLine(pageRect: pageRect, edge: wordEdge, word: word, font: (paragraphFont ?? paragraphBackupFont))
}
}
}
// set bottom of content to the bottom of the paragraph to be used for next content item
wordEdge.bottom += verticalSpace + getWordHeight(pageRect: pageRect, font: (paragraphFont ?? paragraphBackupFont)) + verticalSpace
bottomOfContent = wordEdge.bottom
}
}
}
return data
}
func addLogoImage(pageRect: CGRect, imageTop: CGFloat, image: UIImage) -> CGFloat {
// set the image to be at most 15% of the page height and 15% of the page width
let maxHeight = pageRect.height * 0.15
let maxWidth = pageRect.width * 0.40
// maximize size of the image while ensuring that it fits within constraints and maintains aspect ratio
let aspectWidth = maxWidth / image.size.width
let aspectHeight = maxHeight / image.size.height
let aspectRatio = min(aspectWidth, aspectHeight)
// calculate the scaled height and width to use
let scaledWidth = image.size.width * aspectRatio
let scaledHeight = image.size.height * aspectRatio
// calculate horizontal offset to center the image
let imageX = (pageRect.width - scaledWidth) / 2.0
// Create a rectangle at this coordinate with size calculated
let imageRect = CGRect(x: imageX, y: imageTop, width: scaledWidth, height: scaledHeight)
// Draw image into the rectangle this method scales the image to fit inside of the rectangle
image.draw(in: imageRect)
// return coordinates of the bottom of the image to the caller
return imageRect.origin.y + imageRect.size.height
}
func addImage(pageRect: CGRect, imageTop: CGFloat, image: UIImage) -> CGFloat {
// set the image to be at most 15% of the page height and 15% of the page width
let maxHeight = pageRect.height * 0.40
let maxWidth = pageRect.width * 0.75
// maximize size of the image while ensuring that it fits within constraints and maintains aspect ratio
let aspectWidth = maxWidth / image.size.width
let aspectHeight = maxHeight / image.size.height
let aspectRatio = min(aspectWidth, aspectHeight)
// calculate the scaled height and width to use
let scaledWidth = image.size.width * aspectRatio
let scaledHeight = image.size.height * aspectRatio
// calculate horizontal offset to center the image
let imageX = (pageRect.width - scaledWidth) / 2.0
// Create a rectangle at this coordinate with size calculated
let imageRect = CGRect(x: imageX, y: imageTop, width: scaledWidth, height: scaledHeight)
// Draw image into the rectangle this method scales the image to fit inside of the rectangle
image.draw(in: imageRect)
// return coordinates of the bottom of the image to the caller
return imageRect.origin.y + imageRect.size.height
}
// This function returns the location on the pdf that the end of the image plus 3 lines will end at
// It is useful to know if it will fit on the current page or needs to be moved to another
func imageCanFitOnPage(pageRect: CGRect, imageTop: CGFloat, image: UIImage, font: UIFont) -> Bool {
/*
First find the bottom of the image
*/
// set the image to be at most 5% of the page height and 10% of the page width
let maxHeight = pageRect.height * 0.40
let maxWidth = pageRect.width * 0.75
// maximize size of the image while ensuring that it fits within constraints and maintains aspect ratio
let aspectWidth = maxWidth / image.size.width
let aspectHeight = maxHeight / image.size.height
let aspectRatio = min(aspectWidth, aspectHeight)
// calculate the scaled height and width to use
let scaledWidth = image.size.width * aspectRatio
let scaledHeight = image.size.height * aspectRatio
// calculate horizontal offset to center the image
let imageX = (pageRect.width - scaledWidth) / 2.0
// Create a rectangle at this coordinate with size calculated
let imageRect = CGRect(x: imageX, y: imageTop, width: scaledWidth, height: scaledHeight)
var bottomOfContent = imageTop + imageRect.size.height
/*
Now find the bottom after adding three lines of text
*/
let testString = "Test String"
// set the attributes for the title
let titleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed title with the text of the title and the font
let attributedTitle = NSAttributedString(string: testString, attributes: titleAttributes)
// get the rectangle size that the text fits in
let titleStringSize = attributedTitle.size()
// return y coordinate for the bottom of the rectangle
bottomOfContent += titleStringSize.height + (verticalSpace/2.0) + titleStringSize.height + (verticalSpace/2.0) + titleStringSize.height
// check if drawing this on the page would fit or not
if ( bottomOfContent > (pageRect.size.height - topMargin) ) {
return false
} else {
return true
}
}
func addTitle(pageRect: CGRect, titleTop: CGFloat, title: String, titleFont: UIFont) -> CGFloat {
// set the attributes for the title
let titleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: titleFont]
// create an attributed title with the text of the title and the font
let attributedTitle = NSAttributedString(string: title, attributes: titleAttributes)
// get the rectangle size that the text fits in
let titleStringSize = attributedTitle.size()
// Set the top (y) of the title text to titleTop which is passed from caller
// set the x coordninate to center the title text
let titleStringRect = CGRect(x: (pageRect.width - titleStringSize.width) / 2.0, y: titleTop, width: titleStringSize.width, height: titleStringSize.height)
// Draw the title onto the page
attributedTitle.draw(in: titleStringRect)
// return y coordinate for the bottom of the rectangle
return titleStringRect.origin.y + titleStringRect.size.height
}
func addSectionTitleLeft(pageRect: CGRect, titleTop: CGFloat, title: String, font: UIFont) -> (bottom: CGFloat, right: CGFloat) {
// set the attributes for the title
let titleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed title with the text of the title and the font
let attributedTitle = NSAttributedString(string: title, attributes: titleAttributes)
// get the rectangle size that the text fits in
let titleStringSize = attributedTitle.size()
// Set the top (y) of the title text to titleTop which is passed from caller
// set the x coordninate to the left margin
let titleStringRect = CGRect(x: sideMargin, y: titleTop, width: titleStringSize.width, height: titleStringSize.height)
// Draw the title onto the page
attributedTitle.draw(in: titleStringRect)
// return y coordinate for the bottom of the rectangle
return (titleStringRect.origin.y + titleStringRect.size.height, titleStringRect.origin.x + titleStringRect.size.width)
}
func addSectionTitleRight(pageRect: CGRect, titleTop: CGFloat, title: String, font: UIFont) -> (bottom: CGFloat, right: CGFloat) {
// set the attributes for the title
let titleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed title with the text of the title and the font
let attributedTitle = NSAttributedString(string: title, attributes: titleAttributes)
// get the rectangle size that the text fits in
let titleStringSize = attributedTitle.size()
// Set the top (y) of the title text to titleTop which is passed from caller
// set the x coordninate to the left margin
let xCoordinate = center + centerMargin
let titleStringRect = CGRect(x: xCoordinate, y: titleTop, width: titleStringSize.width, height: titleStringSize.height)
// Draw the title onto the page
attributedTitle.draw(in: titleStringRect)
// return y coordinate for the bottom of the rectangle
return (titleStringRect.origin.y + titleStringRect.size.height, titleStringRect.origin.x + titleStringRect.size.width)
}
func addAttendanceLineLeft(pageRect: CGRect, lineTop: CGFloat, person: Person, font: UIFont) -> (bottom: CGFloat, right: CGFloat) {
// Draw name
// set the attributes for the name string
let stringAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed title with the text of the title and the font
let attributedString = NSAttributedString(string: person.name, attributes: stringAttributes)
// get the rectangle size that the text fits in
let stringSize = attributedString.size()
// Set the top (y) of the title text to titleTop which is passed from caller
// set the x coordninate to the left margin
let stringRect = CGRect(x: sideMargin, y: lineTop, width: stringSize.width, height: stringSize.height)
// Draw the name onto the page
attributedString.draw(in: stringRect)
// Draw "From"
// create an attributed title with the text of the title and the font
let attributedFromString = NSAttributedString(string: person.from, attributes: stringAttributes)
// get the rectangle size that the text fits in
let fromStringSize = attributedFromString.size()
// **put a check here for long names
let xCoordinate = center - centerMargin - fromStringSize.width
let fromStringRect = CGRect(x: xCoordinate, y: lineTop, width: fromStringSize.width, height: fromStringSize.height)
// Draw the name onto the page
attributedFromString.draw(in: fromStringRect)
// return the bottom of the line and the right edge
return (stringRect.origin.y + stringRect.size.height, fromStringRect.origin.x + fromStringRect.size.width)
}
func addAttendanceLineRight(pageRect: CGRect, lineTop: CGFloat, person: Person, font: UIFont) -> (bottom: CGFloat, right: CGFloat) {
// Draw title
// set the attributes for the title string
let titleStringAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed title with the text of the title and the font
let attributedTitle = NSAttributedString(string: person.name, attributes: titleStringAttributes)
// get the rectangle size that the text fits in
let titleStringSize = attributedTitle.size()
// Set the top (y) of the title text to titleTop which is passed from caller
// set the x coordninate to the left margin
let xCoordinate = center + centerMargin
let titleRect = CGRect(x: xCoordinate, y: lineTop, width: titleStringSize.width, height: titleStringSize.height)
// Draw the name onto the page
attributedTitle.draw(in: titleRect)
// Draw Weather value
// create an attributed title with the text of the title and the font
let attributedValueString = NSAttributedString(string: person.from, attributes: titleStringAttributes)
// get the rectangle size that the text fits in
let valueStringSize = attributedValueString.size()
// **put a check here for long names
let valXCoordinate = pageRect.size.width - sideMargin - valueStringSize.width
let valueStringRect = CGRect(x: valXCoordinate, y: lineTop, width: valueStringSize.width, height: valueStringSize.height)
// Draw the name onto the page
attributedValueString.draw(in: valueStringRect)
// return the bottom of the line and the right edge
return (valueStringRect.origin.y + valueStringRect.size.height, valueStringRect.origin.x + valueStringRect.size.width)
}
func addWeatherLineRight(pageRect: CGRect, lineTop: CGFloat, data: (title: String, value: String), font: UIFont) -> (bottom: CGFloat, right: CGFloat) {
// Draw title
// set the attributes for the title string
let titleStringAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed title with the text of the title and the font
let attributedTitle = NSAttributedString(string: data.title, attributes: titleStringAttributes)
// get the rectangle size that the text fits in
let titleStringSize = attributedTitle.size()
// Set the top (y) of the title text to titleTop which is passed from caller
// set the x coordninate to the left margin
let xCoordinate = center + centerMargin
let titleRect = CGRect(x: xCoordinate, y: lineTop, width: titleStringSize.width, height: titleStringSize.height)
// Draw the name onto the page
attributedTitle.draw(in: titleRect)
// Draw Weather value
// create an attributed title with the text of the title and the font
let attributedValueString = NSAttributedString(string: data.value, attributes: titleStringAttributes)
// get the rectangle size that the text fits in
let valueStringSize = attributedValueString.size()
// **put a check here for long names
let valXCoordinate = pageRect.size.width - sideMargin - valueStringSize.width
let valueStringRect = CGRect(x: valXCoordinate, y: lineTop, width: valueStringSize.width, height: valueStringSize.height)
// Draw the name onto the page
attributedValueString.draw(in: valueStringRect)
// return the bottom of the line and the right edge
return (valueStringRect.origin.y + valueStringRect.size.height, valueStringRect.origin.x + valueStringRect.size.width)
}
func addParagraph(pageRect: CGRect, textTop: CGFloat, paragraphText: String, font: UIFont) -> CGFloat {
// Set paragraph information. (wraps at word breaks)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .natural
paragraphStyle.lineBreakMode = .byWordWrapping
// Set the text attributes
let textAttributes = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: font
]
let attributedText = NSAttributedString(
string: paragraphText,
attributes: textAttributes
)
// determine the size of CGRect needed for the string that was given by caller
let paragraphSize = CGSize(width: pageRect.width - 100, height: pageRect.height)
let paragraphRect = attributedText.boundingRect(with: paragraphSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
// Create a CGRect that is the same size as paragraphRect but positioned on the pdf where we want to draw the paragraph
let positionedParagraphRect = CGRect(
x: 50,
y: textTop,
width: paragraphRect.width,
height: paragraphRect.height
)
// draw the paragraph into that CGRect
attributedText.draw(in: positionedParagraphRect)
return positionedParagraphRect.origin.y + positionedParagraphRect.size.height
}
func addWordToLine(pageRect: CGRect, edge: (right: CGFloat, bottom: CGFloat), word: String, font: UIFont) -> (right: CGFloat, bottom: CGFloat) {
// set the attributes for the word
let wordAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed word with the text of the word and the font
let attributedWord = NSAttributedString(string: word, attributes: wordAttributes)
// get the rectangle size that the text fits in
let wordSize = attributedWord.size()
// Set the top (y) of the word to bottom which is passed from caller
// set the x coordninate to the left margin
let wordRect = CGRect(x: edge.right + spaceBar, y: edge.bottom + verticalSpace, width: wordSize.width, height: wordSize.height)
// Draw the word onto the page
attributedWord.draw(in: wordRect)
// return x coordinate for right side of the word. Bottom edge stays the same
return (right: wordRect.origin.x + wordRect.size.width, bottom: edge.bottom)
}
func addNewLine(pageRect: CGRect, edge: (right: CGFloat, bottom: CGFloat), word: String, font: UIFont) -> (right: CGFloat, bottom: CGFloat) {
// set the attributes for the word
let wordAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed word with the text of the word and the font
let attributedWord = NSAttributedString(string: word, attributes: wordAttributes)
// get the rectangle size that the text fits in
let wordSize = attributedWord.size()
// Set the top (y) of the word to bottom (passed by caller) + vertical space + word height + vertical space
// set the x coordninate to the left margin
let wordRect = CGRect(x: sideMargin, y: edge.bottom + verticalSpace + wordSize.height + verticalSpace, width: wordSize.width, height: wordSize.height)
// Draw the word onto the page
attributedWord.draw(in: wordRect)
return (right: wordRect.origin.x + wordRect.size.width, bottom: edge.bottom + verticalSpace + wordRect.size.height)
}
func wordFitsInRow(pageRect: CGRect, edge: (right: CGFloat, bottom: CGFloat), word: String, font: UIFont) -> Bool {
// set the attributes for the word
let wordAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed word with the text of the word and the font
let attributedWord = NSAttributedString(string: word, attributes: wordAttributes)
// get the rectangle size that the word fits in
let wordSize = attributedWord.size()
// if adding this word fits between the margins
if ( (edge.right + spaceBar + wordSize.width) > (pageRect.size.width - sideMargin) ) {
return false
} else {
return true
}
}
func newlineFits(pageRect: CGRect, edge: (right: CGFloat, bottom: CGFloat), word: String, font: UIFont) -> Bool {
// set the attributes for the word
let wordAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed word with the text of the word and the font
let attributedWord = NSAttributedString(string: word, attributes: wordAttributes)
// get the rectangle size that the word fits in
let wordSize = attributedWord.size()
// see if adding the newline fits on the page
if ( (edge.bottom + verticalSpace + wordSize.height) > (pageRect.size.height - topMargin) ) {
return false
} else {
return true
}
}
func getWordHeight(pageRect: CGRect, font: UIFont) -> CGFloat {
let testString = "Testing"
// set the attributes for the word
let wordAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
// create an attributed word with the text of the word and the font
let attributedWord = NSAttributedString(string: testString, attributes: wordAttributes)
// get the rectangle size that the word fits in
let wordSize = attributedWord.size()
// return the height of the word
return wordSize.height
}
//MARK: Helper Functions
func flagFactory(flag: JobContentItem.Severity) -> String {
switch flag {
case JobContentItem.Severity.RED:
return "Red Flag"
case JobContentItem.Severity.YELLOW:
return "Yellow Flag"
case JobContentItem.Severity.GREEN:
return "Green Flag"
}
}
func addContentItem(pageRect: CGRect, item: JobContentItem, photoNumber: Int, contentTop: CGFloat) -> CGFloat {
var bottomOfContent = contentTop
var photoNumberString = ""
if (photoNumber >= 10) {
photoNumberString = String(photoNumber)
} else {
photoNumberString = "0" + String(photoNumber)
}
photoNumberString = "Photo " + photoNumberString
var compressedPhoto: UIImage;
if ((item.editedPhoto) != nil) {
compressedPhoto = item.editedPhoto!
}
else {
let photoData = item.photo?.jpeg(.lowest)
compressedPhoto = UIImage(data: photoData!)!
}
bottomOfContent = addImage(pageRect: pageRect, imageTop: bottomOfContent, image: compressedPhoto)
bottomOfContent = addTitle(pageRect: pageRect, titleTop: bottomOfContent, title: photoNumberString, titleFont: (smallTitleFont ?? smallTitleBackupFont))
let flagString = flagFactory(flag: item.status)
bottomOfContent = addTitle(pageRect: pageRect, titleTop: bottomOfContent + (verticalSpace / 2.0), title: flagString, titleFont: (smallTitleFont ?? smallTitleBackupFont))
bottomOfContent = addTitle(pageRect: pageRect, titleTop: bottomOfContent + (verticalSpace / 2.0), title: item.shortDescription, titleFont: (smallTitleFont ?? smallTitleBackupFont))
return bottomOfContent
}
//Used to count the number of a certain color of severity flag for a list of content items
func countFlags(type: JobContentItem.Severity) -> Int {
var count: Int = 0
for item in self.job.content {
if (item.status == type){
count += 1
}
}
return count
}
func round2Decimal(number: Double) -> Double {
//let y = Double(round(1000*x)/1000)
return round(100 * number) / 100
}
func round1Decimal(number: Double) -> Double {
//let y = Double(round(1000*x)/1000)
return round(10 * number) / 10
}
func degreesToDirection(degrees: Int) -> String {
if ( (degrees >= 340 && degrees <= 360) || (degrees >= 0 && degrees <= 20) ) {
return "N"
}
else if ( (degrees >= 20 && degrees <= 70) ) {
return "NE"
}
else if ( (degrees >= 70 && degrees <= 110) ) {
return "E"
}
else if ( (degrees >= 110 && degrees <= 160) ) {
return "SE"
}
else if ( (degrees >= 160 && degrees <= 200) ) {
return "S"
}
else if ( (degrees >= 200 && degrees <= 250) ) {
return "SW"
}
else if ( (degrees >= 250 && degrees <= 290) ) {
return "W"
}
else if ( (degrees >= 290 && degrees <= 340) ) {
return "NW"
}
return String(degrees)
}
}
| true
|
a00947e6372f0a0f755ce5a7d86675a38ae45d88
|
Swift
|
summercake/SwiftNotes
|
/01-SwiftTouch.playground/Contents.swift
|
UTF-8
| 463
| 3.90625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
// 1. How to import framework to swift
import UIKit
// 2. define identifier
var str1 : String = "Hello, playground"
let str2 : String = "Hello, playground"
let a : Int = 20;
var b : Double = 1.44;
b = 2.44;
// 3. end of sentence
// if there are more than one sentence on one line, ; must be used at end of every sentence
// if there are only one sentence on one line, ; can be ignored
// 4. print
print(b)
| true
|
8d36da75b30cc556a3900da1b64152d4fee19d00
|
Swift
|
intersailengineering/sapiens
|
/Sapiens/Shuffle.swift
|
UTF-8
| 565
| 3.34375
| 3
|
[] |
no_license
|
//
// Shuffle.swift
// Sapiens
//
// Created by Cristiano Boncompagni on 15/12/14.
// Copyright (c) 2014 Cristiano Boncompagni. All rights reserved.
//
import Foundation
extension Array {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&self[i], &self[j])
}
}
/// Return a copy of `self` with its elements shuffled
func shuffled() -> [T] {
var list = self
list.shuffle()
return list
}
}
| true
|
1368f086787f942f6c4474c8bcb9f0d804e0c909
|
Swift
|
assadiandre/3DR-Internship
|
/Extras/Low-res Ortho Leg/Low-res Ortho/OrthoMap/OrthoImageBuilder.swift
|
UTF-8
| 11,230
| 2.96875
| 3
|
[] |
no_license
|
//
// OrthoImageBuilder.swift
// Low-res Ortho
//
// Created by Andre on 7/3/18.
// Copyright © 2018 3DRobotics. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
class OrthoImageBuilder {
var allData:[OrthoImage] = []
init(pathArray:[String]) { // Initializes OrthoImageBuilder with an array of OrthoImage objects
for (index, path) in pathArray.enumerated() {
let orthoImage = OrthoImage(imagePath: path, id: index)
allData.append(orthoImage)
}
let imageLegs = sortLocationsIntoLegs(images:allData)
for (set ,leg) in imageLegs.enumerated() {
for image in leg {
findImageWithID(image.id)!.set = set + 1
print("Image\(image.path.components(separatedBy: "VideoFrame-").last!) is in set \(set + 1)")
}
}
}
func findImageWithID(_ id:Int) -> OrthoImage? {
for image in allData {
if image.id == id {
return image
}
}
return nil
}
func build() { // Builds the ortho
//self.filterAllByPitch()
self.pairAllGPSImageRef()
self.findAllTranslations()
self.pairAllSetImageRef()
self.findAllTranslations()
let newOrigin = self.findNewOrigin()
self.translateAllPoints(newOrigin: newOrigin)
}
func createImage() -> UIImage? { // Draws the ortho
let size = self.getFrameSize()
let returnValue:UIImage?
let renderer = UIGraphicsImageRenderer(size: size)
returnValue = renderer.image { context in
///Uncomment to see border
//UIColor.darkGray.setStroke()
//context.stroke(renderer.format.bounds)
for (index,orthoImage) in self.allData.enumerated() {
print(index)
orthoImage.getImage().draw(at: orthoImage.point!)
}
}
return returnValue
}
func sortLocationsIntoLegs(images: [OrthoImage]) -> [[OrthoImage]] {
guard images.count > 2 else {
return [images]
}
var allLegs: [Leg] = []
var currentLeg: Leg! {
didSet {
allLegs.append(currentLeg)
}
}
currentLeg = Leg(index: 0, images: [images[0], images[1]])
var currentLocationIndex = 2
while currentLocationIndex < images.count {
let currentImage = images[currentLocationIndex]
if currentLeg.isPointInLeg(location: currentImage.location!) {
currentLeg.addImage(image: images[currentLocationIndex])
} else {
let lastLocationInPreviousLeg = currentLeg.images.last!
currentLeg = Leg(index: allLegs.count - 1, images: [lastLocationInPreviousLeg, currentImage])
}
currentLocationIndex += 1
}
return allLegs.map{ $0.images }
}
func setAllYaw(yaw:Double) {
for image in allData {
image.setYaw(yaw)
image.update()
}
}
func findMedianYaw() -> Double {
var allYaws:[Double] = []
for image in allData {
allYaws.append(image.yaw!)
}
allYaws.sort()
return allYaws[ Int( Double(allYaws.count)/2 ) ]
}
func addData(pathArray:[String]) { // Adds OrthoImage objects to OrthoImageBuilder
for index in allData.count ..< pathArray.count {
let orthoImage = OrthoImage(imagePath: pathArray[index], id: index)
allData.append(orthoImage)
}
}
func pairAllGPSImageRef() { // Mass pairs all image references
for (index,image) in allData.enumerated() {
self.pairGPSImageRefLinear(targetImage: image, index:index)
//self.pairGPSImageRef(targetImage: image)
}
}
func pairAllSetImageRef() {
for image in allData {
self.pairSeperateSetImage(targetImage: image)
}
}
func filterAllByPitch() {
for (index,image) in allData.enumerated().reversed() {
if abs(image.pitch! + 90) > 1 {
allData.remove(at: index)
}
}
updateAllIDs() // Updates all IDs in array, need because we remove values
}
func updateAllIDs() {
for (index,image) in allData.enumerated() {
image.setID(index)
}
}
func findAllTranslations() { // Finds the translation needed for all the images
for (image) in allData {
print( "Image ID: \(image.id), Reference IDs: \(image.referenceImages[0].id)" )
print("TargetImage: \(image.path.components(separatedBy: "VideoFrame-").last!) CurrentImageRef: \(image.referenceImages[0].path.components(separatedBy: "VideoFrame-").last!) ")
image.determineImageTranslation()
}
}
func findNewOrigin() -> CGPoint { // Finds the top left most coordinate in allData
return CGPoint(x:findxMin(),y:findyMin())
}
func translateAllPoints(newOrigin:CGPoint) { // Translates all points in allData
for orthoImage in allData {
orthoImage.setTranslatedPoint(newOrigin)
}
}
func getFrameSize() -> CGSize {
let width:CGFloat = (self.findxMax() + self.allData[0].getImage().size.width/2) - (self.findxMin() - self.allData[0].getImage().size.width/2)
let height:CGFloat = (self.findyMax() + self.allData[0].getImage().size.height/2) - (self.findyMin() - self.allData[0].getImage().size.height/2)
return CGSize(width:width,height:height)
}
private func pairGPSImageRefLinear(targetImage:OrthoImage, index:Int) { // Finds smallest GPS distance in array and pairs image
var smallestDistance:Double = Double.greatestFiniteMagnitude
var currentImageRef:OrthoImage?
for i in 0 ... index {
if targetImage.id == 0 { // Sets points for first image
targetImage.point = CGPoint.zero
targetImage.points.append(CGPoint.zero)
targetImage.referencePoints.append(CGPoint.zero)
currentImageRef = targetImage
}
else if allData[i].id != targetImage.id { // All other cases
let sum:Double = targetImage.location!.distanceTo(allData[i].location!)
if sum < smallestDistance {
smallestDistance = sum
currentImageRef = allData[i]
}
}
}
targetImage.referenceImages.append( currentImageRef! )
}
func pairSeperateSetImage(targetImage:OrthoImage) {
if targetImage.id == 0 {
targetImage.points.append(CGPoint.zero )
targetImage.referencePoints.append(CGPoint.zero)
targetImage.referenceImages.append( targetImage )
}
else if targetImage.set! % 2 != 0 { // if the image set is odd
let opposingSet:Int = targetImage.set! + 2
var smallestDistance:Double = Double.greatestFiniteMagnitude
var currentImageRef:OrthoImage?
for image in allData {
if image.set == opposingSet {
let sum:Double = targetImage.location!.distanceTo(image.location!)
if sum < smallestDistance {
smallestDistance = sum
currentImageRef = image
}
}
}
if currentImageRef != nil {
targetImage.referenceImages.append(currentImageRef!)
targetImage.referencePoints.append(currentImageRef!.point!)
print( "Target Image : \(targetImage.path)" )
print( "Reference Image 0: \(targetImage.referenceImages[0].path)" )
print( "Reference Image 1: \(targetImage.referenceImages[1].path)" )
}
}
}
// func pairGPSImageRefNonLinear(targetImage:OrthoImage) {
//
// if targetImage.id == 0 {
// targetImage.setPoint( CGPoint.zero )
// targetImage.setRefPoint( CGPoint.zero )
// targetImage.setReferenceImage( targetImage )
// }
// var possiblePairs:[OrthoImage] = []
// var currentImageRef:OrthoImage?
// var smallestDistance:Double = Double.greatestFiniteMagnitude
//
// for index in 0 ..< 12 {
//
// for image in self.allData {
//
// var allowSearch:Bool = true
// for possibleImage in possiblePairs {
// if possibleImage.id == image.id {
// allowSearch = false
// }
// }
//
// if targetImage.id != image.id && allowSearch {
// print(abs( targetImage.location!.latitude - image.location!.latitude) )
// let sum:Double = targetImage.location!.distanceTo(image.location!)
// if sum < smallestDistance {
// smallestDistance = sum
// currentImageRef = image
// }
//
// }
//
// }
// print()
// possiblePairs.append(currentImageRef!)
// smallestDistance = Double.greatestFiniteMagnitude
//
// }
//
//
// for image in possiblePairs {
// print(image.id)
// }
//
//
//
// }
private func findxMax() -> CGFloat { // Finds max x coordinate in set
var xMax:CGFloat = -CGFloat.greatestFiniteMagnitude
for image in allData {
if CGFloat(image.point!.x) > xMax {
xMax = CGFloat(image.point!.x)
}
}
return xMax
}
private func findxMin() -> CGFloat { // Finds min x coordinate in set
var xMin:CGFloat = CGFloat.greatestFiniteMagnitude
for image in allData {
if CGFloat(image.point!.x) < xMin {
xMin = CGFloat(image.point!.x)
}
}
return xMin
}
private func findyMax() -> CGFloat { // Finds max y coordinate in set
var yMax:CGFloat = -CGFloat.greatestFiniteMagnitude
for image in allData {
if CGFloat(image.point!.y) > yMax {
yMax = CGFloat(image.point!.y)
}
}
return yMax
}
private func findyMin() -> CGFloat { // Finds min y coordinate in set
var yMin:CGFloat = CGFloat.greatestFiniteMagnitude
for image in allData {
if CGFloat(image.point!.y) < yMin {
yMin = CGFloat(image.point!.y)
}
}
return yMin
}
}
| true
|
ea34b59d4fdf35984fb8975496fa043048bac2be
|
Swift
|
samuelstevens/BluetoothConnector
|
/Sources/BluetoothConnector/main.swift
|
UTF-8
| 4,721
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
import IOBluetooth
import SimpleCLI
func printHelp() {
print(cliParser.helpString(CommandLine.arguments))
print("\nGet the MAC address from the list below (if your device is missing, pair it with your computer first):");
IOBluetoothDevice.pairedDevices().forEach({(device) in
guard let device = device as? IOBluetoothDevice,
let addressString = device.addressString,
let deviceName = device.name
else { return }
print("\(addressString) - \(deviceName)")
})
}
func printAndNotify(_ content: String, notify: Bool) {
if (notify) {
// we send notifications via osascript, and so it doesn't let us change the output
// if we turn off notify, and pipe the content to the applescript, we could be fine
Process.launchedProcess(launchPath: "/usr/bin/osascript", arguments: ["-e", "display notification \"\(content)\" with title \"BluetoothConnector\""])
}
print(content)
}
func turnOnBluetoothIfNeeded(notify: Bool) {
guard let bluetoothHost = IOBluetoothHostController.default(),
bluetoothHost.powerState != kBluetoothHCIPowerStateON else { return }
// Definitely not App Store safe
if let iobluetoothClass = NSClassFromString("IOBluetoothPreferences") as? NSObject.Type {
let obj = iobluetoothClass.init()
let selector = NSSelectorFromString("setPoweredOn:")
if (obj.responds(to: selector)) {
obj.perform(selector, with: 1)
}
}
var timeWaited : UInt32 = 0
let interval : UInt32 = 200000 // in microseconds
while (bluetoothHost.powerState != kBluetoothHCIPowerStateON) {
usleep(interval)
timeWaited += interval
if (timeWaited > 5000000) {
printAndNotify("Failed to turn on Bluetooth", notify: notify)
exit(-2)
}
}
}
let cliParser = SimpleCLI(configuration: [
Argument(longName: "connect", shortName: "c", type: .keyOnly, defaultValue: "false"),
Argument(longName: "disconnect", shortName: "d", type: .keyOnly, defaultValue: "false"),
Argument(longName: "status", shortName: "s", type: .keyOnly, defaultValue: "false"),
Argument(longName: "address", type: .valueOnly, obligatory: true, inputName: "00-00-00-00-00-00"),
Argument(longName: "notify", shortName: "n", type: .keyOnly, defaultValue: "false"),
Argument(longName: "print", shortName: "p", type: .keyOnly, defaultValue: "false"),
])
let dictionary = cliParser.parseArgs(CommandLine.arguments)
guard let deviceAddress = dictionary["address"] else {
printHelp()
exit(0)
}
var notify = false
if let notifyString = dictionary["notify"] {
notify = Bool(notifyString) ?? false
}
var shouldPrint = false
if let printString = dictionary["print"] {
shouldPrint = Bool(printString) ?? false
}
guard let bluetoothDevice = IOBluetoothDevice(addressString: deviceAddress) else {
printAndNotify("Device not found", notify: notify)
exit(-2)
}
if !bluetoothDevice.isPaired() {
printAndNotify("Not paired to device", notify: notify)
exit(-4)
}
var connectOnly = false
if let connectString = dictionary["connect"] {
connectOnly = Bool(connectString) ?? false
}
var disconnectOnly = false
if let disconnectString = dictionary["disconnect"] {
disconnectOnly = Bool(disconnectString) ?? false
}
var statusOnly = false
if let statusString = dictionary["status"] {
statusOnly = Bool(statusString) ?? false
}
let alreadyConnected = bluetoothDevice.isConnected()
if statusOnly {
if alreadyConnected {
print("Connected")
}
else {
print("Disconnected")
}
exit(0)
}
var error : IOReturn = -1
enum ActionType {
case Connection
case Disconnect
}
var action : ActionType
let shouldConnect = (connectOnly
|| (!connectOnly && !disconnectOnly && !alreadyConnected))
if shouldConnect {
action = .Connection
turnOnBluetoothIfNeeded(notify: notify)
error = bluetoothDevice.openConnection()
}
else {
action = .Disconnect
error = bluetoothDevice.closeConnection()
}
if error > 0 {
printAndNotify("Error: \(action) failed", notify: notify)
exit(-1)
} else if shouldPrint {
if action == .Connection && alreadyConnected {
printAndNotify("Already connected", notify: notify)
}
else if action == .Disconnect && !alreadyConnected {
printAndNotify("Already disconnected", notify: notify)
}
else {
switch action {
case .Connection:
printAndNotify("Successfully connected", notify: notify)
case .Disconnect:
printAndNotify("Successfully disconnected", notify: notify)
}
}
}
| true
|
265d8a6a44dfe375363eec689583024c329c6021
|
Swift
|
BozidarK93/PayoneerTestApp
|
/PayoneerTestApp/Model/Networks.swift
|
UTF-8
| 362
| 2.546875
| 3
|
[] |
no_license
|
//
// Networks.swift
// PayoneerTestApp
//
// Created by Bozidar Kokot on 05.05.21.
//
import Foundation
/// List response with possible payment networks
struct Networks: Decodable {
/// Collection of applicable payment networks that could be used by a customer to complete the payment in scope of this `LIST` session
let applicable: [ApplicableNetwork]
}
| true
|
f87ba2093bc9c8b598f4a70ee83c1ceecd165b95
|
Swift
|
bazylrei/fuse
|
/Fuse/Fuse/API/CompanyAPI.swift
|
UTF-8
| 1,137
| 2.71875
| 3
|
[] |
no_license
|
//
// CompanyAPI.swift
// Fuse
//
// Created by Bazyl Reinstein on 05/09/2016.
// Copyright © 2016 BazylRei. All rights reserved.
//
import UIKit
import Alamofire
import MagicalRecord
class CompanyAPI: NSObject {
class func getCompanyRequest(companyName: String, completion: (result: Company?, error: String?) -> Void) {
Alamofire.request(.GET, "https://" + companyName + Constants.URLs.findCompanyURL)
.responseJSON { response in
switch response.result {
case .Success:
print(response.response?.statusCode)
if response.response?.statusCode == 200{
guard let JSON = response.result.value else { return }
print(JSON)
MagicalRecord.saveWithBlockAndWait({ (localContext) in
let company = Company.MR_importFromObject(JSON, inContext: localContext)
completion(result: company, error: nil)
})
} else {
completion(result: nil, error: "Company not found")
}
break
case .Failure:
completion(result: nil, error: "something went wrong")
}
}
}
}
| true
|
d8c324f04fac64124137b247f12451bf0307a4e3
|
Swift
|
alexfilimon/products-list
|
/ProductsList/User stories/BLTNPageInput/BLTNPageInput.swift
|
UTF-8
| 1,472
| 2.5625
| 3
|
[] |
no_license
|
//
// BLTNPageInput.swift
// ProductsList
//
// Created by Alexander Filimonov on 28/03/2020.
// Copyright © 2020 Alexander Filimonov. All rights reserved.
//
import BLTNBoard
final class BLTNPageInput: BLTNPageItem {
// MARK: - Properties
var titleInputValue: String?
// MARK: - Private Properties
private let placeholder: String
private let desk: String?
// MARK: - Initializaion
init(title: String, description: String?, placeholder: String) {
self.placeholder = placeholder
self.desk = description
super.init(title: title)
}
// MARK: - BLTNPageItem
override func makeViewsUnderTitle(with interfaceBuilder: BLTNInterfaceBuilder) -> [UIView]? {
let descLabel = interfaceBuilder.makeDescriptionLabel()
descLabel.text = desk
let titleTextField = interfaceBuilder.makeTextField(placeholder: placeholder,
returnKey: .done,
delegate: nil)
titleTextField.addTarget(self,
action: #selector(handleChangingTitle(_:)),
for: .editingChanged)
return [desk == nil ? nil : descLabel, titleTextField].compactMap { $0 }
}
}
// MARK: - Private Properties
private extension BLTNPageInput {
@objc
func handleChangingTitle(_ sender: UITextField) {
titleInputValue = sender.text
}
}
| true
|
478fabef5098653b340432eee2d5e46b38a6b136
|
Swift
|
cojoj/XCSDemo
|
/XCSDemo/BotsTableViewController.swift
|
UTF-8
| 2,363
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// XCSDemo
//
// Created by Mateusz Zając on 29.09.2015.
//
//
import UIKit
import XcodeServerSDK
class BotsTableViewController: UITableViewController {
// MARK: Properties
lazy var server: XcodeServer = {
do {
let config = try XcodeServerConfig(host: "https://localhost")
let endpoints = XcodeServerEndpoints(serverConfig: config)
return XcodeServer(config: config, endpoints: endpoints)
} catch {
fatalError("Cannot initialize XcodeServer.")
}
}()
var bots: [Bot] = []
// MARK: View Controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Fetch bots and store them
server.getBots { bots, error in
guard let bots = bots where error == nil else {
print("Bots fetching error: \(error)")
return
}
self.bots = bots
self.tableView.reloadData()
}
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier,
index = tableView.indexPathForCell((sender as? UITableViewCell)!)?.row else { return }
switch identifier {
case "ShowBotDetails":
guard let destination = segue.destinationViewController as? DetailsViewController else { return }
destination.configure(bots[index], server: server)
default:
break
}
}
}
extension BotsTableViewController {
// MARK: Data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bots.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("BotCell", forIndexPath: indexPath)
let bot = bots[indexPath.row]
cell.textLabel?.text = bot.name
return cell
}
// MARK: Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| true
|
acc9cde8643febf711d741ad98511d4bfa4d2db2
|
Swift
|
betamatt/snell
|
/Snell/DemoProject/DemoRouter.swift
|
UTF-8
| 634
| 2.703125
| 3
|
[] |
no_license
|
//
// DemoRouter.swift
// SwiftServer
//
// Created by Jonathan Klein on 6/13/15.
// Copyright © 2015 artificial. All rights reserved.
//
import Cocoa
class DemoRouter : Router {
// The Router init is the main override point for your Snell app.
override init() {
super.init()
// Route the homepage to the "DemoController.index" action
route("/", to: DemoController.index)
// Route "/closure" to a demo of defining an action as a closure, rather than a controller
route("/closure") { (request:Request) -> Response in
return Response(status: 200, body: "<h1>An action in a closure...</h1>")
}
}
}
| true
|
5280b9b9a2d1308f210dd43e6b1006344c701bd5
|
Swift
|
HenryQuan/BatteryBar
|
/Battery/Core/Battery.swift
|
UTF-8
| 3,838
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// Battery.swift
// BatteryBar
//
// Created by Yiheng Quan on 24/7/19.
// Copyright © 2019 Yiheng Quan. All rights reserved.
//
import Cocoa
class Battery {
var allInfo = ""
/// Get time remaining for this machine
/// Returns a string like 2:12 remaning
func getTimeRemaining() -> String {
var remain = Constant.Estimate
var batteryPercentage = ""
// pmset -g batt
let output = Utils.runCommand(cmd: "/usr/bin/pmset", args: "-g", "batt").output
// Find string with format 1:23
if output.count > 1 {
let matches = Utils.matches(for: "[0-9]+:[0-9]+", in: output[1])
if matches.count > 0 {
remain = matches[0]
}
let percentMatches = Utils.matches(for: "[0-9]+%", in: output[1])
if percentMatches.count > 0 {
batteryPercentage = percentMatches[0]
}
}
// Add different emoji to distinguish different mode
if output.joined().contains("discharg") {
remain += "🔋"
} else {
remain += "⚡️"
}
// Add the percentage
remain += batteryPercentage
return remain
}
/// Get more detailed information like design/max capacity, cycle count and an estimated battery health.
/// All data are from ioreg command
func getDetailedBatteryInfo() -> String {
print("getDetailedBatteryInfo...")
// Get output from ioreg -brc AppleSmartBattery
let output = Utils.runCommand(cmd: "/usr/sbin/ioreg", args: "-brc", "AppleSmartBattery")
.output.dropLast().dropFirst().joined(separator: "\n")
self.allInfo = self.formatOutput(output: output)
let matches = Utils.matches(for: "\"(.*?)\" = (.*)", in: output)
// To format nicelt
var max = 0
var cycle = 0
var design = 0
for m in matches {
let curr = IORegString(output: m)
switch curr.description {
case "MaxCapacity":
let capacity = curr.convertValue() as! Int
if (capacity > 1000) {
#warning("This is 100 on M1")
max = capacity
}
case "AppleRawMaxCapacity":
max = curr.convertValue() as! Int
case "CycleCount":
cycle = curr.convertValue() as! Int
case "DesignCapacity":
design = curr.convertValue() as! Int
default:
break
}
}
var finalResult = ""
// There must be a design capcacity, if not we failed to get any data
if design > 0 {
finalResult += "Cycle count: \(cycle)/1000\n"
let percentage = max * 100 / design
finalResult += "Battery health: \(max)/\(design) (\(percentage)%)\n"
} else {
finalResult += "No battery information\n"
}
finalResult += "Uptime: \(self.getUpTime())\n"
return finalResult
}
/// Get uptime from 'uptime' command
private func getUpTime() -> String {
let output = Utils.runCommand(cmd: "/usr/bin/uptime", args: "").output.joined()
let matches = output.groups(for: "up (.*?),")
var uptime = "??"
// check there are matches and make sure capture is also correct
if matches.count > 0, matches[0].count > 1 {
uptime = matches[0][1]
}
return uptime
}
/// Remove = and "
private func formatOutput(output: String) -> String {
var t = output.replacingOccurrences(of: " =", with: ":")
t = t.replacingOccurrences(of: "\"", with: "")
return t
}
}
| true
|
e905412f58af6c6812275f34f5c25bd6880c9b07
|
Swift
|
Gabriel-Lewis/ProductHuntClone
|
/ph-test1/dataManager.swift
|
UTF-8
| 1,104
| 2.671875
| 3
|
[] |
no_license
|
//
// dataManager.swift
// ph-test1
//
// Created by Gabriel Benbow on 1/23/16.
// Copyright © 2016 Gabriel Benbow. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
let BASE_URL = "https://api.producthunt.com/v1/posts"
let POSTS = "posts"
let headers = [
"Authorization": "Bearer dcdd1d60db8257bd8f65371e92911b5a2e5fd09479017d7f1042bde683934796",
"Content-Type": "application/json",
"Accept": "application/json",
"Host": "api.producthunt.com"
]
class DataManager {
class func getTopAppsDataFromPHWithSuccess(success: ((PHData: NSData!) -> Void)) {
loadDataFromURL(BASE_URL) { (data, error) -> Void in
if let urlData = data {
success(PHData: urlData)
}
}
}
class func loadDataFromURL(Url: String, completion:(data: NSData?, error: NSError?) -> Void) {
Alamofire.request(.GET, Url, headers: headers)
.response { request, response, data, error in
if let responseError = error {
completion(data: nil, error: responseError)
} else if response!.statusCode != 200 {
completion(data: nil, error: error)
} else {
completion(data: data, error: nil)
}
}
}
}
| true
|
90c003ac11d9df94d6818c4238a5aeb5534b46be
|
Swift
|
ShashankKannam/CFTest
|
/CFTest/Common/CallPhoneNumberPresentable.swift
|
UTF-8
| 591
| 2.734375
| 3
|
[] |
no_license
|
//
// CallPhoneNumberPresentable.swift
// CFTest
//
// Created by Shashank Kannam on 9/18/19.
// Copyright © 2019 sk. All rights reserved.
//
import UIKit
protocol CallPhoneNumberPresentable {
/// Opens caller tuner
///
/// - Parameter phoneNumber: phone number to call
func call(phoneNumber: String)
}
extension CallPhoneNumberPresentable {
func call(phoneNumber: String) {
if let url = URL(string: "tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
| true
|
3b5b448e24e7fb01a354b1d67e82ca731bb1ed47
|
Swift
|
MacInLife/PasswordBackup
|
/PasswordBackup/Model/FireDB.swift
|
UTF-8
| 2,117
| 2.875
| 3
|
[] |
no_license
|
//
// FireDB.swift
// PasswordBackup
//
// Created by Marie-Ange Coco on 14/05/2020.
// Copyright © 2020 Marie-Ange Coco. All rights reserved.
//
import Foundation
import Firebase
//import FirebaseFirestore
class FireDB {
let store = Firestore.firestore()
//A l'inscription crée une collection des Utilisateurs (
var users : CollectionReference {
return store.collection("users")
}
//A l'ajout, crée une collection des Password (
var credentials : CollectionReference {
return store.collection("credentials")
}
func addUser(_ uid: String, data: [String: Any]) {
users.document(uid).setData(data)
}
func addCredentials(data: [String: Any], completion: @escaping (_ error: String?) -> Void) {
guard let uid = FireAuth().currentId else {
completion("Erreur, vous n'etes pas connecté !")
return
}
users.document(uid).collection("credentialsCollection").document().setData(data) { (error) in
if let error = error {
completion(error.localizedDescription)
return
}
completion(nil)
}
}
func getCredentialsCollection(completion: @escaping ([Credentials]?, String?) -> Void){
//Récupération uid
guard let uid = FireAuth().currentId else {
completion(nil, "Erreur, vous n'etes pas connecté !")
return
}
users.document(uid).collection("credentialsCollection").addSnapshotListener { (snapshot, error) in
if let error = error {
completion(nil, error.localizedDescription)
return
}
guard let snapshot = snapshot else {
completion(nil, "Erreur indéterminée")
return
}
var credentialsCollection: [Credentials] = []
let documents = snapshot.documents
for document in documents {
credentialsCollection.append(Credentials(document: document))
}
completion(credentialsCollection, nil)
}
}
}
| true
|
7d931637a7f07aa6aef5710ce4353c23b76ccd70
|
Swift
|
toseefkhilji/TopDrawer
|
/TopDrawerTests/Matchers/FolderContentsMatcherTests.swift
|
UTF-8
| 4,847
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// FolderContentsMatcherTests.swift
// MenuNav
//
// Created by Steve Barnegren on 11/08/2017.
// Copyright © 2017 SteveBarnegren. All rights reserved.
//
import XCTest
@testable import TopDrawer
class FolderContentsMatcherTests: XCTestCase {
// MARK: - Test Matching
func testMatchesFilesWithExtension() {
let folder = TestDirectoryBuilder.makeDirectory(withFileNames: ["dog.png"])
let matcher = FolderContentsMatcher.filesWithExtension("png")
XCTAssertTrue(matcher.matches(directory: folder))
}
func testFailsToMatchFilesWithExtension() {
let folder = TestDirectoryBuilder.makeDirectory(withFileNames: ["dog.gif"])
let matcher = FolderContentsMatcher.filesWithExtension("png")
XCTAssertFalse(matcher.matches(directory: folder))
}
func testMatchesFilesWithNameAndExtension() {
let folder = TestDirectoryBuilder.makeDirectory(withFileNames: ["dog.png"])
let matcher = FolderContentsMatcher.filesWithFullName("dog.png")
XCTAssertTrue(matcher.matches(directory: folder))
}
func testFailsToMatchFilesWithNameAndExtension() {
let folder = TestDirectoryBuilder.makeDirectory(withFileNames: ["dog.gif", "cat.png"])
let matcher = FolderContentsMatcher.filesWithFullName("dog.png")
XCTAssertFalse(matcher.matches(directory: folder))
}
func testMatchesFoldersWithName() {
let folder = TestDirectoryBuilder.makeDirectory(withFolderNames: ["animals"])
let matcher = FolderContentsMatcher.foldersWithName("animals")
XCTAssertTrue(matcher.matches(directory: folder))
}
func testFailsToMatchFoldersWithName() {
let folder = TestDirectoryBuilder.makeDirectory(withFolderNames: ["no animals here"])
let matcher = FolderContentsMatcher.foldersWithName("animals")
XCTAssertFalse(matcher.matches(directory: folder))
}
// MARK: - Test Equatable
func testFolderContentsMatchersAreEqualWithFilesWithExtensionCaseAndSameString() {
let firstMatcher = FolderContentsMatcher.filesWithExtension("png")
let secondMatcher = FolderContentsMatcher.filesWithExtension("png")
XCTAssertTrue(firstMatcher == secondMatcher)
}
func testFolderContentsMatchersAreNotEqualWithFilesWithExtensionCaseAndDifferentString() {
let firstMatcher = FolderContentsMatcher.filesWithExtension("png")
let secondMatcher = FolderContentsMatcher.filesWithExtension("pdf")
XCTAssertFalse(firstMatcher == secondMatcher)
}
func testFolderContentsMatchersAreEqualWithFullNameCaseAndSameString() {
let firstMatcher = FolderContentsMatcher.filesWithFullName("dog.png")
let secondMatcher = FolderContentsMatcher.filesWithFullName("dog.png")
XCTAssertTrue(firstMatcher == secondMatcher)
}
func testFolderContentsMatchersAreNotEqualWithFullNameCaseAndDifferentString() {
let firstMatcher = FolderContentsMatcher.filesWithFullName("dog.png")
let differentNameMatcher = FolderContentsMatcher.filesWithFullName("cat.png")
let differentExtMatcher = FolderContentsMatcher.filesWithFullName("dog.pdf")
XCTAssertFalse(firstMatcher == differentNameMatcher)
XCTAssertFalse(firstMatcher == differentExtMatcher)
}
func testFolderContentsMatchersAreEqualWithFolderNameCaseAndSameString() {
let firstMatcher = FolderContentsMatcher.foldersWithName("animals")
let secondMatcher = FolderContentsMatcher.foldersWithName("animals")
XCTAssertTrue(firstMatcher == secondMatcher)
}
func testFolderContentsMatchersAreNotEqualWithFolderNameCaseAndDifferentString() {
let firstMatcher = FolderContentsMatcher.foldersWithName("animals")
let secondMatcher = FolderContentsMatcher.foldersWithName("no animals here")
XCTAssertFalse(firstMatcher == secondMatcher)
}
// MARK: - Test DictionaryRepresentable
func testFolderContentsMatcherToDictionaryAndBackIsSame() {
let filesWithExtension = FolderContentsMatcher.filesWithExtension("pdf")
let filesWithNameAndExtension = FolderContentsMatcher.filesWithFullName("dog.png")
let foldersWithName = FolderContentsMatcher.foldersWithName("animals")
XCTAssertTrue(filesWithExtension == filesWithExtension.convertedToDictionaryAndBack)
XCTAssertTrue(filesWithNameAndExtension == filesWithNameAndExtension.convertedToDictionaryAndBack)
XCTAssertTrue(foldersWithName == foldersWithName.convertedToDictionaryAndBack)
}
}
| true
|
e5c66d3a173fb0ec5e95db16b8e09cd157a2509e
|
Swift
|
AdrianoSong/iOS-SwiftUI-Design_Basics
|
/SwiftUIBasics/movingOffset/MovingOffsetChallengeView.swift
|
UTF-8
| 1,815
| 3.171875
| 3
|
[] |
no_license
|
//
// MovingOffsetChallengeView.swift
// SwiftUIBasics
//
// Created by Song on 29/07/20.
// Copyright © 2020 Adriano Song. All rights reserved.
//
import SwiftUI
struct MovingOffsetChallengeView: View {
@State private var change = false
var body: some View {
GeometryReader { geometry in
VStack {
Text("Challenge").font(.largeTitle)
Text("Move the Circle Shape")
.font(.body)
.foregroundColor(.gray)
HStack {
Circle()
.frame(width: 50, height: 50)
.foregroundColor(.orange)
.padding()
.offset(
x: self.change ? geometry.size.width - 74 : 0,
y: self.change ? geometry.size.height - 200 : 0)
.animation(.easeInOut)
Spacer()
}
Spacer()
Button(action: {
self.change.toggle()
}, label: {
Text("Change")
}).padding()
}
}
}
}
struct MovingOffsetChallengeView_Previews: PreviewProvider {
static var previews: some View {
Group {
MovingOffsetChallengeView()
.previewDevice(PreviewDevice(rawValue: "iPhone SE"))
.previewDisplayName("iPhone SE")
MovingOffsetChallengeView()
.previewDevice(PreviewDevice(rawValue: "iPhone 11"))
.previewDisplayName("iPhone 11")
MovingOffsetChallengeView()
.previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro Max"))
.previewDisplayName("iPhone 11 Pro Max")
}
}
}
| true
|
701014e2cb36f7c3579253e923e1781bd590942c
|
Swift
|
kasa4565/DesignPatterns
|
/03Builder/Students/2018/KacperDębowski/Builder/FactoryVSBuilder/BurgerRestaurants/Burgers/BigMacBurger.swift
|
UTF-8
| 543
| 2.96875
| 3
|
[] |
no_license
|
//
// BigMacBurger.swift
// Builder
//
// Created by Kacper Debowski on 11/01/2019.
// Copyright © 2019 Coding Skies. All rights reserved.
//
import Foundation
class BigMacBurger: Burger {
var typeOfMeat: String
var meatPieces: Int
var veggies: [String]
var sauce: String
var cheese: Bool
var price: Float
init() {
typeOfMeat = "beef"
meatPieces = 2
veggies = ["salad", "pickle", "chopped onion"]
sauce = "special Big Mac sauce"
cheese = true
price = 9.70
}
}
| true
|
3a856b9224d9784d7b0ade07aaf018c6c561a359
|
Swift
|
htlee6/PDFspeaker-1
|
/PDFspeaker/AppDelegate.swift
|
UTF-8
| 3,909
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// AppDelegate.swift
// PDFspeaker
//
// Created by HauTen Lee on 2020/5/28.
// Copyright © 2020 HauTen Lee. All rights reserved.
//
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
// File panel set up
let panel = filePanelSetup()
// Create the window and set the content view.
// Window set up
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.center()
window.isReleasedWhenClosed = false // This line prevents app from 'EXC_BAD_ACCESS' error at runtime, see https://www.reddit.com/r/swift/comments/ghnjfg/reopen_macos_app_from_dock_icon_after_closing_the/
window.setFrameAutosaveName("Main Window")
panel.begin { response in
if response == NSApplication.ModalResponse.OK, let fileUrl = panel.url {
NotificationCenter.default.post(name: .pdfFileLoaded, object: fileUrl)
let pdfEntity = PdfEntity(pdfFilePath: fileUrl)
let contentView = ContentView().environmentObject(pdfEntity)
// window shows up after file successfully opened
self.window.contentView = NSHostingView(rootView: contentView)
self.window.makeKeyAndOrderFront(nil)
}
}
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
//MARK: God please help with this thread error
// print("flag: \(flag)")
if flag {
// print("To front")
window.orderFront(self)
} else {
// print("Recreate")
let panel = filePanelSetup()
// Create the window and set the content view.
// Window set up
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.isReleasedWhenClosed = false // This line prevents app from 'EXC_BAD_ACCESS' error at runtime, see https://www.reddit.com/r/swift/comments/ghnjfg/reopen_macos_app_from_dock_icon_after_closing_the/
window.center()
window.setFrameAutosaveName("Main Window")
panel.begin { response in
if response == NSApplication.ModalResponse.OK, let fileUrl = panel.url {
NotificationCenter.default.post(name: .pdfFileLoaded, object: fileUrl)
let pdfEntity = PdfEntity(pdfFilePath: fileUrl)
let contentView = ContentView().environmentObject(pdfEntity)
// window shows up after file successfully opened
self.window.contentView = NSHostingView(rootView: contentView)
self.window.makeKeyAndOrderFront(nil)
}
}
}
return true
}
/// Initialize a standard file panel for our app.
/// - Returns: A file open panel.
func filePanelSetup() -> NSSavePanel {
let panel = NSOpenPanel()
panel.title = "Select a file"
panel.prompt = "Choose"
panel.allowedFileTypes = ["pdf"]
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
return panel
}
}
extension Notification.Name {
static let pdfFileLoaded = Notification.Name("pdf_file_loaded")
}
| true
|
a40906ee0cf9921cf27f4e6cb75be29d0540a8ad
|
Swift
|
noscrewgiven/DailyDogs
|
/DailyDogs/Model/Breed.swift
|
UTF-8
| 2,028
| 3.234375
| 3
|
[] |
no_license
|
//
// Breed.swift
// DailyDogs
//
// Created by Ramona Cvelf on 24.03.21.
//
import Foundation
struct Breed: Hashable {
static func == (lhs: Breed, rhs: Breed) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
var didLoadImagesFromApi: Bool = false
var name: String
var images: [String]?
var subBreeds: [SubBreed] = []
struct SubBreed {
var name: String
var images: [String]?
}
private let id = UUID()
}
class BreedModel {
private let api = ApiService()
private let persistentStorage = StorageManager()
var breeds: [Breed] = []
init() {
if let persistentBreeds = persistentStorage.load() {
breeds = persistentBreeds
}
}
func getBreedByName(_ name: String) -> Breed? {
return breeds.first(where: { $0.name == name })
}
func loadImagesForBreedsAndSubBreeds(count: Int, completion: @escaping () -> Void) {
api.getImagesForAllBreedsAndSubBreeds(self.breeds, count: count, completion: { result in
switch result {
case .failure(let e):
print("Failed loading Breeds from API with \(e)")
case .success(let breeds):
self.breeds = breeds
DispatchQueue.main.async {
completion()
}
}
})
}
func loadBreedsFromApi(completion: @escaping () -> Void) {
api.getAllBreeds(completion: { result in
switch result {
case .failure(let e):
print("Failed loading Breeds from API with \(e)")
case .success(let breeds):
self.breeds = breeds
self.persistentStorage.save(breeds: self.breeds)
DispatchQueue.main.async {
completion()
}
}
})
}
}
| true
|
ba0959f8445a6f90c8c233bbe325fa20de15a6da
|
Swift
|
matthewrobertsdev/Adjustable-Clock
|
/Adjustable Clock/Code to Discard?/PreferencesWC.swift
|
UTF-8
| 1,281
| 2.65625
| 3
|
[] |
no_license
|
//
// PreferencesWC.swift
// Digital Clock
//
// Created by Matt Roberts on 7/18/17.
// Copyright © 2017 Matt Roberts. All rights reserved.
//
/*
just make the preference window the right size
could have used window restoration class
*/
/*
import Cocoa
class PreferencesWC : NSWindowController,NSWindowDelegate {
override func windowDidLoad() {
super.windowDidLoad()
//for debug
print("PreferencesWC view did load")
//make initial size permanent
window?.maxSize=CGSize(width: (window?.frame.width)!, height: (window?.frame.height)!)
window?.minSize=CGSize(width: (window?.frame.width)!, height: (window?.frame.height)!)
let preferencesWindowStateOperator=PreferencesWindowStateOperator()
preferencesWindowStateOperator.windowLoadOrigin(window: window)
}
//when closing, if appropraite save state
func windowWillClose(_ notification: Notification) {
ifAppropriatePreferencesSaveState()
}
func saveState(){
let preferencesWindowStateOperator=PreferencesWindowStateOperator()
preferencesWindowStateOperator.windowSaveOrigin(window: window)
}
@IBAction func doNothing(digitalClockToolBarIcon: NSToolbarItem){
}
}
*/
| true
|
68adf701cdf18f6d96fb7edadfe4ea3711cf4ae3
|
Swift
|
guowilling/LeetCode-Swifty
|
/LeetCodePlayground.playground/Pages/75_SortColors.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,340
| 4.09375
| 4
|
[
"MIT"
] |
permissive
|
//: [Previous](@previous)
//
// 75. Sort Colors
//
// 题目链接:https://leetcode-cn.com/problems/sort-colors/
// 标签:数组、多指针
// 要点:考察多指针的应用,一个指针指向「小端」,一个指针指向「大端」,一个指针遍历数组
// 注意遍历指针交换时的动作,仅在与小端进行交换时前进,因为与大端交换过来的元素未遍历过
// 时间复杂度:O(n)
// 空间复杂度:O(1)
//
import Foundation
class Solution {
func sortColors(_ nums: inout [Int]) {
if nums.isEmpty { return }
var current = 0, little = 0, big = nums.count - 1
while current <= big {
if nums[current] == 0 {
nums.swapAt(little, current)
little += 1
current += 1
} else if nums[current] == 2 {
nums.swapAt(big, current)
big -= 1
} else {
current += 1
}
}
}
}
// Tests
let s = Solution()
do {
var input = [2,0,2,1,1,0]
let expectOutput = [0,0,1,1,2,2]
s.sortColors(&input)
input
assert(input == expectOutput)
}
do {
var input = [1, 2, 0]
let expectOutput = [0, 1, 2]
s.sortColors(&input)
input
// assert(input == expectOutput)
}
//: [Next](@next)
| true
|
624574eb920c86901e23e0570095b036c0246b01
|
Swift
|
allisonbieber/simpleswiftapp
|
/ReadDataViewController.swift
|
UTF-8
| 4,346
| 2.96875
| 3
|
[] |
no_license
|
//
// ReadDataViewController.swift
// FirebaseProject
//
// Created by Allison Bieber on 7/2/19.
//
import UIKit
import FirebaseFirestore
import FirebaseAuth
class ReadDataViewController: UIViewController {
//Outlets for the retrieve data screen
@IBOutlet weak var retrieveDatePicker: UIDatePicker!
@IBOutlet weak var dateText: UITextField!
@IBOutlet weak var retreiveDateButton: UIButton!
@IBOutlet weak var milesText: UITextField!
@IBOutlet weak var timeText: UITextField!
@IBOutlet weak var paceText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
guard let userCollection = Auth.auth().currentUser?.email else {return}
// Do any additional setup after loading the view.
}
@IBAction func retreieveDataPressed(_ sender: Any) {
//Formats the date from the UIDatePicker
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateStr = dateFormatter.string(from: retrieveDatePicker.date)
dateFormatter.dateFormat = "MM"
let month = dateFormatter.string(from: retrieveDatePicker.date)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: retrieveDatePicker.date)
dateFormatter.dateFormat = "yyyy"
let year = dateFormatter.string(from: retrieveDatePicker.date)
//Set the date field to the full date string
dateText.text=dateStr
//Initialize the connection to the database
let db = Firestore.firestore()
// Find the document where the fields match the user input (date)
db.collection("Runs").whereField("day", isEqualTo:day).whereField("month", isEqualTo: month).whereField("year", isEqualTo: year).getDocuments { (snapshot, error) in
if error != nil {
// catches the error if one occurs
print(error as Any)
print("FAILED")
} else if snapshot?.count == 0 {
//Create a pop-up alert if no documents are found
let alert = UIAlertController(title: "Error", message: "No data found", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
// Indicate that no values were found
self.timeText.text = "none"
self.milesText.text = "none"
self.paceText.text = "none"
} else {
// else, grab all the documents with the given date String
for document in (snapshot?.documents)! {
if var minutes = document.data()["minutes"] as? Int,
let miles = document.data()["distance"] as? Double,
let seconds = document.data()["seconds"] as? Int
{
let paceTime = (Double(minutes) + Double(seconds / 60))
let run = Run(distance: miles, time: paceTime, year: year, month: month, day: day)
if minutes > 60 {
let hours = minutes / 60
minutes = minutes % 60
self.timeText.text = String(hours) + ":" + String(minutes) + ":" + String(seconds)
} else {
self.timeText.text = String(minutes) + " : " + String(seconds)
}
self.milesText.text = String(miles)
self.paceText.text = String(round((paceTime / miles) * 100) / 100)
} else {
print("failed to retrieve data")
}
}
}
}
}
/*
// 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.
}
*/
}
| true
|
2a60abfec7e0520e3deda0b4ef32461fc727fbab
|
Swift
|
JesseBryant/Ar-Galaxy-shooter
|
/AR Madness/mViewController.swift
|
UTF-8
| 1,294
| 2.609375
| 3
|
[] |
no_license
|
//
// mViewController.swift
// AR Madness
//
// Created by Jesse Bryant on 4/15/20.
// Copyright © 2020 Jesse Bryant. All rights reserved.
//
//import UIKit
//import SceneKit
//import ARKit
//class mViewController: UIViewController {
// // static let shared = mViewController()
//
// var audioPlayer = AVAudioPlayer()
//
//
// // private init() { } // private singleton init
//// init(coder decoder: NSCoder) {
//// super.init(coder: decoder)
//// }
//
//// required init?(coder: NSCoder) {
//// fatalError("init(coder:) has not been implemented")
//// }
//
//
// func setup() {
// do {
// audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!))
// audioPlayer.prepareToPlay()
//
// } catch {
// print (error)
// }
// }
//
//
// func play() {
// audioPlayer.play()
// }
//
// func stop() {
// audioPlayer.stop()
// audioPlayer.currentTime = 0 // I usually reset the song when I stop it. To pause it create another method and call the pause() method on the audioPlayer.
// audioPlayer.prepareToPlay()
// }
// }
| true
|
9cc558679d49deef10cd6301fa36cfebeffd63b6
|
Swift
|
lufthansa-group-flight-operations/arinc-834a-apidraft
|
/DemoClient-iOS/Arinc PoC/MenuView.swift
|
UTF-8
| 3,809
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright (c) Deutsche Lufthansa AG.
// Author Frank Hundrieser
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
import SwiftUI
// A simple MenuBar which controls the global activeView to control the ContentView
struct MenuView: View {
@EnvironmentObject var activeView: ViewRouter
var body: some View {
GeometryReader{ geometry in
HStack {
Spacer()
VStack {
if self.activeView.activeView == "polling" {
Image(systemName: "arrow.2.circlepath").resizable().aspectRatio(contentMode: .fit).foregroundColor(.blue)
} else {
Image(systemName: "arrow.2.circlepath").resizable().aspectRatio(contentMode: .fit).foregroundColor(.black)
}
Text("Polling").padding(.bottom,10).foregroundColor(Color.black)
}.frame(width: geometry.size.width/6,height: 75).padding(0).onTapGesture {
self.activeView.activeView="polling"
}
VStack {
if self.activeView.activeView == "subscription" {
Image(systemName: "arrow.clockwise").resizable().aspectRatio(contentMode: .fit).foregroundColor(.blue)
} else {
Image(systemName: "arrow.clockwise").resizable().aspectRatio(contentMode: .fit).foregroundColor(.black)
}
Text("Subscription").padding(.bottom,10).foregroundColor(Color.black)
}.frame(width: geometry.size.width/6,height: 75).onTapGesture {
self.activeView.activeView="subscription"
}
VStack {
if self.activeView.activeView == "file" {
Image(systemName: "folder").resizable().aspectRatio(contentMode: .fit).foregroundColor(.blue)
} else {
Image(systemName: "folder").resizable().aspectRatio(contentMode: .fit).foregroundColor(.black)
}
Text("File").padding(.bottom,10).foregroundColor(Color.black)
}.frame(width: geometry.size.width/6,height: 75).onTapGesture {
self.activeView.activeView="file"
}
VStack {
if self.activeView.activeView == "a429" {
Image(systemName: "airplane").resizable().aspectRatio(contentMode: .fit).foregroundColor(.blue)
} else {
Image(systemName: "airplane").resizable().aspectRatio(contentMode: .fit).foregroundColor(.black)
}
Text("A429").padding(.bottom,10).foregroundColor(Color.black)
}.frame(width: geometry.size.width/6,height: 75).onTapGesture {
self.activeView.activeView="a429"
}
VStack {
if self.activeView.activeView == "video" {
Image(systemName: "video").resizable().aspectRatio(contentMode: .fit).foregroundColor(.blue)
} else {
Image(systemName: "video").resizable().aspectRatio(contentMode: .fit).foregroundColor(.black)
}
Text("Video").padding(.bottom,10).foregroundColor(Color.black)
}.frame(width: geometry.size.width/6,height: 75).onTapGesture {
self.activeView.activeView="video"
}
Spacer()
}.padding(.top,20)
}
}
}
struct MenuView_Previews: PreviewProvider {
static var previews: some View {
MenuView()
}
}
| true
|
c36a3dcf2f6c2ff53aa69eda8e86d0c445ab3cba
|
Swift
|
jaeyeon302/ios-openCV
|
/usingOpencv/taskgroup/taskHandler.swift
|
UTF-8
| 4,155
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// taskHandler.swift
// usingOpencv
//
// Created by jaeyeon-park on 11/12/2018.
// Copyright © 2018 jaeyeon-park. All rights reserved.
//
/*
taskHandler class는 taskHandling class 내부에서 인스턴스화 되고 해당 인스턴스를 공유하여 사용하도록 하고 있다.
taskHandling.shareIt()을 사용하여 클래스 주소를 넘겨, task를 부탁하는 객체와 task 실행, 정지 명령을 내리는 객체들이 어디서든
동일한 taskHandler instance를 제어하도록 하였다.
taskAsker들(renderingAsker, messageAsker, processingAsker)과 viewController에서 동일한 본 클래스 인스턴스가 호출된다.
*/
import Foundation
class taskHandler:manageTasks, managePatchedTasks, executeTask{
private var displayLinker : CADisplayLink?
private var taskQ : Dictionary<taskCategory,Array<(Any)->Void>>
private var patchedTaskQ : [(Int)->Void]
private var _taskState : Int
//public check 용 : debugging용도
var taskState : Int{
get{
return _taskState
}
}
init(stdFps:Int = 5){
_taskState = 0
taskQ = Dictionary<taskCategory,Array<(Any)->Void>>()
patchedTaskQ = [(Int)->Void]()
displayLinker = CADisplayLink(target: self, selector: #selector(linkerCallback));
displayLinker?.preferredFramesPerSecond = stdFps
displayLinker?.add(to: .current, forMode: .common)
displayLinker?.isPaused = true; //등록 후 일시정지
}
@objc func linkerCallback(sender : CADisplayLink){
let signal = sender;
//아래가 제대로 동작할지 의문... 유의할 곳
//동작한다!!!!!!!
for (_,tasks) in taskQ{
for task in tasks{
task(signal)
}
}
for index in 0..<patchedTaskQ.endIndex{
patchedTaskQ[index](index)
}
//print("current taskState : \(taskState)")
}
//manageTasks protocol
func insert(task: @escaping (Any) -> Void, category: taskCategory) {
if taskQ[category] == nil {
taskQ[category] = [(Any)->Void]()
}
_taskState = _taskState + category.rawValue
taskQ[category]?.append(task)
}
func removeAll(category: taskCategory) {
if taskQ[category] != nil{
_taskState = _taskState - category.rawValue*(taskQ[category]?.count)!
taskQ[category]?.removeAll()
}
}
//managePatchedTask Protocol
func insert(patchedTask: @escaping (Int) -> Void){
patchedTaskQ.append(patchedTask)
}
func removePatchedTask(atIndex:Int){
let _ = patchedTaskQ.remove(at: atIndex)
}
//executeTasks protocol
func startTasks() {
print(_taskState)
print("START")
if displayLinker != nil && displayLinker?.isPaused != false{
displayLinker?.isPaused = false
}else{
print("displayLinker is nill or already start");
}
displayLinker?.isPaused = false;
if _taskState<=taskCategory.none.rawValue{
print("no job to start")
}
}
func stopTasks() {
if displayLinker != nil && displayLinker?.isPaused != true{
displayLinker?.isPaused = true
}else{
print("displayLinker is nil or already stop")
}
if _taskState<=taskCategory.none.rawValue{
print("no job to stop")
}
print("taks stop")
}
}
class taskHandling{
private static var _taskHandlers:[taskSize:taskHandler] = Dictionary<taskSize,taskHandler>()
static func share(magnitude:taskSize)->taskHandler{
if _taskHandlers[magnitude] == nil {
_taskHandlers[magnitude] = taskHandler(stdFps: fps[magnitude]!)
}
return _taskHandlers[magnitude]!
}
//비상시 사용하기 위해 만들었음
static func stopALL(){
for (_,handler) in _taskHandlers{
handler.stopTasks()
}
}
static func startALL(){
for (_,handler) in _taskHandlers{
handler.startTasks()
}
}
}
| true
|
c052bbff347849533b78324ff7e2574a6a909c6b
|
Swift
|
rabehssera/RAPlayer
|
/RAPlayer/RAPlayer/Models/Track.swift
|
UTF-8
| 1,471
| 2.765625
| 3
|
[] |
no_license
|
//
// Track.swift
// RAPlayer
//
// Created by Raphael Abehssera on 03/04/2018.
// Copyright © 2018 Raphael Abehssera. All rights reserved.
//
import UIKit
class Track: NSObject {
var artist = ""
var title = ""
var picture = ""
var previewURL = ""
//init from RSS Feed
init(feed: [String: Any]) {
super.init()
if let title = feed["im:name"] as? [String: Any] {
self.title = title["label"] as! String
}
if let artist = feed["im:artist"] as? [String: Any] {
self.artist = artist["label"] as! String
}
if let pictures = feed["im:image"] as? [Any] {
if let picture = pictures.last as? [String: Any] {
self.picture = picture["label"] as! String
}
}
if let links = feed["link"] as? [Any] {
if let link = links.last as? [String: Any] {
if let attributes = link["attributes"] as? [String: Any] {
self.previewURL = attributes["href"] as! String
}
}
}
}
//init from Search WebService
init(searchResult: [String: Any]) {
super.init()
self.title = searchResult["trackName"] as! String
self.artist = searchResult["artistName"] as! String
self.picture = searchResult["artworkUrl100"] as! String
self.previewURL = searchResult["previewUrl"] as! String
}
}
| true
|
17d2696bce7eca74ac20e7abe5a1246ebf8fdc37
|
Swift
|
lcs-dsierraalta/DogFacts
|
/DogFacts/Feature/Facts/Screen/FactsScreen.swift
|
UTF-8
| 804
| 2.875
| 3
|
[] |
no_license
|
//
// FactsScreen.swift
// DogFacts
//
// Created by Diego Sierraalta on 2021-10-13.
//
import SwiftUI
struct FactsScreen: View {
@StateObject private var viewModel = FactsViewModelImpl(service: FactsServiceImpl())
var body: some View {
VStack {
Text("Dog Facts 🐶")
.font(.largeTitle)
.fontWeight(.bold)
.padding()
List {
ForEach(viewModel.facts, id: \.fact) { item in
FactView(item: item)
}
}
.task {
await viewModel.getRandomFact()
}
}
}
}
struct FactsScreen_Previews: PreviewProvider {
static var previews: some View {
FactsScreen()
}
}
| true
|
e4a7defbe64fe9d8f59b0ce8fc2141041214773c
|
Swift
|
kkolontay/Bicycle-Tracker
|
/Bicycle Tracker/BTLocationManager.swift
|
UTF-8
| 3,584
| 3
| 3
|
[] |
no_license
|
//
// BTLocationManager.swift
// Bicycle Tracker
//
// Created by kkolontay on 3/10/16.
// Copyright © 2016 imvimm. All rights reserved.
//
import UIKit
import CoreLocation
protocol BTLocationManagerOutput: class {
func fetchLocationsInteractor(locations:[CLLocation], alert: Bool)
}
protocol BTLocationManagerInput {
func setPresenterProtocol(mainPresenter: BTLocationManagerOutput)
func startLocation()
func stopLocation()
}
class BTLocationManager: NSObject {
class var sharedInstances: BTLocationManager {
struct Static {
static let instance: BTLocationManager = BTLocationManager()
}
return Static.instance
}
weak var presenter: BTLocationManagerOutput?
// set location manager for 9th version iOS
@available(iOS 9.0, *)
private lazy var locationManager: CLLocationManager = {
var _locationManager = CLLocationManager()
_locationManager.delegate = self
_locationManager.desiredAccuracy = kCLLocationAccuracyBest
_locationManager.activityType = .Fitness
_locationManager.distanceFilter = 5.0
_locationManager.allowsBackgroundLocationUpdates = true
return _locationManager
}()
//set location manager for upto 9th version iOS
private lazy var locationManagerIOS8: CLLocationManager = {
var _locationManager = CLLocationManager()
_locationManager.delegate = self
_locationManager.desiredAccuracy = kCLLocationAccuracyBest
_locationManager.activityType = .Fitness
_locationManager.distanceFilter = 5.0
return _locationManager
}()
private override init() {
super.init()
getLocationManagerDependsIOSVersion().requestWhenInUseAuthorization()
getLocationManagerDependsIOSVersion().startUpdatingLocation()
}
//check version of iOS and use location manager for it
func getLocationManagerDependsIOSVersion() -> CLLocationManager {
if #available(iOS 9.0, *) {
return locationManager
}
return locationManagerIOS8
}
//send signal about power of connection
private func getAlertPoorSignal (location: CLLocation) -> Bool {
if (location.horizontalAccuracy < BTHorizontalAccuracy.NoSignal.rawValue)
{
return true
// No Signal
}
else if (location.horizontalAccuracy > BTHorizontalAccuracy.PoorSingnal.rawValue)
{
return true
// Poor Signal
}
return false
}
}
extension BTLocationManager: CLLocationManagerDelegate {
//update location data
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let alert: Bool = getAlertPoorSignal(locations.last!)
presenter?.fetchLocationsInteractor(locations, alert: alert)
}
//callback authorization status, than allow work program in background
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
getLocationManagerDependsIOSVersion().requestAlwaysAuthorization()
}
}
extension BTLocationManager: BTLocationManagerInput {
func startLocation() {
getLocationManagerDependsIOSVersion().startUpdatingLocation()
}
func stopLocation() {
getLocationManagerDependsIOSVersion().stopUpdatingLocation()
}
func setPresenterProtocol(mainPresenter: BTLocationManagerOutput) {
presenter = mainPresenter
}
}
| true
|
52bb855d29ffa4f03c83c0ba69cc4fbcc9de79cf
|
Swift
|
havishat/swiftfundamentals
|
/headsortails.playground/Contents.swift
|
UTF-8
| 643
| 4
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
func tossCoin() -> String {
let coin = Int(arc4random_uniform(UInt32(2)))
if coin == 0 {
return "Heads"
}
else {
return "Tails"
}
}
var x = tossCoin()
print(x)
func tossMultipleCoins(tosses: Int) -> Double {
var hcount = 0
var tcount = 0
for i in 0...tosses {
if tossCoin() == "Heads" {
hcount += 1
}else {
tcount += 1
}
}
print(hcount)
print(tcount)
return Double(tosses) / Double(hcount)
}
var y = tossMultipleCoins(tosses: 10)
print(y)
| true
|
cfaa4a95b921b554915009da3a6ba53254716677
|
Swift
|
fwcd/breakout
|
/Breakout/ExplodingBrick.swift
|
UTF-8
| 607
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// ExplodingBrick.swift
// Breakout
//
// Created by Fredrik on 11.04.18.
// Copyright © 2018 fwcd. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
class ExplodingBrick: BasicBrick {
private let radius: CGFloat
init(radius: CGFloat) {
self.radius = radius
}
override func getColor() -> CGColor {
return UIColor.orange.cgColor
}
override func onHit(ball: Ball) {
game.spawnExplosion(at: gridPosition, withRadius: radius)
}
override func destroyUponHit() -> Bool {
return true
}
override func affectsLevelCounter() -> Bool {
return true
}
}
| true
|
bbb252ee69a80ad12047738609cd9d9671fe6491
|
Swift
|
yangqiwei/StudySwift
|
/MyPlayground2.playground/section-1.swift
|
UTF-8
| 609
| 3.671875
| 4
|
[] |
no_license
|
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//define method 1
//var optInt:Int?
//define method 2
var optInt:Optional<Int>
println("\(optInt)")
if optInt != nil
{
println("true")
}
else
{
println("false")
}
optInt = 32
println("\(optInt!)")
if optInt != nil
{
println("true")
}
else
{
println("false")
}
let intvalue = 10
var sum = optInt! + intvalue
//var optStr:String!
var optStr:ImplicitlyUnwrappedOptional<String>
optStr = "10"
optStr
var intFromStr = optStr.toInt()
println("\(intFromStr)")
var intValueFromStr = intFromStr!
| true
|
16d35f2357c03daa7450f49c446e71987164198d
|
Swift
|
dskuznetsov/ILoveQuiz
|
/ILoveQuiz/Models/RatingsModel.swift
|
UTF-8
| 1,115
| 2.90625
| 3
|
[] |
no_license
|
//
// RatingsModel.swift
// ILoveQuiz
//
// Created by Dmitriy S. Kuznetsov on 02/09/2019.
// Copyright © 2019 Dmitriy S. Kuznetsov. All rights reserved.
//
import UIKit
class RatingModel {
// MARK: Properties
private let client: APIClient
var ratings: Ratings = []
// MARK: UI
var isLoading: Bool = false {
didSet {
showLoading?()
}
}
var showLoading: (() -> Void)?
var reloadData: (() -> Void)?
var showError: ((Error) -> Void)?
init(client: APIClient) {
self.client = client
}
func fetchRatings() {
if let client = client as? ILoveQuizClient {
self.isLoading = true
let endpoint = ILoveQuizEndpoint.rating
client.fetchRating(with: endpoint) { (either) in
switch either {
case .success(let ratings):
self.ratings = ratings
self.isLoading = false
self.reloadData?()
case .error(let error):
self.showError?(error)
}
}
}
}
}
| true
|
c14dd4386590866e670f3cb0dc7813962150aff0
|
Swift
|
Rokimkar/SampleProject
|
/IASTips/MenuTableViewCell.swift
|
UTF-8
| 724
| 2.625
| 3
|
[] |
no_license
|
//
// MenuTableViewCell.swift
// IASTips
//
// Created by S@nchit on 12/21/16.
// Copyright © 2016 S@nchit. All rights reserved.
//
import UIKit
class MenuTableViewCell: UITableViewCell {
@IBOutlet weak var contentLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.init(red: 242/255, green: 242/255, blue: 242/255, alpha: 1)
// Initialization code
}
func bindData(content : String) -> Void {
self.contentLabel.text = content
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(false, animated: true)
// Configure the view for the selected state
}
}
| true
|
4962b85458d150ccb85af641b0fc163f695a0e3f
|
Swift
|
jlgrimes/pal-pad
|
/vmax/Helpers/UX.swift
|
UTF-8
| 653
| 2.546875
| 3
|
[] |
no_license
|
//
// UX.swift
// Pal Pad
//
// Created by Jared Grimes on 12/26/19.
// Copyright © 2019 Jared Grimes. All rights reserved.
//
import SwiftUI
let swipeLRTolerance = 50
struct ActivityIndicator: UIViewRepresentable {
@Binding var isAnimating: Bool
let style: UIActivityIndicatorView.Style
func makeUIView(context: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
return UIActivityIndicatorView(style: style)
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicator>) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
}
| true
|
32f690733a23972a244b181857c7540f8c9fab95
|
Swift
|
iosdevted/Gymbo
|
/Gymbo/CornerStyle.swift
|
UTF-8
| 555
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// CornerStyle.swift
// Gymbo
//
// Created by Rohan Sharma on 6/20/20.
// Copyright © 2020 Rohan Sharma. All rights reserved.
//
import UIKit
enum CornerStyle {
case none
case xSmall
case small
case medium
case circle(length: CGFloat)
var radius: CGFloat {
switch self {
case .none:
return 0
case .xSmall:
return 5
case .small:
return 10
case .medium:
return 20
case .circle(let length):
return length / 2
}
}
}
| true
|
b004bf1635c4bbedcd5e118f46d4d99934d3a83d
|
Swift
|
haguremon/APIURLSessionMVP
|
/APIURLSessionMVP/Presenter/Presenter.swift
|
UTF-8
| 2,053
| 2.921875
| 3
|
[] |
no_license
|
//
// Presenter.swift
// APIURLSessionMVP
//
// Created by IwasakIYuta on 2021/07/28.
//https://api.github.com/users/haguremon
//https://api.github.com/users/haguremon/repos
import Foundation
protocol MygithubAPIDelegate: AnyObject {
func didsetUser(user: [GitHubHaguremon])
func didsetRepository(items: [HaguremonRepository])
}
class MygitHub {
typealias vcdelegate = MygithubAPIDelegate & ViewController
weak var delegate: vcdelegate?
func getApi(url: String) {
guard let url = URL(string:url) else { return }
let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let data = data ,
let response = response as? HTTPURLResponse,
response.statusCode == 200,
error == nil else { return }
//do連続をどうにかしたい
do {
let user = try JSONDecoder().decode(GitHubHaguremon.self, from: data)
self?.delegate?.didsetUser(user: [user])
print(user)
} catch {
print(error)
}
do {
let repository = try JSONDecoder().decode(Repository.self, from: data).items
//let items = repository.items
self?.delegate?.didsetRepository(items: repository)
} catch {
print(error)
}
}
task.resume()
}
func getHaguremon(){
getApi(url: "https://api.github.com/users/haguremon")
DispatchQueue.main.async {
self.getApi(url: "https://api.github.com/search/repositories?q=user:haguremon")
}
}
func setPresenter(delegate: vcdelegate){
self.delegate = delegate
}
}
| true
|
47a2db2b49de80b8bf9d3687056b9c4d6f0f1d0d
|
Swift
|
prasad-dot-ws/GH-Profile
|
/GH Profile/MVP/View/GHProfileView.swift
|
UTF-8
| 10,181
| 2.59375
| 3
|
[] |
no_license
|
//
// GHProfileView.swift
// GH Profile
//
// Created by Prasad De Zoysa on 4/27/21.
//
import UIKit
class ProfileView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .white
setupViews()
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Setup views
func setupViews() {
self.addSubview(scrollView)
//Adding UI elements to the view
[profileImageView, nameLabel, loginLabel, emailLabel, followersCountLabel, followingCountLabel, pinnedHeaderLabel, pinnedViewAllLabel, pinnedStackView, topRepoHeaderLabel, topRepoViewAllLabel, topRepoScroller, starredRepoHeaderLabel, starredRepoViewAllLabel, starredRepoScroller].forEach { scrollView.addSubview($0) }
[topRepoStackView].forEach { topRepoScroller.addSubview($0) }
[starredRepoStackView].forEach { starredRepoScroller.addSubview($0) }
}
//MARK: Constraints
/**
* This function applies all the required constraints to profile view
*/
func setupConstraints() {
scrollView.anchor(top: self.safeAreaLayoutGuide.topAnchor, leading: self.safeAreaLayoutGuide.leadingAnchor, bottom: self.safeAreaLayoutGuide.bottomAnchor, trailing: self.safeAreaLayoutGuide.trailingAnchor)
profileImageView.anchor(top: scrollView.topAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing: nil, padding: .init(top: 15, left: 15, bottom: 0, right: 0), size: .init(width: 70, height: 0))
profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor).isActive = true
nameLabel.anchor(top: nil, leading: profileImageView.trailingAnchor, bottom: profileImageView.centerYAnchor, trailing: self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 10, bottom: 0, right: 10))
loginLabel.anchor(top: profileImageView.centerYAnchor, leading: profileImageView.trailingAnchor, bottom: nil, trailing: self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 10, bottom: 0, right: 10))
emailLabel.anchor(top: profileImageView.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing: self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 20, left: 15, bottom: 0, right: 10))
followersCountLabel.anchor(top: emailLabel.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing: nil, padding: .init(top: 20, left: 15, bottom: 0, right: 0))
followingCountLabel.anchor(top: followersCountLabel.topAnchor, leading: followersCountLabel.trailingAnchor, bottom: nil, trailing: nil, padding: .init(top: 0, left: 15, bottom: 0, right: 0))
pinnedHeaderLabel.anchor(top: followersCountLabel.bottomAnchor, leading: self.safeAreaLayoutGuide.leadingAnchor, bottom: nil, trailing: nil, padding: .init(top: 25, left: 15, bottom: 0, right: 0))
pinnedViewAllLabel.anchor(top: nil, leading: nil, bottom: pinnedHeaderLabel.bottomAnchor, trailing: self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 15))
pinnedStackView.anchor(top: pinnedViewAllLabel.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing:self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 15, left: 15, bottom: 0, right: 15))
topRepoHeaderLabel.anchor(top: pinnedStackView.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing:nil, padding: .init(top: 15, left: 15, bottom: 0, right: 0))
topRepoViewAllLabel.anchor(top: topRepoHeaderLabel.topAnchor, leading: nil, bottom: nil, trailing:self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 15))
topRepoScroller.anchor(top: topRepoViewAllLabel.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing: self.safeAreaLayoutGuide.trailingAnchor, size: .init(width: 0, height: Constants.REPOSITORY_TILE_HEIGHT+(15+15)))//(15+15 is for top and bottom margins)
topRepoStackView.anchor(top: topRepoScroller.topAnchor, leading: topRepoScroller.leadingAnchor, bottom:topRepoScroller.bottomAnchor, trailing:topRepoScroller.trailingAnchor, padding: .init(top: 15, left: 15, bottom: 0, right: 15))
starredRepoHeaderLabel.anchor(top: topRepoScroller.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing:nil, padding: .init(top: 0, left: 15, bottom: 15, right: 0))
starredRepoViewAllLabel.anchor(top: starredRepoHeaderLabel.topAnchor, leading: nil, bottom: nil, trailing:self.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 15))
starredRepoScroller.anchor(top: starredRepoViewAllLabel.bottomAnchor, leading: scrollView.leadingAnchor, bottom: scrollView.bottomAnchor, trailing: self.safeAreaLayoutGuide.trailingAnchor)
starredRepoScroller.heightAnchor.constraint(equalTo: topRepoScroller.heightAnchor).isActive = true
starredRepoStackView.anchor(top: starredRepoScroller.topAnchor, leading: starredRepoScroller.leadingAnchor, bottom:starredRepoScroller.bottomAnchor, trailing:starredRepoScroller.trailingAnchor, padding: .init(top: 15, left: 15, bottom: 0, right: 15))
}
//MARK: UI Components
let scrollView: UIScrollView = {
var refreshControl = UIRefreshControl()
let scroller = UIScrollView(frame: .zero)
scroller.delaysContentTouches = false
scroller.refreshControl = refreshControl
return scroller
}()
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 35
imageView.clipsToBounds = true
imageView.image = UIImage(named: "profile_placeholder")
return imageView
}()
let nameLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.sizeToFit()
label.font = UIFont(name:Constants.FONT_BOLD, size: Constants.FONT_SIZE_HEADER)
return label
}()
let loginLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.sizeToFit()
label.font = UIFont(name:Constants.FONT_REGULAR, size: Constants.FONT_SIZE_REGULAR)
return label
}()
let emailLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont(name:Constants.FONT_SEMI_BOLD, size: Constants.FONT_SIZE_REGULAR)
return label
}()
let followersCountLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont(name:Constants.FONT_REGULAR, size: Constants.FONT_SIZE_REGULAR)
return label
}()
let followingCountLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont(name:Constants.FONT_REGULAR, size: Constants.FONT_SIZE_REGULAR)
return label
}()
let pinnedHeaderLabel: UILabel = {
let label = UILabel()
label.addCharactersSpacing(spacing: 1, text: "Pinned")
label.numberOfLines = 0
label.font = UIFont(name:Constants.FONT_BOLD, size: Constants.FONT_SIZE_HEADER_1)
return label
}()
let pinnedViewAllLabel: UIButton = {
let button = UIButton(type: .system)
button.underline(text: "View all")
button.setTitleColor(.black, for: .normal)
button.titleLabel?.font = UIFont(name:Constants.FONT_SEMI_BOLD, size: Constants.FONT_SIZE_HEADER_2)
return button
}()
let pinnedStackView: UIStackView = {
let stack = UIStackView()
stack.tag = Constants.PINNED_STACK_VIEW_TAG
stack.axis = .vertical
stack.distribution = .fillEqually
stack.spacing = 15
return stack
}()
let topRepoHeaderLabel: UILabel = {
let label = UILabel()
label.addCharactersSpacing(spacing: 1, text: "Top repositories")
label.numberOfLines = 0
label.font = UIFont(name:Constants.FONT_BOLD, size: Constants.FONT_SIZE_HEADER_1)
return label
}()
let topRepoViewAllLabel: UIButton = {
let button = UIButton(type: .system)
button.underline(text: "View all")
button.setTitleColor(.black, for: .normal)
button.titleLabel?.font = UIFont(name:Constants.FONT_SEMI_BOLD, size: Constants.FONT_SIZE_HEADER_2)
return button
}()
let topRepoScroller: UIScrollView = {
let scroller = UIScrollView(frame: .zero)
scroller.showsHorizontalScrollIndicator = false
scroller.delaysContentTouches = false
return scroller
}()
let topRepoStackView: UIStackView = {
let stack = UIStackView()
stack.axis = .horizontal
stack.distribution = .fillEqually
stack.spacing = 15
return stack
}()
let starredRepoHeaderLabel: UILabel = {
let label = UILabel()
label.addCharactersSpacing(spacing: 1, text: "Starred repositories")
label.numberOfLines = 0
label.font = UIFont(name:Constants.FONT_BOLD, size: Constants.FONT_SIZE_HEADER_1)
return label
}()
let starredRepoViewAllLabel: UIButton = {
let button = UIButton(type: .system)
button.underline(text: "View all")
button.setTitleColor(.black, for: .normal)
button.titleLabel?.font = UIFont(name:Constants.FONT_SEMI_BOLD, size: Constants.FONT_SIZE_HEADER_2)
return button
}()
let starredRepoScroller: UIScrollView = {
let scroller = UIScrollView(frame: .zero)
scroller.showsHorizontalScrollIndicator = false
scroller.delaysContentTouches = false
return scroller
}()
let starredRepoStackView: UIStackView = {
let stack = UIStackView()
stack.axis = .horizontal
stack.distribution = .fillEqually
stack.spacing = 15
return stack
}()
}
| true
|
19942dc3bb7318feb06fdd46c566fb384ad46fb1
|
Swift
|
Fredrikostlund/SprintWatch
|
/SprintWatch WatchKit Extension/LapController.swift
|
UTF-8
| 1,611
| 2.875
| 3
|
[] |
no_license
|
//
// SettingsController.swift
// SprintWatch WatchKit Extension
//
// Created by Martin Sjölund on 2018-10-11.
// Copyright © 2018 Fredrik Östlund. All rights reserved.
//
import WatchKit
import Foundation
class LapController: WKInterfaceController{
var lapCount = 0
var pickerItems: [WKPickerItem] = []
override func awake(withContext context: Any?) {
super.awake(withContext: context)
setPickerItems()
// Configure interface objects here.
}
//sets the items 1 to 10 to lap Picker
func setPickerItems(){
for i in 1...10{
let item = WKPickerItem()
item.title = String(i)
pickerItems.append(item)
}
lapPicker.setItems(pickerItems)
}
//Sends lap count to next view trough segue
override func contextForSegue(withIdentifier segueIdentifier: String) -> Any? {
if segueIdentifier == "lapId"{
return lapCount
}
return 0
}
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()
}
//Outlet to Picker where you can choose number of laps
@IBOutlet weak var lapPicker: WKInterfacePicker!
//Changes lapIndex to value shown on Picker
@IBAction func pickerChanged(_ value: Int){
lapCount = value+1
}
}
| true
|
1c4ac38f1c89a680d3313cee3272b2e6fc70d125
|
Swift
|
dougcpr/helloARWorld
|
/hello_AR_world/ViewController.swift
|
UTF-8
| 6,129
| 2.53125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// hello_AR_world
//
// Created by doug on 8/15/17.
// Copyright © 2017 doug. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
let vaseNode = SCNNode()
let cupNode = SCNNode()
let chairNode = SCNNode()
let lampNode = SCNNode()
var node = SCNNode()
override func viewDidLoad() {
super.viewDidLoad()
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinchRecognized(pinch:)))
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panRecognized(pan:)))
self.view.addGestureRecognizer(pinchGesture)
self.view.addGestureRecognizer(panGesture)
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
let vaseButton = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 50))
vaseButton.backgroundColor = UIColor(red: 0.1, green: 0.2, blue: 0.4, alpha: 0.8)
vaseButton.setTitle("Set Vase", for: .normal)
vaseButton.addTarget(self, action: #selector(setVaseNode), for: .touchUpInside)
let cupButton = UIButton(frame: CGRect(x: 50, y: 200, width: 100, height: 50))
cupButton.backgroundColor = UIColor(red: 0.1, green: 0.2, blue: 0.4, alpha: 0.8)
cupButton.setTitle("Set Cup", for: .normal)
cupButton.addTarget(self, action: #selector(setCupNode), for: .touchUpInside)
let chairButton = UIButton(frame: CGRect(x: 50, y: 300, width: 100, height: 50))
chairButton.backgroundColor = UIColor(red: 0.1, green: 0.2, blue: 0.4, alpha: 0.8)
chairButton.setTitle("Set Chair", for: .normal)
chairButton.addTarget(self, action: #selector(setChairNode), for: .touchUpInside)
let lampButton = UIButton(frame: CGRect(x: 50, y: 400, width: 100, height: 50))
lampButton.backgroundColor = UIColor(red: 0.1, green: 0.2, blue: 0.4, alpha: 0.8)
lampButton.setTitle("Set Lamp", for: .normal)
lampButton.addTarget(self, action: #selector(setLampNode), for: .touchUpInside)
self.view.addSubview(vaseButton)
self.view.addSubview(cupButton)
self.view.addSubview(chairButton)
self.view.addSubview(lampButton)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let standardConfiguration: ARWorldTrackingConfiguration = {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
return configuration
}()
// Run the view's session
sceneView.session.run(standardConfiguration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
@IBAction func handleTap(_ sender: UITapGestureRecognizer) {
/* Looking at the location where the user touched the screen */
let result = sceneView.hitTest(sender.location(in: sceneView), types: [ARHitTestResult.ResultType.featurePoint])
guard let hitResult = result.last else {return}
/* transforms the result into a matrix_float 4x4 so the SCN Node can read the data */
let hitTransform = hitResult.worldTransform
/* Print the coordinates captured */
print("x: ", hitTransform[3].x, "\ny: ", hitTransform[3].y, "\nz: ", hitTransform[3].z)
/* Look at Add Geometry Class in Controller Group */
switch node {
case vaseNode:
addObject(position: hitTransform, sceneView: sceneView, node: vaseNode, objectPath: "art.scnassets/vase/vase.scn")
case cupNode:
addObject(position: hitTransform, sceneView: sceneView, node: cupNode, objectPath: "art.scnassets/cup/cup.scn")
case chairNode:
addObject(position: hitTransform, sceneView: sceneView, node: chairNode, objectPath: "art.scnassets/chair/chair.scn")
case lampNode:
addObject(position: hitTransform, sceneView: sceneView, node: lampNode, objectPath: "art.scnassets/lamp/lamp.scn")
default:
print("No Node Found")
}
}
func addObject(position: matrix_float4x4, sceneView: ARSCNView, node: SCNNode, objectPath: String){
node.position = SCNVector3(position[3].x, position[3].y, position[3].z)
// Create a new scene
guard let virtualObjectScene = SCNScene(named: objectPath)
else {
print("Unable to Generate" + objectPath)
return
}
let wrapperNode = SCNNode()
for child in virtualObjectScene.rootNode.childNodes {
child.geometry?.firstMaterial?.lightingModel = .physicallyBased
wrapperNode.addChildNode(child)
}
node.addChildNode(wrapperNode)
sceneView.scene.rootNode.addChildNode(node)
}
@objc func pinchRecognized(pinch: UIPinchGestureRecognizer) {
node.runAction(SCNAction.scale(by: pinch.scale, duration: 0.1))
}
@objc func panRecognized(pan: UIPanGestureRecognizer) {
let xPan = pan.velocity(in: sceneView).x/10000
/*
y pan is a not tuned for user expereience
let yPan = pan.velocity(in: sceneView).y/10000
*/
node.runAction(SCNAction.rotateBy(x: 0, y: xPan, z: 0, duration: 0.1))
}
@objc func setVaseNode(sender: UIButton!) {
node = vaseNode
}
@objc func setCupNode(sender: UIButton!) {
node = cupNode
}
@objc func setChairNode(sender: UIButton!) {
node = chairNode
}
@objc func setLampNode(sender: UIButton!) {
node = lampNode
}
}
| true
|
14a63b6bbc65fab8fc924ab2b902946ee1e26690
|
Swift
|
Geckoyamori/MuscleRecommend-iOS
|
/MuscleRecommend/MuscleRecommend/Common/Date.swift
|
UTF-8
| 867
| 3.296875
| 3
|
[] |
no_license
|
//
// Date.swift
// MuscleRecommend
//
// Created by 多喜和弘 on 2021/08/15.
//
import Foundation
extension Date {
// UTCをJSTに変換
func toJapaneseDeviceDate() -> Date {
let calendar = Calendar(identifier: .gregorian)
let date = Date()
return calendar.date(byAdding: .hour, value: 9, to: date)!
}
// Date型(2021-05-08T21:27:06.640Z)をString型(2021/05/08)に変換
func toStringType(date: Date) -> String {
let dateFormatter = DateFormatter()
// timeZoneがJSTだと、型の変換で自動的に+-9時間されてしまうため、timeZoneをUTCに設定
dateFormatter.timeZone = TimeZone(identifier: "UTC")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy/MM/dd"
return dateFormatter.string(from: date)
}
}
| true
|
f4d212e32851f2c1a02fe49bd36aed8e12d50b9e
|
Swift
|
makinney/PublicArt
|
/PublicArt/Mapping/ArtUserLocation.swift
|
UTF-8
| 3,282
| 2.75
| 3
|
[] |
no_license
|
//
// ArtUserLocation.swift
// City Art San Francisco
//
// Created by Michael Kinney on 1/12/15.
// Copyright (c) 2015 mkinney. All rights reserved.
//
import Foundation
import MapKit
class ArtUserLocation: NSObject {
fileprivate var checkZoomRequired = true
fileprivate var mapView: MKMapView?
fileprivate var trackingUserLocation = false
var trackingCallback: ((_ trackingState: Bool) -> ())?
lazy var locationManager: CLLocationManager = {
var manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.distanceFilter = 1.0 // TODO: constant
return manager
}()
init(mapView: MKMapView) {
super.init()
locationManager.delegate = self
self.mapView = mapView
NotificationCenter.default.addObserver(self, selector: #selector(ArtUserLocation.didEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ArtUserLocation.willEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didEnterBackground() {
if trackingUserLocation {
locationManager.stopUpdatingLocation()
}
}
func willEnterForeground() {
if trackingUserLocation {
locationManager.startUpdatingLocation()
}
}
func toggleShowUserLocation() {
if !trackingUserLocation {
self.startUpdating()
} else {
self.stopUpdating()
}
if !havePermission() {
promptForPermissionPermitted()
return
}
}
func startUpdating() {
mapView?.showsUserLocation = true
trackingUserLocation = true
checkZoomRequired = true
locationManager.startUpdatingLocation()
tracking(trackingUserLocation)
}
func stopUpdating() {
mapView?.showsUserLocation = false;
trackingUserLocation = false
locationManager.stopUpdatingLocation()
tracking(trackingUserLocation)
}
func tracking(_ state: Bool){
trackingCallback?(state)
}
func havePermission() -> Bool {
var permission = false
let status = CLLocationManager.authorizationStatus()
if status == .authorizedAlways || status == .authorizedWhenInUse {
permission = true
}
return permission
}
func promptForPermissionPermitted() {
locationManager.requestWhenInUseAuthorization()
}
func zoomUser(_ coordinates: CLLocationCoordinate2D) {
mapView?.setCenter(coordinates, animated: true)
let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) // TODO:
let region = MKCoordinateRegion(center:coordinates, span:span)
mapView?.setRegion(region, animated: true)
}
}
extension ArtUserLocation: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let userLocation = mapView?.userLocation {
if userLocation.coordinate.latitude != 0.0 && userLocation.coordinate.longitude != 0.0 {
if checkZoomRequired { // && mapView?.userLocationVisible == false {
zoomUser(userLocation.coordinate)
checkZoomRequired = false // so map does not keep centering
}
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { // FIXME: how to use error?
stopUpdating()
}
}
| true
|
859872eb5cc2741e0f1788c42adb392ab9e2b579
|
Swift
|
jotuwisz/CumulusWeather
|
/Cumulus/View/Controller/PrivacyAndTermsVC.swift
|
UTF-8
| 7,151
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// PrivacyPolicyViewController.swift
// Cumulus
//
// Created by Joseph Szafarowicz on 7/12/18.
// Copyright © 2018 Joseph Szafarowicz. All rights reserved.
//
import UIKit
class PrivacyAndTermsViewController: UIViewController {
@IBOutlet weak var privacyPolicyView: UIView!
@IBOutlet weak var statement0TextView: UITextView!
@IBOutlet weak var statement1TextView: UITextView!
@IBOutlet weak var statement2TextView: UITextView!
@IBOutlet weak var statement3TextView: UITextView!
@IBOutlet weak var statement4TextView: UITextView!
@IBOutlet weak var statement5TextView: UITextView!
@IBOutlet weak var statementTitle0Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription0Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription0Height: NSLayoutConstraint!
@IBOutlet weak var statementTitle1Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription1Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription1Height: NSLayoutConstraint!
@IBOutlet weak var statementTitle2Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription2Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription2Height: NSLayoutConstraint!
@IBOutlet weak var statementTitle3Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription3Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription3Height: NSLayoutConstraint!
@IBOutlet weak var statementTitle4Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription4Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription4Height: NSLayoutConstraint!
@IBOutlet weak var statementTitle5Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription5Width: NSLayoutConstraint!
@IBOutlet weak var statementDescription5Height: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
self.navigationItem.title = "Privacy & Terms"
weatherLoaded = true
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
if screenWidth < 375 {
let widthSize: CGFloat = 310
statementTitle0Width.constant = widthSize
statementDescription0Width.constant = widthSize
statementTitle1Width.constant = widthSize
statementDescription1Width.constant = widthSize
statementTitle2Width.constant = widthSize
statementDescription2Width.constant = widthSize
statementTitle3Width.constant = widthSize
statementDescription3Width.constant = widthSize
statementTitle4Width.constant = widthSize
statementDescription4Width.constant = widthSize
statementTitle5Width.constant = widthSize
statementDescription5Width.constant = widthSize
}
self.statement0TextView.text = "Cumulus takes your privacy and personal data seriously. Cumulus will only retrieve the least information that is necessary. Individual users are never tracked and personal data is never given to third parties."
self.statement1TextView.text = "You may opt to grant Cumulus access to your location to receive localized weather forecasts. Cumulus does not require access to your location however some of its features do. For the most accurate weather forecasts location permission is recommended but is not required. You can enable location access by selecting to allow location access \"While Using the App\" or \"Always\". You can always change the location access on your devices' settings."
self.statement2TextView.text = "Cumulus does not collect or store any personally identifiable information. Cumulus may ask for permission to access your location but this can be changed at anytime under your devices' settings and is not required. When you allow location access to Cumulus, your location is used each time a request is made with the weather data server selected by you under Cumulus' data source settings to retrieve weather forecasts for your location. None of the information sent is personally identifiable or stored by any third party."
self.statement3TextView.text = "Some features of Cumulus are only accessible through a subscription basis and billed according to the subscription. You will be billed in advance on a recurring and periodic cycle. Billing cycles are set either on a monthly or yearly basis, depending upon the type of subscription plan you select when purchasing a subscription. \n\nYour subscription will be charged to your iTunes account at confirmation of purchase. Your subscription will automatically renew at the end of your subscription period unless canceled at least 24 hours prior to the end of the current period. Your account will be charged for renewal within 24 hours prior to the end of current period. \n\nYou can manage your subscription or turn off auto-renewal at any time from your iTunes account settings. Cancellation of the active subscription period is not allowed."
self.statement4TextView.text = "Cumulus does not use any third party services for analytics. However, it does utilize Apple's App Analytics platform to collect statistics on app crashes and usage. This information helps to diagnose and resolve any issues when encountered. This data is anonymous and cannot be used to personally identify users."
self.setLabels()
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ThemeTableViewController.doneBarButtonTapped))
setupBarButtonColor(button: doneBarButton)
self.navigationItem.rightBarButtonItem = doneBarButton
}
// Set the labels for all corresponding statements
func setLabels() {
let font = UIFont.systemFont(ofSize: 17)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: UIColor.label,
]
let attributedString = NSMutableAttributedString(string:"To report any issues, ask questions, give feedback, or request features, please feel free to reach out.", attributes: attributes)
let linkWasSet = attributedString.setAsLink(textToFind: "reach out", linkURL: "mailto:support@cumulusweatherapp.com")
if linkWasSet {
statement5TextView.attributedText = attributedString
statement5TextView.textAlignment = .center
}
}
@IBAction func doneBarButtonTapped(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
}
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(.link, value: linkURL, range: foundRange)
return true
}
return false
}
}
| true
|
bfc659720face094032f687d7cc31d06b3568649
|
Swift
|
acloserview/kdeconnect-ios
|
/KDE Connect/KDE Connect/Plugins and Plugin Views/Clipboard/Clipboard.swift
|
UTF-8
| 2,985
| 2.5625
| 3
|
[] |
no_license
|
//
// Clipboard.swift
// KDE Connect Test
//
// Created by Lucas Wang on 2021-09-05.
//
import UIKit
@objc class Clipboard : NSObject, Plugin {
@objc let controlDevice: Device
@objc init (controlDevice: Device) {
self.controlDevice = controlDevice
}
@objc func onDevicePackageReceived(np: NetworkPackage) -> Bool {
if (np._Type == PACKAGE_TYPE_CLIPBOARD || np._Type == PACKAGE_TYPE_CLIPBOARD_CONNECT) {
if (np.object(forKey: "content") != nil) {
if (np._Type == PACKAGE_TYPE_CLIPBOARD) {
UIPasteboard.general.string = np.object(forKey: "content") as? String
connectedDevicesViewModel.lastLocalClipboardUpdateTimestamp = Int(Date().millisecondsSince1970)
print("Local clipboard synced with remote packet, timestamp updated")
} else if (np._Type == PACKAGE_TYPE_CLIPBOARD_CONNECT) {
let packetTimeStamp: Int = np.integer(forKey: "timestamp")
if (packetTimeStamp == 0 || packetTimeStamp < connectedDevicesViewModel.lastLocalClipboardUpdateTimestamp) {
print("Invalid timestamp from \(PACKAGE_TYPE_CLIPBOARD_CONNECT), doing nothing")
return false;
} else {
UIPasteboard.general.string = np.object(forKey: "content") as? String
connectedDevicesViewModel.lastLocalClipboardUpdateTimestamp = Int(Date().millisecondsSince1970)
print("Local clipboard synced with remote packet, timestamp updated")
}
}
} else {
print("Received nil for the content of the remote device's \(String(describing: np._Type)), doing nothing")
}
return true
}
return false
}
@objc func connectClipboardContent() -> Void {
let clipboardConent: String? = UIPasteboard.general.string
if (clipboardConent != nil) {
let np: NetworkPackage = NetworkPackage(type: PACKAGE_TYPE_CLIPBOARD_CONNECT)
np.setObject(clipboardConent, forKey: "content")
np.setInteger(connectedDevicesViewModel.lastLocalClipboardUpdateTimestamp, forKey: "timestamp")
controlDevice.send(np, tag: Int(PACKAGE_TAG_CLIPBOARD))
} else {
print("Attempt to connect local clipboard content with remote device returned nil")
}
}
@objc func sendClipboardContentOut() -> Void {
let clipboardConent: String? = UIPasteboard.general.string
if (clipboardConent != nil) {
let np: NetworkPackage = NetworkPackage(type: PACKAGE_TYPE_CLIPBOARD)
np.setObject(clipboardConent, forKey: "content")
controlDevice.send(np, tag: Int(PACKAGE_TAG_CLIPBOARD))
} else {
print("Attempt to grab and update local clipboard content returned nil")
}
}
}
| true
|
98f6a7e295c69c02c594bc542043c9ca944d68a3
|
Swift
|
murraygoodwin/Beanio
|
/BeanioTests/JSONParserTests.swift
|
UTF-8
| 1,289
| 2.578125
| 3
|
[] |
no_license
|
//
// JSONParserTests.swift
// BeanioTests
//
// Created by Murray Goodwin on 03/02/2021.
//
import XCTest
@testable import Beanio
final class JSONParserTests: XCTestCase {
var sut: JSONParser!
override func setUpWithError() throws {
sut = JSONParser()
}
override func tearDownWithError() throws {
sut = nil
}
func testParseCoffeeShopJSONWithNormalResults() throws {
do {
let testJSON = try Data(contentsOf: Bundle.main.url(forResource: "sampleJSON", withExtension: "json")!)
XCTAssert(try sut.parseCoffeeShopJSON(testJSON).coffeeShops!.count == 30)
XCTAssertNil(try sut.parseCoffeeShopJSON(testJSON).warningText)
} catch {
XCTFail()
}
}
func testParseCoffeeShopJSONWithWarning() throws {
do {
let testJSON = try Data(contentsOf: Bundle.main.url(forResource: "sampleJSONwithWarningMessage", withExtension: "json")!)
XCTAssert(try sut.parseCoffeeShopJSON(testJSON).coffeeShops!.count == 0)
XCTAssertNotNil(try sut.parseCoffeeShopJSON(testJSON).warningText)
XCTAssert(try sut.parseCoffeeShopJSON(testJSON).warningText == "There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area.")
} catch {
XCTFail()
}
}
}
| true
|
edfc422aec24a8b697527469a2a0485c8337399d
|
Swift
|
lbildzinkas/HealthKitRND
|
/HealthKitRND/HealthKitManager.swift
|
UTF-8
| 6,307
| 2.546875
| 3
|
[] |
no_license
|
//
// HealthKitManager.swift
// HealthKitRND
//
// Created by Luiz Bildzinkas on 4/7/16.
// Copyright © 2016 Luiz Bildzinkas. All rights reserved.
//
import Foundation
import HealthKit
class HealthKitManager{
let healthKitStore:HKHealthStore = HKHealthStore()
func AutorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!){
let healthKitTypesToRead : Set<HKObjectType> = [
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType)!,
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.workoutType()
]
let healthKitTypesToWrite : Set<HKSampleType> = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKQuantityType.workoutType()]
if !HKHealthStore.isHealthDataAvailable()
{
let error = NSError(domain: "com.bildzinkas.HealthKitRND", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
if( completion != nil )
{
completion(success:false, error:error)
}
return;
}
// 4. Request HealthKit authorization
healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
if( completion != nil )
{
completion(success:success,error:error)
}
}
}
func GetProfileData() -> (age:Int?, biologicalSex: HKBiologicalSexObject?, bloodType: HKBloodTypeObject?){
var age: Int?
var biologicalSex: HKBiologicalSexObject?
var bloodType: HKBloodTypeObject?
do
{
let birthDay = try healthKitStore.dateOfBirth()
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let differenceComponents = calendar.components(.NSYearCalendarUnit, fromDate: birthDay, toDate: today, options:NSCalendarOptions(rawValue: 0))
age = differenceComponents.year
}
catch
{
print("Error obtaining birthday")
}
do{
biologicalSex = try healthKitStore.biologicalSex()
}
catch
{
print("Error obtaining biological sex")
}
do{
bloodType = try healthKitStore.bloodType()
}
catch
{
print("Error obtaining blood type")
}
return (age, biologicalSex, bloodType)
}
func readMostRecentSample(sampleType: HKSampleType, completion: ((HKSample!, NSError!) -> Void)!)
{
let past = NSDate.distantPast()
let now = NSDate()
let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate: now, options: .None)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let limit = 1
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) {(sampleQuery, results, error)-> Void in
if let queryError = error{
completion(nil, queryError)
return;
}
let mostRecentSample = results?.first as? HKQuantitySample
if completion != nil
{
completion(mostRecentSample, nil)
}
}
self.healthKitStore.executeQuery(sampleQuery)
}
func saveWeight(weight: Double, completion: ((Bool, NSError!) -> Void)!)
{
let now = NSDate()
let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
let quantity = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: weight)
let sample = HKQuantitySample.init(type: quantityType!, quantity: quantity, startDate: now, endDate: now)
healthKitStore.saveObject(sample){ (success, error) -> Void in
completion(success, error)
}
}
func saveHeight(height: Double, completion: ((Bool, NSError!) -> Void)!)
{
let now = NSDate()
let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
let quantity = HKQuantity(unit: HKUnit.meterUnit(), doubleValue: height)
let sample = HKQuantitySample(type: quantityType!, quantity: quantity, startDate: now, endDate: now)
healthKitStore.saveObject(sample){(success, error) -> Void in
completion(success, error)
}
}
}
extension HKBloodType: CustomStringConvertible{
public var description : String {
switch self {
// Use Internationalization, as appropriate.
case NotSet: return "Não definido"
case APositive: return "A+"
case ANegative: return "A-"
case BPositive: return "B+"
case BNegative: return "B-"
case ABPositive: return "AB+"
case ABNegative: return "AB-"
case OPositive: return "O+"
case ONegative: return "O-"
}
}
}
extension HKBiologicalSex: CustomStringConvertible{
public var description: String{
switch self{
case .Female: return "Feminino"
case .Male: return "Masculino"
case .NotSet: return "Não definido"
case .Other: return "Outro"
}
}
}
| true
|
2e274960e51cd829ff44650701b32936a508ce45
|
Swift
|
mohsinalimat/StorageKit
|
/Example/Source/SubExamples/API response/Services/HTTPClient.swift
|
UTF-8
| 672
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//
// HTTPClient.swift
// Example
//
// Created by Marco Santarossa on 16/07/2017.
// Copyright © 2017 MarcoSantaDev. All rights reserved.
//
import Foundation
final class HTTPClient {
private let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)
private var dataTask: URLSessionDataTask?
func get(at url: URL, completionHandler: @escaping (Data) -> Void) {
dataTask = session.dataTask(with: url) { (data, _, error) in
if let error = error {
print("Get error \(error)")
return
}
guard let data = data else { return }
completionHandler(data)
}
dataTask?.resume()
}
func cancel() {
dataTask?.cancel()
}
}
| true
|
4f701742c4b7c067fb67857ddd04cacf5177c767
|
Swift
|
nguyentruongky/knStore
|
/knStore/src/others/AnimateItemCollectionLayout.swift
|
UTF-8
| 1,757
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AnimateItemCollectionLayout.swift
// Ogenii
//
// Created by Ky Nguyen on 4/6/17.
// Copyright © 2017 Ogenii. All rights reserved.
//
import UIKit
class KNAnimateItemCollectionLayout : UICollectionViewFlowLayout {
enum KNAnimateItemType {
case zoom, move
}
var animationType = KNAnimateItemType.zoom
convenience init(animationType: KNAnimateItemType) {
self.init()
self.animationType = animationType
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var insertingIndexPaths = [IndexPath]()
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
super.prepare(forCollectionViewUpdates: updateItems)
insertingIndexPaths.removeAll()
for update in updateItems {
if let indexPath = update.indexPathAfterUpdate, update.updateAction == .insert {
insertingIndexPaths.append(indexPath)
}
}
}
override func finalizeCollectionViewUpdates() {
super.finalizeCollectionViewUpdates()
insertingIndexPaths.removeAll()
}
override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath)
attributes?.alpha = 0.0
attributes?.transform = animationType == .zoom ?
CGAffineTransform(scaleX: 0.1, y: 0.1) :
CGAffineTransform(translationX: 0, y: 500.0)
return attributes
}
}
| true
|
a59e289b5d9cbb7532ef10bc3e84388868d3c4af
|
Swift
|
kavon/NetNewsWire
|
/Multiplatform/Shared/Images/IconImageView.swift
|
UTF-8
| 1,787
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// IconImageView.swift
// NetNewsWire
//
// Created by Maurice Parker on 6/29/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import SwiftUI
struct IconImageView: View {
@Environment(\.colorScheme) var colorScheme
var iconImage: IconImage
var body: some View {
GeometryReader { proxy in
let newSize = newImageSize(viewSize: proxy.size)
let tooShort = newSize.height < proxy.size.height
let indistinguishable = colorScheme == .dark ? iconImage.isDark : iconImage.isBright
let showBackground = (tooShort && !iconImage.isSymbol) || indistinguishable
Group {
Image(rsImage: iconImage.image)
.resizable()
.scaledToFit()
.frame(width: newSize.width, height: newSize.height, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
}
.frame(width: proxy.size.width, height: proxy.size.height, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
.background(showBackground ? AppAssets.iconBackgroundColor : nil)
.cornerRadius(4)
}
}
func newImageSize(viewSize: CGSize) -> CGSize {
let imageSize = iconImage.image.size
let newSize: CGSize
if imageSize.height == imageSize.width {
if imageSize.height >= viewSize.height {
newSize = CGSize(width: viewSize.width, height: viewSize.height)
} else {
newSize = CGSize(width: imageSize.width, height: imageSize.height)
}
} else if imageSize.height > imageSize.width {
let factor = viewSize.height / imageSize.height
let width = imageSize.width * factor
newSize = CGSize(width: width, height: viewSize.height)
} else {
let factor = viewSize.width / imageSize.width
let height = imageSize.height * factor
newSize = CGSize(width: viewSize.width, height: height)
}
return newSize
}
}
| true
|
5c8080fe98563149feb14ec80f8864bb532f99b4
|
Swift
|
robertpankrath/Snake3D
|
/Snake/Point.swift
|
UTF-8
| 743
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
// Created by Robert Pankrath on 11.03.16.
// Copyright © 2016 Robert Pankrath. All rights reserved.
import Foundation
enum PointError: ErrorType {
case DimensionMissmatch
}
public func == (lhs: Point, rhs: Point) -> Bool {
return lhs.indizes == rhs.indizes
}
public func + (lhs: Point, rhs: Point) throws -> Point {
guard lhs.indizes.count == rhs.indizes.count else { throw PointError.DimensionMissmatch }
return Point(indizes: lhs.indizes.enumerate().map { $0.element + rhs.indizes[$0.index] })
}
public struct Point {
public let indizes: [Int]
public init(indizes: [Int]) {
self.indizes = indizes
}
public init(indizes: Int...) {
self.indizes = indizes
}
}
extension Point: Equatable {}
| true
|
0b4980b661674d5ea56c4bd127a17cee23beb97d
|
Swift
|
lukejones1/MarvelApp
|
/MarvelFeed/Character Feature/Character.swift
|
UTF-8
| 175
| 2.640625
| 3
|
[] |
no_license
|
import Foundation
public struct Character: Equatable {
public var id: Int
public var name: String
public var description: String?
public var imageURL: URL?
}
| true
|
ce4d53cdb7ae0e3adcc3a3243bc2807eedd8c9d5
|
Swift
|
eonist/Element
|
/src/Element/ui/window/view/PopupView.swift
|
UTF-8
| 2,167
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
import Cocoa
@testable import Utils
/**
* NOTE: the difference between local and global monitors is that local takes care of events that happen inside an app window, and the global handle events that also is detected outside an app window.
* TODO: add support for NSNotification: windowDidResignKey -> close the popup window when this event happens
*/
class PopupView:WindowView{
var leftMouseDownEventListener:Any?
override func resolveSkin() {
//Swift.print("PopupView.resolveSkin")
StyleManager.addStyle("Window#special{fill:green;}")
super.resolveSkin()
if(leftMouseDownEventListener == nil) {leftMouseDownEventListener = NSEvent.addLocalMonitorForEvents(matching:[.leftMouseDragged], handler:self.onMouseDown ) }//we add a global mouse move event listener
else {fatalError("This shouldn't be possible, if it throws this error then you need to remove he eventListener before you add it")}
}
func onMouseDown(event:NSEvent) -> NSEvent? {
//Swift.print("PopupView.onMouseDown()")
//Swift.print("self.localPos: " + "\(self.localPos())")
if(!CGRect(CGPoint(),frame.size).contains(self.localPos())){/*click outside window, but must hit another app window*/
super.onEvent(Event(Event.update,self))/*notifies the initiator of the PopupWin that it will close*/
if(leftMouseDownEventListener != nil){
NSEvent.removeMonitor(leftMouseDownEventListener!)
leftMouseDownEventListener = nil
}
//TODO: Set the event to it self again here
self.window!.close()
}
return event
}
}
/*
Implement this if you want the popupwin to be closed if the app looses focus:
- (void)setupWindowForEvents{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:) name:NSWindowDidResignMainNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:) name:NSWindowDidResignKeyNotification object:self];
}
-(void)windowDidResignKey:(NSNotification *)note {
NSLog(@"notification");
[self close];
}
*/
| true
|
61ca19ed2b11dc1a6f727061f790da85ef187619
|
Swift
|
boardguy1024/ReactiveSwiftPrimitivesSample
|
/ReactiveSwift_Sample/ViewController.swift
|
UTF-8
| 7,933
| 3.28125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ReactiveSwift_Sample
//
// Created by park kyung suk on 2019/04/11.
// Copyright © 2019 park kyung suk. All rights reserved.
//
import UIKit
import ReactiveSwift
import Result
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Propertyを定義
let title = "ReactiveSwift"
let titleSignal = textSignalGenerator(text: title)
let titleProperty = Property(initial: "", then: titleSignal)
// Action を定義
let titleLengthChecker = Action<Int, Bool, NoError>(
state: titleProperty,
execute: lengthCheckerSignalProducer
)
// Observer 정의
titleLengthChecker.values.observeValues { isValid in
print("is title valid: \(isValid)")
}
// 이것은 textField 에 문자를 하나씩 입력되는 것을 표현함
// Action에 apply
for i in 0..<title.count {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(i)) {
// 10은 최소문자열
titleLengthChecker.apply(10).start()
}
}
}
private func lengthCheckerSignalProducer(text: String, minimumLength: Int) -> SignalProducer<Bool, NoError> {
return SignalProducer<Bool, NoError> { (observer, _) in
observer.send(value: text.count > minimumLength)
observer.sendCompleted()
}
}
// 이것을 호출하면 singalGenegator 가 생성되고 (그 때부터 살아있다)
// 클로저 안에서 n초마다 observer.send 로 값을 방출한다.
private func textSignalGenerator(text: String) -> Signal<String, NoError> {
return Signal<String, NoError> { (observer, _) in
let now = DispatchTime.now()
// text : ReactiveSwift
for index in 0..<text.count {
// 현재의 시점에서 * index 초마다 아래를 실행
DispatchQueue.main.asyncAfter(deadline: now + 1.0 * Double(index)) {
// 이건 now + index 마다
// R
// Re
// Rea
// Reac
// React
// ........ 이렇게 oserver.send( ) 로 값을 송출한다.
let indexStartOfText = text.startIndex
let indexEndOfText = text.index(text.startIndex, offsetBy: index)
let subString = text[indexStartOfText...indexEndOfText]
let value = String(subString)
observer.send(value: value)
}
}
}
}
private func doPropertySample() {
let signalProducer: SignalProducer<Int, NoError> = SignalProducer { (observer, lifetime) in
let now = DispatchTime.now()
for index in 0..<10 {
let timeElapsed = index * 5
DispatchQueue.main.asyncAfter(deadline: now + Double(timeElapsed)) {
guard !lifetime.hasEnded else {
observer.sendInterrupted()
return
}
observer.send(value: timeElapsed)
if index == 9 {
observer.sendCompleted()
}
}
}
}
let property = Property(initial: 0, then: signalProducer)
property.signal.observeValues { value in
print("[Observing Signal] Time elapsed = \(value)]")
}
}
private func doSinglaProducerSample() {
//Observer를 생성
let signalObserver = Signal<Int, NoError>.Observer(
value: { value in
print("Time elapsed: \(value)")
}, completed: {
print("completed")
}, interrupted: {
print("interrupted")
})
let signalProducer: SignalProducer<Int, NoError> = SignalProducer { (observer, lifetime) in
for i in 0..<10 {
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0 * Double(i)) {
guard !lifetime.hasEnded else {
observer.sendInterrupted()
return
}
observer.send(value: i)
if i == 9 { observer.sendCompleted() }
}
}
}
// signalProducer를 start 한다.
let disposable = signalProducer.start(signalObserver)
// 10초후에 dispose한다.
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
disposable.dispose()
}
}
private func doActionSample() {
// 이것은 SignalProducer<Int, NoError> 타입을 반환하는 클로저이다.
let signalProducerGenerator: (Int) -> SignalProducer<Int, NoError> = { timeInterval in
return SignalProducer<Int, NoError> { (observer, lifetime) in
let now = DispatchTime.now()
for index in 0..<10 {
let timeElapsed = index * timeInterval
DispatchQueue.main.asyncAfter(deadline: now + Double(timeElapsed)) {
guard !lifetime.hasEnded else {
observer.sendInterrupted()
return
}
observer.send(value: timeElapsed)
if index == 9 {
observer.sendCompleted()
}
}
}
}
}
let action = Action<Int, Int, NoError>(execute: signalProducerGenerator)
action.values.observeValues { value in
print("Teim elapsed = \(value)")
}
action.values.observeCompleted {
print("Action completed")
}
// 1. input을 apply 하고 start
action.apply(1).start()
// 2. Action 이 처리실행중이므로 무시된다.
action.apply(2).start()
DispatchQueue.main.asyncAfter(deadline: .now() + 12) {
// 3. action.apply(1) 이 완료한 후 이므로 실행된다.
action.apply(3).start()
}
}
private func doSignalSample() {
// Observer를 생성한다.
let signalObserver = Signal<Int, NoError>.Observer(value: { value in
print("Time elapsed: \(value)")
}, completed: {
print("completed")
}, interrupted: {
print("interrupted")
})
// Signal을 생성
let (output, input) = Signal<Int, NoError>.pipe()
for i in 0..<10 {
// 위의 Signal 의 input 에 값을 send로 Event배출한다.
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0 * Double(i)) {
input.send(value: i)
}
}
// output을 감시하는 시그널을 셋팅한다!
output.observe(signalObserver)
}
}
| true
|
7e5837eca3ce9b3f445730c2eb711e00c013b302
|
Swift
|
rapiddeveloper/CurrencyCalculator
|
/CowrywiseCC/Supporting Views/CurrencyTextField.swift
|
UTF-8
| 6,430
| 2.828125
| 3
|
[] |
no_license
|
//
// CurrencyTextfield.swift
// CowrywiseCC
//
// Created by Admin on 12/24/20.
// Copyright © 2020 rapid interactive. All rights reserved.
//
//
// PersonalTodoTextField.swift
// PersonalToDo
//
// Created by Admin on 11/2/20.
// Copyright © 2020 rapid interactive. All rights reserved.
/*
Abstract: A view that allows a user to input an amount of money
*/
import Foundation
import UIKit
import SwiftUI
class CustomTextField: UITextField {
let padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 80);
var width: CGFloat = 0
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
let rightBounds = CGRect(x: bounds.maxX - 72 , y: bounds.origin.y, width: bounds.width, height: bounds.height)
return rightBounds
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
}
/// A view that allows a user to input an amount of money
struct CurrencyTextField: UIViewRepresentable {
var textField = CustomTextField(frame: .zero)
@Binding var text: String
var currencyPlaceHolder: String
var isResultDisplayed: Bool
var onCommit: () -> () = {}
func makeUIView(context: Context) -> UITextField {
let label = UILabel(frame: .zero)
label.textColor = .systemGray3
label.font = UIFont.boldSystemFont(ofSize: 24)
label.text = currencyPlaceHolder
label.tag = 1
label.sizeToFit()
if let labelText = label.text {
let attributedString = NSMutableAttributedString(string: labelText)
attributedString.addAttribute(.kern, value: 2.0, range: NSRange(location: 0, length: attributedString.length))
label.attributedText = attributedString
}
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textField.keyboardType = .numberPad
textField.text = text
textField.clearButtonMode = .whileEditing
textField.returnKeyType = .done
textField.rightViewMode = .always
textField.rightView = label
textField.textColor = .gray
textField.font = UIFont.systemFont(ofSize: 24, weight: .bold)
textField.backgroundColor = UIColor(named: "textfield")
textField.delegate = context.coordinator
textField.adjustsFontSizeToFitWidth = true
return textField
}
func updateUIView(_ textView: UITextField, context: Context) {
for subview in textView.subviews {
if subview.tag == 1 {
if let label = subview as? UILabel {
label.text = currencyPlaceHolder
}
}
}
if !isResultDisplayed {
textView.text = text
} else {
textView.text = text
let result = text.split(separator: ".")
let fractionalPart = result.count == 2 ? String(result[1]) : ""
if fractionalPart.count > 3 {
let thirdCharFromEndIdx = 3
let attributedString = NSMutableAttributedString(string: fractionalPart)
attributedString.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.systemGray4],
range: NSRange(location: thirdCharFromEndIdx,
length: fractionalPart.count - thirdCharFromEndIdx))
let attributedString0 = NSMutableAttributedString(string: String(result[0])+".")
attributedString0.append(attributedString)
textView.attributedText = attributedString0
}
}
}
func makeCoordinator() -> CurrencyTextFieldCoordinator {
return CurrencyTextFieldCoordinator(representable: self)
}
}
class CurrencyTextFieldCoordinator: NSObject, UITextFieldDelegate {
var representable: CurrencyTextField
init(representable: CurrencyTextField) {
self.representable = representable
}
func textFieldDidChangeSelection(_ textField: UITextField) {
if let userText = textField.text {
representable.text = userText
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else { return }
if representable.isResultDisplayed {
textField.textColor = .systemGray
textField.text = ""
let result = text.split(separator: ".")
let fractionalPart = result.count == 2 ? String(result[1]) : ""
if fractionalPart.count > 3 {
let thirdCharFromEndIdx = 3
let attributedString = NSMutableAttributedString(string: fractionalPart)
attributedString.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.systemGray4],
range: NSRange(location: thirdCharFromEndIdx,
length: fractionalPart.count - thirdCharFromEndIdx))
let wholePartWithPoint = String(result[0]) + "."
textField.text = ""
textField.attributedText = nil
let attributedString0 = NSMutableAttributedString(string: wholePartWithPoint)
attributedString0.append(attributedString)
textField.attributedText = attributedString0
}
}
}
}
struct CurrencyTextField_Previews: PreviewProvider {
static var previews: some View {
VStack {
CurrencyTextField(text: .constant("500888"), currencyPlaceHolder: "NGN", isResultDisplayed: false, onCommit: {})
.cornerRadius(5)
.frame(width: 350, height: 56)
}
.previewDevice("iPhone8")
}
}
| true
|
c494bd1b817f4cd4f8ea27e190ca797b8e9fbc37
|
Swift
|
Sou1reaver/DistilleryTestApp
|
/DistilleryTestApp/PresentationLayer/Common/View/BaseViewController/BaseViewController.swift
|
UTF-8
| 1,632
| 2.9375
| 3
|
[] |
no_license
|
//
// BaseViewController.swift
// DistilleryTestApp
//
// Created by Vladimir Gordienko on 22.01.18.
// Copyright © 2018 Vladimir Gordienko. All rights reserved.
//
import UIKit
protocol ActivityIndicatorViewProtocol: class {
func showActivityIndicator()
func removeActivityIndicator()
}
class BaseViewController: UIViewController {
private lazy var activityIndicatorView = createActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - private methods
private func createActivityIndicatorView() -> UIView {
let activityIndicatorView = UIView()
activityIndicatorView.frame = view.bounds
activityIndicatorView.backgroundColor = .black
activityIndicatorView.alpha = 0.3
let loadIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityIndicatorView.addSubview(loadIndicator)
loadIndicator.center = view.center
loadIndicator.startAnimating()
return activityIndicatorView
}
}
// MARK: - LoadingViewProtocol
extension BaseViewController: ActivityIndicatorViewProtocol {
func showActivityIndicator() {
DispatchQueue.main.async { [weak self] in
guard let `activityIndicatorView` = self?.activityIndicatorView else { return }
self?.view.addSubview(activityIndicatorView)
}
}
func removeActivityIndicator() {
DispatchQueue.main.async { [weak self] in
self?.activityIndicatorView.removeFromSuperview()
}
}
}
| true
|
a060690556bb2d76f14b6f88cf4190d08dc6f0d6
|
Swift
|
DavidMNewman/TravelingSalesmanGA
|
/Traveler/Tour.swift
|
UTF-8
| 4,028
| 3.0625
| 3
|
[] |
no_license
|
//
// Created by David Newman on 11/11/16.
// Copyright (c) 2016 orbbabluefletch. All rights reserved.
//
import Foundation
class Tour: CustomStringConvertible {
var startingCity: City
var cities = [City]()
var description: String {
var route = [startingCity]
route.append(contentsOf: cities)
route.append(startingCity)
return "Distance: \(self.distance)\n\(route)"
}
var fitness: Double {
return 1.0/self.distance
}
lazy var distance: Double = {
guard let nextCity = self.cities.first else {
return Double(NSIntegerMax)
}
var result = self.startingCity.distanceTo(city: nextCity)
for i in 0..<self.cities.count - 1 {
result+=self.cities[i].distanceTo(city:self.cities[i+1])
}
if let returnTrip = self.cities.last?.distanceTo(city: self.startingCity) {
result+=returnTrip
}
result*=98 // Rough average for converting coordinate points to kilometers
return Double(result)
}()
init(startingCity: City, cities: [City]) {
self.startingCity = startingCity
self.cities = cities
}
convenience init(mock: Bool=true) {
var cities = [City]()
cities.append(City(name:"Boston", latitude: 42, longitude: -71))
cities.append(City(name:"Buffalo", latitude: 42, longitude: -78))
cities.append(City(name:"Charlotte", latitude: 35, longitude: -80))
cities.append(City(name:"Cleveland", latitude: 41, longitude: -81))
cities.append(City(name:"Dallas", latitude: 32, longitude: -96))
cities.append(City(name:"Fargo", latitude: 46, longitude: -96))
cities.append(City(name:"Denver", latitude: 39, longitude: -105))
cities.append(City(name:"Fresno", latitude: 36, longitude: -119))
cities.append(City(name:"Jacksonville", latitude: 30, longitude: -81))
cities.append(City(name:"Las Vegas", latitude: 36, longitude: -115))
cities.append(City(name:"Los Angeles", latitude: 34, longitude: -118))
cities.append(City(name:"Minneapolis", latitude: 44, longitude: -93))
cities.append(City(name:"New York", latitude: 40, longitude: -73))
cities.append(City(name:"Quebec", latitude: 46, longitude: -71))
cities.append(City(name:"Salt Lake City", latitude: 40, longitude: -111))
cities.append(City(name:"San Francisco", latitude: 37, longitude: -122))
cities.append(City(name:"Toronto", latitude: 43, longitude: -40))
cities.append(City(name:"Vancouver", latitude: 49, longitude: -123))
cities.append(City(name:"Washington D.C.", latitude: 38, longitude: -77))
cities.append(City(name:"Wichita", latitude: 37, longitude: -97))
cities.append(City(name:"London", latitude: 51, longitude: 0))
cities.append(City(name:"Paris", latitude: 49, longitude: 2))
cities.append(City(name:"Berlin", latitude: 52, longitude: 13))
cities.append(City(name:"Moscow", latitude: 56, longitude: 38))
cities.append(City(name:"Rio", latitude: -23, longitude: -43))
cities.append(City(name:"Mexico City", latitude: -24, longitude: -103))
cities = cities.shuffle()
self.init(startingCity: City(name:"Atlanta", latitude: 33, longitude: -84), cities: cities)
}
}
extension Tour: Comparable {
public static func ==(lhs: Tour, rhs: Tour) -> Bool {
return lhs.description == rhs.description
}
public static func <(lhs: Tour, rhs: Tour) -> Bool {
return lhs.distance > rhs.distance
}
public static func <=(lhs: Tour, rhs: Tour) -> Bool {
return lhs.distance >= rhs.distance
}
public static func >=(lhs: Tour, rhs: Tour) -> Bool {
return lhs.distance <= rhs.distance
}
public static func >(lhs: Tour, rhs: Tour) -> Bool {
return lhs.distance < rhs.distance
}
}
| true
|
77da1bf0e65d4ed682997fae2f3f34b567314c51
|
Swift
|
davidvgalbraith/bananas
|
/social-events/social-events/EventCollectionViewController.swift
|
UTF-8
| 3,304
| 2.765625
| 3
|
[] |
no_license
|
//
// EventCollectionViewController.swift
// social-events
//
// Created by David Galbraith on 8/2/15.
// Copyright (c) 2015 David Galbraith. All rights reserved.
//
import UIKit
class EventCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
private let reuseIdentifier = "EventCell"
private let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)
private var events = [EventModel]()
private var selectedEvent:EventModel!
override func viewDidLoad() {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
let filePath = NSBundle.mainBundle().pathForResource("events",ofType:"json")
DataManager.getDataFromFileWithSuccess(filePath, success: { (data) -> Void in
let json = JSON(data: data)
if let events = json["events"].array {
self.events.removeAll(keepCapacity: false)
for event in events {
var e = EventModel(name: event["name"].string, event_description: event["event_description"].string);
self.events.append(e);
}
} else {
println("Event parsing failed")
println(json)
assert(false)
}
})
}
override func viewDidAppear(animated: Bool) {
self.collectionView!.reloadData()
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return events.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("EventCell", forIndexPath: indexPath) as! EventCell
let event = events[indexPath.item]
cell.eventNameLabel.text = event.name
cell.descriptionLabel.text = event.event_description
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var bounds = UIScreen.mainScreen().bounds
return CGSizeMake(bounds.width, 100)
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let event = events[indexPath.item]
] let vc = self.storyboard!.instantiateViewControllerWithIdentifier("EventDetailsViewController") as! EventDetailsViewController
vc.event_title_text = event.name
vc.event_description_text = event.event_description
self.navigationController!.pushViewController(vc, animated: true)
}
}
| true
|
e5e5a7672769fcc29a07984de0fe940a398e2f25
|
Swift
|
lluismoratoguardia/BemobileGNB
|
/BemobileGNB/BemobileGNB/Product Management/Product Selection/Scene/ProductSelectionInteractor.swift
|
UTF-8
| 1,428
| 2.625
| 3
|
[] |
no_license
|
//
// ProductSelectionInteractor.swift
// BemobileGNB
//
// Created by Admin on 09/01/2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol ProductSelectionBusinessLogic {
func getData()
func selectedProduct(_ productSKU: String)
}
protocol ProductSelectionDataStore {
var rates: [RateModel] { get set }
var transactions: [TransactionModel] { get set }
var selectedProductTransactions: [TransactionModel] { get set }
}
class ProductSelectionInteractor: ProductSelectionBusinessLogic, ProductSelectionDataStore {
var rates = [RateModel]()
var transactions = [TransactionModel]()
var selectedProductTransactions = [TransactionModel]()
var presenter: ProductSelectionPresentationLogic?
func getData() {
var products = [String]()
transactions.forEach { (transaction) in
if !products.contains(transaction.sku) {
products.append(transaction.sku)
}
}
presenter?.filteredProducts(products)
}
func selectedProduct(_ productSKU: String) {
selectedProductTransactions = transactions.filter({$0.sku == productSKU})
presenter?.productSelected()
}
}
| true
|
2517583499f806c13dfdc24654aed31d5ec3f78c
|
Swift
|
NikAshanin/Faces
|
/Faces/Capturing/CaptureSessionConfiguration.swift
|
UTF-8
| 631
| 2.5625
| 3
|
[] |
no_license
|
import AVFoundation
internal class CaptureSessionConfiguration {
internal let position: AVCaptureDevice.Position
internal let resolution: CMVideoDimensions
internal let frameRate: Double
internal let videoOrientation: AVCaptureVideoOrientation
internal init(position: AVCaptureDevice.Position,
resolution: CMVideoDimensions,
frameRate: Double,
videoOrientation: AVCaptureVideoOrientation) {
self.position = position
self.resolution = resolution
self.frameRate = frameRate
self.videoOrientation = videoOrientation
}
}
| true
|
08e844277d60ec8e3e87cb1ea19d3c311df0d309
|
Swift
|
CarterYang/Gentleman
|
/Gentleman/Navugation & Tabbar/NavVC.swift
|
UTF-8
| 701
| 2.625
| 3
|
[] |
no_license
|
import UIKit
class NavVC: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
//导航栏中title的颜色
self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
//导航栏中的按钮颜色
self.navigationBar.tintColor = UIColor.black
//导航栏的背景色
self.navigationBar.barTintColor = UIColor.white
//不允许透明
self.navigationBar.isTranslucent = false
//设置状态栏风格,lightContent与导航栏目前文字风格一致
var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
}
}
| true
|
8f57eae7ea3cddd17339c34fca0ba4057324a044
|
Swift
|
vptios/LightsOn
|
/LightsOn/ViewController.swift
|
UTF-8
| 3,358
| 2.5625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// LightsOn
//
// Created by Ameya Vichare on 03/06/17.
// Copyright © 2017 vit. All rights reserved.
//
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager : CBCentralManager?
var discoveredPeripheral : CBPeripheral?
var targetService: CBService?
var writableCharacteristic: CBCharacteristic?
var SERVICE_UUID = "FFF0"
var CHARACTERISTIC_UUID = "FFF3"
override func viewDidLoad() {
super.viewDidLoad()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
@IBAction func onButton(_ sender: UIButton) {
self.writeValue(value: 1)
}
@IBAction func offButton(_ sender: UIButton) {
self.writeValue(value: 0)
}
func writeValue(value: Int8) {
let data = Data.dataWithValue(value: value)
discoveredPeripheral?.writeValue(data, for: writableCharacteristic!, type: .withResponse)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
//3
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
//2
discoveredPeripheral = peripheral
discoveredPeripheral?.delegate = self
centralManager?.connect(discoveredPeripheral!, options: nil)
centralManager?.stopScan()
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
//1
if central.state == .poweredOn {
centralManager?.scanForPeripherals(withServices: [CBUUID(string: SERVICE_UUID)], options: nil)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
//4
targetService = peripheral.services?.first
peripheral.discoverCharacteristics(nil, for: targetService!)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
//5
for characteristic in service.characteristics! {
if characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) {
writableCharacteristic = characteristic
peripheral.setNotifyValue(true, for: characteristic)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
//6
if (characteristic.value?.int8Value())! > 0 {
view.backgroundColor = UIColor.yellow
}
else {
view.backgroundColor = UIColor.black
}
}
}
extension Data {
static func dataWithValue(value: Int8) -> Data {
var variableValue = value
return Data(buffer: UnsafeBufferPointer(start: &variableValue, count: 1))
}
func int8Value() -> Int8 {
return Int8(bitPattern: self[0])
}
}
| true
|
a29ad3313a0fc65a620ddaf414f751f8395c27b5
|
Swift
|
RocketChat/Rocket.Chat.iOS
|
/Rocket.Chat/Models/Base/BaseModel.swift
|
UTF-8
| 851
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// BaseModel.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/8/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
class BaseModel: Object {
@objc dynamic var identifier: String?
override static func primaryKey() -> String? {
return "identifier"
}
static func find(withIdentifier identifier: String) -> Self? {
return Realm.current?.objects(self).filter("identifier = '\(identifier)'").first
}
@discardableResult
static func delete(withIdentifier identifier: String) -> Bool {
guard
let realm = Realm.current,
let object = realm.objects(self).filter("identifier = '\(identifier)'").first
else {
return false
}
realm.delete(object)
return true
}
}
| true
|
dc2d79935768fefcf2f2806ac63d311086e18ee0
|
Swift
|
pbardea/KeepIt
|
/KeepIt/TodoMenuViewController.swift
|
UTF-8
| 1,602
| 2.796875
| 3
|
[] |
no_license
|
//
// TodoMenuViewController.swift
// KeepIt
//
// Created by Paul Bardea on 2016-02-19.
// Copyright © 2016 pbardea stdios. All rights reserved.
//
import Cocoa
class Todo {
var title: String
var completed = false
var dueDate: NSDate?
init(title: String) {
self.title = title
}
init(title: String, dueDate: NSDate) {
self.title = title
self.dueDate = dueDate
}
}
class TodoMenuViewController: NSViewController {
var todoList = [Todo(title: "Thing 1"), Todo(title: "Thing 2"), Todo(title: "Thing 2"), Todo(title: "Thing 2"), Todo(title: "Thing 2"), Todo(title: "Thing 2")]
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
// MARK: - NSTableViewDataSource
extension TodoMenuViewController: NSTableViewDataSource {
func numberOfRowsInTableView(aTableView: NSTableView) -> Int {
return self.todoList.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cellView: TodoListCellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! TodoListCellView
if tableColumn!.identifier == "todoListColumn" {
let todoItem = self.todoList[row]
cellView.backgroundStyle = NSBackgroundStyle.Light
cellView.checkBox.title = todoItem.title
return cellView
}
return cellView
}
}
// MARK: - NSTableViewDelegate
extension TodoMenuViewController: NSTableViewDelegate {
}
| true
|
202e28ef3fa64a08faaa12f290adc6b3d209188c
|
Swift
|
djbrooks111/swift-wisdom
|
/SwiftWisdom/Core/StandardLibrary/Numbers/Int+Extensions.swift
|
UTF-8
| 2,113
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
//
// Int+Extensions.swift
// SwiftWisdom
//
// Created by Logan Wright on 1/19/16.
// Copyright © 2016 Intrepid. All rights reserved.
//
import Foundation
extension IntegerType {
public var ip_isEven: Bool {
return (self % 2) == 0
}
public var ip_isOdd: Bool {
return !ip_isEven
}
}
extension IntegerType {
public func ip_times(@noescape closure: Block) {
precondition(self >= 0)
(0..<self).forEach { _ in closure() }
}
}
extension IntegerType {
public func ip_toMagnitudeString(decimalPlaces decimalPlaces: Int = 1) -> String {
guard self > 999 else { return "\(self)" }
let units = ["K", "M", "B", "T", "Q"]
let value = Double(self.toIntMax())
var magnitude: Int = Int(log10(value) / 3.0) // the order of magnitude of our value in thousands
// divide value by 1000^magnitude to get hundreds value, then round to desired decimal places
var roundedHundredsValue = (value / pow(1000.0, Double(magnitude))).ip_roundToDecimalPlaces(decimalPlaces)
// if rounding brings our display value over 1000, divide by 1000 and then bump the magnitude
if roundedHundredsValue >= 1000 {
roundedHundredsValue /= 1000.0
magnitude += 1
}
// if our number exceeds our current magnitude system return the scientific notation
let magnitudeSuffix = units[ip_safe: magnitude - 1] ?? "E\(magnitude * 3)"
let formatter = NSNumberFormatter.decimalFormatter
guard let valueFormatted = formatter.stringFromNumber(roundedHundredsValue) else {
return "\(roundedHundredsValue)\(magnitudeSuffix)"
}
return "\(valueFormatted)\(magnitudeSuffix)"
}
}
extension NSNumberFormatter {
private static var decimalFormatter: NSNumberFormatter {
let decimalFormatter = NSNumberFormatter()
decimalFormatter.numberStyle = .DecimalStyle
decimalFormatter.minimumFractionDigits = 0
return decimalFormatter
}
}
| true
|
965cc4cb44c440f9a61309a1d2218ab777f7c8c5
|
Swift
|
classpivot/Hercules
|
/Hercules/Services/CoreDataService.swift
|
UTF-8
| 14,342
| 2.53125
| 3
|
[] |
no_license
|
//
// TodayServices.swift
// Bloodhoof
//
// Created by Xiao Yan on 8/3/17.
// Copyright © 2017 Xiao Yan. All rights reserved.
//
import Foundation
import CoreData
import UIKit
typealias Result = ([NSManagedObject]) -> Void
class CoreDataService {
static let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Get latest workout plan
static func getTodayWorkoutData() -> Workout? {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Workout")
fetchRequest.predicate = NSPredicate(format: "(created_date >= %@) and (created_date < %@)", Date().startOfDay() as CVarArg, Date().endOfDay() as CVarArg)
do {
let workoutList = try managedContext.fetch(fetchRequest)
return workoutList.count > 0 ? (workoutList[0] as! Workout) : nil
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
return nil
}
//Get latest workout plan
static func getUnfinishedWorkoutData() -> Workout? {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Workout")
fetchRequest.predicate = NSPredicate(format: "done_flag = false")
do {
let workoutList = try managedContext.fetch(fetchRequest)
return workoutList.count > 0 ? (workoutList[0] as! Workout) : nil
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
return nil
}
//Get last 3 workout records based on body parts
static func getMyWorkoutPlan() -> [Workout] {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Workout")
let sortDescriptor = NSSortDescriptor(key: "created_date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// fetchRequest.predicate = NSPredicate(format: "body_parts CONTAINS ", Date().startOfDay() as CVarArg, Date().endOfDay() as CVarArg)
fetchRequest.predicate = NSPredicate(format: "(created_date >= %@) and (created_date < %@)", Date().startOfDay() as CVarArg, Date().endOfDay() as CVarArg)
do {
let workoutList = try managedContext.fetch(fetchRequest)
return workoutList as! [Workout]
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
return []
}
//get workout templates
static func getWorkoutTemplates() -> [Workout] {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Workout")
let sortDescriptor = NSSortDescriptor(key: "created_date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// fetchRequest.predicate = NSPredicate(format: "body_parts CONTAINS ", Date().startOfDay() as CVarArg, Date().endOfDay() as CVarArg)
fetchRequest.predicate = NSPredicate(format: "template_flag = true")
do {
let workoutList = try managedContext.fetch(fetchRequest)
return workoutList as! [Workout]
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
return []
}
//deep copy a workout
static func deepCopyWorkout(workout: Workout) -> Workout {
let workoutEntity = NSEntityDescription.entity(forEntityName: "Workout", in: managedContext)
let sectionEntity = NSEntityDescription.entity(forEntityName: "Section", in: managedContext)
let exerciseEntity = NSEntityDescription.entity(forEntityName: "Exercise", in: managedContext)
let newWorkout = Workout(entity: workoutEntity!, insertInto: managedContext)
newWorkout.name = workout.name
newWorkout.created_date = NSDate()
newWorkout.body_parts = workout.body_parts
newWorkout.done_flag = false
let newSectionList = newWorkout.mutableOrderedSetValue(forKey: "section")
if let sections = workout.section {
//hard copy all sections
for section in sections {
let newSection = Section(entity: sectionEntity!, insertInto: managedContext)
let newExerciseList = newSection.mutableOrderedSetValue(forKey: "exercise")
newSection.created_date = NSDate()
newSection.name = (section as! Section).name
newSection.index = (section as! Section).index
if let exercises = (section as! Section).exercise {
//hard copy all exercises in each section
for exercise in exercises {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.created_date = NSDate()
newExercise.name = (exercise as! Exercise).name
newExercise.weight = (exercise as! Exercise).weight
newExercise.reps = (exercise as! Exercise).reps
newExercise.done_flag = false
newExerciseList.add(newExercise)
}
}
newSectionList.add(newSection)
}
}
// do {
// try newWorkout.managedObjectContext?.save()
// } catch {
// let saveError = error as NSError
// print(saveError)
// }
return newWorkout
}
//add new workout into core data
static func addWorkout(workout: Workout) {
do {
try workout.managedObjectContext?.save()
} catch {
print(error)
}
}
//Internal use for creating workout template
static func createWorkoutTemplateChest() {
let workoutEntity = NSEntityDescription.entity(forEntityName: "Workout", in: managedContext)
let newWorkout = Workout(entity: workoutEntity!, insertInto: managedContext)
newWorkout.name = "Chest Template One"
newWorkout.created_date = NSDate()
newWorkout.template_flag = true
newWorkout.body_parts = [Body.chest.rawValue]
let sections = newWorkout.mutableOrderedSetValue(forKey: "section")
let sectionEntity = NSEntityDescription.entity(forEntityName: "Section", in: managedContext)
let exerciseEntity = NSEntityDescription.entity(forEntityName: "Exercise", in: managedContext)
//section 0
let newSection0 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection0.index = 0
newSection0.name = "Section 1"
let exercises0 = newSection0.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Barbell Incline Bench Press"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises0.add(newExercise)
}
sections.add(newSection0)
//section 1
let newSection1 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection1.index = 1
newSection1.name = "Section 2"
let exercises1 = newSection1.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Barbell Bench Press"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises1.add(newExercise)
}
sections.add(newSection1)
//section 2
let newSection2 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection2.index = 2
newSection2.name = "Section 3"
let exercises2 = newSection2.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Peck Dec Fly"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises2.add(newExercise)
}
sections.add(newSection2)
//section 3
let newSection3 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection3.index = 3
newSection3.name = "Section 4"
let exercises3 = newSection3.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Cable Triceps Extension"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises3.add(newExercise)
}
sections.add(newSection3)
do {
try newWorkout.managedObjectContext?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
static func createWorkoutTemplateBS() {
let workoutEntity = NSEntityDescription.entity(forEntityName: "Workout", in: managedContext)
let newWorkout = Workout(entity: workoutEntity!, insertInto: managedContext)
newWorkout.name = "Back&Shoulder Template One"
newWorkout.created_date = NSDate()
newWorkout.template_flag = true
newWorkout.body_parts = [Body.back.rawValue, Body.shoulder.rawValue]
let sections = newWorkout.mutableOrderedSetValue(forKey: "section")
let sectionEntity = NSEntityDescription.entity(forEntityName: "Section", in: managedContext)
let exerciseEntity = NSEntityDescription.entity(forEntityName: "Exercise", in: managedContext)
//section 0
let newSection0 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection0.index = 0
newSection0.name = "Section 1"
let exercises0 = newSection0.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Lat Pull"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises0.add(newExercise)
let newExercise2 = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise2.name = "Shoulder Press"
newExercise2.weight = 0
newExercise2.reps = 0
newExercise2.created_date = NSDate()
exercises0.add(newExercise2)
}
sections.add(newSection0)
//section 1
let newSection1 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection1.index = 1
newSection1.name = "Section 2"
let exercises1 = newSection1.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "MTS High Row"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises1.add(newExercise)
let newExercise2 = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise2.name = "Right Up Row"
newExercise2.weight = 0
newExercise2.reps = 0
newExercise2.created_date = NSDate()
exercises1.add(newExercise2)
}
sections.add(newSection1)
//section 2
let newSection2 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection2.index = 2
newSection2.name = "Section 3"
let exercises2 = newSection2.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Row"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises2.add(newExercise)
let newExercise2 = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise2.name = "Bicep Curl"
newExercise2.weight = 0
newExercise2.reps = 0
newExercise2.created_date = NSDate()
exercises2.add(newExercise2)
}
sections.add(newSection2)
//section 3
let newSection3 = Section(entity: sectionEntity!, insertInto: managedContext)
newSection3.index = 3
newSection3.name = "Section 4"
let exercises3 = newSection3.mutableOrderedSetValue(forKey: "exercise")
for _ in 0..<3 {
let newExercise = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise.name = "Face Pull"
newExercise.weight = 0
newExercise.reps = 0
newExercise.created_date = NSDate()
exercises3.add(newExercise)
let newExercise2 = Exercise(entity: exerciseEntity!, insertInto: managedContext)
newExercise2.name = "Bent Over Fly"
newExercise2.weight = 0
newExercise2.reps = 0
newExercise2.created_date = NSDate()
exercises3.add(newExercise2)
}
sections.add(newSection3)
do {
try newWorkout.managedObjectContext?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
static func updateWorkout(workout: Workout) {
do {
try workout.managedObjectContext?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
static func deleteWorkout(workout: Workout) {
}
static func deleteExercise(exercise: Exercise) {
self.managedContext.delete(exercise)
do {
try self.managedContext.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
}
| true
|
d83a0fd4f7a0ff0c67d60e52958e717bb59a0135
|
Swift
|
nntakuya/teaApp
|
/sampleTableView/DetailViewController.swift
|
UTF-8
| 6,577
| 3
| 3
|
[] |
no_license
|
//
// DetailViewController.swift
// sampleTableView
//
// Created by 仲松拓哉 on 19/01/2018.
// Copyright © 2018 仲松拓哉. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
//選択された行番号が受け渡されるプロパティ
var passedIndex = -1 //渡されないことを判別するために-1を代入
//初期化
@IBOutlet weak var teaName: UILabel!
@IBOutlet weak var explanation: UITextView!
@IBOutlet weak var teaImg: UIImageView!
var teaInfo = [
[
"name":"darjeeling",
"image":"sample.jpg",
"explain":"い香りを持つのは、寒暖の差の激しい標高の高い山地で生産されているためである。セカンドフラッシュではマスカテルフレーバー(マスカットフレーバー)と呼ばれる特徴的な香りの顕著なものが上質とされる。マスカテルフレーバーの香気成分の生成には茶葉に対するウンカの吸汁が関与するとされる。ウンカはセカンドフラッシュが摘まれる時期にもっとも多く発生する。紅茶は一般に茶葉を完全に酸化発酵させたものであるが、ダージリン地方の春摘み茶(ファーストフラッシュ)には軽発酵で、緑茶に近いものも少なくない。 現在市場に「ダージリン」の名称で出回っている茶葉は実際の生産量(全紅茶の2%程度がダージリンと言われている)よりかなり多く、ダージリンの名前を騙った偽物やほんの少量しかダージリン紅茶が含まれていない劣悪品の類が出回っていると思われる。"
],
[
"name":"earlgrey",
"image":"sample.jpg",
"explain":"アールグレイは、ベルガモットの落ち着きある芳香が大きな特徴である。このベルガモットの香りは精油や香料で着香されることが多い。茶の香気成分は冷やすと控え目になるが、人工的に香りを付けた着香茶であるアールグレイはアイスでも香りが比較的分かりやすいため、アイスティーに用いられることも多い。一方でベルガモットの芳香は一般的に温度が高くなるほど引き立つので、アイスティーを念頭に強めの香りをつけたものなどをホットティーにすると、慣れていない人にとっては非常に飲みにくいものとなりやすい。この芳香がミルクと相性が良いため、ミルクティーとしても飲まれる。"
],
[
"name":"orangepekoe",
"image":"sample.jpg",
"explain":"オレンジ・ペコー(英語: Orange pekoe若しくはOrange pecco、[pɛk.oʊ]若しくは[piː.koʊ])は西洋の茶、特に紅茶の取引において使用される等級(オレンジ・ペコー等級)。中国語起源とする説もあるが、一般的にこの等級は、非中国語圏のスリランカやインドなど中国以外の産地の茶にも用いられる。この等級は、茶葉のサイズの大きさや形状に基づいている。茶産業では、オレンジ・ペコーの用語を特定の大きさの茶葉のうち、標準的な中等級の紅茶に用いているが、北アメリカなど、地域によってはノーブランドの紅茶の名称として使われている。但し、消費者向けには紅茶の一種として表現されることも多い。この等級において、高い等級を与えられる茶葉は、新芽から得られる。オレンジ・ペコーは少量の枝先の新芽とそのすぐ下の1枚目の若葉からなる。等級は8-30メッシュの網目の篩にかけたときの、葉の大きさによって決定される。それぞれの葉の形状の完全性、即ち欠け具合も等級に関わる。これらは葉の品質を定める要因には留まるわけではないが、葉の大きさや完全性は味、透明度、淹れ時間に影響を与える。"
],
[
"name":"assam",
"image":"sample.jpg",
"explain":"アッサム平原は世界有数の降水量を持ち、世界最大の紅茶産地である。アッサムの紅茶は水色が濃い茶褐色でこくが強いため、ミルクティーとして飲まれることが多い。チャイ用として細かく丸まったCTC製法(Crush Tear Curl--つぶして、ひきさいて、丸める)で製茶されたものが多く出回っている。4月から5月にファーストフラッシュが、6月から7月にセカンドフラッシュが摘まれ、11月までが生産時期である。インド国内で消費される量が多い。"
]
]
//準備すべきデータ
//1.写真
//2.teaの説明
//
override func viewDidLoad() {
super.viewDidLoad()
print("渡された行番号:\(passedIndex)")
print(teaInfo[passedIndex])
//指定のtea名を表示
teaName.text = teaInfo[passedIndex]["name"]!
//指定のteaの説明を表示
explanation.text = teaInfo[passedIndex]["explain"]
//指定の画像を選択
imgSelect(teaName: teaInfo[passedIndex]["name"]!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imgSelect(teaName:String) {
switch teaName {
case "darjeeling" :
teaImg.image = UIImage(named:"Darjeeling.jpeg")
case "earlgrey" :
teaImg.image = UIImage(named:"EarlGrey.jpeg")
case "orangepekoe" :
teaImg.image = #imageLiteral(resourceName: "OrangePekoe .jpeg")
case "assam" :
teaImg.image = UIImage(named:"Assam.jpeg")
default:
teaImg.image = UIImage(named:"Darjeeling.jpeg")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
32d13a56ad8e2c0311be753ee2fabd4448ffc912
|
Swift
|
benkoppe/FencingPools
|
/Fencing/Extensions/GridInfo.swift
|
UTF-8
| 2,971
| 3
| 3
|
[] |
no_license
|
//
// GridInfo.swift
// Fencing
//
// Created by Ben K on 7/4/21.
//
import Foundation
import SwiftUI
struct GridInfoPreference {
let id: Int
let bounds: Anchor<CGRect>
}
struct GridPreferenceKey: PreferenceKey {
static var defaultValue: [GridInfoPreference] = []
static func reduce(value: inout [GridInfoPreference], nextValue: () -> [GridInfoPreference]) {
return value.append(contentsOf: nextValue())
}
}
extension View {
func gridInfoId(_ id: Int) -> some View {
self.anchorPreference(key: GridPreferenceKey.self, value: .bounds) {
[GridInfoPreference(id: id, bounds: $0)]
}
}
func gridInfo(_ info: Binding<GridInfo>) -> some View {
self.backgroundPreferenceValue(GridPreferenceKey.self) { prefs in
GeometryReader { proxy -> Color in
DispatchQueue.main.async {
info.wrappedValue.cells = prefs.compactMap {
GridInfo.Item(id: $0.id, bounds: proxy[$0.bounds])
}
}
return Color.clear
}
}
}
}
struct GridInfo: Equatable {
// A array of all rendered cells's bounds
var cells: [Item] = []
// a computed property that returns the number of columns
var columnCount: Int {
guard cells.count > 1 else { return cells.count }
var k = 1
for i in 1..<cells.count {
if cells[i].bounds.origin.x > cells[i-1].bounds.origin.x {
k += 1
} else {
break
}
}
return k
}
// a computed property that returns the range of cells being rendered
var cellRange: ClosedRange<Int>? {
guard let lower = cells.first?.id, let upper = cells.last?.id else { return nil }
return lower...upper
}
// returns the width of a rendered cell
func cellWidth(_ id: Int) -> CGFloat {
columnCount > 0 ? columnWidth(id % columnCount) : 0
}
// returns the width of a column
func columnWidth(_ col: Int) -> CGFloat {
columnCount > 0 && col < columnCount ? cells[col].bounds.width : 0
}
// returns the spacing between columns col and col+1
func spacing(_ col: Int) -> CGFloat {
guard columnCount > 0 else { return 0 }
let left = col < columnCount ? cells[col].bounds.maxX : 0
let right = col+1 < columnCount ? cells[col+1].bounds.minX : left
return right - left
}
func cellHeight(_ id: Int) -> CGFloat {
columnCount > 0 ? columnHeight(id % columnCount) : 0
}
func columnHeight(_ col: Int) -> CGFloat {
columnCount > 0 && col < columnCount ? cells[col].bounds.height : 0
}
// Do not forget the "Equatable", as it prevent redrawing loops
struct Item: Equatable {
let id: Int
let bounds: CGRect
}
}
| true
|
5b3ce6208c029a050b5314871869d8804cbe619b
|
Swift
|
polytech-RE/KeyExtractor
|
/KeyExtractor/BusinessLogic/TechnicalClasses/SoftwareManager.swift
|
UTF-8
| 5,690
| 2.921875
| 3
|
[] |
no_license
|
//
// SoftwareManager.swift
// KeyExtractor
//
// Created by remy on 28/04/2015.
// Copyright (c) 2015 polytech-RE. All rights reserved.
//
import Foundation
class SoftwareManager {
// MARK: Attributes
///path to ways.txt (contain all the information about compatible software to search)
private let pathListFile: String
///list of pieces of software
private var softwareList: [Software]
// MARK: Initializers
init(){
self.pathListFile = NSBundle.mainBundle().bundlePath + "/ways.txt"
self.softwareList = [Software]()
}
// MARK: Functions
/**
This function allows to find the software present in the file txt
*/
func fileSeek()-> Software? {
let file: FileTXT?
file = FileTXT(path: pathListFile)
if ( file!.contentNotNil() ){
//split the file with the new line character
let separatedline = split(file!.content!, allowEmptySlices: false, isSeparator: {(c:Character)->Bool in return c=="\n"})
for line in separatedline {
//split the file with the character ;
// the file is formated as softwareName;licenceFile;infoFile
let separatedsemicolon = split(line, allowEmptySlices: false, isSeparator: {(c:Character)->Bool in return c==";"})
let fileInfo: File?
let fileLicence: File?
let softwareName: String
let softwareLicenceFilePath: String
let softwareLicenceFileFormat: String
let softwareLicenceKeyName: String
let softwareKey: String?
let softwareInfoFilePath: String
let softwareVersion: String?
let copyright: String?
//TODO try and cath pour lever l'erreur lorsque le fichier est mal rempli
softwareName = separatedsemicolon[0]
softwareLicenceFilePath = separatedsemicolon[1]
softwareLicenceFileFormat = separatedsemicolon[2]
softwareLicenceKeyName = separatedsemicolon[3]
softwareInfoFilePath = separatedsemicolon[4]
//get the software information
//if ( softwareInfoFilePath && softwareLicenceKeyName && softwareLicenceFileFormat && softwareLicenceFilePath ){
fileInfo = FilePlist(path: softwareInfoFilePath)
if ( fileInfo != nil){
softwareVersion = fileInfo?.findValue("CFBundleShortVersionString")
copyright = fileInfo?.findValue("NSHumanReadableCopyright")
if (softwareVersion != nil && copyright != nil){
//get the software information
fileLicence = FileFactory.createFile(softwareLicenceFilePath, format: softwareLicenceFileFormat)
if (fileLicence != nil){
softwareKey = fileLicence?.findValue(softwareLicenceKeyName)
if softwareKey != nil {
//create the software with the information
let software :Software
software = Software(name: softwareName, copyright: copyright!, version: softwareVersion!, key: softwareKey!)
softwareList.append(software)
}
else{
NSLog("clé non trouvée")
NSException(name: "missing key", reason: "key not found", userInfo: nil)
}
}
else{
NSLog("erreur ouverture")
NSException(name: "error opening", reason: "file licence open error", userInfo: nil)
}
}
else{
//version et copyright
}
}
else{
softwareVersion = nil
copyright = nil
NSLog("erreur ouverture")
NSException(name: "error opening", reason: "file information open error", userInfo: nil) }
}
}
NSException(name: "Nil File", reason: "The file isn't initialized (nil)", userInfo: nil)
return nil
}
/** This function allows to find all the software
with licence in the basic folder (maybe
/Library/Preferences) NOT WORKING YET
*/
func autoSeek()-> Software? {
var currentFile:FileXML
var currentPath:String
let fileManager: NSFileManager = NSFileManager()
if let files = fileManager.subpathsAtPath("/Library/Preferences/") as? [String]{
for file in files{
currentPath = "/Library/Preferences/\(file)"
if file.pathExtension == "plist" {
currentFile=FileXML(path: currentPath)
currentFile.startParsing()
}
}
}
return nil
}
/**
Getter for the list of software
:return: softwareList
*/
func getSoftwares() ->[Software] {
return self.softwareList
}
}
| true
|
9260a59e123c2505c2be16a885826cf6481ef638
|
Swift
|
MohankumarExcelli/ExcelliCodingTest
|
/ExcelliCodingTest/ExcelliExploreCardTableViewController.swift
|
UTF-8
| 1,424
| 2.703125
| 3
|
[] |
no_license
|
//
// ANFExploreCardTableViewController.swift
// ExcelliCodingTest
//
import UIKit
class ExcelliExploreCardTableViewController: UITableViewController {
private var exploreData: [[AnyHashable: Any]]? {
if let filePath = Bundle.main.path(forResource: "exploreData", ofType: "json"),
let fileContent = try? Data(contentsOf: URL(fileURLWithPath: filePath)),
let jsonDictionary = try? JSONSerialization.jsonObject(with: fileContent, options: .mutableContainers) as? [[AnyHashable: Any]] {
return jsonDictionary
}
return nil
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
exploreData?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "ExploreContentCell", for: indexPath)
if let titleLabel = cell.viewWithTag(1) as? UILabel,
let titleText = exploreData?[indexPath.row]["title"] as? String {
titleLabel.text = titleText
}
if let imageView = cell.viewWithTag(2) as? UIImageView,
let name = exploreData?[indexPath.row]["backgroundImage"] as? String,
let image = UIImage(named: name) {
imageView.image = image
}
return cell
}
}
| true
|
d37f1a5aab9f43cd37a3f1aef87dacfc396f86c2
|
Swift
|
hshelton/iosProjects
|
/Console/Console/ParentView.swift
|
UTF-8
| 5,309
| 2.78125
| 3
|
[] |
no_license
|
//
// ParentView.swift
// Console
//
// Created by u0658884 on 2/7/15.
// Copyright (c) 2015 u0658884. All rights reserved.
//
import UIKit
protocol ParentViewDelegate: class
{
func parentView(parentView: ParentView, redvalueselected redVal: CGFloat, greenvalueselected greenVal: CGFloat, bluevalueselected blueVal: CGFloat)
}
class ParentView: UIView, ColorKnobDelegate
{
private var _colorKnob: ColorKnob! = nil
private var _alpha: UIView! = nil
private var _saturation: UIView! = nil
private var _hue: UIView! = nil
private var _colorChosen: UIView! = nil
private var _previousColor: UIView! = nil
private var _brightness : UIView! = nil
var red :CGFloat = CGFloat(0.0)
var green: CGFloat = CGFloat(0.0)
var blue: CGFloat = CGFloat(0.0)
weak var delegate: ParentViewDelegate? = nil
override init(frame: CGRect)
{
super.init(frame: frame)
_colorKnob = ColorKnob(frame: frame) //window can't be null for this to work
addSubview(_colorKnob)
_alpha = UIView(frame: frame)
_alpha.backgroundColor = UIColor.blueColor()
addSubview(_alpha)
var alphaLabel: UILabel = UILabel(frame: CGRectMake(16.0, 16.0, _alpha.frame.width, 16.0)); alphaLabel.text = "Alpha"
_alpha.addSubview(alphaLabel)
_saturation = UIView(frame: frame)
_saturation.backgroundColor = UIColor.greenColor()
var satLabel: UILabel = UILabel(frame: CGRectMake(16.0, 0.0, _saturation.frame.width, 16.0)); satLabel.text = "Saturation"
_saturation.addSubview(satLabel)
addSubview(_saturation)
_hue = UIView(frame: frame)
_hue.backgroundColor = UIColor.yellowColor()
var hueLabel: UILabel = UILabel(frame: CGRectMake(16.0, 0.0, _hue.frame.width, 16.0)); hueLabel.text = "Hue"
_hue.addSubview(hueLabel)
addSubview(_hue)
_colorChosen = UIView(frame: frame)
_colorChosen.backgroundColor = UIColor.brownColor()
addSubview(_colorChosen)
var currentLabel: UILabel = UILabel(frame: CGRectMake(16.0, 0.0, _colorChosen.frame.width, 16.0)); currentLabel.text = "Current Color"
_colorChosen.addSubview(currentLabel)
_previousColor = UIView(frame: frame)
_previousColor.backgroundColor = UIColor.whiteColor()
var prevLabel: UILabel = UILabel(frame: CGRectMake(16.0, 0.0, _previousColor.frame.width, 16.0)); prevLabel.text = "Previous Color"
_previousColor.addSubview(prevLabel)
addSubview (_previousColor)
_brightness = UIView(frame: frame)
_brightness.backgroundColor = UIColor.purpleColor()
var brightLabel: UILabel = UILabel(frame: CGRectMake(16.0, 0.0, _brightness.frame.width, 16.0)); brightLabel.text = "Brightness"
_brightness.addSubview(brightLabel)
addSubview (_brightness)
_colorKnob.delegate = self
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
assert(false, "Unsupported")
}
var alphaView:UIView {return _alpha}
var saturationView:UIView {return _saturation}
var hueView:UIView {return _hue}
override func layoutSubviews()
{
var r :CGRect = bounds
var r2 :CGRect = bounds
//(_colorKnob.frame, r) = r.rectsByDividing(r.height * 0.6, fromEdge: CGRectEdge.MinYEdge)
// (_alpha.frame, r) = r.rectsByDividing(r.height * 0.333, fromEdge: CGRectEdge.MinYEdge)
//(_saturation.frame, _hue.frame) = r.rectsByDividing(r.height * 0.5, fromEdge: CGRectEdge.MinYEdge)
(_colorKnob.frame, _colorChosen.frame) = r.rectsByDividing(r.height * 0.7, fromEdge: CGRectEdge.MinYEdge)
(_previousColor.frame, _colorChosen.frame) = _colorChosen.frame.rectsByDividing(_colorChosen.frame.width * 0.5, fromEdge: CGRectEdge.MinXEdge)
(_colorKnob.frame, _alpha.frame) = _colorKnob.frame.rectsByDividing(_colorKnob.frame.width * 0.5, fromEdge: CGRectEdge.MinXEdge)
(_alpha.frame, _saturation.frame) = _alpha.frame.rectsByDividing(_alpha.frame.height * 0.25, fromEdge: CGRectEdge.MinYEdge)
(_saturation.frame, _hue.frame) = _saturation.frame.rectsByDividing(_saturation.frame.height * 0.333, fromEdge: CGRectEdge.MinYEdge)
(_hue.frame, _brightness.frame) = _hue.frame.rectsByDividing(_hue.frame.height * 0.5, fromEdge: CGRectEdge.MinYEdge)
//(_colorKnob.frame, _previousColor.frame) = _colorKnob.frame.rectsByDividing(_colorKnob.frame.height * 0.7, fromEdge: CGRectEdge.MinYEdge)
}
func colorKnob(colorKnob: ColorKnob, getRedValue value: CGFloat)
{
red = value
invokeSelf()
}
func colorKnob(colorKnob: ColorKnob, getGreenValue value: CGFloat)
{
green = value
invokeSelf()
}
func colorKnob(colorKnob: ColorKnob, getBlueValue value: CGFloat)
{
blue = value
invokeSelf()
}
func invokeSelf()
{
delegate?.parentView(self, redvalueselected: red, greenvalueselected:green, bluevalueselected:blue)
}
}
| true
|
5d19b61d0ef898d0fdd8f666cd37de2bf1b74f11
|
Swift
|
khsora34/historiasDelLaberinto
|
/HistoriasDelLaberinto/HistoriasDelLaberinto/features/initialScene/InitialSceneViewController.swift
|
UTF-8
| 1,443
| 2.625
| 3
|
[] |
no_license
|
import UIKit
protocol InitialSceneDisplayLogic: ViewControllerDisplay {
func setLoadButton(isHidden: Bool)
}
class InitialSceneViewController: BaseViewController {
private var presenter: InitialScenePresentationLogic? {
return _presenter as? InitialScenePresentationLogic
}
@IBOutlet weak var gameTitleLabel: UILabel!
@IBOutlet weak var newGameButton: UIButton!
@IBOutlet weak var loadGameButton: UIButton!
@IBOutlet weak var changeLanguageButton: UIButton!
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
gameTitleLabel.text = Localizer.localizedString(key: "gameTitle")
newGameButton.setTitle(Localizer.localizedString(key: "newGameButton"), for: .normal)
loadGameButton.setTitle(Localizer.localizedString(key: "loadGameButton"), for: .normal)
changeLanguageButton.setTitle(Localizer.localizedString(key: "changeLanguageButtonText"), for: .normal)
}
@IBAction func didTapNewGame(_ sender: Any) {
presenter?.startNewGame()
}
@IBAction func didTapLoadGame(_ sender: Any) {
presenter?.loadGame()
}
@IBAction func didTapLanguagesButton(_ sender: Any) {
presenter?.goToLanguagesSelection()
}
}
extension InitialSceneViewController: InitialSceneDisplayLogic {
func setLoadButton(isHidden: Bool) {
loadGameButton.isHidden = isHidden
}
}
| true
|
3b6e9098b5490a775bcfb7e51729905c95c8c5c1
|
Swift
|
santosh241/Windary
|
/Swift/LeetCode/LeetCodeTests/GenerateParenthesesTests.swift
|
UTF-8
| 1,403
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// GenerateParenthesesTests.swift
// LeetCodeTests
//
// Created by 黎赵太郎 on 04/12/2017.
// Copyright © 2017 lizhaotailang. All rights reserved.
//
// Test cases for [GenerateParentheses](./LeetCode/GenerateParentheses.swift).
//
import XCTest
@testable import LeetCode
class GenerateParenthesesTests: XCTestCase {
func testGenerateParenthesis() {
let gp = GenerateParentheses()
XCTAssertTrue(gp.generateParenthesis(0).isEmpty)
let array0 = gp.generateParenthesis(1)
XCTAssertTrue(array0.count == 1)
XCTAssertTrue(array0[0] == "()")
let array1 = gp.generateParenthesis(2)
XCTAssertTrue(array1.count == 2)
XCTAssertTrue(Set<String>.init(array1) == Set<String>.init(arrayLiteral: "()()", "(())"))
let array2 = gp.generateParenthesis(3)
XCTAssertTrue(array2.count == 5)
XCTAssertTrue(Set<String>.init(array2) == Set<String>.init(arrayLiteral: "()()()", "()(())", "(()())", "(())()", "((()))"))
let array3 = gp.generateParenthesis(4)
XCTAssertTrue(array3.count == 14)
XCTAssertTrue(Set<String>.init(array3) == Set<String>.init(arrayLiteral: "()((()))", "(())(())", "(((())))", "(())()()", "()()(())", "(()())()", "(()(()))", "()()()()", "()(())()", "()(()())", "(()()())", "((()()))", "((()))()", "((())())"))
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.