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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1b600d5562decb579e88fb8083f2875e2bf00447
|
Swift
|
MatthewRamos1/NYTBooks-Group-Project
|
/NYTBooks-Group-Project/Models/UserPreference.swift
|
UTF-8
| 1,206
| 3.03125
| 3
|
[] |
no_license
|
//
// UserPreference.swift
// NYTBooks-Group-Project
//
// Created by David Lin on 2/14/20.
// Copyright © 2020 Matthew Ramos. All rights reserved.
//
import Foundation
struct UserKey {
static let selectedList = "News Section"
static let selectedIndex = "Picked Index"
}
protocol UserPreferenceDelegate: AnyObject {
func didChangeBooksSection(_ userPreference: UserPreference, selectedList: String)
func didChangeIndex(_ userPreference: UserPreference, index: Int)
}
final class UserPreference {
weak var delegate: UserPreferenceDelegate?
public func getSectionName() -> String? {
return UserDefaults.standard.object(forKey: UserKey.selectedList) as? String
}
public func setSectionName(_ selectedList: String) {
UserDefaults.standard.set(selectedList, forKey: UserKey.selectedList)
delegate?.didChangeBooksSection(self, selectedList: selectedList)
}
public func getIndex() -> Int? {
return UserDefaults.standard.object(forKey: UserKey.selectedIndex) as? Int
}
public func setIndex(_ index: Int) {
UserDefaults.standard.set(index, forKey: UserKey.selectedIndex)
delegate?.didChangeIndex(self, index: index)
}
}
| true
|
227e9c450ba4652c8f2d8b10c3258899d9f806c7
|
Swift
|
vikasvaish21/ios-nanodegree-main-projects
|
/MarvelComics/MarvelComics/API/MarvelApiContent.swift
|
UTF-8
| 4,574
| 2.71875
| 3
|
[] |
no_license
|
//
// MarvelApi.swift
// MarvelComics
//
// Created by vikas on 05/08/19.
// Copyright © 2019 project1. All rights reserved.
//
import Foundation
enum MarvelApiContent{
case getCharacters(_ nameStartsWith:String?,_ offset: Int)
case downloadThumb(_ fromUrl: String)
case getHeroDetail(_ type: HeroDetailsType,_ heroID: Int,_ offset: Int)
}
extension MarvelApiContent: EndPointsType{
var simpleBaseUrl:String{
switch MarvelAPIManager.enviroment {
case .production:
return Constants.BaseURLProduction
case .qa:
return Constants.BaseURLQA
case .staging:
return Constants.BaseURLStaging
}
}
public var baseURL: URL{
var baseURL = ""
switch self {
case .downloadThumb(let url):
baseURL = url
default:
baseURL = simpleBaseUrl
}
guard let url = URL(string: baseURL) else {
fatalError("baseURL could not be configured.")
}
return url
}
public var path: String{
switch self {
case .getCharacters:
return Constants.PathsMethods.Characters
case .getHeroDetail(let type, let heroID, _):
return Constants.PathsMethods.HeroArtifacts.replacingOccurrences(of: "{id}", with: "\(heroID)").replacingOccurrences(of: "{type}", with: "\(type.path)")
default:
return ""
}
}
public var httpMethod: HTTPMethod{
switch self {
default:
return .get
}
}
public var task: HTTPTask{
let ts = String(Date().timeIntervalSince1970)
let commmonUrlParameters: parameters = [
Constants.ParametersKeys.Ts: ts,
Constants.ParametersKeys.APIKey: Constants.ParametersValues.APIKey,
Constants.ParametersKeys.hash: "\(ts)\(MarvelApiContent.Constants.PrivateKey)\(MarvelApiContent.Constants.PublicKey)".MD5 ?? "",
Constants.ParametersKeys.Limit: Constants.ParametersValues.Limit
]
switch self {
case .getCharacters(let nameStartWith, let offset):
var urlParameters = commmonUrlParameters
urlParameters[Constants.ParametersKeys.Offset] = offset
if let nameStartWith = nameStartWith{
urlParameters[Constants.ParametersKeys.NameStartsWith] = nameStartWith
}
return .requestParameters(bodyParameters: nil, urlParameters: urlParameters)
case .getHeroDetail:
return .requestParameters(bodyParameters: nil, urlParameters: commmonUrlParameters)
case .downloadThumb(let url):
return .download(url)
}
}
public var headers: HTTPHeaders? {
return nil
}
}
extension MarvelApiContent {
struct Constants {
// MARK: - URL constants
static let APIScheme = "https"
static let APIHost = "gateway.marvel.com"
static let APIPath = "/v1/public"
static let BaseURLProduction = "\(APIScheme)://\(APIHost)\(APIPath)"
static let BaseURLQA = ""
static let BaseURLStaging = ""
static let ThumbnailStandardSize = "standard_fantastic"
static let ThumbnailPortraitSiza = "portrait_uncanny"
static let ImageNotAvailable = "image_not_available"
static let InfiniteScrollLimiar = 5
static let DateFormat = "yyyy-MM-dd'T'HH:mm:ss-SSSS"
// MARK: - Request constants
static let PublicKey = "1b2a9f1fcda6b09b16e40484559b4c49"
static let PrivateKey = "d1eb863f2affd1ef594c8f302adba24dc21cd2b3"
// MARK: - Paths Methods
struct PathsMethods {
static let Characters = "/characters"
static let HeroArtifacts = "/characters/{id}/{type}"
}
// MARK: - Parameters Keys
struct ParametersKeys {
static let Ts = "ts"
static let APIKey = "apikey"
static let hash = "hash"
static let NameStartsWith = "nameStartsWith"
static let Offset = "offset"
static let Limit = "limit"
}
// MARK: - Parameters Values
struct ParametersValues {
static let APIKey = PublicKey
static let Limit = 20
}
// MARK: - Response Values
struct ResponseValues {
static let OKStatus = "Ok"
}
}
}
| true
|
42f00ed658fba8f394b42733a4473a6005e6320d
|
Swift
|
lionelmichaud/Patrimoine
|
/Shared/Model/User-Model/Family/LifeEvent.swift
|
UTF-8
| 4,899
| 3.296875
| 3
|
[] |
no_license
|
//
// LifeEvent.swift
// Patrimoine
//
// Created by Lionel MICHAUD on 29/05/2020.
// Copyright © 2020 Lionel MICHAUD. All rights reserved.
//
import Foundation
// MARK: - Limite temporelle fixe ou liée à un événement de vie
/// Limite temporelle d'une dépense: début ou fin.
/// Date fixe ou calculée à partir d'un éventuel événement de vie d'une personne
struct DateBoundary: Hashable, Codable {
// MARK: - Static Properties
static var personEventYearProvider: PersonEventYearProvider!
static let empty: DateBoundary = DateBoundary()
// MARK: - Static Methods
/// Dependency Injection: Setter Injection
static func setPersonEventYearProvider(_ personEventYearProvider : PersonEventYearProvider) {
DateBoundary.personEventYearProvider = personEventYearProvider
}
// MARK: - Properties
// date fixe ou calculée à partir d'un éventuel événement de vie d'une personne
var fixedYear : Int = 0
// non nil si la date est liée à un événement de vie d'une personne
var event : LifeEvent?
// personne associée à l'évenement
var name : String?
// groupe de personnes associées à l'événement
var group : GroupOfPersons?
// date au plus tôt ou au plus tard du groupe
var order : SoonestLatest?
// MARK: - Computed Properties
// date fixe ou calculée à partir d'un événement de vie d'une personne ou d'un groupe
var year : Int? {
if let lifeEvent = self.event {
// la borne temporelle est accrochée à un événement
if let group = group {
if let order = order {
return DateBoundary.personEventYearProvider.yearOf(lifeEvent : lifeEvent,
for : group,
order : order)
} else {
return nil
}
} else {
// rechercher la personne
if let theName = name,
let year = DateBoundary.personEventYearProvider.yearOf(lifeEvent: lifeEvent,
for: theName) {
// rechercher l'année de l'événement pour cette personne
return year
} else {
// on ne trouve pas le nom de la personne dans la famille
return nil
}
}
} else {
// pas d'événement, la date est fixe
return fixedYear
}
}
}
extension DateBoundary: CustomStringConvertible {
var description: String {
if let lifeEvent = self.event {
return lifeEvent.description
} else {
return String(fixedYear)
}
}
}
// MARK: - Evénement de vie
enum LifeEvent: String, PickableEnum, Codable, CustomStringConvertible {
case debutEtude = "Début des études supérieurs"
case independance = "Indépendance financière"
case cessationActivite = "Fin d'activité professionnelle"
case liquidationPension = "Liquidation de pension"
case dependence = "Dépendance"
case deces = "Décès"
// MARK: - Computed Properties
var pickerString: String {
return self.rawValue
}
var description: String {
pickerString
}
// True si l'événement est spécifique des Adultes
var isAdultEvent: Bool {
switch self {
case .cessationActivite,
.liquidationPension,
.dependence:
return true
default:
return false
}
}
// True si l'événement est spécifique des Enfant
var isChildEvent: Bool {
switch self {
case .debutEtude,
.independance:
return true
default:
return false
}
}
}
// MARK: - Groupes de personnes
enum GroupOfPersons: String, PickableEnum, Codable, CustomStringConvertible {
case allAdults = "Tous les Adultes"
case allChildrens = "Tous les Enfants"
case allPersons = "Toutes les Personnes"
// MARK: - Computed Properties
var pickerString: String {
return self.rawValue
}
var description: String {
pickerString
}
}
// MARK: - Date au plus tôt ou au plus tard
enum SoonestLatest: String, PickableEnum, Codable, CustomStringConvertible {
case soonest = "Date au plus tôt"
case latest = "Date au plus tard"
// MARK: - Computed Properties
var pickerString: String {
return self.rawValue
}
var description: String {
pickerString
}
}
| true
|
43286eaf8ca3efe9b80f87a52a512e7b1f607db8
|
Swift
|
johndpope/bangers_and_mash
|
/Bangers and MashTests/Recording/RecordButtonSpec.swift
|
UTF-8
| 7,106
| 2.703125
| 3
|
[] |
no_license
|
import UIKit
import Quick
import Nimble
import Fleet
@testable import Bangers_and_Mash
class RecordButtonSpec: QuickSpec {
override func spec() {
describe("RecordButton") {
var subject: RecordButton!
var animator: FakeAnimator!
beforeEach {
subject = RecordButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
animator = FakeAnimator()
subject.animator = animator
}
describe("drawing the button") {
var circleBorder: CALayer!
beforeEach {
circleBorder = subject.layer.sublayers?.first
}
it("makes the background color clear") {
expect(subject.backgroundColor).to(equal(UIColor.clear))
}
it("draws the button") {
expect(subject.layer.sublayers?.count).to(equal(1))
}
describe("making the circle border") {
it("has a clear background color") {
expect(circleBorder.backgroundColor).to(equal(UIColor.clear.cgColor))
}
it("creates a border") {
expect(circleBorder.borderColor).to(equal(UIColor.white.cgColor))
expect(circleBorder.borderWidth).to(equal(RecordButton.borderWidth))
}
it("sets the bounds to be the same as the button") {
expect(circleBorder.bounds).to(equal(subject.bounds))
}
it("positions it in the center of the view") {
expect(circleBorder.position).to(equal(CGPoint(x: 15, y: 15)))
}
it("creates a circle with the corner radius") {
expect(circleBorder.cornerRadius).to(equal(15))
}
}
describe("indicating recording is happening") {
var recordCircle: UIView!
beforeEach {
subject.indicateRecording()
recordCircle = subject.subviews.first
}
it("makes a red recording circle") {
expect(subject.subviews.count).to(equal(1))
}
it("animates with an ease out") {
expect(animator.capturedDurationForAnimate).to(equal(RecordButton.recordGrowDuration))
expect(animator.capturedDelayForAnimate).to(equal(0))
expect(animator.capturedOptionsForAnimate).to(equal(UIViewAnimationOptions.curveEaseOut))
}
describe("red record circle") {
it("is red and centered in the middle of the button") {
expect(recordCircle.backgroundColor).to(equal(UIColor.red))
expect(recordCircle.center).to(equal(CGPoint(x: 15, y: 15)))
}
it("clips to bounds") {
expect(recordCircle.clipsToBounds).to(beTrue())
}
it("starts small") {
expect(recordCircle.frame.size.width).to(equal(1))
expect(recordCircle.frame.size.height).to(equal(1))
}
it("sets the corner radius to be half its width") {
expect(recordCircle.layer.cornerRadius).to(equal(0.5))
}
}
describe("animating") {
beforeEach {
animator.capturedAnimationsForAnimate?()
}
it("scales the record button") {
expect(recordCircle.frame.size.width).to(beCloseTo(RecordButton.recordButtonScale))
expect(recordCircle.frame.size.height).to(beCloseTo(RecordButton.recordButtonScale))
}
it("scales the circle border") {
expect(circleBorder.frame.size.width).to(beCloseTo(RecordButton.outerBorderScale * 30))
expect(circleBorder.frame.size.height).to(beCloseTo(RecordButton.outerBorderScale * 30))
}
it("adjusts the border width") {
expect(circleBorder.borderWidth).to(beCloseTo(RecordButton.borderWidth / RecordButton.outerBorderScale))
}
describe("indicating recording finished") {
beforeEach {
animator.reset()
subject.indicateRecordingFinished()
}
it("animates") {
expect(animator.capturedDurationForAnimate).to(equal(RecordButton.recordShrinkDuration))
expect(animator.capturedDelayForAnimate).to(equal(0))
expect(animator.capturedOptionsForAnimate).to(equal(UIViewAnimationOptions.curveEaseOut))
}
describe("animating") {
beforeEach {
animator.capturedAnimationsForAnimate?()
}
it("scales the record circle back to its normal size") {
expect(recordCircle.frame.size.width).to(beCloseTo(1))
expect(recordCircle.frame.size.height).to(beCloseTo(1))
}
it("scales the border back to its normal size") {
expect(circleBorder.frame.size.width).to(beCloseTo(30))
expect(circleBorder.frame.size.height).to(beCloseTo(30))
}
it("sets the border width back") {
expect(circleBorder.borderWidth).to(equal(RecordButton.borderWidth))
}
describe("animation completion") {
beforeEach {
animator.capturedCompletionForAnimate?(true)
}
it("removes the record button from the superview") {
expect(subject.subviews.count).to(equal(0))
}
}
}
}
}
}
}
}
}
}
| true
|
e4a99f6f71eaeaae3834d2d5dd57965ce632bc2a
|
Swift
|
marutharajk/flickr
|
/ImageDetector/Extension/Font+Extension.swift
|
UTF-8
| 3,478
| 2.90625
| 3
|
[] |
no_license
|
//
// Font+Extension.swift
// ImageDetector
//
// Created by Marutharaj K on 17/09/21.
//
import SwiftUI
/// Extends String to define font name
private extension String {
static var sfProTextBold = "SFProText-Bold"
static var sfProTextMedium = "SFProText-Medium"
static var sfProTextLight = "SFProText-Light"
static var sfProTextRegular = "SFProText-Regular"
static var sfProTextSemibold = "SFProText-Semibold"
static var sfProTextThin = "SFProText-Thin"
static var sfProDisplayBold = "SFProDisplay-Bold"
static var sfProDisplayMedium = "SFProDisplay-Medium"
}
// MARK: - Type - Font+Extension -
/// Extends Font to return custom font as Font
public extension Font {
static func sfProTextBold(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProTextBold, size: size)
}
static func sfProTextMedium(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProTextMedium, size: size)
}
static func sfProTextLight(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProTextLight, size: size)
}
static func sfProTextRegular(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProTextRegular, size: size)
}
static func sfProTextSemibold(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProTextSemibold, size: size)
}
static func sfProDisplayBold(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProDisplayBold, size: size)
}
static func sfProDisplayMedium(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProDisplayMedium, size: size)
}
static func sfProTextThin(_ size: CGFloat = 12.0) -> Font {
return Font.custom(.sfProTextThin, size: size)
}
}
/// Extends UIFont to return custom font as UIFont
public extension UIFont {
static func getFont(name: String, size: CGFloat) -> UIFont {
return UIFont.init(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProTextBold(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProTextBold, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProTextMedium(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProTextMedium, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProTextLight(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProTextLight, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProTextRegular(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProTextRegular, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProTextSemibold(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProTextSemibold, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProDisplayBold(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProDisplayBold, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProDisplayMedium(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProDisplayMedium, size: size) ?? UIFont.systemFont(ofSize: size)
}
static func sfProTextThin(_ size: CGFloat = 12.0) -> UIFont {
return UIFont.init(name: .sfProTextThin, size: size) ?? UIFont.systemFont(ofSize: size)
}
}
| true
|
179bce1f141e7f37f3491fcbb60eb209e8a8b841
|
Swift
|
dmaia17/liveemcasa
|
/liveemcasa/Liveemcasa/Modules/Live/LivesWireframe.swift
|
UTF-8
| 1,788
| 2.6875
| 3
|
[] |
no_license
|
//
// LivesWireframe.swift
// Liveemcasa
//
// Created by Daniel Maia dos Passos on 04/04/20.
// Copyright (c) 2020 Daniel Maia dos Passos. All rights reserved.
//
//
import UIKit
final class LivesWireframe: BaseWireframe {
// MARK: - Private properties -
private var moduleViewController = LivesViewController(nibName: nil, bundle: nil)
// MARK: - Module setup -
func configureModule(with viewController: LivesViewController) {
moduleViewController = viewController
/*let interactor = LivesInteractor()
let presenter = LivesPresenter(view: viewController, interactor: interactor)
viewController.presenter = presenter */
}
// MARK: - Transitions -
func show(with transition: Transition, animated: Bool = true) {
/* configureModule(with: moduleViewController)
show(moduleViewController, with: transition, animated: animated) */
}
// MARK: - Private Routing -
private func showConnectionErrorAlert() {
}
private func showErrorAlert() {
}
private func goToDetails() {
}
private func openUrlLive(urlLive: String) {
OpenBrowser.sharedInstance.openBrowser(viewController: self.moduleViewController,
title: LiveStrings.titleActionSheets,
message: "",
url: urlLive)
}
}
// MARK: - Extensions -
extension LivesWireframe: LivesWireframeInterface {
func navigate(to option: LivesNavigationOption) {
switch option {
case .showConnectionErrorAlert:
self.showConnectionErrorAlert()
case .showErrorAlert:
self.showErrorAlert()
case .goToDetails:
self.goToDetails()
case .openUrlLive(let urlLive):
self.openUrlLive(urlLive: urlLive)
}
}
}
| true
|
355042e4da049fad1216d6b326dd8dc3fa25abd5
|
Swift
|
ShashikantBhadke/DailyLogs
|
/DailyLogs/Controller/RecordsController/Model/SpendingDetailsModel.swift
|
UTF-8
| 587
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// SpendingDetailsModel.swift
// DailyLogs
//
// Created by Shashikant Bhadke on 30/06/21.
//
import UIKit
import RxDataSources
struct SpendingDetailsModel {
var date = ""
var balance = ""
var credited = ""
var debited = ""
var balanceColor = UIColor.black
var totalBalance = ""
var totalBalanceColor = UIColor.black
}
struct TableViewSection {
var header: String
var items: [Item]
}
extension TableViewSection: SectionModelType {
typealias Item = Any
init(original: TableViewSection, items: [Item]) {
self = original
self.items = items
}
}
| true
|
8f44921d3a9b8d8e2109fae3439b519d6a819a4c
|
Swift
|
FoodForTech/eWeekChallenges
|
/eChallenge1.playground/Contents.swift
|
UTF-8
| 1,345
| 4.125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
class NamedOne {
var firstName: String
var lastName: String
var fullName: String {
get {
return "\(self.firstName) \(self.lastName)"
}
set(newFullName) {
let parsedFullName = newFullName.characters.split{$0 == " "}.map(String.init)
if parsedFullName.count > 1 {
self.firstName = parsedFullName[0]
self.lastName = parsedFullName[1]
}
}
}
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
self.fullName = firstName + lastName;
}
}
// testing object
var namedOne = NamedOne(firstName: "Naomi", lastName: "Wang")
namedOne.firstName = "John"
namedOne.lastName = "Doe"
print(namedOne.firstName)
print(namedOne.lastName)
print(namedOne.fullName)
namedOne.fullName = "Bill Smith"
namedOne.firstName // -> "Bill"
namedOne.lastName // -> "Smith"
print(namedOne.firstName)
print(namedOne.lastName)
print(namedOne.fullName)
namedOne.fullName = "Tom" // -> no : lastName missing
namedOne.fullName = "TomDonnovan" // -> no : no space between first & last names
namedOne.fullName // -> "Bill Smith" (unchanged)
print(namedOne.firstName)
print(namedOne.lastName)
print(namedOne.fullName)
| true
|
fb0f466eb725c347685f5cefb79353fc8ee04e03
|
Swift
|
jwqfqf21231231/Rewards-iOS
|
/Reward/Reward/Models/NotificationModel.swift
|
UTF-8
| 992
| 2.625
| 3
|
[] |
no_license
|
//
// NotificationModel.swift
// Reward
//
// Created by Darshan on 29/04/21.
//
import UIKit
import RealmSwift
import ObjectMapper
class NotificationModel: Object, Mappable {
@objc dynamic var id: Int = 0
@objc dynamic var body: String?
@objc dynamic var seen: Bool = false
@objc dynamic var recipientId: Int = 0
@objc dynamic var alertableType: String?
@objc dynamic var alertableId: Int = 0
@objc dynamic var createdAt: Date?
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
body <- map["body"]
seen <- map["seen"]
recipientId <- map["recipient_id"]
alertableType <- map["alertable_type"]
alertableId <- map["alertable_id"]
createdAt <- (map["created_at"], CustomDateFormatTransform(format: .dateWithMillisecondAndTimeZone))
}
override static func primaryKey() -> String? {
return "id"
}
}
| true
|
cfc07e9e8818016c8cd599878047a1a378ed154c
|
Swift
|
calesce/star-on-github
|
/star-on-github/Logo.swift
|
UTF-8
| 1,204
| 2.734375
| 3
|
[] |
no_license
|
//
// Logo.swift
// star-on-github
//
// Created by Cale Newman on 11/7/16.
// Copyright © 2016 newman.cale. All rights reserved.
//
import UIKit
class Logo: UIView {
override func draw(_ rect: CGRect) {
let strokeColor = UIColor(red: 0.071, green: 0.200, blue: 0.289, alpha: 1.000)
let fillColor = UIColor(red: 0.071, green: 0.200, blue: 0.289, alpha: 1.000)
//// Star Drawing
let starPath = UIBezierPath()
starPath.move(to: CGPoint(x: 115, y: 45))
starPath.addLine(to: CGPoint(x: 137.05, y: 89.66))
starPath.addLine(to: CGPoint(x: 186.33, y: 96.82))
starPath.addLine(to: CGPoint(x: 150.67, y: 131.59))
starPath.addLine(to: CGPoint(x: 159.08, y: 180.68))
starPath.addLine(to: CGPoint(x: 115, y: 157.51))
starPath.addLine(to: CGPoint(x: 70.92, y: 180.68))
starPath.addLine(to: CGPoint(x: 79.33, y: 131.59))
starPath.addLine(to: CGPoint(x: 43.67, y: 96.82))
starPath.addLine(to: CGPoint(x: 92.95, y: 89.66))
starPath.close()
fillColor.setFill()
starPath.fill()
strokeColor.setStroke()
starPath.lineWidth = 37.62
starPath.stroke()
}
}
| true
|
3a1b403b1e6751af237b4f9f17a1838ada2488cb
|
Swift
|
HugoSay/VLabTest
|
/VLabsTest/Scenes/User/PostCollecitonViewCell.swift
|
UTF-8
| 2,726
| 2.59375
| 3
|
[] |
no_license
|
//
// PostCollecitonViewCell.swift
// VLabsTest
//
// Created by Hugo Saynac on 27/08/2019.
// Copyright © 2019 HugoCorp. All rights reserved.
//
import UIKit
class PostCollectionViewCell: UICollectionViewCell {
let titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont.preferredFont(forTextStyle: .body)
return label
}()
let bodyLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont.preferredFont(forTextStyle: .caption2)
return label
}()
fileprivate func addSeparatorView() {
let borderView = UIView()
contentView.addSubview(borderView)
borderView.anchor(bottom: contentView.safeBottomAnchor,
leading: contentView.safeLeadingAnchor, leadingConstant: 12,
trailing: contentView.safeTrailingAnchor,
height: 1 / UIScreen.main.scale)
borderView.backgroundColor = .lightGray
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = .white
contentView.addSubview(titleLabel)
contentView.addSubview(bodyLabel)
titleLabel.anchor(top: contentView.topAnchor,
leading: contentView.safeLeadingAnchor, leadingConstant: 12,
trailing: contentView.safeTrailingAnchor, trailingConstant: 8)
bodyLabel.anchor(top: titleLabel.bottomAnchor, bottom: contentView.bottomAnchor, bottomConstant: 8, leading: titleLabel.leadingAnchor, trailing: titleLabel.trailingAnchor)
addSeparatorView()
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutIfNeeded()
let layoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
layoutAttributes.bounds.size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)
return layoutAttributes
}
required init?(coder aDecoder: NSCoder) { fatalError("\(#function) not implemented") }
func configure(with post: Post) {
titleLabel.text = post.title
bodyLabel.text = post.body
}
}
class UserLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
let width = collectionView.bounds.width
self.estimatedItemSize = CGSize(width: width, height: 200)
headerReferenceSize = CGSize(width: 100, height: 60)
}
}
| true
|
480c2c2fc4e1e0cba3902f104fe5f1d353091a82
|
Swift
|
molhamstein/GlobaPagesIOS
|
/GlobalPages/Classes/Models/MarketProduct.swift
|
UTF-8
| 4,324
| 2.546875
| 3
|
[] |
no_license
|
//
// MarketProduct.swift
// GlobalPages
//
// Created by Abd Hayek on 12/31/19.
// Copyright © 2019 GlobalPages. All rights reserved.
//
import Foundation
import SwiftyJSON
public class MarketProduct: BaseModel {
var titleEn: String?
var titleAr: String?
var descriptionAr: String?
var descriptionEn: String?
var ownerID: String?
var businessID: String?
var status: String?
var price: Int?
var cityID: String?
var locationID: String?
var categoryID: String?
var subCategoryID: String?
var creationDate: Date?
var images: [String]?
var category : Category?
var subCategory : Category?
var city: City?
var location: City?
var owner : Owner?
var bussiness : Bussiness?
var tags: [Tag]?
public var title: String? {
return AppConfig.currentLanguage == .arabic ? titleAr : titleEn
}
public var description: String? {
return AppConfig.currentLanguage == .arabic ? descriptionAr : descriptionEn
}
override init() {
super.init()
}
required public init(json: JSON) {
super.init(json: json)
if let value = json["titleEn"].string {titleEn = value}
if let value = json["titleAr"].string {titleAr = value}
if let value = json["descriptionAr"].string {descriptionAr = value}
if let value = json["descriptionEn"].string {descriptionEn = value}
if let value = json["ownerId"].string {ownerID = value}
if let value = json["businessId"].string {businessID = value}
if let value = json["status"].string {status = value}
if let value = json["price"].int {price = value}
if let value = json["cityId"].string {cityID = value}
if let value = json["locationId"].string {locationID = value}
if let value = json["categoryId"].string {categoryID = value}
if let value = json["subCategoryId"].string {subCategoryID = value}
if let strDate = json["creationDate"].string {
creationDate = DateHelper.getDateFromISOString(strDate)
}
if let value = json["media"].array {self.images = value.map({$0.stringValue})}
if (json["category"] != JSON.null) { category = Category(json: json["category"]) }
if (json["subCategory"] != JSON.null) { subCategory = Category(json: json["subCategory"]) }
if json["city"] != JSON.null { city = City(json:json["city"]) }
if json["location"] != JSON.null { location = City(json:json["location"]) }
if json["owner"] != JSON.null { owner = Owner(json:json["owner"]) }
if json["business"] != JSON.null { bussiness = Bussiness(json:json["business"]) }
if let array = json["tags"].array { tags = array.map{Tag(json:$0)} }
}
override public func dictionaryRepresentation() -> [String:Any] {
var dictionary = super.dictionaryRepresentation()
dictionary["titleEn"] = titleEn
dictionary["titleAr"] = titleAr
dictionary["descriptionAr"] = descriptionAr
dictionary["descriptionEn"] = descriptionEn
dictionary["ownerId"] = ownerID
dictionary["businessId"] = businessID
dictionary["status"] = status
dictionary["price"] = price
dictionary["cityId"] = cityID
dictionary["locationId"] = locationID
dictionary["categoryId"] = categoryID
dictionary["subCategoryId"] = subCategoryID
dictionary["creationDate"] = self.creationDate != nil ? DateHelper.getStringFromDate(self.creationDate!) : ""
dictionary["media"] = images
if let value = city { dictionary["city"] = value.dictionaryRepresentation()}
if let value = location { dictionary["location"] = value.dictionaryRepresentation()}
if owner != nil{dictionary["owner"] = self.owner?.dictionaryRepresentation()}
if category != nil {dictionary["category"] = self.category?.dictionaryRepresentation()}
if subCategory != nil {dictionary["subCategory"] = self.subCategory?.dictionaryRepresentation()}
if bussiness != nil {dictionary["business"] = self.bussiness?.dictionaryRepresentation()}
if let value = tags { dictionary["tags"] = value.map({$0.dictionaryRepresentation()}) }
return dictionary
}
}
| true
|
0d95f9d768abfac0786e567f7fa0f0edac4a2a58
|
Swift
|
mapcodingtest/mapquestservice
|
/MapQuestService/NetworkService.swift
|
UTF-8
| 1,865
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// NetworkService.swift
// MapQuestService
//
// Created by Mac on 9/1/18.
// Copyright © 2018 Mac. All rights reserved.
//
import Foundation
public class NetworkService {
static let baseUrl = "https://www.mapquestapi.com/geocoding/v1/address?key=6UhCWA07EmwxAaPocXGrWF2hUyDJIR1l&location="
public class func getLocations(queryLocation: String, completion: @escaping ([Location]?, Error?) -> ()) {
let urlAsString = "\(baseUrl)\(queryLocation)"
guard let url = URL(string: urlAsString) else {
completion(nil, NetworkErrors.badUrl)
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) {
(data, response, error) in
if let error = error {
completion(nil, error)
return
}
guard let response = response as? HTTPURLResponse else {
completion(nil, NetworkErrors.badResponse)
return
}
guard response.statusCode == 200 else {
completion(nil, NetworkErrors.httpError(code: response.statusCode))
return
}
guard let data = data else {
completion(nil, NetworkErrors.noData)
return
}
do {
let resultArray = try JSONDecoder().decode(ResultArray.self, from: data)
guard let firstResult = resultArray.results.first else {
completion(nil, NetworkErrors.noData)
return
}
completion(firstResult.locations, nil)
return
}
catch let error {
completion(nil, error)
return
}
}
task.resume()
}
}
| true
|
f1456b9b37c53d001035463efc37af7942adad6f
|
Swift
|
QTYResources/macOSAppDevelopment
|
/macOSwift4.0.3-Ebook-Demo/Chapter 07 TableView&TreeView/NSTableView/CustomTableView/CustomTableView/ViewController.swift
|
UTF-8
| 3,535
| 2.9375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CustomTableView
//
// Created by iDevFans on 16/10/17.
// Copyright © 2016年 macdev. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
var datas = [NSDictionary]()
@IBOutlet weak var tableView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
let headerView = NSTableHeaderView(frame: NSMakeRect(0, 0, 120, 30))
//self.tableView.headerView = headerView
//self.tableView.usesAlternatingRowBackgroundColors = true
tableView.gridColor = NSColor.purple
self.updateData()
self.tableView.reloadData()
//self.tableView.selectionHighlightStyle = .none
}
func updateData() {
self.datas = [
["name":"john","address":"USA","gender":"male","married":(1)],
["name":"mary","address":"China","gender":"female","married":(0)],
["name":"park","address":"Japan","gender":"male","married":(0)],
["name":"Daba","address":"Russia","gender":"female","married":(1)],
]
}
}
extension ViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return self.datas.count
}
}
extension ViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let data = self.datas[row]
//表格列的标识
let key = (tableColumn?.identifier)!
//单元格数据
let value = data[key]
//根据表格列的标识,创建单元视图
let view = tableView.makeView(withIdentifier: key, owner: self)
let subviews = view?.subviews
if (subviews?.count)!<=0 {
return nil
}
if key.rawValue == "name" || key.rawValue == "address" {
let textField = subviews?[0] as! NSTextField
if value != nil {
textField.stringValue = value as! String
}
}
if key.rawValue == "gender" {
let comboField = subviews?[0] as! NSComboBox
if value != nil {
comboField.stringValue = value as! String
}
}
if key.rawValue == "married" {
let checkBoxField = subviews?[0] as! NSButton
checkBoxField.state = NSControl.StateValue(rawValue: 0)
if (value != nil) {
checkBoxField.state = NSControl.StateValue(rawValue: 1)
}
}
return view
}
func tableViewSelectionDidChange(_ notification: Notification){
let tableView = notification.object as! NSTableView
let row = tableView.selectedRow
print("selection row \(row)")
}
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
guard let rowView = tableView.makeView(withIdentifier:NSUserInterfaceItemIdentifier(rawValue: "RowView"), owner: nil) as! CustomTableRowView? else {
let rowView = CustomTableRowView()
rowView.identifier = NSUserInterfaceItemIdentifier(rawValue: "RowView")
return rowView
}
return rowView
}
// func tableView(_ tableView: NSTableView, isGroupRow row: Int) -> Bool {
//
// if row % 2 == 1 {
// return true
// }
// return false
// }
//
}
| true
|
8e099d4d0a3a23c9c0002ee88f82cda93cbcf9b5
|
Swift
|
JC2615/BookApp
|
/BookAppChallenge/Services/FetchData.swift
|
UTF-8
| 869
| 3.046875
| 3
|
[] |
no_license
|
//
// FetchData.swift
// BookAppChallenge
//
// Created by Joshua Curry on 8/25/21.
//
import Foundation
class FetchData {
static func getLocalData() -> [Book] {
let pathString = Bundle.main.path(forResource: "Books", ofType: "json")
if let pathString = pathString {
let url = URL(fileURLWithPath: pathString)
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
do {
let bookData = try decoder.decode([Book].self, from: data)
return bookData
} catch {
print(error.localizedDescription)
}
} catch {
print(error.localizedDescription)
}
}
return [Book]()
}
}
| true
|
7b37a5fdb3b4c0beaab2086e42ff0316c64d2e20
|
Swift
|
nhoward23/playlistbuddies
|
/PlaylistBuddies/PlaylistAPI.swift
|
UTF-8
| 3,779
| 3.0625
| 3
|
[] |
no_license
|
//
// PlaylistAPI.swift
// PlaylistBuddies
//
// Created by Kevin Tran on 11/27/18.
// Copyright © 2018 Kevin Tran. All rights reserved.
//
import Foundation
struct PlaylistAPI {
static let baseURL = "http://0.0.0.0:5000/api/playlist"
// connect
static func playlist_url(name: String, password: String) -> URL{
let params = ["name":"test_playlist", "pass":"test"]
var queryItems = [URLQueryItem]()
for (key, value) in params {
queryItems.append(URLQueryItem(name: key, value: value))
}
var components = URLComponents(string: PlaylistAPI.baseURL)!
components.queryItems = queryItems
let url = components.url!
return url
}
static func convert_to_string(playlist: Playlist) -> String?{
let jsonEncoder = JSONEncoder()
do{
let jsonData = try jsonEncoder.encode(playlist)
let json_string = String(data: jsonData, encoding: String.Encoding.utf8)
return json_string!
}
catch{
print("I dun goofed.")
return nil
}
return nil
}
static func convert_to_playlist(json: String) -> Playlist?{
do{
let jsonDecoder = JSONDecoder()
let playlist = try jsonDecoder.decode(Playlist.self, from: json.data(using: .utf8)!)
return playlist
}
catch{
print("I dun goofed.")
return nil
}
return nil
}
static func sample_playlist(){
var s = [Song]()
let song = Song(title: "test", artist: "test", album: "test")
let song2 = Song(title: "test", artist: "test", album: "test")
s.append(song)
s.append(song2)
var playlist = Playlist(songs: s, id: "test_name", password: "test")
let jsonEncoder = JSONEncoder()
do{
let jsonData = try jsonEncoder.encode(playlist)
let json = String(data: jsonData, encoding: String.Encoding.utf8)
}
catch{
print("I dun goofed.")
}
}
// holy shit this is ugly
static func get_playlist(name: String, password: String, completion: @escaping (String?) -> Void){
let url = PlaylistAPI.playlist_url(name: name, password: password)
let task = URLSession.shared.dataTask(with: url){
(data, response, error) in
if let data = data, let dataString = String(data: data, encoding: .utf8){
do{
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard let jsonDict = jsonObject as? [String: Any], let array = jsonDict["value"] as? [[String: Any]]
else{
print("failed")
completion(nil)
return
}
if let playlist = array.first{
let my_list = playlist["playlist"] as! String
var the_play = PlaylistAPI.convert_to_playlist(json: my_list)
print(the_play?.songs[0].title)
}
}
catch{
print("error on json \(error)")
}
DispatchQueue.main.async {
completion(dataString)
}
}
else {
if let error = error {
print("Error getting photos JSON response \(error)")
}
DispatchQueue.main.async {
completion(nil)
}
}
}
task.resume()
}
}
| true
|
b963206cbcc776caf7034f3976c17f9960838aed
|
Swift
|
phucnd0604/Live-Weather
|
/LiveWeather/LiveWeather/MenuViewController.swift
|
UTF-8
| 4,433
| 2.640625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// LiveWeather
//
// Created by phuc on 9/19/15.
// Copyright © 2015 phuc nguyen. All rights reserved.
//
import UIKit
import CoreLocation
var AppmenuItems = [NSDictionary]()
class MenuViewController: UITableViewController {
private let searchController = UISearchController(searchResultsController: nil)
private var searchResult = [NSDictionary]()
var selectedIndex: NSIndexPath? = NSIndexPath(forRow: 0, inSection: 0) {
willSet {
if let indexPath = selectedIndex,
cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.backgroundColor = UIColor.clearColor()
}
} didSet {
if let indexPath = selectedIndex,
cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.backgroundColor = UIColor.brownColor()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Remove the drop shadow from the navigation bar
navigationController!.navigationBar.clipsToBounds = true
title = "Favorite"
// init menuItem
guard let amenuItems = NSUserDefaults.standardUserDefaults().arrayForKey(kAppFavoriteCity) as? [NSDictionary] else {
return
}
AppmenuItems = amenuItems
let containerVC = navigationController!.parentViewController as! ContainerViewController
containerVC.detailViewController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateMenuItem() {
tableView.reloadData()
}
// MARK: - Segues
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedIndex = indexPath
if indexPath.row == 0 {
let containerVC = navigationController!.parentViewController as! ContainerViewController
containerVC.detailViewController!.requestUpdateLocation()
containerVC.hideOrShowMenu(false, animated: true)
} else {
let menuItem = AppmenuItems[indexPath.row - 1]
(navigationController!.parentViewController as! ContainerViewController).menuItem = menuItem
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active {
return searchResult.count
} else {
return AppmenuItems.count + 1
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// adjust row height so items all fit into view
return 80
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if searchController.active {
let cell: UITableViewCell
if let acell = tableView.dequeueReusableCellWithIdentifier("Cell") {
cell = acell
} else {
cell = UITableViewCell()
}
let dict = searchResult[indexPath.row]
cell.textLabel?.text = dict["city"]?.string
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("MenuItemCell") as! MenuItemCell
if indexPath == selectedIndex! {
cell.backgroundColor = UIColor.brownColor()
}
if indexPath.row == 0 {
cell.cityName.text = "Current location"
} else {
let menuItem = AppmenuItems[indexPath.row - 1]
cell.configureForMenuItem(menuItem)
}
return cell
}
}
}
extension MenuViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
}
extension MenuViewController: DetailsViewControllerDelegate {
func didUpdateMenuItem() {
updateMenuItem()
}
}
| true
|
e24c3ec59253f436b5298c5b0eea8532dbadabe2
|
Swift
|
matus-tomlein/seelog
|
/seelog/Models/GeometryDescription.swift
|
UTF-8
| 2,694
| 2.546875
| 3
|
[] |
no_license
|
//
// GeometryDescription.swift
// seelog
//
// Created by Matus Tomlein on 07/03/2020.
// Copyright © 2020 Matus Tomlein. All rights reserved.
//
import Foundation
import GEOSwift
import MapKit
struct GeometryDescription {
var geometry: Geometry?
var minLatitude: Double
var minLongitude: Double
var maxLatitude: Double
var maxLongitude: Double
var minX: Double { Helpers.longitudeToX(minLongitude) }
var minY: Double { Helpers.latitudeToY(maxLatitude) }
var maxX: Double { Helpers.longitudeToX(maxLongitude) }
var maxY: Double { Helpers.latitudeToY(minLatitude) }
// lazy var envelope: Polygon? = {
// if let envelopeGeometry = try? geometry?.envelope().geometry {
// if case let .polygon(envelope) = envelopeGeometry {
// return envelope.exterior.points.map { p in
// Point(x: Helpers.longitudeToX(p.x), Helpers.latitudeToY(p.y))
// }
// }
// }
// return nil
// }()
var polygons: [Polygon] {
var polygons: [Polygon] = []
if let geometry = geometry {
switch geometry {
case let .multiPolygon(p):
polygons = p.polygons
case let .polygon(p):
polygons = [p]
default:
polygons = []
}
}
return polygons
}
var polygonPoints: [[(x: Double, y: Double)]] {
return polygons.map { polygon in
polygon.exterior.points.map {
let (x, y) = Helpers.geolocationToXY(latitude: $0.y, longitude: $0.x)
return (x: x, y: y)
}
}
}
var centroid: Point? {
if let centroid = try? geometry?.centroid() {
let (x, y) = Helpers.geolocationToXY(latitude: centroid.y, longitude: centroid.x)
return Point(x: x, y: y)
}
return nil
}
var boundingRect: Polygon? {
guard let envelope = try? geometry?.minimumRotatedRectangle() else { return nil }
switch envelope {
case let .polygon(polygon):
return try? Polygon(
exterior: Polygon.LinearRing(
points: polygon.exterior.points.map { p in
Point(x: Helpers.longitudeToX(p.x), y: Helpers.latitudeToY(p.y))
}
)
)
default:
return nil
}
}
func intersects(mapRegion: MKCoordinateRegion) -> Bool {
guard let envelope = boundingRect else { return false }
return Helpers.intersects(polygon: envelope, mapRegion: mapRegion)
}
}
| true
|
f2d1da706e400f1aec701bc18558540da9ab488b
|
Swift
|
eshu94/Weather-Details
|
/Weather-Details/Controllers/SettingsTableViewController.swift
|
UTF-8
| 2,128
| 2.859375
| 3
|
[] |
no_license
|
//
// SettingsTableViewController.swift
// Weather-Details
//
// Created by ESHITA on 11/02/21.
//
import Foundation
import UIKit
protocol SettingsDelegate {
func settingsDone(_vm: SettingsViewModel)
}
class SettingsTableViewController: UITableViewController {
var settingsVM = SettingsViewModel()
var delegate: SettingsDelegate?
@IBAction func done () {
if let delegate = self.delegate {
delegate.settingsDone(_vm: self.settingsVM)
}
self.dismiss(animated: true, completion: nil)
}
//Funtions for tableViews
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settingsVM.units.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let settingsVM = self.settingsVM.units[indexPath.row]
let cell = self.tableView.dequeueReusableCell(withIdentifier: "SettingsCell", for: indexPath)
let settingsItem = self.settingsVM.units[indexPath.row]
cell.textLabel?.text = settingsVM.displayName
if settingsItem == self.settingsVM.selectedUnit {
cell.accessoryType = .checkmark
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// uncheck all cells
tableView.visibleCells.forEach { (cell) in
cell.accessoryType = .none
}
if let cell = tableView.cellForRow(at: indexPath){
cell.accessoryType = .checkmark
let unit = Unit.allCases[indexPath.row]
self.settingsVM.selectedUnit = unit
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
}
}
}
| true
|
35d21d3f589066e975ce16a1e5511456efb4845a
|
Swift
|
yefenglei/iosdemo
|
/UIDemo/私人通讯录/controller/FLEditViewController.swift
|
UTF-8
| 2,335
| 2.671875
| 3
|
[] |
no_license
|
//
// FLEditViewController.swift
// UIDemo
//
// Created by 叶锋雷 on 15/6/27.
// Copyright (c) 2015年 叶锋雷. All rights reserved.
//
import UIKit
protocol FLEditViewControllerDelegate{
func EditViewController(sender:FLEditViewController,contact:FLContact)
}
class FLEditViewController: UIViewController,UITextFieldDelegate {
var name:String?
var phone:String?
@IBAction func saveBtnClicked(sender: UIButton) {
if(delegate != nil){
var name:String=nameField.text
var phone:String=phoneField.text
var contact:FLContact=FLContact(name: name, phone: phone)
delegate!.EditViewController(self, contact: contact)
// 回上一个控制器
self.navigationController?.popViewControllerAnimated(true)
}
}
@IBAction func editBarBtnClicked(sender: UIBarButtonItem) {
self.saveBtn.enabled=true
self.nameField.enabled=true
self.phoneField.enabled=true
TextChanged()
}
@IBOutlet weak var phoneField: UITextField!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var saveBtn: UIButton!
var delegate:FLEditViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// 初始化
nameField.text=name
phoneField.text=phone
// 1.添加文本框监听时间
nameField.addTarget(self, action: "TextChanged", forControlEvents: UIControlEvents.EditingChanged)
phoneField.addTarget(self, action: "TextChanged", forControlEvents: UIControlEvents.EditingChanged)
// Do any additional setup after loading the view.
}
func TextChanged(){
self.saveBtn.enabled=(nameField.text != "" && phoneField.text != "")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
3e690cacc41f510d282dc5bd542d019f3f7b6f0f
|
Swift
|
supanat-toy/weather
|
/weather/Helper/NetworkError.swift
|
UTF-8
| 1,709
| 2.90625
| 3
|
[] |
no_license
|
//
// NetworkError.swift
// weather
//
// Created by Supanat on 5/11/2563 BE.
//
import Foundation
import Moya
struct NetworkError: Swift.Error, Equatable, Codable {
var code: String?
var message: String?
var httpStatusCode: Int?
init(error: Error) {
if let moyaError = error as? MoyaError {
switch moyaError {
case .objectMapping(_, let response):
self = NetworkError(response: response)
case .underlying(_, let response):
self = NetworkError(response: response)
case .statusCode(let response):
self = NetworkError(response: response)
default:
self = NetworkError(code: nil, message: "Connection error", httpStatusCode: 0)
}
} else {
self = error as? NetworkError ?? NetworkError(code: nil, message: error.localizedDescription, httpStatusCode: 0)
}
}
init(code: String?, message: String?, httpStatusCode: Int?) {
self.code = code
self.message = message
self.httpStatusCode = httpStatusCode
}
init(response: Response?) {
if let response = response {
if let json = try? JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any] {
self = NetworkError(code: json["cod"] as? String,
message: json["message"] as? String,
httpStatusCode: response.statusCode)
} else {
self = NetworkError(code: nil, message: response.description, httpStatusCode: response.statusCode)
}
}
}
}
| true
|
93007ace2d2e7b2e1f495d50b75c5e7745b12222
|
Swift
|
pksenzov/SimplePasswordKeeper
|
/PKGrandCentralDispatch.swift
|
UTF-8
| 1,366
| 2.78125
| 3
|
[] |
no_license
|
//
// PKDispatchCancelableClosureFile.swift
// Records
//
// Created by Admin on 29/06/16.
// Copyright © 2016 Pavel Ksenzov. All rights reserved.
//
import Foundation
typealias dispatch_cancelable_closure = (_ cancel: Bool) -> Void
func delay(_ time: TimeInterval, closure: @escaping () -> Void) -> dispatch_cancelable_closure? {
func dispatch_later(_ clsr: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: clsr)
}
var closure: (()->())? = closure
var cancelableClosure: dispatch_cancelable_closure?
let delayedClosure: dispatch_cancelable_closure = { cancel in
if closure != nil {
if (cancel == false) {
DispatchQueue.main.async(execute: closure!)
//DispatchQueue.main.async(execute: closure as! @convention(block) () -> Void)//
}
}
closure = nil
cancelableClosure = nil
}
cancelableClosure = delayedClosure
dispatch_later {
if let delayedClosure = cancelableClosure {
delayedClosure(false)
}
}
return cancelableClosure;
}
func cancel_delay(_ closure: dispatch_cancelable_closure?) {
if closure != nil {
closure!(true)
}
}
| true
|
db90e843f2a365adf7f79e5761ddafe05ea1a664
|
Swift
|
Mspaenle/swiftProject
|
/PKProject/PKProject/EmergencyNumberDAO.swift
|
UTF-8
| 1,141
| 2.71875
| 3
|
[] |
no_license
|
//
// EmergencyNumberDAO.swift
// PKProject
//
// Created by Chloe DALGER on 14/03/2018.
// Copyright © 2018 Mahe SPAENLE Chloé DALGER. All rights reserved.
//
import Foundation
import CoreData
import UIKit
/// DAO Extension to access the data base
extension EmergencyNumber{
static func getNewEmergencyNumberDAO() -> EmergencyNumber?{
guard let entity = NSEntityDescription.entity(forEntityName: "EmergencyNumber", in: CoreDataManager.context) else {
return nil
}
return EmergencyNumber(entity: entity, insertInto : CoreDataManager.context)
}
static func create() -> EmergencyNumber{
return EmergencyNumber(context: CoreDataManager.context)
}
static func save() {
do{
try CoreDataManager.save()
}catch let error as NSError{
fatalError("cannot save data: "+error.description)
}
}
static func delete(object: EmergencyNumber){
do{
try CoreDataManager.delete(object: object)
}catch let error as NSError{
fatalError("cannot save data: "+error.description)
}
}
}
| true
|
caed860f038b710fa325535aa60e30aedd9df00f
|
Swift
|
Piercing/Restaurante
|
/Proy-Restaurant/DetalleViewController.swift
|
UTF-8
| 5,942
| 2.796875
| 3
|
[] |
no_license
|
//
// DetalleViewController.swift
// Proy-Restaurant
//
// Created by MacBook Pro on 16/12/15.
// Copyright © 2015 Juan Carlos Merlos. All rights reserved.
//
import UIKit
// Utilizamos el método delegado para el 'texField' que ocultará el
// teclado del dispositivo al introducir una cantidad en la orden.
class DetalleViewController: UIViewController, UITextFieldDelegate {
var datoDetalle : NSDictionary = NSDictionary()
var nombreArchivo = ""
var precioPlato = ""
@IBOutlet weak var imagenDetalle: UIImageView!
@IBOutlet weak var tituloDetalle: UILabel!
@IBOutlet weak var precioDetalle: UILabel!
@IBOutlet weak var descripcionDetalle: UITextView!
@IBOutlet weak var cantidadOrden: UITextField!
@IBAction func agregarOrden(sender: AnyObject) {
let objDAO = DataBase()
let cantidadOrden = self.cantidadOrden.text! as NSString
let nomPlato = tituloDetalle.text!
let precioPlato = self.precioPlato
let archivoPlato = nombreArchivo
if cantidadOrden == "" || cantidadOrden == "0" {
let alerOrden = UIAlertController(title: "Atención", message: "Introduzca una cantidad no nula y mayor que cero para ordenar", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alerOrden.addAction(defaultAction)
presentViewController(alerOrden, animated: true, completion: nil)
}else{
let sqlInsert = "insert into ordenpedido (nombre_plato, precio_plato, archivo_plato, cantidad_plato) values('\(nomPlato)','\(precioPlato)','\(archivoPlato)','\(cantidadOrden)')"
// Insertamos valores si todo es correcto
objDAO.ejecutarInsert(sqlInsert)
}
// llamamos a la función 'getDataBasePath' para ver si se han guardado los datos y dónde
let ruta = DataBase.getDataBasePath()
print(ruta) //nos devuelve la ruta donde se han guardado los datos en nuestro FileSystem
// llamamos a la función devolverPosicionIncial antes de llamar a la funcicón 'alertaOrden'
devolverPosicionInicial()
// llamamos a la función orden cada vez que se produzca una orden al llegar aquí
alertaOrden()
}
override func viewDidLoad() {
super.viewDidLoad()
// le decimos que todos los métodos delegados que han sido aceptados por
// la clase también sean aceptados por el campo textField 'cantidadOrden'
cantidadOrden.delegate = self
// imagen plato
nombreArchivo = (datoDetalle["archivo_plato"] as! String)
imagenDetalle.image = UIImage(named: nombreArchivo)
// Nombre, precio y detalle plato
if let nombrePlato: String = datoDetalle["nombre_plato"] as? String{
tituloDetalle.text = nombrePlato
}
precioPlato = datoDetalle["precio_plato"] as! String
precioDetalle.text = "Precio S/.\(precioPlato)€"
if let descripPlato = datoDetalle["descripcion_plato"]as? String{
descripcionDetalle.text = descripPlato
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Configurando botón de compartir
@IBAction func shareButton(sender: AnyObject) {
var textoCompartir = ""
if let nombrePlato = tituloDetalle.text{
textoCompartir = "Recomendamos visitar nuestro RESTAURANTE y disfurtar de este exquisito plato: \(nombrePlato)"
}
let imagenShared:UIImage! = imagenDetalle.image
if let urlCompartir = NSURL(string: "http://www.google.es"){
let objetoCompartir:NSArray = [textoCompartir, imagenShared, urlCompartir]
let socialActivity = UIActivityViewController(activityItems: objetoCompartir as [AnyObject], applicationActivities: nil)
self.presentViewController(socialActivity, animated: true, completion: nil)
}
}
// Oculatamos el teclado con un función delegado al pulsar fuera de el en la pantalla
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
// Llamamos de nuevo a la función devolverPosicionInicial
devolverPosicionInicial()
}
// Función delegados de texField para mostrar el teclado y desplazar la vista 200 píxeles hacia arriba
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
UIView.animateWithDuration(1) { () -> Void in
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y-200, self.view.frame.width, self.view.frame.height)
}
return true
}
// Creamos una función de alertas para las órdenes (alertView)
func alertaOrden(){
var mensaje: String = ""
let textoCantidad = cantidadOrden.text!
if textoCantidad != ""{
mensaje = "Ha añadido \(textoCantidad) plato(s) de \(tituloDetalle.text!) a su pedido"
}
let alerOrden = UIAlertController(title: "Orden pedido", message: "\(mensaje)", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alerOrden.addAction(defaultAction)
presentViewController(alerOrden, animated: true, completion: nil)
}
// función para devlover al frame inicial la vista
func devolverPosicionInicial(){
UIView.animateWithDuration(0.5) { () -> Void in
self.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
}
}
}
| true
|
b43d6fe69ddfed2346c63bd58582c3c813f9776c
|
Swift
|
mphills92/LoopWorkspace
|
/Loop/ApplyPromoCodeViewController.swift
|
UTF-8
| 4,599
| 2.625
| 3
|
[] |
no_license
|
//
// ApplyPromoCodeViewController.swift
// carpoolApp_v1.0
//
// Created by Matt Hills on 8/3/16.
// Copyright © 2016 Matthew Hills. All rights reserved.
//
import UIKit
class ApplyPromoCodeViewController: UIViewController, UITextFieldDelegate {
@IBAction func closeViewButtonPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: {})
}
@IBOutlet weak var applyPromoCodeButton: UIButton!
@IBOutlet weak var promoCodeTextField: UITextField!
let userReferralCode = UserReferralCode()
var textFieldCharactersCount = Int()
var enteredPromoCode = String()
var promoCodeIsValid: Bool = true
var acceptedPromoCode = String()
override func viewDidLoad() {
super.viewDidLoad()
promoCodeTextField.delegate = self
promoCodeTextField.becomeFirstResponder()
navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
navigationController?.navigationBar.barStyle = UIBarStyle.Default
navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name:"AvenirNext-Regular", size: 26)!, NSForegroundColorAttributeName: UIColor(red: 0/255, green: 51/255, blue: 0/255, alpha: 1.0)]
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navigationController?.navigationBar.shadowImage = UIImage()
applyPromoCodeButton.layer.cornerRadius = 20
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "acceptedPromoCodeNotification", object: self.view.window)
promoCodeTextField.resignFirstResponder()
}
}
extension ApplyPromoCodeViewController {
func textFieldDidBeginEditing(textField: UITextField) {
}
func textFieldDidEndEditing(textField: UITextField) {
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
evaluatePromoCode()
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = promoCodeTextField.text else {return true}
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 15
}
@IBAction func applyPromoCodeButtonPressed(sender: AnyObject) {
evaluatePromoCode()
}
func evaluatePromoCode() {
enteredPromoCode = promoCodeTextField.text!
if (enteredPromoCode == userReferralCode.referralCode) {
promoCodeIsValid == true
let alertController = UIAlertController(title: "Happy golfing!", message: "Your promo code has been applied.", preferredStyle: .Alert)
alertController.view.tintColor = UIColor(red: 0/255, green: 51/255, blue: 0/255, alpha: 1.0)
self.promoCodeTextField.text = self.enteredPromoCode
self.acceptedPromoCode = self.enteredPromoCode
self.promoCodeTextField.resignFirstResponder()
let doneAction = UIAlertAction(title: "OK", style: .Default) { (action) in
NSNotificationCenter.defaultCenter().postNotificationName("acceptedPromoCodeNotification", object: self.acceptedPromoCode)
self.dismissViewControllerAnimated(true, completion: {})
}
alertController.addAction(doneAction)
self.presentViewController(alertController, animated: true) {
alertController.view.tintColor = UIColor(red: 0/255, green: 51/255, blue: 0/255, alpha: 1.0)
}
} else {
promoCodeTextField == false
let alertController = UIAlertController(title: "", message: "The promo code you entered is invalid. Please try something else.", preferredStyle: .Alert)
alertController.view.tintColor = UIColor(red: 0/255, green: 51/255, blue: 0/255, alpha: 1.0)
let tryAgainAction = UIAlertAction(title: "Try Again", style: .Cancel) { (action) in
self.promoCodeTextField.text = ""
}
alertController.addAction(tryAgainAction)
self.presentViewController(alertController, animated: true) {
alertController.view.tintColor = UIColor(red: 0/255, green: 51/255, blue: 0/255, alpha: 1.0)
}
}
}
}
| true
|
b44eaa6484c8a7d15fc3007eb1e9fba71d261bef
|
Swift
|
Juan-Ceballos/Pursuit-Core-iOS-Introduction-to-Unit-Testing-Lab
|
/IntroParseJSONUnitTest/IntroParseJSONUnitTest/JokesViewController.swift
|
UTF-8
| 1,604
| 2.890625
| 3
|
[] |
no_license
|
//
// JokesViewController.swift
// IntroParseJSONUnitTest
//
// Created by Juan Ceballos on 12/3/19.
// Copyright © 2019 Juan Ceballos. All rights reserved.
//
import UIKit
class JokesViewController: UIViewController {
@IBOutlet weak var jokeTableView: UITableView!
var jokes = [ProgrammingJokes]() {
didSet {
jokeTableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
jokeTableView.dataSource = self
}
func loadData() {
jokes = ProgrammingJokes.getJokes()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let jokeDetailedViewController = segue.destination as? JokeDetailedViewController, let indexPath = jokeTableView.indexPathForSelectedRow
else {
fatalError()
}
let joke = jokes[indexPath.row] //from here to there
jokeDetailedViewController.jokes = joke
}
}
extension JokesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
jokes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let jokeCell = jokeTableView.dequeueReusableCell(withIdentifier: "jokeCell", for: indexPath)
let joke = jokes[indexPath.row]
//use joke instance to configure jokeCell
jokeCell.textLabel?.text = joke.setup
return jokeCell
}
}
| true
|
97dfc2a01089d5c75b4ced2daf01f9af2fddc635
|
Swift
|
TelematikFreak/CalculadoraSwift
|
/Calculadora/Controlador/CalculadoraControlador.swift
|
UTF-8
| 1,366
| 3.453125
| 3
|
[] |
no_license
|
//
// CalculadoraControlador.swift
// Calculadora
//
// Created by Manuel Salvador del Águila on 05/11/2019.
// Copyright © 2019 Manuel Salvador del Águila. All rights reserved.
//
import Foundation
class CalculadoraControlador {
var modelo: CalculadoraModelo
var vista: CalculadoraVista
required init(modelo: CalculadoraModelo, vista: CalculadoraVista) {
self.modelo = modelo
self.vista = vista
}
func realizarOperacion() {
print("Operador")
let operador = vista.leerOperador()
print("Numero 1")
let num2 = vista.leerNumero()
print("Numero 2")
let num1 = vista.leerNumero()
var resultado: Double = 0
switch operador {
case "+":
resultado = modelo.sumar(a: num1, b: num2)
break
case "-":
resultado = modelo.restar(a: num1, b: num2)
break
case "*":
resultado = modelo.multiplicar(a: num1, b: num2)
break
case "/":
if (num2 == 0) {
vista.escribirMensajeError(error: "División por cero")
} else {
resultado = modelo.dividir(a: num1, b: num2)
}
break
default:
print("Operador no disponible")
return
}
print("Resultado \(resultado)")
}
}
| true
|
14b13c386eb05cbd0e5ecd3a73fa8f56e23f7c22
|
Swift
|
gifton/Reconsiderate
|
/Reconsiderate/ViewModel/ThoughtDetailHomeViewModel.swift
|
UTF-8
| 1,322
| 2.6875
| 3
|
[] |
no_license
|
import Foundation
class ThoughtDetailHomeViewModel {
init(_ thought: Thought) {
self.thought = thought
}
// MARK: Private vars
public var thought: Thought
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .none
formatter.doesRelativeDateFormatting = false
formatter.formattingContext = .listItem
return formatter
}()
// MARK: public vars
public var title: String {
return thought.title
}
public var createdAt: String {
let date = thought.date
let d = dateFormatter.string(from: date)
return "created \(d)"
}
public var isPersonal: Bool {
return thought.isPersonal
}
public var icon: String {
return thought.icon
}
public var totalSparqCount: String {
return "\(thought.sparqs?.count ?? 0) total sparqs"
}
public var sparqsThisWeek: String {
return "\(thought.sparqCountFromPastWeek) sparqs this week"
}
public var sparqs: [Sparq] {
return thought.computedSparqs
}
public var location: String {
guard let loc = thought.location else { return "" }
return "captured in \(loc)"
}
}
| true
|
2cd5146d480c5bf075a5b81373f282016b3e19d9
|
Swift
|
1abhisheksingh/bookstore
|
/BookStore/APIService/HttpConstants.swift
|
UTF-8
| 1,086
| 2.75
| 3
|
[] |
no_license
|
//
// HttpConstants.swift
// BookStore
//
// Created by Abhishek Singh on 29/07/19.
// Copyright © 2019 Abhishek Singh. All rights reserved.
//
import Foundation
/** Provides constants for working with the HTTP protocol. */
open class HttpConstants {
public class Header {
/** The Authorization header key for HTTP request. */
public static let Authorization = "Authorization"
/** The Content-Type header key for HTTP request. */
public static let ContentType = "Content-Type"
/** The Accept header key for HTTP request. */
public static let Accept = "Accept"
fileprivate init() {}
}
public class ContentType {
/** A content type for url-encoded form data */
public static let FormUrlEncoded = "application/x-www-form-urlencoded"
/** A content type for url-encoded form data */
public static let Json = "application/json"
fileprivate init() {}
}
// MARK: constructors
fileprivate init() {}
}
| true
|
9de54a998fa6e78866f524b5438ac78f3e75cf56
|
Swift
|
kinkofer/BattleNetAPI
|
/Sources/BattleNetAPI/Model/Repositories/AuthenticationRepository.swift
|
UTF-8
| 1,694
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// AuthenticationRepository.swift
// BattleNetAPI
//
// Created by Christopher Jennewein on 4/6/18.
// Copyright © 2018 Prismatic Games. All rights reserved.
//
import Foundation
public struct AuthenticationRepository {
let battleNetAPI: BattleNetAPI
public init(battleNetAPI: BattleNetAPI) {
self.battleNetAPI = battleNetAPI
}
public func getClientAccessToken(clientID: String, clientSecret: String, completion: @escaping (_ result: Result<Access, Error>) -> Void) {
battleNetAPI.authentication.getClientAccess(completion: { $0.decode(completion: completion) })
}
public func getUserAccessToken(clientID: String, clientSecret: String, code: String, redirectURL: String, completion: @escaping (_ result: Result<Access, Error>) -> Void) {
battleNetAPI.authentication.getUserAccess(code: code, redirectURL: redirectURL, completion: { $0.decode(completion: completion) })
}
public func validateClientAccessToken(_ token: String, completion: @escaping (_ result: Result<ClientToken, Error>) -> Void) {
battleNetAPI.authentication.validateClientAccessToken(token, completion: { $0.decode(completion: completion) })
}
public func validateUserAccessToken(_ token: String, completion: @escaping (_ result: Result<UserToken, Error>) -> Void) {
battleNetAPI.authentication.validateUserAccessToken(token, completion: { $0.decode(completion: completion) })
}
public func getOAuthURL(scope: Scope, redirectURL: URL, state: String) -> URL? {
return battleNetAPI.authentication.getOAuthURL(scope: scope, redirectURL: redirectURL, state: state)
}
}
| true
|
70e61c78df98948f96a0bf839607e9be0d5ca5f5
|
Swift
|
habirin/VKnews
|
/VK/Cells/TextTableViewCell.swift
|
UTF-8
| 1,590
| 2.578125
| 3
|
[] |
no_license
|
//
// TextTableViewCell.swift
// VK
//
// Created by Ринат Хабибуллин on 24.01.2018.
// Copyright © 2018 Ринат Хабибуллин. All rights reserved.
//
import UIKit
protocol UpdateTextTableViewCellHeightDelegate: class {
func updateHeight(cell: TextTableViewCell)
}
extension UILabel {
var isTruncated: Bool {
guard let labelText = text else {
return false
}
let labelTextSize = (labelText as NSString).boundingRect(
with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil).size
return labelTextSize.height > bounds.size.height
}
}
class TextTableViewCell: UITableViewCell {
var indexPath: IndexPath!
@IBOutlet weak var smallHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var bigHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var textInfo: UILabel!
weak var delegate: UpdateTextTableViewCellHeightDelegate?
@IBOutlet weak var readAllButton: UIButton!
@IBAction func readAllButton(_ sender: Any) {
self.delegate?.updateHeight(cell: self)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
fd432c683ca3d5fb9e5ea7b0a7ea78c73fe996c6
|
Swift
|
OEA/OEAContentStateView
|
/OEAContentStateView/Classes/OEALoadingStateView.swift
|
UTF-8
| 2,278
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// OEAContentStateView.swift
// OEAContentStateView
//
// Created by Omer Emre Aslan on 14.02.2018.
// Copyright © 2018 Omer Emre Aslan. All rights reserved.
//
class OEALoadingStateView: UIView {
private lazy var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
return activityIndicator
}()
private lazy var textLabel: UILabel = {
let textLabel = UILabel()
textLabel.numberOfLines = 0
textLabel.font = UIFont.systemFont(ofSize: 16)
textLabel.textColor = .gray
textLabel.textAlignment = .center
textLabel.translatesAutoresizingMaskIntoConstraints = false
return textLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension OEALoadingStateView {
func setText(_ text: String) {
textLabel.text = text
}
}
private extension OEALoadingStateView {
func setupLayout() {
addActivityIndicator()
addTextLabel()
}
func addActivityIndicator() {
addSubview(activityIndicator)
activityIndicator
.centerYAnchor
.constraint(equalTo: self.centerYAnchor,
constant: -10)
.isActive = true
activityIndicator
.centerXAnchor
.constraint(equalTo: self.centerXAnchor)
.isActive = true
activityIndicator.startAnimating()
}
func addTextLabel() {
addSubview(textLabel)
textLabel
.topAnchor
.constraint(equalTo: activityIndicator.bottomAnchor,
constant: 5.0)
.isActive = true
textLabel
.leadingAnchor
.constraint(equalTo: self.leadingAnchor, constant: 15.0)
.isActive = true
textLabel
.trailingAnchor
.constraint(equalTo: self.trailingAnchor, constant: -15.0)
.isActive = true
}
}
| true
|
e07dc5674a36b51f39baae7a8e24652510aad06e
|
Swift
|
Enovaid/midterm
|
/midterm/ViewController.swift
|
UTF-8
| 2,412
| 2.828125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// midterm
//
// Created by Айдана on 10/16/20.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, deleteAlarm, changeAlarm, addAlarm {
func addAlarm(alarm: Alarm) {
alarms.append(alarm)
myTableView.reloadData()
}
func deleteAlarmbBy(index i: Int) {
alarms.remove(at: i)
myTableView.reloadData()
}
func changeAlarmBy(index i: Int, _ alarm: Alarm) {
alarms[i] = alarm
myTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return alarms.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? customCell
cell?.timeLabel.text = alarms[indexPath.row].time
cell?.notesLabel.text = alarms[indexPath.row].notes
return cell!
}
var alarms = [
Alarm.init("10:00", "breakfast"),
Alarm.init("18:00", "serial")
]
@IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myTableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
alarms.remove(at: indexPath.row)
myTableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditAlarmSegue"{
let index = (myTableView.indexPathForSelectedRow?.row)!
let destination = segue.destination as! EditAlarmVC
destination.alarm = alarms[index]
destination.currentIndex = index
destination.deleteDelegate = self
destination.changeDelegate = self
}
else if segue.identifier == "NewAlarmSegue" {
let destination = segue.destination as! NewAlarmVC
destination.addDelegate = self
}
}
}
| true
|
c66ec5a0273d3c000a2068b4d794315b2b5591aa
|
Swift
|
nekomaruh/swift_course
|
/2_mvc/2_mvc/Controller/Controller.swift
|
UTF-8
| 710
| 2.640625
| 3
|
[] |
no_license
|
//
// Controller.swift
// 2_mvc
//
// Created by Johan Esteban Ordenes Galleguillos on 18-07-20.
// Copyright © 2020 Johan Esteban Ordenes Galleguillos. All rights reserved.
//
import UIKit
class Controller: UIViewController {
@IBOutlet var iphonePriceLabel: UILabel!
@IBOutlet var iphoneNameLabel: UILabel!
@IBOutlet var iphoneColorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let appleProduct = AppleProduct(name: "iPhone X", color: "Space gray", price: 999.99)
iphoneNameLabel.text = appleProduct.name
iphoneColorLabel.text = appleProduct.color
iphonePriceLabel.text = String(appleProduct.price)
}
}
| true
|
2862231c31fc07c8a35f22448172b11b45d040e1
|
Swift
|
samrayner/LocalizationManager
|
/Localization/LocalizationManager.swift
|
UTF-8
| 7,842
| 2.59375
| 3
|
[] |
no_license
|
//
// LocalizationManager.swift
// Localization
//
// Created by Sam Rayner on 03/10/2018.
// Copyright © 2018 Sam Rayner. All rights reserved.
//
import Foundation
final class LocalizationManager {
typealias LanguageCode = String
typealias TranslationKey = String
typealias LanguageTranslations = [TranslationKey: String]
typealias Translations = [LanguageCode: LanguageTranslations]
enum Errors: Error {
case copy
case creation
}
private static let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
static let shared = LocalizationManager()
private let localizationBundleDestination: URL
private let stringsFilename: String
private let bundleExtension: String
private(set) var currentBundle: Bundle = Bundle(for: LocalizationManager.self)
init(stringsFilename: String = "Localizable.strings",
bundleExtension: String = "localizationBundle",
localizationBundleDestination: URL = documentsDirectory) {
self.stringsFilename = stringsFilename
self.bundleExtension = bundleExtension
self.localizationBundleDestination = localizationBundleDestination
self.currentBundle = findOrCreateLocalizationBundle()
}
private let lProjExtension = "lproj"
private var plistFormat: PropertyListSerialization.PropertyListFormat = .binary
private let plistDecoder = PropertyListDecoder()
private lazy var plistEncoder: PropertyListEncoder = {
let encoder = PropertyListEncoder()
encoder.outputFormat = plistFormat
return encoder
}()
private func findOrCreateLocalizationBundle() -> Bundle {
if let existingBundle = localizationBundle() { return existingBundle }
let classBundle = Bundle(for: LocalizationManager.self)
do {
return try localizationBundle(named: self.newBundleName(), from: classBundle)
} catch {
print("Failed to copy localizations from app Bundle to a new Bundle in the documents directory: \(error)")
return classBundle
}
}
private func contentsOfDirectory(at url: URL) -> [URL] {
do {
return try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [], options: [])
} catch {
return []
}
}
private func localizationBundleURLs() -> [URL] {
return contentsOfDirectory(at: localizationBundleDestination)
.filter { $0.pathExtension == bundleExtension }
.sorted { $0.lastPathComponent > $1.lastPathComponent }
}
private func lProjURLs(for bundle: Bundle) -> [URL] {
return contentsOfDirectory(at: bundle.bundleURL)
.filter { $0.pathExtension == lProjExtension }
}
private func lProjURL(for languageCode: LanguageCode, in bundle: Bundle? = nil) -> URL? {
return lProjURLs(for: bundle ?? currentBundle).first {
$0.deletingPathExtension().lastPathComponent == languageCode
}
}
private func localizationBundle() -> Bundle? {
var urls = localizationBundleURLs()
defer {
//clean up old bundles (shouldn't be any)
urls.forEach { try? FileManager.default.removeItem(at: $0) }
}
guard let url = urls.first,
let bundle = Bundle(url: url),
!lProjURLs(for: bundle).isEmpty else { return nil }
_ = urls.removeFirst() //don't clean up current bundle
return bundle
}
private func updateTranslations(_ old: Translations, with updates: Translations) -> Translations {
var new = old
for (key, value) in updates {
new[key] = old[key, default: [:]].merging(value) { $1 }
}
return new
}
private func newBundleName() -> String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd_HH-mm-ss-SSS"
let dateString = formatter.string(from: Date())
return "\(dateString).\(bundleExtension)"
}
private func createDirectoryForBundle(named bundleName: String) throws -> URL {
let docsBundleURL = localizationBundleDestination.appendingPathComponent(bundleName)
if FileManager.default.fileExists(atPath: docsBundleURL.path) {
try FileManager.default.removeItem(at: docsBundleURL)
}
try FileManager.default.createDirectory(at: docsBundleURL, withIntermediateDirectories: false, attributes: nil)
return docsBundleURL
}
private func localizationBundle(named bundleName: String, from sourceBundle: Bundle) throws -> Bundle {
let docsBundleURL = try createDirectoryForBundle(named: bundleName)
for sourceLprojURL in lProjURLs(for: sourceBundle) {
let sourceStringsURL = sourceLprojURL.appendingPathComponent(stringsFilename)
let docsLprojURL = docsBundleURL.appendingPathComponent(sourceLprojURL.lastPathComponent)
if FileManager.default.fileExists(atPath: sourceStringsURL.path) {
try? FileManager.default.removeItem(at: docsLprojURL) //in case already exists
try FileManager.default.copyItem(at: sourceLprojURL, to: docsLprojURL)
}
}
guard let newBundle = Bundle(url: docsBundleURL) else { throw LocalizationManager.Errors.copy }
return newBundle
}
private func translationsFromBundle(_ bundle: Bundle) throws -> Translations {
var translations: Translations = [:]
for sourceLprojURL in lProjURLs(for: bundle) {
let languageCode = sourceLprojURL.deletingPathExtension().lastPathComponent
let sourceStringsURL = sourceLprojURL.appendingPathComponent(stringsFilename)
if FileManager.default.isReadableFile(atPath: sourceStringsURL.path) {
let data = try Data(contentsOf: sourceStringsURL)
translations[languageCode] = try plistDecoder.decode(LanguageTranslations.self, from: data, format: &plistFormat)
}
}
return translations
}
private func localizationBundle(named bundleName: String, from translations: Translations) throws -> Bundle {
let docsBundleURL = try createDirectoryForBundle(named: bundleName)
for (languageCode, languageTranslations) in translations {
let lprojURL = docsBundleURL.appendingPathComponent("\(languageCode).\(lProjExtension)")
try FileManager.default.createDirectory(at: lprojURL, withIntermediateDirectories: false, attributes: nil)
let data = try plistEncoder.encode(languageTranslations)
try data.write(to: lprojURL.appendingPathComponent(stringsFilename), options: .atomic)
}
guard let newBundle = Bundle(url: docsBundleURL) else { throw LocalizationManager.Errors.creation }
return newBundle
}
private func setBundle(_ newBundle: Bundle) {
let oldBundle = currentBundle
currentBundle = newBundle
try? FileManager.default.removeItem(at: oldBundle.bundleURL) //clean up old bundle
}
func bundle(for languageCode: String? = nil) -> Bundle {
guard let languageCode = languageCode else { return currentBundle }
guard let url = lProjURL(for: languageCode) else { return currentBundle }
return Bundle(url: url) ?? currentBundle
}
func updateBundle(with translations: Translations) throws {
let existingTranslations = try translationsFromBundle(currentBundle)
let updatedTranslations = updateTranslations(existingTranslations, with: translations)
let newBundle = try localizationBundle(named: newBundleName(), from: updatedTranslations)
setBundle(newBundle)
}
}
| true
|
6bab24cbcb1636be8fbcd6cd2fbb2c3850c7557d
|
Swift
|
dknvmlhok/space-launches
|
/Space Launches/Launch Detail/View/LaunchDetail.swift
|
UTF-8
| 2,041
| 2.6875
| 3
|
[] |
no_license
|
//
// LaunchDetail.swift
// Space Launches
//
// Created by Dominik Kohlman on 27/02/2021.
//
import SwiftUI
struct LaunchDetail: View {
// MARK: - Properties
@ObservedObject var viewModel: LaunchDetailViewModel
// MARK: - View Body
var body: some View {
content
.navigationBarItems(trailing: RefreshButtonView(viewModel: viewModel))
.onAppear {
viewModel.send(event: .onAppear)
}
.alert(isPresented: alertBinding.0) {
let message = alertBinding.1.wrappedValue?.localizedDescription ?? Loca.errors.unknownError
return Alert(
title: Text(Loca.errors.networkError),
message: Text("\(Loca.errors.launchDetailLoadingError) \(message)."),
dismissButton: .cancel(Text(Loca.general.ok))
)
}
}
}
// MARK: - Content Generating
private extension LaunchDetail {
func generateContent(with launch: Launch) -> some View {
ScrollView {
LaunchDetailItems(launch)
.padding(.top)
}
}
var content: some View {
switch viewModel.detailState {
case .loading:
return SpinnerView().eraseToAnyView
case .loaded(let launch):
return generateContent(with: launch)
.eraseToAnyView
default:
return Color.clear.eraseToAnyView
}
}
}
// MARK: - Bindings
private extension LaunchDetail {
var alertBinding: Binding<(receivedError: Bool, error: NetworkError?)> {
guard case .error(let error) = viewModel.detailState else {
return Binding.constant((receivedError: false, error: nil))
}
return Binding.constant((receivedError: true, error: error))
}
}
// MARK: - Preview
#if DEBUG
struct LaunchDetail_Previews: PreviewProvider {
static var previews: some View {
LaunchDetail(viewModel: LaunchDetailViewModel(launchId: Launch.mock.id))
}
}
#endif
| true
|
5fa18dab6f1338d35b9e89cad44808157c25cc4c
|
Swift
|
cocos543/LeetCodeOffer
|
/LeetCodeOffer2021/Leet2021/Solution07.swift
|
UTF-8
| 1,675
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
//
// Solution07.swift
// LeetCodeOffer2021
//
// Created by Cocos on 2021/4/25.
//
import Foundation
/*
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution07 {
/*
根据前序遍历和中序遍历的特点, 先找到前序遍历的根节点和左右子树, 再递归左右子树.
*/
func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
if preorder.count == 0 || inorder.count == 0 {
return nil
}
let root = TreeNode(preorder[0])
// 从中序遍历中找到左右子树, 依次递归
// 这里强制解包, 如果输入的数组不合法直接让他crash掉即可.
let rootIdx = inorder.firstIndex(of: root.val)!
let leftPreArr = preorder[1 ..< (1 + rootIdx)]
let leftInArr = inorder[0 ..< rootIdx]
let rightPreArr = preorder[(1 + rootIdx) ..< preorder.endIndex]
let rightInArr = inorder[rootIdx + 1 ..< inorder.endIndex]
root.left = buildTree(Array(leftPreArr), Array(leftInArr))
root.right = buildTree(Array(rightPreArr), Array(rightInArr))
return root
}
}
| true
|
049da60df3a2b6528f7fac7217fa56108641039d
|
Swift
|
lizhijun/WaterfallGrid
|
/WaterfallGridSample/WaterfallGridSample/ContentView.swift
|
UTF-8
| 2,697
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright © 2019 Paolo Leonardi.
//
// Licensed under the MIT license. See the LICENSE file for more info.
//
import SwiftUI
struct ContentView: View {
@State var selectedTab = 0
var body: some View {
#if os(watchOS)
return List() {
NavigationLink(destination: RectanglesGrid(rectangles: .constant(Generator.Rectangles.random(editMode: .addRemove)),
settings: .constant(Settings.default(for: .rectangles(.addRemove))))
) {
Text("Rectangles")
}
NavigationLink(destination: ImagesGrid(images: .constant(Generator.Images.random()),
settings: .constant(Settings.default(for: .images)))
) {
Text("Images")
}
}
#elseif os(OSX)
return TabView(selection: $selectedTab) {
RectanglesGrid(rectangles: .constant(Generator.Rectangles.random(editMode: .addRemove)),
settings: .constant(Settings.default(for: .rectangles(.addRemove))))
.tabItem {
Text("Rectangles")
}.tag(0)
ImagesGrid(images: .constant(Generator.Images.random()), settings: .constant(Settings.default(for: .images)))
.tabItem {
Text("Images")
}.tag(1)
CardsGrid(cards: .constant(Generator.Cards.random()), settings: .constant(Settings.default(for: .cards)))
.tabItem {
Text("Cards")
}.tag(2)
}
#else
return TabView(selection: $selectedTab) {
RectanglesContainer(editMode: .addRemove)
.tabItem {
Image(systemName: "rectangle.3.offgrid.fill")
Text("Add / Remove")
}.tag(0)
RectanglesContainer(editMode: .swapResize)
.tabItem {
Image(systemName: "rectangle.fill.on.rectangle.angled.fill")
Text("Swap / Resize")
}.tag(1)
ImagesContainer()
.tabItem {
Image(systemName: "photo.on.rectangle")
Text("Images")
}.tag(2)
CardsContainer()
.tabItem {
Image(systemName: "doc.richtext")
Text("Cards")
}.tag(3)
}.edgesIgnoringSafeArea(.top)
#endif
}
}
struct ContainerView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
f44568d23bc5dad9576696c12e767bf4d29cfe32
|
Swift
|
barangngr/LookAround
|
/LookAround/LookAround/Scenes/Map/MapContracts.swift
|
UTF-8
| 640
| 2.671875
| 3
|
[] |
no_license
|
//
// MapContracts.swift
// LookAround
//
// Created by Baran on 5.06.2020.
// Copyright © 2020 Baran Gungor. All rights reserved.
//
import UIKit
// MARK: View
protocol MapViewProtocol: class {
func handleOutput(_ output: MapPresenterOutPut)
}
// MARK: - Presenter
protocol MapPresenterProtocol: class {
func goDetail(data: MapInfoModel)
}
enum MapPresenterOutPut {
}
// MARK: - Router
protocol MapRouterProtocol: class {
func navigate(to route: MapRoute)
}
enum MapRoute {
case goOnMap(data: MapInfoModel)
}
// Network kullanılmadığı için kod kalabalığı yapmaması adına Interactor class'ı eklenmemiştir.
| true
|
731e52b11d8d6b5e820aab073f742ea727fa5c85
|
Swift
|
hayashi311/InheritanceMe
|
/Sources/InheritanceMe/InheritanceMe.swift
|
UTF-8
| 588
| 3.234375
| 3
|
[] |
no_license
|
import Foundation
@objc public protocol RunableProtocolBasedNSObjct: NSObjectProtocol {
@objc optional func run1()
@objc func run2()
}
public protocol RunableProtocol {
func run()
}
open class InheritanceMe1: NSObject, RunableProtocolBasedNSObjct {
open func run2() {
print("InheritanceMe2 run2")
}
}
open class InheritanceMe2: NSObject, RunableProtocol {
open func run() {
print("InheritanceMe2 run")
}
}
open class InheritanceMe3: RunableProtocol {
public init() {}
open func run() {
print("InheritanceMe3 run")
}
}
| true
|
f28bea229130b48eae007bdd2c6f99ea72984713
|
Swift
|
afernandezgr/PracticaiOSAvanzado
|
/EverPobre/Views/NotebookCell.swift
|
UTF-8
| 2,327
| 2.65625
| 3
|
[] |
no_license
|
//
// NotebookCell.swift
// EverPobre
//
// Created by Adolfo Fernandez on 3/4/18.
// Copyright © 2018 Adolfo Fernandez. All rights reserved.
//
import UIKit
class NotebookCell : UITableViewHeaderFooterView {
var notebook : Notebook? {
didSet {
nameNotebookLabel.text = notebook?.title
defaultNoteBookImage.isHidden = !(notebook?.defaultNotebook)!
}
}
let nameNotebookLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 16)
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let defaultNoteBookImage: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "favorites"))
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.tintColor = .white
return imageView
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView?.backgroundColor = .lightBlue
addSubview(nameNotebookLabel)
nameNotebookLabel.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 16).isActive = true
nameNotebookLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor).isActive = true
nameNotebookLabel.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -58).isActive = true
nameNotebookLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
//print("\(notebook?.title) \(notebook?.defaultNotebook)")
addSubview(defaultNoteBookImage)
defaultNoteBookImage.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -16).isActive = true
defaultNoteBookImage.centerYAnchor.constraint(equalTo: safeAreaLayoutGuide.centerYAnchor).isActive = true
defaultNoteBookImage.heightAnchor.constraint(equalToConstant: 30).isActive = true
defaultNoteBookImage.widthAnchor.constraint(equalToConstant: 30).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
786befc97ca289e6596c94c8be42c6f373bb25f5
|
Swift
|
varunrau/FractionalIndex
|
/Tests/FractionalIndexTests/FractionalIndexTests.swift
|
UTF-8
| 1,858
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
@testable import FractionalIndex
final class FractionalIndexTests: XCTestCase {
func testGetMidpointTest() {
XCTAssertEqual(try! getMidpoint(a: "", b: nil), "V")
XCTAssertEqual(try! getMidpoint(a: "V", b: nil), "l")
XCTAssertEqual(try! getMidpoint(a: "l", b: nil), "t")
XCTAssertEqual(try! getMidpoint(a: "001", b: "001001"), "001000V")
}
func testIncrementInteger() {
XCTAssertEqual(try! incrementInteger(x: "a0"), "a1")
XCTAssertEqual(try! incrementInteger(x: "az"), "b00")
XCTAssertEqual(try! incrementInteger(x: "Zy"), "Zz")
XCTAssertEqual(try! incrementInteger(x: "zzzzzzzzzzzzzzzzzzzzzzzzzzz"), nil)
XCTAssertEqual(try! incrementInteger(x: "a0"), "a1")
}
func testDecrementInteger() {
XCTAssertEqual(try! decrementInteger(x: "a1"), "a0")
XCTAssertEqual(try! decrementInteger(x: "b00"), "az")
XCTAssertEqual(try! decrementInteger(x: "dAC00"), "dABzz")
XCTAssertEqual(try! decrementInteger(x: "A00000000000000000000000000"), nil)
XCTAssertEqual(try! decrementInteger(x: "Xz00"), "Xyzz")
}
func testGenerateKeyBetween() {
XCTAssertEqual(try! generateKeyBetween(a: "a0", b: nil), "a1")
XCTAssertEqual(try! generateKeyBetween(a: "a0", b: "a0V"), "a0G")
XCTAssertEqual(try! generateKeyBetween(a: nil, b: nil), "a0")
XCTAssertEqual(try! generateKeyBetween(a: "Zz", b: "a0"), "ZzV")
XCTAssertEqual(try! generateKeyBetween(a: "Zz", b: "a01"), "a0")
XCTAssertEqual(try! generateKeyBetween(a: nil, b: "a0"), "Zz")
}
static var allTests = [
("midpoint", testGetMidpointTest),
("increment", testIncrementInteger),
("decrement", testDecrementInteger),
("generateKeyBetween", testGenerateKeyBetween)
]
}
| true
|
df0ac1b3402568279986459df3db1ba1671e9d53
|
Swift
|
kostilal/EVOGallery
|
/EVOGallery/EVOGallery/Gallery/EVOGalleryFlowLayout.swift
|
UTF-8
| 791
| 2.609375
| 3
|
[] |
no_license
|
//
// EVOGalleryFlowLayout.swift
// Gallery
//
// Created by Костюкевич Илья on 23.10.2017.
// Copyright © 2017 evo.company. All rights reserved.
//
import UIKit
class EVOGalleryFlowLayout: UICollectionViewFlowLayout {
init(with frame: CGRect) {
super.init()
setup(with: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup(with: UIScreen.main.bounds)
}
private func setup(with frame: CGRect) {
self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.itemSize = CGSize(width: frame.size.width, height: frame.size.height)
self.scrollDirection = .horizontal
self.minimumLineSpacing = 0
self.minimumInteritemSpacing = 0
}
}
| true
|
0afec4f4435103f936444514de8f369c2013a7da
|
Swift
|
notoriousmarcos/TVMazeApp
|
/TVMazeApp/TVMazeApp/Main/Factory/ShowsViewFactory.swift
|
UTF-8
| 1,161
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// ShowsViewFactory.swift
// TVMazeApp
//
// Created by marcos.brito on 05/09/21.
//
import Foundation
import SwiftUI
protocol ShowsViewFactoryProtocol {
associatedtype ShowsViewModel: ShowsViewModelProtocol
associatedtype ShowDetailViewModel: ShowDetailViewModelProtocol
associatedtype SomeView: View
typealias OpenShowAction = (Show) -> SomeView
func make(openShowAction: @escaping OpenShowAction) -> ShowsView<ShowsViewModel, ShowDetailViewModel>
}
struct ShowsViewFactory: ShowsViewFactoryProtocol {
typealias SomeView = ShowDetailView<ShowDetailViewModel>
let fetchShowsByPageUseCase: FetchShowByPageUseCase
init(fetchShowsByPageUseCase: FetchShowByPageUseCase) {
self.fetchShowsByPageUseCase = fetchShowsByPageUseCase
}
func make(openShowAction: @escaping OpenShowAction) -> ShowsView<ShowsViewModel, ShowDetailViewModel> {
let viewModel = ShowsViewModel(
fetchShowsByPage: fetchShowsByPageUseCase.execute(page:)
)
return ShowsView<ShowsViewModel, ShowDetailViewModel>(
viewModel: viewModel,
openShow: openShowAction
)
}
}
| true
|
a46c2be79d055ab9d4692a3ddbaa4eacafb54fbd
|
Swift
|
wikiwikisf/PlayWithParse
|
/PlayWithParse/AppDelegate.swift
|
UTF-8
| 3,214
| 2.703125
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// PlayWithParse
//
// Created by Vicki Chun on 10/12/15.
// Copyright © 2015 Vicki Grospe. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let parseCredentials = Credentials.parseCredentials
let twitterCredentials = Credentials.twitterCredentials
struct Credentials {
static let parseCredentialsFile = "ParseCredentials"
static let parseCredentials = Credentials.loadFromPropertyListNamed(parseCredentialsFile)
static let twitterCredentialsFile = "TwitterCredentials"
static let twitterCredentials = Credentials.loadFromPropertyListNamed(twitterCredentialsFile)
let consumerKey: String
let consumerSecret: String
private static func loadFromPropertyListNamed(name: String) -> Credentials {
let path = NSBundle.mainBundle().pathForResource(name, ofType: "plist")!
let dictionary = NSDictionary(contentsOfFile: path)!
let consumerKey = dictionary["Key"] as! String
let consumerSecret = dictionary["Secret"] as! String
return Credentials(consumerKey: consumerKey, consumerSecret: consumerSecret)
}
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId(parseCredentials.consumerKey, clientKey: parseCredentials.consumerSecret)
PFTwitterUtils.initializeWithConsumerKey(twitterCredentials.consumerKey, consumerSecret: twitterCredentials.consumerSecret)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| true
|
b8900bf2ce6baef9ef76cdd172a14c3aa1785a03
|
Swift
|
patricoles/URBN-Explore
|
/URBN-Explore/SearchVC.swift
|
UTF-8
| 106,533
| 2.71875
| 3
|
[] |
no_license
|
//
// SearchVC.swift
// URBN-Explore
//
import UIKit
import WatchConnectivity
class SearchVC: UIViewController, UITableViewDataSource, UITableViewDelegate,UIPopoverPresentationControllerDelegate, Dimmable, WCSessionDelegate {
@IBOutlet weak var refineButtonLabel: UIBarButtonItem!
@IBOutlet weak var NavBar: UINavigationBar!
@IBOutlet weak var searchTableView: UITableView!
@IBOutlet weak var navtitle: UINavigationItem!
var rooms = [Room]()
var filterdRooms = [Room]()
var refinedRooms = [Room]()
var roomsUpdated = [Room]()
var isFiltered = ""
var session: WCSession!
// For Filtering
var filterFloor = ""
var filterKind = ""
let dimLevel: CGFloat = 0.5
let dimSpeed: Double = 0.5
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
print("Loaded SearchVC")
// Apple Watch
if (WCSession.isSupported()) {
session = WCSession.defaultSession()
session.delegate = self;
session.activateSession()
}
// Styling Navigation Bar
self.navtitle.title="Room List"
self.NavBar.titleTextAttributes =
[NSFontAttributeName: Font.NavigationTitle!,NSForegroundColorAttributeName: Color.GrayDark]
createRoomStructure()
loadingLocalData()
configureSearchController()
}
func configureSearchController() {
// Initialize and perform a minimum configuration to the search controller.
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search for a room..."
searchController.searchBar.sizeToFit()
searchController.searchBar.barTintColor = Color.White
searchController.searchBar.tintColor = Color.BlueLight
definesPresentationContext = true
// Add to tableview
searchTableView.tableHeaderView = searchController.searchBar
}
func loadingLocalData(){
// Look for stored value and assign to variables
let defaults = NSUserDefaults.standardUserDefaults()
if let floorKey = defaults.stringForKey("Floors")
{
print("Floor: \(floorKey)")
filterFloor = floorKey
}
if let roomKey = defaults.stringForKey("Room Type") {
print("Key: \(roomKey)")
filterKind = roomKey
}
if let Filtered = defaults.stringForKey("isFiltered") {
print("Filtered Value: \(Filtered)")
if Filtered == "1" {
print("Is currently being filtered")
isFiltered = "true"
} else {
print("Is not being filtered")
isFiltered = "false"
}
}
// If filtering options have been selected not blank then filter the array and make sure that it filters by both values else filter one or the other
if filterFloor != "" && filterKind != "" {
refinedRooms = rooms.filter{$0.Floor == filterFloor && $0.Type == filterKind}
refineButtonLabel.title = "Refine(2)"
} else if filterFloor != "" && filterKind == "" {
refinedRooms = rooms.filter{$0.Floor == filterFloor || $0.Type == filterKind}
refineButtonLabel.title = "Refine(1)"
} else if filterFloor == "" && filterKind != "" {
refinedRooms = rooms.filter{$0.Floor == filterFloor || $0.Type == filterKind}
refineButtonLabel.title = "Refine(1)"
}
// Add current structure to a new based on isFiltered status
if isFiltered == "true" {
roomsUpdated = refinedRooms
} else {
roomsUpdated = rooms
}
print("List Count: \(roomsUpdated.count)")
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
filterdRooms = roomsUpdated.filter { room in
return room.Name.lowercaseString.containsString(searchText.lowercaseString)
}
searchTableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filterdRooms.count
}
return roomsUpdated.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? SearchCell
let room: Room
if searchController.active && searchController.searchBar.text != "" {
room = filterdRooms[indexPath.row]
} else {
room = roomsUpdated[indexPath.row]
}
cell?.cellName!.text = room.Name
cell?.cellNumber!.text = room.Number
// Change image of cell based off type of room
if (room.Type == "Classroom") {
let image : UIImage = UIImage(named: "icon_room-class")!
cell?.cellImage.image = image
} else if (room.Type == "Office") {
let image : UIImage = UIImage(named: "icon_room-faculty")!
cell?.cellImage.image = image
} else if (room.Type == "Lab") {
let image : UIImage = UIImage(named: "icon_room-lab")!
cell?.cellImage.image = image
} else if (room.Type == "Restroom") {
let image : UIImage = UIImage(named: "icon_room-restroom")!
cell?.cellImage.image = image
}
return cell!
}
//
// func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// let headerCell = tableView.dequeueReusableCellWithIdentifier("headerCell") as! SearchCell
//
// headerCell.filterFloorCell.text = filterFloor
// headerCell.filterRoomType.text = filterKind
//
//
//
// return headerCell
// }
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Perform Segure Function with identfier
self.performSegueWithIdentifier("showModal", sender: indexPath);
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showModal") {
let rowSelected = (sender as! NSIndexPath).row
if let detailedVC = segue.destinationViewController as? SearchPopOver {
let room: Room
if searchController.active && searchController.searchBar.text != "" {
room = filterdRooms[rowSelected]
} else {
room = roomsUpdated[rowSelected]
}
// Remove presented Search Controller so new view can show
searchController.active = false
print(rowSelected)
detailedVC.detailRoom = room
dim(.In, alpha: dimLevel, speed: dimSpeed)
}
if (segue.identifier == "showFilterVC") {
// let controller = self.storyboard?.instantiateViewControllerWithIdentifier("FilterVC") as! Filter
}
}
}
@IBAction func unwindToSearchList(segue: UIStoryboardSegue) {
if(segue.sourceViewController .isKindOfClass(FilterVC))
{
print("Unwind from FilterVC")
loadingLocalData()
searchTableView.reloadData()
}
if(segue.sourceViewController .isKindOfClass(SearchPopOver))
{
dim(.Out, speed: dimSpeed)
print("Unwind from SearchPopOver")
//let view2:FilterVC = segue.sourceViewController as! FilterVC
// searchController.active = true
}
}
func createRoomStructure() {
rooms = [
Room(
Name:"URBN 103",
Zone:"lab_103_1",
Floor:"1",
Number:"103",
Type:"Office",
Description:"The Student Services office",
Features:"Advisors",
XCoordinate:"42733",
YCoordinate:"36908",
ZCoordinate:"1"
),
Room(
Name:"URBN 103A",
Zone:"office_103a_1",
Floor:"1",
Number:"103A",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"52644",
YCoordinate:"31365",
ZCoordinate:"1"
),
Room(
Name:"URBN 103B",
Zone:"office_103b_1",
Floor:"1",
Number:"103B",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"51561",
YCoordinate:"30618",
ZCoordinate:"1"
),
Room(
Name:"URBN 103C",
Zone:"office_103c_1",
Floor:"1",
Number:"103C",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"49114",
YCoordinate:"30626",
ZCoordinate:"1"
),
Room(
Name:"URBN 103D",
Zone:"office_103d_1",
Floor:"1",
Number:"103D",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"46926",
YCoordinate:"30610",
ZCoordinate:"1"
),
Room(
Name:"URBN 103E",
Zone:"office_103e_1",
Floor:"1",
Number:"103E",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"44654",
YCoordinate:"30603",
ZCoordinate:"1"
),
Room(
Name:"URBN 103F",
Zone:"office_103f_1",
Floor:"1",
Number:"103F",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"40659",
YCoordinate:"34682",
ZCoordinate:"1"
),
Room(
Name:"URBN 103G",
Zone:"office_103g_1",
Floor:"1",
Number:"103G",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"42771",
YCoordinate:"30603",
ZCoordinate:"1"
),
Room(
Name:"URBN 103J",
Zone:"office_103j_1",
Floor:"1",
Number:"103J",
Type:"Office",
Description:"One of the rooms for Student Services Faculty",
Features:"Advisors",
XCoordinate:"43625",
YCoordinate:"35665",
ZCoordinate:"1"
),
Room(
Name:"URBN 105",
Zone:"lab_105_1",
Floor:"1",
Number:"105",
Type:"Lab",
Description:"The Hybrid Lab, home to many different tools for the makers of the URBN Center",
Features:"Wood Cutters, Large Printers, Laser tools",
XCoordinate:"35894",
YCoordinate:"40910",
ZCoordinate:"1"
),
Room(
Name:"URBN 105a",
Zone:"lab_105a_1",
Floor:"1",
Number:"105a",
Type:"Lab",
Description:"The Hybrid Lab, home to many different tools for the makers of the URBN Center",
Features:"Wood Cutters, Large Printers, Laser tools",
XCoordinate:"33866",
YCoordinate:"30313",
ZCoordinate:"1"
),
Room(
Name:"URBN 105B",
Zone:"lab_105b_1",
Floor:"1",
Number:"105B",
Type:"Lab",
Description:"One of the secondary parts of the Hybrid Lab",
Features:"Wood Cutters, Large Printers, Laser tools",
XCoordinate:"38570",
YCoordinate:"25533",
ZCoordinate:"1"
),
Room(
Name:"URBN 106",
Zone:"classroom_106_1",
Floor:"1",
Number:"107",
Type:"Classroom",
Description:"The Seminar Room for Mad Dragon",
Features:"Projector",
XCoordinate:"17764",
YCoordinate:"47726",
ZCoordinate:"1"
),
Room(
Name:"URBN 108",
Zone:"classroom_106_1",
Floor:"1",
Number:"108",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom.",
Features:"Computers, Projector",
XCoordinate:"17764",
YCoordinate:"47726",
ZCoordinate:"1"
),
Room(
Name:"URBN 107",
Zone:"classroom_107_1",
Floor:"1",
Number:"107",
Type:"Classroom",
Description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
Features:"Feature 1, Feature 2, Feature 3",
XCoordinate:"26913",
YCoordinate:"39050",
ZCoordinate:"1"
),
Room(
Name:"URBN 109",
Zone:"classroom_109_1",
Floor:"1",
Number:"109",
Type:"Office",
Description:"The Home of Mad Dragon Enterprises.",
Features:"Projector",
XCoordinate:"27157",
YCoordinate:"40636",
ZCoordinate:"1"
),
Room(
Name:"URBN 110",
Zone:"office_110_1",
Floor:"1",
Number:"110",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"12366",
YCoordinate:"47681",
ZCoordinate:"1"
),
Room(
Name:"URBN 110a",
Zone:"office_110a_1",
Floor:"1",
Number:"110a",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"13372",
YCoordinate:"48779",
ZCoordinate:"1"
),
Room(
Name:"URBN 110b",
Zone:"office_110b_1",
Floor:"1",
Number:"110b",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"13372",
YCoordinate:"50974",
ZCoordinate:"1"
),
Room(
Name:"URBN 110c",
Zone:"office_110c_1",
Floor:"1",
Number:"110c",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"14089",
YCoordinate:"52514",
ZCoordinate:"1"
),
Room(
Name:"URBN 110d",
Zone:"office_110d_1",
Floor:"1",
Number:"110d",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"11786",
YCoordinate:"48748",
ZCoordinate:"1"
),
Room(
Name:"URBN 110e",
Zone:"office_110e_1",
Floor:"1",
Number:"110e",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"11085",
YCoordinate:"52682",
ZCoordinate:"1"
),
Room(
Name:"URBN 110f",
Zone:"office_110f_1",
Floor:"1",
Number:"110f",
Type:"Office",
Description:"The Design and Merchandising Faculty office.",
Features:"Faculty",
XCoordinate:"11771",
YCoordinate:"51020",
ZCoordinate:"1"
),
Room(
Name:"URBN 120",
Zone:"classroom_120_1",
Floor:"1",
Number:"123",
Type:"Classroom",
Description:"A large classroom great for lectures and critiques.",
Features:"Projector",
XCoordinate:"7974",
YCoordinate:"44921",
ZCoordinate:"1"
),
Room(
Name:"URBN 122",
Zone:"classroom_122_1",
Floor:"1",
Number:"122",
Type:"Classroom",
Description:"A large classroom great for lectures and critiques.",
Features:"Projector",
XCoordinate:"10567",
YCoordinate:"44425",
ZCoordinate:"1"
),
Room(
Name:"URBN 123",
Zone:"classroom_123_1",
Floor:"1",
Number:"123",
Type:"Classroom",
Description:"A large classroom great for lectures and critiques.",
Features:"Projector",
XCoordinate:"14013",
YCoordinate:"44524",
ZCoordinate:"1"
),
Room(
Name:"URBN 124",
Zone:"classroom_124_1",
Floor:"1",
Number:"124",
Type:"Lab",
Description:"A fully equipped audio lab.",
Features:"Keyboards, Microphones, Projector",
XCoordinate:"10399",
YCoordinate:"40720",
ZCoordinate:"1"
),
Room(
Name:"URBN 126",
Zone:"classroom_126_1",
Floor:"1",
Number:"126",
Type:"Lab",
Description:"A private fully equipped audio lab that is incredibly soundproof.",
Features:"Keyboards, Microphones, Instruments",
XCoordinate:"10071",
YCoordinate:"30267",
ZCoordinate:"1"
),
Room(
Name:"URBN 128",
Zone:"classroom_128_1",
Floor:"1",
Number:"128",
Type:"Lab",
Description:"A fully equipped audio lab.",
Features:"Keyboards, Microphones, Projector",
XCoordinate:"10376",
YCoordinate:"23116",
ZCoordinate:"1"
),
Room(
Name:"URBN 130",
Zone:"office_130a_1",
Floor:"1",
Number:"130A",
Type:"Lab",
Description:"One of the areas of the Historic Costume Collection",
Features:"Archives, Private Access",
XCoordinate:"14882",
YCoordinate:"22292",
ZCoordinate:"8"
),
Room(
Name:"URBN 130A",
Zone:"office_130a_1",
Floor:"1",
Number:"130A",
Type:"Lab",
Description:"One of the areas of the Historic Costume Collection",
Features:"Archives, Private Access", XCoordinate:"13912",
YCoordinate:"17163",
ZCoordinate:"8"
),
Room(
Name:"URBN 130C",
Zone:"classroom_130c_1",
Floor:"1",
Number:"130C",
Type:"Lab",
Description:"One of the areas of the Historic Costume Collection",
Features:"Archives, Private Access",
XCoordinate:"14935",
YCoordinate:"20295",
ZCoordinate:"1"
),
Room(
Name:"URBN 132",
Zone:"classroom_132_1",
Floor:"1",
Number:"132",
Type:"Classroom",
Description:"A classroom that is used as the meeting ground for the Lindy Institute",
Features:"Lindy Institute, Projector",
XCoordinate:"23245",
YCoordinate:"15789",
ZCoordinate:"1"
),
Room(
Name:"URBN 134",
Zone:"office_134_1",
Floor:"1",
Number:"134",
Type:"Office",
Description:"The faculty office for Arts Administration",
Features:"Faculty",
XCoordinate:"24724",
YCoordinate:"11459",
ZCoordinate:"1"
),
Room(
Name:"URBN 136",
Zone:"office_136_1",
Floor:"1",
Number:"136",
Type:"Office",
Description:"A faculty office.",
Features:"Faculty",
XCoordinate:"22513",
YCoordinate:"10147",
ZCoordinate:"1"
),
Room(
Name:"URBN 138",
Zone:"office_138_1",
Floor:"1",
Number:"138",
Type:"Office",
Description:"A faculty office.",
Features:"Faculty",
XCoordinate:"24153",
YCoordinate:"9583",
ZCoordinate:"1"
),
Room(
Name:"URBN 140",
Zone:"office_140_1",
Floor:"1",
Number:"140",
Type:"Office",
Description:"The office home of Westphal IT.",
Features:"Westphal IT",
XCoordinate:"24846",
YCoordinate:"6587",
ZCoordinate:"1"
),
Room(
Name:"URBN 141",
Zone:"classroom_141_1",
Floor:"1",
Number:"141",
Type:"Classroom",
Description:"A large classroom that's occasionally the place for events in the URBN Center.",
Features:"Projector, Whiteboard",
XCoordinate:"27355",
YCoordinate:"22231",
ZCoordinate:"1"
),
Room(
Name:"Floor 1 Unisex Restroom",
Zone:"bathroomUnisex_172_1",
Floor:"1",
Number:"172",
Type:"Restroom",
Description:"A unisex restroom with handicap-accessibility",
Features:"Water Fountain, Restroom",
XCoordinate:"47787",
YCoordinate:"20417",
ZCoordinate:"1"
),
Room(
Name:"Floor 1 Men's Restroom",
Zone:"bathroomUnisex_171_1",
Floor:"1",
Number:"171",
Type:"Restroom",
Description:"A men's restroom.",
Features:"Water Fountain, Restroom",
XCoordinate:"49183",
YCoordinate:"19502",
ZCoordinate:"1"
),
Room(
Name:"Floor 1 Women's Restroom",
Zone:"bathroomUnisex_173_1",
Floor:"1",
Number:"173",
Type:"Restroom",
Description:"A women's restroom.",
Features:"Water Fountain, Restroom",
XCoordinate:"49167",
YCoordinate:"26417",
ZCoordinate:"1"
),
Room(
Name:"URBN 1A10",
Zone:"office_1a10_1",
Floor:"1A",
Number:"1A10",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"25791",
YCoordinate:"32043",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10A",
Zone:"office_1a10A_1a",
Floor:"1A",
Number:"1A10A",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"22803",
YCoordinate:"30930",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10C",
Zone:"office_1a10c_1a",
Floor:"1A",
Number:"1A10C",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"22185",
YCoordinate:"32638",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10b",
Zone:"office_1a10b_1a",
Floor:"1A",
Number:"1A10b",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"21865",
YCoordinate:"30938",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10D",
Zone:"office_1a10d_1a",
Floor:"1A",
Number:"1A10D",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"25791",
YCoordinate:"32043",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10E",
Zone:"office_1a10e_1a",
Floor:"1A",
Number:"1A10E",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"22185",
YCoordinate:"39461",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10F",
Zone:"office_1a10f_1a",
Floor:"1A",
Number:"1A10F",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"22193",
YCoordinate:"40628",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10G",
Zone:"office_1a10g_1a",
Floor:"1A",
Number:"1A10G",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"22185",
YCoordinate:"43365",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10H",
Zone:"office_1a10h_1a",
Floor:"1A",
Number:"1A10H",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"23695",
YCoordinate:"43395",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10J",
Zone:"office_1a10j_1a",
Floor:"1A",
Number:"1A10J",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"23474",
YCoordinate:"39133",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A10K",
Zone:"office_1a10k_1a",
Floor:"1A",
Number:"1A10K",
Type:"Office",
Description:"The home of the Admissions and Administration faculty",
Features:"Faculty, Admissions",
XCoordinate:"23489",
YCoordinate:"37769",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A20",
Zone:"office_1a20_1a",
Floor:"1A",
Number:"1A20A",
Type:"Office",
Description:"One of the rooms for the faculty of the Dean.",
Features:"Faculty", XCoordinate:"30236",
YCoordinate:"20615",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A20A",
Zone:"office_1a20a_1a",
Floor:"1A",
Number:"1A20A",
Type:"Office",
Description:"One of the rooms for the faculty of the Dean.",
Features:"Faculty", XCoordinate:"31731",
YCoordinate:"22962",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A20B",
Zone:"office_1a20b_1a",
Floor:"1A",
Number:"1A20B",
Type:"Office",
Description:"One of the rooms for the faculty of the Dean.",
Features:"Faculty", XCoordinate:"30892",
YCoordinate:"18556",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A20D",
Zone:"office_1a20d_1a",
Floor:"1A",
Number:"1A20d",
Type:"Office",
Description:"One of the rooms for the faculty of the Dean.",
Features:"Faculty",
XCoordinate:"31746",
YCoordinate:"20996",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A20E",
Zone:"office_1a20e_1a",
Floor:"1A",
Number:"1A20E",
Type:"Office",
Description:"One of the rooms for the faculty of the Dean.",
Features:"Faculty", XCoordinate:"33393",
YCoordinate:"19532",
ZCoordinate:"2"
),
Room(
Name:"URBN 1A22",
Zone:"office_1a22_1a",
Floor:"1A",
Number:"1A22",
Type:"Office",
Description:"An open conference room used primarily by faculty.",
Features:"Projector, Engaging Artwork",
XCoordinate:"33393",
YCoordinate:"19532",
ZCoordinate:"2"
),
Room(
Name:"URBN 201",
Zone:"lab_201_2",
Floor:"2",
Number:"201",
Type:"Lab",
Description:"A large open area filled with desks and projects of product design students",
Features:"Student Installations, Swing",
XCoordinate:"43731",
YCoordinate:"40757",
ZCoordinate:"3"
),
Room(
Name:"URBN 201A",
Zone:"office_201a_2",
Floor:"2",
Number:"201A",
Type:"Lab",
Description:"An additional section of the large product design space",
Features:"Student Installations",
XCoordinate:"32402",
YCoordinate:"32508",
ZCoordinate:"3"
),
Room(
Name:"URBN 202",
Zone:"classroom_202_2",
Floor:"2",
Number:"202",
Type:"Classroom",
Description:"One of the graduate labs for Digital Media students",
Features:"Computers, Whiteboard, Projector",
XCoordinate:"45926",
YCoordinate:"48702",
ZCoordinate:"3"
),
Room(
Name:"URBN 204",
Zone:"lab_204_2",
Floor:"2",
Number:"204",
Type:"Lab",
Description:"A small room with a mounted television in the middle. Perfect for group meetings or presentation practices.",
Features:"Large TV",
XCoordinate:"43426",
YCoordinate:"49098",
ZCoordinate:"3"
),
Room(
Name:"URBN 206",
Zone:"classroom_206_2",
Floor:"2",
Number:"206",
Type:"Classroom",
Description:"One of the graduate labs for Digital Media students",
Features:"Computers, Whiteboard, Projector",
XCoordinate:"40986",
YCoordinate:"48580",
ZCoordinate:"3"
),
Room(
Name:"URBN 210",
Zone:"office_210_2",
Floor:"2",
Number:"210",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"17611",
YCoordinate:"47680",
ZCoordinate:"3"
),
Room(
Name:"URBN 210a",
Zone:"office_210a_2",
Floor:"2",
Number:"210a",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"30938",
YCoordinate:"52056",
ZCoordinate:"3"
),
Room(
Name:"URBN 210b",
Zone:"office_210b_2",
Floor:"2",
Number:"210b",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"27827",
YCoordinate:"52071",
ZCoordinate:"3"
),
Room(
Name:"URBN 210c",
Zone:"office_210c_2",
Floor:"2",
Number:"210c",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"24747",
YCoordinate:"52087",
ZCoordinate:"3"
),
Room(
Name:"URBN 210d",
Zone:"office_210d_2",
Floor:"2",
Number:"210d",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"21743",
YCoordinate:"52102",
ZCoordinate:"3"
),
Room(
Name:"URBN 210e",
Zone:"office_210e_2",
Floor:"2",
Number:"210e",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"18709",
YCoordinate:"52071",
ZCoordinate:"3"
),
Room(
Name:"URBN 210f",
Zone:"office_210f_2",
Floor:"2",
Number:"210f",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"17184",
YCoordinate:"51538",
ZCoordinate:"3"
),
Room(
Name:"URBN 210g",
Zone:"office_210g_2",
Floor:"2",
Number:"210g",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"17169",
YCoordinate:"49693",
ZCoordinate:"3"
),
Room(
Name:"URBN 210h",
Zone:"office_210h_2",
Floor:"2",
Number:"210h",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"19669",
YCoordinate:"50882",
ZCoordinate:"3"
),
Room(
Name:"URBN 210j",
Zone:"office_210j_2",
Floor:"2",
Number:"210j",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"21804",
YCoordinate:"50882",
ZCoordinate:"3"
),
Room(
Name:"URBN 210k",
Zone:"office_210k_2",
Floor:"2",
Number:"210k",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"23893",
YCoordinate:"50897",
ZCoordinate:"3"
),
Room(
Name:"URBN 210l",
Zone:"office_210l_2",
Floor:"2",
Number:"210l",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"25997",
YCoordinate:"50882",
ZCoordinate:"3"
),
Room(
Name:"URBN 210m",
Zone:"office_210m_2",
Floor:"2",
Number:"210m",
Type:"Office",
Description:"The offices of the Arts and Entertainment Faculty",
Features:"Faculty",
XCoordinate:"28208",
YCoordinate:"50867",
ZCoordinate:"3"
),
Room(
Name:"URBN 220",
Zone:"office_220_2",
Floor:"2",
Number:"220",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"8554",
YCoordinate:"48290",
ZCoordinate:"3"
),
Room(
Name:"URBN 220a",
Zone:"office_220a_2",
Floor:"2",
Number:"220a",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"10246",
YCoordinate:"49312",
ZCoordinate:"3"
),
Room(
Name:"URBN 220c",
Zone:"office_220c_2",
Floor:"2",
Number:"220c",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"10658",
YCoordinate:"53124",
ZCoordinate:"3"
),
Room(
Name:"URBN 220d",
Zone:"office_220d_2",
Floor:"2",
Number:"220d",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"5687",
YCoordinate:"51202",
ZCoordinate:"3"
),
Room(
Name:"URBN 220e",
Zone:"office_220e_2",
Floor:"2",
Number:"220e",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"2698",
YCoordinate:"52193",
ZCoordinate:"3"
),
Room(
Name:"URBN 220f",
Zone:"office_220f_2",
Floor:"2",
Number:"220f",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"2561",
YCoordinate:"49251",
ZCoordinate:"3"
),
Room(
Name:"URBN 220g",
Zone:"office_220g_2",
Floor:"2",
Number:"220g",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"4406",
YCoordinate:"49845",
ZCoordinate:"3"
),
Room(
Name:"URBN 220h",
Zone:"office_220h_2",
Floor:"2",
Number:"220h",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"6800",
YCoordinate:"49876",
ZCoordinate:"3"
),
Room(
Name:"URBN 230",
Zone:"office_230_2",
Floor:"2",
Number:"230",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"6907",
YCoordinate:"41245",
ZCoordinate:"3"
),
Room(
Name:"URBN 230a",
Zone:"office_230a_2",
Floor:"2",
Number:"230a",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"6114",
YCoordinate:"42236",
ZCoordinate:"3"
),
Room(
Name:"URBN 230b",
Zone:"office_230b_2",
Floor:"2",
Number:"230b",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"4391",
YCoordinate:"42236",
ZCoordinate:"3"
),
Room(
Name:"URBN 230c",
Zone:"office_230c_2",
Floor:"2",
Number:"230c",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"2271",
YCoordinate:"42801",
ZCoordinate:"3"
),
Room(
Name:"URBN 230d",
Zone:"office_230d_2",
Floor:"2",
Number:"230d",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"2332",
YCoordinate:"40117",
ZCoordinate:"3"
),
Room(
Name:"URBN 230e",
Zone:"office_230e_2",
Floor:"2",
Number:"230e",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"4315",
YCoordinate:"40712",
ZCoordinate:"3"
),
Room(
Name:"URBN 230f",
Zone:"office_230f_2",
Floor:"2",
Number:"230f",
Type:"Office",
Description:"Half of the offices of the Digital Media Faculty",
Features:"Faculty",
XCoordinate:"6160",
YCoordinate:"40727",
ZCoordinate:"3"
),
Room(
Name:"URBN 239",
Zone:"lab_239_2",
Floor:"2",
Number:"239",
Type:"Lab",
Description:"Known as the Cushion Room, this screening room features a large projector and is primarily used for presentations and events",
Features:"Cushions, Projector, Whiteboard", XCoordinate:"12106",
YCoordinate:"39248",
ZCoordinate:"3"
),
Room(
Name:"URBN 240",
Zone:"lab_240_2",
Floor:"2",
Number:"240",
Type:"Lab",
Description:"The equipment room for Digital Media students",
Features:"Equipment for renting",
XCoordinate:"7105",
YCoordinate:"36229",
ZCoordinate:"3"
),
Room(
Name:"URBN 241",
Zone:"office_241_2",
Floor:"2",
Number:"241",
Type:"Office",
Description:"A separate faculty office, usually for adjunct professors or specialized professionals.",
Features:"Faculty",
XCoordinate:"14378",
YCoordinate:"37479",
ZCoordinate:"3"
),
Room(
Name:"URBN 242",
Zone:"office_242_1",
Floor:"2",
Number:"242",
Type:"Office",
Description:"A separate faculty office, usually for adjunct professors or specialized professionals.",
Features:"Faculty",
XCoordinate:"8470",
YCoordinate:"35504",
ZCoordinate:"3"
),
Room(
Name:"URBN 243",
Zone:"lab_243_1",
Floor:"2",
Number:"243",
Type:"Lab",
Description:"One of the graduate labs for Digital Media students",
Features:"Computers, Whiteboard, Projector",
XCoordinate:"14424",
YCoordinate:"28468",
ZCoordinate:"3"
),
Room(
Name:"URBN 244",
Zone:"office_244_2",
Floor:"2",
Number:"244",
Type:"Office",
Description:"A separate faculty office, usually for adjunct professors or specialized professionals.",
Features:"Faculty",
XCoordinate:"11153",
YCoordinate:"32470",
ZCoordinate:"3"
),
Room(
Name:"URBN 245",
Zone:"lab_245_2",
Floor:"2",
Number:"245",
Type:"Lab",
Description:"A lab full of computers, one that classes aren't held in.",
Features:"Computers",
XCoordinate:"15141",
YCoordinate:"24000",
ZCoordinate:"3"
),
Room(
Name:"URBN 246",
Zone:"lab_246_2",
Floor:"2",
Number:"246",
Type:"Lab",
Description:"The motion capture room, one of the more impressive spots of the URBN Center",
Features:"Motion Capture Studio",
XCoordinate:"11207",
YCoordinate:"30221",
ZCoordinate:"3"
),
Room(
Name:"URBN 247",
Zone:"office_247_2",
Floor:"2",
Number:"247",
Type:"Classroom",
Description:"Dubbed the 'Fishbowl Room' by the students at Drexel, this computer lab has half of its walls acting as windows.",
Features:"Projector, Computers, Whiteboard",
XCoordinate:"15476",
YCoordinate:"12106",
ZCoordinate:"3"
),
Room(
Name:"URBN 248",
Zone:"classroom_248_2",
Floor:"2",
Number:"248",
Type:"Classroom",
Description:"A computer lab that also acts as a classroom",
Features:"Computers, Projector, Whiteboard",
XCoordinate:"10231",
YCoordinate:"12777",
ZCoordinate:"3"
),
Room(
Name:"URBN 250",
Zone:"office_250_2",
Floor:"2",
Number:"250",
Type:"Classroom",
Description:"A computer lab that also acts as a classroom",
Features:"Computers, Projector, Whiteboard", XCoordinate:"8005",
YCoordinate:"10414",
ZCoordinate:"3"
),
Room(
Name:"URBN 252",
Zone:"office_252_2",
Floor:"2",
Number:"252",
Type:"Classroom",
Description:"A computer lab that also acts as a classroom, used heavily as a render farm towards the end of the term",
Features:"Computers, Projector, Whiteboard, Render Farm", XCoordinate:"8691",
YCoordinate:"7761",
ZCoordinate:"3"
),
Room(
Name:"URBN 260",
Zone:"office_260_2",
Floor:"2",
Number:"260",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"37250",
YCoordinate:"7745",
ZCoordinate:"3"
),
Room(
Name:"URBN 260a",
Zone:"office_260a_2",
Floor:"2",
Number:"260a",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"31273",
YCoordinate:"6800",
ZCoordinate:"3"
),
Room(
Name:"URBN 260b",
Zone:"office_260b_2",
Floor:"2",
Number:"260b",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"31273",
YCoordinate:"4681",
ZCoordinate:"3"
),
Room(
Name:"URBN 260c",
Zone:"office_260c_2",
Floor:"2",
Number:"260c",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"31685",
YCoordinate:"1799",
ZCoordinate:"3"
),
Room(
Name:"URBN 260d",
Zone:"office_260d_2",
Floor:"2",
Number:"260d",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"36778",
YCoordinate:"2820",
ZCoordinate:"3"
),
Room(
Name:"URBN 260e",
Zone:"office_260e_2",
Floor:"2",
Number:"260e",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"32462",
YCoordinate:"5900",
ZCoordinate:"3"
),
Room(
Name:"URBN 260f",
Zone:"office_260f_2",
Floor:"2",
Number:"260f",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"36701",
YCoordinate:"6129",
ZCoordinate:"3"
),
Room(
Name:"URBN 260g",
Zone:"office_260g_2",
Floor:"2",
Number:"260g",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"37586",
YCoordinate:"1814",
ZCoordinate:"3"
),
Room(
Name:"URBN 260h",
Zone:"office_260h_2",
Floor:"2",
Number:"260h",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"37845",
YCoordinate:"4574",
ZCoordinate:"3"
),
Room(
Name:"URBN 260j",
Zone:"office_260j_2",
Floor:"2",
Number:"260j",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"37860",
YCoordinate:"6587",
ZCoordinate:"3"
), Room(
Name:"URBN 261",
Zone:"lab_261_2",
Floor:"2",
Number:"261",
Type:"Office",
Description:"The offices of the Music Industry faculty",
Features:"Faculty",
XCoordinate:"39965",
YCoordinate:"13311",
ZCoordinate:"3"
),
Room(
Name:"URBN 262",
Zone:"lab_262_2",
Floor:"2",
Number:"262",
Type:"Lab",
Description:"Dubbed the Make Lab, a product design workshop and studio",
Features:"3D printer, Wood cutting",
XCoordinate:"44768",
YCoordinate:"12472",
ZCoordinate:"3"
),
Room(
Name:"URBN 262A",
Zone:"lab_262a_2",
Floor:"2",
Number:"262A",
Type:"Lab",
Description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
Features:"Feature 1, Feature 2, Feature 3",
XCoordinate:"46048",
YCoordinate:"11146",
ZCoordinate:"3"
),
Room(
Name:"URBN 262A",
Zone:"lab_262a_2",
Floor:"2",
Number:"262A",
Type:"Lab",
Description:"An additional section of the Make Lab for storing and working on projects",
Features:"Garage",
XCoordinate:"43777",
YCoordinate:"15568",
ZCoordinate:"3"
),
Room(
Name:"URBN 265",
Zone:"classroom_265_2",
Floor:"2",
Number:"265",
Type:"Classroom",
Description:"A general classroom",
Features:"Projector",
XCoordinate:"43761",
YCoordinate:"26927",
ZCoordinate:"3"
),
Room(
Name:"URBN 270",
Zone:"office_270_2",
Floor:"2",
Number:"270",
Type:"Office",
Description:"The offices of the Product Design faculty",
Features:"Faculty",
XCoordinate:"47177",
YCoordinate:"31624",
ZCoordinate:"3"
),
Room(
Name:"Floor 2 Men's Restroom",
Zone:"bathroomMens_271_2",
Floor:"2",
Number:"271",
Type:"Restroom",
Description:"A men's restroom",
Features:"Water Fountain, Restroom",
XCoordinate:"49098",
YCoordinate:"19532",
ZCoordinate:"3"
),
Room(
Name:"Floor 2 Unisex Restroom",
Zone:"bathroomUnisex_272_2",
Floor:"2",
Number:"272",
Type:"Restroom",
Description:"A unisex restroom with handicap-accessibility",
Features:"Water Fountain, Restroom",
XCoordinate:"47863",
YCoordinate:"20447",
ZCoordinate:"3"
),
Room(
Name:"Floor 2 Women's Restroom",
Zone:"bathroomWomens_273_2",
Floor:"2",
Number:"273",
Type:"Restroom",
Description:"A women's restroom",
Features:"Water Fountain, Restroom",
XCoordinate:"49098",
YCoordinate:"26470",
ZCoordinate:"3"
),
Room(
Name:"URBN 2A10",
Zone:"lab_2a10_2a",
Floor:"2A",
Number:"2A10",
Type:"Lab",
Description:"Dubbed the Replay Lab, a game design research facility.",
Features:"Game consoles and technology",
XCoordinate:"23870",
YCoordinate:"29367",
ZCoordinate:"4"
),
Room(
Name:"URBN 2A10A",
Zone:"office_2a10a_2a",
Floor:"2A",
Number:"2A10A",
Type:"Classroom",
Description:"An additional section of the game research design facility for testing games.",
Features:"Game consoles and technology",
XCoordinate:"21789",
YCoordinate:"35916",
ZCoordinate:"4"
),
Room(
Name:"URBN 2A11",
Zone:"classroom_2a11_2a",
Floor:"2A",
Number:"2A11",
Type:"Classroom",
Description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
Features:"Feature 1, Feature 2, Feature 3",
XCoordinate:"25875",
YCoordinate:"38220",
ZCoordinate:"4"
),
Room(
Name:"URBN 2A20",
Zone:"lab_2a20_2a",
Floor:"2A",
Number:"2A20",
Type:"Lab",
Description:"A product design lab that benefits from its large windows with lots of space for sticky notes.",
Features:"Large TV, 3D Printer, Computers",
XCoordinate:"32020",
YCoordinate:"19319",
ZCoordinate:"4"
),
Room(
Name:"URBN 2A21",
Zone:"lab_2a21_2a",
Floor:"2A",
Number:"2A21",
Type:"Lab",
Description:"Dubbed the Den of Sin, a product design lab that has no natural light or light from outside rooms.",
Features:"Computers",
XCoordinate:"30236",
YCoordinate:"18633",
ZCoordinate:"4"
),
Room(
Name:"URBN 302",
Zone:"lab_302_3",
Floor:"3",
Number:"302",
Type:"Lab",
Description:"A drawing studio with open space for setting up easels.",
Features:"Projector",
XCoordinate:"45111",
YCoordinate:"45972",
ZCoordinate:"5"
),
Room(
Name:"URBN 310",
Zone:"office_310_3",
Floor:"3",
Number:"310",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"27065",
YCoordinate:"48275",
ZCoordinate:"5"
),
Room(
Name:"URBN 310",
Zone:"office_310_3",
Floor:"3",
Number:"310",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"27065",
YCoordinate:"48275",
ZCoordinate:"5"
),
Room(
Name:"URBN 310a",
Zone:"office_310a_3",
Floor:"3",
Number:"310a",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"39919",
YCoordinate:"49334",
ZCoordinate:"5"
), Room(
Name:"URBN 310b",
Zone:"office_310b_3",
Floor:"3",
Number:"310b",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"39972",
YCoordinate:"51553",
ZCoordinate:"5"
), Room(
Name:"URBN 310c",
Zone:"office_310c_3",
Floor:"3",
Number:"310c",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"38379",
YCoordinate:"52239",
ZCoordinate:"5"
), Room(
Name:"URBN 310d",
Zone:"office_310d_3",
Floor:"3",
Number:"310d",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"35413",
YCoordinate:"52254",
ZCoordinate:"5"
), Room(
Name:"URBN 310e",
Zone:"office_310e_3",
Floor:"3",
Number:"310e",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"32402",
YCoordinate:"52262",
ZCoordinate:"5"
), Room(
Name:"URBN 310f",
Zone:"office_310f_3",
Floor:"3",
Number:"310e",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"29375",
YCoordinate:"52247",
ZCoordinate:"5"
), Room(
Name:"URBN 310g",
Zone:"office_310g_3",
Floor:"3",
Number:"310g",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"26409",
YCoordinate:"52270",
ZCoordinate:"5"
), Room(
Name:"URBN 310h",
Zone:"office_310h_3",
Floor:"3",
Number:"310h",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"23321",
YCoordinate:"52247",
ZCoordinate:"5"
),
Room(
Name:"URBN 310j",
Zone:"office_310j_3",
Floor:"3",
Number:"310j",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"20302",
YCoordinate:"52262",
ZCoordinate:"5"
), Room(
Name:"URBN 310k",
Zone:"office_310k_3",
Floor:"3",
Number:"310k",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"22643",
YCoordinate:"51004",
ZCoordinate:"5"
), Room(
Name:"URBN 310m",
Zone:"office_310m_3",
Floor:"3",
Number:"310m",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"32112",
YCoordinate:"51004",
ZCoordinate:"5"
),
Room(
Name:"URBN 310n",
Zone:"office_310n_3",
Floor:"3",
Number:"310n",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"35299",
YCoordinate:"51004",
ZCoordinate:"5"
), Room(
Name:"URBN 310p",
Zone:"office_310p_3",
Floor:"3",
Number:"310p",
Type:"Office",
Description:"The offices of the Department of Design faculty",
Features:"Faculty",
XCoordinate:"37403",
YCoordinate:"50989",
ZCoordinate:"5"
),
Room(
Name:"URBN 321",
Zone:"lab_321_3",
Floor:"3",
Number:"321",
Type:"Lab",
Description:"A large space that acts as fashion research lab.",
Features:"Projector, Computer",
XCoordinate:"24793",
YCoordinate:"44585",
ZCoordinate:"5"
),
Room(
Name:"URBN 322",
Zone:"classroom_322_3",
Floor:"3",
Number:"322",
Type:"Classroom",
Description:"A large open lab with sewing stations and general fashion work.",
Features:"Sewing",
XCoordinate:"8996",
YCoordinate:"47726",
ZCoordinate:"5"
),
Room(
Name:"URBN 323",
Zone:"lab_323_3",
Floor:"3",
Number:"323",
Type:"Lab",
Description:"A laundry room for fashion students' projects, not community access.",
Features:"Washer, Dryer",
XCoordinate:"10650",
YCoordinate:"46140",
ZCoordinate:"5"
),
Room(
Name:"URBN 324",
Zone:"lab_324_3",
Floor:"3",
Number:"324",
Type:"Lab",
Description:"A large open lab with sewing stations and general fashion work.",
Features:"Sewing",
XCoordinate:"6038",
YCoordinate:"46864",
ZCoordinate:"5"
),
Room(
Name:"URBN 325",
Zone:"classroom_325_3",
Floor:"3",
Number:"325",
Type:"Classroom",
Description:"A lab for research and general design work.",
Features:"Computers",
XCoordinate:"9408",
YCoordinate:"40834",
ZCoordinate:"5"
),
Room(
Name:"URBN 326",
Zone:"lab_326_3",
Floor:"3",
Number:"326",
Type:"Lab",
Description:"A large open lab with sewing stations and general fashion work.",
Features:"Sewing",
XCoordinate:"7380",
YCoordinate:"40559",
ZCoordinate:"5"
),
Room(
Name:"URBN 327",
Zone:"lab_327_3",
Floor:"3",
Number:"327",
Type:"Lab",
Description:"A sewing station for fashion students' projects.",
Features:"Sewing",
XCoordinate:"9408",
YCoordinate:"29146",
ZCoordinate:"5"
),
Room(
Name:"URBN 328",
Zone:"classroom_328_3",
Floor:"3",
Number:"328",
Type:"Classroom",
Description:"A large open lab with sewing stations and general fashion work.",
Features:"Sewing",
XCoordinate:"9972",
YCoordinate:"15202",
ZCoordinate:"5"
),
Room(
Name:"URBN 329",
Zone:"classroom_329_3",
Floor:"3",
Number:"329",
Type:"Classroom",
Description:"A sewing station for fashion students' projects.",
Features:"Sewing",
XCoordinate:"11679",
YCoordinate:"22002",
ZCoordinate:"5"
),
Room(
Name:"URBN 330",
Zone:"classroom_330_3",
Floor:"3",
Number:"330",
Type:"Classroom",
Description:"A large open lab with sewing stations and general fashion work.",
Features:"Sewing",
XCoordinate:"10795",
YCoordinate:"8035",
ZCoordinate:"5"
),
Room(
Name:"URBN 331",
Zone:"classroom_331_3",
Floor:"3",
Number:"331",
Type:"Classroom",
Description:"A classroom that doubles as a storage area for fashions students",
Features:"Archives",
XCoordinate:"11710",
YCoordinate:"15141",
ZCoordinate:"5"
),
Room(
Name:"URBN 333",
Zone:"classroom_333_3",
Floor:"3",
Number:"333",
Type:"Classroom",
Description:"A studio and storage space for fashion students",
Features:"Sewing, Archives",
XCoordinate:"11710",
YCoordinate:"10521",
ZCoordinate:"5"
),
Room(
Name:"URBN 340",
Zone:"classroom_340_3",
Floor:"3",
Number:"340",
Type:"Classroom",
Description:"Dubbed the Mary McCue Epstein Classroom, a computer lab for general research and work",
Features:"Computers",
XCoordinate:"33393",
YCoordinate:"7791",
ZCoordinate:"5"
),
Room(
Name:"URBN 341A",
Zone:"classroom_341a_3",
Floor:"3",
Number:"341A",
Type:"Classroom",
Description:"An open area in the hallway that doubles as a meeting place and classroom.",
Features:"TV, Movable Walls",
XCoordinate:"30770",
YCoordinate:"12808",
ZCoordinate:"5"
),
Room(
Name:"URBN 341B",
Zone:"classroom_341b_3",
Floor:"3",
Number:"341B",
Type:"Classroom",
Description:"An open area in the hallway that doubles as a meeting place and classroom.",
Features:"TV, Movable Walls",
XCoordinate:"31639",
YCoordinate:"20218",
ZCoordinate:"5"
),
Room(
Name:"URBN 341C",
Zone:"classroom_341c_3",
Floor:"3",
Number:"341C",
Type:"Classroom",
Description:"An open area in the hallway that doubles as a meeting place and classroom.",
Features:"TV, Movable Walls",
XCoordinate:"32188",
YCoordinate:"25311",
ZCoordinate:"5"
),
Room(
Name:"URBN 347",
Zone:"office_347_3",
Floor:"3",
Number:"347",
Type:"Office",
Description:"A computer lab for general research and work",
Features:"Computers",
XCoordinate:"35909",
YCoordinate:"22338",
ZCoordinate:"5"
),
Room(
Name:"URBN 343",
Zone:"office_343_3",
Floor:"3",
Number:"343",
Type:"Office",
Description:"An office that doubles as a studio space.",
Features:"Building stations, Computers",
XCoordinate:"43655",
YCoordinate:"13585",
ZCoordinate:"5"
),
Room(
Name:"URBN 345",
Zone:"office_345_3",
Floor:"3",
Number:"345",
Type:"Office",
Description:"A computer lab for general research and work",
Features:"Computers",
XCoordinate:"43670",
YCoordinate:"19578",
ZCoordinate:"5"
),
Room(
Name:"URBN 348",
Zone:"classroom_348_3",
Floor:"3",
Number:"348",
Type:"Classroom",
Description:"A room used primarily for presentations or group meetings.",
Features:"Projector",
XCoordinate:"45987",
YCoordinate:"31700",
ZCoordinate:"5"
),
Room(
Name:"URBN 349",
Zone:"lab_349_3",
Floor:"3",
Number:"349",
Type:"Classroom",
Description:"Dubbed the Screening Room, a larger area used for classes and events",
Features:"Projector, Theater-style seating",
XCoordinate:"35649",
YCoordinate:"30267",
ZCoordinate:"5"
),
Room(
Name:"URBN 301",
Zone:"lab_301_3",
Floor:"3",
Number:"301",
Type:"Classroom",
Description:"Dubbed the Screening Room, a larger area used for classes and events",
Features:"Projector, Theater-style seating",
XCoordinate:"33286",
YCoordinate:"37571",
ZCoordinate:"5"
),
Room(
Name:"Floor 3 Men's Restroom",
Zone:"bathroomMens_371_3",
Floor:"3",
Number:"371",
Type:"Restroom",
Description:"A men's restroom",
Features:"Water Fountain, Restroom",
XCoordinate:"49144",
YCoordinate:"19502",
ZCoordinate:"5"
),
Room(
Name:"Floor 3 Unisex Restroom",
Zone:"bathroomUnisex_372_3",
Floor:"3",
Number:"372",
Type:"Restroom",
Description:"A unisex restroom with handicap-accessibility",
Features:"Water Fountain, Restroom",
XCoordinate:"47787",
YCoordinate:"20340",
ZCoordinate:"5"
),
Room(
Name:"Floor 3 Women's Restroom",
Zone:"bathroomWomens_373_3",
Floor:"3",
Number:"373",
Type:"Restroom",
Description:"A women's restroom",
Features:"Water Fountain, Restroom",
XCoordinate:"49266",
YCoordinate:"26379",
ZCoordinate:"5"
),
Room(
Name:"URBN 3A11",
Zone:"classroom_3a11_3a",
Floor:"3A",
Number:"3A11",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom",
Features:"Computers",
XCoordinate:"25952",
YCoordinate:"38165",
ZCoordinate:"6"
),
Room(
Name:"Floor 3 Computer Lab",
Zone:"lab_computer_3a",
Floor:"3A",
Number:"3A12",
Type:"Lab",
Description:"A general computer lab with a large printer used primarily by Architecture students",
Features:"Computers, Printer",
XCoordinate:"23969",
YCoordinate:"29443",
ZCoordinate:"6"
),
Room(
Name:"URBN 3A20",
Zone:"lab_3a20_3a",
Floor:"3A",
Number:"3A20",
Type:"Lab",
Description:"The Westphal Print Center, that handles quality prints for items around the URBN Center and most students' work",
Features:"Laser Printing, Large and Small Prints",
XCoordinate:"32356",
YCoordinate:"25708",
ZCoordinate:"6"
),
Room(
Name:"URBN 3A21",
Zone:"classroom_3a21_3a",
Floor:"3A",
Number:"3A21",
Type:"Classroom",
Description:"This classroom also functions as a library of sorts for materials relating to programs housed in the URBN Center",
Features:"Library, Computer",
XCoordinate:"30114",
YCoordinate:"14340",
ZCoordinate:"6"
),
Room(
Name:"URBN 401",
Zone:"lab_401_4",
Floor:"4",
Number:"401",
Type:"Lab",
Description:"A general computer lab that functions as a classroom and graphic design studio",
Features:"Computers, Cutting board, Photo studio",
XCoordinate:"33804",
YCoordinate:"37708",
ZCoordinate:"7"
),
Room(
Name:"URBN 402",
Zone:"classroom_402_4",
Floor:"4",
Number:"402",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom and graphic design studio",
Features:"Computers, Cutting board",
XCoordinate:"47634",
YCoordinate:"46674",
ZCoordinate:"7"
),
Room(
Name:"URBN 406",
Zone:"classroom_406_4",
Floor:"4",
Number:"406",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom and graphic design studio",
Features:"Computers, Cutting board",
XCoordinate:"46948",
YCoordinate:"47726",
ZCoordinate:"7"
),
Room(
Name:"URBN 408",
Zone:"classroom_408_4",
Floor:"4",
Number:"408",
Type:"Classroom",
Description:"A general drawing studio",
Features:"Easels",
XCoordinate:"29916",
YCoordinate:"47467",
ZCoordinate:"7"
),
Room(
Name:"URBN 410",
Zone:"office_410_4",
Floor:"4",
Number:"410",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"14965",
YCoordinate:"47718",
ZCoordinate:"7"
),
Room(
Name:"URBN 410a",
Zone:"office_410a_4",
Floor:"4",
Number:"410a",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"27873",
YCoordinate:"51965",
ZCoordinate:"7"
),
Room(
Name:"URBN 410b",
Zone:"office_410b_4",
Floor:"4",
Number:"410b",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"24808",
YCoordinate:"52010",
ZCoordinate:"7"
),
Room(
Name:"URBN 410c",
Zone:"office_410c_4",
Floor:"4",
Number:"410c",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"21728",
YCoordinate:"51995",
ZCoordinate:"7"
),
Room(
Name:"URBN 410d",
Zone:"office_410d_4",
Floor:"4",
Number:"410d",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"18892",
YCoordinate:"52010",
ZCoordinate:"7"
),
Room(
Name:"URBN 410e",
Zone:"office_410e_4",
Floor:"4",
Number:"410e",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"15751",
YCoordinate:"51995",
ZCoordinate:"7"
),
Room(
Name:"URBN 410f",
Zone:"office_410f_4",
Floor:"4",
Number:"410f",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"14295",
YCoordinate:"51393",
ZCoordinate:"7"
),
Room(
Name:"URBN 410g",
Zone:"office_410g_4",
Floor:"4",
Number:"410g",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"14302",
YCoordinate:"50440",
ZCoordinate:"7"
),
Room(
Name:"URBN 410h",
Zone:"office_410h_4",
Floor:"4",
Number:"410h",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"16650",
YCoordinate:"50836",
ZCoordinate:"7"
),
Room(
Name:"URBN 410j",
Zone:"office_410j_4",
Floor:"4",
Number:"410j",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"19845",
YCoordinate:"50836",
ZCoordinate:"7"
),
Room(
Name:"URBN 410k",
Zone:"office_410k_4",
Floor:"4",
Number:"410k",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"23207",
YCoordinate:"50836",
ZCoordinate:"7"
),
Room(
Name:"URBN 410l",
Zone:"office_410l_4",
Floor:"4",
Number:"410l",
Type:"Office",
Description:"The offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"25304",
YCoordinate:"50852",
ZCoordinate:"7"
),
Room(
Name:"URBN 420",
Zone:"lab_420_4",
Floor:"4",
Number:"420",
Type:"Lab",
Description:"An incredibly large lab that houses the work of most of the Architecture program in the URBN center.",
Features:"Computers, Cutting board, Building Stations",
XCoordinate:"6053",
YCoordinate:"26226",
ZCoordinate:"7"
),
Room(
Name:"URBN 421",
Zone:"classroom_421_4",
Floor:"4",
Number:"421",
Type:"Classroom",
Description:"An open area in the hallway that doubles as a meeting place and classroom.",
Features:"TV, Movable Walls",
XCoordinate:"13601",
YCoordinate:"41855",
ZCoordinate:"7"
),
Room(
Name:"URBN 423",
Zone:"classroom_423_4",
Floor:"4",
Number:"423",
Type:"Classroom",
Description:"An open area in the hallway that doubles as a meeting place and classroom.",
Features:"TV, Movable Walls",
XCoordinate:"13631",
YCoordinate:"38607",
ZCoordinate:"7"
),
Room(
Name:"URBN 425",
Zone:"classroom_425_4",
Floor:"4",
Number:"425",
Type:"Classroom",
Description:"An open area in the hallway that doubles as a meeting place and classroom.",
Features:"TV, Movable Walls",
XCoordinate:"13585",
YCoordinate:"31060",
ZCoordinate:"7"
),
Room(
Name:"URBN 426",
Zone:"lab_426_4",
Floor:"4",
Number:"426",
Type:"Lab",
Description:"A general studio for work",
Features:"Building station",
XCoordinate:"12289",
YCoordinate:"6541",
ZCoordinate:"7"
),
Room(
Name:"URBN 427a",
Zone:"classroom_427a_4",
Floor:"4",
Number:"427a",
Type:"Classroom",
Description:"An open area of the hall that doubles as a classroom",
Features:"Movable Walls, TVs", XCoordinate:"13753",
YCoordinate:"21621",
ZCoordinate:"7"
),
Room(
Name:"URBN 427b",
Zone:"classroom_427b_4",
Floor:"4",
Number:"427b",
Type:"Classroom",
Description:"An open area of the hall that doubles as a classroom",
Features:"Movable Walls, TVs", XCoordinate:"23283",
YCoordinate:"22463",
ZCoordinate:"7"
)
,
Room(
Name:"URBN 427c",
Zone:"classroom_427c_4",
Floor:"4",
Number:"427c",
Type:"Classroom",
Description:"An open area of the hall that doubles as a classroom",
Features:"Movable Walls, TVs", XCoordinate:"23253",
YCoordinate:"12335",
ZCoordinate:"7"
),
Room(
Name:"URBN 427d",
Zone:"classroom_427d_4",
Floor:"4",
Number:"427d",
Type:"Classroom",
Description:"An open area of the hall that doubles as a classroom",
Features:"Movable Walls, TVs", XCoordinate:"13723",
YCoordinate:"11969",
ZCoordinate:"7"
),
Room(
Name:"URBN 430",
Zone:"lab_430_4",
Floor:"4",
Number:"430",
Type:"Lab",
Description:"A general lab for building projects and cultivating future designs",
Features:"3D printer",
XCoordinate:"27644",
YCoordinate:"4742",
ZCoordinate:"7"
),
Room(
Name:"URBN 432",
Zone:"classroom_432_4",
Floor:"4",
Number:"432",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom and graphic design studio",
Features:"Computers, Cutting board",
XCoordinate:"41855",
YCoordinate:"6571",
ZCoordinate:"7"
),
Room(
Name:"URBN 434",
Zone:"classroom_434_4",
Floor:"4",
Number:"434",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom and graphic design studio",
Features:"Computers, Cutting board",
XCoordinate:"44356",
YCoordinate:"6510",
ZCoordinate:"7"
),
Room(
Name:"URBN 435",
Zone:"classroom_435_4",
Floor:"4",
Number:"435",
Type:"Classroom",
Description:"A general computer lab that functions as a classroom and graphic design studio",
Features:"Computers, Cutting board", XCoordinate:"43853",
YCoordinate:"17489",
ZCoordinate:"7"
),
Room(
Name:"URBN 436",
Zone:"classroom_436_4",
Floor:"4",
Number:"436",
Type:"Classroom",
Description:"Dubbed the EZ Freshman Graphic Design Lab, a general computer lab that functions as a classroom",
Features:"Computers",
XCoordinate:"45759",
YCoordinate:"14439",
ZCoordinate:"7"
),
Room(
Name:"URBN 437",
Zone:"lab_437_4",
Floor:"4",
Number:"437",
Type:"Lab",
Description:"A lab that doubles as a storage room for the programs on Floor 4",
Features:"Storage, Computers",
XCoordinate:"43868",
YCoordinate:"19990",
ZCoordinate:"7"
),
Room(
Name:"URBN 439",
Zone:"lab_439_4",
Floor:"4",
Number:"439",
Type:"Lab",
Description:"One of the libraries of Floor 4 that holds information about programs at the URBN Center",
Features:"Library",
XCoordinate:"38165",
YCoordinate:"27797",
ZCoordinate:"7"
),
Room(
Name:"URBN 440",
Zone:"classroom_440_4",
Floor:"4",
Number:"440",
Type:"Classroom",
Description:"A classroom that doubles as a conference room for faculty and students of Floor 4.",
Features:"Projector",
XCoordinate:"45987",
YCoordinate:"31746",
ZCoordinate:"7"
) ,
Room(
Name:"Floor 4 Men's Restroom",
Zone:"bathroomMens_471_4",
Floor:"4",
Number:"471",
Type:"Restroom",
Description:"A men's restroom",
Features:"Water Fountain, Restroom",
XCoordinate:"49144",
YCoordinate:"19441",
ZCoordinate:"7"
),
Room(
Name:"Floor 4 Unisex Restroom",
Zone:"bathroomUnisex_472_4",
Floor:"4",
Number:"472",
Type:"Restroom",
Description:"A unisex restroom with handicap-accessibility",
Features:"Water Fountain, Restroom",
XCoordinate:"47710",
YCoordinate:"20325",
ZCoordinate:"7"
),
Room(
Name:"Floor 4 Women's Restroom",
Zone:"bathroomWomens_473_4",
Floor:"4",
Number:"473",
Type:"Restroom",
Description:"A women's restroom with handicap-accessibility",
Features:"Water Fountain, Restroom",
XCoordinate:"49281",
YCoordinate:"26409",
ZCoordinate:"7"
),
Room(
Name:"URBN 4A10A",
Zone:"office_4a10a_4a",
Floor:"4A",
Number:"4A10A",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"21553",
YCoordinate:"30823",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10B",
Zone:"office_4a10b_4a",
Floor:"4A",
Number:"4A10B",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"21034",
YCoordinate:"33881",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10C",
Zone:"office_4a10c_4a",
Floor:"4A",
Number:"4A10C",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"21042",
YCoordinate:"38112",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10D",
Zone:"office_4a10d_4a",
Floor:"4A",
Number:"4A10D",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"20256",
YCoordinate:"43388",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10E",
Zone:"office_4a10e_4a",
Floor:"4A",
Number:"4A10E",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"21766",
YCoordinate:"43365",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10F",
Zone:"office_4a10f_4a",
Floor:"4A",
Number:"4A10F",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"24061",
YCoordinate:"43395",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10G",
Zone:"office_4a10g_4a",
Floor:"4A",
Number:"4A10G",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"22063",
YCoordinate:"41451",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10H",
Zone:"office_4a10h_4a",
Floor:"4A",
Number:"4A10H",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"22086",
YCoordinate:"38402",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10J",
Zone:"office_4a10j_4a",
Floor:"4A",
Number:"4A10J",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"22094",
YCoordinate:"33911",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A10L",
Zone:"office_4a10l_4a",
Floor:"4A",
Number:"4A10L",
Type:"Office",
Description:"One of the offices of the Media Arts faculty",
Features:"Faculty",
XCoordinate:"24686",
YCoordinate:"32005",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20A",
Zone:"office_4a20a_4a",
Floor:"4A",
Number:"4A20A",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"36259",
YCoordinate:"24564",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20B",
Zone:"office_4a20b_4a",
Floor:"4A",
Number:"4A20B",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"34643",
YCoordinate:"22178",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20C",
Zone:"office_4a20c_4a",
Floor:"4A",
Number:"4A20C",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"35207",
YCoordinate:"19281",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20D",
Zone:"office_4a20d_4a",
Floor:"4A",
Number:"4A20D",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"33492",
YCoordinate:"13906",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20E",
Zone:"office_4a20e_4a",
Floor:"4A",
Number:"4A20E",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"32180",
YCoordinate:"13913",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20F",
Zone:"office_4a20f_4a",
Floor:"4A",
Number:"4A20F",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"35405",
YCoordinate:"12556",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20G",
Zone:"office_4a20g_4a",
Floor:"4A",
Number:"4A20G",
Type:"Office",
Description:"One of the offices of the Architecture and Interiors faculty",
Features:"Faculty",
XCoordinate:"34193",
YCoordinate:"12541",
ZCoordinate:"8"
),
Room(
Name:"URBN 4A20H",
Zone:"office_4a20h_4a",
Floor:"4A",
Number:"4A20H",
Type:"Office",
Description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
Features:"Feature 1, Feature 2, Feature 3",
XCoordinate:"31746",
YCoordinate:"12549",
ZCoordinate:"8"
)
]
}
}
extension SearchVC: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
| true
|
02e49f4d4c7e45d6e6e9e4323bb226c21f83cd02
|
Swift
|
Bazt/testvk
|
/fbs_test/RequestResult.swift
|
UTF-8
| 278
| 2.921875
| 3
|
[] |
no_license
|
import Foundation
struct RequestResult<D, E>
{
let data: D?
let error: E?
init(withData data: D?)
{
self.data = data
self.error = nil
}
init(withError error: E?)
{
self.data = nil
self.error = error
}
}
| true
|
a9343e1269e0b48b2d16cb5abfc26304fe12fefa
|
Swift
|
HobsonCheng/uimaster_iOS
|
/UIMaster/Base/Tool(工具)/UI/YJDocument.swift
|
UTF-8
| 669
| 2.5625
| 3
|
[] |
no_license
|
//
// YJDocument.swift
// UIMaster
//
// Created by hobson on 2018/10/29.
// Copyright © 2018 one2much. All rights reserved.
//
import UIKit
class YJDocument: UIDocument {
var data: NSData?
var imgData: NSData?
//处理文件上传
override func contents(forType typeName: String) throws -> Any {
if typeName == "public.png" {
return imgData ?? NSData()
} else {
return Data()
}
}
//处理文件下载
override func load(fromContents contents: Any, ofType typeName: String?) throws {
if let userContent = contents as? NSData {
data = userContent
}
}
}
| true
|
9653a24b01fc5ce4befd47c4f841db84beac1b58
|
Swift
|
semv2009/App2
|
/App/Model/Person.swift
|
UTF-8
| 3,102
| 2.953125
| 3
|
[] |
no_license
|
//
// Person.swift
// App
//
// Created by developer on 08.05.16.
// Copyright © 2016 developer. All rights reserved.
//
import Foundation
import CoreData
import BNRCoreDataStack
class Person: NSManagedObject, CoreDataModelable {
@NSManaged var fullName: String?
@NSManaged var salary: NSNumber?
@NSManaged var order: NSNumber?
@NSManaged var sectionOrder: Int
// MARK: - CoreDataModelable
class var entityName: String {
return "Person"
}
var entitySort: Int {
get {
guard let sortStr = entity.valueForKey("userInfo")!.valueForKey("sort") as? String, sort = Int(sortStr) else { fatalError() }
return sort
}
set {
entity.userInfo?["sort"] = "\(newValue)"
}
}
static func createPerson(entity: String, stack: CoreDataStack, manager: AttributeManager) -> Person? {
var person: Person?
switch entity {
case Accountant.entityName:
person = Accountant(managedObjectContext: stack.mainQueueContext)
case Director.entityName:
person = Director(managedObjectContext: stack.mainQueueContext)
case FellowWorker.entityName:
person = FellowWorker(managedObjectContext: stack.mainQueueContext)
default:
break
}
if let person = person {
person.update(manager.dictionary())
}
return person
}
func update(values: [String : AnyObject?]) {
for (key, value) in values {
self.setValue(value, forKey: key)
}
}
static func attributes(entityName: String, stack: CoreDataStack, oldManger: AttributeManager? = nil) -> AttributeManager {
var manager: AttributeManager = AttributeManager()
switch entityName {
case Accountant.entityName:
manager = Accountant(managedObjectContext: stack.newChildContext()).attributes()
case Director.entityName:
manager = Director(managedObjectContext: stack.newChildContext()).attributes()
case FellowWorker.entityName:
manager = FellowWorker(managedObjectContext: stack.newChildContext()).attributes()
default:
break
}
if let oldManger = oldManger {
manager.update(oldManger)
}
return manager
}
func attributes() -> AttributeManager {
var attributes = [Attribute]()
attributes.append(StringAttribute(
name: "full name",
key: "fullName",
placeholder: "John Snow",
value: fullName)
)
attributes.append(NumberAttribute(
name: "salary",
key: "salary",
placeholder: "35000",
value: salary)
)
let manager = AttributeManager()
manager.sections.append(attributes)
return manager
}
}
enum CellType: String {
case String = "StringCell"
case Number = "NumberCell"
case RangeTime = "RangeTimeCell"
case AccountantType = "AccountantTypeCell"
}
| true
|
7b07a1be2c17f6e72a813bddf5a7d95a5f929c6c
|
Swift
|
TeamBuebu/PixelDraw
|
/PixelDraw/MainViewController.swift
|
UTF-8
| 3,924
| 2.59375
| 3
|
[] |
no_license
|
import UIKit
class MainViewController: UIViewController {
var pixelGrid: PixelGridView!
let gridColor = UIColor(rgba: "#efefefff")
let gridSize = 11
var selectedColor = UIColor.clearColor()
let colors = [UIColor(rgba: "#1364b7FF"), UIColor(rgba: "#13b717FF"), UIColor(rgba: "#ffea00FF"), UIColor(rgba: "#000000FF"), UIColor.clearColor()]
@IBOutlet weak var touchView: TouchTrackerView!
@IBOutlet weak var color1ControlView: ColorControlView!
@IBOutlet weak var color2ControlView: ColorControlView!
@IBOutlet weak var color3ControlView: ColorControlView!
@IBOutlet weak var color4ControlView: ColorControlView!
@IBOutlet weak var color5ControlView: ColorControlView!
override func viewDidLoad() {
super.viewDidLoad()
initColorControls()
pixelGrid = PixelGridView(gridSize: gridSize, gridColor: gridColor)
pixelGrid.translatesAutoresizingMaskIntoConstraints = false
self.view.insertSubview(pixelGrid, belowSubview: touchView)
let c1 = NSLayoutConstraint(item: pixelGrid, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: touchView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
let c2 = NSLayoutConstraint(item: pixelGrid, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: touchView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
let c3 = NSLayoutConstraint(item: pixelGrid, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: touchView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let c4 = NSLayoutConstraint(item: pixelGrid, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: touchView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.view.addConstraints([c1, c2, c3, c4])
touchView.onPathDrawn = { points in
self.pixelGrid.colorizeSquaresOnPath(points, color: self.selectedColor)
}
}
func initColorControls() {
let controls = [color1ControlView, color2ControlView, color3ControlView, color4ControlView, color5ControlView]
for (index,control) in controls.enumerate() {
control.backgroundColor = colors[index]
control.onSelect = {
for controlToBeDisabled in controls {
controlToBeDisabled.isControlSelected = false
}
control.isControlSelected = true
self.selectedColor = control.backgroundColor!
}
}
color1ControlView.isControlSelected = true
self.selectedColor = color1ControlView.backgroundColor!
}
@IBAction func clearGrid(sender: AnyObject) {
let alertController = UIAlertController(title: "Alle Pixel löschen?", message: "Möchtest du wirklich alle Pixel löschen. Dies kann nicht rückgangig gemacht werden.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in}
alertController.addAction(cancelAction)
let deleteAction = UIAlertAction(title: "Delete", style: .Default) { (action) in
self.pixelGrid.clearSquares()
}
alertController.addAction(deleteAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
@IBAction func logResult(sender: AnyObject) {
// TODO: log the result in the logbook in the required format
var json = [String : AnyObject]()
json["task"] = "Pixelmaler"
let solutionLogger = SolutionLogger(viewController: self)
json["pixels"] = pixelGrid.getSquaresAsJsonArray()
let solutionStr = solutionLogger.JSONStringify(json)
solutionLogger.logSolution(solutionStr)
}
}
| true
|
13a69331c856a24f20f1c2b8d5a8edcf4eed1107
|
Swift
|
LuizZak/swift-blend2d
|
/Sources/SwiftBlend2D/Color/BLRgba.swift
|
UTF-8
| 1,916
| 3.078125
| 3
|
[
"Zlib",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Libpng"
] |
permissive
|
import blend2d
public extension BLRgba {
/// Get whether the color is fully-opaque (alpha equals 1.0).
@inlinable
var isOpaque: Bool { return a >= 1.0 }
/// Get whether the color is fully-transparent (alpha equals 0.0).
@inlinable
var isTransparent: Bool { return a == 0.0 }
init(_ rgba32: BLRgba32) {
let r = Float(rgba32.r) * (1.0 / 255.0)
let g = Float(rgba32.g) * (1.0 / 255.0)
let b = Float(rgba32.b) * (1.0 / 255.0)
let a = Float(rgba32.a) * (1.0 / 255.0)
self.init(r: r, g: g, b: b, a: a)
}
init(_ rgba64: BLRgba64) {
let r = Float(rgba64.r) * (1.0 / 65535.0)
let g = Float(rgba64.g) * (1.0 / 65535.0)
let b = Float(rgba64.b) * (1.0 / 65535.0)
let a = Float(rgba64.a) * (1.0 / 65535.0)
self.init(r: r, g: g, b: b, a: a)
}
func withTransparency(_ alpha: Float) -> BLRgba {
return BLRgba(r: r, g: g, b: b, a: alpha)
}
func faded(
towards otherColor: BLRgba,
factor: Float,
blendAlpha: Bool = false
) -> BLRgba {
let from = 1 - factor
let a = blendAlpha ? self.a * from + otherColor.a * factor : self.a
let r = self.r * from + otherColor.r * factor
let g = self.g * from + otherColor.g * factor
let b = self.b * from + otherColor.b * factor
return BLRgba(r: r, g: g, b: b, a: a)
}
}
extension BLRgba {
@inlinable
public static func == (lhs: BLRgba, rhs: BLRgba32) -> Bool {
lhs == BLRgba(rhs)
}
@inlinable
public static func == (lhs: BLRgba32, rhs: BLRgba) -> Bool {
BLRgba(lhs) == rhs
}
@inlinable
public static func == (lhs: BLRgba, rhs: BLRgba64) -> Bool {
lhs == BLRgba(rhs)
}
@inlinable
public static func == (lhs: BLRgba64, rhs: BLRgba) -> Bool {
BLRgba(lhs) == rhs
}
}
| true
|
8eee6c5ea3869e770aa986f7bf4106f8f19d224c
|
Swift
|
DaRkViRuS2012/Emall
|
/E-MALL/UIViewController.swift
|
UTF-8
| 1,417
| 2.546875
| 3
|
[] |
no_license
|
//
// UIViewController.swift
// E-MALL
//
// Created by Nour on 4/4/17.
// Copyright © 2017 Nour . All rights reserved.
//
import UIKit
extension UIViewController{
func endEdit() {
view.endEditing(true)
print("sadasd")
}
func hideKeyboard(){
self.view.endEditing(true)
}
func addKeyboardobserver(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShown), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardHidden(){
view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
}
func keyboardShown(notification:NSNotification){
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
print(keyboardHeight)
view.frame = CGRect(x: 0, y: -100, width: view.frame.width, height: view.frame.height)
}
}
| true
|
453bae780bdd836b2244d6f64c23e40c52364925
|
Swift
|
skyekraft/udacity-begios-alien-adventure
|
/Alien Adventure/OldestItemFromPlanet.swift
|
UTF-8
| 980
| 2.640625
| 3
|
[] |
no_license
|
//
// OldestItemFromPlanet.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/3/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func oldestItemFromPlanet(inventory: [UDItem], planet: String) -> UDItem? {
let planets = itemsFromPlanet(inventory, planet: planet)
if planets.count == 0 {
return nil
} else {
var eldestItem: UDItem?
var oldestAge = 0
for t in planets {
if let oldie = t.historicalData["CarbonAge"] as? Int {
if oldie > oldestAge {
oldestAge = oldie
eldestItem = t
}
}
}
return eldestItem
}
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 2"
| true
|
25fe0d6762def68fa4316cddb9123a3c85b1c8d1
|
Swift
|
anodamobi/RxFirestoreExecutor
|
/FirebaseQueryExecutor/Classes/Error/QueryExecutorError.swift
|
UTF-8
| 2,421
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
/*
The MIT License (MIT)
Copyright (c) 2018 ANODA Mobile Development Agency. http://anoda.mobi <info@anoda.mobi>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public enum ErrorStrings: String {
case insufficientArguments = "Insufficien Arguments in call methods. ExecutorError: 0"
case emptyOrNilParametr = "Nil or Empty parametr disallowed. ExecutorError: 1"
case emptyDataSet = "Data set is empty. ExecutorError: 2"
case emptyKeyValue = "Sent parametr or Object ID is empty. ExecutorError: 3"
case emptySnapshotData = "Snapshot data is empty! ExecutorError: 5"
}
public enum ExecutorError: Error {
case insufficientArguments(ErrorStrings)
case emptyOrNilParametr(ErrorStrings)
case emptyDataSet(ErrorStrings)
case emptyKeyValue(ErrorStrings)
case emptySnapshotData(ErrorStrings)
case undefined
}
extension ExecutorError: LocalizedError {
public var localizedDescription: String {
switch self {
case .emptyDataSet(let empty): return empty.rawValue
case .emptyKeyValue(let keyValue): return keyValue.rawValue
case .emptyOrNilParametr(let nilParam): return nilParam.rawValue
case .insufficientArguments(let insufParams): return insufParams.rawValue
case .emptySnapshotData(let emptyData): return emptyData.rawValue
default:
return "Undefined error!"
}
}
}
| true
|
1a74ee5c94dec250a32934a229ddd557547c3e7c
|
Swift
|
OskrNav/pokeApp
|
/pokeApp/model/pokedex.swift
|
UTF-8
| 841
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
//
// pokedex.swift
// pokeApp
//
// Created by Oscar Navidad on 11/24/19.
// Copyright © 2019 Oscar Navidad. All rights reserved.
//
import Foundation
struct PokeDetail {
var id : Int = 0
var name : String = ""
var pokemon_entries:[PokeEntry] = []
init(_ data:JSON){
self.id = data["id"].int ?? 0
self.name = data["name"].string ?? ""
if let items = data["pokemon_entries"].array{
self.pokemon_entries = []
for item in items{
self.pokemon_entries.append(PokeEntry(item))
}
}
}
}
struct PokeEntry {
var id:Int = 0
var name:String = ""
init(_ data:JSON){
self.id = data["entry_number"].int ?? 0
let pokemon_species = data["pokemon_species"]
self.name = pokemon_species["name"].string ?? ""
}
}
| true
|
1d6faec239e441c74b00a4390a2106cfa32d72ef
|
Swift
|
MacMeDan/StarterProject
|
/starterProject/UIView.swift
|
UTF-8
| 2,093
| 3.015625
| 3
|
[] |
no_license
|
//
// UIView.swift
// starterProject
//
// Created by Dan Leonard on 10/26/17.
// Copyright © 2017 Macmedan. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
/// - Tag: View
var x: CGFloat {
set {
frame = CGRect(x: newValue, y: frame.origin.y, width: frame.size.width, height: frame.size.height)
} get {
return frame.origin.x
}
}
var y: CGFloat {
set {
frame = CGRect(x: frame.origin.x, y: newValue, width: frame.size.width, height: frame.size.height)
} get {
return frame.origin.y
}
}
var w: CGFloat {
set {
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: newValue, height: frame.size.height)
} get {
return frame.size.width
}
}
var h: CGFloat {
set {
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: newValue)
} get {
return frame.size.height
}
}
var width: CGFloat {
set {
w = newValue
} get {
return w
}
}
var height: CGFloat {
set {
h = newValue
} get {
return h
}
}
var f: CGPoint {
return CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.height / 2.0)
}
var size: CGSize {
set {
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: newValue.width, height: newValue.height)
} get {
return frame.size
}
}
var right: CGFloat {
get {
return x + width
} set {
x = newValue - width
}
}
var bottom: CGFloat {
get {
return y + height
} set {
y = newValue - height
}
}
var centerY: CGFloat {
get {
return center.y
} set {
center = CGPoint(x: center.x, y: newValue)
}
}
}
| true
|
c76c0d93e5e8b1d0febeb9526ce448fe579dbdfd
|
Swift
|
tainavm/ios-weather
|
/Weather/Weather/Supporting Files/Extensions.swift
|
UTF-8
| 3,516
| 3.125
| 3
|
[] |
no_license
|
//
// Extensions.swift
// Weather
//
// Created by Taina Viriato on 16/04/21.
//
import UIKit
extension UIView {
func addShadow(offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float) {
layer.masksToBounds = false
layer.shadowOffset = offset
layer.shadowColor = color.cgColor
layer.shadowRadius = radius
layer.shadowOpacity = opacity
let backgroundCGColor = backgroundColor?.cgColor
backgroundColor = nil
layer.backgroundColor = backgroundCGColor
layer.masksToBounds = false
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
func addShadow(tableView: UITableView, offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float) {
tableView.layer.masksToBounds = false
tableView.layer.shadowOffset = offset
tableView.layer.shadowColor = color.cgColor
tableView.layer.shadowRadius = radius
tableView.layer.shadowOpacity = opacity
let backgroundCGColor = backgroundColor?.cgColor
backgroundColor = nil
tableView.layer.backgroundColor = backgroundCGColor
tableView.layer.masksToBounds = false
tableView.layer.shouldRasterize = true
tableView.layer.rasterizationScale = UIScreen.main.scale
}
func addCornerRadius(radius: CGFloat) {
layer.cornerRadius = radius
layer.masksToBounds = true
}
func addBorder(borderWidth: CGFloat, borderColor: CGColor) {
layer.borderWidth = borderWidth
layer.borderColor = borderColor
}
}
extension Date {
func toDateString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d"
let str = dateFormatter.string(from: self)
return str
}
func toHourString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let str = dateFormatter.string(from: self)
return str
}
}
extension String {
func getDateFromTimestamp() -> String {
if let date = self.toDate() {
return date.toDateString()
}
return " - "
}
func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: self)
return date
}
func getHourFromTimestamp() -> String {
if let date = self.toDate() {
return date.toHourString()
}
return " - "
}
func toHourDate(withFormat format: String = "HH:mm:ss")-> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: self)
return date
}
func capitalize() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}
mutating func capitalize() {
self = self.capitalize()
}
}
extension Double {
func convertTimestamp() -> String {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0200")
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "h:mm a"
let strDate = dateFormatter.string(from: date)
return strDate
}
}
extension UIImageView {
func loadIcon(icon: String) {
let iconUrl = "http://openweathermap.org/img/wn/\(icon)@2x.png"
let url = URL(string: iconUrl)
if let data = try? Data(contentsOf: url!) {
self.image = UIImage(data: data)
} else {
self.image = UIImage(named: "warning.png")
}
}
}
| true
|
be4649686f04530bfc4e284cdd55317f6144b9f9
|
Swift
|
David-DaSilva7/RecipeApp
|
/RecipeApp/View/Extensions/UIView+shadow.swift
|
UTF-8
| 778
| 2.578125
| 3
|
[] |
no_license
|
//
// UIView+shadow.swift
// RecipeApp
//
// Created by Merouane Bellaha on 20/09/2020.
// Copyright © 2020 Merouane Bellaha. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable
var shadowColor: UIColor {
get { UIColor(cgColor: layer.shadowColor ?? UIColor.gray.cgColor) }
set { layer.shadowColor = newValue.cgColor }
}
@IBInspectable
var shadowOpacity: Float {
get { layer.shadowOpacity }
set { layer.shadowOpacity = newValue }
}
@IBInspectable
var shadowRadius: CGFloat {
get { layer.shadowRadius }
set { layer.shadowRadius = newValue }
}
@IBInspectable
var shadowOffset: CGSize {
get { layer.shadowOffset }
set { layer.shadowOffset = newValue }
}
}
| true
|
2b792b0328d606ac6da7dffe557ea77c78875ec8
|
Swift
|
jfranklin1607/BuildHairApp
|
/HairCare/HairStylist.swift
|
UTF-8
| 469
| 2.828125
| 3
|
[] |
no_license
|
//
// HairStylist.swift
// HairCare
//
// Created by Taylor Lyles on 8/26/19.
// Copyright © 2019 Taylor Lyles. All rights reserved.
//
import UIKit
import Foundation
class HairStylist {
var name: String
var yearsOfExperience: Int
var image: UIImage
init(name: String, yearsOfExperience: Int, imageName: String) {
self.name = name
self.yearsOfExperience = yearsOfExperience
self.image = UIImage(named: imageName)!
}
}
| true
|
be4d9d52be9b593aa4435e24bc151ca7bb2d13d2
|
Swift
|
atkalikov/laoshu-core
|
/Sources/LaoshuCore/Models/Dictionary/Tags/Tag.swift
|
UTF-8
| 3,818
| 3.25
| 3
|
[] |
no_license
|
import Foundation
public class Tag {
public let index: String.Index
public let state: State
public let kind: Kind
public init(index: String.Index, state: Tag.State, kind: Tag.Kind) {
self.index = index
self.state = state
self.kind = kind
}
}
extension Tag {
public enum State {
case opened
case closed
}
public enum Kind: Equatable {
// Formating
case b, i, u, c(ColorPreset?), bg(ColorPreset?), sup, sub, accent
case m(Int?)
// Structure
case p, t, secondary
// Searching
case ex, com, trn, trn1, trs, lang
// Other
case ref
public var asString: String {
switch self {
case .b:
return "b"
case .i:
return "i"
case .u:
return "u"
case .c:
return "c"
case .bg:
return "bg"
case .sup:
return "sup"
case .sub:
return "sub"
case .accent:
return "'"
case .m(let int):
if let int = int {
return "m\(int)"
} else {
return "m"
}
case .p:
return "p"
case .t:
return "t"
case .secondary:
return "*"
case .ex:
return "ex"
case .com:
return "com"
case .trn:
return "trn"
case .trn1:
return "trn1"
case .trs:
return "!trs"
case .lang:
return "lang"
case .ref:
return "ref"
}
}
// Formating
public static var formatingTags: [Kind] = [.b, .i, .u, .c(nil), .bg(nil), .sup, .sub, .accent, .m(nil)]
public static var mDigitTags: [Kind] = [.m(0), .m(1), .m(2), .m(3), .m(4), .m(5), .m(6), .m(7), .m(8), .m(9)]
// Structure
public static var structureTags: [Kind] = [.p, .t, .secondary]
// Searching
public static var searchingTags: [Kind] = [.ex, .com, .trn, .trn1, .trs, .lang]
// Other
public static var otherTags: [Kind] = [.ref]
public static var allCases: [Kind] = {
var tags: [Kind] = []
tags.append(contentsOf: formatingTags)
tags.append(contentsOf: mDigitTags)
tags.append(contentsOf: structureTags)
tags.append(contentsOf: searchingTags)
tags.append(contentsOf: otherTags)
return tags
}()
public static func from(string: String) -> Kind? {
if string.hasPrefix("\(Kind.c(nil).asString) "), let color = string.split(whereSeparator: \.isWhitespace).last {
return .c(ColorPreset(rawValue: String(color)))
}
if string.hasPrefix("\(Kind.bg(nil).asString) "), let color = string.split(whereSeparator: \.isWhitespace).last {
return .bg(ColorPreset(rawValue: String(color)))
}
return allCases.first { $0.asString == string }
}
public static func == (lhs: Self, rhs: Self) -> Bool {
let mDigitTagsAsString = mDigitTags.map { $0.asString }
if mDigitTagsAsString.contains(lhs.asString), rhs.asString == Kind.m(nil).asString { return true }
if mDigitTagsAsString.contains(rhs.asString), lhs.asString == Kind.m(nil).asString { return true }
return lhs.asString == rhs.asString
}
}
}
| true
|
26868f0232941200097c1fa55978cdf191c598c3
|
Swift
|
jiangleligejiang/JSwift
|
/RxSwiftCode/RxSwiftCode/Core/Base/Bag+Rx.swift
|
UTF-8
| 905
| 2.6875
| 3
|
[] |
no_license
|
//
// Bag+Rx.swift
// RxSwiftCode
//
// Created by jams on 2019/10/11.
// Copyright © 2019 jams. All rights reserved.
//
func dispatch<Element>(_ bag: Bag<(Event<Element>) -> Void>, _ event: Event<Element>) {
bag._value0?(event)
if bag._onlyFastPath {
return
}
let pairs = bag._pairs
for i in 0 ..< pairs.count {
pairs[i].value(event)
}
if let dictionary = bag._dictionary {
for element in dictionary.values {
element(event)
}
}
}
func disposeAll(in bag: Bag<Disposable>) {
bag._value0?.dispose()
if bag._onlyFastPath {
return
}
let pairs = bag._pairs
for i in 0 ..< pairs.count {
pairs[i].value.dispose()
}
if let dictionary = bag._dictionary {
for element in dictionary.values {
element.dispose()
}
}
}
| true
|
92177262d04fb7d118e6d2ee495f883e9164b850
|
Swift
|
MaloJaboulet/Bewerbungstracker
|
/BewerbungsApp/BewerbungZeile.swift
|
UTF-8
| 789
| 2.671875
| 3
|
[] |
no_license
|
//
// BewerbungZeile.swift
// BewerbungsApp
//
// Created by Malo Jaboulet on 20.03.21.
//
import SwiftUI
struct BewerbungZeile: View {
@ObservedObject var bewerbung: Bewerbungen
var body: some View {
NavigationLink(destination: EineBewerbungView(eineBewerbung: bewerbung)){
HStack(){
Text(bewerbung.firmenName ?? "Unknown")
.font(.title)
.padding()
Spacer()
}.background(bewerbung.absage != 0 ? (bewerbung.absage != 1 ? (bewerbung.absage == 2 ? Color.yellow : Color.red) : Color.green) : Color.purple)
}
}
}
/*struct BewerbungZeile_Previews: PreviewProvider {
static var previews: some View {
BewerbungZeile(bewerbung: testDaten[1])
}
}
*/
| true
|
8d81146be5be4097bf9590e2d8a6f4a9b5c9eff6
|
Swift
|
bqlin/swift-learning-playground
|
/Boxue Swift Note/Boxue Swift Note.playground/Pages/错误处理.xcplaygroundpage/Contents.swift
|
UTF-8
| 4,848
| 3.90625
| 4
|
[] |
no_license
|
import Foundation
//: # 错误处理
/*:
Swift并没有异常处理这一说,类似的语法都归结为错误(error),语义更加具体明确了。
Error是一个协议,没有具体的约定,只是一个类型的身份,只要遵循了它,就可以使用Swift的错误处理规则(throw、do...catch,说白了只是语法糖而已,本质上跟return、switch...case没有区别)。
*/
enum CarError: Error {
case outOfFuel
}
struct Car {
var fuel: Double
/// - Throws: `CarError` if the car is out of fuel
func start() throws -> String {
guard fuel > 5 else {
// How we press the error here?
// return .failure(CarError.outOfFuel)
throw CarError.outOfFuel
}
// return .success("Ready to go")
return "Ready to go"
}
}
let vw = Car(fuel: 2)
do {
let message = try vw.start()
print(message)
} catch CarError.outOfFuel {
print("Cannot start due to out of fuel")
} catch {
print("We have something wrong")
}
/*:
## NSError to Swift Error
OC的NSError若是以这种形式声明方法签名的:
```
+ (BOOL)checkTemperature: (NSError **)error
```
在桥接到Swift时,会转换成这样的签名:
```
func checkTemperature() throws {
// ...
}
```
这里要特别说明的是,只有返回`BOOL`或`nullable`对象,并通过`NSError **`参数表达错误的OC函数,桥接到Swift时,才会转换成Swift原生的throws函数。并且,由于throws已经足以表达失败了,因此,Swift也不再需要OC版本的BOOL返回值,它会被去掉,改成Void。
在捕获时通过NSError类型和`error.code`进行筛选与匹配,例如:
```
do {
try vw.selfCheck()
} catch let error as NSError
where error.code == CarSensorError.overHeat.rawValue {
// CarSensorErrorDomain
print(error.domain)
// The radiator is over heat
print(error.userInfo["NSLocalizedDescription"] ?? "")
}
```
## Swift Error to NSError
- 类似的,方法签名会自动转换,在OC里,它会被添加一个AndReturnError后缀,并接受一个`NSError **`类型的参数,并且会自动生成error domain和error code。
- 通过遵循并实现LocalizedError,可以为NSError提供以下信息:
- errorDescription
- failureReason
- recoverySuggestion
- helpAnchor
- 另外通过实现CustomNSError,可以自定义NSError中的以下信息:
- errorCode
- errorUserInfo
*/
//: ## 处理作为函数参数的闭包的错误
//: 同步的闭包错误,通过在函数中使用rethrows关键字表达。
// 只有当rule抛出错误时,checkAll才会抛出错误
extension Sequence {
func checkAll(by rule:
(Iterator.Element) throws -> Bool) rethrows -> Bool {
for element in self {
guard try rule(element) else { return false }
}
return true
}
}
//: 对于异步闭包的错误,则更为建议使用Result<T>的形式,包含两类不同的值,一个是错误一个是具体的值,类似于Optional。这样的类型也称为either type。但对于直接使用这种形式回调结果,可能会导致多重switch...case的嵌套,可以给Result添加一个flatMap扩展,使嵌套转变为链式闭包。
enum Result<T> {
case success(T)
case failure(Error)
}
extension Result {
func flatMap<U>(transform: (T) -> Result<U>) -> Result<U> {
switch self {
case let .success(v):
return transform(v)
case let .failure(e):
return .failure(e)
}
}
}
/**
func osUpdate(postUpdate: @escaping (Result<Int>) -> Void) {
DispatchQueue.global().async {
// 1. Download package
switch self.downLoadPackage() {
case let .success(filePath):
// 2. Check integration
switch self.checkIntegration(of: filePath) {
case let .success(checksum):
// 3. Do you want to continue from here?
// ...
case let .failure(e):
postUpdate(.failure(e))
}
case let .failure(e):
postUpdate(.failure(e))
}
}
}
⬇️
func osUpdate(postUpdate: @escaping (Result<Int>) -> Void) {
DispatchQueue.global().async {
let result = self.downLoadPackage()
.flatMap {
self.checkIntegration(of: $0)
}
// Chain other processes here
postUpdate(result)
}
}
*/
//: 与try...catch...finally类似的finally的概念,对应到一般情况,有个对应的语法——defer,在defer闭包内的内容将在离开所在作用域的时候执行。
//: [上一页](@previous) | [下一页](@next)
| true
|
bbc4f733553e237627fd6ae0412f21fb3daeb310
|
Swift
|
abdhilabs/MuviCat-iOS
|
/Core/Core/Domain/UseCase/DetailInteractor.swift
|
UTF-8
| 1,016
| 2.921875
| 3
|
[] |
no_license
|
//
// DetailInteractor.swift
// MuviCat
//
// Created by Abdhi on 20/06/21.
//
import Foundation
import RxSwift
public protocol DetailUseCase {
func getMovieById(_ idMovie: Int) -> Observable<MovieModel>
func getCastsByIdMovie(_ idMovie: Int) -> Observable<[CastModel]>
func updateFavoriteMovieById(_ idMovie: Int, _ isFav: Bool) -> Observable<Bool>
}
public class DetailInteractor: DetailUseCase {
private let repository: MovieRepositoryProtocol
required init(repository: MovieRepositoryProtocol) {
self.repository = repository
}
public func getMovieById(_ idMovie: Int) -> Observable<MovieModel> {
return repository.getMovieById(idMovie)
}
public func getCastsByIdMovie(_ idMovie: Int) -> Observable<[CastModel]> {
return repository.getCastByIdMovie(idMovie)
}
public func updateFavoriteMovieById(_ idMovie: Int, _ isFav: Bool) -> Observable<Bool> {
return repository.updateFavoriteMovie(idMovie, isFav)
}
}
| true
|
132517d5cdcbed4508cc8eec994deb03e18c4779
|
Swift
|
4ecHo4ek/FirstGame
|
/WarFly/PlayerPlane.swift
|
UTF-8
| 1,191
| 3.0625
| 3
|
[] |
no_license
|
//
// PlayerPlane.swift
// WarFly
//
// Created by Сергей Цыганков on 11.06.2020.
// Copyright © 2020 Сергей Цыганков. All rights reserved.
//
import SpriteKit
class PlayerPlane: SKSpriteNode {
static func populate(at point: CGPoint) -> SKSpriteNode {
//текстура удобней тем, что текстура меняется, а изображение нет
let playerPlaneTexture = SKTexture(imageNamed: "airplane_3ver2_13")
//далее перетаскиваем наши фото с самолетиком (папку написать через .atlas)
//синяя папка представляет атлас текстур, они будут рабоать как анимация
//название берется из текстуры
//добавляем нашу текстру
let playerPlane = SKSpriteNode(texture: playerPlaneTexture)
//делаем рисунок в 2 раза меньше
playerPlane.setScale(0.5)
//размещаем самолет
playerPlane.position = point
playerPlane.zPosition = 20
return playerPlane
}
}
| true
|
357d784e59686d9b44220120b70f74b9e9e07983
|
Swift
|
xswm1123/FreryCountDownButtonPackage
|
/Sources/FreryCountDownButtonPackage/FreryCountDownButton/FreryAutoCountDownBtn.swift
|
UTF-8
| 2,689
| 2.5625
| 3
|
[] |
no_license
|
//
// FreryAutoCountDownBtn.swift
// MOSCTools
//
// Created by Frery on 2019/12/16.
// Copyright © 2019 Tima. All rights reserved.
//
import UIKit
import Foundation
class FreryAutoCountDownBtn: FreryCountDownBtn{
///是否终止倒计时,默认为否(每次点击倒计时按钮仅终止这一次的操作,如希望点击倒计时按钮均不执行自动倒计时,请使用FreryCountDownBtn)
public var terminateCountDown :Bool = false
var countDownMark :String?
var countDownSec :Int?
var enAbleAutoCountDown:Bool?
var textFormat : textFormBlock?
override func initOperation() {
super.initOperation()
}
///启用自动倒计时按钮,实现类似点击获取验证码效果,countDownSec为倒计时时间,mark为FreryCountDownBtn用于区分不同倒计时操作的标识,并回调结果
public func enableAutoCountDown(countDown:Int,mark:String,resTextFormat:@escaping textFormBlock){
self.countDownMark = mark
self.countDownSec = countDown
self.enAbleAutoCountDown = true
self.textFormat = resTextFormat
let core = CountDownButtonCore()
let disTime = core.getDisTimeWith(mark: mark)
if(disTime > 0 && !self.disableScheduleStore){
startCountDown()
}
}
///重置倒计时按钮
public func resume(){
stopCountDown()
self.isEnabled = true
self.setTitle(self.value(forKey: "orgText") as? String, for: .normal)
self.setTitleColor(self.value(forKey: "orgTextColor") as? UIColor, for: .normal)
self.backgroundColor = self.value(forKey: "orgBacColor") as? UIColor
}
override func startCountDown() {
if self.isEnabled{
self.setCountDown(countDown: self.countDownSec!, mark: self.countDownMark!) {[weak self] (remainSec) -> String in
if remainSec > 0{
self?.isEnabled = false
}else{
self?.isEnabled = true
}
if((self) != nil){
return self!.textFormat!(remainSec)
}else{
return "";
}
}
super.startCountDown()
}
}
deinit {
invalidateTimer()
}
override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
super.sendAction(action, to: target, for: event)
if(!self.terminateCountDown){
startCountDown()
}
self.terminateCountDown = false
}
}
| true
|
9abfc9e45774ca81e06059530e92e4617dd48d6b
|
Swift
|
MahmoudMohamedIsmail/MovieApp
|
/MovieApp/Data/Remote/AppServiceClient.swift
|
UTF-8
| 2,607
| 2.890625
| 3
|
[] |
no_license
|
//
// APIManager.swift
//
//
//
import Foundation
import Alamofire
import RxSwift
struct ResponseModel<T: Decodable>: Decodable {
let response: T?
var message: String?
enum CodingKeys: String, CodingKey {
case response = "results"
case message = "message"
}
}
protocol AppServiceClientProtocol {
func performRequest<T>(_ object: T.Type, serviceGateway: Gateway)-> Observable<ResponseModel<T>> where T:Decodable
func cancelPreviousNetworkCall()
}
class AppServiceClient: AppServiceClientProtocol {
func performRequest<T>(_ object: T.Type, serviceGateway: Gateway) -> Observable<ResponseModel<T>> where T : Decodable {
return Observable.create { (observer) -> Disposable in
AF.request(serviceGateway)
.validate()
.responseJSON{ (response) in
switch response.result{
case .success:
do {
let responseModel = try JSONDecoder().decode(ResponseModel<T>.self, from: response.data!)
observer.onNext(responseModel)
} catch let error{
observer.onError(error)
}
case let .failure(error):
if let statusCode = response.response?.statusCode{
switch ServiceError.init(rawValue: statusCode){
case .badRequest:
do {
let failerResponseModel = try JSONDecoder().decode(ResponseModel<T>.self, from: response.data!)
observer.onError(AppError(message: failerResponseModel.message ?? ""))
return
} catch let error{
observer.onError(error)
return
}
default:
if let reason = ServiceError(rawValue: statusCode){
observer.onError(reason)
return
}
}
}
observer.onError(error)
}
}.resume()
return Disposables.create()
}
}
func cancelPreviousNetworkCall(){
AF.session.getAllTasks(completionHandler: {$0.forEach{$0.cancel()}})
}
}
| true
|
1a89f730ba3b454d6762c66e2fc742a0af094880
|
Swift
|
yhangeline/SwiftProgramming
|
/Precious/Precious/Common/Utils/Countdown.swift
|
UTF-8
| 2,085
| 3.0625
| 3
|
[] |
no_license
|
//
// Countdown.swift
// Precious
//
// Created by zhubch on 2017/12/12.
// Copyright © 2017年 zhubch. All rights reserved.
//
import UIKit
import RxSwift
class TimerCenter {
static let shared = TimerCenter()
var timer: Timer!
var observers = [Task]()
init() {
start()
}
func start() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(count), userInfo: nil, repeats: true)
}
@objc func count() {
observers.forEach { $0.trigger() }
}
}
class Task: NSObject {
var time: Int
let ob: AnyObserver<Int>
init(time: Int, ob: AnyObserver<Int>) {
self.time = time + 1
self.ob = ob
super.init()
self.trigger()
}
func trigger() {
time -= 1
ob.onNext(time)
if time == 0 {
ob.onCompleted()
}
}
}
func time(from: Int) -> Observable<Int> {
return Observable<Int>.create { (ob) -> Disposable in
let task = Task(time: from, ob: ob)
TimerCenter.shared.observers.append(task)
return Disposables.create {
}
}
}
let UILabelPropertyKey: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "UILabelPropertyKey".hashValue)
typealias TimeFormatBlock = (Int)->String
extension UILabel {
var disposeBag: DisposeBag {
if let bag = objc_getAssociatedObject(self, DisposeBagPropertyKey) as? DisposeBag {
return bag
}
let bag = DisposeBag()
objc_setAssociatedObject(self, DisposeBagPropertyKey, bag, .OBJC_ASSOCIATION_RETAIN)
return bag
}
var timeFormatBlock: TimeFormatBlock? {
get {
return objc_getAssociatedObject(self, UILabelPropertyKey) as? TimeFormatBlock
}
set {
objc_setAssociatedObject(self, UILabelPropertyKey, newValue, .OBJC_ASSOCIATION_COPY)
}
}
func countdown(from: Int) {
time(from:from).map { "\($0)" }.bind(to: rx.text).disposed(by: disposeBag)
}
}
| true
|
4fcbc77747bf610cff8cbe7a89531188850b9a53
|
Swift
|
nanami510/OriginalApp
|
/CreateViewController.swift
|
UTF-8
| 9,160
| 2.5625
| 3
|
[] |
no_license
|
//
// CreateViewController.swift
// RealmApp
//
// Created by 後藤奈々美 on 2017/05/04.
// Copyright © 2017年 litech. All rights reserved.
//
import UIKit
import RealmSwift
class Todo: Object {
dynamic var id: Int = 1
dynamic var title = ""
dynamic var date = NSDate()
dynamic var starttime = ""
dynamic var endtime = ""
dynamic var memo = ""
dynamic var createdAt = NSDate()
dynamic var deleate: Int = 0
dynamic var edit: Int = 0
dynamic var edit_id: Int = 0
}
class TimeTable: Object {
dynamic var id: Int = 0
dynamic var title = ""
dynamic var dayOfTheWeek = ""
dynamic var period: Int = 0
dynamic var createdAt = NSDate()
dynamic var deleate: Int = 0
}
class Note:Object{
dynamic var id: Int = 0
dynamic var timetable_id: Int = 0
dynamic var date = NSDate()
dynamic var memo = ""
dynamic var attendance: Int = 0
dynamic var createdAt = NSDate()
dynamic var deleate: Int = 0
dynamic var edit: Int = 0
dynamic var edit_id: Int = 0
}
class CreateViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var start: UITextField!
@IBOutlet weak var end: UITextField!
@IBOutlet weak var textView:UITextView!
let nowDate = NSDate()
let dateFormat = DateFormatter()
let inputDatePicker = UIDatePicker()
let inputStartDatePicker = UIDatePicker()
let inputEndDatePicker = UIDatePicker()
let timeFormat = DateFormatter()
let inputStartTimePicker = UIDatePicker()
let inputEndTimePicker = UIDatePicker()
@IBOutlet weak var dateSelecter: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
start.delegate = self
end.delegate = self
textField.delegate = self
textField.returnKeyType = .done
NotificationCenter.default.addObserver(
self,
selector: #selector(textFieldDidChange),
name: NSNotification.Name.UITextFieldTextDidChange,
object: textField)
textView.dataDetectorTypes = UIDataDetectorTypes.all
textView.isEditable = true
//日付フィールドの設定
dateFormat.dateFormat = "yyyy年MM月dd日"
dateSelecter.text = dateFormat.string(from: dateOfSelectedDay)
self.dateSelecter.delegate = self
// DatePickerの設定(日付用)
inputDatePicker.datePickerMode = UIDatePickerMode.date
dateSelecter.inputView = inputDatePicker
// キーボードに表示するツールバーの表示
let pickerToolBar = UIToolbar(frame: CGRect(x:0, y:self.view.frame.size.height/6,width: self.view.frame.size.width,height: 40.0))
pickerToolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)
pickerToolBar.barStyle = .blackTranslucent
pickerToolBar.tintColor = UIColor.white
pickerToolBar.backgroundColor = UIColor.black
//ボタンの設定
//右寄せのためのスペース設定
let spaceBarBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace,target: self,action: nil)
//完了ボタンを設定
let toolBarBtn = UIBarButtonItem(title: "完了", style: .done, target: self, action:#selector(toolBarBtnPush(sender:)))
//ツールバーにボタンを表示
pickerToolBar.items = [spaceBarBtn,toolBarBtn]
dateSelecter.inputAccessoryView = pickerToolBar
//日付フィールドの設定
timeFormat.dateFormat = "kk:mm"
start.text = timeFormat.string(from: nowDate as Date)
self.start.delegate = self
// DatePickerの設定(日付用)
inputStartTimePicker.datePickerMode = UIDatePickerMode.time
start.inputView = inputStartTimePicker
//完了ボタンを設定
let toolStartBarBtn = UIBarButtonItem(title: "完了", style: .done, target: self, action:#selector(toolStartBarBtnPush(sender:)))
// キーボードに表示するツールバーの表示
let pickerStartToolBar = UIToolbar(frame: CGRect(x:0, y:self.view.frame.size.height/6,width: self.view.frame.size.width,height: 40.0))
pickerStartToolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)
pickerStartToolBar.barStyle = .blackTranslucent
pickerStartToolBar.tintColor = UIColor.white
pickerStartToolBar.backgroundColor = UIColor.black
//ツールバーにボタンを表示
pickerStartToolBar.items = [spaceBarBtn,toolStartBarBtn]
start.inputAccessoryView = pickerStartToolBar
//日付フィールドの設定
end.text = timeFormat.string(from: nowDate as Date)
self.end.delegate = self
// DatePickerの設定(日付用)
inputEndTimePicker.datePickerMode = UIDatePickerMode.time
end.inputView = inputEndTimePicker
//完了ボタンを設定
let toolEndBarBtn = UIBarButtonItem(title: "完了", style: .done, target: self, action:#selector(toolEndBarBtnPush(sender:)))
// キーボードに表示するツールバーの表示
let pickerEndToolBar = UIToolbar(frame: CGRect(x:0, y:self.view.frame.size.height/6,width: self.view.frame.size.width,height: 40.0))
pickerEndToolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)
pickerEndToolBar.barStyle = .blackTranslucent
pickerEndToolBar.tintColor = UIColor.white
pickerEndToolBar.backgroundColor = UIColor.black
//ツールバーにボタンを表示
pickerEndToolBar.items = [spaceBarBtn,toolEndBarBtn]
end.inputAccessoryView = pickerEndToolBar
}
func toolBarBtnPush(sender: UIBarButtonItem){
let pickerDate = inputDatePicker.date
dateSelecter.text = dateFormat.string(from: pickerDate)
self.view.endEditing(true)
}
func toolStartBarBtnPush(sender: UIBarButtonItem){
let pickerStartTime = inputStartTimePicker.date
start.text = timeFormat.string(from: pickerStartTime)
self.view.endEditing(true)
}
func toolEndBarBtnPush(sender: UIBarButtonItem){
let pickerEndTime = inputEndTimePicker.date
end.text = timeFormat.string(from: pickerEndTime)
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@objc private func textFieldDidChange(notification: NSNotification) {
let textFieldString = notification.object as! UITextField
if let text = textFieldString.text {
if text.characters.count > 8 {
textField.text = text.substring(to: text.index(text.startIndex, offsetBy: 3))
}
}
}
@IBAction func createButton(_sender: Any) {
let realm = try! Realm()
if let title = textField.text, let date = dateFormat.date(from: dateSelecter.text!) , let starttime=start.text,let endtime=end.text,let memo = textView.text{
let todo = Todo()
todo.title = title
todo.date = date as NSDate
todo.starttime = starttime
todo.endtime = endtime
todo.id=(realm.objects(Todo.self).max(ofProperty: "id") as Int? ?? 0) + 1
todo.memo = memo
try! realm.write {
realm.add(todo)
}
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func createButton() {
let realm = try! Realm()
if let title = textField.text, let date = dateFormat.date(from: dateSelecter.text!) , let starttime=start.text,let endtime=end.text,let memo = textView.text{
let todo = Todo()
todo.title = title
todo.date = date as NSDate
todo.starttime = starttime
todo.endtime = endtime
todo.id=(realm.objects(Todo.self).max(ofProperty: "id") as Int? ?? 0) + 1
todo.memo = memo
try! realm.write {
realm.add(todo)
}
let alert = UIAlertController(title:"Complete!", message: "予定: "+title+" を追加しました。", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action: UIAlertAction!) in
})
alert.addAction(action)
textField.text=nil
textView.text=nil
self.present(alert, animated: true, completion: nil)
}
}
}
| true
|
83ba0dad5e9916d03ea8f7acd622af3b45d3cb62
|
Swift
|
iPolyomino/SwiftUI-Chapter4
|
/SwiftUI-Chapter4/NoteView.swift
|
UTF-8
| 2,658
| 3.359375
| 3
|
[] |
no_license
|
//
// Note.swift
// SwiftUI-Chapter4
//
// Created by 萩倉丈 on 2021/06/19.
//
import SwiftUI
// P. 272
extension UIApplication {
func endEditing() {
// キーボードを下げるための処理
sendAction(
#selector(UIResponder.resignFirstResponder),
to: nil, from: nil, for: nil
)
}
}
// P. 274
func saveText(_ textData: String, _ fileName: String) {
guard let url = docURL(fileName) else {
return
}
do {
let path = url.path
try textData.write(toFile: path, atomically:true, encoding: .utf8)
} catch let error as NSError {
print(error)
}
}
// P. 277
func loadText(_ fileName: String) -> String? {
guard let url = docURL(fileName) else {
return nil
}
do {
let textData = try String(contentsOf: url, encoding: .utf8)
return textData
} catch {
return nil
}
}
// P. 275
func docURL(_ fileName: String) -> URL? {
let fileManager = FileManager.default
do {
let docsUrl = try fileManager.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let url = docsUrl.appendingPathComponent(fileName)
return url
} catch {
return nil
}
}
struct NoteView: View {
@State private var theText: String = ""
var body: some View {
NavigationView {
TextEditor(text: $theText)
.lineSpacing(10)
.border(Color.gray)
.padding([.leading, .bottom, .trailing])
.navigationTitle("メモ")
.toolbar {
// P. 276
ToolbarItem(placement:.navigationBarTrailing) {
Button {
if let data = loadText("sample.txt") {
theText = data
}
} label: {
Text("読み込み")
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button {
// キーボードを下げる処理
UIApplication.shared.endEditing()
saveText(theText, "sample.txt")
} label : {
Text("保存")
}
}
}
}
}
}
struct NoteView_Previews: PreviewProvider {
static var previews: some View {
NoteView()
}
}
| true
|
da4ba124ad75cce9b2d1f902eb7056ce11bfe807
|
Swift
|
9ae/ki-ios
|
/iOSKinkedIn/MyKinks/EditKinkForm.swift
|
UTF-8
| 1,626
| 3.203125
| 3
|
[] |
no_license
|
//
// EditKinkForm.swift
// iOSKinkedIn
//
// Created by Alice on 3/28/20.
// Copyright © 2020 KinkedIn. All rights reserved.
//
import SwiftUI
struct EditKinkForm: View {
@State var kinks : [Kink]
let formSentence: String
@Binding var searchLabels : String
let kink2tagFn : (Kink) -> Tag
let markFn : (Kink, Bool) -> Void
var body: some View {
VStack(alignment: .leading) {
Text(formSentence).padding(.horizontal)
TextField("what you're into?", text: $searchLabels).padding(.horizontal)
InteractiveTagsView(tags: kinks.map(self.kink2tagFn))
{ (label, selected) in
if let kink = self.kinks.first(where: { k in
k.label == label
}) { print("checked \(kink.label)"); self.markFn(kink, selected) }
}
}
}
}
struct EditKinkForm_Previews: PreviewProvider {
static var previews: some View {
EditKinkForm(kinks: mockKinksService,
formSentence: "I want to receive",
searchLabels: .constant(""),
kink2tagFn: {k in Tag(label: k.label, isActive: k.way == .get)},
markFn: {(kink, active) in
if active {
if kink.way == .give {
kink.way = .both
} else {
kink.way == .get
}
}
else {
if kink.way == .both {
kink.way = .get
} else {
kink.way = .none
}
}
}
)
}
}
| true
|
d3a74a797e68f79925ada6e91adb937fc8daa3f8
|
Swift
|
Sobhan-Eskandari/iOS_JsonParser
|
/SwiftJson/JsonParse.swift
|
UTF-8
| 1,457
| 3.15625
| 3
|
[] |
no_license
|
//
// JsonParse.swift
// SwiftJson
//
// Created by Sobhan Eskandari on 11/17/16.
// Copyright © 2016 Sobhan Eskandari. All rights reserved.
//
import Foundation
import SwiftyJSON
import Alamofire
enum ParserStatus{
case Succeeded
case Failed
}
class JsonParse {
// Url To Parse
var url:String
static var status:ParserStatus = ParserStatus.Failed
static var jsonValuesDict:[String:[String]] = [:]
init(url:String) {
self.url = url
JsonParse.jsonValuesDict = [:]
}
func parse(JsonArrayNode arrayNode:String){
Alamofire.request(url).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
let item = json[arrayNode].arrayValue
let keys = item[0]
for key in keys{
var arrayOfValues = [String]()
for item in json[arrayNode].arrayValue {
arrayOfValues.append(item[key.0].stringValue)
}
JsonParse.jsonValuesDict[key.0] = arrayOfValues
}
JsonParse.status = ParserStatus.Succeeded
case .failure(let error):
print(error)
JsonParse.status = ParserStatus.Failed
}
}
}
}
| true
|
038aec44f20d1e36c286f93791e0fcac33001ae4
|
Swift
|
sebbu/SwagGen
|
/Specs/TFL/generated/Swift/Sources/TFL/Models/Crowding.swift
|
UTF-8
| 1,425
| 3.015625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
import JSONUtilities
public class Crowding: JSONDecodable, JSONEncodable, PrettyPrintable {
/** Busiest times at a station (static information) */
public var passengerFlows: [PassengerFlow]?
/** Train Loading on a scale 1-6, 1 being "Very quiet" and 6 being "Exceptionally busy" (static information) */
public var trainLoadings: [TrainLoading]?
public init(passengerFlows: [PassengerFlow]? = nil, trainLoadings: [TrainLoading]? = nil) {
self.passengerFlows = passengerFlows
self.trainLoadings = trainLoadings
}
public required init(jsonDictionary: JSONDictionary) throws {
passengerFlows = jsonDictionary.json(atKeyPath: "passengerFlows")
trainLoadings = jsonDictionary.json(atKeyPath: "trainLoadings")
}
public func encode() -> JSONDictionary {
var dictionary: JSONDictionary = [:]
if let passengerFlows = passengerFlows?.encode() {
dictionary["passengerFlows"] = passengerFlows
}
if let trainLoadings = trainLoadings?.encode() {
dictionary["trainLoadings"] = trainLoadings
}
return dictionary
}
/// pretty prints all properties including nested models
public var prettyPrinted: String {
return "\(type(of: self)):\n\(encode().recursivePrint(indentIndex: 1))"
}
}
| true
|
efa5479e77acb51ee48f4f8c5a49a9635396f24d
|
Swift
|
vivekdharmani7/TwignatureAppIos
|
/Twignature/Protocols/Identifierable.swift
|
UTF-8
| 342
| 2.765625
| 3
|
[] |
no_license
|
//
// Identifierable.swift
// Twignature
//
// Created by Anton Muratov on 9/5/17.
// Copyright © 2017 Applikey. All rights reserved.
//
import Foundation
protocol Identifierable {
static var identifier: String { get }
}
extension Identifierable {
static var identifier: String {
return String(describing: Self.self)
}
}
| true
|
0bc765c0826e4424c5c1f9b6e8853309e5b4cfe2
|
Swift
|
VuNTruong/Cuckoo-Swift-iOS
|
/MyHBT-API/Views/Post Detail Views/PostDetailPostPhotoCell.swift
|
UTF-8
| 868
| 2.53125
| 3
|
[] |
no_license
|
//
// PostDetailPostPhotoCell.swift
// MyHBT-API
//
// Created by Vũ Trương on 10/5/20.
// Copyright © 2020 beta. All rights reserved.
//
import UIKit
import SDWebImage
class PostDetailPostPhotoCell: UITableViewCell {
// Photo of the post
@IBOutlet weak var postPhoto: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// The function to load image into image view based on the specified URL
func loadImage(URLString: String) {
// Load image into the image view
postPhoto.sd_setImage(with: URL(string: URLString), placeholderImage: UIImage(named: "placeholder.png"))
}
}
| true
|
b9359b7e91086f4f8505d357f9dfd4faca3858b9
|
Swift
|
miska12345/OpenMarket-swift
|
/OpenMarketPlace-swift/Model/Organization/Organization.swift
|
UTF-8
| 383
| 2.609375
| 3
|
[] |
no_license
|
//
// Organization.swift
// OpenMarketPlace-swift
//
// Created by Weifeng Li on 9/21/20.
//
import Foundation
struct Organization: Identifiable {
let id: String = UUID().uuidString
var organizationName: String
var organizationPicture: String
var organizationDescription: String
var organizationStoreItems: [Item]?
var organizationStoreCurrency: [String]?
}
| true
|
69fa9bea3cb6954dd1d3ecfae2363291066d2166
|
Swift
|
kimdaeman14/IosClassExample
|
/Class0607/Class0607(4)/Class0607(4)/ViewController.swift
|
UTF-8
| 2,301
| 2.921875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Class0607(4)
//
// Created by kimdaeman14 on 2018. 6. 7..
// Copyright © 2018년 kimdaeman14. All rights reserved.
//
import UIKit
class Singleton {
static let shared = Singleton()
private init() {}
let id = "fastcampus"
let password = "123456"
}
let singleton = Singleton.shared
class ViewController: UIViewController {
let loginButton = UIButton(frame: CGRect(x: 35, y: 480, width: 255, height: 35))
let idTextField = UITextField(frame: CGRect(x: 30, y: 200, width: 210, height: 40))
let passwordTextField = UITextField(frame: CGRect(x: 30, y: 300, width: 210, height: 40))
override func viewDidLoad() {
super.viewDidLoad()
//loginbutton
loginButton.setTitle("Login", for: .normal)
loginButton.setTitleColor(.white, for: .normal)
loginButton.backgroundColor = .black
loginButton.layer.cornerRadius = 5
loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
view.addSubview(loginButton)
loginButton.addTarget(self, action: #selector(showSecondViewController(_:)), for: .touchUpInside)
//idTextField
view.addSubview(idTextField)
idTextField.backgroundColor = .gray
idTextField.text = "아이디를 입력하세요."
idTextField.textColor = .white
//passwordTextField
view.addSubview(passwordTextField)
passwordTextField.backgroundColor = .gray
passwordTextField.text = "비밀번호를 입력하세요."
passwordTextField.textColor = .white
}
@objc func showSecondViewController(_ :UIButton){
print("aaa")
if (singleton.id == idTextField.text && singleton.password == passwordTextField.text){
var second = SecondViewController()
second.a = idTextField.text ?? ""
present(second, animated: true)
}else {
print("bbbb")
let alertController = UIAlertController(title: "아이디 또는 비밀번호가 맞지 않습니다.", message: "다시 시도해 주세요.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "확인", style: .default)
alertController.addAction(okAction)
present(alertController, animated: true)
}
}
}
| true
|
b4b9fc43a86ff595d6236219c8a70b0c309e17e5
|
Swift
|
Mundaco/RecipePuppy
|
/RecipePuppy/PresentationModel/RecipeList.swift
|
UTF-8
| 379
| 2.65625
| 3
|
[] |
no_license
|
//
// RecipeList.swift
// RecipePuppy
//
// Created by mnu on 08/12/2018.
// Copyright © 2018 mundaco.com. All rights reserved.
//
extension Array where Element: Recipe {
static func map(recipes: [RecipePuppy]) -> [Recipe] {
var list: [Recipe] = []
for recipe in recipes {
list.append(Recipe(with: recipe))
}
return list
}
}
| true
|
febf605977b7ae804131d76f14802e79768bfe16
|
Swift
|
Lonewolf-72/Looping
|
/Sources/Looping/Models/LoopImageError.swift
|
UTF-8
| 262
| 2.90625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
import Foundation
/// Errors thrown when loading a loop image.
public enum LoopImageError: Error {
/// Codec cannot be found.
case noMatchingCodec
/// Asset cannot be found.
case missingAsset
/// Asset is invalid.
case invalidAsset
}
| true
|
0a4eefa89eef49ba7efc6b1f586b85b0f55bed8d
|
Swift
|
johndpope-karhoo/SnapKitExamples
|
/SnapKitExamples/Extensions/UIColor+Random.swift
|
UTF-8
| 416
| 2.671875
| 3
|
[] |
no_license
|
//
// UIColor+Random.swift
// SnapExamples
//
// Created by Ivana Rast on 02/08/15.
// Copyright (c) 2015 Ivana Rast. All rights reserved.
//
import UIKit
public extension UIColor {
class func randomColor() -> UIColor {
let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
| true
|
c043a1651e4f0decd02c1548e14be463356326e2
|
Swift
|
alo9507/SwiftAlgoPerformanceSuite
|
/SortAlgoBenchmarksTests/Questions/FastSlowPointers/FindCycleInLinkedListTests.swift
|
UTF-8
| 1,792
| 3.078125
| 3
|
[] |
no_license
|
//
// FinCycleInLinkedListTests.swift
// SortAlgoBenchmarksTests
//
// Created by Andrew O'Brien on 3/6/20.
// Copyright © 2020 Andrew O'Brien. All rights reserved.
//
import Foundation
import XCTest
@testable import SortAlgoBenchmarks
class FindCycleInLinkedListTests: XCTestCase {
func test_FindCycleInLinkedList() {
let head_withCycle = LinkedListNode<Int>(0)
let beginCycle = LinkedListNode<Int>(1)
head_withCycle.next = beginCycle
head_withCycle.next?.next = LinkedListNode<Int>(2)
head_withCycle.next?.next?.next = LinkedListNode<Int>(3)
let cycleNode = LinkedListNode<Int>(4)
cycleNode.next = beginCycle
head_withCycle.next?.next?.next?.next = cycleNode
XCTAssertTrue(hasCycle(head_withCycle))
let head_noCycle = LinkedListNode<Int>(0)
head_noCycle.next = LinkedListNode<Int>(1)
head_noCycle.next?.next = LinkedListNode<Int>(2)
XCTAssertFalse(hasCycle(head_noCycle))
}
func test_lengthOfCycle() {
let head_withCycle = LinkedListNode<Int>(0)
let beginCycle = LinkedListNode<Int>(1)
head_withCycle.next = beginCycle
head_withCycle.next?.next = LinkedListNode<Int>(2)
head_withCycle.next?.next?.next = LinkedListNode<Int>(3)
let cycleNode = LinkedListNode<Int>(4)
cycleNode.next = beginCycle
head_withCycle.next?.next?.next?.next = cycleNode
// XCTAssertEqual(4, cycleLength(head_withCycle))
}
func test_inplaceReversalOfLinkedList() {
let head = LinkedListNode<Int>(0)
head.next = LinkedListNode<Int>(1)
head.next?.next = LinkedListNode<Int>(2)
XCTAssertEqual(2, inplaceReversalOfLinkedList(head).value)
}
}
| true
|
0822fbf5f143bbc2fe84ab8da35966e409d6fb9c
|
Swift
|
newblash/oobase
|
/oobase/loginViewController.swift
|
UTF-8
| 13,180
| 2.578125
| 3
|
[] |
no_license
|
//
// loginViewController.swift
// oobase纯代码版
//
// Created by 杨晶 on 16/3/23.
// Copyright © 2016年 YJ. All rights reserved.
//
import UIKit
import SafariServices
//登录框状态枚举
enum LoginShowType {
case NONE
case USER
case PASS
}
class loginViewController: UIViewController, UITextFieldDelegate {
var 登录: UIButton = UIButton(type: UIButtonType.Custom)
var 注册: UIButton = UIButton(type: UIButtonType.Custom)
var 关于我们: UIButton = UIButton(type: UIButtonType.Custom)
var link = "http://www.oobase.com"
//用户密码输入框
var txtUser:UITextField!
var txtPwd:UITextField!
//左手离脑袋的距离
var offsetLeftHand:CGFloat = 60
//左手图片,右手图片(遮眼睛的)
var imgLeftHand:UIImageView!
var imgRightHand:UIImageView!
//左手图片,右手图片(圆形的)
var imgLeftHandGone:UIImageView!
var imgRightHandGone:UIImageView!
//登录框状态
var showType:LoginShowType = LoginShowType.NONE
override func viewDidLoad() {
super.viewDidLoad()
//获取屏幕尺寸
let mainSize = UIScreen.mainScreen().bounds.size
//猫头鹰头部
let imgLogin = UIImageView(frame:CGRectMake(mainSize.width/2-211/2, 40, 211, 109))
imgLogin.image = UIImage(named:"owl-login")
imgLogin.layer.masksToBounds = true
self.view.addSubview(imgLogin)
//猫头鹰左手(遮眼睛的)
let rectLeftHand = CGRectMake(61 - offsetLeftHand, 90, 40, 65)
imgLeftHand = UIImageView(frame:rectLeftHand)
imgLeftHand.image = UIImage(named:"owl-login-arm-left")
imgLogin.addSubview(imgLeftHand)
//猫头鹰右手(遮眼睛的)
let rectRightHand = CGRectMake(imgLogin.frame.size.width / 2 + 60, 90, 40, 65)
imgRightHand = UIImageView(frame:rectRightHand)
imgRightHand.image = UIImage(named:"owl-login-arm-right")
imgLogin.addSubview(imgRightHand)
//登录框背景
let vLogin = UIView(frame:CGRectMake(20, 140, mainSize.width - 40, 120))
vLogin.layer.borderWidth = 0.5
vLogin.layer.cornerRadius = 10
// vLogin.alpha = 0.7//背景透明度
vLogin.layer.borderColor = UIColor.lightGrayColor().CGColor
vLogin.backgroundColor = UIColor.whiteColor()
self.view.addSubview(vLogin)
//猫头鹰左手(圆形的)
let rectLeftHandGone = CGRectMake(mainSize.width / 2 - 100,
vLogin.frame.origin.y - 22, 40, 40)
imgLeftHandGone = UIImageView(frame:rectLeftHandGone)
imgLeftHandGone.image = UIImage(named:"icon_hand")
self.view.addSubview(imgLeftHandGone)
//猫头鹰右手(圆形的)
let rectRightHandGone = CGRectMake(mainSize.width / 2 + 62,
vLogin.frame.origin.y - 22, 40, 40)
imgRightHandGone = UIImageView(frame:rectRightHandGone)
imgRightHandGone.image = UIImage(named:"icon_hand")
self.view.addSubview(imgRightHandGone)
//用户名输入框
txtUser = UITextField(frame:CGRectMake(15, 15, vLogin.frame.size.width - 30, 40))
txtUser.delegate = self
txtUser.layer.cornerRadius = 5
txtUser.layer.borderColor = UIColor.lightGrayColor().CGColor
txtUser.layer.borderWidth = 0.5
txtUser.leftView = UIView(frame:CGRectMake(0, 0, 44, 44))
txtUser.leftViewMode = UITextFieldViewMode.Always
txtUser.clearButtonMode = .Always
txtUser.autocapitalizationType = .None//首字母类型,默认关闭
txtUser.placeholder = "请输入用户名!"
//用户名输入框左侧图标
let imgUser = UIImageView(frame:CGRectMake(11, 11, 22, 22))
imgUser.image = UIImage(named:"iconfont-user")
txtUser.leftView!.addSubview(imgUser)
vLogin.addSubview(txtUser)
//密码输入框
txtPwd = UITextField(frame:CGRectMake(15, txtUser.frame.maxY + 10, vLogin.frame.size.width - 30, 40))
txtPwd.delegate = self
txtPwd.layer.cornerRadius = 5
txtPwd.layer.borderColor = UIColor.lightGrayColor().CGColor
txtPwd.layer.borderWidth = 0.5
txtPwd.secureTextEntry = true
txtPwd.leftView = UIView(frame:CGRectMake(0, 0, 44, 44))
txtPwd.leftViewMode = UITextFieldViewMode.Always
txtPwd.clearButtonMode = .Always
txtPwd.placeholder = "请输入密码!"
//密码输入框左侧图标
let imgPwd = UIImageView(frame:CGRectMake(11, 11, 22, 22))
imgPwd.image = UIImage(named:"iconfont-password")
txtPwd.leftView!.addSubview(imgPwd)
vLogin.addSubview(txtPwd)
登录 = UIButton(frame: CGRectMake(20, vLogin.frame.maxY + 10, mainSize.width - 40, 30))
登录.setTitleColor(UIColor.redColor(), forState: .Highlighted)//点击之后变红色
登录.setTitle("登录", forState: UIControlState.Normal)
登录.layer.cornerRadius = 5//设置圆角
登录.alpha = 0.7
登录.backgroundColor = UIColor(red: 40/255, green: 100/255, blue: 200/255, alpha: 1)//背景颜色
登录.addTarget(self, action: #selector(loginViewController.login), forControlEvents: .TouchUpInside)//按钮事件
self.view.addSubview(登录)
注册 = UIButton(frame: CGRectMake(登录.frame.minX, 登录.frame.maxY + 10, mainSize.width - 40, 30))
注册.setTitleColor(UIColor.redColor(), forState: .Highlighted)//点击之后变红色
注册.setTitle("注册", forState: UIControlState.Normal)
注册.layer.cornerRadius = 5//设置圆角
注册.alpha = 0.7
注册.backgroundColor = UIColor(red: 100/255, green: 150/255, blue: 200/255, alpha: 1)//背景颜色
注册.addTarget(self, action: #selector(loginViewController.register), forControlEvents: .TouchUpInside)//按钮事件
self.view.addSubview(注册)
关于我们 = UIButton(frame: CGRectMake(20,注册.frame.maxY + 10, mainSize.width - 40, 30))
关于我们.setTitleColor(UIColor.redColor(), forState: .Highlighted)//点击之后变红色
关于我们.setTitle("关于oobase", forState: UIControlState.Normal)
关于我们.layer.cornerRadius = 5//设置圆角
关于我们.alpha = 0.7
关于我们.backgroundColor = UIColor(red: 200/255, green: 150/255, blue: 100/255, alpha: 1)//背景颜色
关于我们.addTarget(self, action: #selector(loginViewController.about), forControlEvents: .TouchUpInside)//按钮事件
self.view.addSubview(关于我们)
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bk")!)
// Do any additional setup after loading the view.
}
func textFieldShouldReturn(textField: UITextField) -> Bool{//设置键盘点击之后隐藏
textField.resignFirstResponder()
return true
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {//隐藏键盘的另一种方法
txtUser.resignFirstResponder()
txtPwd.resignFirstResponder()
}
//输入框获取焦点开始编辑
func textFieldDidBeginEditing(textField:UITextField)
{
//如果当前是用户名输入
if textField.isEqual(txtUser){
if (showType != LoginShowType.PASS)
{
showType = LoginShowType.USER
return
}
showType = LoginShowType.USER
//播放不遮眼动画
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.imgLeftHand.frame = CGRectMake(
self.imgLeftHand.frame.origin.x - self.offsetLeftHand,
self.imgLeftHand.frame.origin.y + 30,
self.imgLeftHand.frame.size.width, self.imgLeftHand.frame.size.height)
self.imgRightHand.frame = CGRectMake(
self.imgRightHand.frame.origin.x + 48,
self.imgRightHand.frame.origin.y + 30,
self.imgRightHand.frame.size.width, self.imgRightHand.frame.size.height)
self.imgLeftHandGone.frame = CGRectMake(
self.imgLeftHandGone.frame.origin.x - 70,
self.imgLeftHandGone.frame.origin.y, 40, 40)
self.imgRightHandGone.frame = CGRectMake(
self.imgRightHandGone.frame.origin.x + 30,
self.imgRightHandGone.frame.origin.y, 40, 40)
})
}
//如果当前是密码名输入
else if textField.isEqual(txtPwd){
if (showType == LoginShowType.PASS)
{
showType = LoginShowType.PASS
return
}
showType = LoginShowType.PASS
//播放遮眼动画
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.imgLeftHand.frame = CGRectMake(
self.imgLeftHand.frame.origin.x + self.offsetLeftHand,
self.imgLeftHand.frame.origin.y - 30,
self.imgLeftHand.frame.size.width, self.imgLeftHand.frame.size.height)
self.imgRightHand.frame = CGRectMake(
self.imgRightHand.frame.origin.x - 48,
self.imgRightHand.frame.origin.y - 30,
self.imgRightHand.frame.size.width, self.imgRightHand.frame.size.height)
self.imgLeftHandGone.frame = CGRectMake(
self.imgLeftHandGone.frame.origin.x + 70,
self.imgLeftHandGone.frame.origin.y, 0, 0)
self.imgRightHandGone.frame = CGRectMake(
self.imgRightHandGone.frame.origin.x - 30,
self.imgRightHandGone.frame.origin.y, 0, 0)
})
}
}
func login() {
if txtPwd.text == "" && txtUser.text == "" {
let alert = UIAlertController(title: "⚠️", message: "账号密码不能为空", preferredStyle: .Alert)
// let cancle = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
let ok = UIAlertAction(title: "确定", style: .Default, handler: nil)
// alert.addAction(cancle)
alert.addAction(ok)
self.presentViewController(alert, animated: true, completion: nil)
}else if txtUser.text != "admin" && txtPwd.text != "adimn"{
let alert = UIAlertController(title: "⚠️", message: "账号或密码错误", preferredStyle: .Alert)
// let cancle = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
let ok = UIAlertAction(title: "确定", style: .Default, handler: nil)
// alert.addAction(cancle)
alert.addAction(ok)
self.presentViewController(alert, animated: true, completion: nil)
}else {
presentViewController(TBViewController(), animated: true, completion: nil)//转场
}
presentViewController(TBViewController(), animated: true, completion: nil)//转场
}
func about(){//关于界面的跳转
if 关于我们.touchInside {
// if let url = NSURL(fileURLWithPath: link) {
// UIApplication.sharedApplication().openURL(url)
// }
if let url1 = NSURL(string: link){
UIApplication.sharedApplication().openURL(url1)
}
// let sfVC = SFSafariViewController(URL: NSURL(string: link)!, entersReaderIfAvailable: true)
// presentViewController(sfVC, animated: true, completion: nil)
}
}
func register(){//注册的跳转
if 注册.touchInside {
presentViewController(registerViewController(), animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
97f2807fac19831011194b3f66a928323bceabbd
|
Swift
|
likecatfood/News
|
/News/Views/SearchView.swift
|
UTF-8
| 2,495
| 2.90625
| 3
|
[] |
no_license
|
//
// SearchView.swift
// test
//
// Created by Antony Starkov on 03.03.2020.
// Copyright © 2020 Antony Starkov. All rights reserved.
//
import SwiftUI
struct SearchView: View {
@ObservedObject private var model = SearchViewModel()
var body: some View {
VStack {
List {
searchBar.listRowInsets(EdgeInsets())
ArticleListView(articles: model.articles)
}
.navigationBarTitle(Text("Search"))
.resignKeyboardOnDragGesture()
}
}
var searchBar: some View {
HStack {
HStack {
Image(systemName: "magnifyingglass")
TextField("search", text: $model.searchText, onEditingChanged: { isEditing in
self.model.showCancelButton = true
}, onCommit: {
self.model.load()
UIApplication.shared.endEditing(true)
self.model.showCancelButton = false
}).foregroundColor(.primary).keyboardType(.webSearch)
Button(action: {
self.model.searchText = ""
}) {
Image(systemName: "xmark.circle.fill").opacity(model.searchText == "" ? 0.0 : 1.0)
}
}
.padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
.foregroundColor(.secondary)
.background(Color(.secondarySystemBackground))
.cornerRadius(10.0)
if model.showCancelButton {
Button("Cancel") {
UIApplication.shared.endEditing(true)
self.model.searchText = ""
self.model.showCancelButton = false
}
.foregroundColor(Color(.systemBlue))
}
}
.padding(.horizontal)
.navigationBarHidden(model.showCancelButton).animation(.default) // animation does not work properly
}
}
struct SearchView_Previews: PreviewProvider {
static var previews: some View {
SearchView()
}
}
private struct ResignKeyboardOnDragGesture: ViewModifier {
var gesture = DragGesture().onChanged { _ in
UIApplication.shared.endEditing(true)
}
func body(content: Content) -> some View {
content.gesture(gesture)
}
}
private extension View {
func resignKeyboardOnDragGesture() -> some View {
return modifier(ResignKeyboardOnDragGesture())
}
}
| true
|
16037b4607d15a6a2b549fcbbf4b620b13e943ad
|
Swift
|
vivekptnk/PracticeAppForCaching
|
/PracticeAppForCaching/ViewModels/ImageLoadingViewModel.swift
|
UTF-8
| 1,825
| 3.28125
| 3
|
[] |
no_license
|
//
// ImageLoadingViewModel.swift
// PracticeAppForCaching
//
// Created by Vivek Pattanaik on 6/18/21.
//
import Foundation
import SwiftUI
import Combine
class ImageLoadingViewModel : ObservableObject {
@Published var image : UIImage? = nil
@Published var isLoading : Bool = false
let urlString : String
let imageKey : String
// let manager = PhotoModelFIleManager.instance // for file manager
let manager = PhotoModelCacheManager.instance // for cache
var cancellables = Set<AnyCancellable>()
init (url : String, key : String) {
imageKey = key
urlString = url
downloadImage()
getImage()
}
func getImage(){
if let savedImage = manager.get(key: imageKey) {
image = savedImage
print("Getting saved image!")
} else {
downloadImage()
print("Downloading Image Now")
}
}
func downloadImage() {
isLoading = true
guard let url = URL(string: urlString) else {
isLoading = false
return}
URLSession.shared.dataTaskPublisher(for: url)
.map{ UIImage(data: $0.data)} // Practicing shorter code methods, down below is original method.
// .map { (data, response) -> UIImage? in
// return UIImage(data: data)
// }
.receive(on: DispatchQueue.main)
.sink { [weak self] (_) in
self?.isLoading = false
} receiveValue: { [weak self] (returnedImage) in
guard let self = self,
let image = returnedImage else {return}
self.image = image
self.manager.add(key: self.imageKey, value: image)
}
.store(in: &cancellables)
}
}
| true
|
171a98ab45b5baabac5c62f158b961c60533fdf2
|
Swift
|
Damien-B/CellarTracker
|
/CellarTracker/WineBottleTableViewCell.swift
|
UTF-8
| 1,184
| 2.5625
| 3
|
[] |
no_license
|
//
// WineBottleTableViewCell.swift
// CellarTracker
//
// Created by Damien Bannerot on 29/09/2016.
// Copyright © 2016 Damien Bannerot. All rights reserved.
//
import UIKit
class WineBottleTableViewCell: UITableViewCell {
@IBOutlet weak var wineBottleImageView: UIImageView!
@IBOutlet weak var wineBottleDomainLabel: UILabel!
@IBOutlet weak var wineBottleNameLabel: UILabel!
@IBOutlet weak var wineBottleCountLabel: UILabel!
@IBOutlet weak var wineBottleTypeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func initCell(with bottle: Bottle) {
// if let imageData = bottle.image {
// self.wineBottleImageView.image = UIImage(data: (imageData as Data))
// } else {}
// if let domain = bottle.bottleDomaine {
// self.wineBottleDomainLabel.text = domain.name
// } else {}
// if let name = bottle.name {
// self.wineBottleNameLabel.text = name
// } else {}
// self.wineBottleDomainLabel.text = String(bottle.count)
}
}
| true
|
87ac671bcf33cf51ce58583105b877edf3643c06
|
Swift
|
LeoDeMatos/Rick-And-Morty
|
/RickAndMorty/Scenes/CharacterList/RickAndMortyWorker.swift
|
UTF-8
| 2,960
| 2.859375
| 3
|
[] |
no_license
|
//
// RickAndMortyWorker.swift
// CombineSample
//
// Created by Leonardo de Matos on 29/06/19.
// Copyright © 2019 Leonardo de Matos. All rights reserved.
//
import Foundation
import Combine
struct Some: Codable {
let string: String
}
struct HTTPError: Error {}
struct StatusCodeError: Error {}
class RickAndMortyWorker {
var characters: [RickAndMortyCharacter] = []
lazy var jsonDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
func fetchAllCharacters() {
let endpoint = RickAndMortyAPI.allCharacters
let url = URL(string: endpoint.url)!
var request = URLRequest(url: url)
request.httpMethod = endpoint.method.rawValue
let session = URLSession.shared.dataTaskPublisher(for: request)
_ = session
.tryMap(responseMapper)
.decode(type: RickAndMortyResponseWrapper<[RickAndMortyCharacter]>.self, decoder: jsonDecoder)
.mapError(errorMapper)
.map { result in result.results }
.sink { [weak self] characters in
self?.characters = characters
}
}
func fetchSingleCharacter(_ character: RickAndMortyCharacter) {
let endpoint = RickAndMortyAPI.singleCharacter(id: character.id)
guard let url = URL(string: endpoint.url) else { return }
var request = URLRequest(url: url)
request.httpMethod = endpoint.method.rawValue
let session = URLSession.shared.dataTaskPublisher(for: request)
_ = session
.tryMap(responseMapper)
.decode(type: RickAndMortyResponseWrapper<RickAndMortyCharacter>.self, decoder: jsonDecoder)
.mapError(errorMapper)
.sink { someValue in
print(someValue)
}
}
func fetchEpisode(_ episodeId: Int) {
let endpoint = RickAndMortyAPI.episode(id: episodeId)
guard let url = URL(string: endpoint.url) else { return }
var request = URLRequest(url: url)
request.httpMethod = endpoint.method.rawValue
let session = URLSession.shared.dataTaskPublisher(for: request)
_ = session
.tryMap(responseMapper)
.decode(type: RickAndMortyResponseWrapper<Episode>.self, decoder: jsonDecoder)
.mapError(errorMapper)
.sink { someValue in
print(someValue)
}
}
private func responseMapper(data: Data, response: URLResponse) throws -> Data {
guard let response = response as? HTTPURLResponse else { throw HTTPError() }
guard response.statusCode == 200 else { throw StatusCodeError() }
return data
}
private func errorMapper(error: Error) -> Error {
print(error.localizedDescription)
return error
}
}
| true
|
c22aaeb49ab77e1c64f52265e077fa2fcc4845c2
|
Swift
|
emgranados/Virtual_Tourist_Journal
|
/Virtual Tourist Social Journal/Virtual Tourist/Controller/Map/MapViewAddAnnotations.swift
|
UTF-8
| 980
| 2.828125
| 3
|
[] |
no_license
|
//
// MapViewAddAnnotations.swift
// Virtual Tourist
//
// Created by Edwina Granados on 10/11/19.
// Copyright © 2019 Edwina Granados. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
import MapKit
extension MapViewController{
func addAnnotationToDatabase(for coordinate:CLLocationCoordinate2D) {
let annotation = PutAnnotation()
annotation.coordinate = coordinate
addNewPlace(with: coordinate) {
objectID in
annotation.objectID = objectID
self.places.append(annotation)
self.addAnnotationToMap(annotation)
}
}
func addAnnotationToMap(_ annotation: PutAnnotation) {
mapView.addAnnotation(annotation)
}
func addAnnotationToMap(for annotation: PutAnnotation) {
mapView.addAnnotation(annotation)
}
func showPinsOnMapForAllPlaces() {
for place in places{
addAnnotationToMap(for: place)
}
}
}
| true
|
1e5998f414f47d49bbb65d87866216f0cdb2278b
|
Swift
|
karimslim/iosProjectFinal
|
/iosProject/CustomImage.swift
|
UTF-8
| 627
| 2.5625
| 3
|
[] |
no_license
|
//
// CustomImage.swift
// iosProject
//
// Created by Slim Karim on 03/05/2018.
// Copyright © 2018 Slim Karim. All rights reserved.
//
import UIKit
@IBDesignable class CustomImage: UIImageView {
@IBInspectable var cornerRadius : CGFloat = 0 {
didSet{
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: CGColor = UIColor.black.cgColor {
didSet{
layer.borderColor = borderColor
}
}
}
| true
|
b7bec7ea4aa18da3050d246004f5ed572ba4062c
|
Swift
|
manomuthu-optisol/Git-Sample
|
/MyCloudedLife/Lib/Lib.swift
|
UTF-8
| 10,181
| 3
| 3
|
[] |
no_license
|
//
// Lib.swift
// MyCloudedLife
//
// Created by Dinesh on 17/08/17.
// Copyright © 2017 OptisolBusinessSolution. All rights reserved.
//
import Foundation
import ReachabilitySwift
import MBProgressHUD
class Lib: NSObject {
var loadingNotification = MBProgressHUD()
class var sharedInstance: Lib {
struct Static {
static let instance = Lib()
}
return Static.instance
}
public func isHasConnection () -> Bool {
let reachability = Reachability();
if(reachability?.currentReachabilityStatus == Reachability.NetworkStatus.notReachable){
return false;
}
return true;
}
//MARK: - ProgressHUD
public func showLoader(view: UIView, message: String){
loadingNotification = MBProgressHUD.showAdded(to: view, animated: true)
loadingNotification.mode = MBProgressHUDMode.indeterminate
loadingNotification.label.text = message
}
public func hideLoader(){
loadingNotification.hide(animated: true)
}
//MARK: - Dialog
func showDialog(title : String, msg : String, imageStr : String, transition : PopupDialogTransitionStyle, gesture : Bool, btnTitle : String, bgColor : String, btnBgColor : UIColor, vc : UIViewController) {
// Create a custom view controller
let dialog = DialogView(nibName: Constant().kDialogView, bundle: nil)
dialog.strMsg = msg
dialog.strViewBg = bgColor
dialog.strImg = imageStr
// Create the dialog
let popup = PopupDialog(viewController: dialog, buttonAlignment: .horizontal, transitionStyle: transition, gestureDismissal: gesture)
popup.view.backgroundColor = UIColor.clear
// Create confirm button
let buttonConfirm = DefaultButton(title: btnTitle, height: 50) {
}
buttonConfirm.backgroundColor = btnBgColor
buttonConfirm.titleColor = UIColor.white
buttonConfirm.titleFont = UIFont(name: "CircularStd-Bold", size: 20)
// Add buttons to dialog
popup.addButtons([buttonConfirm])
// Present dialog
vc.present(popup, animated: true, completion: nil)
}
}
//Hex color to UIColor
extension UIColor {
convenience init(hex: String, alpha: CGFloat = 1) {
assert(hex[hex.startIndex] == "#", "Expected hex string of format #RRGGBB")
let scanner = Scanner(string: hex)
scanner.scanLocation = 1 // skip #
var rgb: UInt32 = 0
scanner.scanHexInt32(&rgb)
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16)/255.0,
green: CGFloat((rgb & 0xFF00) >> 8)/255.0,
blue: CGFloat((rgb & 0xFF) )/255.0,
alpha: alpha)
}
}
//String Partial Bold and normal
extension NSMutableAttributedString {
func bold(_ text:String) -> NSMutableAttributedString {
let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "CircularStd-Bold", size: 12)!]
let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
self.append(boldString)
return self
}
func normal(_ text:String)->NSMutableAttributedString {
let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "CircularStd-Bold", size: 15)!]
let normal = NSMutableAttributedString(string:"\(text)", attributes:attrs)
self.append(normal)
return self
}
func orangeColor(_ text:String)->NSMutableAttributedString {
let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "CircularStd-Bold", size: 15)!]
let color = NSMutableAttributedString(string:"\(text)", attributes:attrs)
let range = (text as NSString).range(of: text)
let attribute = NSMutableAttributedString.init(string: text)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange , range: range)
self.append(color)
return self
}
}
//String Split by range
extension String {
func index(from: Int) -> Index {
return self.index(startIndex, offsetBy: from)
}
func substring(from: Int) -> String {
let fromIndex = index(from: from)
return substring(from: fromIndex)
}
func substring(to: Int) -> String {
let toIndex = index(from: to)
return substring(to: toIndex)
}
func substring(with r: Range<Int>) -> String {
let startIndex = index(from: r.lowerBound)
let endIndex = index(from: r.upperBound)
return substring(with: startIndex..<endIndex)
}
}
//Load image from URL
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
//Load UIView from nib
extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle : Bundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
}
extension UIView {
class func fromNib<T : UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}
//Button selected background color
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
//String Equal
extension String {
func isEqualToString(find: String) -> Bool {
return String(format: self) == find
}
}
//Int to String
extension Int {
var stringValue:String {
return "\(self)"
}
}
//Split by length
extension String {
func splitByLength(_ length: Int) -> [String] {
var result = [String]()
var collectedCharacters = [Character]()
collectedCharacters.reserveCapacity(length)
var count = 0
for character in self.characters {
collectedCharacters.append(character)
count += 1
if (count == length) {
// Reached the desired length
count = 0
result.append(String(collectedCharacters))
collectedCharacters.removeAll(keepingCapacity: true)
}
}
// Append the remainder
if !collectedCharacters.isEmpty {
result.append(String(collectedCharacters))
}
return result
}
}
//Check int
extension String {
var isInt: Bool {
return Int(self) != nil
}
}
//Scroll To Top
extension UIScrollView {
// Bonus: Scroll to top
func scrollToTop(animated: Bool) {
let topOffset = CGPoint(x: 0, y: -contentInset.top)
setContentOffset(topOffset, animated: animated)
}
// Bonus: Scroll to bottom
func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
if(bottomOffset.y > 0) {
setContentOffset(bottomOffset, animated: true)
}
}
}
//View Shadow
extension UIView {
func dropShadow(scale: Bool = true, color: CGColor, radius: Int) {
self.layer.masksToBounds = false
self.layer.shadowColor = color
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSize(width: -1, height: 1)
self.layer.shadowRadius = CGFloat(radius)
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
extension Int {
func format(f: String) -> String {
return String(format: "%\(f)d", self)
}
}
extension Double {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
extension UIView {
func addDashedBorder() {
let color = UIColor.init(hex: Constant().kThemeBlue).cgColor
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color
shapeLayer.lineWidth = 2
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = [6,3]
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
self.layer.addSublayer(shapeLayer)
}
}
extension UINavigationController {
func backToViewController(viewController: Swift.AnyClass) {
for element in viewControllers as Array {
if element.isKind(of: viewController) {
self.popToViewController(element, animated: true)
break
}
}
}
}
| true
|
6af351a8ffa950d77f1fddc57ea8cb5aa87fabb2
|
Swift
|
dannys42/zoo
|
/sorting/quicksort.swift
|
UTF-8
| 2,153
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/swift sh
import Shared // ../shared
extension Array where Element: Comparable {
mutating func quickSort(low: Int?=nil, high: Int?=nil) {
let low = low ?? 0
let high = high ?? self.count-1
guard self.count > 0 else { return }
guard high-low >= 1 else { return }
let pNdx = self.partition(low: 0, high: high)
print("quick left \(low) - \(pNdx-1) begin")
self.quickSort(low: low, high: pNdx-1)
print("quick left \(low) - \(pNdx-1) end")
print("quick right \(pNdx+1) - \(high) begin")
self.quickSort(low: pNdx+1, high: high)
print("quick right \(pNdx+1) - \(high) end")
}
internal mutating func partition(low: Int, high: Int) -> Int {
print("partition: \(low) - \(high)")
guard low >= 0 else { return -1 }
guard high >= 0 else { return -1 }
guard low < self.count else { return -1 }
guard high < self.count else { return -1 }
let pivotVal = self[high]
var j = high
var i = low
while i < j {
print("i = \(i) j = \(j)")
print("self[\(i)] begin")
if self[i] < pivotVal {
print("self[\(i)] end in if")
i += 1
print(" i++ \(i)")
continue
}
print("self[\(i)] end out if")
print("as1 beg")
self[j] = self[i]
print("as1 end")
if (j-1) > i {
print("as2 beg")
self[i] = self[j-1]
print("as2 end")
}
j -= 1
print(" j-- \(j)")
}
self[j] = pivotVal
return j
}
}
var a = [5, 20, 7, 19, 8, 1]
print("Unsorted: \(a)")
//a.partition(low: 0, high: a.count-1)
//print("Partition: \(a)")
a.quickSort()
print("Sorted: \(a)")
for r in 0..<10 {
print("--- run \(r) -----")
var b: [Int] = (0..<20).map { _ in .random(in: 0...100) }
print("unsorted b: \(b) isSorted: \(b.isSorted)")
b.quickSort()
print(" sorted b: \(b) isSorted: \(b.isSorted)")
print("")
}
| true
|
f9980b3d1df144d77d7466e67afa834b87aee66c
|
Swift
|
BlaineCD/100DaysOfSwift
|
/Project24_SwiftStrings.playground/Contents.swift
|
UTF-8
| 3,575
| 4.40625
| 4
|
[] |
no_license
|
import UIKit
// Pt. 1: Strings are not arrays
let name = "Blaine"
for letter in name {
print("Give me a \(letter)")
}
let letter = name[name.index(name.startIndex, offsetBy: 3)]
// To find an empty string better to use isEmpty than count == 0.
// right:
name.isEmpty
// wrong:
name.isEmpty
// Pt. 2: Working with Strings in Swift
let password = "12345"
password.hasPrefix("123")
password.hasSuffix("345")
// Add extension methds to extend how prefixing and suffixing works:
extension String {
func deletingPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
func deletingSuffix(_ suffix: String) -> String {
guard self.hasSuffix(suffix) else { return self }
return String(self.dropLast(suffix.count))
}
}
// capitalized property gives first letter of each word a capital letter:
let weather = "it's going to rain"
print(weather.capitalized)
// prints: It's Going To Rain
// add specialized extension that uppercases only the first letter of the strin.
extension String {
var capitalizedFirst: String {
guard let firstLetter = self.first else { return "" }
return firstLetter.uppercased() + self.dropFirst()
}
}
// contains() returns true if it contains another string.
let input = "Swift is like Objective-C without the C"
input.contains("Swift")
// returns true
let languages = ["Python", "Ruby", "Swift"]
languages.contains("Swift")
// returns true
extension String {
func containsAny(of array: [String]) -> Bool {
for item in array {
if self.contains(item) {
return true
}
}
return false
}
}
input.containsAny(of: languages)
// More elegant solution.
languages.contains(where: input.contains)
// Pt. 3: Formatting strings with NSAttributedString
let string = "This is a test string"
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.white,
.backgroundColor: UIColor.red,
.font: UIFont.boldSystemFont(ofSize: 36)
]
let attributedString = NSAttributedString(string: string, attributes: attributes)
let anotherString = "This is a test string"
let anotherAttributedString = NSMutableAttributedString(string: anotherString)
anotherAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 8), range: NSRange(location: 0, length: 4))
anotherAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 5, length: 2))
anotherAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 24), range: NSRange(location: 8, length: 1))
anotherAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 32), range: NSRange(location: 10, length: 4))
anotherAttributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 40), range: NSRange(location: 15, length: 6))
// Challenge 1
extension String {
func withPrefix(_ prefix: String) -> String {
if self.hasPrefix(prefix) { return self }
return prefix + self
}
}
// test
print("boat".withPrefix("house"))
print("boat".withPrefix("bo"))
// Challenge 2
extension String {
var isNumeric: Bool {
self.contains("\(Int())") || self.contains("\(Double())") || self.contains("\(Float())") ? true : false
}
}
// test
"Houseboat".isNumeric
"H0useboat".isNumeric
"H10.7SEBOAT".isNumeric
// Challenge 3
extension String {
var lines: [String] {
self.components(separatedBy: "\n")
}
}
// test
"this\nis\na\ntest".lines
| true
|
003bf6e563c8844fdbc022eb70d81537cfd0b1bb
|
Swift
|
nettan20/AdvancedCollectionView
|
/AdvancedCollectionView/GridLayoutInfo.swift
|
UTF-8
| 18,160
| 2.859375
| 3
|
[] |
no_license
|
//
// GridLayoutInfo.swift
// AdvancedCollectionView
//
// Created by Zachary Waldowski on 12/22/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
enum ElementKey: Hashable {
typealias IndexPathKind = (NSIndexPath, String)
case Cell(NSIndexPath)
case Supplement(IndexPathKind)
case Decoration(IndexPathKind)
init(_ indexPath: NSIndexPath) {
self = .Cell(indexPath)
}
init(supplement kind: String, _ indexPath: NSIndexPath) {
self = .Supplement(indexPath, kind)
}
init(decoration kind: String, _ indexPath: NSIndexPath) {
self = .Decoration(indexPath, kind)
}
var indexPath: NSIndexPath {
switch self {
case .Cell(let indexPath):
return indexPath
case .Supplement(let kind):
return kind.0
case .Decoration(let kind):
return kind.0
}
}
var correspondingItem: ElementKey {
return ElementKey(indexPath)
}
func correspondingSupplement(kind: String) -> ElementKey {
return ElementKey(supplement: kind, indexPath)
}
var components: (Section, Int) {
let ip = indexPath
if ip.length == 1 {
return (.Global, ip[0])
}
return (.Index(ip[0]), ip[1])
}
}
private func ==(lhs: ElementKey.IndexPathKind, rhs: ElementKey.IndexPathKind) -> Bool {
return (lhs.0 === rhs.0 || lhs.0 == rhs.0) && lhs.1 == rhs.1
}
func ==(lhs: ElementKey, rhs: ElementKey) -> Bool {
switch (lhs, rhs) {
case (.Cell(let lIndexPath), .Cell(let rIndexPath)):
return lIndexPath == rIndexPath
case (.Supplement(let lhsKey), .Supplement(let rhsKey)):
return lhsKey == rhsKey
case (.Decoration(let lhsKey), .Decoration(let rhsKey)):
return lhsKey == rhsKey
default:
return false
}
}
extension ElementKey: Hashable {
var hashValue: Int {
var build = SimpleHash(prime: 37)
switch self {
case .Cell:
build.append(UICollectionElementCategory.Cell)
case .Supplement(let kind):
build.append(UICollectionElementCategory.SupplementaryView)
build.append(kind.1)
case .Decoration(let kind):
build.append(UICollectionElementCategory.DecorationView)
build.append(kind.1)
default: break
}
build.append(indexPath)
return build.result
}
}
extension ElementKey: Printable, DebugPrintable {
var description: String {
func describeIndexPath(indexPath: NSIndexPath) -> String {
return join(", ", map(indexPath) { String($0) })
}
func describeKind(kind: IndexPathKind) -> String {
return "\(kind.1)@\(describeIndexPath(kind.0))"
}
switch self {
case .Cell(let indexPath):
return describeIndexPath(indexPath)
case .Supplement(let kind):
return describeKind(kind)
case .Decoration(let kind):
return describeKind(kind)
}
}
var debugDescription: String {
return description
}
}
// MARK: -
private extension SectionMetrics {
func itemPadding(#rows: HalfOpenInterval<Int>, columns: HalfOpenInterval<Int>) -> UIEdgeInsets {
if var insets = padding {
if rows.start != 0 {
insets.top = 0
}
if !rows.isEmpty {
insets.bottom = 0
}
if columns.start > 0 {
insets.left = 0
}
if !columns.isEmpty {
insets.right = 0
}
return insets
}
return UIEdgeInsets()
}
var layoutSlicingEdge: CGRectEdge {
let layout = itemLayout ?? .Natural
switch layout {
case .Natural:
return UIUserInterfaceLayoutDirection.userLayoutDirection == .LeftToRight ? .MinXEdge : .MaxXEdge
case .NaturalReverse:
return UIUserInterfaceLayoutDirection.userLayoutDirection == .RightToLeft ? .MinXEdge : .MaxXEdge
case .LeadingToTrailing:
return .MinXEdge
case .TrailingToLeading:
return .MaxXEdge
}
}
}
// MARK: -
struct SupplementInfo {
let metrics: SupplementaryMetrics
let measurement: ElementLength
let frame: CGRect
private init(metrics: SupplementaryMetrics, measurement: ElementLength? = nil, frame: CGRect = CGRect()) {
self.metrics = metrics
self.measurement = measurement ?? metrics.measurement!
self.frame = frame
}
}
struct ItemInfo {
let measurement: ElementLength
let padding: UIEdgeInsets
let frame: CGRect
private init(measurement: ElementLength, padding: UIEdgeInsets = UIEdgeInsets(), frame: CGRect = CGRect()) {
self.measurement = measurement
self.padding = padding
self.frame = frame
}
}
struct RowInfo {
let items: ArraySlice<ItemInfo>
let frame: CGRect
private init(items: ArraySlice<ItemInfo>, frame: CGRect) {
self.items = items
self.frame = frame
}
}
struct SectionInfo {
let metrics: SectionMetrics
private(set) var items = [ItemInfo]()
private(set) var rows = [RowInfo]() // ephemeral, only full once laid out
private(set) var supplementalItems = Multimap<String, SupplementInfo>()
private(set) var frame = CGRect()
private var headersRect = CGRect()
private var itemsRect = CGRect()
private var footersRect = CGRect()
var contentRect: CGRect {
return frame.rectByInsetting(insets: UIEdgeInsetsMake(0, 0, metrics.margin ?? 0, 0))
}
init(metrics: SectionMetrics) {
self.metrics = metrics
}
// init(metrics: SectionMetrics, supplements: [Supplement]
}
// MARK: Attributes access
extension SectionInfo {
enum SupplementIndex {
case Header
case Footer
case Named(String)
case AllOther
}
private var notNamed: SequenceOf<(String, [SupplementInfo]) > {
return supplementalItems.groups { (key, _) in
key != SupplementKind.Header.rawValue && key != SupplementKind.Footer.rawValue
}
}
func count(#supplements: SupplementIndex) -> Int {
switch supplements {
case .Header:
return supplementalItems[SupplementKind.Header.rawValue].count
case .Footer:
return supplementalItems[SupplementKind.Footer.rawValue].count
case .Named(let kind):
return supplementalItems[kind].count
case .AllOther:
return reduce(lazy(notNamed).map({
$0.1.count
}), 0, +)
}
}
subscript(supplement: SupplementIndex) -> SequenceOf<(String, Int, SupplementInfo)> {
switch supplement {
case .Header:
return SequenceOf(supplementalItems.enumerate(forKey: SupplementKind.Header.rawValue))
case .Footer:
return SequenceOf(supplementalItems.enumerate(forKey: SupplementKind.Footer.rawValue))
case .Named(let kind):
return SequenceOf(supplementalItems.enumerate(forKey: kind))
case .AllOther:
return SequenceOf { MultimapEnumerateGenerator(self.notNamed) }
}
}
var placeholder: SupplementInfo? {
get {
return supplementalItems[SupplementKind.Placeholder.rawValue].first
}
set {
if let info = newValue {
supplementalItems.update(CollectionOfOne(info), forKey: SupplementKind.Placeholder.rawValue)
} else {
supplementalItems.remove(valuesForKey: SupplementKind.Placeholder.rawValue)
}
}
}
mutating func addSupplementalItem(metrics: SupplementaryMetrics) {
let info = SupplementInfo(metrics: metrics)
supplementalItems.append(info, forKey: metrics.kind)
}
mutating func addPlaceholder() {
let metrics = SupplementaryMetrics(kind: SupplementKind.Placeholder)
let info = SupplementInfo(metrics: metrics, measurement: .Remainder)
placeholder = info
}
mutating func addItems(count: Int) {
let item = ItemInfo(measurement: metrics.measurement!)
items += Repeat(count: count, repeatedValue: item)
}
subscript (kind: String, supplementIndex: Int) -> SupplementInfo? {
return supplementalItems[kind, supplementIndex]
}
var numberOfItems: Int {
return items.count
}
subscript (itemIndex: Int) -> ItemInfo? {
if itemIndex < items.endIndex {
return items[itemIndex]
}
return nil
}
}
extension SectionInfo {
typealias MeasureItem = (index: Int, measuringFrame: CGRect) -> CGSize
typealias MeasureSupplement = ( kind: String, index: Int, measuringFrame: CGRect) -> CGSize
mutating func layout(rect viewport: CGRect, inout nextStart: CGPoint, measureSupplement: MeasureSupplement, measureItem: MeasureItem? = nil) {
rows.removeAll(keepCapacity: true)
let numberOfItems = items.count
let numberOfColumns = metrics.numberOfColumns ?? 1
var layoutRect = viewport
layoutRect.size.height = CGFloat.infinity
// First, lay out headers
let headerBeginY = layoutRect.minY
let headerKey = SupplementKind.Header.rawValue
supplementalItems.updateMapWithIndex(groupForKey: headerKey) { (headerIndex, headerInfo) in
// skip headers if there are no items and the header isn't a global header
if numberOfItems == 0 && !headerInfo.metrics.isVisibleWhileShowingPlaceholder { return headerInfo }
// skip headers that are hidden
if headerInfo.metrics.isHidden { return headerInfo }
let measurement: ElementLength
switch (headerInfo.measurement, headerInfo.metrics.measurement) {
case (_, .Some(let value)):
measurement = value
case (.Estimate(let estimate), _):
// This header needs to be measured!
let frame = CGRect(origin: layoutRect.origin, size: CGSize(width: viewport.width, height: estimate))
let measure = measureSupplement(kind: headerKey, index: headerIndex, measuringFrame: frame)
measurement = .Static(measure.height)
case (let value, _):
measurement = value
}
let frame = layoutRect.divide(measurement.lengthValue)
return SupplementInfo(metrics: headerInfo.metrics, measurement: measurement, frame: frame)
}
headersRect = CGRect(x: viewport.minX, y: headerBeginY, width: viewport.width, height: layoutRect.minY - headerBeginY)
switch (numberOfItems, placeholder) {
case (0, .Some(var info)):
itemsRect = CGRect()
footersRect = CGRect()
// Height of the placeholder is equal to the height of the collection view minus the height of the headers
let frame = layoutRect.rectByIntersecting(viewport)
placeholder = SupplementInfo(metrics: info.metrics, measurement: .Static(frame.height), frame: frame)
_ = layoutRect.divide(frame.height)
case (_, .None) where numberOfItems != 0:
// Lay out items and footers only if there actually ARE items.
let itemsBeginY = layoutRect.minY
let columnsPointsRatio = CGFloat(numberOfColumns)
let maxWidth = metrics.padding.map { layoutRect.width - $0.left - $0.right } ?? layoutRect.width
let numberOfRows = Int(ceil(CGFloat(items.count) / columnsPointsRatio))
let columnWidth = maxWidth / columnsPointsRatio
let divideFrom = metrics.layoutSlicingEdge
let sectionMeasurement = metrics.measurement
rows.reserveCapacity(numberOfRows + 1)
for range in take(items.startIndex..<items.endIndex, eachSlice: numberOfColumns) {
let original = items[range]
// take a measurement pass through all items
let measurePass = original.mapWithIndex { (columnIndex, item) -> ItemInfo in
let rowIndex = self.rows.count
let padding = self.metrics.itemPadding(rows: rowIndex..<numberOfRows, columns: columnIndex..<numberOfColumns)
let measurement = { () -> ElementLength in
switch (item.measurement, sectionMeasurement, measureItem) {
case (_, .Some(.Static(let value)), _):
return .Static(value + padding.top + padding.bottom)
case (.Estimate(let estimate), _, .Some(let measure)):
let idx = range.startIndex.advancedBy(columnIndex)
let width = columnWidth + padding.left + padding.right
let height = estimate + padding.top + padding.bottom
let frame = CGRect(origin: layoutRect.origin, size: CGSize(width: width, height: height))
let measured = measure(index: idx, measuringFrame: frame)
return .Static(measured.height)
case (let passthrough, _, _):
return passthrough
}
}()
return ItemInfo(measurement: measurement, padding: padding, frame: item.frame)
}
let rowHeight = maxElement(lazy(measurePass).map { $0.measurement.lengthValue })
let rowRect = layoutRect.divide(rowHeight)
var rowLayoutRect = rowRect
items[range] = measurePass.map {
let frame = rowLayoutRect.divide(columnWidth, fromEdge: divideFrom)
return ItemInfo(measurement: $0.measurement, padding: $0.padding, frame: frame)
}
rows.append(RowInfo(items: items[range], frame: rowRect))
}
itemsRect = CGRect(x: viewport.minX, y: itemsBeginY, width: viewport.width, height: layoutRect.minY - itemsBeginY)
// Lay out footers as well
let footerBeginY = layoutRect.minY
let headerKey = SupplementKind.Header.rawValue
supplementalItems.updateMapWithIndex(groupForKey: SupplementKind.Footer.rawValue) { (footerInfex, footerInfo) in
// skip hidden footers
if (footerInfo.metrics.isHidden) { return footerInfo }
// Temporary: give this full measurement as well
var height = CGFloat(0)
switch footerInfo.metrics.measurement {
case .Some(.Static(let value)):
height = value
default:
return footerInfo
}
let frame = layoutRect.divide(height)
return SupplementInfo(metrics: footerInfo.metrics, measurement: footerInfo.measurement, frame: frame)
}
footersRect = CGRect(x: viewport.minX, y: footerBeginY, width: viewport.width, height: layoutRect.minY - footerBeginY)
default: break
}
// This is now the beginning of the section gap for the next section
if let bottom = metrics.margin {
_ = layoutRect.divide(bottom)
}
frame = CGRect(x: viewport.minX, y: viewport.minY, width: viewport.width, height: layoutRect.minY - viewport.minY)
nextStart = CGPoint(x: frame.minX, y: frame.maxY)
}
}
extension SectionInfo {
mutating func remeasureItem(atIndex index: Int, function: MeasureItem) {
let original = items[index]
var newFrame = CGRect(origin: original.frame.origin, size: CGSize(width: original.frame.width, height: UILayoutFittingExpandedSize.height))
newFrame.size = function(index: index, measuringFrame: newFrame)
let newMeasurement = ElementLength.Static(newFrame.height)
items[index] = ItemInfo(measurement: newMeasurement, padding: original.padding, frame: newFrame)
}
}
// MARK: Printing
extension ItemInfo: DebugPrintable {
var debugDescription: String {
return "{Item}: \(NSStringFromCGRect(frame))"
}
}
extension SupplementInfo: DebugPrintable {
var debugDescription: String {
return "{Supplement}: \(NSStringFromCGRect(frame))"
}
}
extension RowInfo: DebugPrintable {
var debugDescription: String {
var ret = "{Section}: \(NSStringFromCGRect(frame))"
if !isEmpty(items) {
let desc = join("\n ", items.map { $0.debugDescription })
ret += "\n items = [\n \(desc)\n ]"
}
return ret
}
}
extension SectionInfo: DebugPrintable {
var debugDescription: String {
var ret = "{Section}: \(NSStringFromCGRect(frame))"
if !rows.isEmpty {
let desc = join("\n ", rows.map { $0.debugDescription })
ret += "\n rows = [\n %@\n ]"
}
if !supplementalItems.isEmpty {
let desc = join("\n", map(supplementalItems.groups()) {
let desc = join("\n", map($1) { " \($0.debugDescription)" })
return " \($0) = [\n\(desc) ]\n"
})
ret += "\n supplements = [\n\(desc)\n ]"
}
return ret
}
}
| true
|
53673356629c8e7ea92acc4e45358f0d6e8d2137
|
Swift
|
elilaird/CS7323-Mobile-Sensing
|
/common_sense_UI/common_sense/AudioResultViewController.swift
|
UTF-8
| 3,543
| 2.6875
| 3
|
[] |
no_license
|
//
// AudioResultViewController.swift
// common_sense
//
// Created by Eli Laird on 12/12/20.
//
import UIKit
import Charts
class AudioResultViewController: UIViewController {
@IBOutlet weak var hearingRange: UILabel!
@IBOutlet weak var lineChart: LineChartView!
@IBOutlet weak var graphRangeLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
var dataInterface: DataInterface = DataInterface()
let pastelGreen = UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.view.bounds
let startGrad = UIColor(red: 88/255, green: 102/255, blue: 139/255, alpha: 1.0).cgColor
gradientLayer.colors = [startGrad, UIColor.white.cgColor]
self.view.layer.insertSublayer(gradientLayer, at: 0)
self.doneButton.layer.cornerRadius = 9
self.doneButton.backgroundColor = self.pastelGreen
let audioResults = dataInterface.getAudioData()
let high = getFormattedFrequency(with: audioResults.last!.highFrequencyAtMaxdB)
let low = getFormattedFrequency(with: audioResults.last!.lowFrequencyAtMaxdB)
self.hearingRange.adjustsFontSizeToFitWidth = true
self.hearingRange.text = String(format: "%@ - %@", low, high)
// CHART
var yHigh:[Double] = []
var yLow:[Double] = []
let x = Array(stride(from: 0, to: audioResults.count, by:1)).map {Double($0)}
for audioE in audioResults {
yHigh.append(Double(audioE.highFrequencyAtMaxdB))
yLow.append(Double(audioE.lowFrequencyAtMaxdB))
}
let firstTime = audioResults.first?.timeRecorded ?? Date()
let sinceFirstTime = firstTime.timeAgoDisplay()
self.graphRangeLabel.text = "From " + sinceFirstTime + " to now"
self.graphRangeLabel.adjustsFontSizeToFitWidth = true
generateChart(xValsLow: x, yValsLow: yLow, xValsHigh: x, yValsHigh: yHigh, length: x.count)
}
func generateChart(xValsLow: [Double], yValsLow: [Double], xValsHigh: [Double], yValsHigh: [Double], length: Int){
var lineChartEntryLow = [ChartDataEntry]()
var lineChartEntryHigh = [ChartDataEntry]()
for i in 0..<length{
let valueLow = ChartDataEntry(x: xValsLow[i], y: yValsLow[i])
let valueHigh = ChartDataEntry(x: xValsHigh[i], y: yValsHigh[i])
lineChartEntryLow.append(valueLow)
lineChartEntryHigh.append(valueHigh)
}
let lineLow = LineChartDataSet(entries: lineChartEntryLow, label: "Number")
let lineHigh = LineChartDataSet(entries: lineChartEntryHigh, label: "Number")
lineLow.colors = [NSUIColor.blue]
lineHigh.colors = [NSUIColor.red]
let data = LineChartData()
data.addDataSet(lineLow)
data.addDataSet(lineHigh)
lineChart.data = data
lineChart.legend.enabled = false
lineChart.xAxis.enabled = false
lineChart.chartDescription?.text = ""
}
func getFormattedFrequency(with freq:Float) -> String{
let formatter = MeasurementFormatter()
let hertz = Measurement(value: Double(freq), unit: UnitFrequency.hertz)
return formatter.string(from: hertz)
}
@IBAction func returnToLanding(_ sender: Any) {
_ = navigationController?.popToRootViewController(animated: true)
}
}
| true
|
587f36d5e32ef8c0a038bef4d19c309a649c8450
|
Swift
|
evan0322/ALeetcodeADay
|
/ALeetcodeADay.playground/Pages/1049. Last Stone Weight II .xcplaygroundpage/Contents.swift
|
UTF-8
| 1,914
| 3.515625
| 4
|
[] |
no_license
|
//: [Previous](@previous)
import Foundation
/*
Divide the nums into two groups and make the diff minimal
Sm + Sn = S
Sm - Sn = diff ->
diff = S - 2Sn ->
find the max value of Sn that does not exceed S/2 ->
knapsack problem
dp[i][j] -> able to sum to j with element in 0...i
dp[i][j] = dp[i - 1][j - num[i - 1]] || dp[i - 1]
*/
func lastStoneWeightII(_ stones: [Int]) -> Int {
let sum = stones.reduce(0, +)
var dp = Array(repeating:Array(repeating:false, count:sum/2 + 1), count: stones.count + 1)
dp[0][0] = true
for i in 1...stones.count {
for j in 0...sum/2 {
if j >= stones[i - 1] {
dp[i][j] = dp[i - 1][j - stones[i - 1]] || dp[i - 1][j]
} else {
dp[i][j] = dp[i - 1][j]
}
}
}
var minValue = Int.max
for j in 0...sum/2 {
if dp[stones.count][j] {
minValue = min(minValue, sum - j * 2)
}
}
return minValue
}
// We can see that dp[i][x] only relate to dp[i - 1][x]. so we just need one array to remember previous calculated value
func lastStoneWeightIILessSpace(_ stones: [Int]) -> Int {
let sum = stones.reduce(0, +)
var dp = Array(repeating:false, count: sum/2 + 1)
dp[0] = true
for i in 1...stones.count {
var temp = Array(repeating:false, count: sum/2 + 1)
for j in 0...sum/2 {
if j >= stones[i - 1] {
temp[j] = dp[j - stones[i - 1]] || dp[j]
} else {
temp[j] = dp[j]
}
}
dp = temp
}
var minValue = Int.max
for j in 0...sum/2 {
if dp[j] {
minValue = min(minValue, sum - j * 2)
}
}
return minValue
}
| true
|
b080263fefa8d48016d6dfe8740c3313b7e11498
|
Swift
|
mhmoore/CraftedBrew
|
/Coffee/Coffee/Models/Note.swift
|
UTF-8
| 1,091
| 3.359375
| 3
|
[] |
no_license
|
//
// Note.swift
// Coffee
//
// Created by Michael Moore on 9/12/19.
// Copyright © 2019 Michael Moore. All rights reserved.
//
import Foundation
class Note: Codable {
var roaster: String
var coffeeName: String
var origin: String
var grind: String
var ratio: String
var method: String
var tastingNotes: String
init(roaster: String, coffeeName: String, origin: String, grind: String, ratio: String, method: String, tastingNotes: String) {
self.roaster = roaster
self.coffeeName = coffeeName
self.origin = origin
self.grind = grind
self.ratio = ratio
self.method = method
self.tastingNotes = tastingNotes
}
}
extension Note: Equatable {
static func == (lhs: Note, rhs: Note) -> Bool {
return lhs.roaster == rhs.roaster &&
lhs.coffeeName == rhs.coffeeName &&
lhs.method == rhs.method &&
lhs.origin == rhs.origin &&
lhs.tastingNotes == rhs.tastingNotes &&
lhs.ratio == rhs.ratio &&
lhs.grind == rhs.grind
}
}
| true
|
959a8b5210f2de15e2e413b0decb631720f45650
|
Swift
|
BugPersonality/ExamplesOfPatternsForSmallAndStupid
|
/Patterns/Patterns/Decorator, Facade, Flyweight, Proxy/Flyweight.swift
|
UTF-8
| 1,051
| 3.828125
| 4
|
[] |
no_license
|
import Foundation
class Image{}
class Exercise{
var id: Int
var duration: Double
var images: [Image]
init(id: Int, duration: Double, imgs: [Image]) {
self.duration = duration
self.id = id
self.images = imgs
}
func show(step: Int){
if images.count > step{
let img = images[step]
print("Show \(step) image \(img)")
}
}
}
class FactoryExercise{
private var _cache: [Int:Exercise] = [:]
func get (id: Int) -> Exercise{
if _cache[id] == nil{
let ex = fetchFromServer(id: id)
_cache[id] = ex
}
return _cache[id]!
}
func fetchFromServer(id: Int) -> Exercise{
return Exercise(id: id, duration: 10, imgs: [Image(), Image(), Image()])
}
}
class Workout{
private var ex: Exercise
private var step: Int
init(ex: Exercise) {
self.ex = ex
self.step = 0
}
func doIt(){
ex.show(step: step)
step += 1
}
}
| true
|
b553c9d4059487ec47ed35785e8fcfe58eb8fa7d
|
Swift
|
cadb-craftsman/swift-labs
|
/WatchOsIMC/WatchOsIMC WatchKit Extension/InterfaceController.swift
|
UTF-8
| 1,629
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// InterfaceController.swift
// WatchOsIMC WatchKit Extension
//
// Created by Carlos on 16/05/2017.
// Copyright © 2017 Woowrale. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var pesoValor: WKInterfaceLabel!
@IBOutlet var estaturaValor: WKInterfaceLabel!
var pesoActual : Float = 0
var estaturaActual : Float = 0
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func modificarPeso(_ value: Float) {
pesoActual += value
pesoValor.setText(String(pesoActual))
}
@IBAction func modificarEstatura(_ value: Float) {
estaturaActual += value / 100
estaturaValor.setText(String(estaturaActual))
}
@IBAction func calcularIMC() {
let imc = calcularIMC(peso: pesoActual, estatura: estaturaActual)
let contexto = Datos(descripcion:"Peso Normal", imc: imc)
pushController(withName: "IdentificadorDatos", context: contexto)
print("imc: ", imc)
}
func calcularIMC(peso: Float, estatura: Float) -> Float{
return pesoActual / (estaturaActual * estaturaActual)
}
}
| true
|
da0cd919e2451adf57f3331c601bae8da9250ae3
|
Swift
|
Shetoraz/testWeather
|
/testWeather/Main Scene/JSONModel.swift
|
UTF-8
| 1,891
| 2.859375
| 3
|
[] |
no_license
|
//
// JsonModel.swift
// testWeather
//
// Created by Anton Asetski on 1/4/20.
// Copyright © 2020 Anton Asetski. All rights reserved.
//
// MARK: - Welcome
struct Welcome: Codable {
let latitude, longitude: Double
let timezone: String
let currently: Currently
let daily: Daily
let hourly: Hourly
let offset: Int
}
// MARK: - Currently
struct Currently: Codable {
let time: Int
let summary, icon: String
let precipIntensity, precipProbability: Double
let temperature, apparentTemperature, dewPoint, humidity: Double
let pressure, windSpeed, windGust: Double
let windBearing, uvIndex: Int
let visibility, ozone: Double
}
// MARK: - Daily
struct Daily: Codable {
let summary, icon: String
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable {
let time: Int
let summary, icon: String
let sunriseTime, sunsetTime: Int
let moonPhase, precipIntensity, precipIntensityMax: Double
let precipIntensityMaxTime: Int
let precipProbability: Double
let temperatureHigh: Double
let temperatureHighTime: Int
let temperatureLow: Double
let temperatureLowTime: Int
let apparentTemperatureHigh: Double
let apparentTemperatureHighTime: Int
let apparentTemperatureLow: Double
let apparentTemperatureLowTime: Int
let dewPoint, humidity, pressure, windSpeed: Double
let windGust: Double
let windGustTime, windBearing: Int
let cloudCover: Double
let uvIndex, uvIndexTime: Int
let visibility, ozone, temperatureMin: Double
let temperatureMinTime: Int
let temperatureMax: Double
let temperatureMaxTime: Int
let apparentTemperatureMin: Double
let apparentTemperatureMinTime: Int
let apparentTemperatureMax: Double
let apparentTemperatureMaxTime: Int
}
// MARK: - Hourly
struct Hourly: Codable {
let summary: String
let data: [Currently]
}
| true
|
05e44d42242a0009af9851f8998b848d11d3d6a6
|
Swift
|
izhangsheng/leetCode
|
/LeetCode/排序/InsertionSort1.swift
|
UTF-8
| 521
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
//
// InsertionSort1.swift
// DataStructure
//
// Created by 张胜 on 2020/1/21.
// Copyright © 2020 张胜. All rights reserved.
//
import Foundation
class InsertionSort1<T: Comparable>: BaseSort<T> {
override func sort() {
for i in 1 ..< array.count {
var curIndex = i
while curIndex > 0, compare(i1: curIndex, i2: curIndex - 1) {
// 交换值
swap(i1: curIndex, i2: curIndex - 1)
curIndex -= 1
}
}
}
}
| true
|
e0ecbb5bb258688a3449bca3aaf72bee6bd3d970
|
Swift
|
songbai1211/europeantravel
|
/EuropeanTravel/Class/ZSBTraveLineViewController.swift
|
UTF-8
| 4,123
| 2.59375
| 3
|
[] |
no_license
|
//
// ZSBTraveLineViewController.swift
// EuropeanTravel
//
// Created by crespo on 2020/3/12.
// Copyright © 2020 EuropeanTravel. All rights reserved.
//
import UIKit
import AAInfographics
class ZSBTraveLineViewController: ZSBBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "旅行人数"
let aaChartView = AAChartView()
aaChartView.frame = CGRect(x:0,y:0,width:SCREEN_WIDTH,height:SCREEN_HEIGHT)
// set the content height of aachartView
// aaChartView?.contentHeight = self.view.frame.size.height
self.view.addSubview(aaChartView)
let aaChartModel = AAChartModel()
.chartType(.column)//Can be any of the chart types listed under `AAChartType`.
.title("欧洲各国旅行人数")//The chart title
.subtitle("每年前往欧洲旅行人数(w)")//The chart subtitle
.categories(["人数"])
.colorsTheme(["#fe117c","#ffc069","#06caf4","#7dffc0"])
.series([
AASeriesElement()
.name("英国")
.data([80]),
AASeriesElement()
.name("法国")
.data([70]),
AASeriesElement().name("摩洛哥")
.data([58]),
AASeriesElement()
.name("瑞士")
.data([55]),
AASeriesElement()
.name("芬兰")
.data([45]),
AASeriesElement()
.name("丹麦")
.data([42]),
AASeriesElement()
.name("德国")
.data([40]),
AASeriesElement()
.name("俄罗斯")
.data([39]),
AASeriesElement()
.name("冰岛")
.data([35]),
AASeriesElement()
.name("意大利")
.data([32]),
AASeriesElement()
.name("乌克兰")
.data([25]),
AASeriesElement()
.name("西班牙")
.data([23]),
AASeriesElement()
.name("荷兰")
.data([22]),
AASeriesElement()
.name("波兰")
.data([19]),
AASeriesElement()
.name("保加利亚")
.data([17]),
AASeriesElement()
.name("克罗地亚")
.data([16]),
AASeriesElement()
.name("比利时")
.data([16]),
AASeriesElement()
.name("捷克")
.data([14]),
AASeriesElement()
.name("梵蒂冈")
.data([13]),
AASeriesElement()
.name("葡萄牙")
.data([11]),
AASeriesElement()
.name("爱尔兰")
.data([6]),
AASeriesElement()
.name("卢森堡")
.data([6]),
AASeriesElement()
.name("罗马尼亚")
.data([3.9]),
AASeriesElement()
.name("立陶宛")
.data([3]),
])
aaChartView.aa_drawChartWithChartModel(aaChartModel)
}
/*
// 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.