repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
debugsquad/nubecero
refs/heads/master
nubecero/View/OnboardForm/VOnboardFormSender.swift
mit
1
import UIKit class VOnboardFormSender:UIView { private weak var controller:COnboardForm! private let kCornerRadius:CGFloat = 4 private let kButtonWidth:CGFloat = 100 private let kButtonRight:CGFloat = 20 convenience init(controller:COnboardForm) { self.init() clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor(white:1, alpha:0.9) self.controller = controller let border:UIView = UIView() border.isUserInteractionEnabled = false border.translatesAutoresizingMaskIntoConstraints = false border.backgroundColor = UIColor(white:0, alpha:0.05) let button:UIButton = UIButton() button.clipsToBounds = true button.backgroundColor = UIColor.complement button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = kCornerRadius button.setTitleColor(UIColor.white, for:UIControlState.normal) button.setTitleColor(UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) button.setTitle(controller.model.buttonMessage, for:UIControlState.normal) button.titleLabel!.font = UIFont.medium(size:14) button.layer.cornerRadius = kCornerRadius button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) addSubview(border) addSubview(button) let views:[String:UIView] = [ "border":border, "button":button] let metrics:[String:CGFloat] = [ "buttonWidth":kButtonWidth, "buttonRight":kButtonRight] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[border]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[border(1)]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:[button(buttonWidth)]-(buttonRight)-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-6-[button]-5-|", options:[], metrics:metrics, views:views)) } //MARK: actions func actionButton(sender button:UIButton) { controller.send() } }
963479ea6d945f72c910c32c0465d3a6
33.207792
89
0.616932
false
false
false
false
marcelganczak/swift-js-transpiler
refs/heads/master
test/weheartswift/arrays-16.swift
mit
1
var number = 12345 var digits: [Int] = [] while number > 0 { var digit = number % 10 digits = [digit] + digits number /= 10 // 12345 -> 1234 -> 123 -> 12 -> 1 } for digit in digits { print(digit) }
9854dccbaa95ef9fb862d8ce49555e60
14.571429
51
0.552995
false
false
false
false
ZamzamInc/SwiftyPress
refs/heads/main
Sources/SwiftyPress/Preferences/Constants/Services/ConstantsStaticService.swift
mit
1
// // ConstantsStaticService.swift // SwiftyPress // // Created by Basem Emara on 2018-10-03. // Copyright © 2019 Zamzam Inc. All rights reserved. // import Foundation.NSURL import ZamzamCore public struct ConstantsStaticService: ConstantsService { public let isDebug: Bool public let itunesName: String public let itunesID: String public let baseURL: URL public let baseREST: String public let wpREST: String public let email: String public let privacyURL: String public let disclaimerURL: String? public let styleSheet: String public let googleAnalyticsID: String? public let featuredCategoryID: Int public let defaultFetchModifiedLimit: Int public let taxonomies: [String] public let postMetaKeys: [String] public let minLogLevel: LogAPI.Level public init( isDebug: Bool, itunesName: String, itunesID: String, baseURL: URL, baseREST: String, wpREST: String, email: String, privacyURL: String, disclaimerURL: String?, styleSheet: String, googleAnalyticsID: String?, featuredCategoryID: Int, defaultFetchModifiedLimit: Int, taxonomies: [String], postMetaKeys: [String], minLogLevel: LogAPI.Level ) { self.isDebug = isDebug self.itunesName = itunesName self.itunesID = itunesID self.baseURL = baseURL self.baseREST = baseREST self.wpREST = wpREST self.email = email self.privacyURL = privacyURL self.disclaimerURL = disclaimerURL self.styleSheet = styleSheet self.googleAnalyticsID = googleAnalyticsID self.featuredCategoryID = featuredCategoryID self.defaultFetchModifiedLimit = defaultFetchModifiedLimit self.taxonomies = taxonomies self.postMetaKeys = postMetaKeys self.minLogLevel = minLogLevel } }
b3e1cd1bb8b98b1b86412eaf4fba1b35
28.938462
66
0.667523
false
false
false
false
Allow2CEO/browser-ios
refs/heads/development
Client/Frontend/Reader/ReaderModeUtils.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation struct ReaderModeUtils { static let DomainPrefixesToSimplify = ["www.", "mobile.", "m.", "blog."] static func simplifyDomain(_ domain: String) -> String { for prefix in DomainPrefixesToSimplify { if domain.hasPrefix(prefix) { return domain.substring(from: domain.characters.index(domain.startIndex, offsetBy: prefix.characters.count)) } } return domain } static func generateReaderContent(_ readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? { guard let tmplPath = Bundle.main.path(forResource: "Reader", ofType: "html") else { return nil } do { let tmpl = try NSMutableString(contentsOfFile: tmplPath, encoding: String.Encoding.utf8.rawValue) let replacements: [String: String] = ["%READER-STYLE%": initialStyle.encode(), "%READER-DOMAIN%": simplifyDomain(readabilityResult.domain), "%READER-URL%": readabilityResult.url, "%READER-TITLE%": readabilityResult.title, "%READER-CREDITS%": readabilityResult.credits, "%READER-CONTENT%": readabilityResult.content ] for (k,v) in replacements { tmpl.replaceOccurrences(of: k, with: v, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length)) } return tmpl as String } catch _ { return nil } } static func isReaderModeURL(_ url: URL) -> Bool { let scheme = url.scheme, host = url.host, path = url.path return scheme == "http" && host == "localhost" && path == "/reader-mode/page" } static func decodeURL(_ url: URL) -> URL? { if ReaderModeUtils.isReaderModeURL(url) { if let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, queryItems.count == 1 { if let queryItem = queryItems.first, let value = queryItem.value { return URL(string: value) } } } return nil } static func encodeURL(_ url: URL?) -> URL? { let baseReaderModeURL: String = WebServer.sharedInstance.URLForResource("page", module: "reader-mode") if let absoluteString = url?.absoluteString { if let encodedURL = absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) { if let aboutReaderURL = URL(string: "\(baseReaderModeURL)?url=\(encodedURL)") { return aboutReaderURL } } } return nil } }
6327821de6b5e8a24534709cc4bca36b
42.43662
152
0.572957
false
false
false
false
460467069/smzdm
refs/heads/master
什么值得买7.1.1版本/什么值得买(5月12日)/Classes/Main/Extension/UIImageView+ZDM.swift
mit
1
// // UIImageView+ZDM.swift // 什么值得买 // // Created by Wang_ruzhou on 2016/10/15. // Copyright © 2016年 Wang_ruzhou. All rights reserved. // import UIKit import YYWebImage import SDWebImage extension UIImageView{ convenience init(zdm_imageNamed: String) { self.init() self.image = UIImage.init(named: zdm_imageNamed) } func zdm_setImage(urlStr: String?, placeHolder: String?) { guard let urlStr = urlStr else { return } let imageURL = URL.init(string: urlStr) var placeHolderImageStr = "placeholder_dropbox" if let placeHolder = placeHolder { placeHolderImageStr = placeHolder; } sd_setImage(with: imageURL, placeholderImage: UIImage.init(named: placeHolderImageStr)) } func zdm_setAavatarImage(urlStr: String?) { guard let urlStr = urlStr else { return } let imageURL = URL.init(string: urlStr) zdm_setImage(placeholder: #imageLiteral(resourceName: "5_middle_avatar"), imageURL: imageURL, manager: ZZCyclePicHelper.avatarImageManager()) } private func zdm_setImage(placeholder: UIImage?, imageURL: URL?, manager: YYWebImageManager?) { yy_setImage(with: imageURL, placeholder: placeholder, options: .showNetworkActivity, manager: manager, progress: nil, transform: nil, completion: nil) } }
7a2dcd9b76b9872123b33d16a88a4b44
30.081633
99
0.601445
false
false
false
false
Hout/DateInRegion
refs/heads/master
Pod/Classes/DateRegion.swift
mit
1
// // DateRegion.swift // Pods // // Created by Jeroen Houtzager on 09/11/15. // // public class DateRegion: Equatable { /// Calendar to interpret date values. You can alter the calendar to adjust the representation of date to your needs. /// public let calendar: NSCalendar! /// Time zone to interpret date values /// Because the time zone is part of calendar, this is a shortcut to that variable. /// You can alter the time zone to adjust the representation of date to your needs. /// public let timeZone: NSTimeZone! /// Locale to interpret date values /// Because the locale is part of calendar, this is a shortcut to that variable. /// You can alter the locale to adjust the representation of date to your needs. /// public let locale: NSLocale! /// Initialise with a calendar and/or a time zone /// /// - Parameters: /// - calendar: the calendar to work with to assign, default = the current calendar /// - timeZone: the time zone to work with, default is the default time zone /// - locale: the locale to work with, default is the current locale /// - calendarID: the calendar ID to work with to assign, default = the current calendar /// - timeZoneID: the time zone ID to work with, default is the default time zone /// - localeID: the locale ID to work with, default is the current locale /// - region: a region to copy /// /// - Note: parameters higher in the list take precedence over parameters lower in the list. E.g. /// `DateRegion(locale: mylocale, localeID: "en_AU", region)` will copy region and set locale to mylocale, not `en_AU`. /// public init( calendarID: String = "", timeZoneID: String = "", localeID: String = "", calendar aCalendar: NSCalendar? = nil, timeZone aTimeZone: NSTimeZone? = nil, locale aLocale: NSLocale? = nil, region: DateRegion? = nil) { calendar = aCalendar ?? NSCalendar(calendarIdentifier: calendarID) ?? region?.calendar ?? NSCalendar.currentCalendar() timeZone = aTimeZone ?? NSTimeZone(abbreviation: timeZoneID) ?? NSTimeZone(name: timeZoneID) ?? region?.timeZone ?? NSTimeZone.defaultTimeZone() locale = aLocale ?? (localeID != "" ? NSLocale(localeIdentifier: localeID) : nil) ?? region?.locale ?? aCalendar?.locale ?? NSLocale.currentLocale() // Assign calendar fields calendar.timeZone = timeZone calendar.locale = locale } /// Today's date /// /// - Returns: the date of today at midnight (00:00) in the current calendar and default time zone. /// public func today() -> DateInRegion { let components = calendar.components([.Era, .Year, .Month, .Day, .Calendar, .TimeZone], fromDate: NSDate()) let date = calendar.dateFromComponents(components)! return DateInRegion(region: self, date: date) } /// Yesterday's date /// /// - Returns: the date of yesterday at midnight (00:00) in the current calendar and default time zone. /// public func yesterday() -> DateInRegion { return (today() - 1.days)! } /// Tomorrow's date /// /// - Returns: the date of tomorrow at midnight (00:00) in the current calendar and default time zone. /// public func tomorrow() -> DateInRegion { return (today() + 1.days)! } } public func ==(left: DateRegion, right: DateRegion) -> Bool { if left.calendar.calendarIdentifier != right.calendar.calendarIdentifier { return false } if left.timeZone.secondsFromGMT != right.timeZone.secondsFromGMT { return false } if left.locale.localeIdentifier != right.locale.localeIdentifier { return false } return true } extension DateRegion : Hashable { public var hashValue: Int { return calendar.hashValue ^ timeZone.hashValue ^ locale.hashValue } } extension DateRegion : CustomStringConvertible { public var description: String { let timeZoneAbbreviation = timeZone.abbreviation ?? "" return "\(calendar.calendarIdentifier); \(timeZone.name):\(timeZoneAbbreviation); \(locale.localeIdentifier)" } }
7a782abf6539b21b12fbd5662726fdff
36.955752
160
0.643424
false
false
false
false
mactive/rw-courses-note
refs/heads/master
AdvancedSwift3/SwiftBeginningTypesOperations.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit typealias UnsignedInt16 = UInt16 typealias SignedInt16 = Int16 SignedInt16.min SignedInt16.max UnsignedInt16.min UnsignedInt16.max var integer: Int = 100 var decimal: Double = 12.5 var float: Float = 12.01 integer = Int(decimal) var pi = String(Double.pi) let hourlyRate: Double = 19.5 let hoursWorked: Int = 10 let totalCost: Double = hourlyRate * Double(hoursWorked) let actualllyDouble = 3 as Double protocol Multiable { func *(lhs: Self, rhs: Self) -> Self } func MultiplyTwoValue<T: Multiable>(a:T, b:T) -> T { let tempValue: T tempValue = a * b return tempValue } extension Int: Multiable {} extension Double: Multiable {} MultiplyTwoValue(a:10, b:2) MultiplyTwoValue(a: 3.3, b: 4.3) /** * a 决定了 T 是 Int, 但是系统检测 b不是 Int * 所以报错了 */ MultiplyTwoValue(a: 3.1, b: 4.3) //: Concatenation var message = "Hello" + " my name is " let name = "mactive" message += name let exclamationMark: Character = "🐱" let dog = "🐶" print("Character count: \(dog.characters.count)") print("Character unicode count \(dog.unicodeScalars.count)") print("Character utf8 count \(dog.utf8.count)") message += String(exclamationMark) message += dog print(message)
bb7d0f88d0ee20f0178ac4e761d137c8
18.40625
60
0.705314
false
false
false
false
NocturneZX/AEDatabase
refs/heads/dev
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Scan.swift
apache-2.0
8
// // Scan.swift // RxSwift // // Created by Krunoslav Zaher on 6/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ScanSink<ElementType, Accumulate, O: ObserverType where O.E == Accumulate> : Sink<O>, ObserverType { typealias Parent = Scan<ElementType, Accumulate> typealias E = ElementType private let _parent: Parent private var _accumulate: Accumulate init(parent: Parent, observer: O) { _parent = parent _accumulate = parent._seed super.init(observer: observer) } func on(event: Event<ElementType>) { switch event { case .Next(let element): do { _accumulate = try _parent._accumulator(_accumulate, element) forwardOn(.Next(_accumulate)) } catch let error { forwardOn(.Error(error)) dispose() } case .Error(let error): forwardOn(.Error(error)) dispose() case .Completed: forwardOn(.Completed) dispose() } } } class Scan<Element, Accumulate>: Producer<Accumulate> { typealias Accumulator = (Accumulate, Element) throws -> Accumulate private let _source: Observable<Element> private let _seed: Accumulate private let _accumulator: Accumulator init(source: Observable<Element>, seed: Accumulate, accumulator: Accumulator) { _source = source _seed = seed _accumulator = accumulator } override func run<O : ObserverType where O.E == Accumulate>(observer: O) -> Disposable { let sink = ScanSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
b27901c9f5db5b4bb5c181a6cb520bfa
27.234375
106
0.59247
false
false
false
false
ytfhqqu/iCC98
refs/heads/master
iCC98/iCC98/MessageTableViewCell.swift
mit
1
// // MessageTableViewCell.swift // iCC98 // // Created by Duo Xu on 5/20/17. // Copyright © 2017 Duo Xu. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CC98Kit /** 展示短消息信息的单元格。 */ class MessageTableViewCell: UITableViewCell { @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var sendTimeLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! // MARK: - Data /** 设置数据。 - parameter messageInfo: 短消息的信息。 - parameter currentUserName: 当前登录用户的用户名。 */ func setData(messageInfo: MessageInfo, currentUserName: String?) { self.messageInfo = messageInfo self.currentUserName = currentUserName updateUI() } /// 短消息的信息。 private var messageInfo: MessageInfo? /// 当前登录用户的用户名。 private var currentUserName: String? // MARK: - UI // 更新 UI private func updateUI() { if let messageInfo = messageInfo { // 用户名 if currentUserName == messageInfo.receiverName { userNameLabel?.text = messageInfo.senderName ?? "系统" } else { userNameLabel?.text = "➞ " + (messageInfo.receiverName ?? "未知用户") } // 发送时间 let currentTimeDateComponents = Calendar.current.dateComponents([.day, .month, .year], from: Date()) if let sendTime = messageInfo.sendTime { let sendTimeDateComponents = Calendar.current.dateComponents([.day, .month, .year], from: sendTime) let isSameDay = (sendTimeDateComponents.day == currentTimeDateComponents.day) && (sendTimeDateComponents.month == currentTimeDateComponents.month) && (sendTimeDateComponents.year == currentTimeDateComponents.year) let formatter = DateFormatter() if isSameDay { formatter.dateFormat = "H:mm" } else if sendTimeDateComponents.year == currentTimeDateComponents.year { formatter.dateFormat = "M/d" } else { formatter.dateFormat = "yyyy/M/d" } formatter.timeZone = TimeZone(secondsFromGMT: 8 * 60 * 60) sendTimeLabel?.text = formatter.string(from: sendTime) } // 标题 titleLabel?.text = messageInfo.title // 内容,展示时把回车替换为空格 contentLabel?.text = (messageInfo.content ?? "").replacingOccurrences(of: "\n", with: " ") } } }
ce9e9b12f8d7c74ba216840574bda80a
37.726316
115
0.624354
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/core/Repeat.swift
apache-2.0
2
//===--- Repeat.swift - A Collection that repeats a value N times ---------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection whose elements are all identical. /// /// You create an instance of the `Repeated` collection by calling the /// `repeatElement(_:count:)` function. The following example creates a /// collection containing the name "Humperdinck" repeated five times: /// /// let repeatedName = repeatElement("Humperdinck", count: 5) /// for name in repeatedName { /// print(name) /// } /// // "Humperdinck" /// // "Humperdinck" /// // "Humperdinck" /// // "Humperdinck" /// // "Humperdinck" @_fixed_layout public struct Repeated<Element> { /// The number of elements in this collection. public let count: Int /// The value of every element in this collection. public let repeatedValue: Element } extension Repeated: RandomAccessCollection { public typealias Indices = Range<Int> /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a "past the /// end" position that's not valid for use as a subscript. public typealias Index = Int /// Creates an instance that contains `count` elements having the /// value `repeatedValue`. @inlinable internal init(_repeating repeatedValue: Element, count: Int) { _precondition(count >= 0, "Repetition count should be non-negative") self.count = count self.repeatedValue = repeatedValue } /// The position of the first element in a nonempty collection. /// /// In a `Repeated` collection, `startIndex` is always equal to zero. If the /// collection is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Index { return 0 } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In a `Repeated` collection, `endIndex` is always equal to `count`. If the /// collection is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Index { return count } /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. @inlinable public subscript(position: Int) -> Element { _precondition(position >= 0 && position < count, "Index out of range") return repeatedValue } } /// Creates a collection containing the specified number of the given element. /// /// The following example creates a `Repeated<Int>` collection containing five /// zeroes: /// /// let zeroes = repeatElement(0, count: 5) /// for x in zeroes { /// print(x) /// } /// // 0 /// // 0 /// // 0 /// // 0 /// // 0 /// /// - Parameters: /// - element: The element to repeat. /// - count: The number of times to repeat `element`. /// - Returns: A collection that contains `count` elements that are all /// `element`. @inlinable public func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> { return Repeated(_repeating: element, count: n) }
66472584268ab93c9f5a882e8f88577a
32.330275
80
0.650427
false
false
false
false
googleprojectzero/fuzzilli
refs/heads/main
Sources/Fuzzilli/Base/Events.swift
apache-2.0
1
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation // Event dispatching implementation. public class Event<T> { public typealias EventListener = (T) -> Void /// The list of observers for this event. private(set) public var listeners = [EventListener]() /// Registers an event listener for this event. public func addListener(_ listener: @escaping EventListener) { listeners.append(listener) } } /// List of all events that can be dispatched in a fuzzer. public class Events { /// Signals that the fuzzer is fully initialized. public let Initialized = Event<Void>() /// Signals that a this instance is shutting down. public let Shutdown = Event<ShutdownReason>() /// Signals that this instance has successfully shut down. /// Clients are expected to terminate the hosting process when handling this event. public let ShutdownComplete = Event<ShutdownReason>() /// Signals that a log message was dispatched. /// The origin field contains the UUID of the fuzzer instance that originally logged the message. public let Log = Event<(origin: UUID, level: LogLevel, label: String, message: String)>() /// Signals that a new (mutated) program has been generated. public let ProgramGenerated = Event<Program>() /// Signals that a valid program has been found. public let ValidProgramFound = Event<Program>() /// Signals that an invalid program has been found. public let InvalidProgramFound = Event<Program>() /// Signals that a crashing program has been found. Dispatched after the crashing program has been minimized. public let CrashFound = Event<(program: Program, behaviour: CrashBehaviour, isUnique: Bool, origin: ProgramOrigin)>() /// Signals that a program causing a timeout has been found. public let TimeOutFound = Event<Program>() /// Signals that a new interesting program has been found, after the program has been minimized. public let InterestingProgramFound = Event<(program: Program, origin: ProgramOrigin)>() /// Signals a diagnostics event public let DiagnosticsEvent = Event<(name: String, content: String)>() /// Signals that a program is about to be executed. public let PreExecute = Event<Program>() /// Signals that a program was executed. public let PostExecute = Event<Execution>() /// Signals that a worker has connected to this master instance. public let WorkerConnected = Event<UUID>() /// Signals that a worker has disconnected. public let WorkerDisconnected = Event<UUID>() } /// Crash behavior of a program. public enum CrashBehaviour: String { case deterministic = "deterministic" case flaky = "flaky" } /// Reasons for shutting down a fuzzer instance. public enum ShutdownReason: CustomStringConvertible { case userInitiated case finished case fatalError case masterShutdown public var description: String { switch self { case .userInitiated: return "user initiated stop" case .finished: return "maximum number of iterations reached" case .fatalError: return "fatal error" case .masterShutdown: return "master shutting down" } } public func toExitCode() -> Int32 { switch self { case .userInitiated, .finished, .masterShutdown: return 0 case .fatalError: return -1 } } }
7593860821f73a6b5d247e6c0e5f477c
34.359649
121
0.693128
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Display information/Read symbols from a mobile style/ReadSymbolsFromMobileStyleViewController.swift
apache-2.0
1
// // Copyright © 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import ArcGIS /// A view controller that manages the interface of the Read Symbols from a /// Mobile Style sample. class ReadSymbolsFromMobileStyleViewController: UIViewController { /// The map view managed by the view controller. @IBOutlet weak var mapView: AGSMapView! { didSet { mapView.map = AGSMap(basemapStyle: .arcGISTopographic) mapView.graphicsOverlays.add(AGSGraphicsOverlay()) mapView.touchDelegate = self } } /// The view controller that manages the symbol to be added when the map /// view is tapped. let symbolViewController = UIStoryboard(name: "ReadSymbolsFromMobileStyle", bundle: nil).instantiateViewController(withIdentifier: "SymbolViewController") as! ReadSymbolsFromMobileStyleSymbolViewController /// Shows the symbol view controller. @IBAction func showSymbol() { let navigationController = UINavigationController(rootViewController: symbolViewController) navigationController.modalPresentationStyle = .formSheet present(navigationController, animated: true) } /// Removes all the graphics from the map view. @IBAction func removeAllGraphics() { (mapView.graphicsOverlays.firstObject as? AGSGraphicsOverlay)?.graphics.removeAllObjects() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [ "ReadSymbolsFromMobileStyleViewController", "ReadSymbolsFromMobileStyleSymbolViewController", "ReadSymbolsFromMobileStyleSymbolSettingsViewController" ] } } extension ReadSymbolsFromMobileStyleViewController: AGSGeoViewTouchDelegate { func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { guard let symbol = symbolViewController.symbol else { return } let graphic = AGSGraphic(geometry: mapPoint, symbol: symbol) (mapView.graphicsOverlays.firstObject as? AGSGraphicsOverlay)?.graphics.add(graphic) } }
42d26677efe79f347478e3bc8744839b
40.397059
209
0.722202
false
false
false
false
madewithray/ray-broadcast
refs/heads/master
RayBroadcast/AdvertiseViewController.swift
mit
1
// // AdvertiseViewController.swift // RayBroadcast // // Created by Sean Ooi on 7/3/15. // Copyright (c) 2015 Yella Inc. All rights reserved. // import UIKit import CoreLocation import CoreBluetooth class AdvertiseViewController: UIViewController { @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var majorLabel: UILabel! @IBOutlet weak var minorLabel: UILabel! @IBOutlet weak var regionLabel: UILabel! @IBOutlet weak var majorValueLabel: UILabel! @IBOutlet weak var minorValueLabel: UILabel! @IBOutlet weak var regionValueLabel: UILabel! @IBOutlet weak var dotImageView: UIImageView! var beacon: [String: AnyObject]? var pulseEffect: LFTPulseAnimation! = nil var peripheralManager: CBPeripheralManager! = nil var peripheralState = "Unknown" override func viewDidLoad() { super.viewDidLoad() title = "Advertise" descriptionLabel.text = "Advertising beacon data:" majorLabel.text = "Major:" majorLabel.font = UIFont.boldSystemFontOfSize(16) minorLabel.text = "Minor:" minorLabel.font = UIFont.boldSystemFontOfSize(16) regionLabel.text = "Region:" regionLabel.font = UIFont.boldSystemFontOfSize(16) if let beacon = beacon { majorValueLabel.text = String(beacon["major"] as? Int ?? 0) minorValueLabel.text = String(beacon["minor"] as? Int ?? 0) regionValueLabel.text = beacon["identifier"] as? String ?? "No Identifier" } dotImageView.contentMode = .ScaleAspectFit dotImageView.image = UIImage(named: "Dot") peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) advertise() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) peripheralManager.stopAdvertising() } deinit { peripheralManager = nil if pulseEffect != nil { pulseEffect.removeFromSuperlayer() pulseEffect = nil } println("deinit") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func advertise() { if peripheralManager.state == .PoweredOn { if peripheralManager.isAdvertising { peripheralManager.stopAdvertising() if pulseEffect != nil { pulseEffect.removeFromSuperlayer() pulseEffect = nil } } else { if let beacon = beacon, uuid = beacon["uuid"] as? String, major = beacon["major"] as? Int, minor = beacon["minor"] as? Int, identifier = beacon["identifier"] as? String { let beaconRegion = CLBeaconRegion( proximityUUID: NSUUID(UUIDString: uuid), major: UInt16(major), minor: UInt16(minor), identifier: identifier) let manufacturerData = identifier.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) var beaconData = beaconRegion.peripheralDataWithMeasuredPower(1) as [NSObject : AnyObject] beaconData[CBAdvertisementDataLocalNameKey] = "Ray Beacon" beaconData[CBAdvertisementDataTxPowerLevelKey] = -12 beaconData[CBAdvertisementDataManufacturerDataKey] = manufacturerData beaconData[CBAdvertisementDataServiceUUIDsKey] = [CBUUID(NSUUID: NSUUID(UUIDString: uuid))] peripheralManager.startAdvertising(beaconData) if pulseEffect == nil { pulseEffect = LFTPulseAnimation(repeatCount: Float.infinity, radius: 100, position: dotImageView.center) view.layer.insertSublayer(pulseEffect, below: dotImageView.layer) } } } } else { let alertController = UIAlertController(title: "Bluetooth Error", message: peripheralState, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Cancel, handler: {[unowned self] (action) -> Void in if let navigationController = self.navigationController { navigationController.popViewControllerAnimated(true) } }) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) } } }
57ffcc3b3d3d1239670f0d98ffc68324
35.507246
128
0.577809
false
false
false
false
piscoTech/GymTracker
refs/heads/master
Gym Tracker watchOS Extension/WorkoutDetailIC.swift
mit
1
// // WorkoutDetailInterfaceController.swift // Gym Tracker // // Created by Marco Boschi on 23/03/2017. // Copyright © 2017 Marco Boschi. All rights reserved. // import WatchKit import Foundation import GymTrackerCore struct WorkoutDetailData { let listController: WorkoutListInterfaceController? let workout: GTWorkout } class WorkoutDetailInterfaceController: WKInterfaceController { @IBOutlet weak var workoutName: WKInterfaceLabel! @IBOutlet weak var table: WKInterfaceTable! @IBOutlet weak var startBtn: WKInterfaceButton! private var workout: GTWorkout! private var delegate: WorkoutListInterfaceController? private var choices: [GTChoice: Int32]? override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. guard let data = context as? WorkoutDetailData else { fatalError("Inconsistent loading") } workout = data.workout delegate = data.listController delegate?.workoutDetail = self if delegate == nil { startBtn.setEnabled(false) startBtn.setHidden(true) appDelegate.executeWorkoutDetail = self } reloadData(checkExistence: false) updateButton() } func reloadData(checkExistence: Bool = true, choices: [GTChoice: Int32]? = nil, withController ctrl: ExecuteWorkoutController? = nil) { if checkExistence { guard workout.stillExists(inDataManager: appDelegate.dataManager), !workout.archived else { if delegate != nil { // If delegate is not set this is displayed as a page during a workout, so just do nothing self.pop() } return } } self.choices = choices workoutName.setText(workout.name) let exercises = workout.exerciseList let exCell = "exercise" let rows = exercises.flatMap { p -> [(GTPart, String)] in if let r = p as? GTRest { return [(r, "rest")] } else if let e = p as? GTSimpleSetsExercise { return [(e, exCell)] } else if let c = p as? GTCircuit { return c.exerciseList.map { ($0, exCell) } } else if let ch = p as? GTChoice { return [(ch, exCell)] } else { fatalError("Unknown part type") } }.map { p -> (GTPart, String) in if let ch = p.0 as? GTChoice, let i = choices?[ch], let e = ch[i] { return (e, exCell) } else { return p } } table.setRowTypes(rows.map { $0.1 }) for (i, (p, _)) in zip(0 ..< rows.count, rows) { if let r = p as? GTRest { let row = table.rowController(at: i) as! RestCell row.set(rest: r.rest) } else if let se = p as? GTSetsExercise { let row = table.rowController(at: i) as! ExerciseCell if let curWrkt = ctrl { row.detailLabel.setAttributedText(se.summaryWithSecondaryInfoChange(from: curWrkt)) } else { row.detailLabel.setText(se.summary) } row.accessoryWidth = 21 row.showAccessory(false) if let e = se as? GTSimpleSetsExercise { row.set(title: e.title) } else if let ch = se as? GTChoice { row.setChoice(title: ch.title, total: ch.exercises.count) } else { fatalError("Unknown part type") } if let (n, t) = se.circuitStatus { row.setCircuit(number: n, total: t) } } else { fatalError("Unknown part type") } } } func reloadDetails(from ctrl: ExecuteWorkoutController) { reloadData(checkExistence: false, choices: self.choices, withController: ctrl) } 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() } func updateButton() { startBtn.setEnabled(delegate?.canEdit ?? false) } @IBAction func startWorkout() { guard delegate?.canEdit ?? false, appDelegate.dataManager.preferences.runningWorkout == nil else { return } appDelegate.startWorkout(with: ExecuteWorkoutData(workout: workout, resume: false)) } }
71a7a54a64735fd325cf8c50d2b5eb99
26.455782
136
0.674678
false
false
false
false
programersun/HiChongSwift
refs/heads/master
HiChongSwift/FindChooseAgeViewController.swift
apache-2.0
1
// // FindChooseAgeViewController.swift // HiChongSwift // // Created by eagle on 15/1/12. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit protocol FindChooseAgeDelegate: class { func chooseAgeDone(#from: Int, to: Int) } class FindChooseAgeViewController: UIViewController { weak var delegate: FindChooseAgeDelegate? @IBOutlet private weak var icyPickerView: UIPickerView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. addRightButton("确定", action: "doneButtonPressed:") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions func doneButtonPressed(sender: AnyObject) { if let delegate = delegate { let from = icyPickerView.selectedRowInComponent(0) let to = icyPickerView.selectedRowInComponent(2) >= from ? icyPickerView.selectedRowInComponent(2) : from delegate.chooseAgeDone(from: from, to: to) } navigationController?.popViewControllerAnimated(true) } /* // 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. } */ } extension FindChooseAgeViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 3 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return 12 case 1: return 1 case 2: return 12 default: return 0 } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { if component == 1 { return "~" } else { if row == 11 { return "大于10岁" } else if row == 0 { return "小于1岁" } else { return "\(row)岁" } } } func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { let screenWidth = UIScreen.mainScreen().bounds.width if component == 1 { return screenWidth / 5.0 } else { return screenWidth / 5.0 * 2.0 } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 2 { let row1 = pickerView.selectedRowInComponent(0) if row < row1 { pickerView.selectRow(row1, inComponent: 2, animated: true) } } else if component == 0 { let row2 = pickerView.selectedRowInComponent(2) if row2 < row { pickerView.selectRow(row, inComponent: 2, animated: true) } } } }
74c1acfca76d81405f77e00fd8a52b07
29.783019
117
0.604965
false
false
false
false
haikieu/iOS-ViewController-Presentation-Sample
refs/heads/master
PresentAndWindow/PresentAndWindow/UIViewController+Extensions.swift
mit
1
// // UIViewController+Extensions.swift // PresentAndWindow // // Created by Kieu, Hai N on 4/11/17. // Copyright © 2017 Hai Kieu. All rights reserved. // import Foundation import UIKit public extension UIModalPresentationStyle { public var stringValue : String { switch self { case .fullScreen: return "fullScreen" case .pageSheet: return "pageSheet" case .formSheet: return "formSheet" case .currentContext: return "currentContext" case .custom: return "custom" case .overFullScreen: return "overFullScreen" case .overCurrentContext: return "overCurrentContext" case .popover: return "popover" case .none: fallthrough default: return "none" } } } public extension UIViewController { public func alert(withTitle title: String, message: String? = nil, completion: (()->Void)? = nil ) { let alertVC = UIAlertController.init(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction.init(title: "Cancel", style: .default) { (UIAlertAction) in //Dummy clossure, temporarily do nothing } alertVC.addAction(action) self.present(alertVC, animated: true) { //Do anything after presetion if let completion = completion { completion() } } } //This tell us if the vc is presented by any view controller public var isPresented : Bool { return self.presentingViewController != nil } ///This tell us if the vc is presenting any view controller public var isPresenting : Bool { return self.presentedViewController != nil } //This tell us if the vc is presented as well as presenting any view controller public var isPresentedAndPresenting : Bool { return isPresented && isPresenting } public var currentPresentLevel : Int { if let presentingViewController = self.presentingViewController { return 1 + presentingViewController.currentPresentLevel } else { return 0 } } public var totalPresentLevel : Int { return currentPresentLevel + abovePresentLevel } private var abovePresentLevel : Int { if let presentedViewController = self.presentedViewController { return 1 + presentedViewController.abovePresentLevel } else { return 0 } } }
439dc5831a0810a81126041da658ca38
28.244444
104
0.603343
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/Mixpanel-swift/Mixpanel/ObjectIdentityProvider.swift
mit
1
// // ObjectIdentityProvider.swift // Mixpanel // // Created by Yarden Eitan on 8/29/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation class ObjectIdentityProvider { let objectToIdentifierMap: NSMapTable<AnyObject, NSString> let sequenceGenerator = SequenceGenerator() init() { objectToIdentifierMap = NSMapTable(keyOptions: .weakMemory, valueOptions: .strongMemory) } func getIdentifier(for object: AnyObject) -> String { if let object = object as? String { return object } if let identifier = objectToIdentifierMap.object(forKey: object) { return identifier as String } else { let identifier = "$\(sequenceGenerator.next())" as NSString objectToIdentifierMap.setObject(identifier, forKey: object) return identifier as String } } } class SequenceGenerator { private var queue = DispatchQueue(label: "com.mixpanel.sequence.generator") private(set) var value: Int32 = 0 init() { value = 0 } func next() -> Int32 { queue.sync { value += 1 } return value; } }
f47915ae009972623896e223f9d68f2f
23.571429
96
0.619601
false
false
false
false
exoplatform/exo-ios
refs/heads/acceptance
eXo/Sources/Utils/Extensions/StringExtension.swift
lgpl-3.0
1
// // StringExtension.swift // eXo // // Created by Paweł Walczak on 29.01.2018. // Copyright © 2018 eXo. All rights reserved. // import Foundation extension String { func isBlankOrEmpty() -> Bool { // Check empty string if self.isEmpty { return true } // Trim and check empty string return (self.trimmingCharacters(in: .whitespaces) == "") } var localized: String { return NSLocalizedString(self, comment: "") } /* Return the serverURL with protocol & port (if need) example: serverURL = http://localhost:8080/portal/intranet -> full domain with protocol & port = http://localhost:8080 */ var serverDomainWithProtocolAndPort: String? { guard let url = URL(string: self), let scheme = url.scheme, let host = url.host else { return nil } var fullDomain = scheme + "://" + host if let port = url.port { fullDomain += ":\(port)" } return fullDomain } }
6c4eda1ba9ca226e894ff40e59ed128c
25.948718
107
0.573739
false
false
false
false
nodes-ios/Serializable
refs/heads/master
Serpent/Example/SerpentExample/Classes/Models/ProfilePicture.swift
mit
2
// // ProfilePicture.swift // SerpentExample // // Created by Dominik Hádl on 17/04/16. // Copyright © 2016 Nodes ApS. All rights reserved. // import Serpent struct ProfilePicture { var thumbnail: URL? var medium: URL? var large: URL? } extension ProfilePicture: Serializable { init(dictionary: NSDictionary?) { thumbnail <== (self, dictionary, "thumbnail") medium <== (self, dictionary, "medium") large <== (self, dictionary, "large") } func encodableRepresentation() -> NSCoding { let dict = NSMutableDictionary() (dict, "thumbnail") <== thumbnail (dict, "medium") <== medium (dict, "large") <== large return dict } }
8e56b7e43251c488e1715321f4c84bae
22.806452
53
0.590786
false
false
false
false
DarthMike/YapDatabaseExtensions
refs/heads/master
examples/iOS/YapDBExtensionsMobile/Models.swift
mit
2
// // Models.swift // YapDBExtensionsMobile // // Created by Daniel Thorpe on 15/04/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation import YapDatabase import YapDatabaseExtensions public enum Barcode: Equatable { case UPCA(Int, Int, Int, Int) case QRCode(String) } public struct Product: Identifiable, Equatable { public struct Category: Identifiable { public let identifier: Int let name: String } public struct Metadata: Equatable { let categoryIdentifier: Int public init(categoryIdentifier: Int) { self.categoryIdentifier = categoryIdentifier } } public let metadata: Metadata public let identifier: Identifier internal let name: String internal let barcode: Barcode public init(metadata: Metadata, identifier: Identifier, name: String, barcode: Barcode) { self.metadata = metadata self.identifier = identifier self.name = name self.barcode = barcode } } public class Person: NSObject, NSCoding, Equatable { public let identifier: Identifier public let name: String public init(id: String, name n: String) { identifier = id name = n } public required init(coder aDecoder: NSCoder) { identifier = aDecoder.decodeObjectForKey("identifier") as! Identifier name = aDecoder.decodeObjectForKey("name") as! String } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(identifier, forKey: "identifier") aCoder.encodeObject(name, forKey: "name") } } // MARK: - Hashable etc extension Barcode: Hashable { public var hashValue: Int { return identifier } } public func == (a: Barcode, b: Barcode) -> Bool { switch (a, b) { case let (.UPCA(aNS, aM, aP, aC), .UPCA(bNS, bM, bP, bC)): return (aNS == bNS) && (aM == bM) && (aP == bP) && (aC == bC) case let (.QRCode(aCode), .QRCode(bCode)): return aCode == bCode default: return false } } public func == (a: Product, b: Product) -> Bool { return a.identifier == b.identifier } public func == (a: Product.Metadata, b: Product.Metadata) -> Bool { return a.categoryIdentifier == b.categoryIdentifier } public func == (a: Person, b: Person) -> Bool { return (a.identifier == b.identifier) && (a.name == b.name) } extension Person: Printable { public override var description: String { return "id: \(identifier), name: \(name)" } } // MARK: - Persistable extension Barcode: Persistable { public static var collection: String { return "Barcodes" } public var identifier: Int { switch self { case let .UPCA(numberSystem, manufacturer, product, check): return "\(numberSystem).\(manufacturer).\(product).\(check)".hashValue case let .QRCode(code): return code.hashValue } } } extension Product.Category: Persistable { public static var collection: String { return "Categories" } } extension Product: ValueMetadataPersistable { public static var collection: String { return "Products" } } extension Person: Persistable { public static var collection: String { return "People" } } // MARK: - Saveable extension Barcode: Saveable { public typealias Archive = BarcodeArchiver enum Kind: Int { case UPCA = 1, QRCode } public var archive: Archive { return Archive(self) } var kind: Kind { switch self { case UPCA(_): return Kind.UPCA case QRCode(_): return Kind.QRCode } } } extension Product.Category: Saveable { public typealias Archive = ProductCategoryArchiver public var archive: Archive { return Archive(self) } } extension Product.Metadata: Saveable { public typealias Archive = ProductMetadataArchiver public var archive: Archive { return Archive(self) } } extension Product: Saveable { public typealias Archive = ProductArchiver public var archive: Archive { return Archive(self) } } // MARK: - Archivers public class BarcodeArchiver: NSObject, NSCoding, Archiver { public let value: Barcode public required init(_ v: Barcode) { value = v } public required init(coder aDecoder: NSCoder) { if let kind = Barcode.Kind(rawValue: aDecoder.decodeIntegerForKey("kind")) { switch kind { case .UPCA: let numberSystem = aDecoder.decodeIntegerForKey("numberSystem") let manufacturer = aDecoder.decodeIntegerForKey("manufacturer") let product = aDecoder.decodeIntegerForKey("product") let check = aDecoder.decodeIntegerForKey("check") value = .UPCA(numberSystem, manufacturer, product, check) case .QRCode: let code = aDecoder.decodeObjectForKey("code") as! String value = .QRCode(code) } } else { preconditionFailure("Barcode.Kind not correctly encoded.") } } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(value.kind.rawValue, forKey: "kind") switch value { case let .UPCA(numberSystem, manufacturer, product, check): aCoder.encodeInteger(numberSystem, forKey: "numberSystem") aCoder.encodeInteger(manufacturer, forKey: "manufacturer") aCoder.encodeInteger(product, forKey: "product") aCoder.encodeInteger(check, forKey: "check") case let .QRCode(code): aCoder.encodeObject(code, forKey: "code") } } } public class ProductCategoryArchiver: NSObject, NSCoding, Archiver { public let value: Product.Category public required init(_ v: Product.Category) { value = v } public required init(coder aDecoder: NSCoder) { let identifier = aDecoder.decodeIntegerForKey("identifier") let name = aDecoder.decodeObjectForKey("name") as? String value = Product.Category(identifier: identifier, name: name!) } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(value.identifier, forKey: "identifier") aCoder.encodeObject(value.name, forKey: "name") } } public class ProductMetadataArchiver: NSObject, NSCoding, Archiver { public let value: Product.Metadata public required init(_ v: Product.Metadata) { value = v } public required init(coder aDecoder: NSCoder) { let categoryIdentifier = aDecoder.decodeIntegerForKey("categoryIdentifier") value = Product.Metadata(categoryIdentifier: categoryIdentifier) } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(value.categoryIdentifier, forKey: "categoryIdentifier") } } public class ProductArchiver: NSObject, NSCoding, Archiver { public let value: Product public required init(_ v: Product) { value = v } public required init(coder aDecoder: NSCoder) { let metadata: Product.Metadata? = valueFromArchive(aDecoder.decodeObjectForKey("metadata")) let identifier = aDecoder.decodeObjectForKey("identifier") as! String let name = aDecoder.decodeObjectForKey("name") as! String let barcode: Barcode? = valueFromArchive(aDecoder.decodeObjectForKey("barcode")) value = Product(metadata: metadata!, identifier: identifier, name: name, barcode: barcode!) } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(archiveFromValue(value.metadata), forKey: "metadata") aCoder.encodeObject(value.identifier, forKey: "identifier") aCoder.encodeObject(value.name, forKey: "name") aCoder.encodeObject(archiveFromValue(value.barcode), forKey: "barcode") } } // MARK: - Database Views public func products() -> YapDB.Fetch { let grouping: YapDB.View.Grouping = .ByMetadata({ (collection, key, metadata) -> String! in if collection == Product.collection { if let metadata: Product.Metadata = valueFromArchive(metadata) { return "category: \(metadata.categoryIdentifier)" } } return nil }) let sorting: YapDB.View.Sorting = .ByObject({ (group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in if let product1: Product = valueFromArchive(object1) { if let product2: Product = valueFromArchive(object2) { return product1.name.caseInsensitiveCompare(product2.name) } } return .OrderedSame }) let view = YapDB.View( name: "Products grouped by category", grouping: grouping, sorting: sorting, collections: [Product.collection]) return .View(view) }
2f0a2a3cde962a7ac55ba1888937ed1e
26.552469
138
0.644001
false
false
false
false
storehouse/Advance
refs/heads/master
Samples/SampleApp-iOS/Sources/SpringsViewController.swift
bsd-2-clause
1
import Foundation import UIKit import Advance class SpringsViewController: DemoViewController { private let springView: SpringView private let spring: Spring<CGPoint> private let configView = SpringConfigurationView() private let tapRecognizer = UITapGestureRecognizer() required init() { springView = SpringView() spring = Spring(initialValue: springView.center) super.init(nibName: nil, bundle: nil) spring.onChange = { [weak self] point in self?.springView.center = point } title = "Spring" note = "Tap anywhere to move the dot using a spring." } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white view.addGestureRecognizer(tapRecognizer) tapRecognizer.addTarget(self, action: #selector(tap(_:))) tapRecognizer.isEnabled = false springView.bounds = CGRect(x: 0.0, y: 0.0, width: 24.0, height: 24.0) configView.delegate = self configView.alpha = 0.0 contentView.addSubview(springView) contentView.addSubview(configView) updateSprings() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var configFrame = CGRect.zero configFrame.size.width = view.bounds.width configFrame.size.height = configView.sizeThatFits(view.bounds.size).height configFrame.origin.y = view.bounds.maxY - configFrame.height - view.safeAreaInsets.bottom configView.frame = configFrame } @objc dynamic func tap(_ recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: view) spring.target = point } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) spring.reset(to: CGPoint(x: view.bounds.midX, y: view.bounds.midY)) } fileprivate func updateSprings() { spring.tension = Double(configView.tension) spring.damping = Double(configView.damping) } override func didEnterFullScreen() { super.didEnterFullScreen() configView.alpha = 1.0 tapRecognizer.isEnabled = true } override func didLeaveFullScreen() { super.didLeaveFullScreen() configView.alpha = 0.0 spring.target = CGPoint(x: contentView.bounds.midX, y: contentView.bounds.midY) tapRecognizer.isEnabled = false } } extension SpringsViewController: SpringConfigurationViewDelegate { func springConfigurationViewDidChange(_ view: SpringConfigurationView) { updateSprings() } }
898a103fa4a79671aeb4fd18e15be3ce
29.136842
97
0.63919
false
true
false
false
nitrado/NitrAPI-Swift
refs/heads/master
Pod/Classes/services/gameservers/taskmanager/TaskManager.swift
mit
1
import ObjectMapper open class TaskManager { fileprivate var nitrapi: Nitrapi! /// service id fileprivate var id: Int! // MARK: - Initialization public required init(id: Int, nitrapi: Nitrapi) { self.id = id self.nitrapi = nitrapi } // MARK: - Getters open func getScheduledTasks() throws -> [Task]? { let data = try nitrapi.client.dataPost("services/\(id as Int)/tasks", parameters: [:]) return Mapper<Task>().mapArray(JSONArray: data?["tasks"] as! [[String : Any]]) } // MARK: - Actions /// Creates a new scheduled task for the service. /// - parameter minute: Minutes in cron format /// - parameter hour: Hours in cron format /// - parameter day: Days in cron format /// - parameter month: Months in cron format /// - parameter weekday: Weekdays in cron format /// - parameter method: Type of action to be run /// - parameter message: Optional message for restart or stop open func createTask(_ minute: String, hour: String, day: String, month: String, weekday: String, method: Task.ActionType, message: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/tasks", parameters: [ "minute": minute, "hour": hour, "day": day, "month": month, "weekday": weekday, "action_method": method.value, "action_data": message ]) } /// Updates an existing scheduled task for the service. /// - parameter id: id of the existing scheduled task /// - parameter minute: Minutes in cron format /// - parameter hour: Hours in cron format /// - parameter day: Days in cron format /// - parameter month: Months in cron format /// - parameter weekday: Weekdays in cron format /// - parameter method: Type of action to be run /// - parameter message: Optional message for restart or stop open func createTask(_ taskId: Int, minute: String, hour: String, day: String, month: String, weekday: String, method: Task.ActionType, message: String) throws { _ = try nitrapi.client.dataPost("services/\(id as Int)/tasks/\(taskId)", parameters: [ "minute": minute, "hour": hour, "day": day, "month": month, "weekday": weekday, "action_method": method.value, "action_data": message ]) } open func deleteTask(_ taskId: Int) throws { _ = try nitrapi.client.dataDelete("services/\(id as Int)/tasks/\(taskId)", parameters: [:]) } }
fd3a187d633b2faf6be3f9a63da22cda
40.089552
165
0.569924
false
false
false
false
hulinSun/MyRx
refs/heads/master
MyRx/Pods/Moya/Source/Target.swift
apache-2.0
2
import Foundation import Alamofire /// Protocol to define the base URL, path, method, parameters and sample data for a target. public protocol TargetType { var baseURL: URL { get } var path: String { get } var method: Moya.Method { get } var parameters: [String: Any]? { get } var sampleData: Data { get } var task: Task { get } var validate: Bool { get } // Alamofire validation (defaults to `false`) } public extension TargetType { var validate: Bool { return false } } /// Represents an HTTP method. public typealias Method = Alamofire.HTTPMethod extension Method { public var supportsMultipart: Bool { switch self { case .post, .put, .patch, .connect: return true default: return false } } } public enum StubBehavior { case never case immediate case delayed(seconds: TimeInterval) } public enum UploadType { case file(URL) case multipart([MultipartFormData]) } public enum DownloadType { case request(DownloadDestination) } public enum Task { case request case upload(UploadType) case download(DownloadType) } public struct MultipartFormData { public enum FormDataProvider { case data(Foundation.Data) case file(URL) case stream(InputStream, UInt64) } public init(provider: FormDataProvider, name: String, fileName: String? = nil, mimeType: String? = nil) { self.provider = provider self.name = name self.fileName = fileName self.mimeType = mimeType } public let provider: FormDataProvider public let name: String public let fileName: String? public let mimeType: String? }
6c74de89d501931c6aabdb58e8f19ac8
21.857143
109
0.640341
false
false
false
false
rmavani/SocialQP
refs/heads/master
QPrint/Controllers/SideMenu/BaseViewController.swift
mit
1
// // BaseViewController.swift // QPrint // // Created by Admin on 23/02/17. // Copyright © 2017 Admin. All rights reserved. // import Foundation import UIKit class BaseViewController: UIViewController, UIAlertViewDelegate { @IBOutlet var menuView : UIView! var view1: SideMenu! var isMenuView : Bool = false override func viewDidLoad() { super.viewDidLoad() self.view1 = SideMenu(nibName: "SideMenu", bundle: nil) self.view1.view.backgroundColor = UIColor.clear view1.delegate = self view1.view.frame = CGRect(x : -self.view.frame.width, y : 0, width : self.view.frame.width, height : self.view.frame.height ) // view1.view.layer.shadowColor = UIColor.black.cgColor // view1.view.layer.shadowOpacity = 0.5 // view1.view.layer.shadowRadius = 10 // let path = UIBezierPath(rect : CGRect(x:view1.view.frame.width - 80.0,y: 0,width: 20,height: view1.view.frame.height)) // view1.view.layer.shadowPath = path.cgPath let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(BaseViewController.respondToSwipeGesture1(gesture:))) swipeLeft.direction = UISwipeGestureRecognizerDirection.left self.view1.view.addGestureRecognizer(swipeLeft) //let tapGesture = UITapGestureRecognizer(target: self, action: #selector(BaseViewController.respondToTapGesture1(gesture:))) //self.view1.view.addGestureRecognizer(tapGesture) } func respondToTapGesture1(gesture: UITapGestureRecognizer) { if isMenuView { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = false self.view1.view.frame = CGRect(x : -self.view.frame.width, y : 0,width : self.view.frame.width, height :self.view.frame.height ) }) { (finished) in self.view1.view.removeFromSuperview() } } } func respondToSwipeGesture1(gesture: UIGestureRecognizer) { if let swipeGesture = gesture as? UISwipeGestureRecognizer { switch swipeGesture.direction { case UISwipeGestureRecognizerDirection.right: print("Swiped Right") self.SwipeShowView(sender: nil) case UISwipeGestureRecognizerDirection.down: print("Swiped down") case UISwipeGestureRecognizerDirection.left: print("Swiped left") self.SwipeHideView(sender: nil) case UISwipeGestureRecognizerDirection.up: print("Swiped up") default: break } } } @IBAction func loadView(sender : AnyObject!) { self.view.endEditing(true) if isMenuView { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = false self.view1.view.frame = CGRect(x : -self.view.frame.width, y : 0,width : self.view.frame.width, height :self.view.frame.height ) }) { (finished) in self.view1.view.removeFromSuperview() } } else { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = true self.view1.view.frame = CGRect(x : 0, y : 0,width : self.view.frame.width, height : self.view.frame.height ) self.view.addSubview(self.view1.view) }) { (finished) in } } } @IBAction func SwipeHideView(sender : AnyObject!) { if isMenuView { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = false self.view1.view.frame = CGRect(x : -self.view.frame.width, y : 0,width : self.view.frame.width, height :self.view.frame.height ) }) { (finished) in self.view1.view.removeFromSuperview() } } } @IBAction func SwipeShowView(sender : AnyObject!) { if !isMenuView { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = true self.view1.view.frame = CGRect( x : 0, y : 0, width : self.view.frame.width, height : self.view.frame.height ) self.view.addSubview(self.view1.view) }) { (finished) in } } } } extension BaseViewController: DetailViewControllerDelegate { func didSelectButton(sender : UIButton, strType : String) { if isMenuView { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = false self.view1.view.frame = CGRect(x : -self.view.frame.width, y : 0, width : self.view.frame.width,height : self.view.frame.height ) }) { (finished) in if strType == "setting" { // let setting_VC = self.storyboard?.instantiateViewController(withIdentifier: settingVC) as! SettingViewController // self.navigationController?.pushViewController(setting_VC, animated: true) } else if strType == "edit" { // let edit_VC = self.storyboard?.instantiateViewController(withIdentifier: editVC) as! ProfileViewController // self.navigationController?.pushViewController(edit_VC, animated: true) } } } } func didFinishTask(sender: SideMenu, index : IndexPath) { if isMenuView { UIView.animate(withDuration: 0.3, animations: { self.isMenuView = false self.view1.view.frame = CGRect(x : -self.view.frame.width, y : 0, width : self.view.frame.width,height : self.view.frame.height ) }) { (finished) in self.view1.view.removeFromSuperview() if index.row == 0 { let Home_VC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController self.navigationController?.pushViewController(Home_VC, animated: false) } else if index.row == 1 { let MyProfile_VC = self.storyboard?.instantiateViewController(withIdentifier: "MyProfileViewController") as! MyProfileViewController self.navigationController?.pushViewController(MyProfile_VC, animated: false) } else if index.row == 2 { let MyOrders_VC = self.storyboard?.instantiateViewController(withIdentifier: "MyOrdersViewController") as! MyOrdersViewController self.navigationController?.pushViewController(MyOrders_VC, animated: false) } else if index.row == 3 { let MyFiles_VC = self.storyboard?.instantiateViewController(withIdentifier: "MyFilesViewController") as! MyFilesViewController self.navigationController?.pushViewController(MyFiles_VC, animated: false) } else if index.row == 4 { let NearbyStores_VC = self.storyboard?.instantiateViewController(withIdentifier: "NearbyStoresViewController") as! NearbyStoresViewController self.navigationController?.pushViewController(NearbyStores_VC, animated: false) } else if index.row == 5 { let AboutUs_VC = self.storyboard?.instantiateViewController(withIdentifier: "AboutUsViewController") as! AboutUsViewController self.navigationController?.pushViewController(AboutUs_VC, animated: false) } else if index.row == 6 { let Feedback_VC = self.storyboard?.instantiateViewController(withIdentifier: "FeedbackViewController") as! FeedbackViewController self.navigationController?.pushViewController(Feedback_VC, animated: false) } else if index.row == 7 { let alert :UIAlertController = UIAlertController(title: "Logout" , message: "Are you sure want to logout?", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "comment"), style: .default, handler: { action in _ = self.navigationController?.popToRootViewController(animated: true) UserDefaults.standard.removeObject(forKey: "selectedIndex") UserDefaults.standard.removeObject(forKey: "UserData") FBSDKLoginManager().logOut() GIDSignIn.sharedInstance().signOut() })) alert.addAction(UIAlertAction(title: NSLocalizedString("No", comment: "comment"), style: .cancel, handler: { action in })) self.present(alert, animated: true, completion: nil) } } } } func alertView(View: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { switch buttonIndex{ case 1: break; case 0: break; default: NSLog("Default"); break; } } }
7ac74748fed3d41b78583e7a11ab6ef1
42.835556
177
0.557842
false
false
false
false
DaveChambers/SuperCrack
refs/heads/master
SuperCrack!/PegboardView.swift
mit
1
// // PegboardView.swift // Pegs in the Head // // Created by Dave Chambers on 04/07/2017. // Copyright © 2017 Dave Chambers. All rights reserved. // import SnapKit import SwiftySound import UIKit class PegBoardView: UIView { private let dimensions: GameDimensions private let game: GameModel private var snapPointImageViews: [UIImageView] private let leftPaletteArea = UIView() private let mainPlayArea = UIView() private let turnAndFeedbackArea = UIView() private var draggedPegImageView: UIImageView? private var closestPegImageView: UIImageView = UIImageView() private var turnButtons: [UIButton] = Array() init(frame: CGRect, dimensions: GameDimensions, game:GameModel){ self.dimensions = dimensions self.game = game self.snapPointImageViews = [UIImageView] (repeating: UIImageView(), count: dimensions.boardCount) //Snap Points array will hold the UIImageViews, most of which will be snap points super.init(frame: frame) self.backgroundColor = UIColor.orange //Left Palette Area: leftPaletteArea.backgroundColor = UIColor.black self.addSubview(leftPaletteArea) leftPaletteArea.snp.makeConstraints { (make) -> Void in make.width.equalTo(self.dimensions.sectionWidth) make.height.equalTo(self.dimensions.usableHeight) make.left.equalTo(0) make.top.equalTo(0) } //Main Play Area: mainPlayArea.backgroundColor = dimensions.backgroundGrey self.addSubview(mainPlayArea) mainPlayArea.snp.makeConstraints { (make) -> Void in make.width.equalTo(self.dimensions.sectionWidth*CGFloat(game.getNumInCode())) make.height.equalTo(self.dimensions.usableHeight) make.centerX.equalTo(self.center) make.top.equalTo(0) } //Turn and Feedback Area: turnAndFeedbackArea.backgroundColor = UIColor.black self.addSubview(turnAndFeedbackArea) turnAndFeedbackArea.snp.makeConstraints { (make) -> Void in make.width.equalTo(self.dimensions.sectionWidth) make.height.equalTo(self.dimensions.usableHeight) make.left.equalTo(self.frame.width-self.dimensions.sectionWidth) make.top.equalTo(0) } addShowCodeButton() //Turn buttons that will become Feedback area after being pushed: addTurnButtons() } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } func addShowCodeButton() { let button = UIButton() self.addSubview(button) button.snp.makeConstraints { (make) -> Void in make.width.height.equalTo(self.dimensions.pegSize) make.center.equalTo(UIHelpers.pointFor(column: game.getNumInCode()+1, row: game.getNumRowsToUse(), dimensions: self.dimensions)) } button.backgroundColor = UIColor.black button.setTitle("Quit", for: .normal) button.addTarget(self, action: #selector(showCodeButtonAction), for: .touchUpInside) button.isEnabled = true button.titleLabel?.font = UIFont.boldSystemFont(ofSize: self.dimensions.buttonFontSize*2/3) button.setTitleColor(UIColor.white, for: .normal) } @objc func showCodeButtonAction(sender: UIButton!) { Sound.play(file: "Turn.wav") if game.hasEndSoundBeenPlayed() == true { self.endGame(won: self.game.isGameWon() ? true : false) }else{ let parent = self.parentViewController as! PegboardViewController parent.reallyQuit{success in if success == true { self.endGame(won: self.game.isGameWon() ? true : false) } } } } func addTurnButtons() { for button in turnButtons { button.removeFromSuperview() } turnButtons.removeAll() for i in 1...game.getNumGuesses() { let image = UIImage(named: String(describing: i)) as UIImage? let turnButton = UIButton(type: UIButtonType.custom) as UIButton turnButton.setImage(image, for: UIControlState.normal) turnButton.addTarget(self, action: #selector(turnButtonAction), for: .touchUpInside) turnButton.isEnabled = i == game.getTurnNumber() ? true : false //Only row 1 button is enabled at first self.addSubview(turnButton) turnButton.snp.makeConstraints { (make) -> Void in make.width.height.equalTo(self.dimensions.pegSize) make.center.equalTo(UIHelpers.pointFor(column: game.getNumInCode()+1, row: i, dimensions: self.dimensions)) } turnButtons.append(turnButton) } } @objc func turnButtonAction(sender: UIButton!) { if game.getTurnNumber() == game.getNumGuesses() { //If the Turn has a colour in each hole then make the button enabled .... if game.assessIfTurnCanBeTakenForRow() { displayFeedback(button: sender) let (_, _) = game.calculateFeedback() //Necessary to see if the game is won or not endGame(won: game.isGameWon() ? true : false) }else{ Sound.play(file: "Error.wav") } }else{ //If the Turn has a colour in each hole then make the button enabled .... if game.assessIfTurnCanBeTakenForRow() { displayFeedback(button: sender) game.incrementTurn() if game.isGameWon() { endGame(won: true) }else{ Sound.play(file: "Turn.wav") } turnButtons[game.getTurnNumber()-1].isEnabled = game.isGameBeingPlayed() //If the game is still in play, enable the next turn button }else{ Sound.play(file: "Error.wav") } } } override func layoutSubviews() { super.layoutSubviews() //Remove all the views placed in previous calls to this method: _ = subviews.filter{$0.tag != 0}.map{$0.removeFromSuperview()} //Place the Pegs..... for hole in game.getBoardHoles() { if let staticPeg = hole.getStaticPeg() { let sPeg = addPeg(peg: staticPeg, hole: hole) //Don't want the dragged Pegs to snap to the void (invisible) top left positions or the code holes (which will later be covered) but want to snap to all other points... if !sPeg.isHidden && hole.getHoleType() != HoleType.codeHole { snapPointImageViews[game.getSnapPointArrayIndexGivenColumnAndRow(col: staticPeg.getColumn(), row: staticPeg.getRow())] = sPeg } } if let dynamicPeg = hole.getDynamicPeg() { let dPeg = addPeg(peg: dynamicPeg, hole: hole) dPeg.isUserInteractionEnabled = dynamicPeg.isDraggable() } } //Cover the code Pegs: if game.isGameBeingPlayed() { addCodeCovers() } //printPegBoard() //assertGameState() } func addPeg(peg: Peg, hole: Hole) -> UIImageView { let holeImageView :UIImageView = UIImageView(); holeImageView.frame.size = CGSize(width: dimensions.pegSize, height: dimensions.pegSize) holeImageView.center = UIHelpers.pointFor(column: peg.getColumn(), row: peg.getRow(), dimensions: dimensions) holeImageView.image = UIImage(named:peg.getPegColour().getPegName()) holeImageView.isHidden = hole.isHidden() holeImageView.tag = peg.getPegColour().rawValue self.addSubview(holeImageView) return holeImageView } func addCodeCovers() { for i in 1...game.getNumInCode() { let coverLabel :UILabel = UILabel(); coverLabel.frame.size = CGSize(width: dimensions.pegSize, height: dimensions.pegSize) coverLabel.center = UIHelpers.pointFor(column: i, row: game.getNumGuesses()+1, dimensions: dimensions) coverLabel.tag = -1 coverLabel.text = "?" coverLabel.textAlignment = .center coverLabel.font = UIFont.boldSystemFont(ofSize: self.dimensions.buttonFontSize) coverLabel.textColor = UIColor.white coverLabel.backgroundColor = UIColor.black self.addSubview(coverLabel) } } func assertGameState() { //There should be 2 UIImageViews on each spot, except the code Pegs which feature 1 UIImageView. And more... assertPegProperties() } func assertPegProperties() { var codePegCentres: [CGPoint] = Array() var otherCentres: [CGPoint] = Array() let pegImageViews = self.subviews.filter{$0 is UIImageView && $0.tag != 0} for imgView in pegImageViews { let (_, col, row) = UIHelpers.convertPoint(point: imgView.center, dimensions: dimensions) if row == game.getNumRowsToUse() { codePegCentres.append(imgView.center) }else{ otherCentres.append(imgView.center) } let hole = game.getHoleForPosition(column: col, row: row) let (staticPeg, dynamicPeg) = hole.getPegPair() if let staticPeg = staticPeg, let dynamicPeg = dynamicPeg { if row != game.getTurnNumber() && row <= game.getNumGuesses() { assert(staticPeg.getPegColour() == dynamicPeg.getPegColour()) //Assert Static and Dynamic Pegs are the same colour.... assert(staticPeg.isDraggable() == false) //Assert Static Peg's Interaction is disabled.... assert(dynamicPeg.isDraggable() == (dynamicPeg.getPegColour() != PegColour.noPeg)) //The Dynamic Pegs UI is enabled only if the Peg has a colour }else if row == game.getNumRowsToUse(){ assert(staticPeg.getPegColour() != PegColour.noPeg) //Each Peg in the Code row has a colour } } } //Partition the CGPoints into groups: let otherCentreGroups = Set<CGPoint>(otherCentres).map{ value in return otherCentres.filter{$0==value} } for centrePair in otherCentreGroups { assert(centrePair.count == 2) } let codePegCentreGroups = Set<CGPoint>(codePegCentres).map{ value in return codePegCentres.filter{$0==value} } for shouldBeSingle in codePegCentreGroups { assert(shouldBeSingle.count == 1) } } func printPegBoard() { for row in (1...game.getNumRowsToUse()).reversed() { //Reversed is used since we want to display the top left data first and work our way to bottom right var desc: String = String() for column in 0..<dimensions.numPegsAcross { let hole = game.getHoleForPosition(column: column, row: row) var leftStaticPart: String var rightDynamicPart: String if let staticPeg = hole.getStaticPeg() { leftStaticPart = staticPeg.getPegColour().getPegLetter() }else{ leftStaticPart = "-" } if let dynamicPeg = hole.getDynamicPeg() { rightDynamicPart = dynamicPeg.getPegColour().getPegLetter() }else{ rightDynamicPart = "-" } let imageViewsAtPoint: [UIImageView] = getUIPegsOnPoint(point: UIHelpers.pointFor(column: column, row: row, dimensions: dimensions)) assert(imageViewsAtPoint.count <= 2) // Should never be more that 2 Pegs in a Hole (Static + Dynamic) var uiAndModelMatchForStatic: String? var uiAndModelMatchForDynamic: String? for imageView in imageViewsAtPoint { if PegColour.getColourLetter(index: imageView.tag) == leftStaticPart { uiAndModelMatchForStatic = leftStaticPart } if PegColour.getColourLetter(index: imageView.tag) == rightDynamicPart { uiAndModelMatchForDynamic = rightDynamicPart } } var staticCode: String if hole.getHoleType() == HoleType.voidHole { staticCode = " " }else if let match = uiAndModelMatchForStatic { staticCode = match }else{ staticCode = "*" //Make an error sound } var dynamicCode: String if hole.getHoleType() == HoleType.voidHole { dynamicCode = " " }else if hole.getHoleType() == HoleType.codeHole { dynamicCode = "^" }else if let match = uiAndModelMatchForDynamic { dynamicCode = match }else{ dynamicCode = "*" //Make an error sound Sound.play(file: "Error.wav") } desc = desc + "\t\((column, row)) = \((staticCode, dynamicCode)) \t|" } print("\n \(desc)") } print("\n\n") } func displayFeedback(button: UIButton) { button.isHidden = true let feedbackView: FeedbackView = FeedbackView(frame: self.frame, dimensions: dimensions, game: game) feedbackView.backgroundColor = UIColor.white feedbackView.layer.cornerRadius = 10 self.addSubview(feedbackView) feedbackView.snp.makeConstraints { (make) -> Void in make.width.height.equalTo(dimensions.pegSize) make.center.equalTo(UIHelpers.pointFor(column: game.getNumInCode()+1, row: game.getTurnNumber(), dimensions: dimensions)) } } func endGame(won: Bool) { _ = self.subviews.filter{$0.tag == -1}.map{$0.removeFromSuperview()} game.showCodeHoles() for turnButton in turnButtons { turnButton.isEnabled = false } setNeedsLayout() let parent = self.parentViewController as! PegboardViewController if won && game.isGameBeingPlayed() { Sound.play(file: "Win.wav") DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { //Allow the Win sound time to play parent.finaliseGame(won: won, pegBoardView: self) self.game.setEndSoundBeenPlayed(played: true) }) }else{ if game.hasEndSoundBeenPlayed() { parent.finaliseGame(won: won, pegBoardView: self) }else{ Sound.play(file: "Lose.wav") DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { //Allow the Lose sound time to play parent.finaliseGame(won: won, pegBoardView: self) self.game.setEndSoundBeenPlayed(played: true) }) } } game.setGameBeingPlayed(played: false) } func reactivateTurnOne() { turnButtons[0].isEnabled = true } func takeSnapshotForMemoryView() -> UIImage { let rect = CGRect( origin: CGPoint(x: 0, y: dimensions.vertInc), size: CGSize(width: dimensions.usableWidth, height: dimensions.usableHeight - dimensions.vertInc) ) return imageSnapshotCroppedToFrame(frame: rect) } //MARK: Dragging related Functions: func safelyFindClosestPeg(index: Int) -> Int { let ret: Int = 0 if index < snapPointImageViews.count && index >= 0 { return index } return ret } func getUIPegsOnPoint(point: CGPoint) -> [UIImageView] { var ret = [UIImageView]() let myImageViews = self.subviews.filter{$0 is UIImageView} for imgView in myImageViews { if imgView.center == point { ret.append(imgView as! UIImageView) } } return ret } func resetDrag() { draggedPegImageView = nil } func highlightHole() { if closestPegImageView != draggedPegImageView && mainPlayArea.frame.contains(closestPegImageView.frame) { let (_, _, row) = UIHelpers.convertPoint(point: closestPegImageView.center, dimensions: dimensions) let imageViewsAtPoint: [UIImageView] = getUIPegsOnPoint(point: closestPegImageView.center) for view in imageViewsAtPoint { view.layer.borderWidth = 4 view.layer.borderColor = row == game.getTurnNumber() ? UIColor.black.cgColor : UIColor.clear.cgColor } } } func resetBordersOnPegs() { let myImageViews = self.subviews.filter{$0 is UIImageView} for imgView in myImageViews { imgView.layer.borderWidth = 0 imgView.layer.borderColor = UIColor.clear.cgColor } } /** Ensure the touch is inside the circular peg */ func touchIsInsidePeg(centreOfImageView: CGPoint, locationInImgView: CGPoint) -> Bool { let xDist = centreOfImageView.x - locationInImgView.x let yDist = centreOfImageView.y - locationInImgView.y let dist = sqrt((xDist * xDist) + (yDist * yDist)) var isInside: Bool = false if dist < dimensions.pegSize/CGFloat(2){ isInside = true } return isInside } /** If the Dragged Peg is within a certain distance of the closest peg, snap it to that peg */ func draggedPegShouldSnapToNearest(draggedCentre: CGPoint, closestCentre: CGPoint) -> Bool { let holeOfPegOrigin: Hole = game.getHoleForPeg(peg: game.getDraggedPeg()) if holeOfPegOrigin.getHoleType() == HoleType.paletteHole && draggedPegImageView == closestPegImageView { //Should only return false if we are dealing with a Palette Peg since they shouldn't snap return false } let xDist = draggedCentre.x - closestCentre.x let yDist = draggedCentre.y - closestCentre.y let dist = sqrt((xDist * xDist) + (yDist * yDist)) var shouldSnap: Bool = false if dist < dimensions.pegSize/CGFloat(6){ shouldSnap = true } return shouldSnap } func reportMove(move: Move) { //print("Move reported: \(move)") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard game.isGameBeingPlayed() else { return } //Prevent any dragging of pegs if the game is over guard let touch = touches.first else { return } if touch.view is UIImageView{ let imgView = touch.view as! UIImageView let location = touch.location(in: self) if touchIsInsidePeg(centreOfImageView: imgView.center, locationInImgView: location){ //Ensure the touch is inside the circular peg let (_, column, row) = UIHelpers.convertPoint(point: location, dimensions: dimensions) if let peg = game.getDynamicPegForPoint(column: column, row: row) { peg.setIsBeingDragged(isBeingDragged: true) //Set the Peg as beingDragged closestPegImageView = snapPointImageViews[safelyFindClosestPeg(index: game.getSnapPointArrayIndexGivenColumnAndRow(col: column, row: row))] draggedPegImageView = imgView draggedPegImageView?.center = location } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first, let dragged = draggedPegImageView { let location = touch.location(in: self) let (_, column, row) = UIHelpers.convertPoint(point: location, dimensions: dimensions) closestPegImageView = snapPointImageViews[safelyFindClosestPeg(index: game.getSnapPointArrayIndexGivenColumnAndRow(col: column, row: row))] resetBordersOnPegs() highlightHole() if draggedPegShouldSnapToNearest(draggedCentre: dragged.center, closestCentre: closestPegImageView.center) { dragged.center = closestPegImageView.center }else{ dragged.center = touch.location(in: self) } dragged.layer.zPosition = closestPegImageView.layer.zPosition+1 //Keeps the dragged Peg above the Pegs we drag over } //If a peg goes into the Left Palette or the Turn/ Feedback View, make it snap to the peg with that same colour.... if let dragged = draggedPegImageView { if !mainPlayArea.frame.intersects(dragged.frame) { let draggedPegImageViewFromModel = game.getDraggedPeg() let colourPaletteIndex = game.getNumColours()-draggedPegImageViewFromModel.getPegColour().rawValue+1 dragged.center = snapPointImageViews[safelyFindClosestPeg(index: game.getSnapPointArrayIndexGivenColumnAndRow(col: 0, row: colourPaletteIndex))].center } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first, let dragged = draggedPegImageView { let location = touch.location(in: self) let (inMainBoard, column, row) = UIHelpers.convertPoint(point: location, dimensions: dimensions) let pegWeDragged = game.getDraggedPeg() pegWeDragged.setIsBeingDragged(isBeingDragged: false) resetDrag() resetBordersOnPegs() dragged.center = UIHelpers.pointFor(column: pegWeDragged.getColumn(), row: pegWeDragged.getRow(), dimensions: dimensions) //Return the dynamic peg we dragged back to it's spot if inMainBoard, row == game.getTurnNumber() { if let endPeg = game.getDynamicPegForPoint(column: column, row: row) { let endHole: Hole = game.getHoleForPeg(peg: endPeg) if let dynamicPeg = endHole.getDynamicPeg() { dynamicPeg.setPegColour(newPegColour: pegWeDragged.getPegColour()) //Set the colour of the dynamic destination peg. Static colour will only be set at the end of the Turn. dynamicPeg.setDraggable(isDraggable: true) //Make the Dynamic Peg in the Destination Draggable let startHole: Hole = game.getHoleForPeg(peg: pegWeDragged) if startHole.getHoleType() == HoleType.playableHole && startHole.getRow() == endHole.getRow() { //Set the colour to no colour to give the impression we are dragging the Peg to another Hole in the Turn BUT ONLY if the start and end are in the same turn if let startHoleDynamicPeg = startHole.getDynamicPeg() { startHoleDynamicPeg.setPegColour(newPegColour: PegColour.noPeg) } } reportMove(move: Move(pegA: pegWeDragged, pegB: dynamicPeg)) Sound.play(file: "Snap.wav") } }else{ //Dragged a Peg onto a spot NOT in the current Turn Sound.play(file: "ReverseSnap.wav") } }else{ let startHole: Hole = game.getHoleForPeg(peg: pegWeDragged) if pegWeDragged.getRow() == game.getTurnNumber() && startHole.getHoleType() == HoleType.playableHole { //Here, since we are moving from the current Turn, we want a drag offscreen to move the peg from that hole, just like it would in real life. But it must be a playable hole we are dragging otherwise a dragged palette hole will have it's dynamic peg set to 'noPeg' if let startHoleDynamicPeg = startHole.getDynamicPeg() { startHoleDynamicPeg.setPegColour(newPegColour: PegColour.noPeg) //Set the colour to no colour to give the impression we are dragging the Peg to another Hole in the Turn BUT ONLY if the start and end are in the same turn } } Sound.play(file: "ReverseSnap.wav") } setNeedsLayout() } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { resetDrag() touchesEnded(touches, with: event) } func insertTurnReceivedFromPegboard(memoryPegs: [MemoryPeg]) { //print("Received from Memory View the data: \(memoryPegs)") for peg in memoryPegs { let endPeg = game.getDynamicPegForPoint(column: peg.column, row: game.getTurnNumber()) let endHole: Hole = game.getHoleForPeg(peg: endPeg!) let dynamicPeg = endHole.getDynamicPeg() dynamicPeg!.setPegColour(newPegColour: peg.getPegColour()) dynamicPeg!.setDraggable(isDraggable: true) } setNeedsLayout() Sound.play(file: "Snap.wav") } }
cc5ba9e1cea48a442a0ed8c2551ecaeb
41.112546
374
0.668872
false
false
false
false
bitjammer/swift
refs/heads/master
stdlib/private/StdlibUnittestFoundationExtras/StdlibUnittestFoundationExtras.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ObjectiveC import Foundation import StdlibUnittest internal var _temporaryLocaleCurrentLocale: NSLocale? extension NSLocale { @objc public class func _swiftUnittest_currentLocale() -> NSLocale { return _temporaryLocaleCurrentLocale! } } public func withOverriddenLocaleCurrentLocale<Result>( _ temporaryLocale: NSLocale, _ body: () -> Result ) -> Result { let oldMethod = class_getClassMethod( NSLocale.self, #selector(getter: NSLocale.current)) precondition(oldMethod != nil, "could not find +[Locale currentLocale]") let newMethod = class_getClassMethod( NSLocale.self, #selector(NSLocale._swiftUnittest_currentLocale)) precondition(newMethod != nil, "could not find +[Locale _swiftUnittest_currentLocale]") precondition(_temporaryLocaleCurrentLocale == nil, "nested calls to withOverriddenLocaleCurrentLocale are not supported") _temporaryLocaleCurrentLocale = temporaryLocale method_exchangeImplementations(oldMethod, newMethod) let result = body() method_exchangeImplementations(newMethod, oldMethod) _temporaryLocaleCurrentLocale = nil return result } public func withOverriddenLocaleCurrentLocale<Result>( _ temporaryLocaleIdentifier: String, _ body: () -> Result ) -> Result { precondition( NSLocale.availableLocaleIdentifiers.contains(temporaryLocaleIdentifier), "requested locale \(temporaryLocaleIdentifier) is not available") return withOverriddenLocaleCurrentLocale( NSLocale(localeIdentifier: temporaryLocaleIdentifier), body) } /// Executes the `body` in an autorelease pool if the platform does not /// implement the return-autoreleased optimization. /// /// (Currently, only the i386 iOS and watchOS simulators don't implement the /// return-autoreleased optimization.) @inline(never) public func autoreleasepoolIfUnoptimizedReturnAutoreleased( invoking body: () -> Void ) { #if arch(i386) && (os(iOS) || os(watchOS)) autoreleasepool(invoking: body) #else body() #endif } @_versioned @_silgen_name("swift_stdlib_NSArray_getObjects") internal func _stdlib_NSArray_getObjects( nsArray: AnyObject, objects: AutoreleasingUnsafeMutablePointer<AnyObject?>?, rangeLocation: Int, rangeLength: Int) extension NSArray { @nonobjc // FIXME: there should be no need in this attribute. public func available_getObjects( _ objects: AutoreleasingUnsafeMutablePointer<AnyObject?>?, range: NSRange ) { return _stdlib_NSArray_getObjects( nsArray: self, objects: objects, rangeLocation: range.location, rangeLength: range.length) } } @_silgen_name("swift_stdlib_NSDictionary_getObjects") func _stdlib_NSDictionary_getObjects( nsDictionary: NSDictionary, objects: AutoreleasingUnsafeMutablePointer<AnyObject?>?, andKeys keys: AutoreleasingUnsafeMutablePointer<AnyObject?>? ) extension NSDictionary { @nonobjc // FIXME: there should be no need in this attribute. public func available_getObjects( _ objects: AutoreleasingUnsafeMutablePointer<AnyObject?>?, andKeys keys: AutoreleasingUnsafeMutablePointer<AnyObject?>? ) { return _stdlib_NSDictionary_getObjects( nsDictionary: self, objects: objects, andKeys: keys) } } public func expectBridgeToNSValue<T>(_ value: T, nsValueInitializer: ((T) -> NSValue)? = nil, nsValueGetter: ((NSValue) -> T)? = nil, equal: (T, T) -> Bool) { let object = value as AnyObject let nsValue = object as! NSValue if let nsValueInitializer = nsValueInitializer { expectEqual(nsValueInitializer(value), nsValue) } if let nsValueGetter = nsValueGetter { expectTrue(equal(value, nsValueGetter(nsValue))) } if let nsValueInitializer = nsValueInitializer, let nsValueGetter = nsValueGetter { expectTrue(equal(value, nsValueGetter(nsValueInitializer(value)))) } expectTrue(equal(value, object as! T)) }
cb38c9aa50ebf06c684c3303dddffb8d
31.434783
89
0.7042
false
false
false
false
KevinCoble/AIToolbox
refs/heads/master
iOS Playgrounds/LinearRegression.playground/Contents.swift
apache-2.0
1
/*: Introduction # Linear Regression This playground shows how the basics of Linear Regression, and shows how to use the AIToolbox framework to generate test data, train a linear regression model, and plot the results We start with the required import statements. If this was your own program, rather than a playground, you would also add an 'import AIToolbox' line. */ import UIKit import PlaygroundSupport /*: Target Function ## Create a Target function First we need some data. You can hard-code data points, or you can generate them from a function. This playground will generate them from a function and add noise to the data Linear regression input data can be of any dimension. Since we want to plot the data, we will use a 1 dimensional input (and output) for now We will use a linear regression model to generate the data. Set the 'targetOrder' to the maximum power of the polynomial. */ let targetOrder = 2 // Between 1 and 5 /*: The target function is created with the input and output size. We will use a convenience initializer that takes the polynomial order and creates a linear function with no cross terms (y = A, y = A + Bx, y = A + Bx + Cx², etc. */ let target = LinearRegressionModel(inputSize: 1, outputSize: 1, polygonOrder: targetOrder) /*: Next we create some parameters (this is the target function. For the hypothesis function, we 'learn' these parameters) Start with an array of reasonable values, and add some gaussian noise to make different curves for each run. Set the values as the parameters of the target function */ var targetParameters : [Double] = [10.0, 0.5, 0.25, -0.125, 0.0675, -0.038] for index in 0...targetOrder { targetParameters[index] += Gaussian.gaussianRandom(0.0, standardDeviation: targetParameters[index]) } try target.setParameters(targetParameters) targetParameters // Show target parameters to compare with hypothesis parameters later /*: Data Set ## Create a Regression DataSet Now that we have a target function, we need to get some data from it DataSets in AIToolbox come in two types, Regression and Classification. Regression is where you get a value (or array of values if the output dimension is >1) for your inputs. Classification is when you get an integer 'class label' based on the inputs. Regression is used to do things like 'predict time till failure', while classification is used for tasks like 'is that tumor malignant or benign' This is Linear Regression, so our data set will be the 'Regression type, with the same input and output dimensions as our target function. */ let data = DataSet(dataType: .regression, inputDimension: 1, outputDimension: 1) /*: We are going to use the target function to create points, and add noise set numPoints to the number of points to create, and set the standard deviation of the gaussian noise */ let numPoints = 100 // Number of points to fit let standardDeviation = 1.0 // Amount of noise in target line /*: The following code creates the points and adds them to the data set. We are keeping the input data in the range of 0-10, but that could be changed if you wanted. Note that the 'addDataPoint' function is preceded by a 'try' operator. Many AIToolbox routines can throw errors if dimensions don't match */ for index in 0..<numPoints { let x = Double(index) * 10.0 / Double(numPoints) let targetValue = try target.predictOne([x]) let y = targetValue[0] + Gaussian.gaussianRandom(0.0, standardDeviation: standardDeviation) try data.addDataPoint(input: [x], output:[y]) } /*: Hypothesis ## Create a Regression Hypothesis Model The Hypothesis Model is the form of the function to 'learn' the parameters for. Linear regression cannot create a function from the data, you specify the function and linear regression finds the best parameters to match the data to that function We will again use the convenience initializer to create a polygon model of a specific order. The polygon order does NOT have to match that of the target function/data. In fact, having a complicated hypothesis function with a small amount of data leads to 'overfitting'. Note that the input and output dimensions have to match our data. */ let hypothesisOrder = 2 // Polygon order for the model let lr = LinearRegressionModel(inputSize: 1, outputSize: 1, polygonOrder: hypothesisOrder) /*: Training ## 'Train' the model All regressors in AIToolbox, linear or not, have a 'trainRegressor' function that takes a Regression data set. This function asks the hypothesis to find the best parameters for the data set passed in. Note the 'try' again. Don't attempt to train a hypothesis with data of a different dimension. */ try lr.trainRegressor(data) let parameters = try lr.getParameters() /*: Plotting ## Create a Data Plot AIToolbox includes a subclass of NSView that can be used to plot the data and the functions. We use one here to show the data There are different types of plot objects that can be added. Data, functions, axis labels, and legends will be used here. Plot objects are drawn in the order added to the view. Start with creating the view */ let dataView = MLView(frame: CGRect(x: 0, y: 0, width: 480, height: 320)) //: Create a symbol object for plotting the data set - a green circle let dataPlotSymbol = MLPlotSymbol(color: UIColor.green, symbolShape: .circle, symbolSize: 7.0) //: Create a regression data set plot item let dataPlotItem = try MLViewRegressionDataSet(dataset: data, symbol: dataPlotSymbol) //: Set that item as the source of the initial scale of plot items. Some plot items can be set to change the scale, but something needs to set the initial scale dataView.setInitialScaleItem(dataPlotItem) //: Add a set of labels first (so they are underneath any other drawing). Both X and Y axis labels let axisLabels = MLViewAxisLabel(showX: true, showY: true) dataView.addPlotItem(axisLabels) //: Create a regression data line item for the target function, blue let targetLine = MLViewRegressionLine(regressor: target, color: UIColor.blue) dataView.addPlotItem(targetLine) //: Create a regression data line item for the hypothes function, red let hypothesisLine = MLViewRegressionLine(regressor: lr, color: UIColor.red) dataView.addPlotItem(hypothesisLine) //: Add the data plot item now (so the data points are on top of the lines - reorder if you want!) dataView.addPlotItem(dataPlotItem) //: Create a legend let legend = MLViewLegend(location: .lowerRight, title: "Legend") //: Add the target line to the legend let targetLegend = MLLegendItem(label: "target", regressionLinePlotItem: targetLine) legend.addItem(targetLegend) //: Add the data set to the legend let dataLegend = MLLegendItem(label: "data", dataSetPlotItem: dataPlotItem) legend.addItem(dataLegend) //: Add the hypothesis line to the legend let lineLegend = MLLegendItem(label: "hypothesis", regressionLinePlotItem: hypothesisLine) legend.addItem(lineLegend) dataView.addPlotItem(legend) //: Finally, set the view to be drawn by the playground PlaygroundPage.current.liveView = dataView
d730c2a44721cdc1cee375ddf3f9ee19
53.037879
402
0.762092
false
false
false
false
dche/FlatCG
refs/heads/master
Tests/FlatCGTests/TransformTests.swift
mit
1
import XCTest import GLMath @testable import FlatCG class TransformTests: XCTestCase { func testIdentity() { let tm = Transform2D.identity XCTAssertEqual(tm.matrix, tm.invMatrix) XCTAssertEqual(vec2.y.apply(transform: tm), vec2.y) } func testInverse() { let m = mat3(1, 2, 3, 3, 1, 2, 2, 3, 1) let minv = m.inverse let tm = Transform2D(matrix: m, invMatrix: minv) let tminv = tm.inverse XCTAssertEqual(tminv.matrix, minv) XCTAssertEqual(tminv.invMatrix, m) } func testCompose() { let m0 = Transform2D.identity.translate(x: 1, y: 2) let m1 = Transform2D.identity.translate(x: 3, y: 4) let m = m0.compose(m1) XCTAssertEqual(m, m0.translate(vec2(3, 4))) XCTAssertEqual(m, Transform2D.identity.translate(x: 4, y: 6)) } } class TransformableTets: XCTestCase { func testTransformIsTransformable() { var tm = Transform3D.identity.translate(vec3.x * 10) tm = tm.apply(transform: tm) let p = Point3D.origin.apply(transform: tm) XCTAssertEqual(p, Point3D(20, 0, 0)) } func testTranslate() { let tm = Transform3D.identity.translate(x: 1, y: 2, z: 3) let p = Point3D(1, 2, 3) let v = p.vector XCTAssertEqual(p.translate(x: 1, y: 2, z: 3), Point3D(2, 4, 6)) XCTAssertEqual(v.apply(transform: tm), v) } func testScale() { let p = Point3D(1, 1, 1) XCTAssertEqual(p.scale(2), Point3D(2, 2, 2)) XCTAssertEqual(p.scale(x: 2, y: 0, z: 0.5), Point3D(2, 1, 0.5)) } func testRotation() { let p2 = Point2D(vec2.x) XCTAssert(p2.rotate(angle: .half_pi) ~== Point2D(vec2.y)) let v3 = -vec3.z XCTAssert(v3.rotate(around: Normal3D(vec3.z), angle: .pi) ~== v3) let tm = Transform3D.identity.rotate(around: Normal3D(vec3.x), angle: .pi) XCTAssert(v3.apply(transform: tm).isClose(to: -v3, tolerance: .epsilon * 10)) XCTAssert((-v3.apply(transform: tm.inverse)).isClose(to: v3, tolerance: .epsilon * 10)) } }
44c3ef1f9b5e6c152485b701a5aeae59
31.430769
95
0.598672
false
true
false
false
byu-oit/ios-byuSuite
refs/heads/dev
byuSuite/Apps/JobOpenings/controller/JobOpeningsPostingsViewController.swift
apache-2.0
1
// // JobOpeningsPostingsViewController.swift // byuSuite // // Created by Alex Boswell on 2/16/18. // Copyright © 2018 Brigham Young University. All rights reserved. // class JobOpeningsPostingsViewController: ByuTableDataViewController { //MARK: Public Variables var family: JobOpeningsFamily! var siteId: Int! //MARK: View controller lifecycle override func viewDidLoad() { super.viewDidLoad() title = family.jobTitle loadJobPostings() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showPosting", let posting: JobOpeningsPosting = objectForSender(tableView: tableView, cellSender: sender), let vc = segue.destination as? JobOpeningsDetailViewController { vc.posting = posting } } //MARK: Custom Methods private func loadJobPostings() { JobOpeningsClient.getJobPosting(siteId: siteId, jobTemplateId: family.jobTemplateId) { (postings, error) in self.spinner?.stopAnimating() if let postings = postings { self.tableData = TableData(rows: postings.map { Row(text: $0.title, object: $0) }) self.tableView.reloadData() } else { super.displayAlert(error: error) } } } }
428c00a9b191884255a5dd0b0737bdb3
24.625
109
0.712195
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
Objects/scripts/XD/XGScriptInstruction.swift
gpl-2.0
1
// // XGScriptInstruction.swift // GoD Tool // // Created by The Steez on 26/10/2017. // // import Foundation let kXDSLastResultVariable = "LastResult" class XGScriptInstruction: NSObject { var isScriptFunctionLastResult = false // set during decompilation to prevent being attributed to the wrong function var isUnusedPostpendedCall = false // set during decompilation to prevent parsing stray function calls at end of script var opCode = XGScriptOps.nop var subOpCode = 0 var parameter = 0 var longParameter = 0 // used by 'call', 'jumptrue', 'jumpfalse', and 'jump' var subSubOpCodes = (0,0) var level = 0 var length = 1 var raw1 : UInt32 = 0 var raw2 : UInt32 = 0 var constant : XDSConstant! var SCDVariable : String { let param = self.parameter let (_, level) = self.subSubOpCodes switch level { case 0: return "#GVAR[\(self.parameter)]" case 1: return "#Stack[\(self.parameter)]" case 2: return "#LastResult" default: if param < 0x80 && param > 0 { return "#" + XGScriptClass.classes(param).name.lowercased() + "Object" } else if param == 0x80 { return "#characters[player]" } else if param <= 0x120 { return "#characters[\(param - 0x80)]" } else if param < 0x300 && param >= 0x200 { return "#arrays[\(param - 0x200)]" } else { return "#invalid" } } } var isVariable : Bool { return self.opCode == .loadVariable || self.opCode == .loadNonCopyableVariable || self.opCode == .setVariable } var isLocalVariable : Bool { return self.isVariable && self.level == 1 } var isGlobalVariable : Bool { return self.isVariable && self.level == 0 } var isArrayVariable : Bool { return self.isVariable && self.level == 3 && self.parameter >= 0x200 } var XDSVariable : String { // add an asterisk to last result, local variables and script function parameters if the type of the varible isn't copyable. // it is incredibly difficult to infer the underlying type for these variables. let param = self.parameter switch self.level { case 0: return "gvar_" + String(format: "%02d", param) case 1: var pointerAdd = "" switch self.opCode { case .loadNonCopyableVariable: pointerAdd = "*" default: pointerAdd = "" } return (param < 0 ? "var_\(-param)" : "arg_\(param - 1)") + pointerAdd case 2: var pointerAdd = "" switch self.opCode { case .loadNonCopyableVariable: pointerAdd = "*" default: pointerAdd = "" } return kXDSLastResultVariable + pointerAdd default: if param < 0x80 && param > 0 { return XGScriptClass.classes(param).name } else if param == 0x80 { return "player_character" } else if param <= 0x120 { return "character_" + String(format: "%02d", param - 0x80) } else if param < 0x300 && param >= 0x200 { return "array_" + String(format: "%02d", param - 0x200) } else { return "_invalid_var_" } } } var vectorDimension : XDSVectorDimension { let (d, _) = self.subSubOpCodes return XDSVectorDimension(rawValue: d) ?? .invalid } init(bytes: UInt32, next: UInt32) { super.init() let op = ((bytes >> 24) & 0xFF).int self.opCode = XGScriptOps(rawValue: op) ?? .nop self.subOpCode = ((bytes >> 16) & 0xFF).int self.parameter = (bytes & 0xFFFF).int16 self.longParameter = (bytes & 0xFFFFFF).int self.subSubOpCodes = ((self.subOpCode >> 4), self.subOpCode & 0xf) self.level = self.subSubOpCodes.1 self.raw1 = bytes self.raw2 = 0 if self.opCode == .loadImmediate { self.constant = XDSConstant(type: self.subOpCode, rawValue: next) var shortType = false switch constant.type { case .vector: fallthrough case .string: self.constant.value = UInt32(self.parameter) shortType = true default: break } if !shortType { self.length = 2 self.parameter = next.int32 self.raw2 = next } } } convenience init(opCode: XGScriptOps, subOpCode: Int, parameter: Int) { let op = (opCode.rawValue << 24) let sub = (subOpCode << 16) let param = (parameter & 0xFFFF) self.init(bytes: UInt32( op + sub + param ), next: 0) } class func variableInstruction(op: XGScriptOps, level: Int, index: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: op, subOpCode: level, parameter: index) } class func functionCall(classID: Int, funcID: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: .callStandard, subOpCode: classID, parameter: funcID) } class func loadImmediate(c: XDSConstant) -> XGScriptInstruction { switch c.type { case .string: fallthrough case .vector: return XGScriptInstruction(opCode: .loadImmediate, subOpCode: c.type.index, parameter: c.value.int) default: let code : UInt32 = UInt32(XGScriptOps.loadImmediate.rawValue << 24) + (UInt32(c.type.index) << 16) return XGScriptInstruction(bytes: code, next: c.value) } } class func xdsoperator(op: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: .xd_operator, subOpCode: op, parameter: 0) } class func nopInstruction() -> XGScriptInstruction { return XGScriptInstruction(opCode: .nop, subOpCode: 0, parameter: 0) } class func call(location: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: .call, subOpCode: 0, parameter: location) } class func loadVarLastResult() -> XGScriptInstruction { return XGScriptInstruction.variableInstruction(op: .loadVariable, level: 2, index: 0) } class func jump(op: XGScriptOps, location: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: op, subOpCode: 0, parameter: location) } class func reserve(count: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: .reserve, subOpCode: count, parameter: 0) } class func release(count: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: .release, subOpCode: count, parameter: 0) } class func xdsreturn() -> XGScriptInstruction { return XGScriptInstruction(opCode: .return_op, subOpCode: 0, parameter: 0) } class func pop(count: Int) -> XGScriptInstruction { return XGScriptInstruction(opCode: .pop, subOpCode: count, parameter: 0) } override var description: String { var param = self.parameter switch self.opCode { case .call: fallthrough case .jumpIfTrue: fallthrough case .jumpIfFalse: fallthrough case .jump: param = self.longParameter default: break } var sub = "\(self.subOpCode) " switch self.opCode { case .nop: fallthrough case .return_op: fallthrough case .loadVariable: fallthrough case .setVariable: fallthrough case .loadNonCopyableVariable: fallthrough case .setLine: fallthrough case .jump: fallthrough case .jumpIfFalse: fallthrough case .jumpIfTrue: fallthrough case .call: fallthrough case .loadImmediate: sub = "" case .callStandard: sub = XGScriptClass.classes(self.subOpCode).name + "." case .xd_operator: sub = XGScriptClass.operators[self.subOpCode].name case .setVector: let dimensions = ["vx ","vy ", "vz "] let index = self.subSubOpCodes.0 sub = index < 3 ? dimensions[index] : "error" default: break } var paramString = param.string + " (" + param.hexString() + ")" switch self.opCode { case .jump: fallthrough case .jumpIfTrue: fallthrough case.jumpIfFalse: paramString = param.hexString() case .loadVariable: fallthrough case .setVariable: fallthrough case .setVector: fallthrough case .loadNonCopyableVariable: paramString = self.SCDVariable case .callStandard: paramString = XGScriptClass.classes(self.subOpCode)[param].name + "()" case .loadImmediate: paramString = self.constant.description + " (" + param.hexString() + ")" case .pop: fallthrough case .release: fallthrough case .return_op: fallthrough case .nop: fallthrough case .reserve: fallthrough case .xd_operator: paramString = "" default: break } return self.opCode.name + " " + sub + paramString } }
f8e1d6c8bbfa883727a9d7da5ff3033b
24.688889
126
0.675111
false
false
false
false
mflint/ios-tldr-viewer
refs/heads/master
tldr-viewer/TextCellViewModel.swift
mit
1
// // TextCellViewModel.swift // tldr-viewer // // Created by Matthew Flint on 02/01/2016. // Copyright © 2016 Green Light. All rights reserved. // import Foundation class TextCellViewModel: BaseCellViewModel { var cellIdentifier: String! var action: ViewModelAction = {} var attributedText: NSAttributedString? var detailAttributedText: NSAttributedString? init(attributedText: NSAttributedString?, detailAttributedText: NSAttributedString?) { self.attributedText = attributedText self.detailAttributedText = detailAttributedText if detailAttributedText == nil { self.cellIdentifier = "TextCellBasic" } else { self.cellIdentifier = "TextCellRightDetail" } } convenience init(text: String?, detailText: String?) { self.init(attributedText: Theme.bodyAttributed(string: text), detailAttributedText: Theme.detailAttributed(string: detailText)) } convenience init(attributedText: NSAttributedString?) { self.init(attributedText: attributedText, detailAttributedText: nil) } convenience init(text: String?) { self.init(attributedText: Theme.bodyAttributed(string: text)) } func performAction() { // no-op } }
773d5d08f44e3655cf33f0dedfc494b3
28.522727
135
0.677444
false
false
false
false
xsunsmile/zentivity
refs/heads/master
zentivity/ParseClient.swift
apache-2.0
1
// // ParseClient.swift // zentivity // // Created by Eric Huang on 3/6/15. // Copyright (c) 2015 Zendesk. All rights reserved. // import UIKit class ParseClient: NSObject { // Users // Give list of usernames to get users // Used for relations class func usersWithCompletion(usernames: [String], completion: (users: [PFUser], error: NSError?) -> ()) { var query = PFQuery(className:"_User") query.whereKey("username", containedIn: usernames) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if error == nil { completion(users: objects as! [PFUser], error: nil) } else { completion(users: [], error: error) } } } class func setUpUserWithCompletion(user: User, completion: (user: User?, error: NSError?) -> ()) { // if user.contactNumber == nil { user.contactNumber = self.randomPhoneNumber() // } user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in if error == nil { println("Signed up user with username") completion(user: user as User, error: nil) } else { User.logInWithUsernameInBackground(user.username!, password: user.password!, block: { (user, error) -> Void in if error == nil { println("Logged in user with username") completion(user: user as? User, error: nil) } else { completion(user: nil, error: error) } }) } } } class func randomPhoneNumber() -> String { var randomNumber = "(415) " for i in 0...7 { if i == 3 { randomNumber += "-" } else { let randomDigit = arc4random_uniform(10) randomNumber += String(randomDigit) } } return randomNumber } }
8bc506e4a29e716869f97073c2c99788
31.661538
126
0.509425
false
false
false
false
Bouke/HAP
refs/heads/master
Sources/HAP/Base/Predefined/Services/Service.FanV2.swift
mit
1
import Foundation extension Service { open class FanV2: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } active = getOrCreateAppend( type: .active, characteristics: &unwrapped, generator: { PredefinedCharacteristic.active() }) currentFanState = get(type: .currentFanState, characteristics: unwrapped) targetFanState = get(type: .targetFanState, characteristics: unwrapped) lockPhysicalControls = get(type: .lockPhysicalControls, characteristics: unwrapped) name = get(type: .name, characteristics: unwrapped) rotationDirection = get(type: .rotationDirection, characteristics: unwrapped) rotationSpeed = get(type: .rotationSpeed, characteristics: unwrapped) swingMode = get(type: .swingMode, characteristics: unwrapped) super.init(type: .fanV2, characteristics: unwrapped) } // MARK: - Required Characteristics public let active: GenericCharacteristic<Enums.Active> // MARK: - Optional Characteristics public let currentFanState: GenericCharacteristic<Enums.CurrentFanState>? public let targetFanState: GenericCharacteristic<Enums.TargetFanState>? public let lockPhysicalControls: GenericCharacteristic<UInt8>? public let name: GenericCharacteristic<String>? public let rotationDirection: GenericCharacteristic<Enums.RotationDirection>? public let rotationSpeed: GenericCharacteristic<Float>? public let swingMode: GenericCharacteristic<UInt8>? } }
69984ceb6f42517c8b306109df48bc96
50.272727
95
0.683806
false
false
false
false
Onetaway/iOS8-day-by-day
refs/heads/master
03-uivisualeffect/ControlEffects/ControlEffects/ViewController.swift
apache-2.0
3
// // Copyright 2014 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class ViewController: UIViewController, TransformControlsDelegate { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } // <TransformControlsDelegate> func transformDidChange(transform: CGAffineTransform, sender: AnyObject) { // Update the transform applied to the image view imageView.transform = transform } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier? == "showTransformController" { if let transformController = segue.destinationViewController as? TransformControlsViewController { transformController.transformDelegate = self transformController.currentTransform = imageView.transform } } } }
a41e7b8ebce58a22bec25cf1b094e85f
32.704545
104
0.726905
false
false
false
false
suzp1984/IOS-ApiDemo
refs/heads/master
ApiDemo-Swift/ApiDemo-Swift/ControllersAndViewsSampleViewController.swift
apache-2.0
1
// // ControllersAndViewsSampleViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/29/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class ControllersAndViewsSampleViewController: UIViewController, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource { let cellIdentifier = "Controllers Views" let demos: [String] = ["indicator", "progress bar", "picker view", "search bar", "switcher", "stepper", "page controller", "date picker", "slider", "Segmented View", "Button", "Custome Control", "Slider Bubble", "Bar Shadow"] override func viewDidLoad() { super.viewDidLoad() self.title = "Controllers & Views" let table = UITableView(frame: self.view.bounds) table.delegate = self table.dataSource = self table.backgroundColor = UIColor.cyan table.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) self.view.addSubview(table) self.navigationItem.leftItemsSupplementBackButton = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) if cell == nil { cell = UITableViewCell(style:.default, reuseIdentifier:cellIdentifier) cell.textLabel!.textColor = UIColor.white let v2 = UIView() // no need to set frame v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2) cell.selectedBackgroundView = v2 // next line didn't work until iOS 7! cell.backgroundColor = UIColor.red } let v2 = UIView() // no need to set frame v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2) cell.selectedBackgroundView = v2 cell.textLabel!.textColor = UIColor.white cell.backgroundColor = UIColor.red cell.textLabel!.text = demos[(indexPath as NSIndexPath).row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch demos[(indexPath as NSIndexPath).row] { case demos[0]: self.navigationController?.pushViewController(IndicatorSampleViewController(), animated: true) case demos[1]: self.navigationController?.pushViewController(ProgressBarViewController(), animated: true) case demos[2]: self.navigationController?.pushViewController(UIPickerViewController(), animated: true) case demos[3]: self.navigationController?.pushViewController(SearchBarViewController(), animated: true) case demos[4]: self.navigationController?.pushViewController(UISwitchViewController(), animated: true) case demos[5]: self.navigationController?.pushViewController(StepperViewController(), animated: true) case demos[6]: self.navigationController?.pushViewController(PageControlViewController(), animated: true) case demos[7]: self.navigationController?.pushViewController(DatePickerViewController(), animated: true) case demos[8]: self.navigationController?.pushViewController(SliderSampleViewController(), animated: true) case demos[9]: self.navigationController?.pushViewController(SegmentViewController(), animated: true) case demos[10]: self.navigationController?.pushViewController(ButtonSampleViewController(), animated: true) case demos[11]: self.navigationController?.pushViewController(CustomControlViewController(), animated: true) case demos[12]: self.navigationController?.pushViewController(SliderBubbleViewController(), animated: true) case demos[13]: self.navigationController?.pushViewController(BarShadowViewController(), animated: true) default: break } } }
56e2db63ed79e61f45147965e6060337
41.100917
115
0.654609
false
false
false
false
JQJoe/RxDemo
refs/heads/develop
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift
apache-2.0
11
// // CalculatorViewController.swift // RxExample // // Created by Carlos García on 4/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class CalculatorViewController: ViewController { @IBOutlet weak var lastSignLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var allClearButton: UIButton! @IBOutlet weak var changeSignButton: UIButton! @IBOutlet weak var percentButton: UIButton! @IBOutlet weak var divideButton: UIButton! @IBOutlet weak var multiplyButton: UIButton! @IBOutlet weak var minusButton: UIButton! @IBOutlet weak var plusButton: UIButton! @IBOutlet weak var equalButton: UIButton! @IBOutlet weak var dotButton: UIButton! @IBOutlet weak var zeroButton: UIButton! @IBOutlet weak var oneButton: UIButton! @IBOutlet weak var twoButton: UIButton! @IBOutlet weak var threeButton: UIButton! @IBOutlet weak var fourButton: UIButton! @IBOutlet weak var fiveButton: UIButton! @IBOutlet weak var sixButton: UIButton! @IBOutlet weak var sevenButton: UIButton! @IBOutlet weak var eightButton: UIButton! @IBOutlet weak var nineButton: UIButton! override func viewDidLoad() { let commands:[Observable<Action>] = [ allClearButton.rx.tap.map { _ in .clear }, changeSignButton.rx.tap.map { _ in .changeSign }, percentButton.rx.tap.map { _ in .percent }, divideButton.rx.tap.map { _ in .operation(.division) }, multiplyButton.rx.tap.map { _ in .operation(.multiplication) }, minusButton.rx.tap.map { _ in .operation(.subtraction) }, plusButton.rx.tap.map { _ in .operation(.addition) }, equalButton.rx.tap.map { _ in .equal }, dotButton.rx.tap.map { _ in .addDot }, zeroButton.rx.tap.map { _ in .addNumber("0") }, oneButton.rx.tap.map { _ in .addNumber("1") }, twoButton.rx.tap.map { _ in .addNumber("2") }, threeButton.rx.tap.map { _ in .addNumber("3") }, fourButton.rx.tap.map { _ in .addNumber("4") }, fiveButton.rx.tap.map { _ in .addNumber("5") }, sixButton.rx.tap.map { _ in .addNumber("6") }, sevenButton.rx.tap.map { _ in .addNumber("7") }, eightButton.rx.tap.map { _ in .addNumber("8") }, nineButton.rx.tap.map { _ in .addNumber("9") } ] Observable.from(commands) .merge() .scan(CalculatorState.CLEAR_STATE) { a, x in return a.tranformState(x) } .debug("debugging") .subscribe(onNext: { [weak self] calState in self?.resultLabel.text = calState.inScreen switch calState.action { case .operation(let operation): switch operation { case .addition: self?.lastSignLabel.text = "+" case .subtraction: self?.lastSignLabel.text = "-" case .multiplication: self?.lastSignLabel.text = "x" case .division: self?.lastSignLabel.text = "/" } default: self?.lastSignLabel.text = "" } }) .addDisposableTo(disposeBag) } //swifts string api sucks func prettyFormat(str: String) -> String { if str.hasSuffix(".0") { // return str[str.startIndex..<str.endIndex.pre] } return str } }
d6beaba619f9fcf84110643d94e769f1
32.910714
75
0.555556
false
false
false
false
khaptonstall/ios-my-coordinates
refs/heads/master
My Coordinates/My Coordinates/ViewController.swift
mit
1
// // ViewController.swift // My Coordinates // // Created by Kyle Haptonstall on 1/8/16. // Copyright © 2016 Kyle Haptonstall. All rights reserved. // import UIKit import GoogleMaps class ViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate { // MARK: - Global Variables @IBOutlet weak var mapView: GMSMapView! let locationManager = CLLocationManager() var markerOnMap = false // MARK: - Storyboard Labels @IBOutlet weak var latLabel: UILabel! @IBOutlet weak var longLabel: UILabel! // MARK: - Nav Bar Buttons /** Clears the map of all markers and resets the center to the user's current location - parameter sender: Left nav bar button */ @IBAction func resetMap(sender: UIButton) { mapView.clear() markerOnMap = false self.mapView.camera = GMSCameraPosition(target: (locationManager.location?.coordinate)!, zoom: 12, bearing: 0, viewingAngle: 0) self.mapView.myLocationEnabled = true self.latLabel.text = String(locationManager.location!.coordinate.latitude) self.longLabel.text = String(locationManager.location!.coordinate.longitude) } /** Grabs the current latitude and longitude and allows the user to share - parameter sender: Right nav bar button */ @IBAction func shareButtonPressed(sender: AnyObject) { let currLat = latLabel.text let currLong = longLabel.text if currLat != nil && currLong != nil{ let activityController = UIActivityViewController(activityItems: ["My current lattitude is: \(currLat!), and current longitude is: \(currLong!)"], applicationActivities: nil) self.presentViewController(activityController, animated: true, completion: nil) } } // MARK: - View Controller Methods override func viewDidAppear(animated: Bool) { if CLLocationManager.locationServicesEnabled() == false{ self.locationManager.requestWhenInUseAuthorization() } } override func viewDidLoad() { super.viewDidLoad() setUpNavBar() mapView.delegate = self locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } // MARK: - Custom Methods func setUpNavBar(){ let logoView = UIImageView(frame: CGRectMake(0, 0, 30, 30)) logoView.image = UIImage(named: "MyCoordinateLogo") logoView.frame.origin.x = (self.view.frame.size.width - logoView.frame.size.width) / 2 logoView.frame.origin.y = 25 self.navigationController?.view.addSubview(logoView) self.navigationController?.view.bringSubviewToFront(logoView) } // MARK: - MapView Delegate Methods func mapView(mapView: GMSMapView!, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) { if markerOnMap == false { markerOnMap = true } self.latLabel.text = String(coordinate.latitude) self.longLabel.text = String(coordinate.longitude) let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude) self.mapView.clear() self.mapView.myLocationEnabled = false marker.map = self.mapView } // MARK: - Location Manager Delegate Methods func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status != .AuthorizedWhenInUse { self.locationManager.requestAlwaysAuthorization() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if markerOnMap == false{ let locationArr = locations as NSArray let locationObj = locationArr.lastObject as! CLLocation let coordinate = locationObj.coordinate self.mapView.camera = GMSCameraPosition(target: (coordinate), zoom: 12, bearing: 0, viewingAngle: 0) self.mapView.myLocationEnabled = true self.latLabel.text = String(coordinate.latitude) self.longLabel.text = String(coordinate.longitude) self.markerOnMap = true } } }
44c8a94c864f1071d38bc0c490c013b4
31.781022
186
0.647884
false
false
false
false
CodaFi/swift
refs/heads/main
stdlib/public/core/StringCreate.swift
apache-2.0
12
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // String Creation Helpers //===----------------------------------------------------------------------===// internal func _allASCII(_ input: UnsafeBufferPointer<UInt8>) -> Bool { if input.isEmpty { return true } // NOTE: Avoiding for-in syntax to avoid bounds checks // // TODO(String performance): SIMD-ize // let ptr = input.baseAddress._unsafelyUnwrappedUnchecked var i = 0 let count = input.count let stride = MemoryLayout<UInt>.stride let address = Int(bitPattern: ptr) let wordASCIIMask = UInt(truncatingIfNeeded: 0x8080_8080_8080_8080 as UInt64) let byteASCIIMask = UInt8(truncatingIfNeeded: wordASCIIMask) while (address &+ i) % stride != 0 && i < count { guard ptr[i] & byteASCIIMask == 0 else { return false } i &+= 1 } while (i &+ stride) <= count { let word: UInt = UnsafePointer( bitPattern: address &+ i )._unsafelyUnwrappedUnchecked.pointee guard word & wordASCIIMask == 0 else { return false } i &+= stride } while i < count { guard ptr[i] & byteASCIIMask == 0 else { return false } i &+= 1 } return true } extension String { internal static func _uncheckedFromASCII( _ input: UnsafeBufferPointer<UInt8> ) -> String { if let smol = _SmallString(input) { return String(_StringGuts(smol)) } let storage = __StringStorage.create(initializingFrom: input, isASCII: true) return storage.asString } @usableFromInline internal static func _fromASCII( _ input: UnsafeBufferPointer<UInt8> ) -> String { _internalInvariant(_allASCII(input), "not actually ASCII") return _uncheckedFromASCII(input) } internal static func _fromASCIIValidating( _ input: UnsafeBufferPointer<UInt8> ) -> String? { if _fastPath(_allASCII(input)) { return _uncheckedFromASCII(input) } return nil } public // SPI(Foundation) static func _tryFromUTF8(_ input: UnsafeBufferPointer<UInt8>) -> String? { guard case .success(let extraInfo) = validateUTF8(input) else { return nil } return String._uncheckedFromUTF8(input, isASCII: extraInfo.isASCII) } @usableFromInline internal static func _fromUTF8Repairing( _ input: UnsafeBufferPointer<UInt8> ) -> (result: String, repairsMade: Bool) { switch validateUTF8(input) { case .success(let extraInfo): return (String._uncheckedFromUTF8( input, asciiPreScanResult: extraInfo.isASCII ), false) case .error(let initialRange): return (repairUTF8(input, firstKnownBrokenRange: initialRange), true) } } internal static func _fromLargeUTF8Repairing( uninitializedCapacity capacity: Int, initializingWith initializer: ( _ buffer: UnsafeMutableBufferPointer<UInt8> ) throws -> Int ) rethrows -> String { let result = try __StringStorage.create( uninitializedCodeUnitCapacity: capacity, initializingUncheckedUTF8With: initializer) switch validateUTF8(result.codeUnits) { case .success(let info): result._updateCountAndFlags( newCount: result.count, newIsASCII: info.isASCII ) return result.asString case .error(let initialRange): //This could be optimized to use excess tail capacity return repairUTF8(result.codeUnits, firstKnownBrokenRange: initialRange) } } @usableFromInline internal static func _uncheckedFromUTF8( _ input: UnsafeBufferPointer<UInt8> ) -> String { return _uncheckedFromUTF8(input, isASCII: _allASCII(input)) } @usableFromInline internal static func _uncheckedFromUTF8( _ input: UnsafeBufferPointer<UInt8>, isASCII: Bool ) -> String { if let smol = _SmallString(input) { return String(_StringGuts(smol)) } let storage = __StringStorage.create( initializingFrom: input, isASCII: isASCII) return storage.asString } // If we've already pre-scanned for ASCII, just supply the result @usableFromInline internal static func _uncheckedFromUTF8( _ input: UnsafeBufferPointer<UInt8>, asciiPreScanResult: Bool ) -> String { if let smol = _SmallString(input) { return String(_StringGuts(smol)) } let isASCII = asciiPreScanResult let storage = __StringStorage.create( initializingFrom: input, isASCII: isASCII) return storage.asString } @usableFromInline internal static func _uncheckedFromUTF16( _ input: UnsafeBufferPointer<UInt16> ) -> String { // TODO(String Performance): Attempt to form smol strings // TODO(String performance): Skip intermediary array, transcode directly // into a StringStorage space. var contents: [UInt8] = [] contents.reserveCapacity(input.count) let repaired = transcode( input.makeIterator(), from: UTF16.self, to: UTF8.self, stoppingOnError: false, into: { contents.append($0) }) _internalInvariant(!repaired, "Error present") return contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) } } @inline(never) // slow path private static func _slowFromCodeUnits< Input: Collection, Encoding: Unicode.Encoding >( _ input: Input, encoding: Encoding.Type, repair: Bool ) -> (String, repairsMade: Bool)? where Input.Element == Encoding.CodeUnit { // TODO(String Performance): Attempt to form smol strings // TODO(String performance): Skip intermediary array, transcode directly // into a StringStorage space. var contents: [UInt8] = [] contents.reserveCapacity(input.underestimatedCount) let repaired = transcode( input.makeIterator(), from: Encoding.self, to: UTF8.self, stoppingOnError: false, into: { contents.append($0) }) guard repair || !repaired else { return nil } let str = contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) } return (str, repaired) } @usableFromInline @inline(never) // can't be inlined w/out breaking ABI @_specialize( where Input == UnsafeBufferPointer<UInt8>, Encoding == Unicode.ASCII) @_specialize( where Input == Array<UInt8>, Encoding == Unicode.ASCII) internal static func _fromCodeUnits< Input: Collection, Encoding: Unicode.Encoding >( _ input: Input, encoding: Encoding.Type, repair: Bool ) -> (String, repairsMade: Bool)? where Input.Element == Encoding.CodeUnit { guard _fastPath(encoding == Unicode.ASCII.self) else { return _slowFromCodeUnits(input, encoding: encoding, repair: repair) } // Helper to simplify early returns func resultOrSlow(_ resultOpt: String?) -> (String, repairsMade: Bool)? { guard let result = resultOpt else { return _slowFromCodeUnits(input, encoding: encoding, repair: repair) } return (result, repairsMade: false) } // Fast path for untyped raw storage and known stdlib types if let contigBytes = input as? _HasContiguousBytes, contigBytes._providesContiguousBytesNoCopy { return resultOrSlow(contigBytes.withUnsafeBytes { rawBufPtr in let buffer = UnsafeBufferPointer( start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self), count: rawBufPtr.count) return String._fromASCIIValidating(buffer) }) } // Fast path for user-defined Collections if let strOpt = input.withContiguousStorageIfAvailable({ (buffer: UnsafeBufferPointer<Input.Element>) -> String? in return String._fromASCIIValidating( UnsafeRawBufferPointer(buffer).bindMemory(to: UInt8.self)) }) { return resultOrSlow(strOpt) } return resultOrSlow(Array(input).withUnsafeBufferPointer { let buffer = UnsafeRawBufferPointer($0).bindMemory(to: UInt8.self) return String._fromASCIIValidating(buffer) }) } public // @testable static func _fromInvalidUTF16( _ utf16: UnsafeBufferPointer<UInt16> ) -> String { return String._fromCodeUnits(utf16, encoding: UTF16.self, repair: true)!.0 } @usableFromInline internal static func _fromSubstring( _ substring: __shared Substring ) -> String { if substring._offsetRange == substring.base._offsetRange { return substring.base } return String._copying(substring) } @_alwaysEmitIntoClient @inline(never) // slow-path internal static func _copying(_ str: String) -> String { return String._copying(str[...]) } @_alwaysEmitIntoClient @inline(never) // slow-path internal static func _copying(_ str: Substring) -> String { if _fastPath(str._wholeGuts.isFastUTF8) { return str._wholeGuts.withFastUTF8(range: str._offsetRange) { String._uncheckedFromUTF8($0) } } return Array(str.utf8).withUnsafeBufferPointer { String._uncheckedFromUTF8($0) } } }
904db8e1edc905e758806dd14009436f
29.99
80
0.665376
false
false
false
false
CodaFi/swift
refs/heads/main
test/Interpreter/function_metatypes.swift
apache-2.0
44
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test protocol ProtocolHasInOut { associatedtype Input typealias Mutator = (inout Input) -> () var f: Mutator { get } } // Emit type metadata for this struct's fields struct HasInOut<T> { var f: (inout T) -> () } struct HasInOutProtocol : ProtocolHasInOut { typealias Input = Int let f: (inout Input) -> () } func foo<T>(_ t: T.Type) -> Any { return { (x: T) -> Int in return 6060 } } var i = 0 // Dynamic casting var f = foo((Int, Int).self) var g = f as! ((Int, Int)) -> Int print(g((1010, 2020))) // CHECK: 6060 // Struct with InOut let hio = HasInOut(f: { (x: inout Int) in x = 3030 }) i = 0 hio.f(&i) print(i) // CHECK: 3030 // Struct that conforms to Protocol with InOut let hiop = HasInOutProtocol(f: { (x: inout Int) in x = 4040 }) i = 0 hiop.f(&i) print(i) // CHECK: 4040 func fooInOut<T>(_ t: T.Type) -> Any { return { (x: inout T) -> () in x = unsafeBitCast((8080, 9090), to: T.self) } } var fio = fooInOut((Int, Int).self) var gio = fio as! (inout (Int, Int)) -> () var xy = (0, 0) gio(&xy) print(xy) // CHECK: (8080, 9090)
0a3042a39950035ad41a74259c0d3f1d
19.618182
78
0.612875
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Video/VideoEditorViewController+Request.swift
mit
1
// // VideoEditorViewController+Request.swift // HXPHPicker // // Created by Slience on 2021/8/6. // import UIKit import AVKit import Photos // MARK: PhotoAsset Request AVAsset extension VideoEditorViewController { #if HXPICKER_ENABLE_PICKER func requestAVAsset() { if photoAsset.isNetworkAsset { pNetworkVideoURL = photoAsset.networkVideoAsset?.videoURL downloadNetworkVideo() return } let loadingView = ProgressHUD.showLoading(addedTo: view, text: nil, animated: true) view.bringSubviewToFront(topView) assetRequestID = photoAsset.requestAVAsset( filterEditor: true, deliveryMode: .highQualityFormat ) { [weak self] (photoAsset, requestID) in self?.assetRequestID = requestID loadingView?.mode = .circleProgress loadingView?.text = "正在同步iCloud".localized + "..." } progressHandler: { (photoAsset, progress) in if progress > 0 { loadingView?.progress = CGFloat(progress) } } success: { [weak self] (photoAsset, avAsset, info) in ProgressHUD.hide(forView: self?.view, animated: false) self?.pAVAsset = avAsset self?.avassetLoadValuesAsynchronously() // self?.reqeustAssetCompletion = true // self?.assetRequestComplete() } failure: { [weak self] (photoAsset, info, error) in if let info = info, !info.isCancel { ProgressHUD.hide(forView: self?.view, animated: false) if info.inICloud { self?.assetRequestFailure(message: "iCloud同步失败".localized) }else { self?.assetRequestFailure() } } } } #endif func assetRequestFailure(message: String = "视频获取失败!".localized) { PhotoTools.showConfirm( viewController: self, title: "提示".localized, message: message, actionTitle: "确定".localized ) { (alertAction) in self.backAction() } } func assetRequestComplete() { let image = PhotoTools.getVideoThumbnailImage(avAsset: avAsset, atTime: 0.1) filterImageHandler(image: image) videoSize = image?.size ?? view.size coverImage = image videoView.setAVAsset(avAsset, coverImage: image ?? .init()) cropView.avAsset = avAsset if orientationDidChange { setCropViewFrame() } if !videoInitializeCompletion { setEditedSizeData() videoInitializeCompletion = true } if transitionCompletion { setAsset() } } func setEditedSizeData() { if let sizeData = editResult?.sizeData { videoView.setVideoEditedData(editedData: sizeData) brushColorView.canUndo = videoView.canUndoDraw if let stickerData = sizeData.stickerData { musicView.showLyricButton.isSelected = stickerData.showLyric if stickerData.showLyric { otherMusic = stickerData.items[stickerData.LyricIndex].item.music } } } } func setAsset() { if setAssetCompletion { return } videoView.playerView.configAsset() if let editResult = editResult { hasOriginalSound = editResult.hasOriginalSound if hasOriginalSound { videoVolume = editResult.videoSoundVolume }else { videoView.playerView.player.volume = 0 } volumeView.originalVolume = videoVolume musicView.originalSoundButton.isSelected = hasOriginalSound if let audioURL = editResult.backgroundMusicURL { backgroundMusicPath = audioURL.path musicView.backgroundButton.isSelected = true PhotoManager.shared.playMusic(filePath: audioURL.path) { } videoView.imageResizerView.imageView.stickerView.audioView?.contentView.startTimer() backgroundMusicVolume = editResult.backgroundMusicVolume volumeView.musicVolume = backgroundMusicVolume } if !orientationDidChange && editResult.cropData != nil { videoView.playerView.resetPlay() startPlayTimer() } if let videoFilter = editResult.sizeData?.filter, config.filter.isLoadLastFilter, videoFilter.index < config.filter.infos.count { let filterInfo = config.filter.infos[videoFilter.index] videoView.playerView.setFilter(filterInfo, value: videoFilter.value) } videoView.imageResizerView.videoFilter = editResult.sizeData?.filter } setAssetCompletion = true } func filterImageHandler(image: UIImage?) { guard let image = image else { return } var hasFilter = false var thumbnailImage: UIImage? for option in config.toolView.toolOptions where option.type == .filter { hasFilter = true } if hasFilter { DispatchQueue.global().async { thumbnailImage = image.scaleToFillSize( size: CGSize(width: 80, height: 80), equalRatio: true ) if thumbnailImage == nil { thumbnailImage = image } DispatchQueue.main.async { self.filterView.image = thumbnailImage } } } } } // MARK: DownloadNetworkVideo extension VideoEditorViewController { func downloadNetworkVideo() { if let videoURL = networkVideoURL { let key = videoURL.absoluteString if PhotoTools.isCached(forVideo: key) { let localURL = PhotoTools.getVideoCacheURL(for: key) pAVAsset = AVAsset.init(url: localURL) avassetLoadValuesAsynchronously() return } loadingView = ProgressHUD.showLoading(addedTo: view, text: "视频下载中".localized, animated: true) view.bringSubviewToFront(topView) PhotoManager.shared.downloadTask( with: videoURL ) { [weak self] (progress, task) in if progress > 0 { self?.loadingView?.mode = .circleProgress self?.loadingView?.progress = CGFloat(progress) } } completionHandler: { [weak self] (url, error, _) in if let url = url { #if HXPICKER_ENABLE_PICKER if let photoAsset = self?.photoAsset { photoAsset.networkVideoAsset?.fileSize = url.fileSize } #endif self?.loadingView = nil ProgressHUD.hide(forView: self?.view, animated: false) self?.pAVAsset = AVAsset(url: url) self?.avassetLoadValuesAsynchronously() }else { if let error = error as NSError?, error.code == NSURLErrorCancelled { return } self?.loadingView = nil ProgressHUD.hide(forView: self?.view, animated: false) self?.assetRequestFailure() } } } } func avassetLoadValuesAsynchronously() { avAsset.loadValuesAsynchronously( forKeys: ["duration"] ) { [weak self] in guard let self = self else { return } DispatchQueue.main.async { if self.avAsset.statusOfValue(forKey: "duration", error: nil) != .loaded { self.assetRequestFailure() return } self.reqeustAssetCompletion = true self.assetRequestComplete() } } } }
2f33843e4ae84d99fa8becaaaa5f4b02
36.513761
105
0.553558
false
false
false
false
iostalks/SFBlogDemo
refs/heads/master
UICollectionViewBug/BugTest/ViewController.swift
mit
1
// // ViewController.swift // BugTest // // Created by bong on 2017/10/23. // Copyright © 2017年 Smallfly. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var player: AVPlayer? override func viewDidLoad() { super.viewDidLoad() let url = URL(fileURLWithPath: LocalFile.LandingVedio.path()) player = AVPlayer(url: url) NotificationCenter.default.addObserver( self, selector: #selector(playToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) player?.play() } @objc func playToEnd(_ notification: Notification) { print("play to end") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var filp: UIButton! @IBAction func flip(_ sender: Any) { let collectionview = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "CollectionViewController") UIApplication.shared.keyWindow?.rootViewController = collectionview } } enum LocalFile: String { case LandingVedio = "LandingMV" func path() -> String { return Bundle.main.path(forResource: self.rawValue, ofType: "mp4")! } }
2d8ca9bfaf47daff7f4a8268d95e872f
25.75
142
0.65287
false
false
false
false
arthurschiller/ARKit-LeapMotion
refs/heads/master
iOS App/UI Components/Materials/MetalMaterial.swift
mit
1
// // MetalMaterial.swift // iOS App // // Created by Arthur Schiller on 20.08.17. // import Foundation import SceneKit class MetalMaterial: SCNMaterial { enum SurfaceType { case streaked case greasy } var surfaceType: SurfaceType = .streaked override func awakeFromNib() { super.awakeFromNib() commonInit() } init(surfaceType: SurfaceType) { super.init() self.surfaceType = surfaceType commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { lightingModel = SCNMaterial.LightingModel.physicallyBased set(surfaceType: surfaceType) } private func set(surfaceType: SurfaceType) { switch surfaceType { case .streaked: diffuse.contents = UIImage(named: "streakedMetal-albedo") roughness.contents = UIImage(named: "streakedMetal-roughness") metalness.contents = UIImage(named: "streakedMetal-metalness") case .greasy: diffuse.contents = UIImage(named: "greasyMetal-albedo") roughness.contents = UIImage(named: "greasyMetal-roughness") metalness.contents = UIImage(named: "greasyMetal-metalness") normal.contents = UIImage(named: "greasyMetal-normal") } } }
41792a9915b37545b092fb05b297e008
25.849057
74
0.621223
false
false
false
false
Chaosspeeder/YourGoals
refs/heads/master
YourGoals/Business/DataSource/ActionableTimeInfo.swift
lgpl-3.0
1
// // StartingTimeInfo.swift // YourGoals // // Created by André Claaßen on 22.06.19. // Copyright © 2019 André Claaßen. All rights reserved. // import Foundation /// a calculated time info with starting, end time and an indicator if this time is in a conflicting state struct ActionableTimeInfo:Equatable, ActionableItem { /// state of this item /// /// - open: the task is open but not progressing /// - progressing: the task is currently progressing /// - done: the task is done /// - progress: this is a done task progress entry enum State { case open case progressing case progress case done func asString() -> String { switch self { case .progress: return "Progress" case .progressing: return "Progressing" case .open: return "Open" case .done: return "Done" } } } /// the estimated starting time (not date) of an actionable let startingTime:Date /// the estimated ending time let endingTime:Date /// the estimated time left for the task as a timeinterval let estimatedLength:TimeInterval /// the start of this time is in danger cause of the previous task is being late let conflicting: Bool /// indicator, if the starting time is fixed let fixedStartingTime: Bool /// the actionable for this time info let actionable:Actionable /// an optional progress, if this time info is corresponding with a done task progress let progress:TaskProgress? /// calculate the state for the time info /// /// - Parameter forDate: the date/time for the calculating /// - Returns: a state func state(forDate date: Date) -> State { if progress != nil { return .progress } if actionable.isProgressing(atDate: date) { return .progressing } let actionableState = actionable.checkedState(forDate: date) switch actionableState { case .active: return .open case .done: return .done } } static func == (lhs: ActionableTimeInfo, rhs: ActionableTimeInfo) -> Bool { return lhs.startingTime == rhs.startingTime && lhs.endingTime == rhs.endingTime && lhs.estimatedLength == rhs.estimatedLength && lhs.actionable.name == rhs.actionable.name } /// initalize this time info /// /// - Parameters: /// - start: starting time /// - estimatedLength: remaining time /// - conflicting: actionable is conflicting with another actionable /// - fixed: indicator if starting time is fixed init(start:Date, end:Date, remainingTimeInterval:TimeInterval, conflicting: Bool, fixed: Bool, actionable: Actionable, progress: TaskProgress? = nil) { self.startingTime = start.extractTime() self.endingTime = end.extractTime() self.estimatedLength = remainingTimeInterval self.conflicting = conflicting self.fixedStartingTime = fixed self.actionable = actionable self.progress = progress } }
2869fdc7491507e4f84d7fbf82af9861
30.715686
155
0.616692
false
false
false
false
mkrisztian95/iOS
refs/heads/master
Pods/MaterialKit/Source/MKLabel.swift
apache-2.0
2
// // MKLabel.swift // MaterialKit // // Created by Le Van Nghia on 11/29/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit public class MKLabel: UILabel { @IBInspectable public var maskEnabled: Bool = true { didSet { mkLayer.maskEnabled = maskEnabled } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { self.layer.cornerRadius = self.cornerRadius mkLayer.superLayerDidResize() } } @IBInspectable public var elevation: CGFloat = 0 { didSet { mkLayer.elevation = elevation } } @IBInspectable override public var shadowOffset: CGSize { didSet { mkLayer.shadowOffset = shadowOffset } } @IBInspectable public var roundingCorners: UIRectCorner = UIRectCorner.AllCorners { didSet { mkLayer.roundingCorners = roundingCorners } } @IBInspectable public var rippleEnabled: Bool = true { didSet { mkLayer.rippleEnabled = rippleEnabled } } @IBInspectable public var rippleDuration: CFTimeInterval = 0.35 { didSet { mkLayer.rippleDuration = rippleDuration } } @IBInspectable public var rippleScaleRatio: CGFloat = 1.0 { didSet { mkLayer.rippleScaleRatio = rippleScaleRatio } } @IBInspectable public var rippleLayerColor: UIColor = UIColor(hex: 0xEEEEEE) { didSet { mkLayer.setRippleColor(rippleLayerColor) } } @IBInspectable public var backgroundAnimationEnabled: Bool = true { didSet { mkLayer.backgroundAnimationEnabled = backgroundAnimationEnabled } } override public var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } private lazy var mkLayer: MKLayer = MKLayer(withView: self) required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayer() } override public init(frame: CGRect) { super.init(frame: frame) setupLayer() } // MARK: Setup private func setupLayer() { mkLayer.elevation = self.elevation self.layer.cornerRadius = self.cornerRadius mkLayer.elevationOffset = self.shadowOffset mkLayer.roundingCorners = self.roundingCorners mkLayer.maskEnabled = self.maskEnabled mkLayer.rippleScaleRatio = self.rippleScaleRatio mkLayer.rippleDuration = self.rippleDuration mkLayer.rippleEnabled = self.rippleEnabled mkLayer.backgroundAnimationEnabled = self.backgroundAnimationEnabled mkLayer.setRippleColor(self.rippleLayerColor) } // MARK: Touch public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) mkLayer.touchesBegan(touches, withEvent: event) } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) mkLayer.touchesEnded(touches, withEvent: event) } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) mkLayer.touchesCancelled(touches, withEvent: event) } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) mkLayer.touchesMoved(touches, withEvent: event) } }
b64eff0ca534ca5bf7ba7bee58e39eda
30.513043
94
0.648455
false
false
false
false
mooneywang/MJCompatible
refs/heads/master
MJCompatible/MJCompatible/NSData+Compat.swift
mit
1
// // Data+Compat.swift // MJCompatible // // Created by Panda on 2017/7/26. // Copyright © 2017年 MooneyWang. All rights reserved. // import Foundation private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8] private let jpgHeaderIF: [UInt8] = [0xFF] private let gifHeader: [UInt8] = [0x47, 0x49, 0x46] enum ImageFormat { case Unknown, PNG, JPEG, GIF } extension NSData: MJCompatible {} extension Compat where Base: NSData { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) base.getBytes(&buffer, length: 8) if buffer == pngHeader { return .PNG } else if buffer[0] == jpgHeaderSOI[0] && buffer[1] == jpgHeaderSOI[1] && buffer[2] == jpgHeaderIF[0] { return .JPEG } else if buffer[0] == gifHeader[0] && buffer[1] == gifHeader[1] && buffer[2] == gifHeader[2] { return .GIF } return .Unknown } }
3fdd9e99b4e8c698af69f6ac743efef8
26.025641
81
0.585389
false
false
false
false
sarahspins/Loop
refs/heads/master
Loop/Managers/StatusChartManager.swift
apache-2.0
1
// // Chart.swift // Naterade // // Created by Nathan Racklyeft on 2/19/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import CarbKit import GlucoseKit import HealthKit import InsulinKit import LoopKit import SwiftCharts final class StatusChartsManager { // MARK: - Configuration private lazy var chartSettings: ChartSettings = { let chartSettings = ChartSettings() chartSettings.top = 12 chartSettings.bottom = 0 chartSettings.trailing = 8 chartSettings.axisTitleLabelsToLabelsSpacing = 0 chartSettings.labelsToAxisSpacingX = 6 chartSettings.labelsWidthY = 30 return chartSettings }() private lazy var dateFormatter: NSDateFormatter = { let timeFormatter = NSDateFormatter() timeFormatter.dateStyle = .NoStyle timeFormatter.timeStyle = .ShortStyle return timeFormatter }() private lazy var decimalFormatter: NSNumberFormatter = { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .DecimalStyle numberFormatter.minimumFractionDigits = 2 numberFormatter.maximumFractionDigits = 2 return numberFormatter }() private lazy var integerFormatter: NSNumberFormatter = { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .NoStyle numberFormatter.maximumFractionDigits = 0 return numberFormatter }() private lazy var axisLineColor = UIColor.clearColor() private lazy var axisLabelSettings = ChartLabelSettings(font: UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1), fontColor: UIColor.secondaryLabelColor) private lazy var guideLinesLayerSettings = ChartGuideLinesLayerSettings(linesColor: UIColor.gridColor) var panGestureRecognizer: UIPanGestureRecognizer? // MARK: - Data var startDate = NSDate() var glucoseUnit: HKUnit = HKUnit.milligramsPerDeciliterUnit() var glucoseTargetRangeSchedule: GlucoseRangeSchedule? var glucoseValues: [GlucoseValue] = [] { didSet { let unitString = glucoseUnit.glucoseUnitDisplayString glucosePoints = glucoseValues.map { return ChartPoint( x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter), y: ChartAxisValueDoubleUnit($0.quantity.doubleValueForUnit(glucoseUnit), unitString: unitString) ) } } } var predictedGlucoseValues: [GlucoseValue] = [] { didSet { let unitString = glucoseUnit.glucoseUnitDisplayString predictedGlucosePoints = predictedGlucoseValues.map { return ChartPoint( x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter), y: ChartAxisValueDoubleUnit($0.quantity.doubleValueForUnit(glucoseUnit), unitString: unitString, formatter: integerFormatter) ) } } } var IOBValues: [InsulinValue] = [] { didSet { IOBPoints = IOBValues.map { return ChartPoint( x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter), y: ChartAxisValueDoubleUnit($0.value, unitString: "U", formatter: decimalFormatter) ) } } } var COBValues: [CarbValue] = [] { didSet { let unit = HKUnit.gramUnit() let unitString = unit.unitString COBPoints = COBValues.map { ChartPoint( x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter), y: ChartAxisValueDoubleUnit($0.quantity.doubleValueForUnit(unit), unitString: unitString, formatter: integerFormatter) ) } } } var doseEntries: [DoseEntry] = [] { didSet { dosePoints = doseEntries.reduce([], combine: { (points, entry) -> [ChartPoint] in if entry.unit == .unitsPerHour { let startX = ChartAxisValueDate(date: entry.startDate, formatter: dateFormatter) let endX = ChartAxisValueDate(date: entry.endDate, formatter: dateFormatter) let zero = ChartAxisValueInt(0) let value = ChartAxisValueDoubleLog(actualDouble: entry.value, unitString: "U/hour", formatter: decimalFormatter) let newPoints = [ ChartPoint(x: startX, y: zero), ChartPoint(x: startX, y: value), ChartPoint(x: endX, y: value), ChartPoint(x: endX, y: zero) ] return points + newPoints } else { return points } }) } } // MARK: - State private var glucosePoints: [ChartPoint] = [] { didSet { glucoseChart = nil xAxisValues = nil } } private var predictedGlucosePoints: [ChartPoint] = [] { didSet { glucoseChart = nil xAxisValues = nil } } private var targetGlucosePoints: [ChartPoint] = [] { didSet { glucoseChart = nil } } private var targetOverridePoints: [ChartPoint] = [] { didSet { glucoseChart = nil } } private var targetOverrideDurationPoints: [ChartPoint] = [] { didSet { glucoseChart = nil } } private var IOBPoints: [ChartPoint] = [] { didSet { IOBChart = nil xAxisValues = nil } } private var COBPoints: [ChartPoint] = [] { didSet { COBChart = nil xAxisValues = nil } } private var dosePoints: [ChartPoint] = [] { didSet { doseChart = nil xAxisValues = nil } } private var xAxisValues: [ChartAxisValue]? { didSet { if let xAxisValues = xAxisValues { xAxisModel = ChartAxisModel(axisValues: xAxisValues, lineColor: axisLineColor) } else { xAxisModel = nil } } } private var xAxisModel: ChartAxisModel? private var glucoseChart: Chart? private var IOBChart: Chart? private var COBChart: Chart? private var doseChart: Chart? private var glucoseChartCache: ChartPointsTouchHighlightLayerViewCache? private var IOBChartCache: ChartPointsTouchHighlightLayerViewCache? private var COBChartCache: ChartPointsTouchHighlightLayerViewCache? private var doseChartCache: ChartPointsTouchHighlightLayerViewCache? // MARK: - Generators func glucoseChartWithFrame(frame: CGRect) -> Chart? { if let chart = glucoseChart where chart.frame != frame { self.glucoseChart = nil } if glucoseChart == nil { glucoseChart = generateGlucoseChartWithFrame(frame) } return glucoseChart } private func generateGlucoseChartWithFrame(frame: CGRect) -> Chart? { guard glucosePoints.count > 1, let xAxisModel = xAxisModel else { return nil } let allPoints = glucosePoints + predictedGlucosePoints let yAxisValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(allPoints + targetGlucosePoints + targetOverridePoints, minSegmentCount: 2, maxSegmentCount: 4, multiple: glucoseUnit.glucoseUnitYAxisSegmentSize, axisValueGenerator: { ChartAxisValueDouble($0, labelSettings: self.axisLabelSettings) }, addPaddingSegmentIfEdge: true ) let yAxisModel = ChartAxisModel(axisValues: yAxisValues, lineColor: axisLineColor) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: frame, xModel: xAxisModel, yModel: yAxisModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) // The glucose targets var targetLayer: ChartPointsAreaLayer? = nil if targetGlucosePoints.count > 1 { let alpha: CGFloat = targetOverridePoints.count > 1 ? 0.15 : 0.3 targetLayer = ChartPointsAreaLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: targetGlucosePoints, areaColor: UIColor.glucoseTintColor.colorWithAlphaComponent(alpha), animDuration: 0, animDelay: 0, addContainerPoints: false) } var targetOverrideLayer: ChartPointsAreaLayer? = nil if targetOverridePoints.count > 1 { targetOverrideLayer = ChartPointsAreaLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: targetOverridePoints, areaColor: UIColor.glucoseTintColor.colorWithAlphaComponent(0.3), animDuration: 0, animDelay: 0, addContainerPoints: false) } var targetOverrideDurationLayer: ChartPointsAreaLayer? = nil if targetOverrideDurationPoints.count > 1 { targetOverrideDurationLayer = ChartPointsAreaLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: targetOverrideDurationPoints, areaColor: UIColor.glucoseTintColor.colorWithAlphaComponent(0.3), animDuration: 0, animDelay: 0, addContainerPoints: false) } let gridLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: .XAndY, settings: guideLinesLayerSettings, onlyVisibleX: true, onlyVisibleY: false) let circles = ChartPointsScatterCirclesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: glucosePoints, displayDelay: 0, itemSize: CGSize(width: 4, height: 4), itemFillColor: UIColor.glucoseTintColor) var prediction: ChartLayer? if predictedGlucosePoints.count > 1 { prediction = ChartPointsScatterCirclesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: predictedGlucosePoints, displayDelay: 0, itemSize: CGSize(width: 2, height: 2), itemFillColor: UIColor.glucoseTintColor.colorWithAlphaComponent(0.75)) } glucoseChartCache = ChartPointsTouchHighlightLayerViewCache( xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: allPoints, tintColor: UIColor.glucoseTintColor, labelCenterY: chartSettings.top, gestureRecognizer: panGestureRecognizer ) let layers: [ChartLayer?] = [ gridLayer, targetLayer, targetOverrideLayer, targetOverrideDurationLayer, xAxis, yAxis, glucoseChartCache?.highlightLayer, prediction, circles ] return Chart(frame: frame, layers: layers.flatMap { $0 }) } func IOBChartWithFrame(frame: CGRect) -> Chart? { if let chart = IOBChart where chart.frame != frame { self.IOBChart = nil } if IOBChart == nil { IOBChart = generateIOBChartWithFrame(frame) } return IOBChart } private func generateIOBChartWithFrame(frame: CGRect) -> Chart? { guard IOBPoints.count > 1, let xAxisModel = xAxisModel else { return nil } var containerPoints = IOBPoints // Create a container line at 0 if let first = IOBPoints.first { containerPoints.insert(ChartPoint(x: first.x, y: ChartAxisValueInt(0)), atIndex: 0) } if let last = IOBPoints.last { containerPoints.append(ChartPoint(x: last.x, y: ChartAxisValueInt(0))) } let yAxisValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(IOBPoints, minSegmentCount: 2, maxSegmentCount: 3, multiple: 0.5, axisValueGenerator: { ChartAxisValueDouble($0, labelSettings: self.axisLabelSettings) }, addPaddingSegmentIfEdge: false) let yAxisModel = ChartAxisModel(axisValues: yAxisValues, lineColor: axisLineColor) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: frame, xModel: xAxisModel, yModel: yAxisModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) // The IOB area let lineModel = ChartLineModel(chartPoints: IOBPoints, lineColor: UIColor.IOBTintColor, lineWidth: 2, animDuration: 0, animDelay: 0) let IOBLine = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) let IOBArea = ChartPointsAreaLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: containerPoints, areaColor: UIColor.IOBTintColor.colorWithAlphaComponent(0.5), animDuration: 0, animDelay: 0, addContainerPoints: false) // Grid lines let gridLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: .XAndY, settings: guideLinesLayerSettings, onlyVisibleX: true, onlyVisibleY: false) // 0-line let dummyZeroChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0)) let zeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let width: CGFloat = 0.5 let viewFrame = CGRectMake(innerFrame.origin.x, chartPointModel.screenLoc.y - width / 2, innerFrame.size.width, width) let v = UIView(frame: viewFrame) v.backgroundColor = UIColor.IOBTintColor return v }) IOBChartCache = ChartPointsTouchHighlightLayerViewCache( xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: IOBPoints, tintColor: UIColor.IOBTintColor, labelCenterY: chartSettings.top, gestureRecognizer: panGestureRecognizer ) let layers: [ChartLayer?] = [ gridLayer, xAxis, yAxis, zeroGuidelineLayer, IOBChartCache?.highlightLayer, IOBArea, IOBLine, ] return Chart(frame: frame, layers: layers.flatMap { $0 }) } func COBChartWithFrame(frame: CGRect) -> Chart? { if let chart = COBChart where chart.frame != frame { self.COBChart = nil } if COBChart == nil { COBChart = generateCOBChartWithFrame(frame) } return COBChart } private func generateCOBChartWithFrame(frame: CGRect) -> Chart? { guard COBPoints.count > 1, let xAxisModel = xAxisModel else { return nil } var containerPoints = COBPoints // Create a container line at 0 if let first = COBPoints.first { containerPoints.insert(ChartPoint(x: first.x, y: ChartAxisValueInt(0)), atIndex: 0) } if let last = COBPoints.last { containerPoints.append(ChartPoint(x: last.x, y: ChartAxisValueInt(0))) } let yAxisValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(COBPoints, minSegmentCount: 2, maxSegmentCount: 3, multiple: 10, axisValueGenerator: { ChartAxisValueDouble($0, labelSettings: self.axisLabelSettings) }, addPaddingSegmentIfEdge: false) let yAxisModel = ChartAxisModel(axisValues: yAxisValues, lineColor: axisLineColor) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: frame, xModel: xAxisModel, yModel: yAxisModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) // The COB area let lineModel = ChartLineModel(chartPoints: COBPoints, lineColor: UIColor.COBTintColor, lineWidth: 2, animDuration: 0, animDelay: 0) let COBLine = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) let COBArea = ChartPointsAreaLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: containerPoints, areaColor: UIColor.COBTintColor.colorWithAlphaComponent(0.5), animDuration: 0, animDelay: 0, addContainerPoints: false) // Grid lines let gridLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: .XAndY, settings: guideLinesLayerSettings, onlyVisibleX: true, onlyVisibleY: false) COBChartCache = ChartPointsTouchHighlightLayerViewCache( xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: COBPoints, tintColor: UIColor.COBTintColor, labelCenterY: chartSettings.top, gestureRecognizer: panGestureRecognizer ) let layers: [ChartLayer?] = [ gridLayer, xAxis, yAxis, COBChartCache?.highlightLayer, COBArea, COBLine ] return Chart(frame: frame, layers: layers.flatMap { $0 }) } func doseChartWithFrame(frame: CGRect) -> Chart? { if let chart = doseChart where chart.frame != frame { self.doseChart = nil } if doseChart == nil { doseChart = generateDoseChartWithFrame(frame) } return doseChart } private func generateDoseChartWithFrame(frame: CGRect) -> Chart? { guard dosePoints.count > 1, let xAxisModel = xAxisModel else { return nil } let yAxisValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(dosePoints, minSegmentCount: 2, maxSegmentCount: 3, multiple: log10(2) / 2, axisValueGenerator: { ChartAxisValueDoubleLog(screenLocDouble: $0, formatter: self.integerFormatter, labelSettings: self.axisLabelSettings) }, addPaddingSegmentIfEdge: true) let yAxisModel = ChartAxisModel(axisValues: yAxisValues, lineColor: axisLineColor) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: frame, xModel: xAxisModel, yModel: yAxisModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) // The dose area let lineModel = ChartLineModel(chartPoints: dosePoints, lineColor: UIColor.doseTintColor, lineWidth: 2, animDuration: 0, animDelay: 0) let doseLine = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) let doseArea = ChartPointsAreaLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: dosePoints, areaColor: UIColor.doseTintColor.colorWithAlphaComponent(0.5), animDuration: 0, animDelay: 0, addContainerPoints: false) // Grid lines let gridLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: .XAndY, settings: guideLinesLayerSettings, onlyVisibleX: true, onlyVisibleY: false) // 0-line let dummyZeroChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0)) let zeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let width: CGFloat = 1 let viewFrame = CGRectMake(innerFrame.origin.x, chartPointModel.screenLoc.y - width / 2, innerFrame.size.width, width) let v = UIView(frame: viewFrame) v.backgroundColor = UIColor.doseTintColor return v }) doseChartCache = ChartPointsTouchHighlightLayerViewCache( xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: dosePoints.filter { $0.y.scalar != 0 }, tintColor: UIColor.doseTintColor, labelCenterY: chartSettings.top, gestureRecognizer: panGestureRecognizer ) let layers: [ChartLayer?] = [ gridLayer, xAxis, yAxis, zeroGuidelineLayer, doseChartCache?.highlightLayer, doseArea, doseLine ] return Chart(frame: frame, layers: layers.flatMap { $0 }) } private func generateXAxisValues() { let points = glucosePoints + predictedGlucosePoints + IOBPoints + COBPoints + dosePoints guard points.count > 1 else { self.xAxisValues = [] return } let timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "h a" let minDate = startDate let xAxisValues = ChartAxisValuesGenerator.generateXAxisValuesWithChartPoints(points, minSegmentCount: 5, maxSegmentCount: 10, multiple: NSTimeInterval(hours: 1), axisValueGenerator: { ChartAxisValueDate(date: max(minDate, ChartAxisValueDate.dateFromScalar($0)), formatter: timeFormatter, labelSettings: self.axisLabelSettings) }, addPaddingSegmentIfEdge: false) xAxisValues.first?.hidden = true xAxisValues.last?.hidden = true self.xAxisValues = xAxisValues } func prerender() { glucoseChart = nil IOBChart = nil COBChart = nil generateXAxisValues() if let xAxisValues = xAxisValues where xAxisValues.count > 1, let targets = glucoseTargetRangeSchedule { targetGlucosePoints = ChartPoint.pointsForGlucoseRangeSchedule(targets, xAxisValues: xAxisValues) if let override = targets.temporaryOverride { targetOverridePoints = ChartPoint.pointsForGlucoseRangeScheduleOverride(override, xAxisValues: xAxisValues) targetOverrideDurationPoints = ChartPoint.pointsForGlucoseRangeScheduleOverrideDuration(override, xAxisValues: xAxisValues) } else { targetOverridePoints = [] targetOverrideDurationPoints = [] } } } } private extension HKUnit { var glucoseUnitYAxisSegmentSize: Double { if self == HKUnit.milligramsPerDeciliterUnit() { return 25 } else { return 1 } } }
61b5c0df433dba31984b20bf555dae06
36.626891
335
0.647713
false
false
false
false
pascaljette/PokeBattleDemo
refs/heads/master
PokeBattleDemo/PokeBattleDemo/PokeApi/Fetchers/MultiplePokemonTypeFetcher.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // 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 /// Delegate for a multiple pokemon type fetcher. protocol MultiplePokemonTypeFetcherDelegate: class { /// Called after the fetch operation has completed. /// /// - parameter fetcher: Reference on the fetcher that has completed the operation. /// - parameter success: True if the operation succeeded, false otherwise. /// - parameter result: The retrieved type array if successful, nil otherwise. /// - parameter error: Error object if the operation failed, nil if it succeeded. func didGetPokemonTypeArray(fetcher: MultiplePokemonTypeFetcher, success: Bool, result: [PokemonType]?, error: NSError?) } /// Only supports random fetching now. class MultiplePokemonTypeFetcher { // // MARK: Stored properties // /// Weak reference on the delegate. weak var delegate: MultiplePokemonTypeFetcherDelegate? /// Internal reference on pokemon type fetchers. References must be kept here /// so they don't get deallocated when they go out of function scope. private var pokemonTypeFetchers: [PokemonTypeFetcher] = [] /// Store the pokemon type identifiers from initialisation. private let pokemonTypeIdentifiers: [PokemonTypeIdentifier] /// Internal reference on the pokemon type array to pass to the delegate. private var pokemonTypeArray: [PokemonType]? /// Internal reference on the success flag to pass to the delegate. private var success: Bool = true /// Internal reference on the error object to pass to the delegate. private var error: NSError? /// Dispatch group for thread synchronisation. private let dispatchGroup = dispatch_group_create(); // // MARK: Initialization // /// Initialise with an array of pokemon type identifiers. A fetcher /// will be created for every single type identifier in the array. /// /// - parameter pokemonTypeIdentifiers: Array of type identifiers for which to retrieve detailed info. init(pokemonTypeIdentifiers: [PokemonTypeIdentifier]) { self.pokemonTypeIdentifiers = pokemonTypeIdentifiers } } extension MultiplePokemonTypeFetcher { // // MARK: Public functions // /// Fetch the data and calls the delegate on completion. func fetch() { resetResults() for typeIdentifier in self.pokemonTypeIdentifiers { let typeFetcher = PokemonTypeFetcher(pokemonTypeIdentifier: typeIdentifier) typeFetcher.delegate = self pokemonTypeFetchers.append(typeFetcher) dispatch_group_enter(dispatchGroup) typeFetcher.fetch() } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [weak self] in guard let strongSelf = self else { return } dispatch_group_wait(strongSelf.dispatchGroup, DISPATCH_TIME_FOREVER) strongSelf.delegate?.didGetPokemonTypeArray(strongSelf , success: strongSelf.success , result: strongSelf.pokemonTypeArray , error: strongSelf.error) } } } extension MultiplePokemonTypeFetcher : PokemonTypeFetcherDelegate { // // MARK: PokemonTypeFetcherDelegate implementation // /// Called after the fetch operation has completed. /// /// - parameter fetcher: Reference on the fetcher that has completed the operation. /// - parameter success: True if the operation succeeded, false otherwise. /// - parameter result: The retrieved type if successful, nil otherwise. /// - parameter error: Error object if the operation failed, nil if it succeeded. func didGetPokemonType(fetcher: PokemonTypeFetcher, success: Bool, result: PokemonType?, error: NSError?) { defer { dispatch_group_leave(dispatchGroup) pokemonTypeFetchers = pokemonTypeFetchers.filter( { $0 !== fetcher} ) } guard let pokemonTypeInstance = result where success == true else { self.success = false self.error = error self.pokemonTypeArray = nil return } if self.pokemonTypeArray == nil { self.pokemonTypeArray = [] } self.pokemonTypeArray!.append(pokemonTypeInstance) } } extension MultiplePokemonTypeFetcher { // // MARK: Private utility functions // /// Reset all previously obtained results private func resetResults() { pokemonTypeArray = nil success = true error = nil } }
445f003adbbb0bfd928b99a6196b7e01
33.761628
124
0.656632
false
false
false
false
KIPPapp/KIPPapp
refs/heads/master
GroupController.swift
mit
1
// // GroupController.swift // kippapp // // Created by Monika Gorkani on 10/11/14. // Copyright (c) 2014 kippgroup. All rights reserved. // import UIKit class GroupController: UIViewController, UITableViewDataSource, UITableViewDelegate { var groups: [String] = [] var studentGroups: Dictionary<Int, [String]> = Dictionary<Int, [String]>() var students:[Student] = [] var studentList:[Student] = [] let headers = [" Operations and Algebraic Thinking", " Complex Number Systems", " Geometry", " Statistics and probability"] as NSArray let colors = [ UIColor(red: 113/255, green: 169/255, blue: 219/255, alpha: 1.0), UIColor(red: 247/255, green: 174/255, blue: 90/255, alpha: 1.0), UIColor(red: 113/255, green: 169/255, blue: 219/255, alpha: 1.0), UIColor(red: 247/255, green: 174/255, blue: 90/255, alpha: 1.0) ] as NSArray func splitStudentsToGroups(studentInGroups: [String]) { var countInEachGroup = studentInGroups.count/4 var index_begin = 0 as Int var group_index = 0 as Int var index_end = countInEachGroup as Int while(index_end <= studentInGroups.count) { var temp: [String] = [] while(index_begin <= index_end-1) { temp.append(studentInGroups[index_begin]) index_begin += 1 } self.studentGroups[group_index] = temp temp.removeAll(keepCapacity: false) group_index += 1 index_end += countInEachGroup } } @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.opaque = true tableView.backgroundColor = UIColor(red: 239/255, green: 248/255, blue: 255/255, alpha: 1.0) tableView.separatorInset = UIEdgeInsetsMake (0, 15, 0,0); tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.estimatedRowHeight = 50 tableView.rowHeight = UITableViewAutomaticDimension self.view.showActivityViewWithLabel("Loading") //Get topics var parseAPI:ParseAPI = (self.tabBarController as KippAppController).parseAPI parseAPI.getStudentData("Mia Hamm", grade:"Secondary Intervention") { (students, groups, error) -> () in for group in groups! { self.groups.append(group) } self.groups.sort({$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending}) self.splitStudentsToGroups(self.groups) self.students = students! self.view.hideActivityView() self.tableView.reloadData() } // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return headers.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return studentGroups.count - 1 } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("GroupCell") as GroupCell var groupNames = self.studentGroups[indexPath.section] as Array! cell.selectionStyle = UITableViewCellSelectionStyle.None cell.groupName.text = groupNames[indexPath.row] cell.backgroundColor = colors[indexPath.section] as? UIColor return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var headerText = self.headers[section] as NSString return headerText } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var headerLabel = UILabel() headerLabel.font.fontWithSize(25) headerLabel.text = self.headers[section] as NSString headerLabel.textAlignment = NSTextAlignment.Natural headerLabel.textColor = UIColor(red: 59/255, green: 98/255, blue: 157/255, alpha: 1.0) return headerLabel } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let groupName = groups[indexPath.row] // find the students belonging to this group var studentList:[Student] = [] for student in self.students { if (student.groupName == groupName) { studentList.append(student) } } performSegueWithIdentifier("showMembers", sender: studentList) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "showMembers") { var indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()! let groupName = groups[indexPath.row] // find the students belonging to this group var studentList:[Student] = [] for student in self.students { if (student.groupName == groupName) { studentList.append(student) } } let navigationController = segue.destinationViewController as UINavigationController let detailViewController = navigationController.viewControllers[0] as StudentGroupViewController detailViewController.studentList = studentList var groupNames = self.studentGroups[indexPath.section] as Array! detailViewController.groupName = groupNames[indexPath.row] } } /* // 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. } */ }
d7ea8c150facf1fb3be25387e53af294
36.447514
188
0.638094
false
false
false
false
moonrailgun/OpenCode
refs/heads/master
OpenCode/Classes/OrgsDetail/View/OrgsDetailHeaderView.swift
gpl-2.0
1
// // OrgsDetailHeaderView.swift // OpenCode // // Created by 陈亮 on 16/6/27. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit import SwiftyJSON class OrgsDetailHeaderView: UIView { lazy var headerView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 180)) var avatar:UIImageView? var name:UILabel? var desc: UILabel? var followers:RepoInfoView? var following:RepoInfoView? /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ init(){ super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 230)) initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView(){ headerView.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1) self.avatar = UIImageView(frame: CGRect(x: headerView.frame.width/2-50, y: 10, width: 100, height: 100)) headerView.addSubview(avatar!) self.name = UILabel(frame: CGRect(x: 0, y: 110, width: headerView.frame.width, height: 40)) name!.textAlignment = .Center name!.textColor = UIColor.whiteColor() headerView.addSubview(name!) self.desc = UILabel(frame: CGRect(x: 0, y: 130, width: headerView.frame.width, height: 30)) name!.textAlignment = .Center name!.textColor = UIColor.whiteColor() headerView.addSubview(desc!) self.followers = RepoInfoView(frame: CGRectMake(0, headerView.frame.height, headerView.frame.width / 2, 40), name: "团队项目", value: 0) self.following = RepoInfoView(frame: CGRectMake(headerView.frame.width / 2, headerView.frame.height, headerView.frame.width / 2, 40), name: "代码片段", value: 0) self.addSubview(followers!) self.addSubview(following!) self.addSubview(headerView) } func setData(orgsData:JSON) { self.avatar?.sd_setImageWithURL(NSURL(string: orgsData["avatar_url"].string!)) self.name?.text = orgsData["login"].string! self.desc?.text = orgsData["description"].string! self.followers?.setValue(orgsData["public_repos"].int!) self.following?.setValue(orgsData["public_gists"].int!) } }
8bfd845346dd43bfc7ed49350473281b
33.902778
165
0.636291
false
false
false
false
lauraskelton/GPUImage
refs/heads/master
examples/iOS/FilterShowcaseSwift/FilterShowcaseSwift/FilterOperations.swift
bsd-3-clause
1
import Foundation import GPUImage import QuartzCore let filterOperations: Array<FilterOperation> = [ FilterOperation( listName:"Sepia tone", titleName:"Sepia Tone", sliderConfiguration:.Enabled(minimumValue:0.0, initialValue:1.0, maximumValue:1.0), sliderUpdateCallback: {(filter:GPUImageOutput, sliderValue:Float) in (filter as GPUImageSepiaFilter).intensity = CGFloat(sliderValue) // Why do I need to cast this for non-Simulator builds? That seems broken }, filterOperationType:.SingleInput(filter:GPUImageSepiaFilter()), customFilterSetupFunction: nil ), FilterOperation( listName:"Pixellate", titleName:"Pixellate", sliderConfiguration:.Enabled(minimumValue:0.0, initialValue:0.05, maximumValue:0.3), sliderUpdateCallback: {(filter:GPUImageOutput, sliderValue:Float) in (filter as GPUImagePixellateFilter).fractionalWidthOfAPixel = CGFloat(sliderValue) }, filterOperationType:.SingleInput(filter:GPUImagePixellateFilter()), customFilterSetupFunction: nil ), FilterOperation( listName:"Color invert", titleName:"Color Invert", sliderConfiguration:.Disabled, sliderUpdateCallback: nil, filterOperationType:.SingleInput(filter:GPUImageColorInvertFilter()), customFilterSetupFunction: nil ), FilterOperation( listName:"Transform (3-D)", titleName:"Transform (3-D)", sliderConfiguration:.Enabled(minimumValue:0.0, initialValue:0.75, maximumValue:6.28), sliderUpdateCallback:{(filter:GPUImageOutput, sliderValue:Float) in var perspectiveTransform = CATransform3DIdentity perspectiveTransform.m34 = 0.4 perspectiveTransform.m33 = 0.4 perspectiveTransform = CATransform3DScale(perspectiveTransform, 0.75, 0.75, 0.75) perspectiveTransform = CATransform3DRotate(perspectiveTransform, CGFloat(sliderValue), 0.0, 1.0, 0.0) (filter as GPUImageTransformFilter).transform3D = perspectiveTransform }, filterOperationType:.SingleInput(filter:GPUImageTransformFilter()), customFilterSetupFunction: nil ), FilterOperation( listName:"Sphere refraction", titleName:"Sphere Refraction", sliderConfiguration:.Enabled(minimumValue:0.0, initialValue:0.15, maximumValue:1.0), sliderUpdateCallback:{(filter:GPUImageOutput, sliderValue:Float) in (filter as GPUImageSphereRefractionFilter).radius = CGFloat(sliderValue) }, filterOperationType:.Custom, customFilterSetupFunction:{(camera:GPUImageVideoCamera, outputView:GPUImageView, blendImage:UIImage?) in let filter = GPUImageSphereRefractionFilter() camera.addTarget(filter) // Provide a blurred image for a cool-looking background let gaussianBlur = GPUImageGaussianBlurFilter() camera.addTarget(gaussianBlur) gaussianBlur.blurRadiusInPixels = 5.0 let blendFilter = GPUImageAlphaBlendFilter() blendFilter.mix = 1.0 gaussianBlur.addTarget(blendFilter) filter.addTarget(blendFilter) blendFilter.addTarget(outputView) return filter } ), ]
3a51d095d80fa896402e3d4026817e79
43.289474
150
0.679346
false
true
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_2_fixed/0001-rdar19792730.swift
apache-2.0
40
// RUN: %target-swift-frontend %s -emit-silgen // rdar://problem/19792730 public func foo< Expected : Sequence, Actual : Sequence, T : Comparable where Expected.Iterator.Element == Actual.Iterator.Element, Expected.Iterator.Element == T >(expected: Expected, actual: Actual) {} public func foo< Expected : Sequence, Actual : Sequence, T : Comparable where Expected.Iterator.Element == Actual.Iterator.Element, Expected.Iterator.Element == (T, T) >(expected: Expected, actual: Actual) {}
8ffd47c5166ed8ac820da71d0f49cbfb
22.409091
55
0.704854
false
false
false
false
bugitapp/bugit
refs/heads/master
bugit/Tools/PixelatedImageView.swift
apache-2.0
1
// // ShapeView.swift // bugit // // Created by Ernest on 11/20/16. // Copyright © 2016 BugIt App. All rights reserved. // import UIKit import AVFoundation class PixelatedImageView: UIView { var regionSize: CGSize = CGSize(width: 0, height: 0) var containerBounds: CGRect = CGRect.zero var fillColor: UIColor! var outlineColor: UIColor! var canvasImage: UIImage! init(frame: CGRect, image: UIImage, regionSize: CGSize, containerBounds: CGRect) { super.init(frame: frame) self.canvasImage = image self.regionSize = regionSize self.containerBounds = containerBounds self.outlineColor = UIColor.clear self.fillColor = UIColor.clear self.backgroundColor = UIColor.clear initGestureRecognizers() } func scaleImageToImageAspectFit() -> UIImage? { if let img = canvasImage { dlog("origImageSize: \(img.size)") let rect = AVMakeRect(aspectRatio: img.size, insideRect: containerBounds) dlog("scaledImageRect: \(rect)") let scaledImage = img.simpleScale(newSize: rect.size) dlog("scaledImage: \(scaledImage)") return scaledImage } return nil } func applyPixelation() { dlog("self.frame: \(self.frame), self.center: \(self.center)") let scaledRect = AVMakeRect(aspectRatio: canvasImage.size, insideRect: containerBounds) var cropRect = self.frame cropRect.origin.x -= scaledRect.origin.x let sectionImage = canvasImage.crop(bounds: cropRect) dlog("scaledSectionImage: \(sectionImage)") let pixelatedImage = sectionImage?.pixellated() let pixelatedImageView = UIImageView(image: pixelatedImage) pixelatedImageView.contentMode = .scaleAspectFit pixelatedImageView.tag = 99 if let v = self.viewWithTag(99) { dlog("last frame: \(v.frame), center: \(v.center)") v.removeFromSuperview() } self.addSubview(pixelatedImageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initGestureRecognizers() { let panGR = UIPanGestureRecognizer(target: self, action: #selector(didPan)) addGestureRecognizer(panGR) let pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(didPinch)) addGestureRecognizer(pinchGR) let rotationGR = UIRotationGestureRecognizer(target: self, action: #selector(didRotate)) addGestureRecognizer(rotationGR) } func pointFrom(angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint { return CGPoint(radius * cos(angle) + offset.x, radius * sin(angle) + offset.y) } func trianglePathInRect(rect:CGRect) -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint(rect.width / 2.0, rect.origin.y)) path.addLine(to: CGPoint(rect.width,rect.height)) path.addLine(to: CGPoint(rect.origin.x,rect.height)) path.close() return path } func didPan(_ sender: UIPanGestureRecognizer) { self.superview!.bringSubview(toFront: self) guard let canvas = self.canvasImage else { return } var translation = sender.translation(in: self) translation = translation.applying(self.transform) let scaledRect = AVMakeRect(aspectRatio: canvas.size, insideRect: containerBounds) let x:CGFloat = self.center.x - self.bounds.width/2.0 if x >= scaledRect.origin.x { self.applyPixelation() } else { if let v = self.viewWithTag(99) { dlog("last frame: \(v.frame), center: \(v.center)") v.removeFromSuperview() } } self.center.x += translation.x self.center.y += translation.y sender.setTranslation(CGPoint.zero, in: self) } func didPinch(_ sender: UIPinchGestureRecognizer) { self.superview!.bringSubview(toFront: self) let scale = sender.scale self.transform = self.transform.scaledBy(x: scale, y: scale) sender .scale = 1.0 } func didRotate(_ sender: UIRotationGestureRecognizer) { self.superview!.bringSubview(toFront: self) let rotation = sender.rotation self.transform = self.transform.rotated(by: rotation) sender.rotation = 0.0 } }
e8fb7e41e6d5a84a85b187d8d3f3e37a
29.541401
96
0.592701
false
false
false
false
mrdepth/eufe
refs/heads/master
swift-wrapper/DGMStructure.swift
lgpl-2.1
2
// // DGMStructure.swift // dgmpp // // Created by Artem Shimanski on 14.12.2017. // import Foundation import cwrapper public class DGMStructure: DGMShip { public convenience init(typeID: DGMTypeID) throws { guard let type = dgmpp_structure_create(dgmpp_type_id(typeID)) else { throw DGMError.typeNotFound(typeID)} self.init(type) } public convenience init(_ other: DGMStructure) { self.init(dgmpp_structure_copy(other.handle)) } public var fuelBlockTypeID: DGMTypeID { return DGMTypeID(dgmpp_structure_get_fuel_block_type_id(handle)) } public var fuelUse: DGMFuelUnitsPerHour { return DGMFuelUnitsPerHour(dgmpp_structure_get_fuel_use(handle)) } public var area: DGMArea? { get { guard let area = dgmpp_structure_get_area(handle) else {return nil} return DGMArea(area) } set { willChange() dgmpp_structure_set_area(handle, newValue?.handle) } } enum StructureCodingKeys: String, CodingKey { case area } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: StructureCodingKeys.self) try container.encodeIfPresent(area, forKey: .area) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let typeID = try container.decode(DGMTypeID.self, forKey: .typeID) guard let type = dgmpp_structure_create(dgmpp_type_id(typeID)) else { throw DGMError.typeNotFound(typeID)} super.init(type) try decodeLoadout(from: decoder) area = try decoder.container(keyedBy: StructureCodingKeys.self).decodeIfPresent(DGMArea.self, forKey: .area) } required init(_ handle: dgmpp_type) { super.init(handle) } }
6300eab558ab765cc9f086e8bbdc9317
26.863636
116
0.687874
false
false
false
false
FuckBoilerplate/RxCache
refs/heads/master
Examples/Pods/Gloss/Sources/ExtensionDictionary.swift
mit
1
// // ExtensionDictionary.swift // Gloss // // Copyright (c) 2015 Harlan Kellaway // // 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 extension Dictionary { // MARK: - Public functions /** Retrieves value from dictionary given a key path delimited with provided delimiter to indicate a nested value. For example, a dictionary with [ "outer" : [ "inner" : "value" ] ] could retrieve 'value' via path "outer.inner", given a delimiter of ''. - parameter keyPath: Key path delimited by delimiter. - parameter delimiter: Delimiter. - returns: Value retrieved from dic */ public func value(forKeyPath keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter) -> AnyObject? { let keys = keyPath.components(separatedBy: delimiter) guard let first = keys.first as? Key else { print("[Gloss] Unable to use keyPath '\(keyPath)' as key on type: \(Key.self)") return nil } guard let value = self[first] else { return nil } if keys.count > 1, let subDict = value as? JSON { let rejoined = keys[1..<keys.endIndex].joined(separator: delimiter) return subDict.value(forKeyPath: rejoined, withDelimiter: delimiter) } return value as AnyObject } // MARK: - Internal functions /** Creates a dictionary from a list of elements. This allows use of map, flatMap and filter. - parameter elements: Elements to add to the new dictionary. */ internal init(elements: [Element]) { self.init() for (key, value) in elements { self[key] = value } } /** Flat map for dictionary. - parameter transform: Transform function. - returns: New dictionary of transformed values. */ internal func flatMap<KeyPrime : Hashable, ValuePrime>(transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] { return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ (key, value) in return try transform(key, value) })) } /** Adds entries from provided dictionary to current dictionary. Note: If current dictionary and provided dictionary have the same key, the value from the provided dictionary overwrites current value. - parameter other: Dictionary to add entries from - parameter delimiter: Key path delimiter */ internal mutating func add(_ other: Dictionary, delimiter: String = GlossKeyPathDelimiter) -> () { for (key, value) in other { if let key = key as? String { self.setValue(valueToSet: value, forKeyPath: key, withDelimiter: delimiter) } else { self.updateValue(value, forKey:key) } } } // MARK: - Private functions /** Sets value for provided key path delimited by provided delimiter. - parameter valueToSet: Value to set - parameter keyPath: Key path. - parameter withDelimiter: Delimiter for key path. */ private mutating func setValue(valueToSet value: Any, forKeyPath keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter) { var keys = keyPath.components(separatedBy: delimiter) guard let first = keys.first as? Key else { print("[Gloss] Unable to use string as key on type: \(Key.self)") return } keys.remove(at: 0) if keys.isEmpty, let settable = value as? Value { self[first] = settable } else { let rejoined = keys.joined(separator: delimiter) var subdict: JSON = [ : ] if let sub = self[first] as? JSON { subdict = sub } subdict.setValue(valueToSet: value, forKeyPath: rejoined, withDelimiter: delimiter) if let settable = subdict as? Value { self[first] = settable } else { print("[Gloss] Unable to set value: \(subdict) to dictionary of type: \(type(of: self))") } } } }
7b5b43dfbe80ef64d2400e4f7659367e
34.096774
155
0.616176
false
false
false
false
TMTBO/TTAMusicPlayer
refs/heads/master
TTAMusicPlayer/TTAMusicPlayer/Classes/Player/Views/PlayerView.swift
mit
1
// // PlayerView.swift // MusicPlayer // // Created by ys on 16/11/23. // Copyright © 2016年 TobyoTenma. All rights reserved. // import UIKit let kICON_IMAGE_ROTATION_KEY = "iconImageViewRotation" @objc protocol PlayerViewDelegate: NSObjectProtocol { @objc optional func playerView(_ playerView : PlayerView, play : UIButton) @objc optional func playerView(_ playerView : PlayerView, pause: UIButton) @objc optional func playerView(_ playerView : PlayerView, next : UIButton) @objc optional func playerView(_ playerView : PlayerView, preview : UIButton) } class PlayerView: UIView { weak var delegate : PlayerViewDelegate? var playAndPauseButton : UIButton? = UIButton() var nextButton : UIButton? = UIButton() var previewButton : UIButton? = UIButton() var progressSlider : UISlider? = UISlider() var currentTimeLabel : UILabel? = UILabel() var durationTimeLabel : UILabel? = UILabel() var iconImageView : UIImageView? = UIImageView() var playNeedelImageView : UIImageView? = UIImageView() /// 更新播放器显示的最大时间 lazy var updateDurationTime : () -> Void = { _ in self.progressSlider?.maximumValue = PlayerManager.shared.durationTime self.durationTimeLabel?.text = PlayerManager.shared.durationTimeString } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } } extension PlayerView { func setupUI() { let blur = UIBlurEffect(style: .light) let blurView = UIVisualEffectView(effect: blur) // config blurView.frame = self.bounds configPlayButton() playAndPauseButton?.addTarget(self, action: #selector(didClickPlayAndPauseButton(sender:)), for: .touchUpInside) nextButton?.addTarget(self, action: #selector(didClickNextButton(sender:)), for: .touchUpInside) nextButton?.setImage(#imageLiteral(resourceName: "cm2_fm_btn_next"), for: .normal) nextButton?.setImage(#imageLiteral(resourceName: "cm2_fm_btn_next_prs"), for: .highlighted) previewButton?.addTarget(self, action: #selector(didClickPreviewButton(sender:)), for: .touchUpInside) previewButton?.setImage(#imageLiteral(resourceName: "cm2_play_btn_prev"), for: .normal) previewButton?.setImage(#imageLiteral(resourceName: "cm2_play_btn_prev_prs"), for: .highlighted) currentTimeLabel?.font = UIFont.systemFont(ofSize: 15 * kSCALEP) currentTimeLabel?.textAlignment = .center currentTimeLabel?.text = kNONE_TIME durationTimeLabel?.font = UIFont.systemFont(ofSize: 15 * kSCALEP) durationTimeLabel?.textAlignment = .center durationTimeLabel?.text = kNONE_TIME progressSlider?.setMinimumTrackImage(#imageLiteral(resourceName: "cm2_fm_playbar_curr").resizableImage(withCapInsets: .init(top: 0.5, left: 0.5, bottom: 0.5, right: 0.5)), for: .normal) progressSlider?.setMaximumTrackImage(#imageLiteral(resourceName: "cm2_fm_playbar_ready").resizableImage(withCapInsets: .init(top: 0.5, left: 0.5, bottom: 0.5, right: 0.5)), for: .normal) progressSlider?.setThumbImage(#imageLiteral(resourceName: "cm2_fm_playbar_btn").tta_combineAtCenter(with: #imageLiteral(resourceName: "cm2_fm_playbar_btn_dot")), for: .normal) progressSlider?.addTarget(self, action: #selector(pressAction(slider:)), for: .touchDown) progressSlider?.addTarget(self, action: #selector(valueChangedAction(slider:)), for: .valueChanged) progressSlider?.addTarget(self, action: #selector(upInsideAction(slider:)), for: .touchUpInside) playNeedelImageView?.image = #imageLiteral(resourceName: "cm2_play_needle_play") // add self.addSubview(blurView) self.addSubview(playAndPauseButton!) self.addSubview(nextButton!) self.addSubview(previewButton!) self.addSubview(currentTimeLabel!) self.addSubview(durationTimeLabel!) self.addSubview(progressSlider!) self.addSubview(iconImageView!) self.addSubview(playNeedelImageView!) // layout playAndPauseButton?.snp.makeConstraints({ (make) in make.centerX.equalTo(self) make.centerY.equalTo(self.snp.bottom).offset(-60 * kSCALEP) }) nextButton?.snp.makeConstraints({ (make) in make.centerY.equalTo(playAndPauseButton!) make.left.equalTo(playAndPauseButton!.snp.right).offset(20 * kSCALEP) }) previewButton?.snp.makeConstraints({ (make) in make.centerY.equalTo(playAndPauseButton!) make.right.equalTo(playAndPauseButton!.snp.left).offset(-20 * kSCALEP) }) currentTimeLabel?.snp.makeConstraints({ (make) in make.left.equalTo(self).offset(12 * kSCALEP) make.centerY.equalTo(playAndPauseButton!.snp.centerY).offset(-60 * kSCALEP) make.width.equalTo(50 * kSCALEP) }) progressSlider?.snp.makeConstraints({ (make) in make.centerX.equalTo(playAndPauseButton!) make.left.equalTo(currentTimeLabel!.snp.right).offset(20 * kSCALEP) make.centerY.equalTo(currentTimeLabel!) }) durationTimeLabel?.snp.makeConstraints({ (make) in make.left.equalTo(progressSlider!.snp.right).offset(20 * kSCALEP) make.centerY.equalTo(progressSlider!) make.right.equalTo(self).offset(-12 * kSCALEP) make.width.equalTo(50 * kSCALEP) }) iconImageView?.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-40 * kSCALEP) } playNeedelImageView?.snp.makeConstraints({ (make) in make.left.equalTo(self.snp.centerX).offset(-26 * kSCALEP) make.top.equalTo(64 - (22 * kSCALEP)) }) } /// 配置播放按钮图片 func configPlayButton() { playAndPauseButton?.setImage(#imageLiteral(resourceName: "cm2_fm_btn_pause"), for: .normal) playAndPauseButton?.setImage(#imageLiteral(resourceName: "cm2_fm_btn_pause_prs"), for: .highlighted) print("configPlayButton") } /// 配置暂停按钮图片 func configPauseButton() { playAndPauseButton?.setImage(#imageLiteral(resourceName: "cm2_fm_btn_play"), for: .normal) playAndPauseButton?.setImage(#imageLiteral(resourceName: "cm2_fm_btn_play_prs"), for: .highlighted) print("configPauseButton") } /// 更新进度条与时间 open func updateProgressAndTime() { progressSlider?.setValue(PlayerManager.shared.currentTime, animated: true) currentTimeLabel?.text = PlayerManager.shared.currentTimeString } /// 配置播放器中间的歌曲图片 func configIconImageView(with image : UIImage) { let iconImage = image.tta_clip(image: image, with: CGRect(x: 0, y: 0, width: 200 * kSCALEP, height: 200 * kSCALEP)) iconImageView?.image = #imageLiteral(resourceName: "cm2_play_disc").tta_combineAtCenter(with: #imageLiteral(resourceName: "cm2_playing_mask"))?.tta_combineAtCenter(with: iconImage!) } /// 给中间歌曲图片添加动画 func addAnimationToIconImageView() { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.duration = 20 animation.toValue = 2 * M_PI animation.repeatCount = MAXFLOAT animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.speed = 1.0 iconImageView?.layer.add(animation, forKey: kICON_IMAGE_ROTATION_KEY) } } // MARK: - Actions extension PlayerView { /// 播放与暂停 func didClickPlayAndPauseButton(sender : UIButton) { if PlayerManager.shared.isPlaying { guard let _ = delegate?.responds(to: #selector(delegate?.playerView(_:pause:))) else { return } self.delegate?.playerView?(self, pause: self.playAndPauseButton!) self.configPauseButton() } else { guard let _ = delegate?.responds(to: #selector(delegate?.playerView(_:play:))) else { return } self.delegate?.playerView?(self, play: self.playAndPauseButton!) self.configPlayButton() } } /// 下一曲 func didClickNextButton(sender : UIButton) { if let _ = delegate?.responds(to: #selector(delegate?.playerView(_:next:))) { delegate?.playerView?(self, next: sender) self.configPlayButton() } } /// 上一曲 func didClickPreviewButton(sender : UIButton) { if let _ = delegate?.responds(to: #selector(delegate?.playerView(_:preview:))) { delegate?.playerView?(self, preview: sender) self.configPlayButton() } } /** ------------------- progressSlider -------------------------- */ /// 点击事件 停止定时器 func pressAction(slider : UISlider) { PlayerManager.shared.stopTimer() } /// 拖动事件 更新播放时间与进度条 func valueChangedAction(slider : UISlider) { guard let value = progressSlider?.value else { return } currentTimeLabel?.text = PlayerManager.shared.getTimeString(with: TimeInterval(value)) } /// 松开手指事件 设置播放时间,开启定时器 func upInsideAction(slider : UISlider) { PlayerManager.shared.currentTime = slider.value PlayerManager.shared.startTimer() } /** ------------------- iconImageView动画 -------------------------- */ func startIconImageViewAnmation() { if let _ = iconImageView?.layer.animation(forKey: kICON_IMAGE_ROTATION_KEY) { } else { addAnimationToIconImageView() } let layer = iconImageView?.layer let pausedTime:CFTimeInterval = layer!.timeOffset // 当前层的暂停时间 /** 层动画时间的初始化值 **/ layer!.speed = 1.0 layer!.timeOffset = 0.0 layer!.beginTime = 0.0 /** end **/ let timeSincePause : CFTimeInterval = layer!.convertTime(CACurrentMediaTime(),from:nil) let timePause = timeSincePause - pausedTime //计算从哪里开始恢复动画 layer!.beginTime = timePause //让层的动画从停止的位置恢复动效 } func stopIconImageViewAnmation() { //申明一个暂停时间为这个层动画的当前时间 let layer = iconImageView?.layer let pausedTime : CFTimeInterval = layer!.convertTime(CACurrentMediaTime(),from:nil) layer!.speed = 0.0 //当前层的速度 layer!.timeOffset = pausedTime //层的停止时间设为上面申明的暂停时间 } }
1be0aeb7d2656e239adb2f07bc12c4bf
42.434426
194
0.648424
false
false
false
false
gzios/swift
refs/heads/master
SwiftBase/Swift逻辑分支.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play import UIKit //if-else,三目,guard //判断不再有非0、nil 即真,判断句必须要有明确的真假(Bool-->true) let a = 10 if a > 0 { print("a大于0") }else{ print("a小于等于0") } //else if let score = 92 if score < 0 || score > 100 { print("不合理范围") }else if score < 60{ print("不及格") }else if score < 80{ print("及格") }else if score < 90{ print("良好") }else if score == 100{ print("不错啊") } //三目 let m = 20 let n = 30 var recs = 0 recs = m > n ? m : n //guard 用来代替if的 //guard 条件 else{ // 条件语句 // break(中断) retur continue throw //} //语句块 let age = 20 //func 函数名称(参数列表<类型名:类型>){ // //} /* func online(age : Int){ if age >= 18 { print("可以留下来上网") }else{ print("回家找妈妈去吧") } } */ //func online(age:Int){ // guard age >= 18 else { // print("回家找妈妈去吧") // return // } // guard 带身份证 else { // print("回家找妈妈去吧") // return // } // guard 带钱 else { // print("回家找妈妈去吧") // return // } // print("留下来"); //} //online(age: age) //1.switch 基本用法 //0:男 1:女 let sex = 0 //break 省略。。。 switch sex { case 0: print("0") case 1: print("1") } //case 穿透 switch sex { case 0: print("0") fallthrough //穿透 case 1: print("1") } switch sex { case 0,1: print("0") fallthrough //穿透 case 1: print("1") } //可以判读浮点型 let asd = 3.14 switch asd { case 3.14: print(">>>") default: print("<<<") } //判断字符串 let m = 20 let n = 30 let opration = "+" var result = 0 switch opration { case "+": result = m + n case "-": result = m - n case "*": result = m * n case "/": result = m / n default: print("no") } //判读区间 let scor = 88; //开区间 0..<10 表示0到9 //闭区间 0...10 表示0到10 switch scor { case 0..<60: print("不及格") case 60..<80: print("及格") case 80..<90: print("良好") case 90...10: print("优秀") default: }
7746dbc772398a47ea4d95f2d1f70402
11.057325
52
0.514271
false
false
false
false
Ivacker/swift
refs/heads/master
test/Driver/options-repl.swift
apache-2.0
20
// RUN: not %swift -repl %s 2>&1 | FileCheck -check-prefix=REPL_NO_FILES %s // RUN: not %swift_driver -repl %s 2>&1 | FileCheck -check-prefix=REPL_NO_FILES %s // RUN: not %swift_driver -lldb-repl %s 2>&1 | FileCheck -check-prefix=REPL_NO_FILES %s // RUN: not %swift_driver -deprecated-integrated-repl %s 2>&1 | FileCheck -check-prefix=REPL_NO_FILES %s // REPL_NO_FILES: REPL mode requires no input files // RUN: %swift_driver -deprecated-integrated-repl -### | FileCheck -check-prefix=INTEGRATED %s // INTEGRATED: swift -frontend -repl // INTEGRATED: -module-name REPL // RUN: %swift_driver -lldb-repl -### | FileCheck -check-prefix=LLDB %s // RUN: %swift_driver -lldb-repl -DA,B,C -DD -L /path/to/libraries -L /path/to/more/libraries -F /path/to/frameworks -lsomelib -framework SomeFramework -sdk / -I "this folder" -module-name Test -### | FileCheck -check-prefix=LLDB-OPTS %s // LLDB: lldb{{"?}} "--repl= // LLDB-NOT: -module-name // LLDB: -target {{[^ "]+}} // LLDB-NOT: -module-name // LLDB: " // LLDB-OPTS: lldb{{"?}} "--repl= // LLDB-OPTS-DAG: -target {{[^ ]+}} // LLDB-OPTS-DAG: -D A,B,C -D D // LLDB-OPTS-DAG: -sdk / // LLDB-OPTS-DAG: -L /path/to/libraries // LLDB-OPTS-DAG: -L /path/to/more/libraries // LLDB-OPTS-DAG: -F /path/to/frameworks // LLDB-OPTS-DAG: -lsomelib // LLDB-OPTS-DAG: -framework SomeFramework // LLDB-OPTS-DAG: -I \"this folder\" // LLDB-OPTS: " // Test LLDB detection, first in a clean environment, then in one that looks // like the Xcode installation environment. We use hard links to make sure // the Swift driver really thinks it's been moved. // RUN: %swift_driver -repl -### | FileCheck -check-prefix=INTEGRATED %s // RUN: %swift_driver -### | FileCheck -check-prefix=INTEGRATED %s // RUN: rm -rf %t // RUN: mkdir -p %t/usr/bin/ // RUN: touch %t/usr/bin/lldb // RUN: chmod +x %t/usr/bin/lldb // RUN: ln %swift_driver_plain %t/usr/bin/swift // RUN: %t/usr/bin/swift -repl -### | FileCheck -check-prefix=LLDB %s // RUN: %t/usr/bin/swift -### | FileCheck -check-prefix=LLDB %s
48f5b366fb0f97185a7498993fa8b321
39.46
237
0.661394
false
false
true
false
iwheelbuy/VK
refs/heads/master
VK/Object/VK+Object+MarketItem.swift
mit
1
import Foundation public extension Object { /// Объект, описывающий товар public struct MarketItem: Decodable { /// Статус доступности товара public enum Availability: Decodable { /// Товар доступен case available /// Товар удален case deleted /// Товар недоступен case unavailable /// Неизвестное значение case unexpected(Int) init(rawValue: Int) { switch rawValue { case 0: self = .available case 1: self = .deleted case 2: self = .unavailable default: self = .unexpected(rawValue) } } public var rawValue: Int { switch self { case .available: return 0 case .deleted: return 1 case .unavailable: return 2 case .unexpected(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.MarketItem.Availability(rawValue: rawValue) } } /// Категория товара public struct Category: Decodable { /// Секция public struct Section: Decodable { /// Идентификатор секции public let id: Int? /// Название секции public let name: String? } /// Идентификатор категории public let id: Int? /// Название категории public let name: String? /// Секция public let section: Object.MarketItem.Category.Section? } /// Информация об отметках «Мне нравится» public struct Likes: Decodable { /// Число отметок «Мне нравится» let count: Int? /// Есть ли отметка «Мне нравится» от текущего пользователя let user_likes: Object.Boolean? } /// Объект, описывающий цену public struct Price: Decodable { /// Объект, описывающий информацию о валюте public struct Currency: Decodable { /// Идентификатор валюты public let id: Int? /// Буквенное обозначение валюты public let name: String? } /// Цена товара в сотых долях единицы валюты public let amount: String? /// Объект currency public let currency: Object.MarketItem.Price.Currency? /// Строка с локализованной ценой и валютой public let text: String? } /// Статус доступности товара public let availability: Object.MarketItem.Availability? /// Возможность комментировать товар для текущего пользователя public let can_comment: Object.Boolean? /// Возможность сделать репост товара для текущего пользователя public let can_repost: Object.Boolean? /// Категория товара public let category: Object.MarketItem.Category? /// Creation date in Unixtime public let date: Int? /// Текст описания товара public let description: String? /// Идентификатор товара public let id: Int? /// Информация об отметках «Мне нравится» public let likes: Object.MarketItem.Likes? /// Идентификатор владельца товара public let owner_id: Int? /// Изображения товара public let photos: [Object.Photo]? /// Цена public let price: Object.MarketItem.Price? /// URL of the item photo public let thumb_photo: String? /// Название товара public let title: String? } }
7686120e4d77f99f15e426db91045de9
34.301724
73
0.517705
false
false
false
false
youandthegang/APILayer
refs/heads/master
APILayer/Mapper.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 you & the gang UG(haftungsbeschränkt) // // 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 // MARK : required protocols and extensions for generic to implement T() as an initializer public protocol Defaultable {init()} extension Int: Defaultable {} extension String: Defaultable {} extension Float: Defaultable {} extension Double: Defaultable {} extension Bool: Defaultable {} infix operator <- open class Map { open var error: APIResponseStatus? open var representation: AnyObject public init(representation: AnyObject) { self.representation = representation } open func value<T: Defaultable>(_ key: String) -> T { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value<T: Defaultable>(_ key: String) -> T? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value<T: Defaultable>(_ key: String) -> [T]? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value<T: Defaultable>(_ key: String) -> [T] { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value<T: MappableObject>(_ key: String) -> T { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value<T: MappableObject>(_ key: String) -> T? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value<T: MappableObject>(_ key: String) -> [T]? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value<T: MappableObject>(_ key: String) -> [T] { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value(_ key: String) -> Date { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value(_ key: String) -> Date? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value(_ key: String) -> [String: AnyObject]? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value(_ key: String) -> [String: AnyObject] { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value(_ key: String, formatter: DateFormatter) -> Date { return API.mapper.value(fromRepresentation: representation, key: key, error: &error, customFormatter: formatter) } open func value(_ key: String, formatter: DateFormatter) -> Date? { return API.mapper.value(fromRepresentation: representation, key: key, customFormatter: formatter) } open func value<T: MappableObject>(_ key: String) -> [String: T] { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value<T: MappableObject>(_ key: String) -> [String: T]? { return API.mapper.value(fromRepresentation: representation, key: key) } open func value<T: Defaultable>(_ key: String) -> [String: T] { return API.mapper.value(fromRepresentation: representation, key: key, error: &error) } open func value<T: Defaultable>(_ key: String) -> [String: T]? { return API.mapper.value(fromRepresentation: representation, key: key) } static func map<T: MappableObject>(fromRepresentation representation: AnyObject) -> T? { let map = Map(representation: representation) let entity = T(map: map) return map.error == nil ? nil : entity } } open class Mapper { open var dateFormatter: DateFormatter = DateFormatter() // This key is used in CollectionResponse to get the wrapped item array. open var collectionResponseItemsKey = "items" // This makes the constructor available to the public. Otherwise subclasses can't get initialized public init() { } // MARK: Date formatting open func stringFromDate(_ date: Date) -> String { return dateFormatter.string(from: date) } // MARK: Parameters for routers open func parametersForRouter(_ router: RouterProtocol) -> [String : Any]? { print("You need to implement the method parametersForRouter() in your Mapper subclass in order to have parameters in your requests") return nil } // MARK: Headers for routers open func headersForRouter(_ router: RouterProtocol) -> [String : String] { return [:] } // MARK: Single value extraction open func value(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> Date { if let value = representation.value(forKeyPath: key) as? String { if let date = dateFormatter.date(from: value) { return date } } error = APIResponseStatus.missingKey(description: "Could not parse date for key '\(key)'. Key is missing or format is wrong.") return Date() } open func value(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?, customFormatter: DateFormatter) -> Date { if let value = representation.value(forKeyPath: key) as? String { if let date = customFormatter.date(from: value) { return date } } error = APIResponseStatus.missingKey(description: "Could not parse date for key '\(key)'. Key is missing or format is wrong.") return Date() } open func value<T: Defaultable>(fromRepresentation representation: AnyObject, key: String) -> T? { if let value = representation.value(forKeyPath: key) as? T { return value } return nil } open func value<T: MappableObject>(fromRepresentation representation: AnyObject, key: String) -> T? { if let candidateObject: Any = representation.value(forKey: key) { if let validDict = candidateObject as? [String: AnyObject] { let map = Map(representation: validDict as AnyObject) let entity = T(map: map) return map.error == nil ? entity : nil } } return nil } open func value(fromRepresentation representation: AnyObject, key: String) -> [String: AnyObject]? { if let value = representation.value(forKeyPath: key) as? [String: AnyObject] { return value } return nil } open func value(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> [String: AnyObject] { if let value = representation.value(forKeyPath: key) as? [String: AnyObject] { return value } error = APIResponseStatus.missingKey(description: "Could not extract value for key \(key). Key is missing.") return [:] } open func value(fromRepresentation representation: AnyObject, key: String) -> Date? { if let value = representation.value(forKeyPath: key) as? String { if let date = dateFormatter.date(from: value) { return date } } return nil } open func value(fromRepresentation representation: AnyObject, key: String, customFormatter: DateFormatter) -> Date? { if let value = representation.value(forKeyPath: key) as? String { if let date = customFormatter.date(from: value) { return date } } return nil } open func value<T: Defaultable>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> T { if let value = representation.value(forKeyPath: key) as? T { return value } error = APIResponseStatus.missingKey(description: "Could not extract value for key \(key). Key is missing.") return T() } open func value<T: MappableObject>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> T { if let candidateObject: Any = representation.value(forKey: key) { if let validDict = candidateObject as? [String: AnyObject] { let map = Map(representation: validDict as AnyObject) let entity = T(map: map) // var localError: APIResponseStatus? // let entity = T(representation: validDict, error: &localError) if let localError = map.error { error = localError } return entity } else { error = APIResponseStatus.invalidValue(description: "Could not parse entity for key '\(key)'. Value is not a dictionary.") } } else { error = APIResponseStatus.missingKey(description: "Could not parse entity for key '\(key)'. Key is missing.") } // Return some object (we do not want to throw, otherwise "let" properties would be a problem in response entities) let map = Map(representation: [:] as AnyObject) return T(map: map) // var dummyError: APIResponseStatus? // return T(representation: [:], error: &dummyError) } // MARK: Array value extraction open func value<T: MappableObject>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> [T] { let validObject = representation.value(forKey: key) if validObject != nil { let validAnyObjectArray = validObject as AnyObject let validArray: [T]? = entityArray(fromRepresentation: validAnyObjectArray) if let validArray = validArray{ return validArray } else { error = APIResponseStatus.invalidValue(description: "Could not parse entity array for key '\(key)'. Value is invalid.") } } error = APIResponseStatus.missingKey(description: "Could not parse entity array for key '\(key)'. Key is missing.") return [] } open func value<T: Defaultable>(fromRepresentation representation: AnyObject, key: String) -> [T]? { if let value = representation.value(forKeyPath: key) as? [T] { return value } return nil } open func value<T: MappableObject>(fromRepresentation representation: AnyObject, key: String) -> [T]? { if let candidateObject: Any = representation.value(forKey: key), let validAnyCandidateObject = candidateObject as? AnyObject { if let validArray = validAnyCandidateObject as? [AnyObject] { var result = [T]() for candidateItem in validArray { if let validDict = candidateItem as? [String: AnyObject] { let map = Map(representation: validDict as AnyObject) let entity = T(map: map) // If deserialization of the entity failed, we ignore it if map.error == nil { result.append(entity) } } } return result } } return nil } open func value<T: Defaultable>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> [T] { if let value = representation.value(forKeyPath: key) as? [T] { return value } error = APIResponseStatus.missingKey(description: "Could not extract array for key \(key). Key is missing or type is wrong.") return [] } // MARK: Dictionary value extraction open func value<T: MappableObject>(fromRepresentation representation: AnyObject, key: String) -> [String: T]? { if let candidateObject: Any = representation.value(forKey: key), let validAnyCandidateObject = candidateObject as? AnyObject { if let validDict = validAnyCandidateObject as? [String: AnyObject] { var result = [String: T]() for (key, value) in validDict { if let entityDict = value as? [String: AnyObject] { let map = Map(representation: entityDict as AnyObject) let entity = T(map: map) if map.error == nil { result[key] = entity } } } return result } } return nil } open func value<T: MappableObject>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> [String: T] { if let candidateObject: Any = representation.value(forKey: key), let validAnyCandidateObject = candidateObject as? AnyObject { if let validDict = validAnyCandidateObject as? [String: AnyObject] { var result = [String: T]() for (key, value) in validDict { if let entityDict = value as? [String: AnyObject] { let map = Map(representation: entityDict as AnyObject) let entity = T(map: map) if map.error == nil { result[key] = entity } } } return result } else { error = APIResponseStatus.missingKey(description: "Value for key \(key) is not a dictionary.") return [:] } } error = APIResponseStatus.missingKey(description: "Could not extract value for key \(key). Key is missing.") return [:] } open func value<T: Defaultable>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> [String: T] { if let value = representation.value(forKeyPath: key) as? [String: T] { return value } error = APIResponseStatus.missingKey(description: "Could not extract array for key \(key). Key is missing or type is wrong.") return [:] } open func value<T: Defaultable>(fromRepresentation representation: AnyObject, key: String) -> [String: T]? { if let value = representation.value(forKeyPath: key) as? [String: T] { return value } return nil } // MARK: Internal entity array parsing fileprivate func entityArray<T: MappableObject>(fromRepresentation representation: AnyObject) -> [T]? { if let validArray = representation as? [AnyObject] { var result = [T]() for candidateItem in validArray { if let validDict = candidateItem as? [String: AnyObject] { let map = Map(representation: validDict as AnyObject) let entity = T(map: map) // If deserialization of the entity failed, we ignore it if map.error == nil { result.append(entity) } } } return result } return nil } fileprivate func entityArray<T: MappableObject>(fromRepresentation representation: AnyObject, key: String, error: inout APIResponseStatus?) -> [T] { if let validObject: Any = representation.value(forKey: key), let validAnyObject = validObject as? AnyObject { let validArray: [T]? = entityArray(fromRepresentation: validAnyObject) if let validArray = validArray{ return validArray } else { error = APIResponseStatus.invalidValue(description: "Could not parse entity array for key '\(key)'. Value is invalid.") } } error = APIResponseStatus.missingKey(description: "Could not parse entity array for key '\(key)'. Key is missing.") return [] } }
acd7efd411755be647871a231e008bf3
37.145263
153
0.582703
false
false
false
false
mz2/MPMailingListService
refs/heads/master
MailingListSignupWindowController.swift
mit
1
// // MailingListSignupWindowController.swift // MPMailingListService // // Created by Matias Piipari on 10/09/2016. // Copyright © 2016 Matias Piipari & Co. All rights reserved. // import Foundation @objc public protocol MailingListSignupWindowControllerDelegate { @objc (didDismissMailingListSignupWindowController:) func didDismiss(mailingListSignupWindowController controller:MailingListSignupWindowController) } @IBDesignable @objc open class MailingListSignupWindowController: NSWindowController, NSWindowDelegate { @IBOutlet weak open var delegate:MailingListSignupWindowControllerDelegate? @IBInspectable open var APIKey:String? { didSet { self.listSignupViewController?.APIKey = APIKey } } @IBInspectable open var listID:String? { didSet { self.listSignupViewController?.listID = listID } } @IBInspectable @objc open var icon:NSImage? { didSet { self.listSignupViewController?.icon = icon ?? NSApplication.shared.applicationIconImage } } @IBInspectable @objc open var signupTitle:String? { didSet { self.listSignupViewController?.signupTitle = signupTitle } } @IBInspectable @objc open var signupPrompt:String? { didSet { self.listSignupViewController?.signupPrompt = signupPrompt } } @IBInspectable @objc open var dismissPrompt:String? { didSet { self.listSignupViewController?.dismissPrompt = dismissPrompt } } @IBInspectable @objc open var signupMessage:String? { didSet { self.listSignupViewController?.signupMessage = signupMessage } } @IBInspectable @objc open var signupThankYou:String? { didSet { self.listSignupViewController?.signupThankYou = signupThankYou ?? "" } } @objc fileprivate(set) open var listSignupViewController:MailingListSignupViewController? @objc open class var productName: String { return Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "<Your app whose bundle lacks Info.plist key 'CFBundleName'>" } public required init?(coder: NSCoder) { super.init(coder: coder) } public override init(window: NSWindow?) { super.init(window:window) } open override func awakeFromNib() { super.awakeFromNib() let signupVC = MailingListSignupViewController(nibName: nil, bundle: self.bundleForSignupNib) signupVC.delegate = self self.listSignupViewController = signupVC self.contentViewController = signupVC self.signupTitle = "Sign up to our newsletter" self.signupPrompt = "Sign up" self.dismissPrompt = "No, Thanks" self.signupMessage = "Sign up to receive news and updates on \(type(of: self).productName)!\n\nWe will email you with instructions to get started, and will update you on news and special deals." self.signupThankYou = "Thanks for signing up!" } open override func windowDidLoad() { super.windowDidLoad() } // override in subclass if you want to use a custom MailingListSignupViewController subclass var signupViewControllerClass: MailingListSignupViewController.Type { return MailingListSignupViewController.self } // override in subclass if you want to use a custom MailingListSignupViewController subclass… // but for instance the original Nib var bundleForSignupNib: Bundle { return Bundle(for: self.signupViewControllerClass) } } extension MailingListSignupWindowController: MailingListSignupViewControllerDelegate { public func shouldDismissSignupViewController(_ signupViewController: MailingListSignupViewController) { self.delegate?.didDismiss(mailingListSignupWindowController: self) self.window?.close() } }
20065c13c53f55526f8e3420ddccaba1
38.947917
202
0.71395
false
false
false
false
shamanskyh/Precircuiter
refs/heads/main
Precircuiter/Utilities/Utilities.swift
mit
1
// // Utilities.swift // Precircuiter // // Created by Harry Shamansky on 5/9/15. // Copyright © 2015 Harry Shamansky. All rights reserved. // import Foundation import AppKit // XOR Operator - from https://gist.github.com/JadenGeller/8afdbaa6cf8bf30bf645 precedencegroup BooleanPrecedence { associativity: left } infix operator ^^ : BooleanPrecedence func ^^(lhs: Bool, rhs: Bool) -> Bool { return lhs != rhs } /// Extension to determine whether a color is light or dark extension NSColor { func isLight() -> Bool { let convertedColor = self.usingColorSpace(NSColorSpace.genericRGB) let red = convertedColor?.redComponent let green = convertedColor?.greenComponent let blue = convertedColor?.blueComponent guard let r = red, let b = blue, let g = green else { return true // default to dark text } let score = ((r * 255 * 299) + (g * 255 * 587) + (b * 255 * 114)) / 1000 return score >= 175 } } /// Remove objects from an array by value from http://stackoverflow.com/a/30724543 extension Array where Element : Equatable { // Remove first collection element that is equal to the given `object`: mutating func removeObject(_ object : Iterator.Element) { if let index = self.firstIndex(of: object) { self.remove(at: index) } } } /// Random number generation from https://gist.github.com/JadenGeller/407036af08a28513eef2 struct Random { static func within(_ range: ClosedRange<Int>) -> Int { return Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound + 1))) + range.lowerBound } static func within(_ range: ClosedRange<Float>) -> Float { return (range.upperBound - range.lowerBound) * Float(Float(arc4random()) / Float(UInt32.max)) + range.lowerBound } static func within(_ range: ClosedRange<Double>) -> Double { return (range.upperBound - range.lowerBound) * Double(Double(arc4random()) / Double(UInt32.max)) + range.lowerBound } static func generate() -> Int { return Random.within(0...1) } static func generate() -> Bool { return Random.generate() == 0 } static func generate() -> Float { return Random.within(0.0...1.0) } static func generate() -> Double { return Random.within(0.0...1.0) } } // MARK: String/Key Conversion Utilities /// Given a key/value pair as strings, add or modify the corresponding property /// on an `Instrument` object. /// /// - Parameter inst: the instrument to modify (passed by reference) /// - Parameter propertyString: the property to modify, as a string from VWX /// - Parameter propertyValue: the value to set the property to func addPropertyToInstrument(_ inst: inout Instrument, propertyString: String, propertyValue: String) throws { func stringToDeviceType(_ devType: String) -> DeviceType { switch devType { case "Light": return .light case "Moving Light": return .movingLight case "Accessory": return .accessory case "Static Accessory": return .staticAccessory case "Device": return .device case "Practical": return .practical case "SFX": return .sfx case "Power": return .power default: return .other } } // throw out any of Vectorworks' hyphens if propertyValue == "-" { return } switch propertyString { case "Device Type": inst.deviceType = stringToDeviceType(propertyValue) case "Inst Type": inst.instrumentType = propertyValue case "Instrument Type": inst.instrumentType = propertyValue case "Wattage": inst.wattage = propertyValue case "Purpose": inst.purpose = propertyValue case "Position": inst.position = propertyValue case "Unit Number": inst.unitNumber = propertyValue case "Color": inst.color = propertyValue case "Dimmer": inst.dimmer = propertyValue case "Channel": inst.channel = propertyValue case "Address": inst.address = propertyValue case "Universe": inst.universe = propertyValue case "U Address": inst.uAddress = propertyValue case "U Dimmer": inst.uDimmer = propertyValue case "Circuit Number": inst.circuitNumber = propertyValue case "Circuit Name": inst.circuitName = propertyValue case "System": inst.system = propertyValue case "User Field 1": inst.userField1 = propertyValue case "User Field 2": inst.userField2 = propertyValue case "User Field 3": inst.userField3 = propertyValue case "User Field 4": inst.userField4 = propertyValue case "User Field 5": inst.userField5 = propertyValue case "User Field 6": inst.userField6 = propertyValue case "Num Channels": inst.numChannels = propertyValue case "Frame Size": inst.frameSize = propertyValue case "Field Angle": inst.fieldAngle = propertyValue case "Field Angle 2": inst.fieldAngle2 = propertyValue case "Beam Angle": inst.beamAngle = propertyValue case "Beam Angle 2": inst.beamAngle2 = propertyValue case "Weight": inst.weight = propertyValue case "Gobo 1": inst.gobo1 = propertyValue case "Gobo 1 Rotation": inst.gobo1Rotation = propertyValue case "Gobo 2": inst.gobo2 = propertyValue case "Gobo 2 Rotation": inst.gobo2Rotation = propertyValue case "Gobo Shift": inst.goboShift = propertyValue case "Mark": inst.mark = propertyValue case "Draw Beam": inst.drawBeam = (propertyValue.lowercased() == "true") case "Draw Beam as 3D Solid": inst.drawBeamAs3DSolid = (propertyValue.lowercased() == "true") case "Use Vertical Beam": inst.useVerticalBeam = (propertyValue.lowercased() == "true") case "Show Beam at": inst.showBeamAt = propertyValue case "Falloff Distance": inst.falloffDistance = propertyValue case "Lamp Rotation Angle": inst.lampRotationAngle = propertyValue case "Top Shutter Depth": inst.topShutterDepth = propertyValue case "Top Shutter Angle": inst.topShutterAngle = propertyValue case "Left Shutter Depth": inst.leftShutterDepth = propertyValue case "Left Shutter Angle": inst.leftShutterAngle = propertyValue case "Right Shutter Depth": inst.rightShutterDepth = propertyValue case "Right Shutter Angle": inst.rightShutterAngle = propertyValue case "Bottom Shutter Depth": inst.bottomShutterDepth = propertyValue case "Bottom Shutter Angle": inst.bottomShutterAngle = propertyValue case "Symbol Name": inst.symbolName = propertyValue case "Use Legend": inst.useLegend = (propertyValue.lowercased() == "true") case "Flip Front && Back Legend Text": inst.flipFrontBackLegendText = (propertyValue.lowercased() == "true") case "Flip Left && Right Legend Text": inst.flipLeftRightLegendText = (propertyValue.lowercased() == "true") case "Focus": inst.focus = propertyValue case "Set 3D Orientation": inst.set3DOrientation = (propertyValue.lowercased() == "true") case "X Rotation": inst.xRotation = propertyValue case "Y Rotation": inst.yRotation = propertyValue case "X Location": do { inst.rawXLocation = propertyValue try inst.addCoordinateToInitialLocation(.x, value: propertyValue) } catch { throw InstrumentError.ambiguousLocation } case "Y Location": do { inst.rawYLocation = propertyValue try inst.addCoordinateToInitialLocation(.y, value: propertyValue) } catch { throw InstrumentError.ambiguousLocation } case "Z Location": do { inst.rawZLocation = propertyValue try inst.addCoordinateToInitialLocation(.z, value: propertyValue) } catch { throw InstrumentError.ambiguousLocation } case "FixtureID": inst.fixtureID = propertyValue case "__UID": inst.UID = propertyValue case "Accessories": inst.accessories = propertyValue default: throw InstrumentError.propertyStringUnrecognized } } /// Given a VWX property string, find the corresponding property on an `Instrument` /// object and return its value. /// /// - Parameter inst: the instrument to modify (passed by reference) /// - Parameter propertyString: the property to return, as a string from VWX /// - Returns: the value of the requested property, or nil func getPropertyFromInstrument(_ inst: Instrument, propertyString: String) throws -> String? { switch propertyString { case "Device Type": return inst.deviceType?.description case "Inst Type": return inst.instrumentType case "Instrument Type": return inst.instrumentType case "Wattage": return inst.wattage case "Purpose": return inst.purpose case "Position": return inst.position case "Unit Number": return inst.unitNumber case "Color": return inst.color case "Dimmer": return inst.dimmer case "Channel": return inst.channel case "Address": return inst.address case "Universe": return inst.universe case "U Address": return inst.uAddress case "U Dimmer": return inst.uDimmer case "Circuit Number": return inst.circuitNumber case "Circuit Name": return inst.circuitName case "System": return inst.system case "User Field 1": return inst.userField1 case "User Field 2": return inst.userField2 case "User Field 3": return inst.userField3 case "User Field 4": return inst.userField4 case "User Field 5": return inst.userField5 case "User Field 6": return inst.userField6 case "Num Channels": return inst.numChannels case "Frame Size": return inst.frameSize case "Field Angle": return inst.fieldAngle case "Field Angle 2": return inst.fieldAngle2 case "Beam Angle": return inst.beamAngle case "Beam Angle 2": return inst.beamAngle2 case "Weight": return inst.weight case "Gobo 1": return inst.gobo1 case "Gobo 1 Rotation": return inst.gobo1Rotation case "Gobo 2": return inst.gobo2 case "Gobo 2 Rotation": return inst.gobo2Rotation case "Gobo Shift": return inst.goboShift case "Mark": return inst.mark case "Draw Beam": return (inst.drawBeam == true) ? "True" : "False" case "Draw Beam as 3D Solid": return (inst.drawBeamAs3DSolid == true) ? "True" : "False" case "Use Vertical Beam": return (inst.useVerticalBeam == true) ? "True" : "False" case "Show Beam at": return inst.showBeamAt case "Falloff Distance": return inst.falloffDistance case "Lamp Rotation Angle": return inst.lampRotationAngle case "Top Shutter Depth": return inst.topShutterDepth case "Top Shutter Angle": return inst.topShutterAngle case "Left Shutter Depth": return inst.leftShutterDepth case "Left Shutter Angle": return inst.leftShutterAngle case "Right Shutter Depth": return inst.rightShutterDepth case "Right Shutter Angle": return inst.rightShutterAngle case "Bottom Shutter Depth": return inst.bottomShutterDepth case "Bottom Shutter Angle": return inst.bottomShutterAngle case "Symbol Name": return inst.symbolName case "Use Legend": return (inst.useLegend == true) ? "True" : "False" case "Flip Front && Back Legend Text": return (inst.flipFrontBackLegendText == true) ? "True" : "False" case "Flip Left && Right Legend Text": return (inst.flipLeftRightLegendText == true) ? "True" : "False" case "Focus": return inst.focus case "Set 3D Orientation": return (inst.set3DOrientation == true) ? "True" : "False" case "X Rotation": return inst.xRotation case "Y Rotation": return inst.yRotation case "X Location": return inst.rawXLocation case "Y Location": return inst.rawYLocation case "Z Location": return inst.rawZLocation case "FixtureID": return inst.fixtureID case "__UID": return inst.UID case "Accessories": return inst.accessories default: throw InstrumentError.propertyStringUnrecognized } } func connect(light: Instrument, dimmers: [Instrument]) { var shortestDistance: Double? if dimmers.filter({ $0.dimmer == light.dimmer }).count == 0 { light.receptacle = nil return } for dimmer in dimmers.filter({ $0.dimmer == light.dimmer }) { if shortestDistance == nil { do { shortestDistance = try HungarianMatrix.distanceBetween(light: light, dimmer: dimmer, cutCorners: Preferences.cutCorners) light.receptacle = dimmer dimmer.light = light } catch { shortestDistance = nil } } else { do { let tempDistance = try HungarianMatrix.distanceBetween(light: light, dimmer: dimmer, cutCorners: Preferences.cutCorners) if tempDistance < (shortestDistance ?? Double.greatestFiniteMagnitude) { shortestDistance = tempDistance light.receptacle = dimmer dimmer.light = light } } catch { continue } } } }
c109e98f7b2f8b22b8d4372713bc7fde
42.305648
136
0.67664
false
false
false
false
imfree-jdcastro/Evrythng-iOS-SDK
refs/heads/master
Evrythng-iOS/EvrythngNetworkErrorResponse.swift
apache-2.0
1
// // EvrythngNetworkErrorResponse.swift // EvrythngiOS // // Created by JD Castro on 24/05/2017. // Copyright © 2017 ImFree. All rights reserved. // import UIKit import Moya_SwiftyJSONMapper import SwiftyJSON open class EvrythngNetworkErrorResponse: Error, ALSwiftyJSONAble { open var jsonData: JSON? open var moreInfo: String? open var responseStatusCode: Int? open var code: Int64? open var errors: Array<String>? required public init?(jsonData:JSON){ self.jsonData = jsonData self.moreInfo = jsonData["moreInfo"].string self.responseStatusCode = jsonData["status"].int self.code = jsonData["code"].int64 self.errors = jsonData["errors"].arrayObject as? [String] } }
86a9248f0bd37ca4d5842e3955accfdd
23.709677
67
0.674935
false
false
false
false
codefellows/sea-b19-ios
refs/heads/master
Projects/Week3FIlterApp/Week3FIlterApp/GridViewController.swift
gpl-2.0
1
// // GridViewController.swift // Week3FIlterApp // // Created by Bradley Johnson on 8/5/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit import Photos class GridViewController: UIViewController, UICollectionViewDataSource, PhotoSelectedDelegate { var assetsFetchResult : PHFetchResult! var imageManager : PHCachingImageManager! var assetGridThumbnailSize : CGSize! var delegate : PhotoSelectedDelegate? @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self //create a PHCachingImageManager self.imageManager = PHCachingImageManager() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { //grab the cell size from our collectionview var scale = UIScreen.mainScreen().scale var flowLayout = self.collectionView.collectionViewLayout as UICollectionViewFlowLayout var cellSize = flowLayout.itemSize self.assetGridThumbnailSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale) } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier == "ShowPhoto" { var cell = sender as PhotoCell var indexPath = self.collectionView.indexPathForCell(cell) let photoVC = segue.destinationViewController as PhotoViewController photoVC.asset = self.assetsFetchResult[indexPath.item] as PHAsset photoVC.delegate = self } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int { return self.assetsFetchResult.count } func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoCell", forIndexPath: indexPath) as PhotoCell var currentTag = cell.tag + 1 println("cell has been used \(currentTag) times") cell.tag = currentTag var asset = self.assetsFetchResult[indexPath.item] as PHAsset //requesting the image for asset for each cell self.imageManager.requestImageForAsset(asset, targetSize: self.assetGridThumbnailSize, contentMode: PHImageContentMode.AspectFill, options: nil) { (result : UIImage!, [NSObject : AnyObject]!) -> Void in if cell.tag == currentTag{ cell.imageView.image = result } } return cell } //MARK: - PhotoSelectedDelegate func photoSelected(asset : PHAsset) -> Void { println("doing something for the delegate") self.delegate!.photoSelected(asset) } /* // 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. } */ }
6a5b7460fb3703da528f7d35b43b84e3
35.315789
210
0.67913
false
false
false
false
KSMissQXC/KS_DYZB
refs/heads/master
KS_DYZB/KS_DYZB/Classes/Home/Controller/KSHomeController.swift
mit
1
// // KSHomeController.swift // KS_DYZB // // Created by 耳动人王 on 2016/10/28. // Copyright © 2016年 KS. All rights reserved. // import UIKit //MARK: - 常量 private let kTitleViewH : CGFloat = 40 class KSHomeController: UIViewController { //MARK: - 属性 lazy var pagetTilteView : KSPageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: KStatusBarH + KNavigationBarH, width: KScreenW, height: kTitleViewH) let titles = ["推荐","游戏","娱乐","游玩"] let titleView = KSPageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() lazy var pageContenView : KSPageContentView = { //确定内容的Frame let contentH = KScreenH - KStatusBarH - KNavigationBarH - kTitleViewH - KTabBarH let contentFrame = CGRect(x: 0, y: KStatusBarH + KNavigationBarH + kTitleViewH, width: KScreenW, height: contentH) var childVcs = [UIViewController]() childVcs.append(KSRecommendController()) childVcs.append(UIViewController()) childVcs.append(UIViewController()) childVcs.append(UIViewController()) let pageContentView = KSPageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) pageContentView.delegate = self return pageContentView }() //MARK: - 方法 //设在状态栏为白色 override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } override func viewDidLoad() { super.viewDidLoad() setupUI() } } //MARK: - 设置UI界面 extension KSHomeController{ func setupUI(){ view.addSubview(pagetTilteView) view.addSubview(pageContenView) } } //MARK: - 设置代理方法 extension KSHomeController: KSPageTitleViewDelegate,KSPageContentViewDelegate{ func pageTileView(_ titleView: KSPageTitleView, _ clickTitleIndex: Int) { pageContenView.setCurrentIndex(clickTitleIndex) } func pageContentView(_ contentView: KSPageContentView, _ scroProgess: CGFloat, _ sourceIndex: Int, _ targetIndex: Int) { pagetTilteView.setTitleWithProgress(scroProgess, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
b01de7c463b37c168090597ac72814cc
21.699029
124
0.63858
false
false
false
false
iqingchen/DouYuZhiBo
refs/heads/master
DY/DY/Classes/Main/Model/AnchorGroup.swift
mit
1
// // AnchorGroup.swift // DY // // Created by zhang on 16/12/2. // Copyright © 2016年 zhang. All rights reserved. // import UIKit class AnchorGroup: BaseGameModel { /// 该组中对应的房间信息 var room_list : [[String : NSObject]]? { didSet{ guard let room_list = room_list else {return} for dict in room_list { anchors.append(AnchorModel(dict: dict)) } } } /// 组显示的图标 var icon_name : String = "home_header_normal" ///定义主播模型对象数组 lazy var anchors : [AnchorModel] = [AnchorModel]() /* override func setValue(_ value: Any?, forKey key: String) { if key == "room_list" { if let dataArr = value as? [[String : NSObject]] { for dic in dataArr { anchors.append(AnchorModel(dict: dic)) } } } }*/ }
bf04df5069f7c8cc1126d0cc8f2b4d3b
23.135135
63
0.513998
false
false
false
false
iceman201/NZAirQuality
refs/heads/master
NZAirQuality/View/Weather/WeatherDetailsTableViewCell.swift
mit
1
// // WeatherDetailsTableViewCell.swift // NZAirQuality // // Created by Liguo Jiao on 29/12/17. // Copyright © 2017 Liguo Jiao. All rights reserved. // import UIKit class WeatherDetailsTableViewCell: UITableViewCell { @IBOutlet weak var sendibleTempImage: UIImageView! @IBOutlet weak var sendibleLabel: UILabel! @IBOutlet weak var sendibleTemp: UILabel! @IBOutlet weak var sunriseImage: UIImageView! @IBOutlet weak var sunriseLabel: UILabel! @IBOutlet weak var sunriseTime: UILabel! @IBOutlet weak var sunsetImage: UIImageView! @IBOutlet weak var sunsetLabel: UILabel! @IBOutlet weak var sunsetTime: UILabel! var weatherData: Weather? var humidity: String { return weatherData?.data.channel.atmosphere?.humidity ?? "0" } var windSpeed: String { return weatherData?.data.channel.wind?.speed ?? "0" } var tempture: String { return weatherData?.data.channel.item?.currentCondition?.temp ?? "0" } override func awakeFromNib() { super.awakeFromNib() // Initialization code self.backgroundColor = .clear setLabelStyle(self.sendibleTemp) setLabelStyle(self.sendibleLabel) setLabelStyle(self.sunriseTime) setLabelStyle(self.sunriseLabel) setLabelStyle(self.sunsetLabel) setLabelStyle(self.sunsetTime) sunriseLabel.text = "Sunrise" sunsetLabel.text = "Sunset" sendibleLabel.text = "Feels Like" sunriseImage.image = #imageLiteral(resourceName: "sunrise") sunsetImage.image = #imageLiteral(resourceName: "sunset") sendibleTempImage.image = #imageLiteral(resourceName: "feellike") self.selectionStyle = .none } func setLabelStyle(_ label:UILabel) { label.textColor = NZAWhite label.layer.shadowColor = UIColor.black.cgColor label.layer.shadowRadius = 3.0 label.layer.shadowOpacity = 1.0 label.layer.shadowOffset = CGSize(width: 4, height: 4) label.layer.masksToBounds = false } func loadContent() { sunriseTime.text = weatherData?.data.channel.astronomy?.sunrise sunsetTime.text = weatherData?.data.channel.astronomy?.sunset //According to wiki: https://en.wikipedia.org/wiki/Apparent_temperature if let humidtyFloat = Float(humidity), let windSpeedFloat = Float(windSpeed), let tempFloat = Float(tempture) { let windSpeedMeterPerSecond = windSpeedFloat * 0.44704 let e = (humidtyFloat/100) * 6.105 * exp((17.27 * windSpeedMeterPerSecond)/(237.7 + windSpeedMeterPerSecond)) let AT = 1.07 * tempFloat + 0.2 * e - 0.65 * windSpeedMeterPerSecond - 2.7 sendibleTemp.text = String(format: "%.0f°C", fahrenheitToCelsius(feh: AT)) } } }
dbf2094a05729090d578c7c820b763e3
34.8125
121
0.660035
false
false
false
false
Daniseijo/AplicacionPFC
refs/heads/master
AplicacionPFC/ViewController.swift
mit
1
// // ViewController.swift // AplicacionPFC // // Created by Daniel Seijo Sánchez on 26/9/15. // Copyright © 2015 Daniel Seijo Sánchez. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var barButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent // Do any additional setup after loading the view, typically from a nib. if self.revealViewController() != nil { barButton.target = self.revealViewController() barButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
2fd07373d995d3e104a1ea5730391e30
28.352941
94
0.687375
false
false
false
false
CodaFi/swift-compiler-crashes
refs/heads/master
crashes-duplicates/00424-no-stacktrace.random.swift
mit
12
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing return d<A"\() import CoreData return " case b in x in a { typealias B<I : B? = { self] in let g = compose(g: c> [B) -> (""" } case b { let c: NSObject { protocol a { import Foundation return $0 protocol A : Array) { self.E == .c> U.dynamicType) return nil } return b } } return d return true return [B let t: P { func f("")-> Int = { x } typealias R } import Foundation } extension NSSet { } static let h = [T>: NSManagedObject { } let g = { c>() typealias h> { convenience init() -> T var c>Bool) } func g(t: C { var e: String = { init() } } class d: NSObject { } } self.B func b<T>(t: T]((t: NSObject { self] { protocol c = { func a(object1: P { typealias R convenience init("\() { class C<T var e) } var e: AnyObject.R extension NSSet { let c: Array) -> [B<T] { import CoreData var e: A.d.Type) { class C) -> { } protocol P { println(object2: T } } class C } } typealias e : Int -> : d where T) -> { let a { struct D : A { } } import Foundation let d<H : A? = nil self.B? { private let d<T, f: NSManagedObject { class func f: B<C> : C> Self { typealias F>(n: NSObject { } protocol P { class A : e, f: AnyObject, AnyObject) -> Int = A"\(n: d = { c) { typealias F = compose()(f) class C<f : Int -> { import Foundation } } class A : A: T>>(false) } let g = D>) import Foundation struct D : Int -> T>()) import Foundation let c(AnyObject, b = .init() println(t: A { f = b: U.E == { if true { } case b = e: P { private class A { return nil func g<T) { convenience init() if c == f<T! { return self.b = "" if c = b<T where A: e, object1, f<T] in override init(n: P { } func f(t: A((c: A : A> Int = b> { } } d: Int } return d.Type) { struct S { [T>() } import Foundation } class A : T>? { var b { self.E struct B } protocol c { typealias e = 0 func b struct c { convenience init(x) import Foundation } typealias R = b typealias e : B<A? = 0 } class C) ->) -> Int { } return { x } } typealias R } protocol P { let c: B("A.e where A.c()(f<T where T>(g<T! { var b<H : P> { let f = { e : T] in } } class A { } } class func b.e == { c(x: e: Int let v: P { } } class func a(self) let d<T>) { } println(c: B? = B<c> Self { let c = { } self.R } class A { struct c == e: A>>() let c(n: Array) -> T -> { } return $0 } private class A : U : (x: P> T where H) { if true { let c
b71d755993fcfde10c4cb54a6ad8b57a
12.740113
87
0.594984
false
false
false
false
0x73/SugarRecord
refs/heads/develop
spec/Realm/DefaultREALMStackTests.swift
mit
11
// // DefaultREALMStackTests.swift // SugarRecord // // Created by Pedro Piñera Buendía on 27/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import UIKit import XCTest import Realm class DefaultREALMStackTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testThatPropertiesAreSetInInit() { let stack: DefaultREALMStack = DefaultREALMStack(stackName: "name", stackDescription: "description") XCTAssertEqual(stack.name, "name", "The name should be set in init") XCTAssertEqual(stack.stackDescription, "description", "The description should be set in init") } func testIfReturnsTheDefaultRLMContextForTheContext() { let stack: DefaultREALMStack = DefaultREALMStack(stackName: "name", stackDescription: "description") XCTAssertEqual((stack.mainThreadContext() as SugarRecordRLMContext).realmContext, RLMRealm.defaultRealm(), "Default stack should return the default realm object") } func testIfReturnsTheDefaultRLMContextForTheContextInBAckground() { let stack: DefaultREALMStack = DefaultREALMStack(stackName: "name", stackDescription: "description") let expectation = expectationWithDescription("background operation") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in XCTAssertEqual((stack.backgroundContext() as SugarRecordRLMContext).realmContext, RLMRealm.defaultRealm(), "Default stack should return the default realm object") expectation.fulfill() }) waitForExpectationsWithTimeout(0.2, handler: nil) } func testIfInitializeTriesToMigrateIfNeeded() { class MockRealmStack: DefaultREALMStack { var migrateIfNeededCalled: Bool = false override func migrateIfNeeded() { self.migrateIfNeededCalled = true } } let mockRealmStack: MockRealmStack = MockRealmStack(stackName: "Mock Stack", stackDescription: "Stack description") mockRealmStack.initialize() XCTAssertTrue(mockRealmStack.migrateIfNeededCalled, "Migration checking should be done in when initializing") } func testIfMigrationsAreProperlySorted() { var migrations: [RLMObjectMigration<RLMObject>] = [RLMObjectMigration<RLMObject>]() migrations.append(RLMObjectMigration<RLMObject>(toSchema: 13, migrationClosure: { (oldObject, newObject) -> () in })) migrations.append(RLMObjectMigration<RLMObject>(toSchema: 3, migrationClosure: { (oldObject, newObject) -> () in })) migrations.append(RLMObjectMigration<RLMObject>(toSchema: 1, migrationClosure: { (oldObject, newObject) -> () in })) let stack: DefaultREALMStack = DefaultREALMStack(stackName: "Stack name", stackDescription: "Stack description", migrations: migrations) var sortedMigrations: [RLMObjectMigration<RLMObject>] = DefaultREALMStack.sorteredAndFiltered(migrations: migrations, fromOldSchema: 2) XCTAssertEqual(sortedMigrations.first!.toSchema, 3, "First migration in the array should have toSchema = 3") XCTAssertEqual(sortedMigrations.last!.toSchema, 13, "First migration in the array should have toSchema = 13") } /* func testDatabaseRemoval() { let stack = DefaultREALMStack(stackName: "test", stackDescription: "test stack") SugarRecord.addStack(stack) let documentsPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let databaseName: String = documentsPath.stringByAppendingPathComponent("default.realm") XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(databaseName), "The database is not created in the right place") stack.removeDatabase() XCTAssertFalse(NSFileManager.defaultManager().fileExistsAtPath(databaseName), "The database is not created in the right place") SugarRecord.removeAllStacks() } */ }
9d75361911e667580cfce278b2c7b80d
46.662791
174
0.714321
false
true
false
false
jjochen/photostickers
refs/heads/master
MessagesExtension/Protocols/WiggleEffect.swift
mit
1
// // WiggleEffect.swift // MessagesExtension // // Created by Jochen on 04.04.19. // Copyright © 2019 Jochen Pfeiffer. All rights reserved. // import UIKit protocol WiggleEffect { func startWiggle() func stopWiggle() } extension WiggleEffect where Self: UIView { func startWiggle() { let wiggleBounceY = 1.5 let wiggleBounceDuration = 0.18 let wiggleBounceDurationVariance = 0.025 let wiggleRotateAngle = 0.02 let wiggleRotateDuration = 0.14 let wiggleRotateDurationVariance = 0.025 guard !hasWiggleAnimation else { return } // Create rotation animation let rotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotationAnimation.values = [-wiggleRotateAngle, wiggleRotateAngle] rotationAnimation.autoreverses = true rotationAnimation.duration = randomize(interval: wiggleRotateDuration, withVariance: wiggleRotateDurationVariance) rotationAnimation.repeatCount = .infinity rotationAnimation.isRemovedOnCompletion = false // Create bounce animation let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") bounceAnimation.values = [wiggleBounceY, 0] bounceAnimation.autoreverses = true bounceAnimation.duration = randomize(interval: wiggleBounceDuration, withVariance: wiggleBounceDurationVariance) bounceAnimation.repeatCount = .infinity bounceAnimation.isRemovedOnCompletion = false // Apply animations to view UIView.animate(withDuration: 0) { self.layer.add(rotationAnimation, forKey: AnimationKey.Rotation) self.layer.add(bounceAnimation, forKey: AnimationKey.Bounce) self.transform = .identity } } func stopWiggle() { layer.removeAnimation(forKey: AnimationKey.Rotation) layer.removeAnimation(forKey: AnimationKey.Bounce) } // Utility private var hasWiggleAnimation: Bool { guard let keys = layer.animationKeys() else { return false } return keys.contains(AnimationKey.Bounce) || keys.contains(AnimationKey.Rotation) } private func randomize(interval: TimeInterval, withVariance variance: Double) -> Double { let random = (Double(arc4random_uniform(1000)) - 500.0) / 500.0 return interval + variance * random } } private struct AnimationKey { static let Rotation = "wiggle.rotation" static let Bounce = "wiggle.bounce" }
e97afe7adfb4fa7c9391f63d96b3f338
31.74359
122
0.6852
false
false
false
false
kalvish21/AndroidMessenger
refs/heads/master
AndroidMessengerMacDesktopClient/AndroidMessenger/MessageCell.swift
mit
1
// // MessageCell.swift // AndroidMessenger // // Created by Kalyan Vishnubhatla on 3/22/16. // Copyright © 2016 Kalyan Vishnubhatla. All rights reserved. // import Cocoa class MessageCell: NSTableCellView { @IBOutlet weak var nameLabel: NSTextField! @IBOutlet weak var descriptionLabel: NSTextField! var defaultBackgroundStyle: NSBackgroundStyle = .Light override var backgroundStyle: NSBackgroundStyle { didSet { // super.backgroundStyle = defaultBackgroundStyle if self.backgroundStyle == .Light { self.nameLabel.textColor = NSColor.blackColor() self.descriptionLabel.textColor = NSColor.NSColorFromRGB(0x9A9A9A) } else if self.backgroundStyle == .Dark { self.nameLabel.textColor = NSColor.whiteColor() self.descriptionLabel.textColor = NSColor.NSColorFromRGB(0xd6d6d6) } } } }
1925095c608840cf28058786ac1b977a
30.366667
82
0.659574
false
false
false
false
alessiobrozzi/firefox-ios
refs/heads/master
Sync/Synchronizers/LoginsSynchronizer.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger let PasswordsStorageVersion = 1 private func makeDeletedLoginRecord(_ guid: GUID) -> Record<LoginPayload> { // Local modified time is ignored in upload serialization. let modified: Timestamp = 0 // Arbitrary large number: deletions sync down first. let sortindex = 5_000_000 let json: JSON = JSON([ "id": guid, "deleted": true, ]) let payload = LoginPayload(json) return Record<LoginPayload>(id: guid, payload: payload, modified: modified, sortindex: sortindex) } func makeLoginRecord(_ login: Login) -> Record<LoginPayload> { let id = login.guid let modified: Timestamp = 0 // Ignored in upload serialization. let sortindex = 1 let tLU = NSNumber(value: login.timeLastUsed / 1000) let tPC = NSNumber(value: login.timePasswordChanged / 1000) let tC = NSNumber(value: login.timeCreated / 1000) let dict: [String: Any] = [ "id": id, "hostname": login.hostname, "httpRealm": login.httpRealm as Any, "formSubmitURL": login.formSubmitURL as Any, "username": login.username ?? "", "password": login.password , "usernameField": login.usernameField ?? "", "passwordField": login.passwordField ?? "", "timesUsed": login.timesUsed, "timeLastUsed": tLU, "timePasswordChanged": tPC, "timeCreated": tC, ] let payload = LoginPayload(JSON(dict)) return Record<LoginPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex) } /** * Our current local terminology ("logins") has diverged from the terminology in * use when Sync was built ("passwords"). I've done my best to draw a reasonable line * between the server collection/record format/etc. and local stuff: local storage * works with logins, server records and collection are passwords. */ open class LoginsSynchronizer: IndependentRecordSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "passwords") } override var storageVersion: Int { return PasswordsStorageVersion } func getLogin(_ record: Record<LoginPayload>) -> ServerLogin { let guid = record.id let payload = record.payload let modified = record.modified let login = ServerLogin(guid: guid, hostname: payload.hostname, username: payload.username, password: payload.password, modified: modified) login.formSubmitURL = payload.formSubmitURL login.httpRealm = payload.httpRealm login.usernameField = payload.usernameField login.passwordField = payload.passwordField // Microseconds locally, milliseconds remotely. We should clean this up. login.timeCreated = 1000 * (payload.timeCreated ?? 0) login.timeLastUsed = 1000 * (payload.timeLastUsed ?? 0) login.timePasswordChanged = 1000 * (payload.timePasswordChanged ?? 0) login.timesUsed = payload.timesUsed ?? 0 return login } func applyIncomingToStorage(_ storage: SyncableLogins, records: [Record<LoginPayload>], fetched: Timestamp) -> Success { return self.applyIncomingToStorage(records, fetched: fetched) { rec in let guid = rec.id let payload = rec.payload guard payload.isValid() else { log.warning("Login record \(guid) is invalid. Skipping.") return succeed() } // We apply deletions immediately. That might not be exactly what we want -- perhaps you changed // a password locally after deleting it remotely -- but it's expedient. if payload.deleted { return storage.deleteByGUID(guid, deletedAt: rec.modified) } return storage.applyChangedLogin(self.getLogin(rec)) } } fileprivate func uploadChangedRecords<T>(_ deleted: Set<GUID>, modified: Set<GUID>, records: [Record<T>], lastTimestamp: Timestamp, storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<T>) -> Success { let onUpload: (POSTResult, Timestamp?) -> DeferredTimestamp = { result, lastModified in let uploaded = Set(result.success) return storage.markAsDeleted(uploaded.intersection(deleted)) >>> { storage.markAsSynchronized(uploaded.intersection(modified), modified: lastModified ?? lastTimestamp) } } return uploadRecords(records, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: onUpload) >>> succeed } // Find any records for which a local overlay exists. If we want to be really precise, // we can find the original server modified time for each record and use it as // If-Unmodified-Since on a PUT, or just use the last fetch timestamp, which should // be equivalent. // We will already have reconciled any conflicts on download, so this upload phase should // be as simple as uploading any changed or deleted items. fileprivate func uploadOutgoingFromStorage(_ storage: SyncableLogins, lastTimestamp: Timestamp, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> Success { let deleted: () -> Deferred<Maybe<(Set<GUID>, [Record<LoginPayload>])>> = { return storage.getDeletedLoginsToUpload() >>== { guids in let records = guids.map(makeDeletedLoginRecord) return deferMaybe((Set(guids), records)) } } let modified: () -> Deferred<Maybe<(Set<GUID>, [Record<LoginPayload>])>> = { return storage.getModifiedLoginsToUpload() >>== { logins in let guids = Set(logins.map { $0.guid }) let records = logins.map(makeLoginRecord) return deferMaybe((guids, records)) } } return accumulate([deleted, modified]) >>== { result in let (deletedGUIDs, deletedRecords) = result[0] let (modifiedGUIDs, modifiedRecords) = result[1] let allRecords = deletedRecords + modifiedRecords return self.uploadChangedRecords(deletedGUIDs, modified: modifiedGUIDs, records: allRecords, lastTimestamp: lastTimestamp, storage: storage, withServer: storageClient) } } open func synchronizeLocalLogins(_ logins: SyncableLogins, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(.notStarted(reason)) } let encoder = RecordEncoder<LoginPayload>(decode: { LoginPayload($0) }, encode: { $0.json }) guard let passwordsClient = self.collectionClient(encoder, storageClient: storageClient) else { log.error("Couldn't make logins factory.") return deferMaybe(FatalError(message: "Couldn't make logins factory.")) } let since: Timestamp = self.lastFetched log.debug("Synchronizing \(self.collection). Last fetched: \(since).") let applyIncomingToStorage: (StorageResponse<[Record<LoginPayload>]>) -> Success = { response in let ts = response.metadata.timestampMilliseconds let lm = response.metadata.lastModifiedMilliseconds! log.debug("Applying incoming password records from response timestamped \(ts), last modified \(lm).") log.debug("Records header hint: \(response.metadata.records)") return self.applyIncomingToStorage(logins, records: response.value, fetched: lm) >>> effect { NotificationCenter.default.post(name: NotificationDataRemoteLoginChangesWereApplied, object: nil) } } statsSession.start() return passwordsClient.getSince(since) >>== applyIncomingToStorage // TODO: If we fetch sorted by date, we can bump the lastFetched timestamp // to the last successfully applied record timestamp, no matter where we fail. // There's no need to do the upload before bumping -- the storage of local changes is stable. >>> { self.uploadOutgoingFromStorage(logins, lastTimestamp: 0, withServer: passwordsClient) } >>> { return deferMaybe(self.completedWithStats) } } }
2e231a106948ca889d4600a6a65ca6e2
45.457895
226
0.660134
false
false
false
false
einsteinx2/iSub
refs/heads/master
Classes/UI/Specific/MiniPlayerViewController.swift
gpl-3.0
1
// // MiniPlayerViewController.swift // iSub // // Created by Benjamin Baron on 6/18/16. // Copyright © 2016 Ben Baron. All rights reserved. // import UIKit class MiniPlayerViewController: UIViewController { let coverArtView = CachedImageView() let titleLabel = UILabel() let artistLabel = UILabel() let playButton = UIButton(type: .custom) let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) let progressView = UIView() var progressDisplayLink: CADisplayLink! let tapRecognizer = UITapGestureRecognizer() let swipeRecognizer = UISwipeGestureRecognizer() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .lightGray self.view.addSubview(coverArtView) coverArtView.snp.makeConstraints { make in make.left.equalToSuperview() make.top.equalToSuperview() make.bottom.equalToSuperview() make.width.equalTo(self.view.snp.height) } playButton.setTitleColor(.black, for: UIControlState()) playButton.titleLabel?.font = .systemFont(ofSize: 20) playButton.addTarget(self, action: #selector(playPause), for: .touchUpInside) self.view.addSubview(playButton) playButton.snp.makeConstraints { make in make.right.equalToSuperview() make.top.equalToSuperview() make.bottom.equalToSuperview() make.width.equalTo(self.view.snp.height) } spinner.hidesWhenStopped = true self.view.addSubview(spinner) spinner.snp.makeConstraints { make in make.centerX.equalTo(playButton) make.centerY.equalTo(playButton) } titleLabel.textColor = .black titleLabel.font = .systemFont(ofSize: 14) self.view.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.left.equalTo(coverArtView.snp.right).offset(5) make.right.equalTo(playButton.snp.left).offset(5) make.top.equalToSuperview().offset(5) make.height.equalToSuperview().dividedBy(2) } artistLabel.textColor = .darkGray artistLabel.font = .systemFont(ofSize: 12) self.view.addSubview(artistLabel) artistLabel.snp.makeConstraints { make in make.left.equalTo(titleLabel) make.right.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom) make.bottom.equalToSuperview().offset(-5) } progressView.backgroundColor = .white self.view.addSubview(progressView) progressView.snp.makeConstraints { make in make.left.equalToSuperview() make.width.equalTo(0) make.height.equalTo(3) make.bottom.equalToSuperview() } progressDisplayLink = CADisplayLink(target: self, selector: #selector(updateProgressView)) progressDisplayLink.isPaused = true progressDisplayLink.add(to: RunLoop.main, forMode: .defaultRunLoopMode) updatePlayButton() updateCurrentSong() updateProgressView() NotificationCenter.addObserverOnMainThread(self, selector: #selector(playbackStarted), name: GaplessPlayer.Notifications.songStarted) NotificationCenter.addObserverOnMainThread(self, selector: #selector(playbackPaused), name: GaplessPlayer.Notifications.songPaused) NotificationCenter.addObserverOnMainThread(self, selector: #selector(playbackEnded), name: GaplessPlayer.Notifications.songEnded) NotificationCenter.addObserverOnMainThread(self, selector: #selector(indexChanged), name: PlayQueue.Notifications.indexChanged) tapRecognizer.addTarget(self, action: #selector(showPlayer)) self.view.addGestureRecognizer(tapRecognizer) swipeRecognizer.direction = .up swipeRecognizer.addTarget(self, action: #selector(showPlayer)) self.view.addGestureRecognizer(swipeRecognizer) } deinit { NotificationCenter.removeObserverOnMainThread(self, name: GaplessPlayer.Notifications.songStarted) NotificationCenter.removeObserverOnMainThread(self, name: GaplessPlayer.Notifications.songPaused) NotificationCenter.removeObserverOnMainThread(self, name: GaplessPlayer.Notifications.songEnded) NotificationCenter.removeObserverOnMainThread(self, name: PlayQueue.Notifications.indexChanged) } @objc fileprivate func playPause() { if !GaplessPlayer.si.isStarted { spinner.startAnimating() } PlayQueue.si.playPause() } @objc fileprivate func playbackStarted() { spinner.stopAnimating() updatePlayButton() progressDisplayLink.isPaused = false } @objc fileprivate func playbackPaused() { updatePlayButton() progressDisplayLink.isPaused = true } @objc fileprivate func playbackEnded() { updatePlayButton() progressDisplayLink.isPaused = true } @objc fileprivate func indexChanged() { updateCurrentSong() } fileprivate func updatePlayButton(_ playing: Bool = GaplessPlayer.si.isPlaying) { if playing { playButton.setTitle("| |", for: UIControlState()) } else { playButton.setTitle(">", for: UIControlState()) } } fileprivate func updateCurrentSong() { let currentSong = PlayQueue.si.currentDisplaySong if let coverArtId = currentSong?.coverArtId, let serverId = currentSong?.serverId { coverArtView.loadImage(coverArtId: coverArtId, serverId: serverId, size: .cell) } else { coverArtView.setDefaultImage(forSize: .cell) } titleLabel.text = currentSong?.title artistLabel.text = currentSong?.artistDisplayName } @objc fileprivate func updateProgressView() { let progress = GaplessPlayer.si.progressPercent let width = self.view.frame.width * CGFloat(progress) progressView.snp.updateConstraints { make in make.width.equalTo(width) } } @objc fileprivate func showPlayer() { self.parent?.present(PlayerContainerViewController(), animated: true, completion: nil) } }
b8d788784f4b33c752face9005d6516d
37.113095
141
0.661877
false
false
false
false
haldun/MapleBacon
refs/heads/master
MapleBaconExample/MapleBaconExample/AppDelegate.swift
mit
3
// // Copyright (c) 2015 Zalando SE. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:AnyObject]?) -> Bool { adjustAppearance() return true } func adjustAppearance() { let lightColor = UIColor(red: 127 / 255, green: 187 / 255, blue: 154 / 255, alpha: 1) UINavigationBar.appearance().barTintColor = lightColor UITabBar.appearance().tintColor = lightColor let darkColor = UIColor(red: 14 / 255, green: 43 / 255, blue: 57 / 255, alpha: 1) UINavigationBar.appearance().tintColor = darkColor UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: darkColor] UITabBar.appearance().barTintColor = darkColor } }
29ab5007fc27a0a9cf234b969bf05b8a
29.633333
126
0.694233
false
false
false
false
RedRoster/rr-ios
refs/heads/master
RedRoster/Roster/Cells/SubjectCell.swift
apache-2.0
1
// // SubjectCell.swift // RedRoster // // Created by Daniel Li on 3/27/16. // Copyright © 2016 dantheli. All rights reserved. // import UIKit class SubjectCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var abbreviationLabel: UILabel! func configure(_ subject: Subject) { backgroundColor = UIColor.rosterCellBackgroundColor() nameLabel.text = subject.name nameLabel.textColor = UIColor.rosterCellTitleColor() abbreviationLabel.text = subject.abbreviation abbreviationLabel.textColor = UIColor.rosterCellSubtitleColor() let background = UIView() background.backgroundColor = UIColor.rosterCellSelectionColor() selectedBackgroundView = background } }
d3a992365e4dbe713c8965676cb6fa53
25.8
71
0.677861
false
false
false
false
andrea-prearo/SwiftExamples
refs/heads/master
SmoothScrolling/Client/Shared/Controllers/UserViewModelController.swift
mit
1
// // UserController.swift // SmoothScrolling // // Created by Andrea Prearo on 10/29/16. // Copyright © 2016 Andrea Prearo. All rights reserved. // import Foundation typealias RetrieveUsersCompletionBlock = (_ success: Bool, _ error: NSError?) -> Void class UserViewModelController { private static let pageSize = 25 private var viewModels: [UserViewModel?] = [] private var currentPage = -1 private var lastPage = -1 private var retrieveUsersCompletionBlock: RetrieveUsersCompletionBlock? func retrieveUsers(_ completionBlock: @escaping RetrieveUsersCompletionBlock) { retrieveUsersCompletionBlock = completionBlock loadNextPageIfNeeded(for: 0) } var viewModelsCount: Int { return viewModels.count } func viewModel(at index: Int) -> UserViewModel? { guard index >= 0 && index < viewModelsCount else { return nil } loadNextPageIfNeeded(for: index) return viewModels[index] } } private extension UserViewModelController { static func parse(_ jsonData: Data) -> [User?]? { do { return try JSONDecoder().decode([User].self, from: jsonData) } catch { return nil } } static func initViewModels(_ users: [User?]) -> [UserViewModel?] { return users.map { user in if let user = user { return UserViewModel(user: user) } else { return nil } } } func loadNextPageIfNeeded(for index: Int) { let targetCount = currentPage < 0 ? 0 : (currentPage + 1) * UserViewModelController.pageSize - 1 guard index == targetCount else { return } currentPage += 1 let id = currentPage * UserViewModelController.pageSize + 1 let urlString = String(format: "https://aqueous-temple-22443.herokuapp.com/users?id=\(id)&count=\(UserViewModelController.pageSize)") guard let url = URL(string: urlString) else { retrieveUsersCompletionBlock?(false, nil) return } let session = URLSession.shared let task = session.dataTask(with: url) { [weak self] (data, response, error) in guard let strongSelf = self else { return } guard let jsonData = data, error == nil else { DispatchQueue.main.async { strongSelf.retrieveUsersCompletionBlock?(false, error as NSError?) } return } strongSelf.lastPage += 1 if let users = UserViewModelController.parse(jsonData) { let newUsersPage = UserViewModelController.initViewModels(users) strongSelf.viewModels.append(contentsOf: newUsersPage) DispatchQueue.main.async { strongSelf.retrieveUsersCompletionBlock?(true, nil) } } else { DispatchQueue.main.async { strongSelf.retrieveUsersCompletionBlock?(false, NSError.createError(0, description: "JSON parsing error")) } } } task.resume() } }
8e513e7aef7e1c917e0b9dda2cd5c76e
33.445652
141
0.601136
false
false
false
false
mactive/rw-courses-note
refs/heads/master
AdvancedSwift3/Intermediate-inheritance.playground/Contents.swift
mit
1
import UIKit /*: #### Intermediate Swift Video Tutorial Series - raywenderlich.com #### Video 6: Initializers **Note:** If you're seeing this text as comments rather than nicely-rendered text, select Editor\Show Rendered Markup in the Xcode menu. */ //: Create a class called Account that has a balance property. Have the balance set to 0. Create a function to withdrawl money from the balance. Make sure the withdrawl amount is greater than 0 and the amount is less than the balance. class Account { var balance: Int = 0 init(bal: Int){ balance = bal } func withdrawl(cost: Int) { if (balance > cost && cost > 0) { balance -= cost print("you have \(balance) after withdrawl \(cost)") } else { print("make sure you have enough money") } } } //: Create a subclass called SavingsAccount and override withdrawl(). In this method, make sure that the withdrawn amount is greater than 10. class SavingAccount: Account { override func withdrawl(cost: Int) { if (balance - cost > 10) { super.withdrawl(cost: cost) } else { print("make sure you balance greater 10") } } } var pubAccount = Account(bal: 40) pubAccount.withdrawl(cost: 20) pubAccount.withdrawl(cost: 18) pubAccount.withdrawl(cost: 1) var privateAccount = SavingAccount(bal: 20) privateAccount.withdrawl(cost: 10)
9407f3c2c044bbcf8c0ced263cc96612
30.108696
234
0.657582
false
false
false
false
eCrowdMedia/MooApi
refs/heads/develop
Sources/network/ApiManager.swift
mit
1
import Foundation import Argo import Result public class ApiManager { public class HighlightApi { public struct HighlightResult { public let highlightArray: [Highlight] public var inclusion: ApiDocumentInclusion? init(highlightArray: [Highlight], inclusion: ApiDocumentInclusion?) { self.highlightArray = highlightArray self.inclusion = inclusion } } public static func sync(readingId: String, auth: Authorization, params: [String: String]? = ["page[count]": "100"], isDevelopment: Bool = false, failure: @escaping (ServiceError) -> Void, success: @escaping ([HighlightResult]) -> Void) { let service = Service(ServiceMethod.get, api: ServiceApi.meReadingsHighlights(readingId: readingId), authorization: auth, parameters: params, isDevelopment: isDevelopment) service.fetchJSONModelArray(queue: nil) { (result: Result<ApiDocumentEnvelope<Highlight>, ServiceError>) in switch result { case .failure(let error): failure(error) case .success(let value): let resultArray: [HighlightResult] = [HighlightResult(highlightArray: value.data, inclusion: value.included)] guard let nextUrlString = value.paginationLinks?.next else { success(resultArray) return } guard let nextPageUrl = URL(string: nextUrlString) else { failure(ServiceError.nextPageUrlFailure) return } downloadHighlight( auth: auth, nextURL: nextPageUrl, results: resultArray, isDevelopment: isDevelopment, failure: { (error) in failure(error) }, then: { (closureRessultArray) in success(closureRessultArray) }) } } } static func downloadHighlight( auth: Authorization, nextURL: URL, results: [HighlightResult], isDevelopment: Bool = false, failure: @escaping (ServiceError) -> Void, then: @escaping ([HighlightResult]) -> Void) { let service = Service(ServiceMethod.get, url: nextURL, authorization: auth) service.fetchJSONModelArray(queue: nil) { (result: Result<ApiDocumentEnvelope<Highlight>, ServiceError>) in switch result { case .failure(let error): failure(error) case .success(let value): var newResults = results let result = HighlightResult(highlightArray: value.data, inclusion: value.included) newResults.append(result) guard let nextUrlString = value.paginationLinks?.next else { then(newResults) return } guard let nextPageUrl = URL(string: nextUrlString) else { failure(ServiceError.nextPageUrlFailure) return } downloadHighlight( auth: auth, nextURL: nextPageUrl, results: newResults, isDevelopment: isDevelopment, failure: { (error) in failure(error) }, then: { (closureResults) in then(closureResults) }) } } } /// callback 回傳 (serverId, serviceError) public static func append(readingId: String, highlightData: Data, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (String?, ServiceError?) -> Void) { let service = Service(ServiceMethod.post, api: ServiceApi.meReadingsHighlights(readingId: readingId), authorization: auth, parameters: nil, httpBody: highlightData, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(nil, error!) return } guard let headers = headers, let serverId = headers["Location"] as? String else { completion(nil, .headerDataNotExisted) return } completion(serverId, nil) } } public static func modify(serverId: String, highlightData: Data, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (ServiceError?) -> Void) { let service = Service(ServiceMethod.patch, api: ServiceApi.meHighlights(highlightId: serverId), authorization: auth, parameters: nil, httpBody: highlightData, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(error) return } completion(nil) } } public static func remove(serverId: String, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (ServiceError?) -> Void) { let service = Service(ServiceMethod.delete, api: ServiceApi.meHighlights(highlightId: serverId), authorization: auth, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(error) return } completion(nil) } } } public class BookmarkApi { public struct BookmarkResult { public let bookmarkArray: [Bookmark] public var inclusion: ApiDocumentInclusion? init(bookmarkArray: [Bookmark], inclusion: ApiDocumentInclusion?) { self.bookmarkArray = bookmarkArray self.inclusion = inclusion } } public static func sync(readingId: String, auth: Authorization, params: [String: String]? = ["page[count]": "100"], isDevelopment: Bool = false, failure: @escaping (ServiceError) -> Void, success: @escaping ([BookmarkResult]) -> Void) { let service = Service(ServiceMethod.get, api: ServiceApi.meReadingsBookmarks(readingId: readingId), authorization: auth, parameters: params, isDevelopment: isDevelopment) service.fetchJSONModelArray(queue: nil) { (result: Result<ApiDocumentEnvelope<Bookmark>, ServiceError>) in switch result { case .failure(let error): failure(error) case .success(let value): let resultArray: [BookmarkResult] = [BookmarkResult(bookmarkArray: value.data, inclusion: value.included)] guard let nextUrlString = value.paginationLinks?.next else { success(resultArray) return } guard let nextPageUrl = URL(string: nextUrlString) else { failure(ServiceError.nextPageUrlFailure) return } downloadBookmark(auth: auth, nextURL: nextPageUrl, results: resultArray, failure: { (error) in failure(error) }, then: { (closureResults) in success(closureResults) }) } } } static func downloadBookmark( auth: Authorization, nextURL: URL, results: [BookmarkResult], isDevelopment: Bool = false, failure: @escaping (ServiceError) -> Void, then: @escaping ([BookmarkResult]) -> Void) { let service = Service(ServiceMethod.get, url: nextURL, authorization: auth) service.fetchJSONModelArray(queue: nil) { (result: Result<ApiDocumentEnvelope<Bookmark>, ServiceError>) in switch result { case .failure(let error): failure(error) case .success(let value): var newResults = results let result = BookmarkResult(bookmarkArray: value.data, inclusion: value.included) newResults.append(result) guard let nextUrlString = value.paginationLinks?.next else { then(newResults) return } guard let nextPageUrl = URL(string: nextUrlString) else { failure(ServiceError.nextPageUrlFailure) return } downloadBookmark(auth: auth, nextURL: nextPageUrl, results: newResults, failure: { (error) in failure(error) }, then: { (closureResults) in then(closureResults) }) } } } /// callback 回傳 (serverId, serviceError) public static func append(readingId: String, bookmarkData: Data, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (String?, ServiceError?) -> Void) { let service = Service(ServiceMethod.post, api: ServiceApi.meReadingsBookmarks(readingId: readingId), authorization: auth, httpBody: bookmarkData, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(nil, error!) return } guard let headers = headers, let serverId = headers["Location"] as? String else { completion(nil, .headerDataNotExisted) return } completion(serverId, nil) } } public static func modify(serverId: String, bookmarkData: Data, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (ServiceError?) -> Void) { let service = Service(ServiceMethod.patch, api: ServiceApi.meBookmarks(bookmarkId: serverId), authorization: auth, httpBody: bookmarkData, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(error) return } completion(nil) } } public static func remove(serverId: String, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (ServiceError?) -> Void) { let service = Service(ServiceMethod.delete, api: ServiceApi.meBookmarks(bookmarkId: serverId), authorization: auth, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(error) return } completion(nil) } } } public class ReadingPingApi { public static func append(readingId: String, pingData: Data, auth: Authorization, isDevelopment: Bool = false, completion: @escaping (ServiceError?) -> Void) { let service = Service(ServiceMethod.post, api: ServiceApi.meReadingsReadinglogs(readingId: readingId), authorization: auth, httpBody: pingData, isDevelopment: isDevelopment) service.uploadJSONData(queue: nil) { (data, headers, error) in if error != nil { completion(error!) return } completion(nil) } } } public class ReadingApi { public struct ReadingResult { public let reading: Reading public var inclusion: ApiDocumentInclusion? init(reading: Reading, inclusion: ApiDocumentInclusion?) { self.reading = reading self.inclusion = inclusion } } public static func sync(readingId: String, auth: Authorization, isDevelopment: Bool = false, failure: @escaping (ServiceError) -> Void, success: @escaping (ReadingResult) -> Void) { let service: Service = Service(ServiceMethod.get, api: ServiceApi.meReadings(readingId), authorization: auth, isDevelopment: isDevelopment) service.fetchJSONModel(queue: nil) { (result: Result<ApiDocument<Reading>, ServiceError>) in switch result { case .failure(let error): failure(error) case .success(let value): let result = ReadingResult(reading: value.data, inclusion: value.included) success(result) } } } } }
bdaf8f2f9f87bca7b3a20064662c3a53
32.449438
113
0.484313
false
false
false
false
Coderian/SwiftedGPX
refs/heads/master
SwiftedGPX/SPNSXMLParser.swift
mit
2
// // SPNSXMLParser.swift // SwiftedGPX // // Created by 佐々木 均 on 2016/02/04. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// Generic Parser of NSXMLParser public class SPXMLParser<T:HasXMLElementValue where T:XMLElementRoot>: NSObject,NSXMLParserDelegate{ var parser:NSXMLParser! /// 作成中 Elementを保持 private var stack:Stack<SPXMLElement> = Stack() /// 処理しなかったelements public var unSupported:Stack<UnSupportXMLElement> = Stack() private var contents:String = "" private var previewStackCount:Int = 0 /// parse結果取得用 var root:T! /// root Element Type var rootType:T.Type var debugPrintOn:Bool = false init(Url:NSURL, root:T.Type,debugPrintOn:Bool = false) { self.debugPrintOn = debugPrintOn parser = NSXMLParser(contentsOfURL: Url) self.rootType = root super.init() parser.delegate = self } func parse() -> T?{ parser.parse() return self.root } internal func createXMLElement(stack:Stack<SPXMLElement>, elementName:String,attributes:[String:String]) -> SPXMLElement { guard let retValue = self.rootType.createElement(elementName, attributes: attributes, stack: stack) else { // elementが対象外 return UnSupportXMLElement(elementName: elementName,attributes: attributes) } return retValue } // MARK: NSXMLParserDelegate public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { let element = createXMLElement(stack,elementName: elementName,attributes: attributeDict) stack.push(element) if self.debugPrintOn { debugPrint("OnStart didStartElement=\(elementName) pushd=\(element) namespaceURI=\(namespaceURI) qualifiedName=\(qName)") } self.contents = "" } public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let current = stack.pop() if self.debugPrintOn { debugPrint("OnEnd poped=\(current) == \(elementName)") } switch current { case let element as UnSupportXMLElement: if element.elementName == elementName { element.value = self.contents unSupported.push(element) } case let elemnt as HasXMLElementSimpleValue : // stack.push(v.makeRelation( self.contents, parent: stack.pop())) elemnt.makeRelation( self.contents, parent: stack.items[stack.count-1]) case let element as HasXMLElementName: if element.dynamicType.elementName == elementName { if self.rootType.elementName == elementName { self.root = element as? T } else { // let parent = stack.pop() let parent = stack.items[stack.count-1] // make the Relationship current.parent = parent // stack.push(parent) } } else { stack.push(current) } default: break } } public func parser(parser: NSXMLParser, foundCharacters string: String) { // contentsが長い文字列の場合は複数回呼ばれるので対応が必要 if self.previewStackCount == stack.count { self.contents += string } else{ self.contents = string } self.previewStackCount = stack.count if self.debugPrintOn { debugPrint("OnCharacters \(stack) self.contents=[\(self.contents)]") } } }
dfc119917c7b3c2301b5a21d8f8f37bb
34.783019
180
0.607068
false
false
false
false
yonasstephen/swift-of-airbnb
refs/heads/master
airbnb-main/airbnb-main/AirbnbHome.swift
mit
1
// // AirbnbHome.swift // airbnb-main // // Created by Yonas Stephen on 3/4/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import Foundation class AirbnbHome { var imageName: String var homeDescription: String var price: Int var rating: Double var reviewCount: Int init(imageName: String, description: String, price: Int, reviewCount: Int, rating: Double) { self.imageName = imageName self.homeDescription = description self.price = price self.reviewCount = reviewCount self.rating = rating } }
a56119161affc06dbd109a0b21c2b649
22.6
96
0.657627
false
false
false
false
nissivm/DemoShopPayPal
refs/heads/master
DemoShop-PayPal/View Controllers/Products_VC.swift
mit
1
// // Products_VC.swift // DemoShop-PayPal // // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import UIKit class Products_VC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, ItemForSaleCellDelegate, ShoppingCart_VC_Delegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var shoppingCartButton: UIButton! @IBOutlet weak var authenticationContainerView: UIView! @IBOutlet weak var shopName: UILabel! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var shoppingCartButtonHeightConstraint: NSLayoutConstraint! var allItemsForSale = [ItemForSale]() var itemsForSale = [ItemForSale]() var shoppingCartItems = [ShoppingCartItem]() var multiplier: CGFloat = 1 override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionStarted", name: "SessionStarted", object: nil) if Device.IS_IPHONE_6 { multiplier = Constants.multiplier6 adjustForBiggerScreen() } else if Device.IS_IPHONE_6_PLUS { multiplier = Constants.multiplier6plus adjustForBiggerScreen() } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //-------------------------------------------------------------------------// // MARK: Notifications //-------------------------------------------------------------------------// func sessionStarted() { authenticationContainerView.hidden = true retrieveProducts() } //-------------------------------------------------------------------------// // MARK: IBActions //-------------------------------------------------------------------------// @IBAction func shoppingCartButtonTapped(sender: UIButton) { if shoppingCartButton.enabled { performSegueWithIdentifier("ToShoppingCart", sender: self) } } //-------------------------------------------------------------------------// // MARK: Retrieve products //-------------------------------------------------------------------------// var minimum = 0 var maximum = 5 func retrieveProducts() { Auxiliar.showLoadingHUDWithText("Retrieving products...", forView: self.view) guard Reachability.connectedToNetwork() else { Auxiliar.hideLoadingHUDInView(self.view) return } let ref = Firebase(url: Constants.baseURL + "ItemsForSale") ref.observeEventType(.Value, withBlock: { [unowned self](snapshot) in if let response = snapshot.value as? [[NSObject : AnyObject]] { for responseItem in response { let item = ItemForSale() item.position = responseItem["position"] as! Int item.itemId = responseItem["itemId"] as! String item.itemName = responseItem["itemName"] as! String item.itemPrice = responseItem["itemPrice"] as! CGFloat item.imageAddr = responseItem["imageAddr"] as! String self.allItemsForSale.append(item) } self.allItemsForSale.sortInPlace { item1, item2 in return item1.position < item2.position } var firstItemsForSale = [ItemForSale]() for (index, item) in self.allItemsForSale.enumerate() { firstItemsForSale.append(item) if index == 5 { break } } self.incorporateItems(firstItemsForSale) } }) } //-------------------------------------------------------------------------// // MARK: UIScrollViewDelegate //-------------------------------------------------------------------------// var hasMoreToShow = true func scrollViewDidScroll(scrollView: UIScrollView) { if collectionView.contentOffset.y >= (collectionView.contentSize.height - collectionView.bounds.size.height) { if hasMoreToShow { hasMoreToShow = false Auxiliar.showLoadingHUDWithText("Retrieving products...", forView: self.view) var counter = 6 var newItemsForSale = [ItemForSale]() while counter <= 11 { newItemsForSale.append(allItemsForSale[counter]) counter++ } incorporateItems(newItemsForSale) } } } //-------------------------------------------------------------------------// // MARK: Incorporate new search items //-------------------------------------------------------------------------// func incorporateItems(items : [ItemForSale]) { var indexPath : NSIndexPath = NSIndexPath(forItem: 0, inSection: 0) var counter = collectionView.numberOfItemsInSection(0) var newItems = [NSIndexPath]() for item in items { indexPath = NSIndexPath(forItem: counter, inSection: 0) newItems.append(indexPath) let imageURL : NSURL = NSURL(string: item.imageAddr)! item.itemImage = UIImage(data: NSData(contentsOfURL: imageURL)!) itemsForSale.append(item) counter++ } collectionView.performBatchUpdates({ [unowned self]() -> Void in self.collectionView.insertItemsAtIndexPaths(newItems) }){ completed in Auxiliar.hideLoadingHUDInView(self.view) } } //-------------------------------------------------------------------------// // MARK: UICollectionViewDataSource //-------------------------------------------------------------------------// func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemsForSale.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemForSaleCell", forIndexPath: indexPath) as! ItemForSaleCell cell.index = indexPath.item cell.delegate = self cell.setupCellWithItem(itemsForSale[indexPath.item]) return cell } //-------------------------------------------------------------------------// // MARK: UICollectionViewDelegateFlowLayout //-------------------------------------------------------------------------// func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let cellWidth = self.view.frame.size.width/2 return CGSizeMake(cellWidth, 190 * multiplier) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } //-------------------------------------------------------------------------// // MARK: ItemForSaleCellDelegate //-------------------------------------------------------------------------// func addThisItemToShoppingCart(clickedItemIndex: Int) { let item = itemsForSale[clickedItemIndex] var found = false var message = "\(item.itemName) was added to shopping cart." if shoppingCartItems.count > 0 { for (index, cartItem) in shoppingCartItems.enumerate() { if cartItem.itemForSale.itemId == item.itemId { found = true cartItem.amount++ shoppingCartItems[index] = cartItem let lastLetterIdx = item.itemName.characters.count - 1 let lastLetter = NSString(string: item.itemName).substringFromIndex(lastLetterIdx) if lastLetter != "s" { message = "You have \(cartItem.amount) \(item.itemName)s in your shopping cart." } else { message = "You have \(cartItem.amount) \(item.itemName) in your shopping cart." } break } } } else { shoppingCartButton.enabled = true } if found == false { let cartItem = ShoppingCartItem() cartItem.itemForSale = item shoppingCartItems.append(cartItem) } Auxiliar.presentAlertControllerWithTitle("Item added!", andMessage: message, forViewController: self) } //-------------------------------------------------------------------------// // MARK: ShoppingCart_VC_Delegate //-------------------------------------------------------------------------// func shoppingCartItemsListChanged(cartItems: [ShoppingCartItem]) { shoppingCartItems = cartItems if shoppingCartItems.count == 0 { shoppingCartButton.enabled = false } } //-------------------------------------------------------------------------// // MARK: Ajust for bigger screen //-------------------------------------------------------------------------// func adjustForBiggerScreen() { for constraint in shopName.constraints { constraint.constant *= multiplier } headerHeightConstraint.constant *= multiplier shoppingCartButtonHeightConstraint.constant *= multiplier var fontSize = 25.0 * multiplier shopName.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) fontSize = 17.0 * multiplier shoppingCartButton.imageEdgeInsets = UIEdgeInsetsMake(5 * multiplier, 144 * multiplier, 5 * multiplier, 144 * multiplier) } //-------------------------------------------------------------------------// // MARK: Navigation //-------------------------------------------------------------------------// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier != nil) && (segue.identifier == "ToShoppingCart") { let vc = segue.destinationViewController as! ShoppingCart_VC vc.shoppingCartItems = shoppingCartItems vc.delegate = self } } //-------------------------------------------------------------------------// // MARK: Memory Warning //-------------------------------------------------------------------------// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9a094955b670718ee9cb43fa74b44821
34.398281
172
0.457342
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarViewController+FilesPopover.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import MobileCoreServices import WireSyncEngine extension ConversationInputBarViewController: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { uploadFiles(at: urls) } } extension ConversationInputBarViewController { func configPopover(docController: UIDocumentPickerViewController, sourceView: UIView, delegate: UIPopoverPresentationControllerDelegate, pointToView: UIView) { guard let popover = docController.popoverPresentationController else { return } popover.delegate = delegate popover.config(from: self, pointToView: pointToView, sourceView: sourceView) popover.permittedArrowDirections = .down } func createDocUploadActionSheet(sender: IconButton? = nil) -> UIAlertController { let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // Alert actions for debugging #if targetEnvironment(simulator) let plistHandler: ((UIAlertAction) -> Void) = { _ in ZMUserSession.shared()?.enqueue({ let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) guard let basePath = paths.first, let sourceLocation = Bundle.main.url(forResource: "CountryCodes", withExtension: "plist") else { return } let destLocation = URL(fileURLWithPath: basePath).appendingPathComponent(sourceLocation.lastPathComponent) try? FileManager.default.copyItem(at: sourceLocation, to: destLocation) self.uploadFile(at: destLocation) }) } controller.addAction(UIAlertAction(title: "CountryCodes.plist", style: .default, handler: plistHandler)) let size = UInt(ZMUserSession.shared()?.maxUploadFileSize ?? 0) + 1 let humanReadableSize = size / 1024 / 1024 controller.addAction(uploadTestAlertAction(size: size, title: "Big file (size = \(humanReadableSize) MB)", fileName: "BigFile.bin")) controller.addAction(uploadTestAlertAction(size: 20971520, title: "20 MB file", fileName: "20MBFile.bin")) controller.addAction(uploadTestAlertAction(size: 41943040, title: "40 MB file", fileName: "40MBFile.bin")) if ZMUser.selfUser()?.hasTeam == true { controller.addAction(uploadTestAlertAction(size: 83886080, title: "80 MB file", fileName: "80MBFile.bin")) controller.addAction(uploadTestAlertAction(size: 125829120, title: "120 MB file", fileName: "120MBFile.bin")) } #endif let uploadVideoHandler: ((UIAlertAction) -> Void) = { _ in self.presentImagePicker(with: .photoLibrary, mediaTypes: [kUTTypeMovie as String], allowsEditing: true, pointToView: self.videoButton.imageView) } controller.addAction(UIAlertAction(icon: .movie, title: "content.file.upload_video".localized, tintColor: view.tintColor, handler: uploadVideoHandler)) let takeVideoHandler: ((UIAlertAction) -> Void) = { _ in self.recordVideo() } controller.addAction(UIAlertAction(icon: .cameraShutter, title: "content.file.take_video".localized, tintColor: view.tintColor, handler: takeVideoHandler)) let browseHandler: ((UIAlertAction) -> Void) = { _ in let documentPickerViewController = UIDocumentPickerViewController(documentTypes: [kUTTypeItem as String], in: .import) documentPickerViewController.modalPresentationStyle = self.isIPadRegular() ? .popover : .fullScreen if self.isIPadRegular(), let sourceView = self.parent?.view, let pointToView = sender?.imageView { self.configPopover(docController: documentPickerViewController, sourceView: sourceView, delegate: self, pointToView: pointToView) } documentPickerViewController.delegate = self documentPickerViewController.allowsMultipleSelection = true self.parent?.present(documentPickerViewController, animated: true) } controller.addAction(UIAlertAction(icon: .ellipsis, title: "content.file.browse".localized, tintColor: view.tintColor, handler: browseHandler)) controller.addAction(.cancel()) controller.configPopover(pointToView: sender ?? view) return controller } @objc func docUploadPressed(_ sender: IconButton) { mode = ConversationInputBarViewControllerMode.textInput inputBar.textView.resignFirstResponder() let controller = createDocUploadActionSheet(sender: sender) present(controller, animated: true) } @objc func videoButtonPressed(_ sender: IconButton) { recordVideo() } private func recordVideo() { guard !CameraAccess.displayAlertIfOngoingCall(at: .recordVideo, from: self) else { return } presentImagePicker(with: .camera, mediaTypes: [kUTTypeMovie as String], allowsEditing: false, pointToView: videoButton.imageView) } #if targetEnvironment(simulator) private func uploadTestAlertAction(size: UInt, title: String, fileName: String) -> UIAlertAction { return UIAlertAction(title: title, style: .default, handler: {_ in ZMUserSession.shared()?.enqueue({ let randomData = Data.secureRandomData(length: UInt(size)) if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let fileURL = dir.appendingPathComponent(fileName) try? randomData.write(to: fileURL) self.uploadFile(at: fileURL) } }) }) } #endif }
048d56e01c1740a5e580b1ec261b8940
42.627329
145
0.632118
false
false
false
false
KoheiKanagu/hogehoge
refs/heads/master
EndTermExamAdder/EndTermExamAdder/ViewController.swift
mit
1
// // ViewController.swift // EndTermExamAdder // // Created by Kohei on 2014/12/09. // Copyright (c) 2014年 KoheiKanagu. All rights reserved. // import Cocoa import EventKit class ViewController: NSViewController { @IBOutlet var myTextField: NSTextField? @IBOutlet var myComboBox: NSComboBox? let eventStore = EKEventStore() var calEventList: NSArray? override func viewDidLoad() { super.viewDidLoad() calEventList = eventStore.calendarsForEntityType(EKEntityTypeEvent) for var i=0; i<calEventList?.count; i++ { myComboBox?.insertItemWithObjectValue((calEventList![i] as EKCalendar).title, atIndex: (myComboBox?.numberOfItems)!) } } @IBAction func addButtonAction(sender: AnyObject) { if myComboBox?.indexOfSelectedItem == -1 { println("ComboBox未選択") return } let contents = loadHTML((myTextField?.stringValue)!) if contents == nil { println("HTMLが見つかりません") return } let year = (formalWithRule("<td align=\"right\" width=\"...\"><b>(.*)</b></td>", content: contents! as NSString)!)[0] as NSString let subjects = formalWithRule("<tr bgcolor=\"#FFFFFF\">\\n(.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n).*\"center\">", content: contents!)! for string in subjects{ let dateAndTimeRaw = formalWithRule("<td width=\"200\" align=\"center\">(.*)</td>", content: string as NSString) let dateAndTime = (dateAndTimeRaw![0] as NSString).componentsSeparatedByString("/") let date = dateAndTime[0] as NSString let time = dateAndTime[1] as NSString let name = (formalWithRule("<td name=\"rsunam_r\" width=\"286\">(.*)</td>", content: string as NSString)!)[0] as NSString let clas = (formalWithRule("<td name=\"clas\" align=\"center\" >(.*)</td>", content: string as NSString)!)[0] as NSString let teacher = (formalWithRule("<td name=\"kyoin\" width=\"162\">(.*)<br></td>", content: string as NSString)!)[0] as NSString let convertedDate = convertDate(rawYearString: year, rawDateString: date, rawTimeString: time) makeCalender(eventStore, title: name + clas, startDate: convertedDate.startTime, endDate: convertedDate.endTime, calendar: calEventList![myComboBox!.indexOfSelectedItem] as EKCalendar, notes: teacher) } } func convertDate(#rawYearString: NSString, rawDateString: NSString, rawTimeString: NSString) -> (startTime: NSDate, endTime: NSDate) { let calender = NSCalendar.currentCalendar() let components = NSDateComponents() let year = convertYear(rawYearString) components.year = year let array = rawDateString.componentsSeparatedByString("(") let array2 = (array[0] as NSString).componentsSeparatedByString("/") components.month = (array2[0] as NSString).integerValue components.day = (array2[1] as NSString).integerValue var convertedTime = convertTime(rawTimeString) components.hour = convertedTime.startTime!.hour components.minute = convertedTime.startTime!.minute let startTime = calender.dateFromComponents(components) components.hour = convertedTime.endTime!.hour components.minute = convertedTime.endTime!.minute let endTime = calender.dateFromComponents(components) return (startTime!, endTime!) } func convertYear(yearRawString: NSString) -> (Int) { let array = yearRawString.componentsSeparatedByString("&") var year: Int = ((array[0] as NSString).stringByReplacingOccurrencesOfString("年度", withString: "") as NSString).integerValue if (array[1] as NSString).hasSuffix("後期") { year++ } return year } func convertTime(rawTimeString: NSString) -> (startTime: NSDateComponents?, endTime: NSDateComponents?) { switch rawTimeString { case "1時限": return (makeNSDateComponents(hour: 9, minute: 30), makeNSDateComponents(hour: 10, minute: 30)) case "2時限": return (makeNSDateComponents(hour: 11, minute: 00), makeNSDateComponents(hour: 12, minute: 00)) case "3時限": return (makeNSDateComponents(hour: 13, minute: 30), makeNSDateComponents(hour: 14, minute: 30)) case "4時限": return (makeNSDateComponents(hour: 15, minute: 00), makeNSDateComponents(hour: 16, minute: 00)) case "5時限": return (makeNSDateComponents(hour: 16, minute: 30), makeNSDateComponents(hour: 17, minute: 30)) case "6時限": return (makeNSDateComponents(hour: 18, minute: 30), makeNSDateComponents(hour: 19, minute: 30)) case "7時限": return (makeNSDateComponents(hour: 20, minute: 00), makeNSDateComponents(hour: 21, minute: 00)) default: return (nil, nil) } } func makeNSDateComponents(#hour: Int, minute: Int) -> (NSDateComponents) { let components = NSDateComponents() components.hour = hour components.minute = minute return components } func loadHTML(pathString: NSString) -> (NSString?) { if pathString.length == 0 { return nil } let url: NSURL = NSURL(fileURLWithPath: pathString)! let contents = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: nil) return contents } func formalWithRule(rule:NSString, content:NSString) -> (NSArray?) { var resultArray = [NSString]() var error:NSError? let regex = NSRegularExpression(pattern: rule, options: NSRegularExpressionOptions.CaseInsensitive, error: &error); if error != nil { return nil } var matches = (regex?.matchesInString(content, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, content.length))) as Array<NSTextCheckingResult> for match:NSTextCheckingResult in matches { resultArray.append(content.substringWithRange(match.rangeAtIndex(1))) } return resultArray } func makeCalender(eventStore: EKEventStore, title: NSString, startDate: NSDate, endDate: NSDate, calendar: EKCalendar, notes: NSString) { eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted, error) -> Void in if !granted { println("カレンダーにアクセスできません") println("セキュリティとプライバシーからカレンダーへのアクセスを許可してください") return } let event = EKEvent(eventStore: eventStore) event.title = title event.startDate = startDate event.endDate = endDate event.calendar = calendar event.notes = notes var error: NSErrorPointer = nil if eventStore.saveEvent(event, span: EKSpanThisEvent, commit: true, error: error) { NSLog("%@に%@を%@から%@までの予定として追加しました", calendar.title, title, startDate, endDate) }else{ println("\(title)を追加できませんでした.") } }) } }
8f5b1c4548e5f8bdc6a9a8f6048e70fd
41.258621
168
0.614035
false
false
false
false
BenEmdon/swift-algorithm-club
refs/heads/master
Brute-Force String Search/BruteForceStringSearch.swift
mit
3
/* Brute-force string search */ extension String { func indexOf(_ pattern: String) -> String.Index? { for i in self.characters.indices { var j = i var found = true for p in pattern.characters.indices{ if j == self.characters.endIndex || self[j] != pattern[p] { found = false break } else { j = self.characters.index(after: j) } } if found { return i } } return nil } }
f8db815ef65b700fa153d89ad819dd72
22.086957
71
0.474576
false
false
false
false
neonichu/SwiftShell
refs/heads/master
SwiftShell/Pipes.swift
mit
1
/* * Released under the MIT License (MIT), http://opensource.org/licenses/MIT * * Copyright (c) 2014 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com) * * Contributors: * Kåre Morstøl, https://github.com/kareman - initial API and implementation. */ /** This file contains operators and functions inspired by Functional Programming. It can be used on its own. */ infix operator |> { precedence 50 associativity left } public func |> <T,U> (lhs: T, rhs: T -> U) -> U { return rhs(lhs) } /** Lazily return a sequence containing the elements of source, in order, that satisfy the predicate includeElement */ public func filter <S : SequenceType> (includeElement: (S.Generator.Element) -> Bool) (source: S) -> LazyFilterSequence<S> { return source.lazy.filter(includeElement) } /** Return an `Array` containing the sorted elements of `source` according to 'isOrderedBefore'. Requires: `isOrderedBefore` is a `strict weak ordering <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>` over `elements`. */ public func sorted <S : SequenceType> (isOrderedBefore: (S.Generator.Element, S.Generator.Element) -> Bool) (source: S) -> [S.Generator.Element] { return source.sort(isOrderedBefore) } /** Lazily return a sequence containing the results of mapping transform over source. */ public func map <S: SequenceType, T> (transform: (S.Generator.Element) -> T) (source: S) -> LazyMapSequence<S,T> { return source.lazy.map(transform) } /** Return the result of repeatedly calling combine with an accumulated value initialized to initial and each element of sequence, in turn. */ public func reduce <S : SequenceType, U> (initial: U, combine: (U, S.Generator.Element) -> U) (sequence: S) -> U { return sequence.reduce(initial, combine: combine) } /** Split text over delimiter, returning an array. */ public func split (delimiter delimiter: String = "\n")(text: String) -> [String] { return text.componentsSeparatedByString(delimiter) } /** Insert separator between each item in elements. */ public func join <C : RangeReplaceableCollectionType, S : SequenceType where S.Generator.Element == C> (separator: C) (elements: S) -> JoinSequence<S> { return elements.joinWithSeparator(separator) } /** Turn a sequence into an array. For use after the |> operator. */ public func toArray <S : SequenceType> (sequence: S) -> [S.Generator.Element] { return Array(sequence) } /** Discard all elements in `tobedropped` from sequence. */ public func drop <S : SequenceType, T : Equatable where S.Generator.Element == T> (tobedropped: [T]) (sequence: S) -> LazyFilterSequence<S> { return sequence |> filter { !tobedropped.contains($0) } } /** Return at most the first `numbertotake` elements of sequence */ public func take <S : SequenceType, T where S.Generator.Element == T> (numbertotake: Int)(sequence: S) -> [T] { var generator = sequence.generate() var result = [T]() for _ in 0..<numbertotake { if let value = generator.next() { result.append(value) } else { break } } return result }
d92521cb08f2a39983f1c15bd0209b8e
27.728972
118
0.708848
false
false
false
false
SuPair/firefox-ios
refs/heads/master
Client/Frontend/Browser/BackForwardTableViewCell.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage class BackForwardTableViewCell: UITableViewCell { private struct BackForwardViewCellUX { static let bgColor = UIColor.Photon.Grey50 static let faviconWidth = 29 static let faviconPadding: CGFloat = 20 static let labelPadding = 20 static let borderSmall = 2 static let borderBold = 5 static let IconSize = 23 static let fontSize: CGFloat = 12.0 static let textColor = UIColor.Photon.Grey80 } lazy var faviconView: UIImageView = { let faviconView = UIImageView(image: FaviconFetcher.defaultFavicon) faviconView.backgroundColor = UIColor.Photon.White100 faviconView.layer.cornerRadius = 6 faviconView.layer.borderWidth = 0.5 faviconView.layer.borderColor = UIColor(white: 0, alpha: 0.1).cgColor faviconView.layer.masksToBounds = true faviconView.contentMode = .center return faviconView }() lazy var label: UILabel = { let label = UILabel() label.text = " " label.font = label.font.withSize(BackForwardViewCellUX.fontSize) label.textColor = BackForwardViewCellUX.textColor return label }() var connectingForwards = true var connectingBackwards = true var isCurrentTab = false { didSet { if isCurrentTab { label.font = UIFont(name: "HelveticaNeue-Bold", size: BackForwardViewCellUX.fontSize) } } } var site: Site? { didSet { if let s = site { faviconView.setFavicon(forSite: s, onCompletion: { [weak self] (color, url) in if s.tileURL.isLocal { self?.faviconView.image = UIImage(named: "faviconFox") self?.faviconView.image = self?.faviconView.image?.createScaled(CGSize(width: BackForwardViewCellUX.IconSize, height: BackForwardViewCellUX.IconSize)) self?.faviconView.backgroundColor = UIColor.Photon.White100 return } self?.faviconView.image = self?.faviconView.image?.createScaled(CGSize(width: BackForwardViewCellUX.IconSize, height: BackForwardViewCellUX.IconSize)) self?.faviconView.backgroundColor = color == .clear ? .white : color }) var title = s.title if title.isEmpty { title = s.url } label.text = title setNeedsLayout() } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear selectionStyle = .none contentView.addSubview(faviconView) contentView.addSubview(label) faviconView.snp.makeConstraints { make in make.height.equalTo(BackForwardViewCellUX.faviconWidth) make.width.equalTo(BackForwardViewCellUX.faviconWidth) make.centerY.equalTo(self) make.leading.equalTo(self.snp.leading).offset(BackForwardViewCellUX.faviconPadding) } label.snp.makeConstraints { make in make.centerY.equalTo(self) make.leading.equalTo(faviconView.snp.trailing).offset(BackForwardViewCellUX.labelPadding) make.trailing.equalTo(self.snp.trailing).offset(-BackForwardViewCellUX.labelPadding) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } var startPoint = CGPoint(x: rect.origin.x + BackForwardViewCellUX.faviconPadding + CGFloat(Double(BackForwardViewCellUX.faviconWidth)*0.5), y: rect.origin.y + (connectingForwards ? 0 : rect.size.height/2)) var endPoint = CGPoint(x: rect.origin.x + BackForwardViewCellUX.faviconPadding + CGFloat(Double(BackForwardViewCellUX.faviconWidth)*0.5), y: rect.origin.y + rect.size.height - (connectingBackwards ? 0 : rect.size.height/2)) // flip the x component if RTL if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft { startPoint.x = rect.origin.x - startPoint.x + rect.size.width endPoint.x = rect.origin.x - endPoint.x + rect.size.width } context.saveGState() context.setLineCap(.square) context.setStrokeColor(BackForwardViewCellUX.bgColor.cgColor) context.setLineWidth(1.0) context.move(to: startPoint) context.addLine(to: endPoint) context.strokePath() context.restoreGState() } override func setHighlighted(_ highlighted: Bool, animated: Bool) { if highlighted { self.backgroundColor = UIColor(white: 0, alpha: 0.1) } else { self.backgroundColor = UIColor.clear } } override func prepareForReuse() { super.prepareForReuse() connectingForwards = true connectingBackwards = true isCurrentTab = false label.font = UIFont(name: "HelveticaNeue", size: BackForwardViewCellUX.fontSize) } }
124a235d38e60144f187d09cc6214dad
38.216783
174
0.62714
false
false
false
false
longsirhero/DinDinShop
refs/heads/master
DinDinShopDemo/DinDinShopDemo/首页/ViewControllers/WCProductRecommentVC.swift
mit
1
// // WCProductRecommentVC.swift // DinDinShopDemo // // Created by longsirHERO on 2017/9/4. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import UIKit class WCProductRecommentVC: WCBaseController { @IBOutlet weak var recommendField: UITextView! @IBOutlet weak var clearBtn: UIButton! @IBOutlet weak var comfirmBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() self.recommendField.layer.cornerRadius = 1.0 self.recommendField.layer.borderWidth = 1 self.recommendField.layer.borderColor = UIColor.flatGray().cgColor self.recommendField.layer.masksToBounds = true self.clearBtn.layer.cornerRadius = 5 self.clearBtn.layer.borderWidth = 1 self.clearBtn.layer.borderColor = RGBA(r: 82, g: 166, b: 229, a: 1.0).cgColor self.clearBtn.layer.masksToBounds = true self.comfirmBtn.setTitleColor(UIColor.white, for: .normal) self.comfirmBtn.backgroundColor = RGBA(r: 82, g: 166, b: 229, a: 1.0) self.comfirmBtn.layer.cornerRadius = 5 self.comfirmBtn.layer.borderWidth = 1 self.comfirmBtn.layer.borderColor = RGBA(r: 82, g: 166, b: 229, a: 1.0).cgColor self.comfirmBtn.layer.masksToBounds = true } @IBAction func clearClick(_ sender: UIButton) { self.recommendField.text = "" } @IBAction func comfirmClick(_ sender: UIButton) { if self.recommendField.text.characters.count == 0 { self.view.showWarning(words: "请填写留言") } } }
6fdb663c647eea238e4b4bad6caff08d
30.365385
87
0.647456
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/UIComponents/UIComponentsKit/LayoutConstants.swift
lgpl-3.0
1
import SwiftUI public enum LayoutConstants { public static let buttonCornerRadious: CGFloat = 8 public static let buttonMinHeight: CGFloat = 48 } extension LayoutConstants { public enum VerticalSpacing { public static let betweenContentGroups: CGFloat = 16 public static let betweenContentGroupsLarge: CGFloat = 24 public static let withinButtonsGroup: CGFloat = 16 public static let withinFormGroup: CGFloat = 4 } } extension LayoutConstants { enum Text { enum FontSize { static let title: CGFloat = 20 static let heading: CGFloat = 16 static let subheading: CGFloat = 14 static let body: CGFloat = 14 static let formField: CGFloat = 16 } enum LineHeight { static let title: CGFloat = 30 static let heading: CGFloat = 24 static let subheading: CGFloat = 20 static let body: CGFloat = 20 static let formField: CGFloat = 24 } enum LineSpacing { static let title: CGFloat = LineHeight.title - FontSize.title static let heading: CGFloat = LineHeight.heading - FontSize.heading static let subheading: CGFloat = LineHeight.subheading - FontSize.subheading static let body: CGFloat = LineHeight.body - FontSize.body static let formField: CGFloat = LineHeight.formField - FontSize.formField } } }
7ae5b2254744d053bfa7f1a4afd86f57
30.553191
88
0.633176
false
false
false
false
joshdholtz/old_harmonic
refs/heads/master
Classes/HarmonicFormatter.swift
mit
1
// // HarmonicFormatter.swift // Harmonic // // Created by Josh Holtz on 8/3/14. // Copyright (c) 2014 Josh Holtz. All rights reserved. // class HarmonicFormatter { var formatters = Dictionary<String, HarmonicFormatterFunction>(); // MARK: Singleton class var sharedInstance : HarmonicFormatter { struct Static { static let instance : HarmonicFormatter = HarmonicFormatter() } return Static.instance } // MARK: Public func addFormatter(name : String, formatter : HarmonicFormatterFunction) { self.formatters[name] = formatter; } func removeFormatter(name : String) { self.formatters.removeValueForKey(name); } func getFormatter(name : String) -> HarmonicFormatterFunction? { return self.formatters[name]; } } class HarmonicFormatterFunction { typealias formatterType = (value : AnyObject) -> (AnyObject); var formatter : formatterType; init(formatter : formatterType) { self.formatter = formatter; } }
34fa792a769dca7cbea09d1bcff45047
22.042553
77
0.636784
false
false
false
false
EgeTart/MedicineDMW
refs/heads/master
DWM/MedicineController.swift
mit
1
// // MedicineController.swift // DWM // // Created by MacBook on 9/26/15. // Copyright © 2015 EgeTart. All rights reserved. // import UIKit class MedicineController: UIViewController { @IBOutlet weak var medicineTableView: UITableView! var parentType = "" var medicineTypeID = "" var medicineCategory = 1 var fiveLevelMedicine = [Dictionary<String, String!>]() let db = MedicineDB.sharedInstance() override func viewDidLoad() { super.viewDidLoad() medicineTableView.tableFooterView = UIView() getFifthLevelMedicine() print(medicineTypeID) } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBarHidden = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = false } } extension MedicineController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fiveLevelMedicine.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("medicineCell", forIndexPath: indexPath) cell.textLabel!.text = fiveLevelMedicine[indexPath.row]["name"] cell.detailTextLabel!.text = parentType return cell } func getFifthLevelMedicine() { db.open() var tableName = "west_medicine" if (medicineCategory == 2) { tableName = "chinese_medicine" } let results = db.executeQuery("select id, name from \(tableName) where medicine_type_id=\(medicineTypeID)", withArgumentsInArray: nil) while(results.next()) { let id = results.stringForColumn("id") let name = results.stringForColumn("name") let medicine = ["id": id, "name": name] fiveLevelMedicine.append(medicine) } db.close() } } extension MedicineController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("detail", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destinationVC = segue.destinationViewController as! DetailController destinationVC.medicineCategory = medicineCategory destinationVC.medicineID = fiveLevelMedicine[medicineTableView.indexPathForSelectedRow!.row]["id"]! } }
63668d9147044eeb941caa499a7fd64b
27.050505
142
0.645893
false
false
false
false
eburns1148/CareKit
refs/heads/master
Sample/OCKSample/HamstringStretch.swift
bsd-3-clause
2
/* Copyright (c) 2016, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CareKit /** Struct that conforms to the `Activity` protocol to define a hamstring stretch activity. */ struct HamstringStretch: Activity { // MARK: Activity let activityType: ActivityType = .hamstringStretch func carePlanActivity() -> OCKCarePlanActivity { // Create a weekly schedule. let startDate = DateComponents(year: 2016, month: 01, day: 01) let schedule = OCKCareSchedule.weeklySchedule(withStartDate: startDate as DateComponents, occurrencesOnEachDay: [2, 1, 1, 1, 1, 1, 2]) // Get the localized strings to use for the activity. let title = NSLocalizedString("Hamstring Stretch", comment: "") let summary = NSLocalizedString("5 mins", comment: "") let instructions = NSLocalizedString("Gentle hamstring stretches on both legs.", comment: "") // Create the intervention activity. let activity = OCKCarePlanActivity.intervention( withIdentifier: activityType.rawValue, groupIdentifier: nil, title: title, text: summary, tintColor: Colors.blue.color, instructions: instructions, imageURL: nil, schedule: schedule, userInfo: nil ) return activity } }
499084c674e5e1bf671b4fa9c4777de2
43.059701
142
0.721206
false
false
false
false
joostholslag/BNRiOS
refs/heads/master
iOSProgramming6ed/24 - Accessibility/Solutions/Photorama/Photorama/PhotosViewController.swift
gpl-3.0
1
// // Copyright © 2015 Big Nerd Ranch // import UIKit class PhotosViewController: UIViewController, UICollectionViewDelegate { @IBOutlet var collectionView: UICollectionView! var store: PhotoStore! let photoDataSource = PhotoDataSource() override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = photoDataSource collectionView.delegate = self store.fetchInterestingPhotos() { (photosResult) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock() { switch photosResult { case let .Success(photos): print("Successfully found \(photos.count) interesting photos.") self.photoDataSource.photos = photos case let .Failure(error): self.photoDataSource.photos.removeAll() print("Error fetching interesting photos: \(error)") } self.collectionView.reloadSections(NSIndexSet(index: 0)) } } } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let photo = photoDataSource.photos[indexPath.row] // Download the image data, which could take some time store.fetchImageForPhoto(photo, completion: { (result) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock() { // The index path for the photo might have changed between the // time the request started and finished, so find the most // recent index path // (Note: You will have an error on the next line; you will fix it shortly) let photoIndex = self.photoDataSource.photos.indexOf(photo)! let photoIndexPath = NSIndexPath(forItem: photoIndex, inSection: 0) // When the request finishes, only update the cell if it's still visible if let cell = self.collectionView.cellForItemAtIndexPath(photoIndexPath) as? PhotoCollectionViewCell { cell.updateWithImage(photo.image) } } }) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showPhoto" { if let selectedIndexPath = collectionView.indexPathsForSelectedItems()?.first { let photo = photoDataSource.photos[selectedIndexPath.row] let destinationVC = segue.destinationViewController as! PhotoInfoViewController destinationVC.photo = photo destinationVC.store = store } } } }
7e4dd8762e9e634ee83acdfc634a0b4c
38
95
0.55
false
false
false
false
sammyd/VT_InAppPurchase
refs/heads/master
projects/01_GettingStarted/001_ChallengeComplete/GreenGrocer/GreenGrocerIAPHelper.swift
mit
10
/* * Copyright (c) 2015 Razeware LLC * * 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 enum GreenGrocerPurchase: String { case AdRemoval = "AdRemoval" case NewShoppingLists_One = "NewShoppingLists_One" case NewShoppingLists_Five = "NewShoppingLists_Five" case NewShoppingLists_Ten = "NewShoppingLists_Ten" var productId: String { return (NSBundle.mainBundle().bundleIdentifier ?? "") + "." + rawValue } init?(productId: String) { guard let bundleID = NSBundle.mainBundle().bundleIdentifier where productId.hasPrefix(bundleID) else { return nil } self.init(rawValue: productId.stringByReplacingOccurrencesOfString(bundleID + ".", withString: "")) } }
dbdab2b33eefe12c9ab5efce47c4cae6
40.238095
103
0.753322
false
false
false
false
bradleymackey/WWDC-2017
refs/heads/master
EmojiSort.playground/Sources/UIView+Animations.swift
mit
1
import Foundation import UIKit extension UIView { func bounce(_ times:Int, completion: (()->Void)?) { CATransaction.begin() CATransaction.setCompletionBlock(completion) let animation = CABasicAnimation(keyPath: "transform.scale") animation.duration = 0.15 // how long the animation will take animation.repeatCount = Float(times) animation.autoreverses = true // so it auto returns to 0 offset animation.fromValue = 1 animation.toValue = 1.1 layer.add(animation, forKey: "transform.scale") CATransaction.commit() } func shake(completion: (()->Void)?) { CATransaction.begin() CATransaction.setCompletionBlock(completion) let animation = CABasicAnimation(keyPath: "transform.translation.x") animation.duration = 0.03 animation.repeatCount = 10 animation.autoreverses = true animation.fromValue = -4 animation.toValue = 4 layer.add(animation, forKey: "transform.translation.x") CATransaction.commit() } func setAnchorPoint(anchorPoint: CGPoint) { var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y) var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y) newPoint = newPoint.applying(self.transform) oldPoint = oldPoint.applying(self.transform) var position = self.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y self.layer.position = position self.layer.anchorPoint = anchorPoint } }
82c5ad7bd17084fa076bdf4ad568dec3
31.625
133
0.737548
false
false
false
false
miroslavkovac/Lingo
refs/heads/master
Sources/Lingo/Pluralization/Common/OneTwoOther.swift
mit
1
import Foundation /// Used for Cornish, Inari Sami, Inuktitut, Lule Sami, Nama, Northern Sami, Skolt Sami, Southern Sami class OneTwoOther: AbstractPluralizationRule { let availablePluralCategories: [PluralCategory] = [.one, .two, .other] func pluralCategory(forNumericValue n: UInt) -> PluralCategory { if n == 1 { return .one } if n == 2 { return .two } return .other } }
db6ec70daf0bad6a91bda8dfd09144f2
23.2
102
0.570248
false
false
false
false
marcbbb/Spline
refs/heads/master
Spline/ViewController.swift
apache-2.0
1
// // ViewController.swift // Spline // // Created by balas on 22/10/2015. // Copyright © 2015 com.balas. All rights reserved. // import UIKit class ViewController: UIViewController { let curve = UIBezierPath() let shapeLayer = CAShapeLayer() var pointViewArray = [PointView]() var spline : SplineView! @IBOutlet var splineIB : SplineView! @IBOutlet var help : UILabel! @IBOutlet var slider : UISlider! @IBOutlet var viewProgrammatically : UIView! @IBOutlet var viewIB : UIView! @IBAction func didChange(sender : UISegmentedControl ){ if sender.selectedSegmentIndex == 0{ splineIB.interpolationType = .CatMull spline.interpolationType = .CatMull }else{ splineIB.interpolationType = .Hermite spline.interpolationType = .Hermite } } @IBAction func didChangeType(sender : UISegmentedControl ){ if sender.selectedSegmentIndex == 1{ viewProgrammatically.hidden = false viewIB.hidden = true }else{ viewProgrammatically.hidden = true viewIB.hidden = false } } override func viewDidLoad() { super.viewDidLoad() help.text = "Drag red control points to edit \n Tap on control point to remove \n Tap any where to add a new point " var points = [CGPoint]() for i in 0 ..< 4 { points.append(CGPoint(x: i * 60 + 30 + random()%100, y: 60 * i + 300)) } spline = SplineView(points: points, frame: self.viewProgrammatically.bounds) self.viewProgrammatically.addSubview(spline) } @IBAction func sliderValueChanged(slider: UISlider) { splineIB.contractionFactor = CGFloat( slider.value) spline.contractionFactor = CGFloat( slider.value) } }
71c71c9939dcd258c6bdf6ab3a4899d9
24.086957
120
0.668977
false
false
false
false
bhajian/raspi-remote
refs/heads/master
Carthage/Checkouts/ios-sdk/Source/VisualRecognitionV3/Tests/VisualRecognitionTests.swift
mit
1
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import XCTest import VisualRecognitionV3 class VisualRecognitionTests: XCTestCase { private var visualRecognition: VisualRecognition! private let classifierPrefix = "swift-sdk-unit-test-" private let timeout: NSTimeInterval = 60.0 private var examplesBaseball: NSURL! private var examplesCars: NSURL! private var examplesTrucks: NSURL! private var faces: NSURL! private var car: NSURL! private var obama: NSURL! private var sign: NSURL! private let obamaURL = "https://www.whitehouse.gov/sites/whitehouse.gov/files/images/" + "Administration/People/president_official_portrait_lores.jpg" private let carURL = "https://raw.githubusercontent.com/watson-developer-cloud/" + "java-sdk/master/src/test/resources/visual_recognition/car.png" private let signURL = "https://raw.githubusercontent.com/watson-developer-cloud/java-sdk/" + "master/src/test/resources/visual_recognition/open.png" // MARK: - Test Configuration /** Set up for each test by instantiating the service. */ override func setUp() { super.setUp() continueAfterFailure = false instantiateVisualRecognition() loadImageFiles() deleteStaleClassifiers() } /** Instantiate Visual Recognition. */ func instantiateVisualRecognition() { let bundle = NSBundle(forClass: self.dynamicType) guard let file = bundle.pathForResource("Credentials", ofType: "plist"), let credentials = NSDictionary(contentsOfFile: file) as? [String: String], let apiKey = credentials["VisualRecognitionAPIKey"] else { XCTFail("Unable to read credentials.") return } visualRecognition = VisualRecognition(apiKey: apiKey, version: "2016-05-10") } /** Load image files with class examples and test images. */ func loadImageFiles() { let bundle = NSBundle(forClass: self.dynamicType) guard let examplesBaseball = bundle.URLForResource("baseball", withExtension: "zip"), let examplesCars = bundle.URLForResource("cars", withExtension: "zip"), let examplesTrucks = bundle.URLForResource("trucks", withExtension: "zip"), let faces = bundle.URLForResource("faces", withExtension: "zip"), let car = bundle.URLForResource("car", withExtension: "png"), let obama = bundle.URLForResource("obama", withExtension: "jpg"), let sign = bundle.URLForResource("sign", withExtension: "jpg") else { XCTFail("Unable to locate sample image files.") return } self.examplesBaseball = examplesBaseball self.examplesCars = examplesCars self.examplesTrucks = examplesTrucks self.faces = faces self.car = car self.obama = obama self.sign = sign } /** Delete any stale classifiers previously created by our unit tests. */ func deleteStaleClassifiers() { let description = "Delete any stale classifiers previously created by our unit tests." let expectation = expectationWithDescription(description) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.name.hasPrefix(self.classifierPrefix) { self.visualRecognition.deleteClassifier(classifier.classifierID) } } expectation.fulfill() } waitForExpectations() } /** Fail false negatives. */ func failWithError(error: NSError) { XCTFail("Positive test failed with error: \(error)") } /** Fail false positives. */ func failWithResult<T>(result: T) { XCTFail("Negative test returned a result.") } /** Wait for expectations. */ func waitForExpectations() { waitForExpectationsWithTimeout(timeout) { error in XCTAssertNil(error, "Timeout") } } // MARK: - Positive Tests /** Retrieve a list of user-trained classifiers. */ func testGetClassifiers() { let description = "Retrieve a list of user-trained classifiers." let expectation = expectationWithDescription(description) visualRecognition.getClassifiers(failWithError) { classifiers in expectation.fulfill() } waitForExpectations() } /** Train a classifier with only positive examples. */ func testCreateDeleteClassifier1() { let description1 = "Train a classifier with only positive examples." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "baseball-cars-trucks" let baseball = Class(name: "baseball", examples: examplesBaseball) let cars = Class(name: "car", examples: examplesCars) let trucks = Class(name: "truck", examples: examplesTrucks) let classes = [baseball, cars, trucks] var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: classes, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 3) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Check that our classifier can be retrieved." let expectation2 = expectationWithDescription(description2) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { expectation2.fulfill() return } } XCTFail("The created classifier could not be retrieved from the service.") } waitForExpectations() let description3 = "Delete the custom classifier." let expectation3 = expectationWithDescription(description3) visualRecognition.deleteClassifier(id, failure: failWithError) { expectation3.fulfill() } waitForExpectations() } /** Train a classifier with both positive and negative examples. */ func testCreateDeleteClassifier2() { let description1 = "Train a classifier with both positive and negative examples." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Check that our classifier can be retrieved." let expectation2 = expectationWithDescription(description2) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { expectation2.fulfill() return } } XCTFail("The created classifier could not be retrieved from the service.") } waitForExpectations() let description3 = "Delete the custom classifier." let expectation3 = expectationWithDescription(description3) visualRecognition.deleteClassifier(id, failure: failWithError) { expectation3.fulfill() } waitForExpectations() } /** Get information about a classifier. */ func testGetClassifier() { let description1 = "Train a classifier with both positive and negative examples." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Get information about the custom classifier." let expectation2 = expectationWithDescription(description2) visualRecognition.getClassifier(id, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) expectation2.fulfill() } waitForExpectations() let description3 = "Delete the custom classifier." let expectation3 = expectationWithDescription(description3) visualRecognition.deleteClassifier(id, failure: failWithError) { expectation3.fulfill() } waitForExpectations() } /** Classify images by URL using the default classifier and all default parameters. */ func testClassifyByURL1() { let description = "Classify images by URL using the default classifier." let expectation = expectationWithDescription(description) visualRecognition.classify(obamaURL, failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 1) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertEqual(image?.sourceURL, self.obamaURL) XCTAssertEqual(image?.resolvedURL, self.obamaURL) XCTAssertNil(image?.image) XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, "default") XCTAssertEqual(classifier?.name, "default") XCTAssertEqual(classifier?.classes.count, 1) XCTAssertEqual(classifier?.classes.first?.classification, "person") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation.fulfill() } waitForExpectations() } /** Classify images by URL using the default classifier and specifying default parameters. */ func testClassifyByURL2() { let description = "Classify images by URL using the default classifier." let expectation = expectationWithDescription(description) visualRecognition.classify( obamaURL, owners: ["IBM"], classifierIDs: ["default"], showLowConfidence: true, outputLanguage: "en", failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 1) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertEqual(image?.sourceURL, self.obamaURL) XCTAssertEqual(image?.resolvedURL, self.obamaURL) XCTAssertNil(image?.image) XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, "default") XCTAssertEqual(classifier?.name, "default") XCTAssertEqual(classifier?.classes.count, 1) XCTAssertEqual(classifier?.classes.first?.classification, "person") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation.fulfill() } waitForExpectations() } /** Classify images by URL using a custom classifier and all default parameters. */ func testClassifyByURL3() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 10.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify(carURL, classifierIDs: [id], failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 0) // Should be 1? Bug with service? XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertEqual(image?.sourceURL, self.carURL) XCTAssertEqual(image?.resolvedURL, self.carURL) XCTAssertNil(image?.image) XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, id) XCTAssertEqual(classifier?.name, name) XCTAssertEqual(classifier?.classes.count, 1) XCTAssertEqual(classifier?.classes.first?.classification, "car") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation4.fulfill() } waitForExpectations() } /** Classify images by URL using a custom classifier and specifying default parameters. */ func testClassifyByURL4() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 10.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify( carURL, owners: ["me"], classifierIDs: [id], showLowConfidence: true, outputLanguage: "en", failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 0) // Should be 1? Bug with service? XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertEqual(image?.sourceURL, self.carURL) XCTAssertEqual(image?.resolvedURL, self.carURL) XCTAssertNil(image?.image) XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, id) XCTAssertEqual(classifier?.name, name) XCTAssertEqual(classifier?.classes.count, 1) XCTAssertEqual(classifier?.classes.first?.classification, "car") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation4.fulfill() } waitForExpectations() } /** Classify images by URL with both the default classifier and a custom classifier. */ func testClassifyByURL5() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 10.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify( carURL, classifierIDs: ["default", id], failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 1) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertEqual(image?.sourceURL, self.carURL) XCTAssertEqual(image?.resolvedURL, self.carURL) XCTAssertNil(image?.image) XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 2) // verify the image's default classifier let classifier1 = image?.classifiers.first XCTAssertEqual(classifier1?.classifierID, "default") XCTAssertEqual(classifier1?.name, "default") XCTAssertEqual(classifier1?.classes.count, 4) XCTAssertEqual(classifier1?.classes.first?.classification, "car") if let score = classifier1?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } // verify the image's custom classifier let classifier2 = image?.classifiers.last XCTAssertEqual(classifier2?.classifierID, id) XCTAssertEqual(classifier2?.name, name) XCTAssertEqual(classifier2?.classes.count, 1) XCTAssertEqual(classifier2?.classes.first?.classification, "car") if let score = classifier2?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation4.fulfill() } waitForExpectations() } /** Classify uploaded images using the default classifier and all default parameters. */ func testClassifyImage1() { let description = "Classify uploaded images using the default classifier." let expectation = expectationWithDescription(description) visualRecognition.classify(car, failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 1) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertNil(image?.sourceURL) XCTAssertNil(image?.resolvedURL) XCTAssert(image?.image == "car.png") XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, "default") XCTAssertEqual(classifier?.name, "default") XCTAssertEqual(classifier?.classes.count, 4) XCTAssertEqual(classifier?.classes.first?.classification, "car") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation.fulfill() } waitForExpectations() } /** Classify uploaded images using the default classifier and specifying default parameters. */ func testClassifyImage2() { let description = "Classify uploaded images using the default classifier." let expectation = expectationWithDescription(description) visualRecognition.classify( car, owners: ["IBM"], classifierIDs: ["default"], showLowConfidence: true, outputLanguage: "en", failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 1) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertNil(image?.sourceURL) XCTAssertNil(image?.resolvedURL) XCTAssert(image?.image == "car.png") XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, "default") XCTAssertEqual(classifier?.name, "default") XCTAssertEqual(classifier?.classes.count, 4) XCTAssertEqual(classifier?.classes.first?.classification, "car") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation.fulfill() } waitForExpectations() } /** Classify uploaded images using a custom classifier and all default parameters. */ func testClassifyImage3() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 10.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify(car, classifierIDs: [id], failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 0) // Should be 1? Bug with service? XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertNil(image?.sourceURL) XCTAssertNil(image?.resolvedURL) XCTAssert(image?.image == "car.png") XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, id) XCTAssertEqual(classifier?.name, name) XCTAssertEqual(classifier?.classes.count, 1) XCTAssertEqual(classifier?.classes.first?.classification, "car") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation4.fulfill() } waitForExpectations() } /** Classify uploaded images using a custom classifier and specifying default parameters. */ func testClassifyImage4() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 10.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify( car, owners: ["me"], classifierIDs: [id], showLowConfidence: true, outputLanguage: "en", failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 0) // Should be 1? Bug with service? XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertNil(image?.sourceURL) XCTAssertNil(image?.resolvedURL) XCTAssert(image?.image == "car.png") XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 1) // verify the image's classifier let classifier = image?.classifiers.first XCTAssertEqual(classifier?.classifierID, id) XCTAssertEqual(classifier?.name, name) XCTAssertEqual(classifier?.classes.count, 1) XCTAssertEqual(classifier?.classes.first?.classification, "car") if let score = classifier?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation4.fulfill() } waitForExpectations() } /** Classify uploaded images with both the default classifier and a custom classifier. */ func testClassifyImage5() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 10.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify( car, classifierIDs: ["default", id], failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 1) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 1) // verify the image's metadata let image = classifiedImages.images.first XCTAssertNil(image?.sourceURL) XCTAssertNil(image?.resolvedURL) XCTAssert(image?.image == "car.png") XCTAssertNil(image?.error) XCTAssertEqual(image?.classifiers.count, 2) // verify the image's default classifier let classifier1 = image?.classifiers.first XCTAssertEqual(classifier1?.classifierID, "default") XCTAssertEqual(classifier1?.name, "default") XCTAssertEqual(classifier1?.classes.count, 4) XCTAssertEqual(classifier1?.classes.first?.classification, "car") if let score = classifier1?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } // verify the image's custom classifier let classifier2 = image?.classifiers.last XCTAssertEqual(classifier2?.classifierID, id) XCTAssertEqual(classifier2?.name, name) XCTAssertEqual(classifier2?.classes.count, 1) XCTAssertEqual(classifier2?.classes.first?.classification, "car") if let score = classifier2?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } expectation4.fulfill() } waitForExpectations() } /** Classify multiple images using a custom classifier. */ func testClassifyImage6() { let description1 = "Create a custom classifier." let expectation1 = expectationWithDescription(description1) let name = classifierPrefix + "cars-trucks" let cars = Class(name: "car", examples: examplesCars) var classifierID: String? visualRecognition.createClassifier( name, positiveExamples: [cars], negativeExamples: examplesTrucks, failure: failWithError) { classifier in XCTAssertEqual(classifier.name, name) XCTAssertEqual(classifier.classes.count, 1) classifierID = classifier.classifierID expectation1.fulfill() } waitForExpectations() guard let id = classifierID else { XCTFail("Classifier ID should not be nil.") return } let description2 = "Wait for the classifier to be trained." let expectation2 = expectationWithDescription(description2) let seconds = 15.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue()) { expectation2.fulfill() } waitForExpectations() let description3 = "Ensure the classifier was trained." let expectation3 = expectationWithDescription(description3) visualRecognition.getClassifiers(failWithError) { classifiers in for classifier in classifiers { if classifier.classifierID == id { XCTAssertEqual(classifier.status, "ready") expectation3.fulfill() return } } XCTFail("The created classifier needs more time to train. Increase the delay.") } waitForExpectations() let description4 = "Classify images by URL using a custom classifier." let expectation4 = expectationWithDescription(description4) visualRecognition.classify( examplesCars, classifierIDs: ["default", id], failure: failWithError) { classifiedImages in // verify classified images object XCTAssertEqual(classifiedImages.imagesProcessed, 16) XCTAssertNil(classifiedImages.warnings) XCTAssertEqual(classifiedImages.images.count, 16) for image in classifiedImages.images { // verify the image's metadata XCTAssertNil(image.sourceURL) XCTAssertNil(image.resolvedURL) XCTAssert(image.image?.hasPrefix("car") == true) XCTAssertNil(image.error) XCTAssertEqual(image.classifiers.count, 2) // verify the image's default classifier let classifier1 = image.classifiers.first XCTAssertEqual(classifier1?.classifierID, "default") XCTAssertEqual(classifier1?.name, "default") XCTAssert(classifier1?.classes.count >= 1) let classification = classifier1?.classes.first?.classification XCTAssert(classification == "car" || classification == "vehicle") if let score = classifier1?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } // verify the image's custom classifier let classifier2 = image.classifiers.last XCTAssertEqual(classifier2?.classifierID, id) XCTAssertEqual(classifier2?.name, name) XCTAssertEqual(classifier2?.classes.count, 1) XCTAssertEqual(classifier2?.classes.first?.classification, "car") if let score = classifier2?.classes.first?.score { XCTAssertGreaterThan(score, 0.5) } } expectation4.fulfill() } waitForExpectations() } /** Detect faces by URL. */ func testDetectFacesByURL() { let description = "Detect faces by URL." let expectation = expectationWithDescription(description) visualRecognition.detectFaces(obamaURL, failure: failWithError) { faceImages in // verify face images object XCTAssertEqual(faceImages.imagesProcessed, 1) XCTAssertNil(faceImages.warnings) XCTAssertEqual(faceImages.images.count, 1) // verify the face image object let face = faceImages.images.first XCTAssertEqual(face?.sourceURL, self.obamaURL) XCTAssertEqual(face?.resolvedURL, self.obamaURL) XCTAssertNil(face?.image) XCTAssertNil(face?.error) XCTAssertEqual(face?.faces.count, 1) // verify the age let age = face?.faces.first?.age XCTAssert(age?.min >= 55) XCTAssert(age?.max <= 64) XCTAssert(age?.score >= 0.25) // verify the face location let location = face?.faces.first?.location XCTAssert(location?.height == 185) XCTAssert(location?.left == 200) XCTAssert(location?.top == 65) XCTAssert(location?.width == 175) // verify the gender let gender = face?.faces.first?.gender XCTAssert(gender?.gender == "MALE") XCTAssert(gender?.score >= 0.75) // verify the identity let identity = face?.faces.first?.identity XCTAssert(identity?.name == "Barack Obama") XCTAssert(identity?.score >= 0.75) expectation.fulfill() } waitForExpectations() } /** Detect faces in an uploaded image */ func testDetectFacesByImage1() { let description = "Detect faces in an uploaded image." let expectation = expectationWithDescription(description) visualRecognition.detectFaces(obama, failure: failWithError) { faceImages in // verify face images object XCTAssertEqual(faceImages.imagesProcessed, 1) XCTAssertNil(faceImages.warnings) XCTAssertEqual(faceImages.images.count, 1) // verify the face image object let face = faceImages.images.first XCTAssertNil(face?.sourceURL) XCTAssertNil(face?.resolvedURL) XCTAssertEqual(face?.image, "obama.jpg") XCTAssertNil(face?.error) XCTAssertEqual(face?.faces.count, 1) // verify the age let age = face?.faces.first?.age XCTAssert(age?.min >= 55) XCTAssert(age?.max <= 64) XCTAssert(age?.score >= 0.25) // verify the face location let location = face?.faces.first?.location XCTAssert(location?.height == 185) XCTAssert(location?.left == 200) XCTAssert(location?.top == 65) XCTAssert(location?.width == 175) // verify the gender let gender = face?.faces.first?.gender XCTAssert(gender?.gender == "MALE") XCTAssert(gender?.score >= 0.75) // verify the identity let identity = face?.faces.first?.identity XCTAssert(identity?.name == "Barack Obama") XCTAssert(identity?.score >= 0.75) expectation.fulfill() } waitForExpectations() } /** Detect faces in uploaded images. */ func testDetectFacesByImage2() { let description = "Detect faces in uploaded images." let expectation = expectationWithDescription(description) visualRecognition.detectFaces(faces, failure: failWithError) { faceImages in // verify face images object XCTAssertEqual(faceImages.imagesProcessed, 3) XCTAssertNil(faceImages.warnings) XCTAssertEqual(faceImages.images.count, 3) for image in faceImages.images { // verify the face image object XCTAssertNil(image.sourceURL) XCTAssertNil(image.resolvedURL) XCTAssert(image.image?.hasPrefix("faces.zip/faces/face") == true) XCTAssertNil(image.error) XCTAssertEqual(image.faces.count, 1) // verify the age let age = image.faces.first?.age XCTAssert(age?.min >= 18) XCTAssert(age?.max <= 44) XCTAssert(age?.score >= 0.25) // verify the face location let location = image.faces.first?.location XCTAssert(location?.height >= 100) XCTAssert(location?.left >= 30) XCTAssert(location?.top >= 20) XCTAssert(location?.width >= 90) // verify the gender let gender = image.faces.first?.gender XCTAssert(gender?.gender == "MALE") XCTAssert(gender?.score >= 0.75) // verify the identity if let identity = image.faces.first?.identity { XCTAssertEqual(identity.name, "Tiger Woods") XCTAssert(identity.score >= 0.75) } } expectation.fulfill() } waitForExpectations() } /** Recognize text by URL. */ func testRecognizeTextURL() { let description = "Recognize text by URL." let expectation = expectationWithDescription(description) visualRecognition.recognizeText(signURL, failure: failWithError) { wordImages in // verify the word images object XCTAssertEqual(wordImages.imagesProcessed, 1) XCTAssertNil(wordImages.warnings) XCTAssertEqual(wordImages.images.count, 1) // verify the word image object let image = wordImages.images.first XCTAssertEqual(image?.sourceURL, self.signURL) XCTAssertEqual(image?.resolvedURL, self.signURL) XCTAssertNil(image?.image) XCTAssertNil(image?.error) XCTAssertEqual(image?.text, "its\nopen") // verify first word let word1 = image?.words.first XCTAssertEqual(word1?.lineNumber, 0) XCTAssertNotNil(word1?.location) XCTAssert(word1?.score >= 0.9) XCTAssertEqual(word1?.word, "its") // verify second word let word2 = image?.words.last XCTAssertEqual(word2?.lineNumber, 1) XCTAssertNotNil(word2?.location) XCTAssert(word2?.score >= 0.9) XCTAssertEqual(word2?.word, "open") expectation.fulfill() } waitForExpectations() } /** Recognize text in an uploaded image. */ func testRecognizeTextByImage1() { let description = "Recognize text in an uploaded image." let expectation = expectationWithDescription(description) visualRecognition.recognizeText(sign, failure: failWithError) { wordImages in // verify the word images object XCTAssertEqual(wordImages.imagesProcessed, 1) XCTAssertNil(wordImages.warnings) XCTAssertEqual(wordImages.images.count, 1) // verify the word image object let image = wordImages.images.first XCTAssertNil(image?.sourceURL) XCTAssertNil(image?.resolvedURL) XCTAssertEqual(image?.image, "sign.jpg") XCTAssertNil(image?.error) XCTAssertEqual(image?.text, "notice\nincreased\ntrain traffic") // verify the first word let word1 = image?.words[0] XCTAssertEqual(word1?.lineNumber, 0) XCTAssertNotNil(word1?.location) XCTAssert(word1?.score >= 0.9) XCTAssertEqual(word1?.word, "notice") // verify the second word let word2 = image?.words[1] XCTAssertEqual(word2?.lineNumber, 1) XCTAssertNotNil(word2?.location) XCTAssert(word2?.score >= 0.9) XCTAssertEqual(word2?.word, "increased") // verify the third word let word3 = image?.words[2] XCTAssertEqual(word3?.lineNumber, 2) XCTAssertNotNil(word3?.location) XCTAssert(word3?.score >= 0.9) XCTAssertEqual(word3?.word, "train") // verify the fourth word let word4 = image?.words[3] XCTAssertEqual(word4?.lineNumber, 2) XCTAssertNotNil(word4?.location) XCTAssert(word4?.score >= 0.9) XCTAssertEqual(word4?.word, "traffic") expectation.fulfill() } waitForExpectations() } }
227245b6ced04671ba55a96cadddd0db
38.407054
99
0.589189
false
false
false
false
velvetroom/columbus
refs/heads/master
Source/View/Settings/VSettingsListCellStorage.swift
mit
1
import UIKit final class VSettingsListCellStorage:VSettingsListCell { private(set) weak var model:MSettingsStorage? override init(frame:CGRect) { super.init(frame:frame) let icon:UIImageView = UIImageView() icon.isUserInteractionEnabled = false icon.translatesAutoresizingMaskIntoConstraints = false icon.clipsToBounds = true icon.contentMode = UIViewContentMode.center icon.image = #imageLiteral(resourceName: "assetGenericStorage") let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.isUserInteractionEnabled = false label.text = String.localizedView(key:"VSettingsListCellStorage_title") label.font = UIFont.medium(size:VSettingsListCellStorage.Constants.titleFontSize) label.textColor = UIColor.colourBackgroundDark let button:UIButton = UIButton() button.clipsToBounds = true button.translatesAutoresizingMaskIntoConstraints = false button.addTarget( self, action:#selector(selectorHighlighted(sender:)), for:UIControlEvents.touchDown) button.addTarget( self, action:#selector(selectorUnhighlighted(sender:)), for:UIControlEvents.touchUpOutside) button.addTarget( self, action:#selector(selectorButton(sender:)), for:UIControlEvents.touchUpInside) addSubview(icon) addSubview(label) addSubview(button) NSLayoutConstraint.equalsVertical( view:icon, toView:self) NSLayoutConstraint.leftToLeft( view:icon, toView:self) NSLayoutConstraint.width( view:icon, constant:VSettingsListCellStorage.Constants.iconWidth) NSLayoutConstraint.equals( view:button, toView:self) NSLayoutConstraint.equalsVertical( view:label, toView:self) NSLayoutConstraint.leftToRight( view:label, toView:icon) NSLayoutConstraint.widthGreaterOrEqual( view:label) } required init?(coder:NSCoder) { return nil } override func config( controller:CSettings, model:MSettingsProtocol) { super.config( controller:controller, model:model) guard let model:MSettingsStorage = model as? MSettingsStorage else { return } self.model = model } //MARK: selectors @objc private func selectorHighlighted(sender button:UIButton) { alpha = VSettingsListCellStorage.Constants.alphaHighlighted } @objc private func selectorUnhighlighted(sender button:UIButton) { alpha = 1 } @objc private func selectorButton(sender button:UIButton) { selectorUnhighlighted(sender:button) guard let database:Database = model?.database, let settings:DSettings = model?.settings else { return } controller?.openMemory( database:database, settings:settings) } }
4ed14e2c56c133adeaad941195579d05
26.265625
89
0.588539
false
false
false
false
getstalkr/stalkr-cloud
refs/heads/master
Sources/StalkrCloud/Models/TeamMembership.swift
mit
1
// // TeamMembership.swift // stalkr-cloud // // Created by Matheus Martins on 5/5/17. // // import JWT import Vapor import FluentProvider import Foundation final class TeamMembership: Model { let storage = Storage() struct Keys { static let id = TeamMembership.idKey static let teamId = Team.foreignIdKey static let userId = User.foreignIdKey } var teamId: Identifier var userId: Identifier init(teamId: Identifier, userId: Identifier) { self.teamId = teamId self.userId = userId } required init(row: Row) throws { teamId = try row.get(Keys.teamId) userId = try row.get(Keys.userId) } func makeRow() throws -> Row { var row = Row() try row.set(Keys.teamId, teamId) try row.set(Keys.userId, userId) return row } } // MARK: Relations extension TeamMembership { var team: Parent<TeamMembership, Team> { return parent(id: teamId) } var user: Parent<TeamMembership, User> { return parent(id: userId) } } extension Team { var teamMemberships: Children<Team, TeamMembership> { return children() } } extension User { var teamMemberships: Children<User, TeamMembership> { return children() } } // Preparations extension TeamMembership: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { c in c.id() let teamId = Field(name: Keys.teamId, type: .int, optional: false, unique: false, default: nil, primaryKey: true) let userId = Field(name: Keys.userId, type: .int, optional: false, unique: false, default: nil, primaryKey: true) c.field(teamId) c.field(userId) c.foreignKey(for: Team.self) c.foreignKey(for: User.self) } } static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSONRepresentable extension TeamMembership: JSONRepresentable { func makeJSON() throws -> JSON { var json = JSON() try json.set(Keys.id, self.id) try json.set(Keys.teamId, self.teamId) try json.set(Keys.userId, self.userId) return json } } // MARK: ResponseRepresentable extension TeamMembership: ResponseRepresentable { }
42808bf80aaa4a78278bce2873281a87
21.772727
78
0.587226
false
false
false
false
chrislzm/TimeAnalytics
refs/heads/master
Time Analytics/TACommuteDetailViewController.swift
mit
1
// // TACommuteDetailViewController.swift // Time Analytics // // Shows details about a TACommuteSegment: // - Summary statistics // - Line chart with data points and trend line if there are at least 2 or 3 data points respectively (LineChartView) // - Map location (MapView) // - Commute history with commute highlighted whose detail view this belongs to (TableView) // - Time spent at place departure point before the departure on this commute (TableView) // - Time spent at place arrival point after the arrival on this commute (TableView) // // Created by Chris Leung on 5/22/17. // Copyright © 2017 Chris Leung. All rights reserved. // import Charts import CoreLocation import MapKit import UIKit class TACommuteDetailViewController: TADetailViewController, UITableViewDelegate { // MARK: Properties var startName:String? var startLat:Double! var startLon:Double! var startTime:NSDate! var endName:String? var endLat:Double! var endLon:Double! var endTime:NSDate! var commuteHistoryTableData = [TACommuteSegment]() var timeBeforeDepartingTableData = [TAPlaceSegment]() var timeAfterArrivingTableData = [TAPlaceSegment]() var didTapOnDepartureTable:Bool = false var didTapOnArrivalTable:Bool = false var selectedIndexPath:IndexPath! // Stores the index of the item whose detail view this belongs to // MARK: Outlets @IBOutlet weak var totalCommutesLabel: UILabel! @IBOutlet weak var pastMonthTotalCommutesLabel: UILabel! @IBOutlet weak var averageTimeLabel: UILabel! @IBOutlet weak var totalTimeLabel: UILabel! @IBOutlet weak var lineChartView: LineChartView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var commuteHistoryTableHeaderLabel: UILabel! @IBOutlet weak var commuteHistoryTableView: UITableView! @IBOutlet weak var timeBeforeDepartingTableHeaderLabel: UILabel! @IBOutlet weak var timeBeforeDepartingTableView: UITableView! @IBOutlet weak var timeAfterArrivingTableHeaderLabel: UILabel! @IBOutlet weak var timeAfterArrivingTableView: UITableView! // MARK: Actions @IBAction func didTapOnMapView(_ sender: Any) { showDetailMapViewController() } @IBAction func didTapOnLineChartView(_ sender: Any) { showDetailLineChartViewController("Length of Commute from \(startName!) to \(endName!)") } //MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() // Setup the view setTitle() // Get data for this place, to be used below let(commuteDates,commuteLengths,totalCommutes,totalCommuteTime) = getDataForThisCommute() // SETUP CHART AND MAP VIEWS setupLineChartView(lineChartView, commuteDates, commuteLengths) lineChartXVals = commuteDates lineChartYVals = commuteLengths setupMapView(mapView) // SETUP SUMMARY LABELS totalCommutesLabel.text = "\(totalCommutes)" let lastMonthCommutes = getNumLastMonthCommutes() pastMonthTotalCommutesLabel.text = "\(lastMonthCommutes)" let averageCommuteTimeString = (StopWatch(totalSeconds: Int(totalCommuteTime)/totalCommutes)).simpleTimeString averageTimeLabel.text = averageCommuteTimeString let totalCommuteTimeString = (StopWatch(totalSeconds: Int(totalCommuteTime))).simpleTimeString totalTimeLabel.text = totalCommuteTimeString // SETUP TABLEVIEWS // Styles commuteHistoryTableView.separatorStyle = .none timeBeforeDepartingTableView.separatorStyle = .none timeAfterArrivingTableView.separatorStyle = .none // Data Sources commuteHistoryTableData = getEntityObjectsWithQuery("TACommuteSegment", "startLat == %@ AND startLon == %@ AND endLat == %@ AND endLon == %@", [startLat,startLon,endLat,endLon], "startTime", false) as! [TACommuteSegment] setSelectedIndexPathForCommute() // Find and set the table indexpath for the row whose detail view this belongs to timeBeforeDepartingTableData = getDeparturePlaceHistory(commuteHistoryTableData) timeAfterArrivingTableData = getDestinationPlaceHistory(commuteHistoryTableData) // SETUP TABLE HEADER LABELS setCommuteHistoryTableHeaderLabelText(totalCommutes) setTimeBeforeDepartingTableHeaderLabel() setTimeAfterArrivingTableHeaderLabel() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Select and scroll to the item whose detail view this belongs to commuteHistoryTableView.selectRow(at: selectedIndexPath, animated: true, scrollPosition: .middle) // Check if place names were updated, and update if necessary if didTapOnDepartureTable { updatePlaceNames(true) didTapOnDepartureTable = false } else if didTapOnArrivalTable { updatePlaceNames(false) didTapOnArrivalTable = false } // Deselect row if we selected one that caused a segue if let selectedRowIndexPath = timeBeforeDepartingTableView.indexPathForSelectedRow { timeBeforeDepartingTableView.deselectRow(at: selectedRowIndexPath, animated: true) } else if let selectedRowIndexPath = timeAfterArrivingTableView.indexPathForSelectedRow { timeAfterArrivingTableView.deselectRow(at: selectedRowIndexPath, animated: true) } } // MARK: UITableView Data Source Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count:Int? if tableView == commuteHistoryTableView { count = commuteHistoryTableData.count } else if tableView == timeBeforeDepartingTableView { count = timeBeforeDepartingTableData.count } else if tableView == timeAfterArrivingTableView { count = timeAfterArrivingTableData.count } return count! } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell() if tableView == commuteHistoryTableView { let commute = commuteHistoryTableData[indexPath.row] let commuteCell = tableView.dequeueReusableCell(withIdentifier: "TACommuteDetailCommuteTableViewCell", for: indexPath) as! TACommuteDetailCommuteTableViewCell // Get descriptions and assign to cell label let (timeInOutString,lengthString,dateString) = generateCommuteStringDescriptions(commute,currentYear) commuteCell.timeLabel.text = timeInOutString commuteCell.lengthLabel.text = lengthString commuteCell.dateLabel.text = dateString // Select (highlight) the cell that contains the commute that this detail view belongs to if commute.startTime == startTime, commute.endTime == endTime { selectedIndexPath = indexPath highlightTableCell(commuteCell) } cell = commuteCell } else if tableView == timeBeforeDepartingTableView { let place = timeBeforeDepartingTableData[indexPath.row] let placeCell = tableView.dequeueReusableCell(withIdentifier: "TACommuteDetailDepartureTableViewCell", for: indexPath) as! TACommuteDetailDepartureTableViewCell // Get descriptions and assign to cell label let (timeInOutString,lengthString,dateString) = generatePlaceStringDescriptions(place,currentYear) placeCell.timeLabel.text = timeInOutString placeCell.lengthLabel.text = lengthString placeCell.dateLabel.text = dateString cell = placeCell } else if tableView == timeAfterArrivingTableView { let place = timeAfterArrivingTableData[indexPath.row] let placeCell = tableView.dequeueReusableCell(withIdentifier: "TACommuteDetailDestinationTableViewCell", for: indexPath) as! TACommuteDetailDestinationTableViewCell // Get descriptions and assign to cell label let (timeInOutString,lengthString,dateString) = generatePlaceStringDescriptions(place,currentYear) placeCell.timeLabel.text = timeInOutString placeCell.lengthLabel.text = lengthString placeCell.dateLabel.text = dateString cell = placeCell } return cell } // MARK: Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == commuteHistoryTableView, indexPath != selectedIndexPath { // Don't allow the user to highlight another row whose detail view this doesn't belong to tableView.deselectRow(at: indexPath, animated: false) } else if tableView == timeBeforeDepartingTableView { // Save tap so we know to update the place name, in case it was edited didTapOnDepartureTable = true let place = timeBeforeDepartingTableData[indexPath.row] showPlaceDetailViewController(place) } else if tableView == timeAfterArrivingTableView { didTapOnArrivalTable = true let place = timeAfterArrivingTableData[indexPath.row] showPlaceDetailViewController(place) } } // Don't allow the user to unhighlight the row whose detail view this belongs to func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? { if tableView == commuteHistoryTableView { return nil } else { return indexPath } } // MARK: Data Methods // Find the row in the table whose detail view this belongs to func setSelectedIndexPathForCommute() { var dataIndex = 0 for i in 0..<commuteHistoryTableData.count { if commuteHistoryTableData[i].startTime == startTime, commuteHistoryTableData[i].endTime == endTime { dataIndex = i break } } selectedIndexPath = IndexPath(row: dataIndex, section: 0) } // Convenience method for assembling data needed to setup the view func getDataForThisCommute() -> ([Double],[Double],Int,Double) { let commutes = getEntityObjectsWithQuery("TACommuteSegment", "startLat == %@ AND startLon == %@ AND endLat == %@ AND endLon == %@", [startLat,startLon,endLat,endLon], "startTime", true) as! [TACommuteSegment] let totalCommutes = commutes.count var totalCommuteTime:Double = 0 // These two arrays are used in the Line Chart var commuteLengths = [Double]() var commuteDates = [Double]() for commute in commutes { let startTime = commute.startTime! as Date let endTime = commute.endTime! as Date let commuteTime = endTime.timeIntervalSince(startTime) totalCommuteTime += commuteTime commuteLengths.append(commuteTime) commuteDates.append(startTime.timeIntervalSinceReferenceDate) } return (commuteDates,commuteLengths,totalCommutes,totalCommuteTime) } // Get total number of times we made this commute over the last month func getNumLastMonthCommutes() -> Int { let oneMonthAgo = Date() - 2678400 // There are this many seconds in a month let lastMonthCommutes = getEntityObjectsWithQuery("TACommuteSegment", "startLat == %@ AND startLon == %@ AND endLat == %@ AND endLon == %@ AND startTime >= %@", [startLat,startLon,endLat,endLon,oneMonthAgo], nil, nil) return lastMonthCommutes.count } // Gets a list of place data for the departure place on these commutes func getDeparturePlaceHistory(_ commutes:[TACommuteSegment]) -> [TAPlaceSegment] { var departurePlaceHistory = [TAPlaceSegment]() for commute in commutes { let place = getEntityObjectsWithQuery("TAPlaceSegment", "lat == %@ AND lon == %@ AND endTime == %@", [commute.startLat,commute.startLon,commute.startTime!], nil, nil) as! [TAPlaceSegment] departurePlaceHistory.append(place[0]) } return departurePlaceHistory } // Gets a list of place data for the destination on these commutes func getDestinationPlaceHistory(_ commutes:[TACommuteSegment]) -> [TAPlaceSegment] { var destinationPlaceHistory = [TAPlaceSegment]() for commute in commutes { let place = getEntityObjectsWithQuery("TAPlaceSegment", "lat == %@ AND lon == %@ AND startTime == %@", [commute.endLat,commute.endLon,commute.endTime!], nil, nil) as! [TAPlaceSegment] destinationPlaceHistory.append(place[0]) } return destinationPlaceHistory } // If the user tapped on a place and renamed it, we need to reflect that change in this view func updatePlaceNames(_ isDeparturePlace:Bool) { if isDeparturePlace { let startPlace = getTAPlaceSegment(startLat, startLon, startTime as Date, false) if startName != startPlace.name { startName = startPlace.name setTitle() setTimeBeforeDepartingTableHeaderLabel() } } else { let endPlace = getTAPlaceSegment(endLat, endLon, endTime as Date, true) if endName != endPlace.name { endName = endPlace.name setTitle() setTimeAfterArrivingTableHeaderLabel() } } } // MARK: View Methods func setTitle() { title = "\(startName!) to \(endName!)" } func setCommuteHistoryTableHeaderLabelText(_ totalCommutes:Int) { commuteHistoryTableHeaderLabel.text = " Commute History - \(totalCommutes) Total" } func setTimeBeforeDepartingTableHeaderLabel() { timeBeforeDepartingTableHeaderLabel.text = " \(startName!) - Before Departure" } func setTimeAfterArrivingTableHeaderLabel() { timeAfterArrivingTableHeaderLabel.text = " \(endName!) - After Arrival" } // Displays both start and end points of the commute and centers+sizes the map accordingly to show them both override func setupMapView(_ mapView:MKMapView) { super.setupMapView(mapView) let startAnnotation = MKPointAnnotation() let startCoordinate = CLLocationCoordinate2D(latitude: startLat, longitude: startLon) startAnnotation.coordinate = startCoordinate startAnnotation.title = startName mapView.addAnnotation(startAnnotation) let endAnnotation = MKPointAnnotation() let endCoordinate = CLLocationCoordinate2D(latitude: endLat, longitude: endLon) endAnnotation.coordinate = endCoordinate endAnnotation.title = endName mapView.addAnnotation(endAnnotation) // Move the screen up slightly since the pin sticks out at the top var centerLat = (startLat+endLat) / 2 // Midpoint of two latitudes centerLat += abs(startLat-endLat) / 8 // Move view up by 20% (1/8) let centerCoordinate = CLLocationCoordinate2D(latitude: centerLat, longitude: (startLon+endLon)/2) let startLocation = CLLocation(latitude: startLat, longitude: startLon) let endLocation = CLLocation(latitude: endLat, longitude: endLon) let distanceInMeters = startLocation.distance(from: endLocation) // result is in meter let regionSize = CLLocationDistance(distanceInMeters * 1.5) // Expand the view region to 1.5 times the distance between the two points let viewRegion = MKCoordinateRegionMakeWithDistance(centerCoordinate, regionSize, regionSize); mapView.setRegion(viewRegion, animated: true) // Save data for segue mapViewAnnotations.append(startAnnotation) mapViewAnnotations.append(endAnnotation) mapViewRegionSize = regionSize mapViewCenter = centerCoordinate } }
91abb7ac2c2f1cd700ed4fbe6a480283
42.546419
228
0.671804
false
false
false
false