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
19e1a8cde43807fcb2731f0264300e12393688c9
Swift
rtabler/RyanTabler_MAD
/Projects/project 1 milestone 3/project 1/TTCCommon.swift
UTF-8
725
2.75
3
[]
no_license
// // TTCCommon.swift // project 1 // // Created by Ryan Tabler on 3/13/18. // Copyright © 2018 Ryan Tabler. All rights reserved. // import Foundation class TTCCommon { func translatorCodeToShortname(translator: String) -> String { if translator == "Mitchell" { return "Mitchell" } else if translator == "FengEnglish" { return "Feng/English" } else { return "" } } func translatorCodeToLongName(translator: String) -> String { if translator == "Mitchell" { return "Stephen Mitchell" } else if translator == "FengEnglish" { return "Gia-Fu Feng and Jane English" } else { return "" } } }
true
1fbce06f1234059da8d6eddae0e210818dc2eb98
Swift
Reybravin/CodeSamples
/coordinator/OnboardingCoordinator.swift
UTF-8
1,135
3
3
[]
no_license
// class OnboardingCoordinator: OnboardingViewControllerDelegate { weak var delegate: OnboardingCoordinatorDelegate? private let navigationController: UINavigationController private var nextPageIndex = 0 // MARK: - Initializer init(navigationController: UINavigationController) { self.navigationController = navigationController } // MARK: - API func activate() { goToNextPageOrFinish() } // MARK: - OnboardingViewControllerDelegate func onboardingViewControllerNextButtonTapped( _ viewController: OnboardingViewController) { goToNextPageOrFinish() } // MARK: - Private private func goToNextPageOrFinish() { // We use an enum to store all content for a given onboarding page guard let page = OnboardingPage(rawValue: nextPageIndex) else { delegate?.onboardingCoordinatorDidFinish(self) return } let nextVC = OnboardingViewController(page: page) nextVC.delegate = self navigationController.pushViewController(nextVC, animated: true) nextPageIndex += 1 } }
true
f89cfc86869f1782f77cc5dd7449f96426908c78
Swift
arunsirrpi/CABook
/CABook/CABook/InfoViewController.swift
UTF-8
769
2.578125
3
[]
no_license
// // InfoViewController.swift // CABook // // Created by Raheel Ahmad on 7/14/14. // Copyright (c) 2014 Sakun Labs. All rights reserved. // import UIKit class InfoViewController: UIViewController { var info: String? @IBOutlet var textView: UITextView convenience init(info: String) { self.init() self.info = info } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) textView.text = info } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension InfoViewController { @IBAction func done(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } }
true
ea6a30b2477ed026dd1ec0555cd13d127deb09e5
Swift
cnotethegr8/ios-utilities
/View/BorderView.swift
UTF-8
2,577
2.75
3
[]
no_license
// // BorderView.swift // cnotethegr8 // // Created by Corey Werner on 3/5/18. // Copyright © 2018 cnotethegr8. All rights reserved. // import UIKit class BorderView: UIView { let edge: UIRectEdge init(edge: UIRectEdge, height: CGFloat = .halfPoint) { self.edge = edge super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false backgroundColor = .border setContentHuggingPriority(UILayoutPriority.required, for: .vertical) setContentHuggingPriority(UILayoutPriority.required, for: .horizontal) setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical) setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal) switch edge { case .top, .bottom: heightAnchor.constraint(equalToConstant: height).isActive = true case .left, .right: widthAnchor.constraint(equalToConstant: height).isActive = true default: break } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { super.didMoveToSuperview() guard let superview = superview else { return } switch edge { case .top: topAnchor.constraint(equalTo: superview.topAnchor).isActive = true leadingAnchor.constraint(equalTo: superview.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: superview.trailingAnchor).isActive = true case .left: topAnchor.constraint(equalTo: superview.topAnchor).isActive = true leadingAnchor.constraint(equalTo: superview.leadingAnchor).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true case .bottom: leadingAnchor.constraint(equalTo: superview.leadingAnchor).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true trailingAnchor.constraint(equalTo: superview.trailingAnchor).isActive = true case .right: topAnchor.constraint(equalTo: superview.topAnchor).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true trailingAnchor.constraint(equalTo: superview.trailingAnchor).isActive = true default: break } } }
true
0433ea3883d559c87bc53fcd3034254e0fbe90c1
Swift
iosYang/SearchFlow
/SearchFlow/SearchFlow/RowView.swift
UTF-8
1,139
2.84375
3
[]
no_license
// // RowView.swift // SearchFlow // // Created by 杨旗 on 2020/10/13. // Copyright © 2020 杨旗. All rights reserved. // import SwiftUI struct RowView: View { var resultModel:SearchResultModel var body: some View { HStack{ VStack { Text("\(resultModel.title)") .font(.headline) Text("\(resultModel.describe)") .font(.subheadline) .fontWeight(.thin) }.frame(width: 200.0, height: 80.0, alignment: .leading) Text(" $\(resultModel.price) ").foregroundColor(Color.blue).fontWeight(.light).background(Color(red: 230.0/255.0, green: 230.0/255.0, blue: 230.0/255.0)).frame(width: 100.0, height: 30.0, alignment: .trailing).cornerRadius(20) }.frame(width: UIScreen.main.bounds.size.width, height: 80.0, alignment: .center) } } struct RowView_Previews: PreviewProvider { static var previews: some View { RowView(resultModel: SearchResultModel()).previewLayout(.fixed(width: UIScreen.main.bounds.size.width, height: 80.0)) } }
true
20e3bb01c74984b0941034693aef103bc62938c0
Swift
KrystYohoMan/Breweries
/Pivovary/Pivovary/Pivovary/General/Resources/Constants/Colors.swift
UTF-8
1,118
3.296875
3
[]
no_license
// // Colors.swift // Pivovary // // Created by Tadeusz Raszka on 29.06.18. // Copyright © 2018 Krystian Labaj. All rights reserved. // import UIKit import UIKit enum Color { case white case black case beerYellow case gray var color: UIColor { switch self { case .white: return UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1) case .black: return UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1) case .beerYellow: return UIColor(red: 242/255, green: 203/255, blue: 108/255, alpha: 1) case .gray: return UIColor(red: 76/255, green: 76/255, blue: 76/255, alpha: 1) } } } struct ColorStruct { public static func whiteWith(alpha: CGFloat) -> UIColor { return UIColor.white.withAlphaComponent(alpha) } public static func colorWith(color: UIColor, alpha: CGFloat) -> UIColor { return color.withAlphaComponent(alpha) } public static func blackWith(alpha: CGFloat) -> UIColor { return UIColor.black.withAlphaComponent(alpha) } }
true
34882ca44b090d9b540b38d806e6ad7f910e1bc4
Swift
zond-platform/ground-control-station-ios
/Zond/Views/MissionMenu/ParametersView.swift
UTF-8
2,072
2.625
3
[]
no_license
// // ParametersView.swift // Zond // // Created by Evgeny Agamirzov on 17.10.20. // Copyright © 2020 Evgeny Agamirzov. All rights reserved. // import UIKit class ParametersView : UIView { // Stored properties private var parameterEditViews: [ParameterEditView] = [] private let stackView = UIStackView() // Notifyer properties var parameterValuePressed: ((_ id: MissionParameterId) -> Void)? var parameterIncrementPressed: ((_ id: MissionParameterId) -> Void)? var parameterDecrementPressed: ((_ id: MissionParameterId) -> Void)? required init?(coder: NSCoder) { super.init(coder: coder) } init() { super.init(frame: CGRect()) stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .leading for parameterId in MissionParameterId.allCases { parameterEditViews.append(ParameterEditView(parameterId)) stackView.addArrangedSubview(parameterEditViews.last!) } stackView.translatesAutoresizingMaskIntoConstraints = false; addSubview(stackView) registerListeners() NSLayoutConstraint.activate([ stackView.widthAnchor.constraint(equalTo: widthAnchor) ]) } } // Public methods extension ParametersView { func registerListeners() { for i in 0..<parameterEditViews.count { parameterEditViews[i].parameterDecrementPressed = { self.parameterDecrementPressed?(self.parameterEditViews[i].id) } parameterEditViews[i].parameterIncrementPressed = { self.parameterIncrementPressed?(self.parameterEditViews[i].id) } parameterEditViews[i].parameterValuePressed = { self.parameterValuePressed?(self.parameterEditViews[i].id) } } } func updateValueLabel(for id: MissionParameterId, with value: Float) { let index = parameterEditViews.firstIndex(where: { $0.id == id })! parameterEditViews[index].updateValueLabel(id, value) } }
true
818ccc2d5ff38931de10d5021d294e07d9bdaa3c
Swift
m-rwash/PracticingCoreData
/TopAnime/Animes/Characters/CharactersListVC+UITableView.swift
UTF-8
1,994
2.671875
3
[]
no_license
// // CharactersListVC+UITableView.swift // TopAnime // // Created by Mohamed Rwash on 10/7/18. // Copyright © 2018 mrwash. All rights reserved. // import UIKit extension CharactersListVC { override func numberOfSections(in tableView: UITableView) -> Int { return allCharacters.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor.whiteBlueColor let label = UILabel() view.addSubview(label) label.backgroundColor = UIColor.whiteBlueColor label.text = genders[section] label.textColor = UIColor.darkBlueColor label.font = UIFont.boldSystemFont(ofSize: 16) label.translatesAutoresizingMaskIntoConstraints = false label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = true return view } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allCharacters[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) let character = allCharacters[indexPath.section][indexPath.row] cell.textLabel?.text = character.name if let gender = character.characterInfo?.gender { cell.textLabel?.text?.append(" - " + gender) } cell.textLabel?.textColor = UIColor.white cell.backgroundColor = UIColor.lightBlueColor cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16) return cell } }
true
b5a8634daba5d57965c28a014fafa030c48e9277
Swift
pradorocchi/booklab
/booklab-frontend-ios/src/main/swift/Booklab/Views/Collection/CollectionTableViewController.swift
UTF-8
9,476
2.53125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 The BookLab Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import Siesta import CRRefresh import Material public class CollectionTableViewController: UITableViewController { public var userService: UserService! public var collectionService: CollectionService! var collectionsResource: Resource? { didSet { oldValue?.removeObservers(ownedBy: self) collectionsResource? .addObserver(self) .addObserver(self.snackbarController!) .loadIfNeeded() } } var collections: [BookCollection] = [] { didSet { tableView.reloadData() } } var user: User! public override func viewDidLoad() { super.viewDidLoad() // Configure edit button self.navigationItem.rightBarButtonItem = self.editButtonItem // Request the current user self.userService.me .addObserver(self) .addObserver(self.snackbarController!) .loadIfNeeded() // Configure refresh toggle self.tableView.cr.addHeadRefresh(animator: NormalHeaderAnimator()) { [weak self] in self?.collectionsResource?.load() .onCompletion { _ in self?.tableView.cr.endHeaderRefresh() } } // Load header view nib let nib = UINib(nibName: "Collection", bundle: Bundle.main) tableView.register(nib, forHeaderFooterViewReuseIdentifier: "header") tableView.sectionHeaderHeight = 55.0 } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Update the collections if they were updated in another part of the // application. collectionsResource?.loadIfNeeded() } // Handler for creating a collection @IBAction public func create() { let alertController = UIAlertController(title: "Create collection", message: "Enter name for collection", preferredStyle: .alert) let confirmAction = UIAlertAction(title: "Create", style: .default) { (_) in let name = alertController.textFields?[0].text self.create(name: name!) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in } alertController.addTextField { (textField) in textField.placeholder = "Enter Name" } alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } @IBAction public func delete(sender: UIControl) { if sender is UIButton { let header = sender.superview?.superview?.superview as! CollectionHeaderView delete(at: header.section) } else { let header = sender.superview?.superview as! CollectionHeaderView delete(at: header.section) } } /** * Create a [BookCollection] with the given name. */ public func create(name: String) { let _ = self.collectionService .create(name: name) .useSnackbar(snackbarController: self.snackbarController!) } /** * Delete a [BookCollection] at the given section. */ public func delete(at section: Int) { let collection = collections[section] let alert = UIAlertController( title: "Delete collection", message: "Are you sure you want to delete this collection?", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ in let _ = self.collectionService .delete(collection: collection) .useSnackbar(snackbarController: self.snackbarController!) }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) self.present(alert, animated: true, completion: nil) } /** * Delete a [Book] from at the given indexPath. */ public func deleteBook(at indexPath: IndexPath) { let collection = collections[indexPath.section] let book = collection.books[indexPath.row] let cell = tableView.cellForRow(at: indexPath) cell?.isUserInteractionEnabled = false let _ = self.collectionService .remove(from: collection, books: [book]) .useSnackbar(snackbarController: self.snackbarController!) .onSuccess { self.tableView.beginUpdates() self.collections[indexPath.section] = $0.typedContent()! self.tableView.deleteRows(at: [indexPath], with: .top) self.tableView.endUpdates() } .onCompletion { _ in cell?.isUserInteractionEnabled = true } } /** * Move a [Book] to another index. */ public func moveBook(from origin: IndexPath, to destination: IndexPath) { let originCollection = collections[origin.section] let destinationCollection = collections[destination.section] let book = originCollection.books[origin.row] if origin.section == destination.section { return } let _ = self.collectionService .remove(from: originCollection, books: [book]) .flatMap { _ in return self.collectionService.add(to: destinationCollection, books: [book]) } .useSnackbar(snackbarController: self.snackbarController!) } // MARK: - Table view data source public override func numberOfSections(in tableView: UITableView) -> Int { return collections.count } public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return collections[section].books.count } public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "book", for: indexPath) as! CatalogueBookTableViewCell let book = collections[indexPath.section].books[indexPath.row] cell.book = book return cell } public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0; } public override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as! CollectionHeaderView let collection = collections[section] header.name.text = collection.name.uppercased() header.section = section return header } public override func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return 55.0 } // Override to support conditional editing of the table view. public override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // Override to support editing the table view. public override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source deleteBook(at: indexPath) } } // Override to support conditional rearranging of the table view. public override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } public override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { moveBook(from: sourceIndexPath, to: destinationIndexPath) } // MARK: Navigation public override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "detail", let destination = segue.destination as? CatalogueBookViewController, let index = tableView.indexPathForSelectedRow { destination.book = collections[index.section].books[index.row] } } } extension CollectionTableViewController : ResourceObserver { public func resourceChanged(_ resource: Resource, event: ResourceEvent) { if resource == self.userService.me, let user: User = resource.typedContent() { self.user = user self.collectionsResource = self.collectionService.get(for: user) } else { collections = resource.typedContent() ?? [] } } }
true
ddddec951b4c91fe9c8802cf01770110a9d68251
Swift
brightdigit/Options
/Sources/Options/EnumSet.swift
UTF-8
2,591
3.71875
4
[ "MIT" ]
permissive
/// Generic struct for using Enums with RawValue type of Int as an Optionset public struct EnumSet<EnumType: RawRepresentable>: OptionSet where EnumType.RawValue == Int { public typealias RawValue = EnumType.RawValue /// Raw Value of the OptionSet public let rawValue: Int /// Creates the EnumSet based on the `rawValue` /// - Parameter rawValue: Integer raw value of the OptionSet public init(rawValue: Int) { self.rawValue = rawValue } /// Creates the EnumSet based on the values in the array. /// - Parameter values: Array of enum values. public init(values: [EnumType]) { let set = Set(values.map { $0.rawValue }) rawValue = Self.cumulativeValue(basedOnRawValues: set) } internal static func cumulativeValue( basedOnRawValues rawValues: Set<Int>) -> Int { rawValues.map { 1 << $0 }.reduce(0, |) } } extension EnumSet where EnumType: CaseIterable { internal static func enums(basedOnRawValue rawValue: Int) -> [EnumType] { let cases = EnumType.allCases.sorted { $0.rawValue < $1.rawValue } var values = [EnumType]() var current = rawValue for item in cases { guard current > 0 else { break } let rawValue = 1 << item.rawValue if current & rawValue != 0 { values.append(item) current -= rawValue } } return values } /// Returns an array of the enum values based on the OptionSet /// - Returns: Array for each value represented by the enum. public func array() -> [EnumType] { Self.enums(basedOnRawValue: rawValue) } } extension EnumSet: Codable where EnumType: MappedValueRepresentable, EnumType.MappedType: Codable { /// Decodes the EnumSet based on an Array of MappedTypes. /// - Parameter decoder: Decoder which contains info as an array of MappedTypes. public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let values = try container.decode([EnumType.MappedType].self) let rawValues = try values.map(EnumType.rawValue(basedOn:)) let set = Set(rawValues) rawValue = Self.cumulativeValue(basedOnRawValues: set) } /// Encodes the EnumSet based on an Array of MappedTypes. /// - Parameter encoder: Encoder which will contain info as an array of MappedTypes. public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() let values = Self.enums(basedOnRawValue: rawValue) let mappedValues = try values .map { $0.rawValue } .map(EnumType.mappedValue(basedOn:)) try container.encode(mappedValues) } }
true
48e514812123af86e239e112fff89fc4a8388856
Swift
abrahamshenghur/ShoppingList
/ShoppingList/Model/ImageStorage.swift
UTF-8
557
2.8125
3
[]
no_license
// // ImageStorage.swift // ShoppingList // // Created by John on 9/2/18. // Copyright © 2018 Abraham Shenghur. All rights reserved. // import UIKit class ImageStorage { let cache = NSCache<NSString,UIImage>() func setImage(_ image: UIImage, forKey key: String) { cache.setObject(image, forKey: key as NSString) } func image(forKey key: String) -> UIImage? { return cache.object(forKey: key as NSString) } func deleteImage(forKey key: String) { cache.removeObject(forKey: key as NSString) } }
true
4146882fea2a1250740de6b2dd35cb3b1073c7a8
Swift
traning-ios/LearningSwiftUI
/SwiftUI-Sample-App-master/Demo/LRF/ForgotPasswordView.swift
UTF-8
3,156
3.109375
3
[ "MIT" ]
permissive
// // ForgotPasswordView.swift // DemoSwiftUI // // Created by mac-00018 on 10/10/19. // Copyright © 2019 mac-00018. All rights reserved. // import SwiftUI struct ForgotPasswordView: View { @State var email: String = "" @State var showAlert = false @State var alertMsg = "" var alert: Alert { Alert(title: Text(""), message: Text(alertMsg), dismissButton: .default(Text("OK"))) } @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> var body: some View { NavigationView { ScrollView { VStack { Spacer(minLength: 80) Text("Write your email address in the text box and we will send you a verification code to reset your password.") .font(.body) .padding() .fixedSize(horizontal: false, vertical: true) .multilineTextAlignment(.center) VStack { HStack { Image("ic_email") .padding(.leading, 20) TextField("Email", text: $email) .frame(height: 40, alignment: .center) .padding(.leading, 10) .padding(.trailing, 10) .font(.system(size: 15, weight: .regular, design: .default)) .imageScale(.small) .keyboardType(.emailAddress) .autocapitalization(UITextAutocapitalizationType.none) } seperator() } Spacer(minLength: 20) Button(action: { if self.isValidInputs() { self.presentationMode.wrappedValue.dismiss() } }) { buttonWithBackground(btnText: "SUBMIT") } } } }.alert(isPresented: $showAlert, content: { self.alert }) } func isValidInputs() -> Bool { if self.email == "" { self.alertMsg = "Email can't be blank." self.showAlert.toggle() return false } else if !self.email.isValidEmail { self.alertMsg = "Email is not valid." self.showAlert.toggle() return false } return true } } struct ModalView: View { var body: some View { Group { Text("Modal view") } } } struct ForgotPasswordView_Previews: PreviewProvider { static var previews: some View { ForgotPasswordView() } }
true
b820c223dd39673d78b33413639137a18ba39dba
Swift
adamcin/RxExecs
/Tests/RxExecsTests/ANSITests.swift
UTF-8
1,861
2.75
3
[]
no_license
// // ANSITests.swift // RxExecs // import XCTest import RxSwift import RxBlocking @testable import RxExecs class ANSITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParse() { //let nsString = NSMutableAttributedString(string: "") let ansiString = "before \u{1b}[34mblue \u{1b}[0mafter" let ansi = ANSI() let decoded = ansi.decodeANSI(encodedString: ansiString) print("decoded: \(decoded)") assert(decoded.string == "before blue after") let stripped = ansi.stripANSI(encodedString: ansiString) print("stripped: \(stripped)") assert(stripped.string == "before blue after") } func testContinuation() { let ansi = ANSI(font: NSFont(name: "Source Code Pro", size: 12.0)!, fgColor: NSColor.black) let ansiString = " \u{1B}[1mPlease note that these warnings are just used to help the Homebrew maintainers.\n" let ansiString2 = "with debugging if you file an issue. If everything you use Homebrew for is" let decoded = [ansiString, ansiString2].reduce((NSMutableAttributedString(string: ""), [SGRCode]())) { (pair, val) -> (NSMutableAttributedString, [SGRCode]) in let (nsa, open) = pair let (nsa2, open2) = ansi.decodeANSI(encodedString: val, openCodes: open) print("open: \(open), open2: \(open2)") nsa.append(nsa2) return (nsa, open2) } print("decoded: \(decoded.0)") } }
true
b0aa31f93b4cd107efdded8f1ea93acff0787026
Swift
jonnymbaird/GoTCombine
/GoTCombine/Models/Book.swift
UTF-8
1,904
3.53125
4
[]
no_license
// // Book.swift // GoTCombine // // Created by Jonathan Baird on 26/03/2021. // import Foundation /** An API of IceAndFire Book. [API Documentation](https://anapioficeandfire.com/Documentation#books) */ struct Book: Decodable, Hashable { static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" return formatter }() let name: String let numberOfPages: Int let released: Date let isbn: String func hash(into hasher: inout Hasher) { hasher.combine(isbn) } static func == (lhs: Book, rhs: Book) -> Bool { lhs.isbn == rhs.isbn } enum CodingKeys: String, CodingKey { case name case numberOfPages case released case isbn } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decode(String.self, forKey: .name) self.numberOfPages = try container.decode(Int.self, forKey: .numberOfPages) let dateString = try container.decode(String.self, forKey: .released) Book.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" self.released = Book.dateFormatter.date(from: dateString) ?? Date() self.isbn = try container.decode(String.self, forKey: .isbn) } } extension Book { var displayModel: BookDisplayModel { Book.dateFormatter.locale = Locale(identifier: "en_GB") Book.dateFormatter.setLocalizedDateFormatFromTemplate("MMMyyyy") return BookDisplayModel(name: name, numberofPages: "\(numberOfPages) pages", date: Book.dateFormatter.string(from: released)) } } struct BookDisplayModel { let name: String let numberofPages: String let date: String }
true
5eba64f69462e19df7c43f9d539a1c67210c80a8
Swift
zondug/PY
/PY/CellsView.swift
UTF-8
1,651
3.28125
3
[]
no_license
// // CellsView.swift // PY // // Created by Zondug Kim on 2017. 10. 4.. // Copyright © 2017년 Zondug Kim. All rights reserved. // import Foundation import UIKit class CellsView: UIView { var textlabel: UILabel! // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // } func initializeCells() { self.backgroundColor = .black let noOfCells: Int = 5 let cellsize: Int = Int(self.bounds.maxX)/(noOfCells+1) let spacing: Int = 5 let centering: Int = Int(self.bounds.width)/2 - (noOfCells * cellsize + (spacing * 4))/2 for rows in 0...(noOfCells-1) { for cols in 0...(noOfCells-1) { let back = UIView() back.frame = CGRect(x: centering + (rows * cellsize) + (rows * spacing), y: centering + (cols * cellsize) + (cols * spacing), width: cellsize, height: cellsize) let cell: UIImageView = UIImageView(frame: back.bounds) // 이 레이블은 이제 UIImage로 교체해야 함: celldata <- mapdata textlabel = UILabel(frame: cell.bounds) textlabel.textAlignment = .center textlabel.textColor = .white // textlabel.text = "\(rows, cols)" textlabel.text = "\((mapArray[viewkey])!)" cell.addSubview(textlabel) cell.layer.borderWidth = 1.5 cell.layer.borderColor = UIColor.white.cgColor cell.layer.cornerRadius = 2 cell.layer.masksToBounds = true cell.bringSubview(toFront: textlabel) back.addSubview(cell) self.addSubview(back) viewkey = "\(rows)|\(cols)" cells[viewkey] = cell } } } func drawingcell() { // cell 그리는 부분을 별도 함수로 뺄 수 있나? } }
true
0ce7606e29885276150e6b01417dee865f1d37c1
Swift
ramirolvn/MovieCollectionView
/SkyTest/SkyTestTests/FakeDataService.swift
UTF-8
1,369
2.71875
3
[]
no_license
// // FakeDataService.swift // SkyTestTests // // Created by Ramiro Neto on 24/05/2019. // Copyright © 2019 Ramiro Lima Vale Neto. All rights reserved. // @testable import SkyTest import Foundation import ObjectMapper class FakeDataService: DataService { private let fakeDataDict = [["title": "Movie 1", "overview": "Just a test movie", "duration" : "1h 55m", "release_year":"2017", "cover_url":"coverIMG1", "backdrops_url": ["backdrops_url1","backdrops_url2"], "id": "1"], ["title": "Movie 2", "overview": "Just a test movie 2", "duration" : "3h 45m", "release_year":"1999", "cover_url":"coverIMG2", "backdrops_url": ["backdrops_url1","backdrops_url2"], "id": "2"], ["title": "Movie 3", "overview": "Just a test movie 3", "duration" : "3h 34m", "release_year":"2013", "cover_url":"coverIMG3", "backdrops_url": ["backdrops_url1","backdrops_url2"], "id": "3"]] as [[String : Any]] func getFakeMoviesTest(sucess: Bool) -> ([Movie]?,String?){ if sucess { var movies = [Movie]() for obj in fakeDataDict { if let movie = Movie(map: Map.init(mappingType: .fromJSON, JSON: obj)){ movies.append(movie) } } if movies.count > 0{return(movies,nil)} return (nil,"Nenhum filme encontrado!") } return (nil,"Erro na requisição!") } }
true
94d84bdd60d311365a49ce2ee5f3b5cb623b8547
Swift
William-Weng/Swift-5
/MyEnglish/MyEnglish/ViewController/View/Cells.swift
UTF-8
2,159
3
3
[ "MIT" ]
permissive
// // Cells.swift // MyEnglish // // Created by Yu-Bin Weng on 2021/1/10. // import UIKit import AVFoundation final class MyTableViewCell: UITableViewCell { static var records: [[String: Any]] = [] static var levels: [[String: Any]] = [] @IBOutlet weak var indexLabel: UILabel! @IBOutlet weak var wordLabel: UILabel! @IBOutlet weak var notesLabel: UILabel! @IBOutlet weak var levelColorView: UIView! func configure(with indexPath: IndexPath) { guard let record = Self.records[safe: indexPath.row], let info = Record._build(record: record), let fields = NoteFields._build(fields: info.fields), let backgroundColor = levelColor(fields.level) else { return } indexLabel.text = (indexPath.row + 1)._repeatString(count: 3) wordLabel.text = fields.word notesLabel.text = fields.notes levelColorView.backgroundColor = backgroundColor } } extension MyTableViewCell: CellReusable, AVSpeechSynthesizerDelegate { /// [文字發聲](https://medium.com/彼得潘的-swift-ios-app-開發問題解答集/讓開不了口的-app-開口說話-48c674f8f69e) /// - Parameter string: 要讀的文字 func speech(string: String, voice: Utility.VoiceCode = .english) { let synthesizer = AVSpeechSynthesizer._build(delegate: self) synthesizer._speak(string: string, voice: voice) } /// 取得該等級的顏色 /// - Parameter level: 等級 (1~5) /// - Returns: UIColor? private func levelColor(_ level: Int) -> UIColor? { let colors = Self.levels.compactMap { (record) -> String? in guard let info = Record._build(record: record), let fields = LevelFields._build(fields: info.fields), fields.level == level else { return nil } return fields.color } guard let colorString = colors.first else { return nil } return UIColor(rgb: colorString) } }
true
241e6965beaac946bcdc6d6cdf3bceac39cd8d76
Swift
00mjk/NBus
/NBus/Classes/Core/Bus+Message.swift
UTF-8
5,627
2.875
3
[ "MIT" ]
permissive
// // Bus+Message.swift // NBus // // Created by nuomi1 on 2020/8/23. // Copyright © 2020 nuomi1. All rights reserved. // import Foundation public struct Message: RawRepresentable, Hashable { public typealias RawValue = String public let rawValue: Self.RawValue public init(rawValue: Self.RawValue) { self.rawValue = rawValue } } public enum Messages { public static let text = Message(rawValue: "com.nuomi1.bus.message.text") public static let image = Message(rawValue: "com.nuomi1.bus.message.image") public static let audio = Message(rawValue: "com.nuomi1.bus.message.audio") public static let video = Message(rawValue: "com.nuomi1.bus.message.video") public static let webPage = Message(rawValue: "com.nuomi1.bus.message.webPage") public static let file = Message(rawValue: "com.nuomi1.bus.message.file") public static let miniProgram = Message(rawValue: "com.nuomi1.bus.message.miniProgram") public static func text( text: String ) -> TextMessage { TextMessage( text: text ) } public static func image( data: Data, title: String? = nil, description: String? = nil, thumbnail: Data? = nil ) -> ImageMessage { ImageMessage( data: data, title: title, description: description, thumbnail: thumbnail ) } public static func audio( link: URL, dataLink: URL? = nil, title: String? = nil, description: String? = nil, thumbnail: Data? = nil ) -> AudioMessage { AudioMessage( link: link, dataLink: dataLink, title: title, description: description, thumbnail: thumbnail ) } public static func video( link: URL, title: String? = nil, description: String? = nil, thumbnail: Data? = nil ) -> VideoMessage { VideoMessage( link: link, title: title, description: description, thumbnail: thumbnail ) } public static func webPage( link: URL, title: String? = nil, description: String? = nil, thumbnail: Data? = nil ) -> WebPageMessage { WebPageMessage( link: link, title: title, description: description, thumbnail: thumbnail ) } public static func file( data: Data, fileExtension: String, fileName: String? = nil, title: String? = nil, description: String? = nil, thumbnail: Data? = nil ) -> FileMessage { FileMessage( data: data, fileExtension: fileExtension, fileName: fileName, title: title, description: description, thumbnail: thumbnail ) } public static func miniProgram( miniProgramID: String, path: String, link: URL, miniProgramType: MiniProgramMessage.MiniProgramType, title: String? = nil, description: String? = nil, thumbnail: Data? = nil ) -> MiniProgramMessage { MiniProgramMessage( miniProgramID: miniProgramID, path: path, link: link, miniProgramType: miniProgramType, title: title, description: description, thumbnail: thumbnail ) } } public protocol MessageType { var identifier: Message { get } } public protocol MediaMessageType: MessageType { var title: String? { get } var description: String? { get } var thumbnail: Data? { get } } public struct TextMessage: MessageType { public let identifier = Messages.text public let text: String } public struct ImageMessage: MediaMessageType { public let identifier = Messages.image public let data: Data public let title: String? public let description: String? public let thumbnail: Data? } public struct AudioMessage: MediaMessageType { public let identifier = Messages.audio public let link: URL public let dataLink: URL? public let title: String? public let description: String? public let thumbnail: Data? } public struct VideoMessage: MediaMessageType { public let identifier = Messages.video public let link: URL public let title: String? public let description: String? public let thumbnail: Data? } public struct WebPageMessage: MediaMessageType { public let identifier = Messages.webPage public let link: URL public let title: String? public let description: String? public let thumbnail: Data? } public struct FileMessage: MediaMessageType { public let identifier = Messages.file public let data: Data public let fileExtension: String public let fileName: String? public let title: String? public let description: String? public let thumbnail: Data? public var fullName: String? { fileName.map { "\($0).\(fileExtension)" } } } public struct MiniProgramMessage: MediaMessageType { public enum MiniProgramType { case release case test case preview } public let identifier = Messages.miniProgram public let miniProgramID: String public let path: String public let link: URL public let miniProgramType: MiniProgramType public let title: String? public let description: String? public let thumbnail: Data? }
true
5d2ea6369d8084d221ad517779a92275848dbf09
Swift
His-writing/swiftTbale
/swiftTbale/ViewController.swift
UTF-8
1,785
2.84375
3
[]
no_license
// // ViewController.swift // swiftTbale // // Created by china on 15/10/26. // Copyright © 2015年 china. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableviewSwift:UITableView? var items :NSMutableArray? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title="tableView-swift--love" self.items=["111","222","333","444"] self.tableviewSwift = UITableView(frame:self.view!.frame) // // self.tableviewSwift!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.tableviewSwift!.delegate=self; self.tableviewSwift!.dataSource=self; self.view .addSubview(self.tableviewSwift!); } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.items?.count)!; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //判断是不是空 tableView.registerClass(UITableViewCell.self , forCellReuseIdentifier: "cell") let cell = tableView .dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell cell.textLabel!.text = String(format: "%i", indexPath.row+1) cell.textLabel?.backgroundColor=UIColor .redColor(); return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
04c8993579f72cb86febd268ee978fb410599e36
Swift
BrunoCA-xD/StartingWith_siriKit
/StartingWithSirikit/SecondViewController.swift
UTF-8
3,371
2.6875
3
[ "MIT" ]
permissive
// // SecondViewController.swift // StartingWithSirikit // // Created by Bruno Cardoso Ambrosio on 17/03/20. // Copyright © 2020 Bruno Cardoso Ambrosio. All rights reserved. // import UIKit import IntentsUI class SecondViewController: UIViewController { @IBOutlet weak var siriButtonContainer: UIView! private let siriButton = INUIAddVoiceShortcutButton(style: .automatic) override func viewDidLoad() { super.viewDidLoad() prepareSiriButton() } @objc func addToSiri(sender: Any) { guard let sender = sender as? INUIAddVoiceShortcutButton, let shortcutFromButton = sender.shortcut else { return } SiriUtil.openShortcutViewController(caller: self, shortcut: shortcutFromButton) { (shortcutViewController) in // as we are on a closure, we need to call the main thread to present the modal DispatchQueue.main.async { self.present(shortcutViewController, animated: true, completion: nil) } } } func prepareSiriButton() { //set the horizontal content hugging to 250 (defaultLow) siriButton.setContentHuggingPriority(.defaultLow, for: .horizontal) //Turn off the autolayout constraints because we gonna do by our own siriButton.translatesAutoresizingMaskIntoConstraints = false //Add the button to the container siriButtonContainer.addSubview(siriButton) //Centralize the button in X axis in the container siriButton.centerXAnchor.constraint(equalTo: siriButtonContainer.centerXAnchor).isActive = true //Bind the both heights siriButtonContainer.heightAnchor.constraint(equalTo: siriButton.heightAnchor).isActive = true //TODO: add shortcut to the button //set the callback of the button siriButton.addTarget(self, action: #selector(addToSiri), for: .touchUpInside) } } extension SecondViewController: INUIAddVoiceShortcutViewControllerDelegate { // when the add action is completed func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) { controller.dismiss(animated: true, completion: nil) } // when the add action is canceled func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } } extension SecondViewController: INUIEditVoiceShortcutViewControllerDelegate{ //When the edit option is to update the shortcut func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) { controller.dismiss(animated: true, completion: nil) } //When the edit option is to delete the shortcut func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID) { controller.dismiss(animated: true, completion: nil) } //When modal Cancel button is tapped func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } }
true
4abd1a8d8183aa307cc8d1db58078acecc1d2f4f
Swift
Hel-len/Serenity
/Serenity/Model/Episode.swift
UTF-8
3,454
3.09375
3
[]
no_license
// // Episode.swift // Serenity // // Created by Елена Дранкина on 14.09.2021. // import Foundation struct Episode { let chapterId: Int let hero: Hero? let emotion: Emotion? let backgroundImage: BackgroundImage let shownImage: ShownImage? let chapterSound: ChapterSound let chapterText: String static func getEpisodes() -> [Episode] { [ Episode( chapterId: 1, hero: nil, emotion: nil, backgroundImage: .shuttleInterior, shownImage: nil, chapterSound: .standart, chapterText: """ За столом сидели несколько офицеров. Кто-то пил ром, кто-то просто слушал разговоры. Обсуждали план захвата транспортника. """ ), Episode( chapterId: 2, hero: .kris, emotion: .neutral, backgroundImage: .shuttleInterior, shownImage: nil, chapterSound: .standart, chapterText: """ Да там приключение на десять минут. Зашли и вышли! Не так давно банда Кристи перехватила план передвижения «Серенити» — транспортника с ценным грузом. """ ), Episode( chapterId: 3, hero: nil, emotion: nil, backgroundImage: .shuttleInterior, shownImage: .skyMap, chapterSound: .swipe, chapterText: "Джо отставил пустую кружку и разложил на столе голографическую карту." ), Episode( chapterId: 4, hero: .joe, emotion: .neutral, backgroundImage: .shuttleInterior, shownImage: .skyMapDest, chapterSound: .swipe, chapterText: "Обычно с транспортником в комплекте идет крейсер и минимум пять кораблей поменьше." ) ] } } enum Hero: String { case joe = "joe" case kris = "kris" case nik = "nik" case dow = "dow" case conf = "conf" var name: String { switch self { case .joe: return "Джо" case .kris: return "Крис" case .nik: return "Ник" case .dow: return "Доу" case .conf: return "Конфидо" } } } enum Emotion: String { case angry = "Angry" case happy = "Happy" case neutral = "Neutral" case sad = "Sad" case scared = "Scared" case suprised = "Suprised" } enum ShownImage: String { case skyMap = "skyMap" case skyMapSerenity = "skyMapSerenity" case skyMapDest = "skyMapDest" case book = "book" } enum BackgroundImage: String { case shuttleInterior = "shuttleInterior" case bgSpace = "bgSpace" case bgStars = "bgStars" case mainMenu = "mainMenu" } enum ChapterSound: String { case loadInterface = "loadInteface" case swipe = "swipe" case attack = "attack" case psh = "psh" case standart = "standart" case chat = "chat" }
true
851cfe5d7706f7fc9c5f6186a56d2caee2d93dbb
Swift
ejp-rd-vp/ejp-rd-metadata-swift
/Sources/EJPRDMetadata/Dataset.swift
UTF-8
818
2.796875
3
[]
no_license
import Foundation public struct Dataset: Codable { public let id: URL public let type = "BiobankDataset" public let name: String public let theme: [Theme] public let publisher: Publisher public let numberOfPatients: Int public let context = URL(string: "https://raw.githubusercontent.com/ejp-rd-vp/resource-metadata-schema/master/ejp_vocabulary_context.json")! public init(id: URL, name: String, theme: [Theme], publisher: Publisher, numberOfPatients: Int) { self.id = id self.name = name self.theme = theme self.publisher = publisher self.numberOfPatients = numberOfPatients } private enum CodingKeys: String, CodingKey { case id = "@id", type = "@type", name, theme, publisher, numberOfPatients, context = "@context" } }
true
c60c6961e13aed327aee1c419a313f5b12c5d67b
Swift
Chylis/Swiftilities
/Tests/SwiftilitiesTests/DictionaryTests.swift
UTF-8
2,681
3.375
3
[]
no_license
// // DictionaryTests.swift // Swiftilities // // Created by Magnus Eriksson on 17/05/16. // Copyright © 2016 Magnus Eriksson. All rights reserved. // import XCTest @testable import Swiftilities final class DictionaryTests: XCTestCase { func testDefaultToSubscript() { var dict = [0:0,1:1,2:2,3:3] //Assert correct value for existing key is returned XCTAssertEqual(3, dict[3, default: 5]) //Assert default value for non-existing key is returned XCTAssertEqual(5, dict[9, default: 5]) //Assert possibility to add new values using custom subscript operator dict[77, default: 100] += 1 XCTAssertEqual(101, dict[77]) } func testUnion() { var dict1 = [0:0,1:1,2:2,3:3] let dict2 = [4:4,5:5,6:6,7:7] dict1.union(with: dict2) for int in 0...7 { XCTAssertEqual(int, dict1[int]) } } func testUnioned() { let empty: [Int:Int] = [:] let dict1 = [0:0,1:1,2:2,3:3] let dict2 = [4:4,5:5,6:6,7:7] let dict3 = dict1.unioned(with: dict2) //Test union with one or more empty dictionaries XCTAssertEqual(empty.unioned(with: empty), empty) XCTAssertEqual(dict1.unioned(with: empty), dict1) XCTAssertEqual(empty.unioned(with: dict1), dict1) //Test union with non-empty dictionaries for int in 0...7 { XCTAssertEqual(int, dict3[int]) } } func testPlusOperator() { let dict1 = [0:0,1:1,2:2,3:3] let dict2 = [4:4,5:5,6:6,7:7] let dict3 = dict1 + dict2 for int in 0...7 { XCTAssertEqual(int, dict3[int]) } } func testMinusOperator() { //Test removing empty dictionary XCTAssertEqual([1:1,2:2,3:3] - [:], [1:1,2:2,3:3]) XCTAssertEqual(([:] as [Int:Int]) - ([:] as [Int:Int]), [:]) XCTAssertEqual([:] - [1:1,2:2,3:3], [:]) //Test removing single element in dict XCTAssertEqual([1:1,2:2,3:3] - [3:3], [1:1,2:2]) //Test removing several elements XCTAssertEqual([1:1,2:2,3:3] - [3:3, 1:1], [2:2]) XCTAssertEqual([1:1,3:3,5:5,6:6,7:7] - [1:1,2:2,3:3], [5:5,6:6,7:7]) //Test removing all elements XCTAssertEqual([1:1,2:2,3:3] - [1:1,2:2,3:3,4:4,5:5], [:]) } func testMapValues() { let dict1 = [0:0,1:1,2:2,3:3] let dict2: [Int:String] = dict1.mappingValues { String($0) } for (key,value) in dict1 { XCTAssertEqual(dict2[key], String(value)) } } }
true
e25e4dcd6cedb7fb3158e052b4c7ad626691d020
Swift
zcgong/bulleted-list-for-uilabel-uitextview
/BulletedList/ViewController.swift
UTF-8
2,011
2.875
3
[]
no_license
// // ViewController.swift // BulletedList // // Created by Ben Dodson on 09/08/2018. // Copyright © 2018 Dodo Apps. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: .UIContentSizeCategoryDidChange, object: nil) updateUI() } @objc func updateUI() { let bullet = "• " var strings = [String]() strings.append("Payment will be charged to your iTunes account at confirmation of purchase.") strings.append("Your subscription will automatically renew unless auto-renew is turned off at least 24-hours before the end of the current subscription period.") strings.append("Your account will be charged for renewal within 24-hours prior to the end of the current subscription period.") strings.append("Automatic renewals will cost the same price you were originally charged for the subscription.") strings.append("You can manage your subscriptions and turn off auto-renewal by going to your Account Settings on the App Store after purchase.") strings.append("Read our terms of service and privacy policy for more information.") strings = strings.map { return bullet + $0 } label.adjustsFontForContentSizeCategory var attributes = [NSAttributedStringKey: Any]() attributes[.font] = UIFont.preferredFont(forTextStyle: .body) attributes[.foregroundColor] = UIColor.darkGray let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.headIndent = (bullet as NSString).size(withAttributes: attributes).width attributes[.paragraphStyle] = paragraphStyle let string = strings.joined(separator: "\n\n") label.attributedText = NSAttributedString(string: string, attributes: attributes) } }
true
eda1545f38ca3f8b0d9f2680f75ee942b47370cd
Swift
MixFon/Swifty_Companion
/Swifty Companion/Authentication.swift
UTF-8
2,127
2.71875
3
[]
no_license
// // Authentication.swift // Swifty Companion // // Created by Михаил Фокин on 26.01.2021. // import Foundation final class Authentication { private enum DefaultsKey: String { case codeAuthorisation case isCodeAuthorisation case isAccessToken case accessToken } static var isCodeAuthorisation: Bool! { get { return UserDefaults.standard.bool(forKey: DefaultsKey.isCodeAuthorisation.rawValue) } set { let key = DefaultsKey.isCodeAuthorisation.rawValue if let isAut = newValue { UserDefaults.standard.set(isAut , forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } } } static var isAccessToken: Bool! { get { return UserDefaults.standard.bool(forKey: DefaultsKey.isAccessToken.rawValue) } set { let key = DefaultsKey.isAccessToken.rawValue if let isAut = newValue { UserDefaults.standard.set(isAut , forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } } } static var codeAuthorisation: String! { get { return UserDefaults.standard.string(forKey: DefaultsKey.codeAuthorisation.rawValue) } set { let key = DefaultsKey.codeAuthorisation.rawValue if let code = newValue { UserDefaults.standard.set(code , forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } } } static var accessToken: String! { get { return UserDefaults.standard.string(forKey: DefaultsKey.accessToken.rawValue) } set { let key = DefaultsKey.accessToken.rawValue if let accessToken = newValue { UserDefaults.standard.set(accessToken , forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } } } }
true
47d53d33e1889b6a03bc6aeebc4ab6b6c9b3cb29
Swift
ycaihua/FaceReplacer
/FaceReplacer/Sources/ViewControllers/MainVC/MainVC.swift
UTF-8
3,911
2.5625
3
[]
no_license
// // MainVC.swift // FaceReplacer // // Created by Admin on 01.07.15. // Copyright (c) 2015 Admin. All rights reserved. // import UIKit import QuartzCore class MainVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: - IBOutlets @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var swapFacesBarButton: UIBarButtonItem! @IBOutlet weak var cameraBarButton: UIBarButtonItem! // MARK: - Variables var imagePickerController:UIImagePickerController = UIImagePickerController() // MARK: - ViewController's methods override func viewDidLoad() { super.viewDidLoad() self.imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.imagePickerController.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(UIImagePickerControllerSourceType.PhotoLibrary)! self.imagePickerController.delegate = self } // MARK: - IBActions @IBAction func SwapFacesButtonPressed(sender: UIBarButtonItem) { if let photoImageViewsImage = self.photoImageView.image { sender.enabled = false self.cameraBarButton.enabled = false var processedImage: UIImage? self.activityIndicator.startAnimating() self.activityIndicator.hidden = false dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), { processedImage = photoImageViewsImage.recognizeAndSwapFaces() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.activityIndicator.stopAnimating() if let resultImage = processedImage { self.photoImageView.image = resultImage } else { var alertView = UIAlertView(title: "Face recognition problem", message: "Can't find faces and swap them. Please chose another photo", delegate: nil, cancelButtonTitle: "OK") alertView.show() } sender.enabled = true self.cameraBarButton.enabled = true }) }) } else { var alertView = UIAlertView(title: "Image is empty", message: "Please chose photo from library before swapping faces", delegate: nil, cancelButtonTitle: "OK") alertView.show() } } @IBAction func CameraButtonPressed(sender: UIBarButtonItem) { presentViewController(self.imagePickerController, animated: true, completion: nil) } // MARK: - UIImagePickerControllerDelegate methods func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { var originalImage: UIImage? = info[UIImagePickerControllerOriginalImage] as! UIImage? if let libraryImage = originalImage { self.photoImageView.image = libraryImage } else { var alertView = UIAlertView(title: "Error", message: "Can't get image", delegate: nil, cancelButtonTitle: "OK") alertView.show() } self.imagePickerController.dismissViewControllerAnimated(true, completion: nil) } }
true
b669fbc018624171a770fdd617fc44ce09d908a6
Swift
RickeyBoy/JSONToSwift
/JSONToSwiftExtension/JSONToSwift/ModelStructure/ModelComponents.swift
UTF-8
623
2.8125
3
[ "MIT" ]
permissive
// // ModelComponents.swift // JSONToSwift // // Created by Rickey on 2019/11/18. // Copyright © 2019 Rickey Wang. All rights reserved. // /// 模型中的变量信息 internal struct ModelComponents { var list: [ModelComponent] = [] } internal struct ModelComponent { /// name var name = "" /// type var type = "" /// 默认值 var defaultValue = "" /// raw name to map var map = "" init(name: String, type: String, defaultValue: String, map: String) { self.name = name self.type = type self.defaultValue = defaultValue self.map = map } }
true
8f762566e274b9fac08bff171a841d20db332833
Swift
EvaGonf12/UI-Avanzada-IOS
/DiscourseClient/Model/Requests/GetUsersRequest.swift
UTF-8
789
2.609375
3
[]
no_license
// // GetUsersRequest.swift // DiscourseClient // // Created by Hadrian Grille Negreira on 11/04/2020. // Copyright © 2020 Roberto Garrido. All rights reserved. // import Foundation /// Implementación de la request que obtiene los latest topics struct GetUsersRequest: APIRequest { typealias Response = GetUsersResponse var method: Method { return .GET } var path: String { return "/directory_items.json" //return "/directory_items.json?period=all&order=likes_received" } var parameters: [String : String] { return ["period":"all", "order":"likes_received"] //return[:] } var body: [String : Any] { return [:] } var headers: [String : String] { return [:] } }
true
47de6d89bb2a5cd257fb63e0264b6767b0182628
Swift
Mintri1199/Trip_Planner
/Trip_Planner/HelperExtensions.swift
UTF-8
1,372
2.796875
3
[]
no_license
// // HelperExtensions.swift // Trip_Planner // // Created by Jackson Ho on 4/19/19. // Copyright © 2019 Jackson Ho. All rights reserved. // import Foundation import UIKit // Hide the keyboard when the user is tapping anywhere extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } extension UIView { // Find the viewController of a UI component func findViewController() -> UIViewController? { if let nextResponder = self.next as? UIViewController { return nextResponder } else if let nextResponder = self.next as? UIView { return nextResponder.findViewController() } else { return nil } } // Shake animation func shake() { let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) animation.duration = 0.6 animation.values = [-10.0, 10.0, -10.0, 10.0, -5.0, 5.0, -5.0, 5.0, 0.0 ] layer.add(animation, forKey: "shake") } }
true
1ad7b231c69346d3983aeac4f16821e8ef23d4db
Swift
tatianepinto/FitnessClub
/Controllers/TabControllers/Home/SettingTableView.swift
UTF-8
1,240
2.515625
3
[]
no_license
// // SettingTableView.swift // FitnessClub // // Created by Tatiane on 2020-04-08. // Copyright © 2020 Tatiane. All rights reserved. // import UIKit import CoreData class SettingTableView: UITableViewController { //MARK: Constants let segueProfile = "segueProfile" let seguePlan = "seguePlan" //MARK: Properties var managedContext: NSManagedObjectContext! var name = "Name" //MARK: Outlets @IBOutlet weak var lbName: UILabel! override func viewDidLoad() { self.tabBarController?.tabBar.isHidden = true lbName.text = name } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case self.segueProfile: let controller = segue.destination as! EditProfile controller.managedContext = managedContext case self.seguePlan: let controller = segue.destination as! EditPlan controller.managedContext = managedContext default: return } } } // MARK: - Table view data source extension SettingTableView { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } }
true
00812440637269c3b4dd3d06cea92f5bb5f4423a
Swift
festrs/DummyProject
/Frameworks/Common/Sources/Common/Publisher+Extension.swift
UTF-8
1,973
2.59375
3
[]
no_license
// // Publisher+Extension.swift // Common // // Created by Felipe Dias Pereira on 14/09/20. // import Combine public extension Publisher { typealias ResultOutput = Result<Output, Failure> func sinkToResult(_ result: @escaping (ResultOutput) -> Void) -> AnyCancellable { return sink(receiveCompletion: { completion in switch completion { case let .failure(error): result(.failure(error)) default: break } }, receiveValue: { value in result(.success(value)) }) } func sinkToResult<Object: AnyObject>(for object: Object, _ result: @escaping (Object, ResultOutput) -> Void) -> AnyCancellable { return sink(receiveCompletion: { [weak object] completion in guard let object = object else { return } switch completion { case let .failure(error): result(object, .failure(error)) default: break } }, receiveValue: { [weak object] value in guard let object = object else { return } result(object, .success(value)) }) } func sinkToLoadable(_ completion: @escaping (Loadable<Output>) -> Void) -> AnyCancellable { return sink(receiveCompletion: { subscriptionCompletion in if case .failure(let error) = subscriptionCompletion { completion(.failed(error)) } }, receiveValue: { value in completion(.loaded(value)) }) } func sinkToLoadable<Object: AnyObject>(for object: Object, _ result: @escaping (Object, Loadable<Output>) -> Void) -> AnyCancellable { return sink(receiveCompletion: { [weak object] subscriptionCompletion in guard let object = object else { return } if case .failure(let error) = subscriptionCompletion { result(object, .failed(error)) } }, receiveValue: { [weak object] value in guard let object = object else { return } result(object, .loaded(value)) }) } }
true
632d601bf46821ebe74e8264242a882b7c0c296a
Swift
GioLucero/iOS-ShopifyChallenge
/ShopifyStore/View Model/CollectsViewModel.swift
UTF-8
1,559
2.921875
3
[]
no_license
// // CollectsViewModel.swift // ShopifyStore // // Created by Gio Lucero on 2020-03-25. // Copyright © 2020 Gio Lucero. All rights reserved. // import Foundation import SwiftUI import Combine import Alamofire /// Used to group products to the corresponding collection class CollectsViewModel: ObservableObject { /// Shared singleton of the global instance of CollectionViewModel static let shared = CollectsViewModel() /// Updates views once data has been changed let didChange = PassthroughSubject<CollectsViewModel, Never>() /// Array of collects that we can bind the values of our collectsViewModel @Published var collectsData: [Collects] = [Collects]() { didSet { didChange.send(self) } } /// Fetching the collect data public func getCollectData(withCollectionId collectionId: Int, completion: @escaping ([Int]) -> Void) { /// Passing in parameters for getCardData funcrtion let parameter: Parameters = [ "collection_id": collectionId ] /// Passing in the collection url for API call NetworkManager.shared.getCardData(withURL: NetworkManager.collectionURL, andParameters: parameter) { collectsDataJSON in /// Going through the JSON and accessing the first key element let productIds: [Int] = collectsDataJSON["collects"].arrayValue.map { /// $0 - accesses the key elemenent $0["product_id"].intValue } completion(productIds) } } }
true
9f4daf6f222a5639d4f7384312d64d2a9dfaa040
Swift
Tyrant2013/LeetCodePractice
/LeetCodePractice/Easy/20_Valid_Parentheses.swift
UTF-8
1,425
3.46875
3
[ "MIT" ]
permissive
// // Valid_Parentheses.swift // LeetCodePractice // // Created by 庄晓伟 on 2018/2/9. // Copyright © 2018年 Zhuang Xiaowei. All rights reserved. // import UIKit class Valid_Parentheses: Solution { override func ExampleTest() { ["[", "()", "()[]{}", "(]", "([)]", "()[((()))]", "((", "{{)}", "(])"].forEach { str in print("input str: \(str), isValid: \(self.isValid(str))") } } func isValid(_ s: String) -> Bool { let strArray = s.map({ $0 }) var queue = [Character]() var ret = true for ch in strArray { if ch == "(" || ch == "[" || ch == "{" { queue.append(ch) } else { if queue.count == 0 { ret = false break } let popCh = queue.popLast() switch ch { case ")": ret = popCh! == "(" case "]": ret = popCh! == "[" case "}": ret = popCh! == "{" default: ret = false } if ret == false { queue.append(popCh!) break } } } return queue.count == 0 && ret } }
true
b356cc08922640387160d30b0d4320351ff1682e
Swift
BeihaoZhang/SwiftBasicLearning
/Swift基础学习/Swift基础学习/CustomOperators.swift
UTF-8
1,432
3.953125
4
[]
no_license
// // CustomOperators.swift // Swift基础学习 // // Created by Lincoln on 2018/6/13. // Copyright © 2018年 Lincoln. All rights reserved. // import Foundation precedencegroup ExponentiationPrecedence { associativity: right higherThan: MultiplicationPrecedence } // 如果是swift中未声明的操作符,需要显式说明 infix operator **: ExponentiationPrecedence func **(base: Int, power: Int) -> Int { precondition(power >= 2) var result = base for _ in 2 ... power { result *= base } return result } // The exponentiation operator now works for all integer types: Int, UInt, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64 and UInt64. func **<T: BinaryInteger>(base: T, power: Int) -> T { precondition(power > 2) var result = base for _ in 2 ... power { result *= base } return result } infix operator **= func **=<T: BinaryInteger>(lhs: inout T, rhs: Int) { lhs = lhs ** rhs } struct Vector2D { var x = 0.0 var y = 0.0 } fileprivate func +(lhs: Vector2D, rhs: Vector2D) -> Vector2D { return Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } class CustomOperator { func test() { let lhs = Vector2D(x: 3, y: 6) let rhs = Vector2D(x: 4, y: 3) let result = lhs + rhs; let a = 3 + 4 print(result, a) let intResult = 2 * 2 ** 3 ** 2 print(intResult) } }
true
aa069cda2e59ac4a7c262b4843b67b924b073a86
Swift
BrunoScheltzke/FakeApp
/FakeApp/FakeApp/Service/PreviewManager.swift
UTF-8
1,259
2.578125
3
[]
no_license
// // PreviewManager.swift // FakeApp // // Created by Bruno Scheltzke on 10/10/18. // Copyright © 2018 Bruno Scheltzke. All rights reserved. // import Foundation import SwiftLinkPreview class PreviewManager { let slp: SwiftLinkPreview init() { let sessionConfig = URLSessionConfiguration.default sessionConfig.timeoutIntervalForRequest = 05.0 sessionConfig.timeoutIntervalForResource = 05.0 let session = URLSession(configuration: sessionConfig) slp = SwiftLinkPreview(session: session, workQueue: SwiftLinkPreview.defaultWorkQueue, responseQueue: DispatchQueue.main, cache: DisabledCache.instance) } func getPreview(of url: String, completion: @escaping((title: String, portal: String)?, Error?) -> Void) { slp.preview(url, onSuccess: { result in if let title = result[SwiftLinkResponseKey.title] as? String, let portal = result[SwiftLinkResponseKey.canonicalUrl] as? String { completion((title, portal), nil) } else { completion(nil, nil) } }) { error in completion(nil, error) } } }
true
00c298217e9d443e3d843e2c930d5c6c70b18f18
Swift
cgi4u/FacePDFViewer
/FacePDFViewer/Classes/FaceGestureRecognizer/Subclasses/LookPointRecognizer.swift
UTF-8
687
2.90625
3
[]
no_license
// // FaceGestureRecognizer.swift // FacePDFViewer // // Created by cgi on 21/05/2019. // Copyright © 2019 cgi. All rights reserved. // import Foundation import UIKit protocol LookPointRecognizerDelegate: class { func handleLookPoint(_ point: CGPoint) } class LookPointRecognizer: FaceGestureRecognizer { weak var delegate: LookPointRecognizerDelegate? override func handleFaceGestureData(_ data: FaceGestureData) { guard let delegate = delegate, let point = usesSmoothedPoint ? data.smoothedLookPoint : data.lookPoint else { return } DispatchQueue.main.async { delegate.handleLookPoint(point) } } }
true
040f72ee66102262883edab5343d0ae09713b204
Swift
scvalencia/MOOC
/TreeHouse/iOS/Swift_Basics/hello.swift
UTF-8
113
3.734375
4
[]
no_license
var name : String = "Sebastián" // Explicit type let message = "Hello \(name)." // Type inference print(message)
true
8f383014ee80dee6e642473168cb6a2d565cb113
Swift
ngocphu2810/ios-date-tools
/DateToolsTests/TimePeriodTests+DateShifting.swift
UTF-8
16,521
2.53125
3
[ "Apache-2.0" ]
permissive
// // TimePeriodTests+DateShifting.swift // DateTools // // Created by Paweł Sękara on 23.09.2015. // Copyright © 2015 CodeWise sp. z o.o. Sp. k. All rights reserved. // import Foundation import XCTest import Nimble @testable import DateTools extension TimePeriodTests { //MARK: - Date shifting methods func testTimePeriod_shiftEarlier_shiftsPeriodEarlier() { self.testShiftEarlier(shortPeriod, .Second, 3, date("1999-12-31 23:59:57")) self.testShiftEarlier(shortPeriod, .Minute, 73, date("1999-12-31 22:47")) self.testShiftEarlier(shortPeriod, .Hour, 122, date("1999-12-26 22")) self.testShiftEarlier(shortPeriod, .Day, 44, date("1999-11-18")) self.testShiftEarlier(shortPeriod, .Week, 1, date("1999-12-25")) self.testShiftEarlier(shortPeriod, .Month, 8, date("1999-05-01")) self.testShiftEarlier(shortPeriod, .Year, 1, date("1999-01-01")) } func testTimePeriod_shiftEarlierByNegativeAmount_shiftsPeriodLater() { self.testShiftEarlier(shortPeriod, .Second, -12, date("2000-01-01 00:00:12")) self.testShiftEarlier(shortPeriod, .Minute, -39, date("2000-01-01 00:39")) self.testShiftEarlier(shortPeriod, .Hour, -31, date("2000-01-02 07")) self.testShiftEarlier(shortPeriod, .Day, -43, date("2000-02-13")) self.testShiftEarlier(shortPeriod, .Week, -2, date("2000-01-15")) self.testShiftEarlier(shortPeriod, .Month, -14, date("2001-03-01")) self.testShiftEarlier(shortPeriod, .Year, -1, calendar.dateWithYear(2001)) } func testTimePeriod_shiftLater_shiftsPeriodLater() { self.testShiftLater(shortPeriod, .Second, 12, date("2000-01-01 00:00:12")) self.testShiftLater(shortPeriod, .Minute, 39, date("2000-01-01 00:39")) self.testShiftLater(shortPeriod, .Hour, 31, date("2000-01-02 07")) self.testShiftLater(shortPeriod, .Day, 43, date("2000-02-13")) self.testShiftLater(shortPeriod, .Week, 2, date("2000-01-15")) self.testShiftLater(shortPeriod, .Month, 14, date("2001-03-01")) self.testShiftLater(shortPeriod, .Year, 1, calendar.dateWithYear(2001)) } func testTimePeriod_shiftLaterByNegativeAmount_shiftsPeriodEarlier() { self.testShiftLater(shortPeriod, .Second, -3, date("1999-12-31 23:59:57")) self.testShiftLater(shortPeriod, .Minute, -73, date("1999-12-31 22:47")) self.testShiftLater(shortPeriod, .Hour, -122, date("1999-12-26 22")) self.testShiftLater(shortPeriod, .Day, -44, date("1999-11-18")) self.testShiftLater(shortPeriod, .Week, -1, date("1999-12-25")) self.testShiftLater(shortPeriod, .Month, -8, date("1999-05-01")) self.testShiftLater(shortPeriod, .Year, -1, date("1999-01-01")) } //MARK: - lengthen with anchor Start func testTimePeriod_lengthenWithStartAnchorBySeconds_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Second, amount: 39) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-14 00:00:39") } func testTimePeriod_lengthenWithStartAnchorByMinutes_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Minute, amount: 41) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-14 00:41") } func testTimePeriod_lengthenWithStartAnchorByHours_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Hour, amount: 5) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-14 05") } func testTimePeriod_lengthenWithStartAnchorByDays_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Day, amount: 5) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-19") } func testTimePeriod_lengthenWithStartAnchorByWeeks_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Week, amount: 2) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-28") } func testTimePeriod_lengthenWithStartAnchorByMonths_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Month, amount: 4) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-07-14") } func testTimePeriod_lengthenWithStartAnchorByYears_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Start, size: .Year, amount: 7) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2007-03-14") } //MARK: lengthen with anchor Center func testTimePeriod_lengthenWithCenterAnchorBySeconds_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Second, amount: 40) expect(self.shortPeriod.startDate) == date("1999-12-31 23:59:40") expect(self.shortPeriod.endDate) == date("2000-03-14 00:00:20") } func testTimePeriod_lengthenWithCenterAnchorByMinutes_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Minute, amount: 30) expect(self.shortPeriod.startDate) == date("1999-12-31 23:45") expect(self.shortPeriod.endDate) == date("2000-03-14 00:15") } func testTimePeriod_lengthenWithCenterAnchorByHours_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Hour, amount: 6) expect(self.shortPeriod.startDate) == date("1999-12-31 21") expect(self.shortPeriod.endDate) == date("2000-03-14 03") } func testTimePeriod_lengthenWithCenterAnchorByDays_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Day, amount: 4) expect(self.shortPeriod.startDate) == date("1999-12-30") expect(self.shortPeriod.endDate) == date("2000-03-16") } func testTimePeriod_lengthenWithCenterAnchorByWeeks_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Week, amount: 2) expect(self.shortPeriod.startDate) == date("1999-12-25") expect(self.shortPeriod.endDate) == date("2000-03-21") } func testTimePeriod_lengthenWithCenterAnchorByMonths_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Month, amount: 4) expect(self.shortPeriod.startDate) == date("1999-11-01") expect(self.shortPeriod.endDate) == date("2000-05-14") } func testTimePeriod_lengthenWithCenterAnchorByYears_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.Center, size: .Year, amount: 8) expect(self.shortPeriod.startDate) == calendar.dateWithYear(1996) expect(self.shortPeriod.endDate) == date("2004-03-14") } //MARK: lengthen with anchor end func testTimePeriod_lengthenWithEndAnchorBySeconds_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Second, amount: 40) expect(self.shortPeriod.startDate) == date("1999-12-31 23:59:20") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_lengthenWithEndAnchorByMinutes_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Minute, amount: 30) expect(self.shortPeriod.startDate) == date("1999-12-31 23:30:00") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_lengthenWithEndAnchorByHours_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Hour, amount: 6) expect(self.shortPeriod.startDate) == date("1999-12-31 18") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_lengthenWithEndAnchorByDays_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Day, amount: 4) expect(self.shortPeriod.startDate) == date("1999-12-28") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_lengthenWithEndAnchorByWeeks_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Week, amount: 2) expect(self.shortPeriod.startDate) == date("1999-12-18") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_lengthenWithEndAnchorByMonths_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Month, amount: 4) expect(self.shortPeriod.startDate) == date("1999-09-01") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_lengthenWithEndAnchorByYears_lengthensPeriodByGivenSize() { self.shortPeriod.lengthenWithAnchorDate(.End, size: .Year, amount: 8) expect(self.shortPeriod.startDate) == calendar.dateWithYear(1992) expect(self.shortPeriod.endDate) == date("2000-03-14") } //MARK: - shorten with anchor start func testTimePeriod_shortenWithStartAnchorBySeconds_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Second, amount: 39) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-13 23:59:21") } func testTimePeriod_shortenWithStartAnchorByMinutes_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Minute, amount: 41) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-13 23:19") } func testTimePeriod_shortenWithStartAnchorByHours_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Hour, amount: 5) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-13 19") } func testTimePeriod_shortenWithStartAnchorByDays_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Day, amount: 5) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-03-09") } func testTimePeriod_shortenWithStartAnchorByWeeks_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Week, amount: 2) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("2000-02-29") } func testTimePeriod_shortenWithStartAnchorByMonths_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Month, amount: 4) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("1999-11-14") } func testTimePeriod_shortenWithStartAnchorByYears_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Start, size: .Year, amount: 7) expect(self.shortPeriod.startDate) == startDate expect(self.shortPeriod.endDate) == date("1993-03-14") } //MARK: shorten with anchor center func testTimePeriod_shortenWithCenterAnchorBySeconds_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Center, size: .Second, amount: 40) expect(self.shortPeriod.startDate) == date("2000-01-01 00:00:20") expect(self.shortPeriod.endDate) == date("2000-03-13 23:59:40") } func testTimePeriod_shortenWithCenterAnchorByMinutes_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Center, size: .Minute, amount: 30) expect(self.shortPeriod.startDate) == date("2000-01-01 00:15") expect(self.shortPeriod.endDate) == date("2000-03-13 23:45") } func testTimePeriod_shortenWithCenterAnchorByHours_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Center, size: .Hour, amount: 6) expect(self.shortPeriod.startDate) == date("2000-01-01 03") expect(self.shortPeriod.endDate) == date("2000-03-13 21") } func testTimePeriod_shortenWithCenterAnchorByDays_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Center, size: .Day, amount: 4) expect(self.shortPeriod.startDate) == date("2000-01-03") expect(self.shortPeriod.endDate) == date("2000-03-12") } func testTimePeriod_shortenWithCenterAnchorByWeeks_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.Center, size: .Week, amount: 2) expect(self.shortPeriod.startDate) == date("2000-01-08") expect(self.shortPeriod.endDate) == date("2000-03-07") } func testTimePeriod_shortenWithCenterAnchorByMonths_shortensPeriodByGivenSize() { self.longPeriod.shortenWithAnchorDate(.Center, size: .Month, amount: 4) expect(self.longPeriod.startDate) == date("1900-08-15") expect(self.longPeriod.endDate) == date("1999-11-01") } func testTimePeriod_shortenWithCenterAnchorByYears_shortensPeriodByGivenSize() { self.longPeriod.shortenWithAnchorDate(.Center, size: .Year, amount: 8) expect(self.longPeriod.startDate) == date("1904-06-15") expect(self.longPeriod.endDate) == date("1996-01-01") } //MARK: shorten with anchor end func testTimePeriod_shortenWithEndAnchorBySeconds_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Second, amount: 40) expect(self.shortPeriod.startDate) == date("2000-01-01 00:00:40") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_shortenWithEndAnchorByMinutes_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Minute, amount: 30) expect(self.shortPeriod.startDate) == date("2000-01-01 00:30") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_shortenWithEndAnchorByHours_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Hour, amount: 6) expect(self.shortPeriod.startDate) == date("2000-01-01 06") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_shortenWithEndAnchorByDays_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Day, amount: 4) expect(self.shortPeriod.startDate) == date("2000-01-05") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_shortenWithEndAnchorByWeeks_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Week, amount: 2) expect(self.shortPeriod.startDate) == date("2000-01-15") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_shortenWithEndAnchorByMonths_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Month, amount: 4) expect(self.shortPeriod.startDate) == date("2000-05-01") expect(self.shortPeriod.endDate) == date("2000-03-14") } func testTimePeriod_shortenWithEndAnchorByYears_shortensPeriodByGivenSize() { self.shortPeriod.shortenWithAnchorDate(.End, size: .Year, amount: 8) expect(self.shortPeriod.startDate) == calendar.dateWithYear(2008) expect(self.shortPeriod.endDate) == date("2000-03-14") } //MARK: - Helpers func testShiftEarlier(var period: TimePeriod, _ size: TimePeriodSize, _ amount: Int, _ startDate: NSDate) { period = period.copy() as! TimePeriod period.shiftEarlierWithSize(size, amount: amount) expect(period.startDate) == startDate } func testShiftLater(var period: TimePeriod, _ size: TimePeriodSize, _ amount: Int, _ startDate: NSDate) { period = period.copy() as! TimePeriod period.shiftLaterWithSize(size, amount: amount) expect(period.startDate) == startDate } }
true
16d0487778f33500a2f85cb5670321b787c67695
Swift
martinprot/MPModelKit
/MPModelKit/Classes/Services/BackendService.swift
UTF-8
5,930
2.640625
3
[ "MIT" ]
permissive
// // BackendService.swift // MPModelKit // // Created by Martin Prot on 12/01/2017. // Copyright © 2017 appricot media. All rights reserved. // import Foundation public final class BackendConfiguration { public let baseURL: URL? var apiAuthenticator: BackendAPIAuth? public init() { self.baseURL = .none } public init(baseURL: URL) { self.baseURL = baseURL } convenience public init(baseURL: URL, apiAuth: BackendAPIAuth) { self.init(baseURL: baseURL) self.apiAuthenticator = apiAuth } public func setAsDefault() { BackendConfiguration.shared = self } static var shared = BackendConfiguration() } public class BackendService { /// the backend configuration private let configuration: BackendConfiguration /// the service to connect private let service: NetworkService = NetworkService() public init() { self.configuration = BackendConfiguration() } public init(configuration: BackendConfiguration) { self.configuration = configuration } public func fetch(request: BackendAPIRequest, success: @escaping (Any) -> Void, failure: (([String: Any]?, NetworkServiceError, Int) -> Void)? = nil) { // Configure URL let serviceURL: URL? if request.endpoint.starts(with: "http") { serviceURL = URL(string: request.endpoint) } else if let baseURL = configuration.baseURL { serviceURL = baseURL.appendingPathComponent(request.endpoint) } else { serviceURL = URL(string: "http://" + request.endpoint) } guard let url = serviceURL else { failure?(.none, .wrongURL, 0) return } let completeUrl: URL let body: Data? // Configure parameters if let parameters = request.parameters { switch request.bodyType { case .formData: // creating the query string let getParameters = parameters.map() { (key, value) -> String in if let array = value as? [Any] { // for arrays, the string should be for example: // order[]=intl_title&order[]=publication let values = array.map() { "\(key)[]=\($0)" } return values.joined(separator: "&") } else { return "\(key)=\(value)" } } let queryString = getParameters.joined(separator: "&") switch request.method { case .GET, .DELETE: // including GET parameters directly in URL var components = URLComponents(url: url, resolvingAgainstBaseURL: true) components?.query = queryString completeUrl = components?.url ?? url body = .none case .POST, .PUT: // including parameters in body, as x-www-form-urlencoded completeUrl = url body = queryString.data(using: String.Encoding.utf8) } case .rawJson: completeUrl = url body = try? JSONSerialization.data(withJSONObject: request.parameters ?? [:], options: []) } } else { completeUrl = url body = .none } // Configure headers var headers = request.headers if let authHeaders = configuration.apiAuthenticator?.authenticationHeader(withUrl: completeUrl, body: body) { // adds auth headers into headers authHeaders.forEach { _ = headers?.updateValue($1, forKey: $0) } } service.request(url: completeUrl, method: request.method, body: body, headers: headers, success: { data in switch request { // The request was asking a Data object (such as an image) case _ as BackendAPIDataRequest: guard let returnedData = data else { DispatchQueue.main.async { failure?(.none, .unreadableResponse, 0) } return } DispatchQueue.main.async { success(returnedData) } // The request was asking a String object (such as HTML string) case _ as BackendAPIHTMLRequest: guard let returnedData = data, let htmlString = String.init(data: returnedData, encoding: .utf8) else { DispatchQueue.main.async { failure?(.none, .unreadableResponse, 0) } return } DispatchQueue.main.async { success(htmlString) } // The request was asking a [String: Any] object case let objectRequest as BackendAPIObjectRequest: var json: Any? = .none if let data = data { json = try? JSONSerialization.jsonObject(with: data, options: []) } guard let dic = json as? [String: Any] else { DispatchQueue.main.async { failure?(.none, .unreadableResponse, 0) } return } if let objectKey = objectRequest.objectKey { guard let objectDic: Any = dic.key(objectKey) else { DispatchQueue.main.async { failure?(.none, .unreadableResponse, 0) } return } DispatchQueue.main.async { success(objectDic) } } else { DispatchQueue.main.async { success(dic) } } default: DispatchQueue.main.async { failure?(.none, .unreadableResponse, 0) } } }, failure: { data, error, statusCode in var json: Any? = .none if let data = data { json = try? JSONSerialization.jsonObject(with: data, options: []) } DispatchQueue.main.async { failure?(json as? [String: Any], error, statusCode) } }) } public func cancel() { service.cancel() } } /// BackendAPIAuth is used to sign the request and send the result of the signature un headers /// BackendAPIAuth can handle a OAuth bearer public protocol BackendAPIAuth { func authenticationHeader(withUrl url: URL) -> [String: String] func authenticationHeader(withUrl url: URL, body postData: Data?) -> [String: String] } public struct OAuthBearerAPIAuth: BackendAPIAuth { let token: String public init(token: String) { self.token = token } public func authenticationHeader(withUrl url: URL) -> [String: String] { ["Authorization": "Bearer \(token)"] } public func authenticationHeader(withUrl url: URL, body postData: Data?) -> [String: String] { authenticationHeader(withUrl: url) } }
true
634ec6044e726ee5465950e88d910c4eccedaa31
Swift
cezarywojcik/Operations
/Sources/Core/Shared/NoFailedDependenciesCondition.swift
UTF-8
2,604
3.125
3
[ "MIT" ]
permissive
// // NoFailedDependenciesCondition.swift // Operations // // Created by Daniel Thorpe on 27/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation /** A condition that specificed that every dependency of the operation must succeed. If any dependency fails/cancels, the target operation will be fail. */ open class NoFailedDependenciesCondition: Condition { /// The `ErrorType` returned to indicate the condition failed. public enum ErrorType: Error, Equatable { /// When some dependencies were cancelled case cancelledDependencies /// When some dependencies failed with errors case failedDependencies } /// Initializer which takes no parameters. public override init() { super.init() name = "No Cancelled Condition" mutuallyExclusive = false } /** Evaluates the operation with respect to the finished status of its dependencies. The condition first checks if any dependencies were cancelled, in which case it fails with an `NoFailedDependenciesCondition.Error.CancelledDependencies`. Then it checks to see if any dependencies failed due to errors, in which case it fails with an `NoFailedDependenciesCondition.Error.FailedDependencies`. The cancelled or failed operations are no associated with the error. - parameter operation: the `Operation` which the condition is attached to. - parameter completion: the completion block which receives a `OperationConditionResult`. */ open override func evaluate(_ operation: AdvancedOperation, completion: @escaping CompletionBlockType) { let dependencies = operation.dependencies let cancelled = dependencies.filter { $0.isCancelled } let failures = dependencies.filter { if let operation = $0 as? AdvancedOperation { return operation.failed } return false } if !cancelled.isEmpty { completion(.failed(ErrorType.cancelledDependencies)) } else if !failures.isEmpty { completion(.failed(ErrorType.failedDependencies)) } else { completion(.satisfied) } } } /// Equatable conformance for `NoFailedDependenciesCondition.Error` public func == (lhs: NoFailedDependenciesCondition.ErrorType, rhs: NoFailedDependenciesCondition.ErrorType) -> Bool { switch (lhs, rhs) { case (.cancelledDependencies, .cancelledDependencies), (.failedDependencies, .failedDependencies): return true default: return false } }
true
6e3882c088f806fca3159fcc6edc14ab2a206990
Swift
DlifeProject/DlifeProjectIOS
/DLife/Page1/DiaryView.swift
UTF-8
763
2.6875
3
[]
no_license
// // DiaryView.swift // D.Life // // Created by Allen on 2018/3/16. // Copyright © 2018年 康晉嘉. All rights reserved. // import Foundation import UIKit class DiaryView{ var date:String = "" var starttime:String = "" var endtime:String = "" var place:String var note:String = "" var photoImage:UIImage? static var all = [Diary]() init(date:String,starttime:String,endtime:String,place:String,note:String,photoImage:UIImage) { self.date = date self.starttime = starttime self.endtime = endtime self.place = place self.note = note self.photoImage = photoImage } init(place:String) { self.place = place } static func add(diary:Diary) { all.append(diary) } static func remove(at index:Int) { all.remove(at:index) } }
true
3e9b4a9846a1d3bcf033336519b960a6ba9849c5
Swift
iwufan/SocketClientDemo
/SocketDemo-Client/SocketDemo/Custom/Extensions/String+Extension.swift
UTF-8
2,049
3.15625
3
[ "MIT" ]
permissive
// // String+Extension.swift // MusicWorld // // Created by David Jia on 24/8/2017. // Copyright © 2017 David Jia. All rights reserved. // import UIKit // MARK - attribute string extension String { func attributedString(rangeArray: Array<Dictionary<String, Any>>, fontArray: Array<UIFont>, colorArray: Array<UIColor>, lineSpacing: CGFloat = 0) -> NSMutableAttributedString { // 如果range数组为空,直接返回自己 if rangeArray.count == 0 { return NSMutableAttributedString(string: self) } // 如果数组元素个数不一致,直接把返回自己 if (rangeArray.count != fontArray.count) || (rangeArray.count != colorArray.count) { return NSMutableAttributedString(string: self) } // 带属性字符串 let attrContent = NSMutableAttributedString(string: self) for index in 0..<rangeArray.count { // 获取range let dict = rangeArray[index]; let location:String = dict[MW_RANGE_LOCATION] as! String; let length:String = dict[MW_RANGE_LENGTH] as! String; // range let range = NSMakeRange(Int(location)!, Int(length)!); // 字体大小 attrContent.addAttribute(NSAttributedStringKey.font, value: fontArray[index], range: range) // 字体颜色 attrContent.addAttribute(NSAttributedStringKey.foregroundColor, value: colorArray[index], range: range) } // 内容行间距 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpacing; attrContent.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, self.characters.count)) return attrContent; } /// 获取字符串长度 /// /// - Returns: 长度 func length() -> Int { return characters.count } }
true
e8fbee26e586e40b54f6b1dc6e432199fa1903ac
Swift
Mackellen/interviewDemo
/interviewDemo/ApiNetwork/ApiManager.swift
UTF-8
4,321
2.953125
3
[]
no_license
// // ApiManager.swift // interviewDemo // // Created by Mackellen on 2020/9/24. // Copyright © 2020 mackellen. All rights reserved. // import UIKit import Alamofire import RxCocoa import RxSwift import SwiftyJSON enum baseURLPath:String{ case test = "https://test.github.com/" case sit = "https://sit.github.com/" case uat = "https://uat.github.com/" case pre = "https://wanandroid.com/" case online = "https://api.github.com/" } struct ResponseData<T: Decodable>: Decodable { var data: T? } class ApiManager: NSObject { static let shared = ApiManager() var URLPath = baseURLPath.online var headers: HTTPHeaders { return ["Content-Type": "text/plain"] } func apiBaseURL(path:String) -> String { let baseURLString = URLPath.rawValue+path let newURL = baseURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let urlRequest = URLRequest(url: URL(string: newURL)!) let urlString = urlRequest.url?.absoluteString return urlString! } // MARK: Get Method public func get(url: String, parameter: [String: Any]?) -> Observable<[String: Any]> { return Observable<[String: Any]>.create { [weak self] (observer) -> Disposable in let allURL = self?.apiBaseURL(path: url) Alamofire.request(allURL!, method: .get,parameters: parameter,encoding: URLEncoding.default,headers: self?.headers) .responseJSON { (respose) in switch respose.result { case .success(let vaue): let responseDiction = JSON(vaue).dictionaryObject observer.onNext(responseDiction!) observer.onCompleted() #if DEBUG print("Get:链接-->\(allURL ?? "")\n参数-->\(String(describing: parameter))\n返回值-->\(vaue)\n\r"); #endif case .failure(let error): #if DEBUG print("Get:链接-->\(allURL ?? "")\n参数-->\(String(describing: parameter))\n返回值-->\(error)\n\r"); #endif observer.onError(error) } } return Disposables.create() } } // MARK: Post Method public func post(url: String, parameter: [String: Any]?) -> Observable<[String: Any]> { return Observable<[String: Any]>.create {[weak self] (observer) -> Disposable in let allURL = self?.apiBaseURL(path: url) Alamofire.request(allURL!, method: .post,parameters: parameter,encoding: URLEncoding.default,headers: self?.headers) .responseJSON { (respose) in switch respose.result { case .success(let value): let responseDiction = JSON(value).dictionaryObject observer.onNext(responseDiction!) observer.onCompleted() #if DEBUG print("Post:链接-->\(allURL ?? "")\n参数-->\(String(describing: parameter))\n返回值-->\(value)\n\r"); #endif case .failure(let error): #if DEBUG print("Post:链接-->\(allURL ?? "")\n参数-->\(String(describing: parameter))\n返回值-->\(error)\n\r"); #endif observer.onError(error) } } return Disposables.create() } } } extension ApiManager { class func requestData(type: String?, path:String?, params:[String: Any]?) -> Observable<[String: Any]> { if type?.lowercased() == "get" { return ApiManager.shared.get(url: path ?? "", parameter: params) }else{ return ApiManager.shared.post(url: path ?? "", parameter: params) } } }
true
8c8b8a51f534a37d02f5a03b66f821d03d6f1d9f
Swift
Bhron/LeetCode
/Algorithms/Swift/Easy/6_ZigZag_Conversion.swift
UTF-8
663
3.390625
3
[]
no_license
class Solution { func convert(s: String, _ numRows: Int) -> String { if s.isEmpty || numRows <= 1 { return s } var result = "" var rows = [String](count: numRows, repeatedValue: "") let cycle = numRows + numRows - 2 for (index, character) in s.characters.enumerate() { let rowIndex = index % cycle if rowIndex < numRows { rows[rowIndex] += String(character) } else { rows[cycle - rowIndex] += String(character) } } for row in rows { result += row } return result } }
true
3bf4508071af482a1a837d637b6d30dfbcbdaf3c
Swift
codecat15/Youtube-tutorial
/SwiftArrayFunctions/SimpleFunctionDemo/SimpleFunctionDemo/Solution.swift
UTF-8
1,187
3.609375
4
[]
no_license
// // Solution.swift // SimpleFunctionDemo // // Created by CodeCat15 on 11/24/22. // import Foundation class Solution { // MARK: allSatisfy func collectionIsDivisibleBy2(arr: Array<Int>) -> Bool { guard !arr.isEmpty else { return false } return arr.allSatisfy({$0 % 2 == 0}) } // MARK: max func findTheLargestNumber(from arr: Array<Int>) -> Int { guard !arr.isEmpty else { return 0 } return arr.max() ?? 0 } // MARK: min func findTheSmallestNumber(from arr: Array<Int>) -> Int { guard !arr.isEmpty else { return 0 } return arr.min() ?? 0 } /** Input: [1,2,3,4,5] Output: 15 */ // MARK: Reduce func getArraySum(arr: Array<Int>) -> Int { guard !arr.isEmpty else { return 0 } return arr.reduce(0, {$0 + $1}) } func doesContain(elementWithName name: String, inCollection names: Array<String>) -> Bool { guard !names.isEmpty else { return false } return names.contains(where: {$0.caseInsensitiveCompare(name) == .orderedSame}) } }
true
61f044ff3ca1363ced4668a8af2c94547da44ac3
Swift
MaxDevelopeer/NetworkLayer
/NetworkLayer/Network/Multipart/MultipartBoundary.swift
UTF-8
484
2.65625
3
[]
no_license
// // MultipartBoundary.swift // NetworkLayer // // Created by Maxim on 01/02/2020. // Copyright © 2020 maxim.kruchinin@firstlinesoftware.com. All rights reserved. // import Foundation public struct MultipartBoundary { private let uuid = UUID() var boundaryString: String { return "Boundary-\(uuid.uuidString)" } var delimiter: String { return "--\(boundaryString)" } var endDelimiter: String { return "--\(boundaryString)--" } }
true
6da8b3b23cec53f4dd3597bd769673b16b6b966d
Swift
morenm14/ITDEV-184
/Moreno_InjuryTrackerApp/Moreno_FinalProjectApp/LoginViewController.swift
UTF-8
1,666
2.6875
3
[]
no_license
// // ViewController.swift // // Created by Mario Moreno on 3/25/21. // import UIKit class LoginViewController: UIViewController { let authUser = "Mario" let authPassword = "myapp" @IBOutlet var loginButton: UIButton! @IBOutlet var username: UITextField! @IBOutlet var password: UITextField! override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard(){ view.endEditing(true) } @IBAction func login(_ sender: UIButton) { if username.text != authUser || password.text != authPassword{ let alert = UIAlertController(title: "No Match", message: "invalid username or password. Try again", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) username.text = "" password.text = "" } else if username.text == authUser && password.text == authPassword{ // if let vc = storyboard?.instantiateViewController(identifier: "PatientsScreen") as? PatientsScreen{ // navigationController?.pushViewController(vc, animated: true) // } } username.text = "" password.text = "" } @IBAction func logout(segue: UIStoryboardSegue) { } }
true
95bc5f819d575dedceb7a6bd8ae30897f070b342
Swift
preema22/RTLNews
/RTLNews/Binding/Dynamic.swift
UTF-8
1,196
3.5
4
[]
no_license
// // Dynamic.swift // RTLNews // // Created by Preema DSouza on 16/10/2020. // Copyright © 2020 Preema DSouza. All rights reserved. // import Foundation /// This type should be used for view model variables. It realizes a one direction binding. public class Dynamic<T> { public typealias Listener = (T) -> Void fileprivate var listener: Listener? /// Wrapped value public var value: T { didSet { listener?(value) } } public init(_ value: T) { self.value = value } public func notifyListener() { listener?(value) } /** Bind value with passed function. - parameter listener: Function which is invoked everytime the value changes */ public func bind(listener: @escaping Listener) { self.listener = listener } /** Binds value with passed function and invokes function. - parameter listener: Function which is invoked everytime the value changes */ public func bindAndFire(listener: @escaping Listener) { self.listener = listener listener(value) } public func removeListener() { listener = nil } }
true
7ac165c7d31d8fc10e007c33348754067de63ff1
Swift
yoshimasa36g/DelaunayTriangulationAndMinimumSpanningTree
/DelaunayTriangulationAndMinimumSpanningTreeTests/DelaunayTriangulation/CGPointTests.swift
UTF-8
1,646
2.828125
3
[]
no_license
// // CGPointTests.swift // DelaunayTriangulationAndMinimumSpanningTree // // Created by Yoshimasa Aoki on 2016/12/27. // Copyright © 2016年 yoshimasa36g. All rights reserved. // import XCTest @testable import DelaunayTriangulationAndMinimumSpanningTree class CGPointTests: XCTestCase { func testDistance() { let samples = [ (p1: CGPoint(x: 0, y: 0), p2: CGPoint(x: 3, y: 4), expected: CGFloat(5)), (p1: CGPoint(x: 3, y: 1), p2: CGPoint(x: 9, y: 9), expected: CGFloat(10)), (p1: CGPoint(x: -20, y: -8), p2: CGPoint(x: -15, y: 4), expected: CGFloat(13)) ] samples.forEach { let actual = $0.p1.distance(from: $0.p2) XCTAssertEqual(actual, $0.expected) } } func testSumOfSquares() { let samples = [ (point: CGPoint(x: 1, y: 2), expected: CGFloat(5)), (point: CGPoint(x: 0, y: 0), expected: CGFloat(0)), (point: CGPoint(x: -8, y: 6), expected: CGFloat(100)) ] samples.forEach { let actual = $0.point.sumOfSquares() XCTAssertEqual(actual, $0.expected) } } func testSubtractOperator() { let samples = [ (p1: CGPoint(x: 3, y: 4), p2: CGPoint(x: 0, y: 0), expected: CGPoint(x: 3, y: 4)), (p1: CGPoint(x: 3, y: 1), p2: CGPoint(x: 9, y: 9), expected: CGPoint(x: -6, y: -8)), (p1: CGPoint(x: -2, y: -8), p2: CGPoint(x: -5, y: 4), expected: CGPoint(x: 3, y: -12)) ] samples.forEach { let actual = $0.p1 - $0.p2 XCTAssertEqual(actual, $0.expected) } } }
true
d1677830351ef5c466c348afd4a5c9eb0bfe6f4a
Swift
ridwanc12/paradigm
/Paradigm/ViewControllers/ProfileTableViewController.swift
UTF-8
11,744
2.671875
3
[]
no_license
// // ProfileTableViewController.swift // Paradigm // // Created by Isha Mahadalkar on 2/16/21. // Copyright © 2021 team5. All rights reserved. // import UIKit class ProfileTableViewController: UITableViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBAction func updateButtonTapped(_ sender: UIButton) { // When the update button is tapped let firstname: String = firstNameTextField.text ?? "" let lastname: String = lastNameTextField.text ?? "" let email: String = emailTextField.text ?? "" let userID = Utils.global_userID // let semaphore = DispatchSemaphore (value: 0) let _ = DispatchSemaphore (value: 0) if (firstname == "" || lastname == "" || email == "") { let alert = UIAlertController(title: "Empty Field", message: "Please enter all the fields.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } else if (!isValidEmail(email: email)) { let alert = UIAlertController(title: "Invalid Email", message: "Please make sure to provide a valid email address.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } else { //all fields meet needed criteria if (email != Utils.global_email) { let changeEmailAlert = UIAlertController(title: "Update Email", message: "Are you sure you want to update your email?", preferredStyle: .alert) changeEmailAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in print("User confirms updating email.") //update email let ret = self.databaseRequestEditUser(userID: userID, first: firstname, last: lastname, email: email) print("RET VALUE: " + ret) if (ret.contains("account edited")) { //successfully edited info Utils.global_firstName = firstname UserDefaults.standard.set(firstname, forKey: "firstName") Utils.global_lastName = lastname UserDefaults.standard.set(lastname, forKey: "lastName") Utils.global_email = email UserDefaults.standard.set(email, forKey: "email") let alert = UIAlertController(title: "Success!", message: "Your account information has been updated.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } else if (ret == "Email already registered.") { //user tried to update email to one already in use let alert = UIAlertController(title: "Email Already In Use", message: "This email is already associated with an account. Please use a different one.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } else { //handle all other return values which equate to errors let alert = UIAlertController(title: "Oops!", message: "Something went wrong on our end. Please try again.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } })) changeEmailAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in print("User cancels updating email.") //do nothing })) self.present(changeEmailAlert, animated: true, completion: nil) } else { //email not being changed let ret = databaseRequestEditUser(userID: userID, first: firstname, last: lastname, email: email) print("RET VALUE: " + ret) if (ret == "account edited.") { //successfully edited info Utils.global_firstName = firstname UserDefaults.standard.set(firstname, forKey: "firstName") Utils.global_lastName = lastname UserDefaults.standard.set(lastname, forKey: "lastName") Utils.global_email = email UserDefaults.standard.set(email, forKey: "email") let alert = UIAlertController(title: "Success!", message: "Your account information has been updated.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) // Updating the title label titleLabel.text = Utils.global_firstName + " " + Utils.global_lastName } else if (ret == "Email already registered.") { //user tried to update email to one already in use let alert = UIAlertController(title: "Email Already In Use", message: "This email is already associated with an account. Please use a different one.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } else { //handle all other return values which equate to errors let alert = UIAlertController(title: "Oops!", message: "Something went wrong on our end. Please try again.", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } } } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem // let editButton = UIBarButtonItem(title: "Edit", style: UIBarButtonItem.Style.plain, target: self, action: Selector(("editProfile:"))) // self.navigationItem.rightBarButtonItem = editButton //filling in user's data firstNameTextField.text = Utils.global_firstName lastNameTextField.text = Utils.global_lastName emailTextField.text = Utils.global_email // Updating the title label titleLabel.text = Utils.global_firstName + " " + Utils.global_lastName } func editProfile(sender: UIBarButtonItem) { // Perform your custom actions print("Function called") } func isValidEmail(email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } func databaseRequestEditUser(userID: String, first: String, last: String, email: String) -> String { let semaphore = DispatchSemaphore (value: 0) var ret = ""; let link = "https://boilerbite.000webhostapp.com/paradigm/editUser.php" let request = NSMutableURLRequest(url: NSURL(string: link)! as URL) request.httpMethod = "POST" let postString = "userID=\(userID)&email=\(email)&firstName=\(first)&lastName=\(last)" request.httpBody = postString.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in if error != nil { print("ERROR") print(String(describing: error!)) ret = "ERROR" semaphore.signal() return } print("PRINTING DATA") let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) ret = String(describing: responseString!) semaphore.signal() print(ret) } task.resume() semaphore.wait() return ret } // MARK: - Table view data source /* override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } */ /* override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } */ /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return UITableViewCell.EditingStyle.none } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
33ff65592b95f735dbfa46a87f1ddaa1a27a70cb
Swift
SDOSLabs/UnidadEditorialItunes
/src/main/common/models/mapper/ArtistMapper.swift
UTF-8
431
2.515625
3
[]
no_license
// // ArtistMapper.swift // // Created by Rafael Fernandez Alvarez on 12/06/2019. // Archivo creado usando la plantilla VIPER por SDOS http://www.sdos.es/ // import UIKit extension ArtistDTO { func toBO() -> ArtistBO { return ArtistBO(dto: self) } } extension ArtistBO { init(dto item: ArtistDTO) { artistId = item.artistId artistName = item.artistName primaryGenreName = item.primaryGenreName } }
true
e109fdffbbf4da8107e33664772ef3f5f4899cba
Swift
TomRitchey/Qpony_zadanie
/Qpony_Zadanie/ButtonStateS.swift
UTF-8
1,850
3.484375
3
[]
no_license
// // ButtonState.swift // Qpony_Zadanie // // Created by Kacper Augustyniak on 05/06/16. // Copyright © 2016 Kacper Augustyniak. All rights reserved. // import Foundation import UIKit protocol ButtonStateProtocol { func returnColor() -> UIColor func returnText() -> String } class ButtonStateDefault: ButtonStateProtocol { var color:UIColor = UIColor.whiteColor() var text:String = "Default State" func returnColor() -> UIColor { return self.color } func returnText() -> String { return self.text } } //MARK: Button states enum ButtonStatesEnum { case StateOne, StateTwo, StateThree, StateFour, StateFive, StateDefault static func getState(state:ButtonStatesEnum) -> ButtonStateDefault { switch state { case .StateOne: return ButtonStateFirst() case .StateTwo: return ButtonStateSecond() case .StateThree: return ButtonStateThird() case .StateFour: return ButtonStateFourth() case .StateFive: return ButtonStateFifth() default: return ButtonStateDefault() } } } class ButtonStateFirst: ButtonStateDefault { override init() { super.init() self.color = UIColor.greenColor() self.text = "First State" } } class ButtonStateSecond: ButtonStateDefault { override init() { super.init() self.color = UIColor.yellowColor() self.text = "Second State" } } class ButtonStateThird: ButtonStateDefault { override init() { super.init() self.color = UIColor.brownColor() self.text = "Third State" } } class ButtonStateFourth: ButtonStateDefault { override init() { super.init() self.color = UIColor.redColor() self.text = "Fourth State" } } class ButtonStateFifth: ButtonStateDefault { override init() { super.init() self.color = UIColor.orangeColor() self.text = "Fifth State" } }
true
350f98ac5a0491750dd04f3e414b18fc60bcc9a4
Swift
Joule87/ItemFinder
/ItemFinder/Model/Item/Item.swift
UTF-8
711
2.984375
3
[]
no_license
// // Item.swift // ItemFinder // // Created by Julio Collado on 11/9/19. // Copyright © 2019 Julio Collado. All rights reserved. // import Foundation class Item { var id: String var title: String var price: Int var currency: String var available_quantity: Int var thumbnail: String var condition: String init(id: String, title: String, price: Int, currency: String, available_quantity: Int, thumbnail: String, condition: String) { self.id = id self.title = title self.price = price self.currency = currency self.available_quantity = available_quantity self.thumbnail = thumbnail self.condition = condition } }
true
33cee8b944de450ebf2ec76905dbd20440a65690
Swift
HDLuckySlevin/Corona-App-1
/Corona-App/EndangeredViewController.swift
UTF-8
3,114
2.765625
3
[]
no_license
// // EndangeredViewController.swift // Corona-App // // Created by BB1151 on 14.06.20. // Copyright © 2020 BB1151. All rights reserved. // import UIKit protocol ChangeVCDelegate1 { // functions of data } class EndangeredViewController: UIViewController, ChangeToStationNavControllerDelegate, ChangeTabBarVCDelegate{ @IBOutlet weak var endangeredLabel: UILabel! @IBOutlet weak var informationLabel: UILabel! @IBOutlet weak var skipButtonLabel: UIButton! var delegate1: ChangeVCDelegate1? override func viewDidLoad() { super.viewDidLoad() setupLabel() setupSkipButtonLabel() if #available(iOS 13.0, *) { // Always adopt a light interface style. overrideUserInterfaceStyle = .light } } func setupLabel() { // endangered Label let text1: String = "Sie sind gefährdet!" endangeredLabel.text = text1 endangeredLabel.lineBreakMode = NSLineBreakMode.byWordWrapping endangeredLabel.numberOfLines = 0 let yourAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.darkGray, .font: UIFont(name: "Raleway-Medium", size: 26) as Any] let attributeString = NSAttributedString(string: text1, attributes: yourAttributes) endangeredLabel.attributedText = attributeString // information Label let text2: String = "Kontaktieren Sie telefonisch einen Arzt oder begeben Sie sich zu einem Arzt in Ihrer Nähe!\n\nTragen Sie stets eine Maske und achten Sie darauf den Sicherheitsabstand einzuhalten." informationLabel.text = text2 informationLabel.lineBreakMode = NSLineBreakMode.byWordWrapping informationLabel.numberOfLines = 0 let yourAttributes2: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.darkGray, .font: UIFont(name: "Raleway-Medium", size: 15) as Any] let attributeString2 = NSAttributedString(string: text2, attributes: yourAttributes2) informationLabel.attributedText = attributeString2 } func setupSkipButtonLabel() { let yourAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.systemRed, .font: UIFont(name: "Raleway-Medium", size: 18) as Any, .underlineStyle: NSUnderlineStyle.single.rawValue] let attributeString = NSMutableAttributedString(string: "Ärzte in der Nähe finden", attributes: yourAttributes) skipButtonLabel.setAttributedTitle(attributeString, for: .normal) } @IBAction func skipButton_Tapped(_ sender: UIButton) { performSegue(withIdentifier: "ToStationSegue", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ToStationSegue" { if let destVC = segue.destination as? TabBarViewController { destVC.selectedIndex = 4 } } } }
true
ccbe397b1e06e8cfb26f03fcf27e7adf930bcaf8
Swift
wizardguy/BFInfiniteHorizontalMovingView
/BFInfiniteHorizontalMovingView/BFInfiniteHorizontalMovingView/BFInfiniteHorizontalMovingView.swift
UTF-8
4,606
2.6875
3
[ "MIT" ]
permissive
// // BFInfiniteHorizontalMovingView.swift // animationTest // // Created by Dennis on 25/3/2018. // Copyright © 2018 Dennis. All rights reserved. // import Foundation import UIKit @objc protocol BFInfiniteHorizontalMovingViewDelegate { @objc optional func didTapped(view: BFInfiniteHorizontalMovingView) } @IBDesignable class BFInfiniteHorizontalMovingView: UIView { @IBInspectable public var backgroundPatternImage:UIImage? { didSet { guard let img = backgroundPatternImage else { return } #if !TARGET_INTERFACE_BUILDER backgroundImageView1.backgroundColor = UIColor(patternImage: img) backgroundImageView2.backgroundColor = UIColor(patternImage: img) #else self.backgroundColor = UIColor(patternImage: img) #endif } } public var movingSpeed: TimeInterval = 4.0 public var delegate: BFInfiniteHorizontalMovingViewDelegate? fileprivate var backgroundImageView1: UIView! fileprivate var backgroundImageView2: UIView! private var backupBackgroundColor: UIColor! static public func newInstance(patternImage: UIImage, frame: CGRect, backColor: UIColor? = UIColor.clear) -> BFInfiniteHorizontalMovingView { let newView = BFInfiniteHorizontalMovingView(frame: frame) newView.backgroundPatternImage = patternImage newView.backgroundColor = backColor newView.backupBackgroundColor = backColor return newView } internal override init(frame: CGRect) { super.init(frame: frame) setup() } internal required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func adjustSubviewsPosition() { backgroundImageView1.frame = self.bounds backgroundImageView2.frame = CGRect(x:self.bounds.size.width, y: 0, width: self.bounds.size.width, height: self.bounds.height) } private func setup() { // UIImageView 1 backgroundImageView1 = UIView() self.addSubview(backgroundImageView1!) // UIImageView 2 backgroundImageView2 = UIView() self.addSubview(backgroundImageView2!) adjustSubviewsPosition() self.clipsToBounds = true let tap = UILongPressGestureRecognizer(target: self, action: #selector(viewDidTapped(gesture:))) tap.minimumPressDuration = 0.1 self.addGestureRecognizer(tap) } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() } @objc private func viewDidTapped(gesture: UITapGestureRecognizer) { if gesture.state == .began { self.backgroundColor = backupBackgroundColor.lighter() } else if gesture.state == .ended { self.backgroundColor = backupBackgroundColor delegate?.didTapped?(view: self) } } } extension BFInfiniteHorizontalMovingView { func startMoving() { let animationOptions = UIViewAnimationOptions.repeat.rawValue | UIViewAnimationOptions.curveLinear.rawValue // Animate background UIView.animate(withDuration: movingSpeed, delay: 0.0, options: UIViewAnimationOptions(rawValue: animationOptions), animations: { self.backgroundImageView1.frame = self.backgroundImageView1.frame.offsetBy(dx: -1 * self.backgroundImageView1.frame.size.width, dy: 0) self.backgroundImageView2.frame = self.backgroundImageView2.frame.offsetBy(dx: -1 * self.backgroundImageView2.frame.size.width, dy: 0) }) } func stopMoving() { backgroundImageView1.layer.removeAllAnimations() backgroundImageView2.layer.removeAllAnimations() adjustSubviewsPosition() } } extension UIColor { func lighter(by percentage:CGFloat=30.0) -> UIColor? { return self.adjust(by: abs(percentage) ) } func darker(by percentage:CGFloat=30.0) -> UIColor? { return self.adjust(by: -1 * abs(percentage) ) } func adjust(by percentage:CGFloat=30.0) -> UIColor? { var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0; if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){ return UIColor(red: min(r + percentage/100, 1.0), green: min(g + percentage/100, 1.0), blue: min(b + percentage/100, 1.0), alpha: a) }else{ return nil } } }
true
ee2225412764b76a744cdb7defed82465f318b40
Swift
wantonio/final-project-ios
/final-project-ios/MainNotes.swift
UTF-8
1,199
2.703125
3
[]
no_license
// // MainNotes.swift // final-project-ios // // Created by Admin on 28/6/21. // import Foundation import CoreData class MainNotesProxy { init() { } static func saveMainNote(note:String, delegate: AppDelegate) -> NSManagedObject?{ let manageContext = delegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "MainNotes", in: manageContext)! let user = NSManagedObject(entity: entity, insertInto: manageContext) user.setValue(note, forKey: "note") do { try manageContext.save() return user }catch let error as NSError { print(error) } return nil } static func getMainNotes(delegate: AppDelegate) -> [NSManagedObject]? { let managedContext = delegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "MainNotes") do { let users:[NSManagedObject] = try managedContext.fetch(fetchRequest) return users } catch let error as NSError { print(error) } return nil } }
true
b95bc2fcf9d69fdf0d4b13c73877c0e10c612eaa
Swift
cindy-th-nguyen/AnimalzGraphQL
/AnimalzGraphQL/View/Announcement/AnimalFormView.swift
UTF-8
7,843
2.828125
3
[]
no_license
// // Animal.swift // AnimalzGraphQL // // Created by Nguyen Cindy on 16/09/2021. // import SwiftUI struct AnimalFormView: View { @Environment(\.presentationMode) private var presentationMode @State var isPressed: Bool = false @State private var selectedRace: RaceEnum = .shiba @State private var selectedSpecie: SpeciesEnum = .dog @State private var selectedGender: AnimalGender = .female @State private var selectedColor: FurColorEnum = .blue @State private var showingImagePicker = false @State private var inputImage: UIImage? @State private var image: Image? @State private var name: String = "" @State private var age: String = "" @State private var weight: String = "" @State private var height: String = "" @State private var isCastrated: Bool = true @State var dynamicSize: CGFloat = 100 @ObservedObject private var appSetting = AppSetting.shared func loadImage() { guard let inputImage = inputImage else { return } image = Image(uiImage: inputImage) } var body: some View { VStack { if !self.isPressed { ZStack { if image != nil { image? .resizable() .scaledToFill() .clipShape(Circle()) .frame(width: dynamicSize, height: dynamicSize) } else { VStack() { Image(systemName: "photo") .resizable() .scaledToFill() .foregroundColor(.white) .padding(30) } .frame(width: dynamicSize, height: dynamicSize) .background(Color.secondary) .clipShape(Circle()) .padding() } } .onTapGesture { self.showingImagePicker = true } VStack { TextField("Nom", text: $name) .disableAutocorrection(true) .padding() .overlay( RoundedRectangle(cornerRadius: 25) .stroke(Color.orange, lineWidth: 2) ) TextField("Age", text: $age) .keyboardType(.numberPad) .padding() .overlay( RoundedRectangle(cornerRadius: 25) .stroke(Color.orange, lineWidth: 2) ) TextField("Taille", text: $weight) .keyboardType(.numberPad) .padding() .overlay( RoundedRectangle(cornerRadius: 25) .stroke(Color.orange, lineWidth: 2) ) TextField("Poids", text: $height) .keyboardType(.numberPad) .padding() .overlay( RoundedRectangle(cornerRadius: 25) .stroke(Color.orange, lineWidth: 2) ) } .padding(.bottom, 10) .sheet(isPresented: $showingImagePicker, onDismiss: loadImage) { ImagePicker(image: self.$inputImage) } Spacer() Button(action: { self.isPressed = true }, label: { Text("Suivant") .fontWeight(.bold) .font(.headline) .frame(minWidth: 0, maxWidth: .infinity) .padding() .foregroundColor(.white) .background(Color.orange) .cornerRadius(25) }) } if self.isPressed { VStack(alignment: .leading) { Text("Genre") .fontWeight(.bold) .font(.body) .foregroundColor(.orange) Picker("", selection: $selectedGender) { ForEach(AnimalGender.allCases, id: \.self) { value in Text(value.rawValue).tag(value) } }.pickerStyle(SegmentedPickerStyle()) Text("Espèce") .fontWeight(.bold) .font(.body) .foregroundColor(.orange) Picker("", selection: $selectedSpecie) { ForEach(SpeciesEnum.allCases, id: \.self) { value in Text(value.rawValue).tag(value) } }.pickerStyle(SegmentedPickerStyle()) Text("Race") .fontWeight(.bold) .font(.body) .foregroundColor(.orange) Picker("", selection: $selectedRace) { ForEach(RaceEnum.allCases, id: \.self) { value in Text(value.rawValue).tag(value) } }.pickerStyle(SegmentedPickerStyle()) Text("Couleur du pelage") .fontWeight(.bold) .font(.body) .foregroundColor(.orange) Picker("", selection: $selectedColor) { ForEach(FurColorEnum.allCases, id: \.self) { value in Text(value.rawValue).tag(value) } }.pickerStyle(SegmentedPickerStyle()) Toggle("Castré.e ?", isOn: $isCastrated) } Spacer() Button(action: { guard let userFields = appSetting.userFields else { return } //Exemple insert base Animal // TO DO : Fur color Network.shared.apollo.perform(mutation: NewAnimalMutationWithVariablesMutation(animal: newAnimalInput(ownerId: userFields.userId, name: self.name, specie: SpeciesEnum(rawValue: self.selectedSpecie.rawValue), gender: AnimalGender(rawValue: self.selectedGender.rawValue), race: RaceEnum(rawValue: self.selectedRace.rawValue), description: "", age: Int(self.age), isCastrated: self.isCastrated, furColor: FurColorEnum(rawValue: self.selectedColor.rawValue), weight: 10, size: 10, photo: self.inputImage?.description))) self.presentationMode.wrappedValue.dismiss() }, label: { Text("Terminer") .fontWeight(.bold) .font(.headline) .frame(minWidth: 0, maxWidth: .infinity) .padding() .foregroundColor(.white) .background(Color.orange) .cornerRadius(25) }) } } .padding() } } struct Animal_Previews: PreviewProvider { static var previews: some View { AnimalFormView() } }
true
d689e878dfd0c8e3f725de3c2574176791f29aa7
Swift
igor1309/TengizReportSP
/Tests/TengizReportSPTests/Tools and Data Samples/TokenizedReport Samples/vaiMe_2020_12.swift
UTF-8
8,751
2.71875
3
[]
no_license
// // vaiMe_2020_12.swift // TengizReportSPTests // // Created by Igor Malyarov on 11.02.2021. // @testable import TengizReportModel extension TokenizedReport { static let vaiMe_2020_12 = TokenizedReport( header: [Token<HeaderSymbol>(source: "Название объекта: Вай Мэ! Щелково", symbol: HeaderSymbol.company(name: "Вай Мэ! Щелково")), Token<HeaderSymbol>(source: "Декабрь2020", symbol: HeaderSymbol.month(monthStr: "Декабрь2020")), Token<HeaderSymbol>(source: "Оборот факт:929.625", symbol: HeaderSymbol.revenue(929_625)), Token<HeaderSymbol>(source: "Средний показатель:29.987", symbol: HeaderSymbol.dailyAverage(29_987))], body: [[Token<BodySymbol>(source: "Основные расходы:\t-----------------------------\t25%\t", symbol: .header(title: "Основные расходы", plan: Optional(0.25), fact: nil)), Token<BodySymbol>(source: "5. Аренда головного офиса\t11.500\t\t", symbol: .item(itemNumber: 5, title: "Аренда головного офиса", value: 11_500, note: nil)), Token<BodySymbol>(source: "7.Вывоз мусора\t18.000\t\t", symbol: .item(itemNumber: 7, title: "Вывоз мусора", value: 18_000, note: nil)), Token<BodySymbol>(source: "ИТОГ:\t29.500\t\t", symbol: .footer(title: "ИТОГ:", value: 29_500))], [Token<BodySymbol>(source: "Зарплата:\t-----------------------------\t20%\t", symbol: .header(title: "Зарплата", plan: Optional(0.2), fact: nil)), Token<BodySymbol>(source: "1.ФОТ общий\t261.978\t\t", symbol: .item(itemNumber: 1, title: "ФОТ общий", value: 261_978, note: nil)), Token<BodySymbol>(source: "2. ФОТ Бренд, логистика, бухгалтерия\t90.000\t\t", symbol: .item(itemNumber: 2, title: "ФОТ Бренд, логистика, бухгалтерия", value: 90_000, note: nil)), Token<BodySymbol>(source: "ИТОГ:\t351.978\t\t", symbol: .footer(title: "ИТОГ:", value: 351_978))], [Token<BodySymbol>(source: "Фактический приход товара и оплата товара:\t-----------------------------\t30%\t", symbol: .header(title: "Фактический приход товара и оплата товара", plan: Optional(0.3), fact: nil)), Token<BodySymbol>(source: "1. Приход товара по накладным\t473.128р43к(оплаты фактические:231.572р46к-переводы;51.104р93к-корпоративная карта;2.799р-наличные из кассы; Итого 285.476р39к)\t\t", symbol: .item(itemNumber: 1, title: "Приход товара по накладным", value: 285476.39, note: Optional("473.128р43к(оплаты фактические:231.572р46к-переводы;51.104р93к-корпоративная карта;2.799р-наличные из кассы; Итого 285.476р39к)"))), Token<BodySymbol>(source: "ИТОГ:\t285.476р39к\t\t", symbol: .footer(title: "ИТОГ:", value: 285_476.39))], [Token<BodySymbol>(source: "Прочие расходы:\t\t8%\t", symbol: .header(title: "Прочие расходы", plan: 0.08, fact: nil)), Token<BodySymbol>(source: "1.Налоговые платежи \t22.282р86к\t\t", symbol: .item(itemNumber: 1, title: "Налоговые платежи", value: 22_282.86, note: nil)), Token<BodySymbol>(source: "2.Банковское обслуживание\t2.344р29к\t\t", symbol: .item(itemNumber: 2, title: "Банковское обслуживание", value: 2_344.29, note: nil)), Token<BodySymbol>(source: "4.Банковская комиссия 1.6% за эквайринг\t12.111\t\t", symbol: .item(itemNumber: 4, title: "Банковская комиссия 1.6% за эквайринг", value: 12_111, note: nil)), Token<BodySymbol>(source: "5.Юридическое сопровождение\t40.000\t\t", symbol: .item(itemNumber: 5, title: "Юридическое сопровождение", value: 40_000, note: nil)), Token<BodySymbol>(source: "6.Обслуживание кассовой программы\t15.995\t\t", symbol: .item(itemNumber: 6, title: "Обслуживание кассовой программы", value: 15_995, note: nil)), Token<BodySymbol>(source: "7. Обслуживание хостинга\t2.500\t\t", symbol: .item(itemNumber: 7, title: "Обслуживание хостинга", value: 2_500, note: nil)), Token<BodySymbol>(source: "8.Аудит Кантора (бухуслуги)\t60.000\t\t", symbol: .item(itemNumber: 8, title: "Аудит Кантора (бухуслуги)", value: 60_000, note: nil)), Token<BodySymbol>(source: "9. Реклама и IT поддержка\t59.200\t\t", symbol: .item(itemNumber: 9, title: "Реклама и IT поддержка", value: 59_200, note: nil)), Token<BodySymbol>(source: "12.Интернет\t3.500\t\t", symbol: .item(itemNumber: 12, title: "Интернет", value: 3_500, note: nil)), Token<BodySymbol>(source: "15.Ремонт и чистка вентиляции\t15.000\t\t", symbol: .item(itemNumber: 15, title: "Ремонт и чистка вентиляции", value: 15_000, note: nil)), Token<BodySymbol>(source: "16. Текущие мелкие расходы\t1.400\t\t", symbol: .item(itemNumber: 16, title: "Текущие мелкие расходы", value: 1_400, note: nil)), Token<BodySymbol>(source: "17. Чистка жироуловителей и канализации\t10.139\t\t", symbol: .item(itemNumber: 17, title: "Чистка жироуловителей и канализации", value: 10_139, note: nil)), Token<BodySymbol>(source: "ИТОГ:\t244.472р15к\t\t", symbol: .footer(title: "ИТОГ:", value: 244_472.15))], [Token<BodySymbol>(source: "Расходы на доставку:\t-----------------------------\t\t", symbol: .header(title: "Расходы на доставку", plan: nil, fact: nil)), Token<BodySymbol>(source: "2. Агрегаторы\t9.528\t\t", symbol: .item(itemNumber: 2, title: "Агрегаторы", value: 9_528, note: nil)), Token<BodySymbol>(source: "ИТОГ:\t9.528\t\t", symbol: .footer(title: "ИТОГ:", value: 9_528))] ], footer: [Token<FooterSymbol>(source: "ИТОГ всех расходов за месяц:\t920.954р54к", symbol: .totalExpenses(title: "ИТОГ всех расходов за месяц", value: 920_954.54)), Token<FooterSymbol>(source: "Фактический остаток:\t8.670р46к", symbol: .balance(title: "Фактический остаток", value: 8_670.46, percentage: nil)), Token<FooterSymbol>(source: "Остаток с ноября \t684.753р85к", symbol: .openingBalance(title: "Остаток с ноября \t684.753р85к", value: 684_753.85)), Token<FooterSymbol>(source: "ИТОГ:\t693.424р31к переносим на январь", symbol: .runningBalance(title: "ИТОГ", value: 693_424.31)) ] ) }
true
1993f9b39945794beb3518bb1f0df03ff8a12af2
Swift
daflecardoso/MockServiceSwift
/Example/MockServiceSwift/MyNetwork.swift
UTF-8
1,047
2.734375
3
[ "MIT" ]
permissive
// // MyNetwork.swift // MockServiceSwift_Example // // Created by Dafle on 27/09/21. // Copyright © 2021 CocoaPods. All rights reserved. // import Foundation import MockServiceSwift class MyNetwork { func foo(success: @escaping (String) -> Void, failure: @escaping (Error) -> Void) { let api = FooBiggerNameToTestAPI.someGet if api.isEnabled { print("from mock...") success(api.json) return } print("from network...") let request = URLRequest(url: URL(string: api.baseUrl + api.mockPath)!) URLSession.shared.dataTask(with: request) { data, _, error in DispatchQueue.main.async { if let error = error { failure(error) } else { let dataResponse = data ?? Data() let json = String(data: dataResponse, encoding: .utf8) ?? "" success(json) } } }.resume() } }
true
3f881619394e4dfd2ef24ad41f72c57f20d4237d
Swift
kenjef1962/swift-RoShamBo
/RoShamBo/UIImageView+.swift
UTF-8
585
2.703125
3
[]
no_license
// // UIImageView+.swift // RoShamBo // // Created by Kendall Jefferson on 2/27/17. // Copyright © 2017 Kendall Jefferson. All rights reserved. // import Foundation import UIKit extension UIImageView { func setBorder(on visible: Bool) { self.layer.cornerRadius = 5 self.layer.borderWidth = visible ? 1 : 0 self.layer.borderColor = UIColor.gray.cgColor self.clipsToBounds = true } func reset() { self.alpha = 1.0 self.image = nil self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.setBorder(on: false) } }
true
334d300fb708e4fce5e5de6e89a91c63681a7180
Swift
edgaradrian/iOS-Practices
/SwiftUI/Examples/MyFirstBasicTemplate/MyFirstBasicTemplate/EffectModifiers/DrawingGroup/DrawingGroup_Intro.swift
UTF-8
1,889
3.328125
3
[ "MIT" ]
permissive
// // DrawingGroup_Intro.swift // MyFirstBasicTemplate // // Created by Edgar Adrián on 02/07/22. // import SwiftUI struct DrawingGroup_Intro: View { @State private var scaling = false var body: some View { VStack(spacing: 10) { HeaderView(titulo: "Grupo de Dibujo", subtitulo: "Introducción", description: "Usar el modificador drawingGroup mejora el rendimiento cuando trabajas muchas capasen un Zstack") Button { self.scaling = true } label: { Text("Cambiar Escala") } GeometryReader { g in ZStack { ForEach(0...200, id: \.self) { _ in Circle() .foregroundColor(.blue) .opacity(0.2) .animation(.interpolatingSpring(stiffness: 0.5, damping: 0.5) .repeatForever() .speed(.random(in: 0.05...0.9)) .delay(.random(in: 0...2)) ) .scaleEffect(self.scaling ? .random(in: 0.1...2) : 1) .frame(width: .random(in: 10...100), height: .random(in: 10...100)) .position(x: randomCoordinate(max: g.size.width), y: randomCoordinate(max: g.size.height)) } } .drawingGroup() } } }//body func randomCoordinate(max: CGFloat) -> CGFloat { return CGFloat.random(in: 0...max) }//randomCoordinate }//DrawingGroup_Intro struct DrawingGroup_Intro_Previews: PreviewProvider { static var previews: some View { DrawingGroup_Intro() } }
true
23dcf90ee8d8b313d526aacaab3db7cd5e5238b3
Swift
Skylout/ExtendVCPractice
/ExtendVCPractice/ViewController.swift
UTF-8
1,524
3.234375
3
[]
no_license
// // ViewController.swift // ExtendVCPractice // // Created by Леонид on 28.06.2021. // import UIKit class ViewController: UIViewController { @IBOutlet weak var coolButton: UIButton! var isAlreadyPressed = false override func viewDidLoad() { super.viewDidLoad() coolButton.layer.borderWidth = 1.0 coolButton.layer.cornerRadius = 2.0 } @IBAction func coolButtonPressed(_ sender: UIButton) { if !isAlreadyPressed { showBlackSquare() isAlreadyPressed = true DispatchQueue.main.async { self.coolButton.setTitle("Убрать квадрат", for: .normal) } } else { hideBlackSquare() isAlreadyPressed = false DispatchQueue.main.async { self.coolButton.setTitle("Вернуть квадрат на законное место", for: .normal) } } } } extension ViewController { func showBlackSquare () { let w = UIScreen.main.bounds.width let h = UIScreen.main.bounds.height let blackSquare = UIView(frame: CGRect(x: w/2, y: h/2, width: 25, height: 25)) blackSquare.layer.backgroundColor = UIColor.black.cgColor blackSquare.tag = 60 self.view.addSubview(blackSquare) } func hideBlackSquare () { if let viewWithCurrentTag = self.view.viewWithTag(60) { viewWithCurrentTag.removeFromSuperview() } } }
true
1d5916b008b7c3f2244368ab6a4787a0008c068d
Swift
nebhale/LoggerLogger
/LoggerLogger/PlistConfigurationProvider.swift
UTF-8
3,783
2.671875
3
[ "Apache-2.0" ]
permissive
/* Copyright 2015 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /** An implementation of `ConfigurationProvider` that reads configuration values from a plist */ public final class PlistConfigurationProvider: ConfigurationProvider { private static let DEFAULT_FORMAT = "%date{HH:mm:ss} %level %message" private static let DEFAULT_LEVEL = Level.Info private var configurations: [String : Configuration] = [:] private let rootConfiguration: Configuration /** Creates a new instance of `PlistConfigurationProvider` - parameter file: The name of the plist file to read - parameter bundle: The bundle to read the plist from. Defaults to `NSBundle.mainBundle()` */ public init(file: String = "Logging", bundle: NSBundle = NSBundle.mainBundle()) { let source = PlistConfigurationProvider.readSource(file, bundle: bundle) self.rootConfiguration = PlistConfigurationProvider.toConfiguration("ROOT", source: source) for (key, value) in source { if let value = value as? [String : AnyObject] { configurations += PlistConfigurationProvider.toConfiguration(key, source: value) } } } /** Returns the `Configuration` instance for a `Logger` - parameter name: The name of the `Logger` - returns: The `Configuration` instance for the `Logger` */ public func configuration(name: String) -> Configuration { if let configuration = self.configurations[name] { return configuration } else { return self.rootConfiguration } } private static func toConfiguration(name: String, source: [String : AnyObject]) -> Configuration { let level: Level if let candidate = source["Level"] as? String { level = Level(candidate) } else { level = DEFAULT_LEVEL } let format: String if let candidate = source["Format"] as? String { format = candidate } else { format = DEFAULT_FORMAT } return Configuration(name: name, level: level, format: format) } private static func readSource(file: String, bundle: NSBundle) -> [String : AnyObject] { if let url = bundle.URLForResource(file, withExtension: "plist"), let dictionary = NSDictionary(contentsOfURL: url) as? [String: AnyObject] { return dictionary } else { return [:] } } } // MARK: - Level From String extension Level { private init(_ rawValue: String) { switch rawValue { case let value where value =~ (Level.Debug.toString(), true): self = .Debug case let value where value =~ (Level.Info.toString(), true): self = .Info case let value where value =~ (Level.Warn.toString(), true): self = .Warn case let value where value =~ (Level.Error.toString(), true): self = .Error default: self = .Debug } } } // MARK: - Dictionary Addition func +=(inout dictionary: [String : Configuration], configuration: Configuration) -> [String : Configuration] { dictionary[configuration.name] = configuration return dictionary }
true
1767a9952b6c749c614f04103ac87a178af366dd
Swift
MaxDesiatov/WASIFoundation
/Sources/WASIFoundation/URL.swift
UTF-8
4,033
3.125
3
[ "MIT", "Apache-2.0", "Swift-exception" ]
permissive
// // URL.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 6/29/15. // Copyright © 2015 PureSwift. // /// Encapsulates the components of an URL. public struct URL: CustomStringConvertible { // MARK: - Properties public let scheme: String public let user: String? public let password: String? /// The host URL subcomponent (e.g. domain name, IP address) public let host: String? public let port: UInt? public let path: String? public let query: [(String, String)]? /// The fragment URL component (the part after a # symbol) public var fragment: String? // MARK: - Initialization public init(fileURLWithPath path: String) { scheme = "file://" user = nil password = nil host = nil port = nil self.path = path query = nil fragment = nil } /// Returns a valid URL string or ```nil``` var urlString: String? { var stringValue = scheme + "://" if let user = user { stringValue += user } if let password = password { stringValue += ":\(password)" } if user != nil { stringValue += "@" } if let host = host { stringValue += host } if let port = port { stringValue += ":\(port)" } if let path = path { stringValue += "/\(path)" } if let query = query { stringValue += "?" for (index, queryItem) in query.enumerated() { let (name, value) = queryItem stringValue += name + "=" + value if index != query.count - 1 { stringValue += "&" } } } if let fragment = fragment { stringValue += "#\(fragment)" } return stringValue } public var description: String { let separator = " " var description = "" if let urlString = urlString { description += "URL: " + urlString + separator } description += "Scheme: " + scheme if let user = user { description += separator + "User: " + user } if let password = password { description += separator + "Password: " + password } if let host = host { description += separator + "Host: " + host } if let port = port { description += separator + "Port: " + "\(port)" } if let path = path { description += separator + "Path: " + path } if let query = query { var stringValue = "" for (index, queryItem) in query.enumerated() { let (name, value) = queryItem stringValue += name + "=" + value if index != query.count - 1 { stringValue += "&" } } description += separator + "Query: " + stringValue } if let fragment = fragment { description += separator + "Fragment: " + fragment } return description } func _pathByFixingSlashes(compress: Bool = true, stripTrailing: Bool = true) -> String? { guard let p = path else { return nil } if p == "/" { return p } var result = p if compress { let startPos = result.startIndex var endPos = result.endIndex var curPos = startPos while curPos < endPos { if result[curPos] == "/" { var afterLastSlashPos = curPos while afterLastSlashPos < endPos && result[afterLastSlashPos] == "/" { afterLastSlashPos = result.index(after: afterLastSlashPos) } if afterLastSlashPos != result.index(after: curPos) { result.replaceSubrange(curPos..<afterLastSlashPos, with: ["/"]) endPos = result.endIndex } curPos = afterLastSlashPos } else { curPos = result.index(after: curPos) } } } if stripTrailing && result.hasSuffix("/") { result.remove(at: result.index(before: result.endIndex)) } return result } public var lastPathComponent: String { guard let fixedSelf = _pathByFixingSlashes() else { return "" } if fixedSelf.count <= 1 { return fixedSelf } return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent)) } }
true
b1ae4aa671bd8607784bdaa4c7ec71f5a131ab74
Swift
Aaqibali279/ProjectFramework
/ProjectStructure/Utilities/MyUserDefaults.swift
UTF-8
552
2.5625
3
[]
no_license
// // MyUserDefaults.swift // ProjectFramework // // Created by Aqib Ali on 09/07/18. // Copyright © 2018 SignYourself. All rights reserved. // import Foundation class MyUserDefaults{ //MARK:- KEYS static let USER_ID = "userid" static var userPreference = UserDefaults.standard static func setUserID(id:String) { userPreference.set(id, forKey: USER_ID) userPreference.synchronize() } static func getUserID() -> String? { return userPreference.string(forKey: USER_ID) } }
true
3349a5962feecc608bb0ec4d3167c41da9fe9f0a
Swift
bmitchelmore/Sequoia
/SequoiaTests/Mocks/MockSearch.swift
UTF-8
976
2.5625
3
[]
no_license
// // MockSearch.swift // SequoiaTests // // Created by Blair Mitchelmore on 2021-01-14. // import Foundation import XCTest @testable import Sequoia final class MockSearch: GraphQL { private var searches: [(String?, Any)] = [] deinit { verify() } func verify() { XCTAssertEqual(searches.count, 0) } func expectSearch<T: Codable>(query: String? = nil, result: Result<SearchPage<T>, Error>) { searches.append((query, result as Any)) } func search<T: Codable>(query: String, completion: @escaping (Result<SearchPage<T>, Error>) -> Void) { if let (expectedQuery, result) = searches.first { searches.removeFirst() if let expectedQuery = expectedQuery { XCTAssertEqual(query, expectedQuery) } completion(result as! Result<SearchPage<T>, Error>) } else { XCTFail("Unexpected search call on MockSearch") } } }
true
4dae2f7e6ee2c358e9611b4484da313054918a69
Swift
lukasdekret/tribal-wars
/tribal-wars/tribal-wars/Controller/StockVC.swift
UTF-8
788
2.546875
3
[]
no_license
// // StockVC.swift // tribal-wars // // Created by Lukáš Dekrét on 8.2.18. // Copyright © 2018 Lukáš Dekrét. All rights reserved. // import UIKit class StockVC: UIViewController { @IBOutlet weak var stockCapacity: UILabel! @IBOutlet weak var goldLbl: UILabel! @IBOutlet weak var woodLbl: UILabel! @IBOutlet weak var nextLevelCapacity: UILabel! var materials: Materials! var buildingsLevel: BuildingsLevel! var army: Army! override func viewDidLoad() { super.viewDidLoad() stockCapacity.text = String(materials.woodCapacity) goldLbl.text = String(materials.gold) woodLbl.text = String(materials.wood) nextLevelCapacity.text = String(Production.countNextCapacity(currentCapacity: materials.goldCapacity)) } }
true
eacf445aedf5c247f5e03a7f522f5cd6e1961779
Swift
platipus25/Timer-App
/Timer App/ViewController copy.swift
UTF-8
3,714
3
3
[]
no_license
// // ViewController.swift // Timer App // // Created by Ravago on 7/25/18. // Copyright © 2018 blabblabla. All rights reserved. // import UIKit import Foundation enum AlarmMode: Int { case time, duration } class ViewController : UIViewController { let calendar = Calendar.current var futureDate: Date? = nil let dateFormatter = DateFormatter() var timer: Timer? = nil var timeLeftTimer: Timer? = nil let durationFormatter = DateComponentsFormatter() var currentMode: AlarmMode = .time var timerInterval: TimeInterval? { get { if currentMode == .time { if let date = futureDate{ if(date > Date()){ return DateInterval(start: Date(), end: date).duration }else{ return nil } } }else if currentMode == .duration { return datePicker.countDownDuration } return nil } } @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var modeSwitch: UISegmentedControl! @IBOutlet weak var datePicker: UIDatePicker! @IBAction func modeSwitchHandler(_ sender: Any) { for mode in 0...1 { if(modeSwitch.isEnabledForSegment(at: mode)){ currentMode = AlarmMode(rawValue: mode) ?? .time if(currentMode == .duration){ datePicker.datePickerMode = .countDownTimer }else if(currentMode == .time){ datePicker.datePickerMode = .time } } } } @IBAction func datePickerHandler(_ sender: UIDatePicker) { if currentMode == .time { let hourAndMinuteComponent = calendar.dateComponents(Set<Calendar.Component>([.hour, .minute]), from: sender.date) futureDate = calendar.nextDate(after:Date(), matching:hourAndMinuteComponent, matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward) } if let date = futureDate { print(dateFormatter.string(from: date)) } updateTimeRemaining() timeLeftTimer?.invalidate() timeLeftTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true){ timer in self.updateTimeRemaining() } timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: timerInterval ?? 0.1, repeats: false){ timer in print("Alarm Done") self.titleLabel.text = "Countdown" self.timeLeftTimer?.invalidate() } } func updateTimeRemaining(){ if let durationText = durationFormatter.string(from: timerInterval ?? 0){ titleLabel.text = durationText print(durationText) } else{ titleLabel.text = "Countdown" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // init formatters dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short durationFormatter.unitsStyle = .short durationFormatter.includesApproximationPhrase = true durationFormatter.includesTimeRemainingPhrase = true durationFormatter.allowedUnits = [.day, .hour, .minute, .second] durationFormatter.maximumUnitCount = 2 print("hello world") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
b10907a4b48e2f3b41c33f7f28dea74da707217e
Swift
arjunpa/PhotoCollection
/PhotoCollection/PhotoListTableViewCell.swift
UTF-8
841
2.78125
3
[]
no_license
// // PhotoListTableViewCell.swift // PhotoCollection // // Created by Arjun P A on 15/07/20. // Copyright © 2020 Arjun P A. All rights reserved. // import UIKit class PhotoListTableViewCell: UITableViewCell { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var thumbnailImageView: UIImageView! func configure(with viewModelInterface: PhotoViewModelInterface) { self.titleLabel.text = viewModelInterface.title self.thumbnailImageView.image = nil viewModelInterface.image(with: self.thumbnailImageView.bounds.size) { [weak self] result in switch result { case .success(let image): self?.thumbnailImageView.image = image case .failure: self?.thumbnailImageView.image = nil } } } }
true
21cc5da5bd5c2f7bee04b3a61fb4221f82ab84a0
Swift
ArchieGertsman/Evo-Live-Events
/Evo/TokenView.swift
UTF-8
7,845
2.59375
3
[]
no_license
// // TokenView.swift // Evo // // Created by Admin on 7/18/17. // Copyright © 2017 Evo. All rights reserved. // import UIKit import CLTokenInputView /* Wrapper class for CLTokenInputView. Creates functioning token views. */ class TokenView: UIView { private var height_constraint: NSLayoutConstraint! private var height_of_token_input_view: CGFloat = 65 private var data = [String]() // all of the data that the token view can search through private var filtered_data = [String]() // buffer containing search resuluts of data private var selected_data = [String]() // buffer containing selected data private lazy var table_view: UITableView = { // displays search results let table_view = UITableView() table_view.isHidden = true table_view.translatesAutoresizingMaskIntoConstraints = false return table_view }() private let token_input_view: CLTokenInputView = { // token container let token_input_view = CLTokenInputView() token_input_view.backgroundColor = .white token_input_view.fieldName = NSLocalizedString("Add: ", comment: "") token_input_view.tintColor = .EVO_blue token_input_view.drawBottomBorder = true token_input_view.layer.borderColor = UIColor.EVO_border_gray.cgColor token_input_view.layer.cornerRadius = 5 token_input_view.layer.masksToBounds = true token_input_view.translatesAutoresizingMaskIntoConstraints = false return token_input_view }() var max_number_of_tokens: UInt? var is_border_enabled = false { didSet { self.token_input_view.layer.borderWidth = is_border_enabled ? 1 : 0 } } // constructor which takes in all of the searchable data and sets up UI required init(_ data: [String], field_name: String) { self.data = data self.token_input_view.fieldName = NSLocalizedString("\(field_name): ", comment: "") super.init(frame: CGRect.zero) self.table_view.dataSource = self self.table_view.delegate = self self.token_input_view.delegate = self self.table_view.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUpUI() { self.addSubview(token_input_view) self.addSubview(table_view) token_input_view.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true token_input_view.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true token_input_view.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true self.height_constraint = self.heightAnchor.constraint(equalToConstant: height_of_token_input_view) self.height_constraint.isActive = true constrainTableView() } func constrainTableView() { table_view.topAnchor.constraint(equalTo: self.token_input_view.bottomAnchor).isActive = true table_view.centerXAnchor.constraint(equalTo: self.token_input_view.centerXAnchor).isActive = true table_view.widthAnchor.constraint(equalTo: self.token_input_view.widthAnchor).isActive = true table_view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true } func getAllTokens() -> [CLToken] { return self.token_input_view.allTokens } func getBottomAnchorOfInputView() -> NSLayoutYAxisAnchor { return self.token_input_view.bottomAnchor } func changeHeightConstraint(withConstant height: CGFloat) { self.height_constraint.isActive = false self.height_constraint.constant = height self.height_constraint.isActive = true } private func openTableView() { self.table_view.isHidden = false self.changeHeightConstraint(withConstant: 200) } private func closeTableView() { self.table_view.isHidden = true self.changeHeightConstraint(withConstant: height_of_token_input_view) } } /* TokenView extensions */ extension TokenView: CLTokenInputViewDelegate { // handle a change of text in the input view func tokenInputView(_ view: CLTokenInputView, didChangeText text: String?) { if let max = self.max_number_of_tokens { if self.selected_data.count >= Int(max) { // if a maximum token amount is defined and reached then return self.closeTableView() return } } if text!.isEmpty { // if entered text is empty then clear buffer self.filtered_data = [] self.closeTableView() } else { // search for entered text and update the filtered data buffer let predicate = NSPredicate(format: "self contains[cd] %@", text ?? "") self.filtered_data = self.data.filter { predicate.evaluate(with: $0) } self.openTableView() } self.table_view.reloadData() } // if a token is added then add the token's text to the selected data buffer func tokenInputView(_ view: CLTokenInputView, didAdd token: CLToken) { self.selected_data.append(token.displayText) } // if a token is removed then remove its text from the selected data buffer func tokenInputView(_ view: CLTokenInputView, didRemove token: CLToken) { let idx = self.selected_data.index(of: token.displayText) self.selected_data.remove(at: idx!) } func tokenInputView(_ view: CLTokenInputView, tokenForText text: String) -> CLToken? { guard self.filtered_data.count > 0 else { return nil } var matching_name: String! for name in filtered_data { if !selected_data.contains(name) { matching_name = name break } } guard let _ = matching_name else { return nil } let match = CLToken() match.displayText = matching_name match.context = nil return match } func tokenInputViewDidEndEditing(_ view: CLTokenInputView) { view.accessoryView = nil } func tokenInputViewDidBeginEditing(_ view: CLTokenInputView) { self.layoutIfNeeded() } func tokenInputView(_ view: CLTokenInputView, didChangeHeightTo height: CGFloat) { self.height_of_token_input_view = height + 10 self.changeHeightConstraint(withConstant: self.height_of_token_input_view) } } extension TokenView: UITableViewDataSource, UITableViewDelegate { //MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.filtered_data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) let name = self.filtered_data[indexPath.row] cell.textLabel!.text = name cell.accessoryType = self.selected_data.contains(name) ? .checkmark : .none return cell } //MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let name = self.filtered_data[indexPath.row] guard !self.selected_data.contains(name) else { return } let token = CLToken() token.displayText = name token.context = nil self.token_input_view.add(token) } }
true
eda80365bbf1f5daf335d9513480aaafb8d9255f
Swift
MrMatten/SwiftUICleanTemplates
/SwiftCollectionView.xctemplate/SwiftCollectionView/___FILEBASENAME___ViewModel.swift
UTF-8
864
2.765625
3
[ "MIT" ]
permissive
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // protocol ___VARIABLE_sceneName___StateActions: class { func saveSomething() } class ___VARIABLE_sceneName___ViewModel: ObservableObject, ___VARIABLE_sceneName___StateActions { var interactor: ___VARIABLE_sceneName___BusinessLogic? // MARK: init init() { setup() } // MARK: Setup private func setup() { let viewModel = self let interactor = ___VARIABLE_sceneName___Interactor() let presenter = ___VARIABLE_sceneName___Presenter() viewModel.interactor = interactor interactor.presenter = presenter presenter.viewModel = viewModel } // MARK: State @Published var someVar: String = "Hello World" func doSomething() { interactor?.doSomething() } func saveSomething(/*someString: String*/) { // self.someVar = someString } }
true
fdff415cfe31ba22998c379ee5aa5342dc7643bb
Swift
HinWong/Intro
/Day26Demo/lifeCycle/lifeCycle/AppDelegate.swift
UTF-8
3,492
2.921875
3
[]
no_license
// // AppDelegate.swift // lifeCycle // // Created by Luat on 2/15/21. // import UIKit import BackgroundTasks @main class AppDelegate: UIResponder, UIApplicationDelegate { /** 1) Not Running / Not Attached (before the app is opened) - no code is ran 2) Foreground Inactive (On screen) - running code - launching app - coming out from background state - not receiving UI events 3) Foreground Active (On screen) - running code - receiving UI events 4) Background (Off screen) - running code - not receiving UI events - automatically suspended after 30 secs - can request more time by begining a new task - beginBackgroundTask(withName:expirationHandler:) - var backgroundTimeRemaining 5) Suspended 1) Not Running AppDelegate vs SceneDelegate 1) app delegate - App lifecycle and setup - App launching, with options - Configure the new scene - clean up, release resources when scene is dicarded 2) Scene delegate - manage the scene-base life cycle - has UIWindow, manages the life cycle of what is shown to user Background fetch: 1) Add capabilities: Background Modes: Background Fetch In appDelegate - 2) set UIApplication.shared.setMinimumBackgroundFetchInerval() in app launch - 3) implement: performFetchWithCompletionHandler 4) In iOS 13 and 14: Import BackgoundTasks, use BGAppRefreshTask */ /** launchOptions: the reason why app was lauched and was passed some data - some other app can start our app and pass some data to launchOptions - pushNotification, location event, passing a URL */ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. print("didFinishLaunchingWithOptions") return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. print("configurationForConnecting") return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. print("didDiscardSceneSessions") } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if let newData = fetchUpdates() { addDataToFeed(newData: newData) completionHandler(.newData) } completionHandler(.noData) } func fetchUpdates() -> Data? { return nil } func addDataToFeed(newData: Data) {} }
true
c4749db99f1d7066580e5ee0b01b246b07a0cdf6
Swift
editorscut/ec007-swift-kickstart
/8Protocols.playground/Pages/Protocol Extensions.xcplaygroundpage/Contents.swift
UTF-8
551
3.5625
4
[]
no_license
//: ### Protocol Extensions //: [TOC](TOC) | [Previous](@previous) | [Next](@next) func shiftLeft<T: Movable>(movable: T) -> T { return movable.moveByX(-1) } let point = Vertex(x: 3.0, y: 4.0) let shiftedLeftPoint = shiftLeft(point) let shiftedRightPoint = point.shiftRight() let rectangle = Rectangle(topLeftCorner: point, width: 200.0, height: 100.0) let shiftedLeftRectangle = shiftLeft(rectangle) let shiftedRightRectangle = rectangle.shiftRight() point.whereAmI() rectangle.whereAmI() //: [TOC](TOC) | [Previous](@previous) | [Next](@next)
true
eb10cd9900d34f2e5b3cca82627a3fd61eb69dde
Swift
yewonbahn/MovieAppClone
/MovieApp/DetailViewController.swift
UTF-8
2,393
3.046875
3
[]
no_license
// // DetailViewController.swift // MovieApp // // Created by 반예원 on 2021/08/08. // import UIKit import AVKit class DetailViewController: UIViewController { var movieResult: MovieResult?{ //값을 넣었다라는 상태! didSet{ } } @IBOutlet weak var descriptionLabel: UILabel!{ didSet{ descriptionLabel.font = .systemFont(ofSize: 16, weight: .light) } } var player: AVPlayer? @IBOutlet weak var movieContainer: UIView! @IBOutlet weak var titleLabel: UILabel!{ didSet{ titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .medium) } } //메모리에 올리긴했는데 여기서는 실제디바이스 크기가 어떤지는 확인하지 못함 override func viewDidLoad() { super.viewDidLoad() titleLabel.text = movieResult?.trackName descriptionLabel.text = movieResult?.longDescription } // Do any additional setup after loading the view. override func viewDidAppear(_ animated: Bool) { if let hasURL = movieResult?.previewUrl { makePlayerAndPlay(urlString: hasURL) } } func makePlayerAndPlay(urlString: String) { if let hasUrl = URL(string: urlString){ self.player = AVPlayer(url: hasUrl) let playerLayer = AVPlayerLayer(player: player) movieContainer.layer.addSublayer(playerLayer) playerLayer.frame = movieContainer.bounds self.player?.play() } } @IBAction func play(_ sender: Any) { self.player?.play() } @IBAction func stop(_ sender: Any) { self.player?.pause() } @IBAction func close(_ sender: Any) { //dismiss는 present한걸 내릴떄! //present로 띄운건, dismiss로 내릴수있다.ㄴ self.dismiss(animated: true, completion: nil) } /* // 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
53c2f5cc8ce08ba114705792bcf0da468c879398
Swift
vanessa-bergen/SimpleChatApp
/client/ChatApp/ChatApp/UITextViewWrapper.swift
UTF-8
2,030
2.9375
3
[]
no_license
// // UITextViewWrapper.swift // ChatApp // // Created by Vanessa Bergen on 2020-12-14. // Copyright © 2020 Vanessa Bergen. All rights reserved. // import SwiftUI struct UITextViewWrapper: UIViewRepresentable { @Binding var text: String var placeholder: String var placeholderActive = true var textColor: UIColor { return placeholderActive ? UIColor.placeholderText : UIColor.black } func makeUIView(context: Context) -> UITextView { let view = UITextView() view.delegate = context.coordinator view.isScrollEnabled = true view.isEditable = true view.isUserInteractionEnabled = true view.textAlignment = .left view.font = UIFont.preferredFont(forTextStyle: .body) view.adjustsFontForContentSizeCategory = true view.text = placeholder view.textColor = textColor return view } func updateUIView(_ uiView: UITextView, context: Context) { } class Coordinator: NSObject, UITextViewDelegate { var parent: UITextViewWrapper init(_ parent: UITextViewWrapper) { self.parent = parent } func textViewDidBeginEditing(_ textView: UITextView) { if parent.text.isEmpty { textView.text = nil } self.parent.placeholderActive = false } func textViewDidEndEditing(_ textView: UITextView) { if parent.text.isEmpty { textView.text = parent.placeholder self.parent.placeholderActive = true textView.textColor = parent.textColor } } func textViewDidChange(_ textView: UITextView) { if !parent.placeholderActive { self.parent.text = textView.text } textView.textColor = parent.textColor } } func makeCoordinator() -> Coordinator { Coordinator(self) } }
true
87f977affee41b53ccce239dfb412f16224e3834
Swift
miamarklee/123
/作業8-snow and sakura/ViewController.swift
UTF-8
4,796
3.203125
3
[]
no_license
// // ViewController.swift // 作業8-snow and sakura // // Created by apple on 2019/4/13. // Copyright © 2019 apple. All rights reserved. // import UIKit import AVFoundation ///下面不認得AVSpeechUtterance,一般import會加在檔案的最前面 class ViewController: UIViewController { @IBOutlet weak var speakSlider: UIButton! @IBAction func buttonPressed(_sender: Any) { // 生出要講的話 let speechUtterance=AVSpeechUtterance(string:"跟我玩球吧") //講中文 speechUtterance.voice=AVSpeechSynthesisVoice(language: "zh-TW") speechUtterance.rate = 0.5 //說話速度 speechUtterance.pitchMultiplier = 2.0//說話音調 //生出講話的合成器 let synthesizer = AVSpeechSynthesizer() //下面沒寫(使用常數),會產生警告 synthesizer.speak(speechUtterance) } override func viewDidLoad() { super.viewDidLoad() //peter叫我加這個 //view.backgroundColor = UIColor.white.withAlphaComponent(0.40) //CAEmitterLayer發射的粒子其實是 CAEmitterCell,so需要產生 CAEmitterCell物件 //???let snowEmitterLayer = CAEmitterLayer() let snowEmitterCell = CAEmitterCell() snowEmitterCell.contents = UIImage(named: "snow")?.cgImage //透過scaleRang設定大小的範圍,0.5是一半的大小。設定0.06~0.3為一個range snowEmitterCell.scale = 0.06 snowEmitterCell.scaleRange = 0.1 snowEmitterCell.scaleSpeed = -0.02//雪花大小改變的速度 snowEmitterCell.emissionRange = .pi snowEmitterCell.lifetime = 20.0 //雪花維持的秒數,讓雪花只停留20秒 snowEmitterCell.birthRate = 8 //設定每秒發射幾個雪花,指定一秒2個 snowEmitterCell.velocity = -30 //雪花移動的速度 snowEmitterCell.velocityRange = -20 //利用yAcceleration 設定向下移動的加速度 snowEmitterCell.yAcceleration = 30 snowEmitterCell.xAcceleration = 5 //利用spin和spinRange 設定雪花轉速的範圍 snowEmitterCell.spin = 0.5 snowEmitterCell.spinRange = 1.0 //控制snow從哪裡發射(以下都不用再重覆寫,因為最後用[snowEmitterCell,sakuraEmitterCell] 可以寫在一起) //snowEmitterLayer.emitterPosition = CGPoint(x: view.bounds.width / 2.0, y: -50) //snowEmitterLayer.emitterSize = CGSize(width: view.bounds.width, height: 0) //snowEmitterLayer.emitterShape = CAEmitterLayerEmitterShape.line //snowEmitterLayer.beginTime = CACurrentMediaTime() //snowEmitterLayer.timeOffset = 10 //view.layer.addSublayer(snowEmitterLayer)這行不寫,因為只要產生一個 CAEmitterLayer //以下4行,造成程式沒寫在 function 的 { } 裡 // } //override func viewDidLoad() { //super.viewDidLoad() //view.backgroundColor = UIColor.white.withAlphaComponent(0.40) //再來下櫻花 //let sakuraEmitterLayer = CAEmitterLayer() let sakuraEmitterCell = CAEmitterCell() sakuraEmitterCell.contents = UIImage(named: "sakura")?.cgImage sakuraEmitterCell.scale = 0.06 sakuraEmitterCell.scaleRange = 0.1 sakuraEmitterCell.scaleSpeed = -0.02//改變的速度 sakuraEmitterCell.emissionRange = .pi sakuraEmitterCell.lifetime = 10.0 //只停留10秒 sakuraEmitterCell.birthRate = 2 //指定一秒2個 sakuraEmitterCell.velocity = -30 //移動的速度 sakuraEmitterCell.velocityRange = -20 //利用yAcceleration 設定向下移動的加速度 sakuraEmitterCell.yAcceleration = 30 sakuraEmitterCell.xAcceleration = 5//設定轉速的範圍 sakuraEmitterCell.spin = 0.5 sakuraEmitterCell.spinRange = 1.0 //let sakuraEmitterLayer=CAEmitterLayer() 這行不寫,因為只要產生一個 CAEmitterLayer //控制sakura從哪裡發射(以下都不用再重覆寫,因為最後用[snowEmitterCell,sakuraEmitterCell] 可以寫在一起) //sakuraEmitterLayer.emitterPosition = CGPoint(x: view.bounds.width / 2.0, y: -50) //sakuraEmitterLayer.emitterSize = CGSize(width: view.bounds.width, height: 0) //sakuraEmitterLayer.emitterShape = //(這行不寫)CAEmitterLayerEmitterShape.line //sakuraEmitterLayer.beginTime = CACurrentMediaTime() //sakuraEmitterLayer.timeOffset = 10 //view.layer.addSublayer(sakuraEmitterLayer) 這行不寫,因為只要產生一個 CAEmitterLayer let snowEmitterLayer = CAEmitterLayer() snowEmitterLayer.emitterCells = [snowEmitterCell,sakuraEmitterCell] //控制從哪裡發射(用 [snowEmitterCell,sakuraEmitterCell] 把snow和sakura兩個元件依snow為首寫在一起) snowEmitterLayer.emitterPosition = CGPoint(x: view.bounds.width / 2.0, y: -50) snowEmitterLayer.emitterSize = CGSize(width: view.bounds.width, height: 0) snowEmitterLayer.emitterShape = CAEmitterLayerEmitterShape.line snowEmitterLayer.beginTime = CACurrentMediaTime() snowEmitterLayer.timeOffset = 10 view.layer.addSublayer(snowEmitterLayer) } }
true
5a370528c1d449a4fc7ca81edf8e7aee6f0e0511
Swift
SandraBasquero/multiEduca
/MultiEduca/MultiEduca/Components/Cells/OneTextGameCell/OneTextGameCellCollectionViewCell.swift
UTF-8
1,273
2.59375
3
[]
no_license
// // OneTextGameCellCollectionViewCell.swift // MultiEduca // // Created by Sandra on 12/07/2019. // Copyright © 2019 Sandra. All rights reserved. // import UIKit class OneTextGameCellCollectionViewCell: UICollectionViewCell { @IBOutlet weak var text: UILabel! static let identifier = "OneTextGameCellCollectionViewCell" static func registerCellForCollectionView(_ collectionView:UICollectionView) { collectionView.register(UINib.init(nibName: "OneTextGameCellCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: identifier) } static func calculateCellSize(collectionViewWidth: CGFloat, cellsMinSpacing: CGFloat, totalInfo: [String]) -> CGSize { var maxLenght = 0 totalInfo.forEach { maxLenght = $0.count > maxLenght ? $0.count : maxLenght } let cellWidth = maxLenght > 6 ? collectionViewWidth / 2 : collectionViewWidth / 3 return CGSize(width: cellWidth - cellsMinSpacing, height: 100) } override func awakeFromNib() { super.awakeFromNib() layer.borderWidth = 0.5 layer.borderColor = UIColor.white.cgColor layer.cornerRadius = 10 } func setData(text: String) { self.text.text = text } }
true
85ca470ea8ee693c58c09256e91b89439ef4a815
Swift
veroce/XGArqmobUI
/XGArqmobUI/Classes/ArqmobAlert/AmAlert.swift
UTF-8
2,613
2.515625
3
[ "MIT" ]
permissive
// // AmAlert.swift // arqmob-ui // // Created by Vero on 13/04/2020. // Copyright © 2020 Soluciones y Proyecto de Información. All rights reserved. // import UIKit open class AmAlert: UIViewController { @IBOutlet weak var viewAlert: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var lbTitle: UILabel! @IBOutlet weak var lbBody: UILabel! @IBOutlet weak var btnCancel: UIButton! @IBOutlet weak var btnAction: UIButton! @IBOutlet weak var contraintHeightLine: NSLayoutConstraint! @IBOutlet weak var constraintWidthLine: NSLayoutConstraint! private var titleValue: String? private var bodyValue: String? private var titleAction: String? private var imageString: String? var handler: ((UIButton) -> Void)? public var style = AmAlertStyle() { didSet { loadStyle() } } public func loadTitle(_ title: String, message: String, image: String){ titleValue = title bodyValue = message imageString = image } open override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. loadStyle() loadData() } private func loadData() { lbBody.text = bodyValue lbTitle.text = titleValue btnAction.setTitle(titleAction, for: .normal) if let imageString = imageString { if let image = UIImage(named: imageString) { imageView.image = image }else{ } } btnCancel.setTitle(NSLocalizedString("Cancelar", comment: ""), for: .normal) } private func loadStyle() { constraintWidthLine.constant = 0.5 contraintHeightLine.constant = 0.5 viewAlert.layer.cornerRadius = 14 lbTitle.font = style.titleFont lbBody.font = style.messageFont btnAction.titleLabel?.font = style.actionButtonFont btnCancel.titleLabel?.font = style.cancelButtonFont btnAction.tintColor = style.actionButtonColor btnCancel.tintColor = style.cancelButtonColor imageView.backgroundColor = style.backgroundColor } public func addAction(title: String, handler: ((UIButton) -> Void)? = nil) { titleAction = title self.handler = handler } @IBAction func btnCancelTouch(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func btnActionTouch(_ sender: Any) { handler?(btnAction) } }
true
75cf1635105ce4ce1e70d7de4b29bdc091fe5608
Swift
killvak/erotS
/Hyper/NavigationBarView.swift
UTF-8
926
2.59375
3
[]
no_license
// // NavigationBarView.swift // Hyper // // Created by admin on 2/28/18. // Copyright © 2018 admin. All rights reserved. // import UIKit //https://stackoverflow.com/questions/45782669/swift-4-ios-11-search-bar-scope-wont-appear-as-it-should class NavigationBarView: UIView { @IBOutlet weak var backBtn: UIButton! @IBOutlet weak var navTitleLbl: UILabel! var titleS = "" { didSet { self.navTitleLbl?.text = titleS } } override init(frame: CGRect) { super.init(frame: frame) commonUnit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonUnit() } private func commonUnit() { let view = Bundle.main.loadNibNamed("NavigationBarView", owner: self, options: nil)?.first as! UIView view.frame = self.bounds addSubview(view) } }
true
9fffd367a6b8936a5a8e3857a446cc65c4970d89
Swift
a-beco/iOS-CleanArchitecture-Example
/iOS-CleanArchitecture-Example/Domain/UseCase/FriendListUseCase.swift
UTF-8
1,680
3.078125
3
[]
no_license
// // FriendListUseCase.swift // iOS-CleanArchitecture-Example // // Created by Kohei Abe on 2016/12/13. // Copyright © 2016年 Kohei Abe. All rights reserved. // import Foundation protocol FriendListUseCaseInput: class { func load() } protocol FriendListUseCaseInputDelegate: class { func useCase(_ useCase: FriendListUseCase, didLoadFriendList friendList: [UserEntity]) } // データ取得のためDataに求めるインタフェース protocol FriendListUseCaseDataInput: class { weak var delegate: FriendListUseCaseDataInputDelegate? { get set } func load() } // 依存方向をGateway->UseCaseにするためここに書く必要がある。 // UseCaseはGatewayの存在を一切知らないようにする。 protocol FriendListUseCaseDataInputDelegate: class { func dataInput(_ dataInput: FriendListUseCaseDataInput, didLoadFriendList friendList: [UserEntity]) } // フレンド一覧を取得するUseCase。 // ユーザプロフィールやメッセージの送信先の選択などなど、複数画面から使いまわす可能性がある。 final class FriendListUseCase: FriendListUseCaseInput { weak var delegate: FriendListUseCaseInputDelegate? let input: FriendListUseCaseDataInput init(input: FriendListUseCaseDataInput) { self.input = input } func load() { input.load() } } // Gatewayからデータ取得した結果を受け取る。 extension FriendListUseCase: FriendListUseCaseDataInputDelegate { func dataInput(_ dataInput: FriendListUseCaseDataInput, didLoadFriendList friendList: [UserEntity]) { delegate?.useCase(self, didLoadFriendList: friendList) } }
true
190e53f51c80771a054ddb2120c22a680d3a6256
Swift
IgorChernyshov/GuessTheFlag
/GuessTheFlag/ViewController.swift
UTF-8
4,401
2.90625
3
[]
no_license
// // ViewController.swift // GuessTheFlag // // Created by Igor Chernyshov on 19.06.2021. // import UIKit import NotificationCenter class ViewController: UIViewController { // MARK: - Outlets @IBOutlet var button1: UIButton! @IBOutlet var button2: UIButton! @IBOutlet var button3: UIButton! // MARK: - Properties private let notificationCenter = UNUserNotificationCenter.current() private var score = 0 private var correctAnswer = 0 private var questionsAnswered = 0 private var countries: [String] = ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"] // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(didTapScoreButton)) configureNotifications() [button1, button2, button3].forEach { $0?.layer.borderWidth = 1 $0?.layer.borderColor = UIColor.lightGray.cgColor } askQuestion(action: nil) } // MARK: - Game Progress private func askQuestion(action: UIAlertAction?) { countries.shuffle() button1.setImage(UIImage(named: countries[0]), for: .normal) button2.setImage(UIImage(named: countries[1]), for: .normal) button3.setImage(UIImage(named: countries[2]), for: .normal) correctAnswer = Int.random(in: 0...2) title = "\(countries[correctAnswer].uppercased()). Score \(score)" } // MARK: - Actions @IBAction func buttonTapped(_ sender: UIButton) { var title: String var message: String? UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: [.autoreverse]) { sender.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) } completion: { _ in sender.transform = .identity } if sender.tag == correctAnswer { title = "Correct!" message = nil score += 1 } else { title = "Wrong!" message = "That's \(countries[sender.tag].uppercased())" score -= 1 } questionsAnswered += 1 if questionsAnswered >= 5 { let highestScoreKey = "highestScore" let highestScore = UserDefaults.standard.integer(forKey: highestScoreKey) if self.score > highestScore { UserDefaults.standard.set(self.score, forKey: highestScoreKey) } let alertController = UIAlertController(title: "Game Over", message: "You scored \(score). Your highest score is \(highestScore) so far.", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Reset", style: .default) { _ in self.score = 0 self.questionsAnswered = 0 self.askQuestion(action: nil) }) present(alertController, animated: true) } else { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion)) present(alertController, animated: true) } } @objc func didTapScoreButton() { let alertController = UIAlertController(title: "Your score is \(score)", message: "In case like you can't read it in the navigation bar", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "M'kay", style: .default)) present(alertController, animated: true) } // MARK: - Notifications private func configureNotifications() { requestNotificationsPermission() { [weak self] in self?.notificationCenter.removeAllPendingNotificationRequests() self?.scheduleNotifications() } } private func requestNotificationsPermission(completion: @escaping () -> Void) { notificationCenter.requestAuthorization(options: [.alert, .sound]) { result, error in if result { print("Permissions granted") completion() } else { print("No luck") } } } private func scheduleNotifications() { let content = UNMutableNotificationContent() content.title = "Go play the game" content.body = "Now! It's fun and educational" content.categoryIdentifier = "play" content.sound = .default var dateComponents = DateComponents() dateComponents.hour = Calendar.current.component(.hour, from: Date()) dateComponents.minute = Calendar.current.component(.minute, from: Date()) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) notificationCenter.add(request) } }
true
8e17926417f3707377ac2ad389ddeb6d83f7563f
Swift
RoboAtenaga/Manner
/Manner/Controllers/AuthViewController.swift
UTF-8
1,748
2.578125
3
[]
no_license
// // ViewController.swift // Manner // // Created by Robo Atenaga on 1/22/18. // Copyright © 2018 Robo Atenaga. All rights reserved. // import UIKit class AuthViewController: UIViewController, FBSDKLoginButtonDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func loginWithFacebook(_ sender: UIButton) { handleCustomFBLogin() } func handleCustomFBLogin() { FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile"], from: self) { (result, error) in if error != nil { print("Custom FB login failed: ", error as Any) return } self.getUserInformation() self.performSegue(withIdentifier: "segueToHome", sender: Any!.self) } } func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if error != nil{ print("FB login failed: ",error) return } getUserInformation() } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { print("Logout successful") } func getUserInformation(){ // To get info of user, use FBSDKGraphRequest FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, error) in if error != nil { print("Failed to start graph request:", error as Any) return } // email isn't part of result because sometimes it requires permission print(result as Any) } } }
true
629238e1167bb46a955d3109c6eeaf071fd6aa8b
Swift
musiienko/animal-locator
/AnimalLocator/Core/Managers/MapManager.swift
UTF-8
2,904
2.875
3
[]
no_license
// // MapManager.swift // AnimalLocator // // Created by Maksym Musiienko on 13.05.21. // import MapKit protocol MapManaging: AnyObject { func setup(with mapView: MKMapView) func configure(with vehicles: [VehicleModel]) } final class MapManager: NSObject, MapManaging { // MARK: - Private properties private let reuseId = String(describing: VehicleAnnotationView.self) private var isInitialUpdate = true private weak var mapView: MKMapView? // MARK: - Setup func setup(with mapView: MKMapView) { self.mapView = mapView mapView.showsUserLocation = true mapView.delegate = self mapView.userTrackingMode = .follow mapView.register(VehicleAnnotationView.self, forAnnotationViewWithReuseIdentifier: self.reuseId) self.setDefaultLocation(on: mapView) } private func setDefaultLocation(on mapView: MKMapView) { let center = Coordinate(latitude: 52.506282329714104, longitude: 13.373136712291933) let region = MKCoordinateRegion(center: center, latitudinalMeters: 100, longitudinalMeters: 100) mapView.setRegion(region, animated: true) } // MARK: - Configure func configure(with vehicles: [VehicleModel]) { defer { self.isInitialUpdate = true } guard let mapView = self.mapView else { return } mapView.removeAnnotations(mapView.annotations) let annotations = vehicles.map(VehicleAnnotation.init(vehicle:)) mapView.addAnnotations(annotations) let rentableAnnotations = annotations.filter(\.vehicle.canBeRented) let userAnnotation = mapView.userLocation if rentableAnnotations.isEmpty { mapView.showAnnotations(annotations + [userAnnotation], animated: true) return } guard let userLocation = mapView.userLocation.location else { mapView.showAnnotations(rentableAnnotations + [userAnnotation], animated: true) return } // safe to unwrap since we have a check for rentable annotations above let closestAnnotation = rentableAnnotations.min { userLocation.distance(from: $0.coordinate) < userLocation.distance(from: $1.coordinate) }! mapView.showAnnotations([closestAnnotation, mapView.userLocation], animated: true) if self.isInitialUpdate { mapView.selectAnnotation(closestAnnotation, animated: true) } } } // MARK: - MKMapViewDelegate extension MapManager: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? VehicleAnnotation { return mapView.dequeueReusableAnnotationView(withIdentifier: self.reuseId, for: annotation) } else { // clustering return nil } } }
true
e9257e05c3a7b3b14676e37d9d6e9ada07e01439
Swift
shumozhou/SwiftSummary
/ORSwiftSummary/ORSwiftSummary/Demo/AlertView/Popover(气泡菜单)/PopoverViewVC.swift
UTF-8
1,451
2.578125
3
[]
no_license
// // PopoverViewVC.swift // ORSwiftSummary // // Created by orilme on 2020/2/27. // Copyright © 2020 orilme. All rights reserved. // import UIKit class PopoverViewVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white let sureBtn = UIButton.init(frame: CGRect(x: 20, y: 100, width: 100, height: 50)) sureBtn.backgroundColor = UIColor.green sureBtn.setTitle("气泡", for: .normal) sureBtn.setTitleColor(.black, for: .normal) sureBtn.addTarget(self, action: #selector(showPopover(button:)), for: .touchUpInside) self.view.addSubview(sureBtn) } // MARK: Action @objc func showPopover(button: UIButton) { let options: [PopoverViewOption] = [.type(.down), .showBlackOverlay(false), .showShadowy(true), .arrowPositionRatio(0.3), .arrowSize(CGSize(width: 12, height: 13)), .color(.white)] let pop = PopoverView.init(options: options) let contentView = PopFilterView.init(frame: CGRect(x: 0, y: 0, width: 150, height: 175), style: .plain, list: ["访问时间倒叙", "访问时间正序", "访问次数倒叙", "访问次数正序"]) contentView.didSelect = { [weak self] (indexPath) in pop.dismiss() button.isSelected = false } pop.contentView = contentView pop.show(pop.contentView, fromView: button) } }
true
cd4ccdbd5e950f21bb311b4ef2c572cea685203b
Swift
hcanfly/Photos13
/Photos13/MainMenu/MainMenuViewCell.swift
UTF-8
3,792
2.796875
3
[ "Unlicense" ]
permissive
// // MainMenuViewCell.swift // // Created by Edgar on 10/7/15. // import UIKit final class MainMenuPlainCell: UITableViewCell { var icon: UIImageView? var selectedIcon: UIImageView? var title: UILabel? fileprivate let margin: CGFloat = 24 fileprivate let gap: CGFloat = 24 fileprivate let iconSize: CGFloat = 26 fileprivate let defaultColor = LyveColors.selectedText.color() fileprivate let defaultSelectedColor = LyveColors.selectedDarkText.color() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = UIColor.clear self.icon = UIImageView(frame: frame) self.icon?.contentMode = UIView.ContentMode.scaleAspectFit self.addSubview(self.icon!) self.selectedIcon = UIImageView(frame: frame) self.selectedIcon!.contentMode = UIView.ContentMode.scaleAspectFit self.selectedIcon!.isHidden = true self.addSubview(self.selectedIcon!) self.title = UILabel(frame: frame) self.title!.textAlignment = .left self.title!.font = LyveFont.light.font(17) self.title!.textColor = defaultColor self.addSubview(self.title!) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.icon!.tintColor = selected ? defaultSelectedColor : defaultColor self.selectedIcon!.tintColor = self.icon!.tintColor self.icon!.isHidden = selected self.selectedIcon!.isHidden = !selected self.title!.textColor = selected ? defaultSelectedColor : defaultColor self.title!.font = selected ? LyveFont.medium.font(17) : LyveFont.light.font(17) } override func layoutSubviews() { super.layoutSubviews() var iconFrame = CGRect(x: 0, y: 0, width: iconSize, height: iconSize) iconFrame = iconFrame.offsetBy(dx: self.margin, dy: (self.frame.height - iconFrame.height) / 2.0) self.icon!.frame = iconFrame self.selectedIcon!.frame = iconFrame let titleFrame = CGRect(x: iconFrame.maxX + gap, y: 0, width: self.frame.width - iconFrame.maxX - gap, height: self.frame.height) self.title!.frame = titleFrame } } class MainMenuSeparatorCell: UITableViewCell { fileprivate var separatorView: UIView? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.separatorView = UIView(frame: frame) self.separatorView?.backgroundColor = UIColor(white: 0.8, alpha: 1.0) self.addSubview(self.separatorView!) self.isUserInteractionEnabled = false } override func layoutSubviews() { super.layoutSubviews() let separatorFrame = CGRect(x: 0, y: 0, width: self.frame.width, height: 1) self.separatorView!.frame = separatorFrame } } final class MainMenuMiniSeparatorCell: MainMenuSeparatorCell { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.separatorView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0) } override func layoutSubviews() { super.layoutSubviews() let separatorFrame = CGRect(x: 16, y: 0, width: self.frame.width - 32, height: 1) self.separatorView!.frame = separatorFrame } }
true
4e561bf622cea3f9797ed3eb414b738420f00e30
Swift
briankeane/vc-testing-example
/FakeMusicPlayer/AudioPlayer/AudioPlayerProtocol.swift
UTF-8
386
3.0625
3
[]
no_license
// // AudioPlayerProtocol.swift // FakeMusicPlayer // // Created by Brian Keane on 2/5/21. // import Foundation enum AudioPlayerStatus { case playing case stopped } protocol AudioPlayer { var volume:Double { get set } var delegate:AudioPlayerDelegate? { get set } var status: AudioPlayerStatus { get set } func play() func stop() func setVolume(newVolume: Double) }
true
6ba1301bcf8ef0418f4d928252722ac48b578a4b
Swift
lcapkovic/aoc2019
/AdventOfCode2019/Solutions/Day8.swift
UTF-8
1,726
3.25
3
[]
no_license
// // Day8.swift // AdventOfCode2019 // // Created by Lukas Capkovic on 08/12/2019. // Copyright © 2019 Lukas Capkovic. All rights reserved. // import Foundation class Day8: Day { static let w = 25 static let h = 6 static func part1(_ input: String) -> String { let pass = Array(input.trimmingCharacters(in: .newlines)) .compactMap { $0.wholeNumberValue } let layered = pass.chunked(into: w*h) let bestLayer = layered.reduce(into: [Int]()) { best, current in if best == [] || current.filter({ $0 == 0 }).count < best.filter({ $0 == 0 }).count { best = current } } return String(bestLayer.filter({$0 == 1}).count * bestLayer.filter({$0 == 2}).count) } static func part2(_ input: String) -> String { let pass = Array(input.trimmingCharacters(in: .newlines)) .compactMap { $0.wholeNumberValue } let layered = pass.chunked(into: w*h) let squashed = layered.reduce(into: Array(repeating: 2, count: w*h)) { squashed, current in for i in 0..<squashed.count { if squashed[i] == 2 { squashed[i] = current[i] } } } for row in 0..<h { for col in 0..<w { print(squashed[row*w + col] == 1 ? "O" : " ", terminator: "") } print() } return "^^^ Answer is above ^^^" } } extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: count, by: size).map { Array(self[$0 ..< Swift.min($0 + size, count)]) } } }
true
e26966dc7dec4568c8645c08ce0c1338834b6a0f
Swift
jianli2017/DataStructBySwift
/alg/图/有向图/DirectedCycle.swift
UTF-8
3,375
3.28125
3
[ "Apache-2.0" ]
permissive
// // DirectedCycle.swift // DataStruct // // Created by lijian on 2019/7/23. // Copyright © 2019 lijian. All rights reserved. // import Foundation let G_TinyDG_Cycle1_TXT = "/Users/lijian/Desktop/数据结构学习/DataStruct/alg/图/Resource/tinyDG_Cycle1.txt" let G_TinyDG_Cycle2_TXT = "/Users/lijian/Desktop/数据结构学习/DataStruct/alg/图/Resource/tinyDG_Cycle2.txt" class DirectedCycle { var _marked: [Bool] var _edgeTo: [Int] var _cycle: Stack<Int>? var _onStack: [Bool] init(graph: Digraph) { let vertexCount = graph.v() self._marked = [Bool](repeating: false, count: vertexCount) self._edgeTo = [Int](repeating: 0, count: vertexCount) self._onStack = [Bool](repeating: false, count: vertexCount) for v in 0..<vertexCount { if !self._marked[v] { dfs(graph, v) } } } func dfs(_ graph: Digraph, _ v: Int) { self._onStack[v] = true self._marked[v] = true for w in graph.adj(v) { if !self._marked[w] { //如果没有标记,递归标记(这里不需要判断换,没有标记过,肯定不在调用栈上) self._edgeTo[w] = v dfs(graph, w) } else { //标记过了,可以判断这个顶点是否在栈上 if self._onStack[w] { //有环 self._cycle = Stack<Int>() var x = v repeat { self._cycle?.push(x) x = self._edgeTo[x] } while x != w self._cycle?.push(w) self._cycle?.push(v) } } } self._onStack[v] = false } func hasCycle() -> Bool { return self._cycle != nil } func cycle() -> [Int] { if self.hasCycle() { return self._cycle!.iterater() } else { return [Int]() } } static func test1() { let path = G_TinyDG_Cycle1_TXT let file = ReadFile(fileName: path) guard file != nil else { return } let digraph = Digraph(inStream: file!) guard digraph != nil else { return } print("开始测试是否有环......") let cycle = DirectedCycle(graph: digraph!) if cycle.hasCycle() { print("有环") print(cycle.cycle()) } else { print("无环") } print("输出图片数据:") let result = digraph!.toString() print(result) } static func test2() { let path = G_TinyDG_Cycle2_TXT let file = ReadFile(fileName: path) guard file != nil else { return } let digraph = Digraph(inStream: file!) guard digraph != nil else { return } print("开始测试是否有环......") let cycle = DirectedCycle(graph: digraph!) if cycle.hasCycle() { print("有环") print(cycle.cycle()) } else { print("无环") } print("输出图片数据:") let result = digraph!.toString() print(result) } }
true
ac147bac88433fc94fd3c9b258df9b74242160b7
Swift
Songer585/diplomado2018
/tareas/Algoritmos Swift/Algoritmos Swift.playground/Contents.swift
UTF-8
956
4.40625
4
[ "MIT" ]
permissive
//: Parra Avila Jorge Arturo import UIKit //Algoritmo 1: Numero Primo func numeroPrimo(_ n: Int) -> Bool{ for i in 2..<n{ if n % i == 0{ return false } } return true } numeroPrimo(2) //Algoritmo 2: Serie de Fibonacci func fibonacci(_ n: Int){ var a = 0, b = 1 while b < n { print(b) (a,b) = (b, a + b) } } fibonacci(90) //Actividad 3: Palindromo func palindromo(_ cadena: String){ let contrario = String(cadena.reversed()) if contrario == cadena{ print("Es palindromo") }else { print("No es palindromo") } } palindromo("anitalavalatina") //Actividad 4: Funcion que compare dos cadenas y verifique que contenga los mismos caracteres en el mismo o diferente orden func comparacionCadenas(_ cadena1: String, _ cadena2: String) -> Bool{ return cadena1.count == cadena2.count && cadena1.sorted() == cadena2.sorted() } comparacionCadenas("hola", "loah")
true
28922accb35302f2df59d8e35d1116c24b4e9b03
Swift
lisheng1009/FightFishDemo
/FightFish/FightFish/Classes/Tools/extension/UIButton+extension.swift
UTF-8
1,023
3.203125
3
[ "MIT" ]
permissive
// // UIButton+extension.swift // FightFish // // Created by 安静清晨 on 2019/5/10. // Copyright © 2019年 walk-in-minds. All rights reserved. // import UIKit extension UIButton { //扩展一个类方法 /* class func createButton(imageName:String, highlightedImageName:String, size: CGSize) -> UIButton { let btn = UIButton() btn.setImage(UIImage(named: imageName), for: .normal) btn.setImage(UIImage(named: highlightedImageName), for: .highlighted) btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return btn } */ //扩展一个构造函数 // 1. 必须以便利开头 2. 在构造函数中必须ming convenience init(imageName:String, highlightedImageName:String, size: CGSize){ self.init() self.setImage(UIImage(named: imageName), for: .normal) self.setImage(UIImage(named: highlightedImageName), for: .highlighted) self.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) } }
true
b37f7648bff37c58533e398e9246cc63b556d536
Swift
ixmeza/delai
/respawn/ViewController.swift
UTF-8
6,155
2.671875
3
[]
no_license
// // ViewController.swift // respawn // // Created by Ixchel on 17/08/20. // Copyright © 2020 flakeystories. All rights reserved. // import UIKit import Lottie class ViewController: UIViewController { var timer : Timer! var seconds: Int32 = 0 var minutes: Int32 = 0 var status : Bool = false var tiempo : Int64 = 0 @IBOutlet var startBtn: UIButton! @IBOutlet var timerLabel: UILabel! @IBOutlet weak var animationView: AnimationView! override open var shouldAutorotate: Bool { return false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) UIApplication.shared.isIdleTimerDisabled = true // changing colors and style startBtn.backgroundColor = UIColor.init(red: 248/255, green: 166/255, blue: 69/255, alpha: 1) startBtn.layer.cornerRadius = startBtn.frame.height / 2 startBtn.setTitleColor(UIColor.white, for: UIControl.State.normal) startBtn.layer.shadowColor = UIColor.init(red: 253/255, green: 221/255, blue: 139/255, alpha: 1).cgColor startBtn.layer.shadowOpacity = 3 view.backgroundColor = UIColor.white // Storing the default time the user has set in the application in user defaults, // the default for my pomodoro is 25 minutes if let t = UserDefaults.standard.string(forKey: "time") as String? { tiempo = Int64(t) ?? 25 } else { tiempo = 25 } let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil) // lottie code needed to play the animation // Set animation content mode animationView.contentMode = .scaleAspectFill // Set animation loop mode animationView.loopMode = .loop // Adjust animation speed animationView.animationSpeed = 0.5 /** below code is for testing purposes // get the current date and time let currentDateTime = Date() // initialize the date formatter and set the style let formatter = DateFormatter() formatter.timeStyle = .none formatter.dateStyle = .short var dateStamp = formatter.string(from: currentDateTime) dateStamp = dateStamp.replacingOccurrences(of: "/", with: "-", options: NSString.CompareOptions.literal, range:nil) var record = Record(id: 1,date: dateStamp, duration: 20) // Save dummy records into the database RecordManager.shared.create(record : record) record = Record(id: 1,date: "8-01-2020", duration: 5) RecordManager.shared.create(record : record) record = Record(id: 1,date: "7-30-2020", duration: 10) RecordManager.shared.create(record : record) **/ } @objc func applicationDidBecomeActive(notification: NSNotification) { status = false } @objc func applicationDidEnterBackground(notification: NSNotification) { status = false } @objc func appMovedToBackground(notification: NSNotification) { // if user leaves the screen no minutes are recorded - penalty reset() } @objc func action(){ timerLabel.text = "00 : 00" var fs = "0" var fm = "0" seconds += 1 if(seconds > 9) { fs = "" } if (seconds > 59) { minutes += 1 seconds = 0 fs = "0" } if (minutes > 9) { fm = "" } let time = "\(fm)\(minutes) : \(fs)\(seconds)" // play animation animationView.play() if (minutes < tiempo) { timerLabel.text = String(time) } else { let alert = UIAlertController(title: "You did it!", message: "The world didn't end without you using your phone.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)) self.present(alert, animated: true) // get the current date and time let currentDateTime = Date() // initialize the date formatter and set the style let formatter = DateFormatter() formatter.timeStyle = .none formatter.dateStyle = .short var dateStamp = formatter.string(from: currentDateTime) dateStamp = dateStamp.replacingOccurrences(of: "/", with: "-", options: NSString.CompareOptions.literal, range:nil) let record = Record(id: 1,date: dateStamp, duration: tiempo) // we only save a record in the database if user waited until the time goes off // Save into database RecordManager.shared.create(record : record) reset() } } func reset(){ if timer != nil { timer.invalidate() } timerLabel.text = "00 : 00" startBtn.setTitle("Start", for: .normal) seconds = 0 minutes = 0 // Stop animation animationView.stop() } @IBAction func startTime(_ sender: Any) { if(startBtn.title(for: .normal) == "Give up") { timer.invalidate() timerLabel.text = "00 : 00" startBtn.setTitle("Start", for: .normal) seconds = 0 minutes = 0 // stop playing animation animationView.stop() } else { animationView.play(fromFrame: 0, toFrame: 270, loopMode: nil, completion: nil) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.action), userInfo: nil, repeats: true) startBtn.setTitle("Give up", for: .normal) } } }
true
fd09157ef6a9350c801278c7ba317288319e724f
Swift
28th-SOPT-iOS-CloneCoding/PPuringClone-KimSoYeon
/ClockApp/ClockApp/Sources/Cells/WorldClock/WorldClockCell.swift
UTF-8
848
2.734375
3
[]
no_license
// // WorldClockTableViewCell.swift // ClockApp // // Created by soyeon on 2021/04/29. // import UIKit class WorldClockCell: UITableViewCell { static let identifier = "WorldClockCell" @IBOutlet weak var timeDifferLabel: UILabel! @IBOutlet weak var countryLabel: UILabel! @IBOutlet weak var dayAndNightLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setUpClock(world: WorldTime) { countryLabel.text = world.country dayAndNightLabel.text = world.dayAndNight timeLabel.text = world.time timeDifferLabel.text = "오늘, \(world.timeDifference)시간" } }
true
7d201b9383dca4d1ccc024adf5d36a1b6002c9d0
Swift
aligungor/SwiftTutorial
/SwiftTutorial/UITableView/TableViewController.swift
UTF-8
3,198
2.875
3
[]
no_license
// // TableViewController.swift // SwiftTutorial // // Created by Ali Gungor on 17/05/15. // Copyright (c) 2015 AliGungor. All rights reserved. // import UIKit class TableViewController: UITableViewController { var carArray = NSMutableArray() override func viewDidLoad() { super.viewDidLoad() self.generateCarArray() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return carArray.count } func generateCarArray() { let car1 = Car() car1.carName = "Ferrari" car1.carImage = "Ferrari" carArray.add(car1) carArray.add(Car().generateACar("Lamborghini", imageName: "Lamborghini")) carArray.add(Car().generateACar("Tesla", imageName: "Tesla")) carArray.add(Car().generateACar("Mercedes-Benz", imageName: "Mercedes")) carArray.add(Car().generateACar("BMW", imageName: "BMW")) carArray.add(Car().generateACar("Porsche", imageName: "Porsche")) carArray.add(Car().generateACar("Aston Martin", imageName: "Aston")) self.tableView.reloadData() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "carCell", for: indexPath) as! CarTableViewCell let carAtIndex = carArray.object(at: (indexPath as NSIndexPath).row) as! Car cell.lblCar?.text = carAtIndex.carName cell.imgCar?.image = UIImage(named: carAtIndex.carImage!) cell.btnCarInfo?.tag = (indexPath as NSIndexPath).row return cell } @IBAction func onClickCarCellInfo(_ sender: UIButton) { let carInfoClicked = carArray.object(at: sender.tag) as! Car let alert = UIAlertController( title: carInfoClicked.carName!, message: carInfoClicked.carName! + " Info Button Click!", preferredStyle: UIAlertControllerStyle.alert ) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80; } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let carInfoClicked = carArray.object(at: (indexPath as NSIndexPath).row) as! Car let alert = UIAlertController( title: carInfoClicked.carName!, message: carInfoClicked.carName! + " Cell Select", preferredStyle: UIAlertControllerStyle.alert ) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
true
af006b06e4829382b1a30123e2de4918f94369a1
Swift
DmitryPashinskiy/TestTask
/TestTaskReddit/PresentationLayer/Screens/PostListTableVC/Cells/PostTableCell.swift
UTF-8
1,149
2.5625
3
[]
no_license
// // PostTableCell.swift // TestTaskReddit // // Created by Newcomer on 19.10.2019. // Copyright © 2019 Home. All rights reserved. // import UIKit protocol PostTableCellDelegate: class { func cellDidTapImage(_ cell: PostTableCell) } class PostTableCell: UITableViewCell { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var commentsLabel: UILabel! @IBOutlet weak var postedDateLabel: UILabel! weak var delegate: PostTableCellDelegate? override func awakeFromNib() { super.awakeFromNib() let tap = UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:))) thumbImageView.addGestureRecognizer(tap) } override func prepareForReuse() { super.prepareForReuse() thumbImageView.hideLoading() thumbImageView.image = nil thumbImageView.isHidden = false titleLabel.text = nil topLabel.text = nil commentsLabel.text = nil postedDateLabel.text = nil } @IBAction func imageTapped(_ gesture: UITapGestureRecognizer) { delegate?.cellDidTapImage(self) } }
true
b6bd9ad0d846736fcd8711e80a477e3399e50875
Swift
Nextdoor/corridor
/Sources/Corridor/CorridorRouter.swift
UTF-8
7,005
3.171875
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
import Foundation /** A type that stores values extracted from a matched URL. */ public protocol CorridorRoute: Decodable { } /** A type that stores generic values extracted from a matched URL. Such values may be contained in multiple types of matched URLs, irrespective of the route the URL resolves to. */ public protocol CorridorGlobalParams: Decodable { } /** Represents URL query params that can be present in any matched URL, regardless of the route the URL resolves to. */ public struct GlobalQueryOptionalParamsMapping { public let params: [String] public let decoder: (_ extracted: [String: Any]) throws -> CorridorGlobalParams /** Instantiates with keys that may be contained in a URL's query, and a decoder that serializes the corresponding key value pairs found in the URL. - parameter params: A list of keys that are present in the query portion of the URL. - parameter decoder: Yields a CorridorGlobalParams type that contains values from the URL's query. - parameter extracted: A dictionary of key-value pairs that are present in the query portion of the URL. */ public init(params: [String], decoder: @escaping (_ extracted: [String: Any]) throws -> CorridorGlobalParams) { self.params = params self.decoder = decoder } } /** Represents the matched URL. */ public struct RouteResponse { public let route: CorridorRoute public let globalParams: CorridorGlobalParams public init(route: CorridorRoute, globalParams: CorridorGlobalParams) { self.route = route self.globalParams = globalParams } } /** A no-value struct that conforms to CorridorGlobalParams. It is created if CorridorRouter wasn't initialized with a custom GlobalQueryOptionalParamsMapping struct. */ public struct CorridorGlobalParamsNone: CorridorGlobalParams { } struct RouteMapping { let attributes: CorridorAttributesProtocol let decoder: ([String: Any]) throws -> CorridorRoute } /** Extracts values from a URL, and converts the values into a typesafe struct called a "route". */ public class CorridorRouter { private let compiler: CorridorCompiler private var routeMappings: [RouteMapping] = [] private var globalQueryOptionalParamsDecoder: (([String: Any]) throws -> CorridorGlobalParams)? /** Instantiates with params used for custom configuration - parameter CorridorTypes: Represents primitive types that can be present in URLs. If not present, the primitive types will be limited to the built-in ones. - parameter globalQueryOptionalParamsMapping: (Optional) Specifies query params that the router will attempt to extract from any URL. */ public init(corridorTypes: CorridorTypes = CorridorTypes(), globalQueryOptionalParamsMapping: GlobalQueryOptionalParamsMapping?=nil) { let globalQueryOptionalParamNames = globalQueryOptionalParamsMapping?.params ?? [] self.compiler = CorridorCompiler(types: corridorTypes, globalQueryOptionalParamNames: globalQueryOptionalParamNames) self.globalQueryOptionalParamsDecoder = globalQueryOptionalParamsMapping?.decoder } /** Registers a string that defines the high level structure of a URL category, and a block used to create a route once a matching URL is found. - parameter expression: Defines high level structure of a URL category - parameter decoder: Creates a route once a matching URL is found - parameter extracted: A dictionary of extracted key-value pairs from the path and query portions of the URL */ public func register(_ expression: String, _ decoder: @escaping (_ extracted: [String: Any]) throws -> CorridorRoute) { let attributes = try! self.compiler.compile(expression: expression) self.routeMappings.append(RouteMapping(attributes: attributes, decoder: decoder)) } /** Attempts to match a URL with the registered expressions. If a match is found it will return a response struct. - parameter url: A URL - returns: A RouteResponse struct if the URL is matched, nil otherwise */ public func attemptMatch(url: URL) -> RouteResponse? { let matcher = CorridorMatcher(url: url) for routeMapping in self.routeMappings { let attributes = routeMapping.attributes if let params = matcher.attemptMatch(attributes: attributes) { let globalParamsDict = matcher.globalQueryParams(queryParams: attributes.globalQueryParams) let route = decodeRoute(params: params, decoder: routeMapping.decoder) let globalParams = decodeGlobalParams(params: globalParamsDict) if let route = route, let globalParams = globalParams { return RouteResponse(route: route, globalParams: globalParams) } } } return nil } private func decodeRoute(params: [String: Any], decoder: ([String: Any]) throws -> CorridorRoute) -> CorridorRoute? { do { let route = try decoder(params) return route } catch { print(error) return nil } } private func decodeGlobalParams(params: [String: Any]) -> CorridorGlobalParams? { guard let globalQueryOptionalParamsDecoder = globalQueryOptionalParamsDecoder else { return CorridorGlobalParamsNone() } do { let globalParams = try globalQueryOptionalParamsDecoder(params) return globalParams } catch { print(error) return nil } } } /** Serializes a struct that conforms to CorridorRoute based on a dictionary of key-value pairs - parameter params: A dictionary of key-value pairs - parameter type: a struct type that conforms to CorridorRoute - returns: A serialized struct of type T */ /// - Throws: Serialization error if the struct can't be serialized public func corridorResponse<T: CorridorRoute>(_ params: [String: Any], _ type: T.Type) throws -> T { let data = try JSONSerialization.data(withJSONObject: params, options: []) return try JSONDecoder().decode(type, from: data) } /** Serializes a struct that conforms to CorridorGlobalParams based on a dictionary of key-value pairs - parameter params: A dictionary of key-value pairs - parameter type: a struct type that conforms to CorridorGlobalParams - returns: A serialized struct of type T */ /// - Throws: Serialization error if the struct can't be serialized public func corridorGlobalParamsResponse<T: CorridorGlobalParams>(_ params: [String: Any], _ type: T.Type) throws -> T { let data = try JSONSerialization.data(withJSONObject: params, options: []) return try JSONDecoder().decode(type, from: data) }
true
c6f6973f40f9a0a0a3328954e48730e8b39d297b
Swift
alyona-bachurina/Configurist
/Example/Tests/Tests.swift
UTF-8
1,281
2.796875
3
[ "MIT" ]
permissive
// // ConfiguristTests.swift // ConfiguristTests // // Created by Alyona on 11/16/15. // Copyright © 2015 Alyona Bachurina. All rights reserved. // import XCTest @testable import Configurist class Tests: XCTestCase { func testPlistConfiguration() { let c = Configurist(names: ["config_1", "config_2", "config_3"], bundle: Bundle(for: type(of: self))) testConfigurist(c) } func testJSONConfiguration() { let c = Configurist(names: ["config_1a", "config_2a", "config_3a"], bundle: Bundle(for: type(of: self))) testConfigurist(c) } func testConfigurist(_ c:Configurist){ XCTAssertEqual(c.string("base.url"), "http://github.com") XCTAssertEqual(c.colorRGBA("color.red.rgba"), UIColor.red) XCTAssertEqual(c.colorRGB("color.red.rgb"), UIColor.red) XCTAssertEqual(c.number("magic.number"), 100500) XCTAssertEqual(c.array("array").count, 5) XCTAssertEqual( (c.array("array")[1] as! String) , "Italy") XCTAssertNotNil(c.dictionary("account")) XCTAssertNotNil(c.dictionary("account")["_id"] as? String) XCTAssertEqual(c.string("one.more.string"), "Some another string") } }
true
17d93285dc0d3d802a85c3ffdbd52d49fb40ec2a
Swift
Cookiezby/iOSDC2018APP
/iOSDC2018/WebVC/WebViewController.swift
UTF-8
1,171
2.640625
3
[]
no_license
// // WebInfoViewController.swift // iOSDC2018 // // Created by cookie on 2018/8/19. // Copyright © 2018 zhubingyi. All rights reserved. // import Foundation import UIKit import WebKit final class WebInfoViewController: UIViewController { private let webView: WKWebView = { let view = WKWebView() return view }() let url: URL init(url: URL) { self.url = url super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(webView) autoLayout() webView.load(URLRequest(url: url)) webView.reactive.producer(forKeyPath: "title").take(during: reactive.lifetime).startWithValues { [weak self] (value) in if let title = value as? String { self?.navigationItem.title = title } } } private func autoLayout() { webView.snp.makeConstraints{ $0.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
a9aff22d6ce569e7e247b953287b0c11034a8e07
Swift
amolon615/KavSoft-Tutorials-iOS
/PhoneAuthFirebase/PhoneAuthFirebase/ViewModel/LoginViewModel.swift
UTF-8
2,355
2.953125
3
[]
no_license
// // LoginViewModel.swift // PhoneAuthFirebase // // Created by Ginger on 23/01/2021. // import SwiftUI import Firebase class LoginViewModel: ObservableObject { @Published var phNo = "" @Published var code = "" // Getting country Phone Code // DataModel For Error View @Published var errorMsg = "" @Published var error = false // storing CODE for verification @Published var CODE = "" @Published var gotoVerify = false // User Logged Status @AppStorage("log_Status") var status = false // Loading View @Published var loading = false func getCountryCode() -> String { let regionCode = Locale.current.regionCode ?? "" return countries[regionCode] ?? "" } // sending Code To User func sendCode() { // enabling testing code // disable when you need to test with real device Auth.auth().settings?.isAppVerificationDisabledForTesting = true let number = "+\(getCountryCode())\(phNo)" PhoneAuthProvider.provider().verifyPhoneNumber(number, uiDelegate: nil) { (CODE, err) in if let error = err { self.errorMsg = error.localizedDescription withAnimation { self.error.toggle() } return } self.CODE = CODE ?? "" self.gotoVerify = true } } func verifyCode() { let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.CODE, verificationCode: code) loading = true Auth.auth().signIn(with: credential) { (result, err) in self.loading = false if let error = err { self.errorMsg = error.localizedDescription withAnimation { self.error.toggle() } return } // else, user logged in successfully withAnimation { self.status = true } } } func requestCode() { sendCode() withAnimation { self.errorMsg = "Code Sent Successfully." self.error.toggle() } } }
true
6ef526903726b58d77c5fa9d22dedeb8f38c5303
Swift
n-e-o-n-7/AetherSpace
/iOS/Helpers/SlideOverCard.swift
UTF-8
2,197
3
3
[]
no_license
// // SlideOverCard.swift // Aether // // Created by 许滨麟 on 2021/3/21. // import SwiftUI struct SlideOverCard<Content: View>: View { @GestureState private var dragState = DragState.inactive @State var position = CardPosition.top var content: () -> Content var body: some View { let drag = DragGesture() .updating($dragState) { drag, state, transaction in state = .dragging(translation: drag.translation) } .onEnded(onDragEnded) return Group { HandleView() self.content() } .frame(height: UIScreen.main.bounds.height) .background(Color.white) .cornerRadius(10.0) .shadow(color: Color(.sRGBLinear, white: 0, opacity: 0.13), radius: 10.0) .offset(y: self.position.rawValue + self.dragState.translation.height) .animation( self.dragState.isDragging ? nil : .interpolatingSpring(stiffness: 300.0, damping: 30.0, initialVelocity: 10.0) ) .gesture(drag) } private func onDragEnded(drag: DragGesture.Value) { let verticalDirection = drag.predictedEndLocation.y - drag.location.y let cardTopEdgeLocation = self.position.rawValue + drag.translation.height let positionAbove: CardPosition let positionBelow: CardPosition let closestPosition: CardPosition if cardTopEdgeLocation <= CardPosition.middle.rawValue { positionAbove = .top positionBelow = .middle } else { positionAbove = .middle positionBelow = .bottom } if (cardTopEdgeLocation - positionAbove.rawValue) < (positionBelow.rawValue - cardTopEdgeLocation) { closestPosition = positionAbove } else { closestPosition = positionBelow } if verticalDirection > 0 { self.position = positionBelow } else if verticalDirection < 0 { self.position = positionAbove } else { self.position = closestPosition } } } enum CardPosition: CGFloat { case top = 100 case middle = 500 case bottom = 850 } enum DragState { case inactive case dragging(translation: CGSize) var translation: CGSize { switch self { case .inactive: return .zero case .dragging(let translation): return translation } } var isDragging: Bool { switch self { case .inactive: return false case .dragging: return true } } }
true
222a3c18b1816092365a2e3529ab5fb735ca6e18
Swift
arturlector/client-server-app
/client-server/client-server/Delegation/FruitsViewController.swift
UTF-8
1,457
2.90625
3
[]
no_license
// // FruitsViewController.swift // client-server // // Created by Artur Igberdin on 07.04.2021. // import UIKit protocol FruitsViewControllerDelegate: class { func fruitDidSelect(_ fruit: String) } class FruitsViewController: UITableViewController { weak var delegate: FruitsViewControllerDelegate? let fruits = ["Яблоко", "Банан", "Киви"] // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "AppleCell") } // MARK: - UITableViewDatasource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fruits.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "AppleCell", for: indexPath) cell.textLabel?.text = fruits[indexPath.row] return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let fruit = fruits[indexPath.row] delegate?.fruitDidSelect(fruit) print(fruit) self.navigationController?.popViewController(animated: true) } }
true