repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gokselkoksal/Core
|
refs/heads/master
|
Core/Sources/Subscription.swift
|
mit
|
1
|
//
// Subscription.swift
// Core
//
// Created by Göksel Köksal on 04/06/2017.
// Copyright © 2017 GK. All rights reserved.
//
import Foundation
public protocol AnySubscriber: class, NavigationPerformer {
func _update(with state: State)
}
public protocol Subscriber: AnySubscriber {
associatedtype StateType: State
func update(with state: StateType)
}
public extension Subscriber {
func _update(with state: State) {
guard let state = state as? StateType else { return }
update(with: state)
}
}
internal struct Subscription {
internal private(set) weak var subscriber: AnySubscriber?
private let queue: DispatchQueue
internal init(subscriber: AnySubscriber?, queue: DispatchQueue) {
self.subscriber = subscriber
self.queue = queue
}
internal func notify(with newState: State) {
execute {
self.subscriber?._update(with: newState)
}
}
internal func notify(with navigation: Navigation) {
execute {
self.subscriber?.perform(navigation)
}
}
private func execute(_ block: @escaping () -> Void) {
if queue == DispatchQueue.main && Thread.isMainThread {
block()
} else {
queue.async {
block()
}
}
}
}
|
c6bc57cf73d30fdfb82a8a6eb69bd9e8
| 20.172414 | 67 | 0.666938 | false | false | false | false |
sarahspins/Loop
|
refs/heads/master
|
Loop/Models/Glucose.swift
|
apache-2.0
|
1
|
//
// GlucoseRxMessage.swift
// Loop
//
// Created by Nathan Racklyeft on 5/30/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import xDripG5
extension Glucose: SensorDisplayable {
var stateDescription: String {
let status: String
switch self.status {
case .OK:
status = ""
case .LowBattery:
status = NSLocalizedString(" Low Battery", comment: "The description of a low G5 transmitter battery with a leading space")
case .Unknown(let value):
status = String(format: "%02x", value)
}
return String(format: "%1$@ %2$@", String(state), status)
}
var trendType: GlucoseTrend? {
guard trend < Int(Int8.max) else {
return nil
}
switch trend {
case let x where x <= -30:
return .DownDownDown
case let x where x <= -20:
return .DownDown
case let x where x <= -10:
return .Down
case let x where x < 10:
return .Flat
case let x where x < 20:
return .Up
case let x where x < 30:
return .UpUp
default:
return .UpUpUp
}
}
}
|
e55d43512c2563162d4a2977ef63798b
| 23.98 | 135 | 0.542034 | false | false | false | false |
nahive/spotify-notify
|
refs/heads/master
|
SpotifyNotify/Storage/UserPreferences.swift
|
unlicense
|
1
|
//
// UserPreferences.swift
// SpotifyNotify
//
// Created by 先生 on 22/02/2018.
// Copyright © 2018 Szymon Maślanka. All rights reserved.
//
import Foundation
import Magnet
enum StatusBarIcon: Int {
case `default` = 0
case monochromatic = 1
case none = 99
init(value: Int?) {
guard let value = value else { self = .none; return }
self = StatusBarIcon(rawValue: value) ?? .none
}
}
struct UserPreferences {
private struct Keys {
static let appAlreadySetup = "already.setup.key"
static let notificationsEnabled = "notifications.enabled.key"
static let notificationsPlayPause = "notifications.playpause.key"
static let notificationsSound = "notifications.sound.key"
static let notificationsDisableOnFocus = "notifications.focus.key"
static let notificationsLength = "notifications.length.key"
static let startOnLogin = "startonlogin.key"
static let showAlbumArt = "showalbumart.key"
static let roundAlbumArt = "roundalbumart.key"
static let showSongProgress = "songprogress.key"
static let menuIcon = "menuicon.key"
static let shortcutKeyCode = "shortcut.keycode.key"
static let shortcutModifiers = "shortcut.modifiers.key"
}
private let defaults = UserDefaults.standard
var appAlreadySetup: Bool {
get { return defaults.bool(forKey: Keys.appAlreadySetup) }
set { defaults.set(newValue, forKey: Keys.appAlreadySetup) }
}
var notificationsEnabled: Bool {
get { return defaults.bool(forKey: Keys.notificationsEnabled) }
set { defaults.set(newValue, forKey: Keys.notificationsEnabled) }
}
var notificationsPlayPause: Bool {
get { return defaults.bool(forKey: Keys.notificationsPlayPause) }
set { defaults.set(newValue, forKey: Keys.notificationsPlayPause) }
}
var notificationsSound: Bool {
get { return defaults.bool(forKey: Keys.notificationsSound) }
set { defaults.set(newValue, forKey: Keys.notificationsSound) }
}
var notificationsDisableOnFocus: Bool {
get { return defaults.bool(forKey: Keys.notificationsDisableOnFocus) }
set { defaults.set(newValue, forKey: Keys.notificationsDisableOnFocus) }
}
var notificationsLength: Int {
get { return defaults.integer(forKey: Keys.notificationsLength) }
set { defaults.set(newValue, forKey: Keys.notificationsLength) }
}
var startOnLogin: Bool {
get { return defaults.bool(forKey: Keys.startOnLogin) }
set { defaults.set(newValue, forKey: Keys.startOnLogin) }
}
var showAlbumArt: Bool {
get { return defaults.bool(forKey: Keys.showAlbumArt) }
set { defaults.set(newValue, forKey: Keys.showAlbumArt) }
}
var roundAlbumArt: Bool {
get { return defaults.bool(forKey: Keys.roundAlbumArt) }
set { defaults.set(newValue, forKey: Keys.roundAlbumArt) }
}
var showSongProgress: Bool {
get { return defaults.bool(forKey: Keys.showSongProgress) }
set { defaults.set(newValue, forKey: Keys.showSongProgress) }
}
var menuIcon: StatusBarIcon {
get { return StatusBarIcon(value: defaults.integer(forKey: Keys.menuIcon)) }
set { defaults.set(newValue.rawValue, forKey: Keys.menuIcon) }
}
var shortcut: KeyCombo? {
get {
let keycode = defaults.integer(forKey: Keys.shortcutKeyCode)
let modifiers = defaults.integer(forKey: Keys.shortcutModifiers)
guard keycode != 0 && modifiers != 0 else { return nil }
return KeyCombo(QWERTYKeyCode: keycode, carbonModifiers: modifiers)
}
set {
guard let keyCombo = newValue else {
defaults.set(0, forKey: Keys.shortcutKeyCode)
defaults.set(0, forKey: Keys.shortcutModifiers)
return
}
defaults.set(keyCombo.QWERTYKeyCode, forKey: Keys.shortcutKeyCode)
defaults.set(keyCombo.modifiers, forKey: Keys.shortcutModifiers)
}
}
}
|
4f01f1e4d408c2b222c3b535ed77ba2f
| 30.92437 | 78 | 0.714135 | false | false | false | false |
mozilla-magnet/magnet-client
|
refs/heads/master
|
ios/NotificationsHelperIOS10.swift
|
mpl-2.0
|
1
|
//
// NotificationsHelperIOS10.swift
// Magnet
//
// Created by Francisco Jordano on 04/11/2016.
// Copyright © 2016 Mozilla. All rights reserved.
//
import Foundation
import UserNotifications
import UserNotificationsUI
import SwiftyJSON
@available(iOS 10.0, *)
class NotificationsHelperIOS10: NSObject, UNUserNotificationCenterDelegate {
private static let CATEGORY = "magnet.notifications.category"
override init() {
super.init()
UNUserNotificationCenter.currentNotificationCenter().delegate = self
}
func processNotifications(toNotify: Dictionary<String, String>) {
toNotify.keys.forEach { (url) in
let channel = toNotify[url]
processNotification(url, channel: channel!)
}
}
private func processNotification(url: String, channel: String) {
Log.l("Processing notification for \(url)")
fetchData(url, callback: { (json) in
do {
guard json[0] != nil && json[0]["description"] != nil && json[0]["title"] != nil else {
return
}
try self.showRichNotification(json[0]["title"].string!,
subtitle: "by \(channel)",
body: json[0]["description"].string!,
image: json[0]["image"].string,
url: url)
Log.l("Dispatching rich notification for \(json.rawString())")
} catch {
Log.w("Could not launch notification for \(url) : \(channel)")
}
})
}
private func fetchData(url: String, callback: ((JSON) -> Void)) {
let api = ApiMetadata()
let urls: NSArray = [url]
api.post("metadata", data: urls, callback: ApiCallback(success: { json in
callback(json)
}, error: { (err) in
debugPrint("Could not get metadata for \(url): \(err)")
}))
}
private func showRichNotification(title: String, subtitle: String, body: String, image: String?, url: String) {
let content = UNMutableNotificationContent()
content.title = title
content.subtitle = subtitle
content.body = body
if let _image: String = image! {
content.launchImageName = _image
}
content.categoryIdentifier = NotificationsHelperIOS10.CATEGORY
let action = UNNotificationAction(identifier: "visit", title: "Visit", options: UNNotificationActionOptions.Foreground)
let category = UNNotificationCategory(identifier: NotificationsHelperIOS10.CATEGORY, actions: [action], intentIdentifiers: [], options: [])
UNUserNotificationCenter.currentNotificationCenter().setNotificationCategories([category])
// Trigger this notification in 1 second from now.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: url, content: content, trigger: trigger)
UNUserNotificationCenter.currentNotificationCenter().addNotificationRequest(request, withCompletionHandler: {error in
guard let error = error else {
return
}
Log.w("Error while sending notification \(error)")
})
}
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
if (response.actionIdentifier == "visit") {
Log.l("Launching web page \(response.notification.request.identifier)")
let url = NSURL(string: response.notification.request.identifier)
UIApplication.sharedApplication().openURL(url!, options: [:], completionHandler: nil)
} else {
// We were clicked but not the visit (go to browser) action
// so we navigate to the deep link inside the app
let url = NSURL(string: "mozilla-magnet://item?url=\(response.notification.request.identifier)")
UIApplication.sharedApplication().openURL(url!, options: [:], completionHandler: nil)
}
}
}
|
57aa9cb8f2e3cbbcbcc68735d641bd7f
| 37.5 | 183 | 0.682597 | false | false | false | false |
warumono-for-develop/SwiftPageViewController
|
refs/heads/master
|
SwiftPageViewController/SwiftPageViewController/IntroViewController.swift
|
mit
|
1
|
//
// IntroViewController.swift
// Maniau1
//
// Created by kevin on 2017. 2. 24..
// Copyright © 2017년 warumono. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController
{
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var containerView: UIView!
fileprivate var introPageViewController: IntroPageViewController?
{
didSet
{
introPageViewController?.introPageViewControllerDataSource = self
introPageViewController?.introPageViewControllerDelegate = self
}
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .lightContent
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
pageControl.addTarget(self, action: #selector(IntroViewController.didChangePage), for: .valueChanged)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if let introPageViewController = segue.destination as? IntroPageViewController
{
self.introPageViewController = introPageViewController
}
}
}
extension IntroViewController
{
@IBAction func didTouch(_ sender: UIButton)
{
if sender.tag == 0
{
if pageControl.numberOfPages <= pageControl.currentPage + 1
{
return
}
introPageViewController?.pageTo(at: pageControl.numberOfPages - 1)
}
else if sender.tag == 1
{
introPageViewController?.next()
}
}
@objc fileprivate func didChangePage()
{
introPageViewController?.pageTo(at: pageControl.currentPage)
}
}
extension IntroViewController: IntroPageViewControllerDataSource
{
func introPageViewController(_ pageViewController: IntroPageViewController, numberOfPages pages: Int)
{
pageControl.numberOfPages = pages
}
}
extension IntroViewController: IntroPageViewControllerDelegate
{
func introPageViewController(_ pageViewController: IntroPageViewController, didChangePageIndex index: Int)
{
pageControl.currentPage = index
}
}
|
2dddf7d357d54e30ad4f8ecaee123dd9
| 21.311828 | 107 | 0.760482 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
refs/heads/master
|
TranslationEditor/StatefulStackView.swift
|
mit
|
1
|
//
// StatefulStackView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 16.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
enum DataState
{
// Data is not yet available, but is being retrieved
case loading
// No data was found
case empty
// An error occurred while retrieving data
case error
// Data was found and loaded successfully
case data
}
// This stack view is designed to change visible content based on program status
class StatefulStackView: UIStackView
{
// ATTRIBUTES -----------------
private var views = [DataState: Weak<UIView>]()
private var lastState: DataState?
// OTHER METHODS -------------
func dataLoaded(isEmpty: Bool = false)
{
setState(isEmpty ? .empty : .data)
}
func errorOccurred(title: String? = nil, description: String? = nil, canContinueWithData: Bool = true)
{
if !canContinueWithData || lastState != .data
{
if title != nil || description != nil
{
registerDefaultErrorView(heading: title, description: description)
}
setState(.error)
}
}
func setState(_ state: DataState)
{
if lastState == state
{
return
}
else
{
lastState = state
}
// Makes sure there exists a suitable view in the stack
if !views[state].exists({ $0.isDefined })
{
var defaultView: UIView?
switch state
{
case .loading: defaultView = DefaultLoadingView()
case .empty: defaultView = DefaultNoDataView()
case .error: defaultView = DefaultErrorView()
default: defaultView = nil
}
if let defaultView = defaultView
{
register(defaultView, for: state)
}
else
{
return
}
}
// Sets the view for the state visible and other views invisible
views.values.forEach { $0.value?.isHidden = true }
views[state]?.value?.isHidden = false
}
func register(_ view: UIView, for state: DataState)
{
// Removes any previous view for that state
if let previousView = views[state]?.value
{
removeArrangedSubview(previousView)
}
views[state] = Weak(view)
// Adds the view to this stack view if not already
if !view.isDescendant(of: self)
{
view.isHidden = true
addArrangedSubview(view)
}
}
func registerDefaultLoadingView(title: String? = nil)
{
let view = DefaultLoadingView()
if let title = title
{
view.title = title
}
register(view, for: .loading)
}
func registerDefaultErrorView(heading: String? = nil, description: String? = nil)
{
let view = DefaultErrorView()
if let heading = heading
{
view.title = heading
}
if let description = description
{
view.errorDescription = description
}
register(view, for: .error)
}
func registerDefaultNoDataView(heading: String? = nil, description: String? = nil)
{
let view = DefaultNoDataView()
if let heading = heading
{
view.title = heading
}
if let description = description
{
view.extraDescription = description
}
register(view, for: .empty)
}
}
|
dcb1d289d167c68e0c34c2d04923b3ea
| 18.81457 | 103 | 0.664104 | false | false | false | false |
AnthonyMDev/CrashlyticsRecorder
|
refs/heads/master
|
Pod/Classes/AnalyticsRecorder.swift
|
mit
|
1
|
//
// AnalyticsRecorder.swift
// CrashlyticsRecorder
//
// Created by David Whetstone on 1/7/19.
//
import Foundation
public protocol AnalyticsProtocol: class {
static func logEvent(_ name: String, parameters: [String: Any]?)
static func setUserProperty(_ value: String?, forName name: String)
static func setUserID(_ userID: String?)
static func setScreenName(_ screenName: String?, screenClass screenClassOverride: String?)
static func appInstanceID() -> String
static func resetAnalyticsData()
}
public class AnalyticsRecorder {
/// The `AnalyticsRecorder` shared instance to be used for recording Analytics events
public private(set) static var sharedInstance: AnalyticsRecorder?
private var analyticsClass: AnalyticsProtocol.Type
private init(analyticsClass: AnalyticsProtocol.Type) {
self.analyticsClass = analyticsClass
}
/**
Creates the `sharedInstance` with the `Analytics` class for the application. This method should be called in `application:didFinishLaunchingWithOptions:`.
- parameter analytics: The `Analytics` class from the `FirebaseCore` framework.
- returns: The created `FirebaseRecorder` shared instance
*/
public class func createSharedInstance(analytics analyticsClass: AnalyticsProtocol.Type) -> AnalyticsRecorder {
let recorder = AnalyticsRecorder(analyticsClass: analyticsClass)
sharedInstance = recorder
return recorder
}
public func logEvent(_ name: String, parameters: [String: Any]?) {
analyticsClass.logEvent(name, parameters: parameters)
}
public func setUserProperty(_ value: String?, forName name: String) {
analyticsClass.setUserProperty(value, forName: name)
}
public func setUserID(_ userID: String?) {
analyticsClass.setUserID(userID)
}
public func setScreenName(_ screenName: String?, screenClass screenClassOverride: String?) {
analyticsClass.setScreenName(screenName, screenClass: screenClassOverride)
}
public func appInstanceID() -> String {
return analyticsClass.appInstanceID()
}
public func resetAnalyticsData() {
analyticsClass.resetAnalyticsData()
}
}
public extension AnalyticsRecorder {
public func logEvent(_ name: AnalyticsEvent, parameters: [AnalyticsParameter: Any]? = nil) {
let parameters = parameters?.reduce(into: [:]) { result, x in result[x.key.rawValue] = x.value }
logEvent(name.rawValue, parameters: parameters)
}
public func setUserProperty(_ value: String?, forName name: AnalyticsUserProperty) {
analyticsClass.setUserProperty(value, forName: name.rawValue)
}
}
public enum AnalyticsEvent: String {
case addPaymentInfo = "add_payment_info"
case addToCart = "add_to_cart"
case addToWishlist = "add_to_wishlist"
case appOpen = "app_open"
case beginCheckout = "begin_checkout"
case campaignDetails = "campaign_details"
case checkoutProgress = "checkout_progress"
case earnVirtualCurrency = "earn_virtual_currency"
case ecommercePurchase = "ecommerce_purchase"
case generateLead = "generate_lead"
case joinGroup = "join_group"
case levelUp = "level_up"
case login = "login"
case postScore = "post_score"
case presentOffer = "present_offer"
case purchaseRefund = "purchase_refund"
case removeFromCart = "remove_from_cart"
case search = "search"
case selectContent = "select_content"
case setCheckoutOption = "set_checkout_option"
case share = "share"
case signUp = "sign_up"
case spendVirtualCurrency = "spend_virtual_currency"
case tutorialBegin = "tutorial_begin"
case tutorialComplete = "tutorial_complete"
case unlockAchievement = "unlock_achievement"
case viewItem = "view_item"
case viewItemList = "view_item_list"
case viewSearchResults = "view_search_results"
case levelStart = "level_start"
case levelEnd = "level_end"
}
public enum AnalyticsParameter: String {
case achievementID = "achievement_id"
case adNetworkClickID = "aclid"
case affiliation = "affiliation"
case campaign = "campaign"
case character = "character"
case checkoutStep = "checkout_step"
case checkoutOption = "checkout_option"
case content = "content"
case contentType = "content_type"
case coupon = "coupon"
case cP1 = "cp1"
case creativeName = "creative_name"
case creativeSlot = "creative_slot"
case currency = "currency"
case destination = "destination"
case endDate = "end_date"
case flightNumber = "flight_number"
case groupID = "group_id"
case index = "index"
case itemBrand = "item_brand"
case itemCategory = "item_category"
case itemID = "item_id"
case itemLocationID = "item_location_id"
case itemName = "item_name"
case itemList = "item_list"
case itemVariant = "item_variant"
case level = "level"
case location = "location"
case medium = "medium"
case numberOfNights = "number_of_nights"
case numberOfPassengers = "number_of_passengers"
case numberOfRooms = "number_of_rooms"
case origin = "origin"
case price = "price"
case quantity = "quantity"
case score = "score"
case searchTerm = "search_term"
case shipping = "shipping"
case signUpMethod = "sign_up_method"
case source = "source"
case startDate = "start_date"
case tax = "tax"
case term = "term"
case transactionID = "transaction_id"
case travelClass = "travel_class"
case value = "value"
case virtualCurrencyName = "virtual_currency_name"
case levelName = "level_name"
case success = "success"
}
public enum AnalyticsUserProperty: String {
case signUpMethod = "sign_up_method"
}
|
ddcb3b8c3c1d61be95510af6eca79a05
| 36.624277 | 159 | 0.618682 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
refs/heads/master
|
Source/LoadStateViewController.swift
|
apache-2.0
|
2
|
//
// LoadStateViewController.swift
// edX
//
// Created by Akiva Leffert on 5/13/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public enum LoadState {
case Initial
case Loaded
case Empty(icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?, buttonInfo : MessageButtonInfo?)
// if attributed message is set then message is ignored
// if message is set then the error is ignored
case Failed(error : NSError?, icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?, buttonInfo : MessageButtonInfo?)
var accessibilityMessage : String? {
switch self {
case Initial: return nil
case Loaded: return nil
case let Empty(info): return info.accessibilityMessage
case let Failed(info): return info.accessibilityMessage
}
}
var isInitial : Bool {
switch self {
case .Initial: return true
default: return false
}
}
var isLoaded : Bool {
switch self {
case .Loaded: return true
default: return false
}
}
var isError : Bool {
switch self {
case .Failed(_): return true
default: return false
}
}
static func failed(error : NSError? = nil, icon : Icon? = .UnknownError, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil, buttonInfo : MessageButtonInfo? = nil) -> LoadState {
return LoadState.Failed(error : error, icon : icon, message : message, attributedMessage : attributedMessage, accessibilityMessage : accessibilityMessage, buttonInfo : buttonInfo)
}
static func empty(icon icon : Icon?, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil, buttonInfo : MessageButtonInfo? = nil) -> LoadState {
return LoadState.Empty(icon: icon, message: message, attributedMessage: attributedMessage, accessibilityMessage : accessibilityMessage, buttonInfo : buttonInfo)
}
}
/// A controller should implement this protocol to support reloading with fullscreen errors for unknownErrors
@objc protocol LoadStateViewReloadSupport {
func loadStateViewReload()
}
class LoadStateViewController : UIViewController {
private let loadingView : UIView
private var contentView : UIView?
private let messageView : IconMessageView
private var delegate: LoadStateViewReloadSupport?
private var madeInitialAppearance : Bool = false
var state : LoadState = .Initial {
didSet {
// this sets a background color so when the view is pushed in it doesn't have a black or weird background
switch state {
case .Initial:
view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
default:
view.backgroundColor = UIColor.clearColor()
}
updateAppearanceAnimated(madeInitialAppearance)
}
}
var insets : UIEdgeInsets = UIEdgeInsetsZero {
didSet {
self.view.setNeedsUpdateConstraints()
}
}
init() {
messageView = IconMessageView()
loadingView = SpinnerView(size: .Large, color: .Primary)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var messageStyle : OEXTextStyle {
return messageView.messageStyle
}
override func loadView() {
self.view = PassthroughView()
}
func setupInController(controller : UIViewController, contentView : UIView) {
controller.addChildViewController(self)
didMoveToParentViewController(controller)
self.contentView = contentView
contentView.alpha = 0
controller.view.addSubview(loadingView)
controller.view.addSubview(messageView)
controller.view.addSubview(self.view)
if isSupportingReload() {
delegate = controller as? LoadStateViewReloadSupport
}
}
func loadStateViewReload() {
if isSupportingReload() {
delegate?.loadStateViewReload()
}
}
func isSupportingReload() -> Bool {
if let _ = self.parentViewController as? LoadStateViewReloadSupport as? UIViewController {
return true
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
messageView.alpha = 0
view.addSubview(messageView)
view.addSubview(loadingView)
state = .Initial
self.view.setNeedsUpdateConstraints()
self.view.userInteractionEnabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
madeInitialAppearance = true
}
override func updateViewConstraints() {
loadingView.snp_updateConstraints {make in
make.center.equalTo(view)
}
messageView.snp_updateConstraints {make in
make.center.equalTo(view)
}
view.snp_updateConstraints { make in
if let superview = view.superview {
make.edges.equalTo(superview).inset(insets)
}
}
super.updateViewConstraints()
}
private func updateAppearanceAnimated(animated : Bool) {
var alphas : (loading : CGFloat, message : CGFloat, content : CGFloat, touchable : Bool) = (loading : 0, message : 0, content : 0, touchable : false)
UIView.animateWithDuration(0.3 * NSTimeInterval(animated)) {
switch self.state {
case .Initial:
alphas = (loading : 1, message : 0, content : 0, touchable : false)
case .Loaded:
alphas = (loading : 0, message : 0, content : 1, touchable : false)
case let .Empty(info):
self.messageView.buttonInfo = info.buttonInfo
UIView.performWithoutAnimation {
if let message = info.attributedMessage {
self.messageView.attributedMessage = message
}
else {
self.messageView.message = info.message
}
self.messageView.icon = info.icon
}
alphas = (loading : 0, message : 1, content : 0, touchable : true)
case let .Failed(info):
self.messageView.buttonInfo = info.buttonInfo
UIView.performWithoutAnimation {
if let error = info.error where error.oex_isNoInternetConnectionError {
self.messageView.showError(Strings.networkNotAvailableMessageTrouble, icon: .InternetError)
}
else if let error = info.error as? OEXAttributedErrorMessageCarrying {
self.messageView.showError(error.attributedDescriptionWithBaseStyle(self.messageStyle), icon: info.icon)
}
else if let message = info.attributedMessage {
self.messageView.showError(message, icon: info.icon)
}
else if let message = info.message {
self.messageView.showError(message, icon: info.icon)
}
else if let error = info.error where error.errorIsThisType(NSError.oex_unknownNetworkError()) {
self.messageView.showError(Strings.unknownError, icon: info.icon)
}
else if let error = info.error where error.errorIsThisType(NSError.oex_outdatedVersionError()) {
self.messageView.setupForOutdatedVersionError()
}
else {
self.messageView.showError(info.error?.localizedDescription, icon: info.icon)
}
}
alphas = (loading : 0, message : 1, content : 0, touchable : true)
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.parentViewController?.hideSnackBar()
}
}
self.messageView.accessibilityMessage = self.state.accessibilityMessage
self.loadingView.alpha = alphas.loading
self.messageView.alpha = alphas.message
self.contentView?.alpha = alphas.content
self.view.userInteractionEnabled = alphas.touchable
}
}
}
|
e339dd0a69858d41e3fceec1b2742a49
| 36.512712 | 240 | 0.599232 | false | false | false | false |
guoc/excerptor
|
refs/heads/master
|
Excerptor/Preferences.swift
|
mit
|
1
|
//
// Preferences.swift
// Excerptor
//
// Created by Chen Guo on 23/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
import Foundation
private let sharedInstance = Preferences()
class Preferences: NSObject, PrefsPaneDelegate {
fileprivate var userDefaults: UserDefaults = {
var userDefaults = UserDefaults(suiteName: "name.guoc.excerptor")!
let defaultValuesFilePath = Bundle.main.path(forResource: "PreferencesDefaultValues", ofType: "plist")!
guard let defaultValues = NSDictionary(contentsOfFile: defaultValuesFilePath)! as? [String: AnyObject] else {
exitWithError("Fail to read preferences default values: \(NSDictionary(contentsOfFile: defaultValuesFilePath)!)")
}
userDefaults.register(defaults: defaultValues)
if Preferences.dntpIsInstalled() {
let defaultValuesForDNtpFilePath = Bundle.main.path(forResource: "PreferencesDefaultValues(DNtp)", ofType: "plist")!
guard let defaultValuesForDNtp = NSDictionary(contentsOfFile: defaultValuesForDNtpFilePath)! as? [String: AnyObject] else {
exitWithError("Fail to read preferences default values for DNtp: \(NSDictionary(contentsOfFile: defaultValuesForDNtpFilePath)!)")
}
userDefaults.register(defaults: defaultValuesForDNtp)
}
return userDefaults
}()
class var sharedPreferences: Preferences {
return sharedInstance
}
static func dntpIsInstalled() -> Bool {
return (LSCopyApplicationURLsForBundleIdentifier("com.devon-technologies.thinkpro2" as CFString, nil) != nil)
}
let boolForSelectionLinkIncludesBoundsInfo = false
// MARK: PrefsPaneDelegate
fileprivate struct Constants {
static let AppForOpenPDF = "AppForOpenPDF"
static let SelectionLinkPlainText = "SelectionLinkPlainText"
static let SelectionLinkRichTextSameAsPlainText = "SelectionLinkRichTextSameAsPlainText"
static let SelectionLinkRichText = "SelectionLinkRichText"
static let ShowNotificationWhenFileNotFoundInDNtpForSelectionLink = "ShowNotificationWhenFileNotFoundInDNtpForSelectionLink" // swiftlint:disable:this identifier_name
static let SelectionFilesLocation = "SelectionFilesLocation"
static let SelectionFileName = "SelectionFileName"
static let SelectionFileExtension = "SelectionFileExtension"
static let SelectionFileTags = "SelectionFileTags"
static let SelectionFileContent = "SelectionFileContent"
static let ShowNotificationWhenFileNotFoundInDNtpForSelectionFile = "ShowNotificationWhenFileNotFoundInDNtpForSelectionFile" // swiftlint:disable:this identifier_name
static let AnnotationFilesLocation = "AnnotationFilesLocation"
static let AnnotationFileName = "AnnotationFileName"
static let AnnotationFileExtension = "AnnotationFileExtension"
static let AnnotationFileTags = "AnnotationFileTags"
static let AnnotationFileContent = "AnnotationFileContent"
static let ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile = "ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile" // swiftlint:disable:this identifier_name
// Hidden preferences
static let PathVariables = "PathVariables"
static let PathSubstitutes = "PathSubstitutes"
}
// swiftlint:disable variable_name
struct CommonPlaceholders {
static let PDFFileLink_DEVONthinkUUIDType = "{{PDFFileLink_DEVONthinkUUID}}"
static let PDFFileLink_FilePathType = "{{PDFFileLink_FilePath}}"
static let PDFFilePath = "{{PDFFilePath}}"
static let PDFFileName = "{{PDFFileName}}"
static let PDFFileName_NoExtension = "{{PDFFileName_NoExtension}}"
static let PDFFileDEVONthinkUUID = "{{PDFFileDEVONthinkUUID}}"
static let Page = "{{Page}}"
}
struct SelectionPlaceholders {
static let SelectionText = "{{SelectionText}}"
static let UserName = "{{UserName}}"
static let CreationDate = "{{CreationDate}}"
static let SelectionLink_DEVONthinkUUIDType = "{{SelectionLink_DEVONthinkUUID}}"
static let SelectionLink_FilePathType = "{{SelectionLink_FilePath}}"
}
struct AnnotationPlaceholders {
static let AnnotationText = "{{AnnotationText}}"
static let NoteText = "{{NoteText}}"
static let annotationType = "{{Type}}"
static let Color = "{{Color}}"
static let Author = "{{Author}}"
static let AnnotationDate = "{{AnnotationDate}}"
static let ExportDate = "{{ExportDate}}"
static let AnnotationLink_DEVONthinkUUIDType = "{{AnnotationLink_DEVONthinkUUID}}"
static let AnnotationLink_FilePathType = "{{AnnotationLink_FilePath}}"
}
// swiftlint:enable variable_name
static let availablePlaceholders: [String] = { () -> [String] in
let selectionPlaceholders = Set(Preferences.availableSelectionPlaceholders)
let annotationPlaceholders = Set(Preferences.availableAnnotationPlaceholders)
return [String](selectionPlaceholders.union(annotationPlaceholders))
}()
static let availableSelectionPlaceholders = [
Preferences.CommonPlaceholders.PDFFileLink_DEVONthinkUUIDType,
Preferences.CommonPlaceholders.PDFFileLink_FilePathType,
Preferences.CommonPlaceholders.PDFFilePath,
Preferences.CommonPlaceholders.PDFFileName,
Preferences.CommonPlaceholders.PDFFileName_NoExtension,
Preferences.CommonPlaceholders.PDFFileDEVONthinkUUID,
Preferences.CommonPlaceholders.Page,
Preferences.SelectionPlaceholders.SelectionText,
Preferences.SelectionPlaceholders.UserName,
Preferences.SelectionPlaceholders.CreationDate,
Preferences.SelectionPlaceholders.SelectionLink_DEVONthinkUUIDType,
Preferences.SelectionPlaceholders.SelectionLink_FilePathType
]
static let availableAnnotationPlaceholders = [
Preferences.CommonPlaceholders.PDFFileLink_DEVONthinkUUIDType,
Preferences.CommonPlaceholders.PDFFileLink_FilePathType,
Preferences.CommonPlaceholders.PDFFilePath,
Preferences.CommonPlaceholders.PDFFileName,
Preferences.CommonPlaceholders.PDFFileName_NoExtension,
Preferences.CommonPlaceholders.PDFFileDEVONthinkUUID,
Preferences.CommonPlaceholders.Page,
Preferences.AnnotationPlaceholders.AnnotationText,
Preferences.AnnotationPlaceholders.NoteText,
Preferences.AnnotationPlaceholders.annotationType,
Preferences.AnnotationPlaceholders.Color,
Preferences.AnnotationPlaceholders.Author,
Preferences.AnnotationPlaceholders.AnnotationDate,
Preferences.AnnotationPlaceholders.ExportDate,
Preferences.AnnotationPlaceholders.AnnotationLink_DEVONthinkUUIDType,
Preferences.AnnotationPlaceholders.AnnotationLink_FilePathType
]
var availablePlaceholders: [Any] {
return Preferences.availablePlaceholders as [AnyObject]
}
var availableSelectionPlaceholders: [Any] {
return Preferences.availableSelectionPlaceholders as [AnyObject]
}
var availableAnnotationPlaceholders: [Any] {
return Preferences.availableAnnotationPlaceholders as [AnyObject]
}
var appForOpenPDF: PDFReaderApp {
get {
self.userDefaults.synchronize()
return PDFReaderApp(rawValue: self.userDefaults.integer(forKey: Constants.AppForOpenPDF))!
}
set {
self.userDefaults.set(newValue.rawValue, forKey: Constants.AppForOpenPDF)
self.userDefaults.synchronize()
}
}
var stringForSelectionLinkPlainText: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionLinkPlainText)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionLinkPlainText)
self.userDefaults.synchronize()
}
}
var boolForSelectionLinkRichTextSameAsPlainText: Bool { // swiftlint:disable:this identifier_name
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.SelectionLinkRichTextSameAsPlainText)
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionLinkRichTextSameAsPlainText)
self.userDefaults.synchronize()
}
}
var stringForSelectionLinkRichText: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionLinkRichText)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionLinkRichText)
self.userDefaults.synchronize()
}
}
// swiftlint:disable identifier_name
var boolForShowNotificationWhenFileNotFoundInDNtpForSelectionLink: Bool {
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionLink)
}
set {
self.userDefaults.set(newValue, forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionLink)
self.userDefaults.synchronize()
}
}
var stringForSelectionFilesLocation: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFilesLocation)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFilesLocation)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileName: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileName)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileName)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileExtension: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileExtension)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileExtension)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileTags: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileTags)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileTags)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileContent: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileContent)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileContent)
self.userDefaults.synchronize()
}
}
var boolForShowNotificationWhenFileNotFoundInDNtpForSelectionFile: Bool {
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionFile)
}
set {
self.userDefaults.set(newValue, forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionFile)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFilesLocation: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFilesLocation)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFilesLocation)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileName: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileName)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileName)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileExtension: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileExtension)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileExtension)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileTags: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileTags)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileTags)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileContent: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileContent)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileContent)
self.userDefaults.synchronize()
}
}
var boolForShowNotificationWhenFileNotFoundInDNtpForAnnotationFile: Bool {
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile)
}
set {
self.userDefaults.set(newValue, forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile)
self.userDefaults.synchronize()
}
}
// Hidden preferences
var dictionaryForPathVariables: [String: String] {
self.userDefaults.synchronize()
guard let dict = self.userDefaults.dictionary(forKey: Constants.PathVariables) as? [String: String] else {
return [String: String]()
}
return dict
}
var dictionaryForPathSubstitutes: [String: String] {
self.userDefaults.synchronize()
guard let dict = self.userDefaults.dictionary(forKey: Constants.PathSubstitutes) as? [String: String] else {
return [String: String]()
}
return dict
}
func resetSelectionLinkPreferences() {
self.userDefaults.removeObject(forKey: Constants.SelectionLinkPlainText)
self.userDefaults.removeObject(forKey: Constants.SelectionLinkRichTextSameAsPlainText)
self.userDefaults.removeObject(forKey: Constants.SelectionLinkRichText)
self.userDefaults.removeObject(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionLink)
}
func resetSelectionFilePreferences() {
self.userDefaults.removeObject(forKey: Constants.SelectionFilesLocation)
self.userDefaults.removeObject(forKey: Constants.SelectionFileName)
self.userDefaults.removeObject(forKey: Constants.SelectionFileExtension)
self.userDefaults.removeObject(forKey: Constants.SelectionFileTags)
self.userDefaults.removeObject(forKey: Constants.SelectionFileContent)
self.userDefaults.removeObject(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionFile)
}
func resetAnnotationFilePreferences() {
self.userDefaults.removeObject(forKey: Constants.AnnotationFilesLocation)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileName)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileExtension)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileTags)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileContent)
self.userDefaults.removeObject(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile)
}
}
|
9ebdc89679ac75ea318726fcccfbe47e
| 38.553086 | 176 | 0.699045 | false | false | false | false |
kdawgwilk/vapor
|
refs/heads/master
|
Tests/Vapor/SessionTests.swift
|
mit
|
1
|
@testable import Vapor
import XCTest
class SessionTests: XCTestCase {
static let allTests = [
("testDestroy_asksDriverToDestroy", testDestroy_asksDriverToDestroy),
("testSubscriptGet_asksDriverForValue", testSubscriptGet_asksDriverForValue),
("testSubscriptSet_asksDriverToSetValue", testSubscriptSet_asksDriverToSetValue),
("testIdentifierCreation", testIdentifierCreation)
]
func testDestroy_asksDriverToDestroy() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
subject.destroy()
guard let action = driver.actions.first, case .Destroy = action else {
XCTFail("No actions recorded or recorded action was not a destroy action")
return
}
}
func testSubscriptGet_asksDriverForValue() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
_ = subject["test"]
guard let action = driver.actions.first, case .ValueFor(let key) = action else {
XCTFail("No actions recorded or recorded action was not a value for action")
return
}
XCTAssertEqual(key.key, "test")
}
func testSubscriptSet_asksDriverToSetValue() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
subject["foo"] = "bar"
guard let action = driver.actions.first, case .SetValue(let key) = action else {
XCTFail("No actions recorded or recorded action was not a set value action")
return
}
XCTAssertEqual(key.value, "bar")
XCTAssertEqual(key.key, "foo")
}
func testIdentifierCreation() throws {
let drop = Droplet()
drop.get("cookie") { request in
request.session?["hi"] = "test"
return "hi"
}
let request = try Request(method: .get, path: "cookie")
request.headers["Cookie"] = "vapor-session=123"
let response = try drop.respond(to: request)
var sessionMiddleware: SessionMiddleware?
for middleware in drop.globalMiddleware {
if let middleware = middleware as? SessionMiddleware {
sessionMiddleware = middleware
}
}
XCTAssert(sessionMiddleware != nil, "Could not find session middleware")
XCTAssert(sessionMiddleware?.sessions.contains(identifier: "123") == false, "Session should not contain 123")
XCTAssert(response.cookies["vapor-session"] != nil, "No cookie was added")
let id = response.cookies["vapor-session"] ?? ""
XCTAssert(sessionMiddleware?.sessions.contains(identifier: id) == true, "Session did not contain cookie")
}
}
private class TestDriver: Sessions {
var drop = Droplet()
enum Action {
case ValueFor(key: String, identifier: String)
case SetValue(value: String?, key: String, identifier: String)
case Destroy(identifier: String)
}
var actions = [Action]()
func makeIdentifier() -> String {
return "Foo"
}
func value(for key: String, identifier: String) -> String? {
actions.append(.ValueFor(key: key, identifier: identifier))
return nil
}
private func contains(identifier: String) -> Bool {
return false
}
func set(_ value: String?, for key: String, identifier: String) {
actions.append(.SetValue(value: value, key: key, identifier: identifier))
}
func destroy(_ identifier: String) {
actions.append(.Destroy(identifier: identifier))
}
}
|
0b27873a30a75385769c80196bf36797
| 31.4375 | 117 | 0.63281 | false | true | false | false |
Legoless/Saystack
|
refs/heads/master
|
Code/Extensions/UIKit/UIViewController+Traverse.swift
|
mit
|
1
|
//
// UIViewController+Traverse.swift
// Saystack
//
// Created by Dal Rupnik on 4/5/20.
// Copyright © 2020 Unified Sense. All rights reserved.
//
import Foundation
import UIKit
public extension UIViewController {
func findController<T : UIViewController>(ofType: T.Type) -> T? {
let controller = self
if controller.isKind(of: T.self) {
return controller as? T
}
if let navigationController = controller as? UINavigationController {
for childController in navigationController.viewControllers {
if let child = childController.findController(ofType: T.self) {
return child
}
}
}
if let splitController = controller as? UISplitViewController {
for childController in splitController.viewControllers {
if let child = childController.findController(ofType: T.self) {
return child
}
}
}
if let tabBarController = controller as? UITabBarController {
for childController in tabBarController.viewControllers ?? [] {
if let child = childController.findController(ofType: T.self) {
return child
}
}
}
return nil
}
}
|
3b1002421be277882c224feb5aa2d10b
| 29.130435 | 79 | 0.562771 | false | false | false | false |
voloshynslavik/MVx-Patterns-In-Swift
|
refs/heads/master
|
MVX Patterns In Swift/Patterns/MVVM/ViewModel.swift
|
mit
|
1
|
//
// ModelView.swift
// MVX Patterns In Swift
//
// Created by Yaroslav Voloshyn on 17/07/2017.
//
import Foundation
final class ViewModel: NSObject {
weak var delegate: ViewModelDelegate?
fileprivate let picsumPhotos = PicsumPhotosManager()
fileprivate var lastPageIndex: Int?
fileprivate var photos: [(PicsumPhoto, Data?)] = []
fileprivate var isLoading = false {
didSet {
self.delegate?.didLoadingStateChanged(in: self, from: oldValue, to: isLoading)
}
}
var photosCount: Int {
return photos.count
}
func getPhotoData(for index: Int, width: Int, height: Int) -> Data? {
guard let data = photos[index].1 else {
startLoadPhoto(for: index, width: width, height: height)
return nil
}
return data
}
func getPhotoAuthor(for index: Int) -> String {
return photos[index].0.author
}
}
// MARK: - Load items
extension ViewModel {
func loadMoreItems() {
guard !isLoading else {
return
}
var pageIndex = 1
if let lastPageIndex = lastPageIndex {
pageIndex = lastPageIndex + 1
}
loadItems(with: pageIndex)
}
private func loadItems(with pageIndex: Int) {
isLoading = true
picsumPhotos.getPhotos(pageIndex) { [weak self] (photos, error) in
defer {
self?.isLoading = false
}
guard let sself = self else {
return
}
sself.lastPageIndex = pageIndex
photos?.forEach {
sself.photos.append(($0, nil))
}
sself.delegate?.didUpdatedData(in: sself)
}
}
}
// MARK: - Load Photo
extension ViewModel {
func stopLoadPhoto(for index: Int, width: Int, height: Int) {
let url = photos[index].0.getResizedImageURL(width: width, height: height)
DataLoader.shared.stopDownload(with: url)
}
func startLoadPhoto(for index: Int, width: Int, height: Int) {
let url = photos[index].0.getResizedImageURL(width: width, height: height)
DataLoader.shared.downloadData(with: url) { [weak self] (data) in
guard let sself = self else {
return
}
sself.photos[index].1 = data
sself.delegate?.didDownloadPhoto(in: sself, with: index)
}
}
}
protocol ViewModelDelegate: class {
func didLoadingStateChanged(in viewModel: ViewModel, from oldState: Bool, to newState:Bool)
func didUpdatedData(in viewModel: ViewModel)
func didDownloadPhoto(in viewMode: ViewModel, with index: Int)
}
|
118d8d678530489e0948eedceae72d55
| 24.790476 | 95 | 0.589734 | false | false | false | false |
shlyren/ONE-Swift
|
refs/heads/master
|
ONE_Swift/Classes/Reading-阅读/View/Detail/JENReadToolBarView.swift
|
mit
|
1
|
//
// JENReadToolBarView.swift
// ONE_Swift
//
// Created by 任玉祥 on 16/5/4.
// Copyright © 2016年 任玉祥. All rights reserved.
//
import UIKit
class JENReadToolBarView: UIView {
@IBOutlet private weak var praiseBtn: UIButton!
@IBOutlet private weak var commentBtn: UIButton!
@IBOutlet private weak var shareBtn: UIButton!
private var readType = JENReadType.Unknow
private var detail_id = ""
class func toolBarView(type: JENReadType, detail_id: String) -> JENReadToolBarView {
let toolBar = NSBundle.mainBundle().loadNibNamed("JENReadToolBarView", owner: nil, options: nil).first as! JENReadToolBarView
toolBar.frame = CGRectMake(0, JENScreenHeight - 44, JENScreenWidth, 44)
toolBar.readType = type
toolBar.detail_id = detail_id
return toolBar
}
func setToolBarTitle(praisenum: Int, commentnum: Int, sharenum: Int) {
praiseBtn.setTitle("\(praisenum)", forState: .Normal)
praiseBtn.setTitle("\(praisenum)", forState: .Selected)
commentBtn.setTitle("\(commentnum)", forState: .Normal)
commentBtn.setTitle("\(commentnum)", forState: .Highlighted)
shareBtn.setTitle("\(sharenum)", forState: .Normal)
shareBtn.setTitle("\(sharenum)", forState: .Highlighted)
}
}
|
f23a0275dcb1ce056ab9db034caada60
| 34.324324 | 133 | 0.672533 | false | false | false | false |
donnywdavis/Word-Jive
|
refs/heads/master
|
WordJive/WordJive/WordsViewController.swift
|
cc0-1.0
|
1
|
//
// WordsViewController.swift
// WordJive
//
// Created by Allen Spicer on 7/16/16.
// Copyright © 2016 Donny Davis. All rights reserved.
//
import UIKit
class WordsViewController: UIViewController {
var solutionsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
placeSolutionsFromArrayOnView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func placeSolutionsFromArrayOnView(){
solutionsArray = ["FED", "ON", "AT", "OH"]
var i = 0
while i < solutionsArray.count{
let width = view.frame.width
let rect = CGRectMake(0, CGFloat(20*i+100), width, 20)
let newLabel = UILabel.init(frame: rect)
newLabel.text = solutionsArray[i]
newLabel.textAlignment = .Center
self.view.addSubview(newLabel)
i = i + 1
}
}
}
|
774f2e6edefeb7dea9225827d05b403f
| 19 | 62 | 0.569405 | false | false | false | false |
farion/eloquence
|
refs/heads/master
|
Eloquence/EloquenceIOS/EMAccountsViewController.swift
|
apache-2.0
|
1
|
import Foundation
import UIKit
import XMPPFramework
protocol EMAccountsViewControllerDelegate:NSObjectProtocol {
func didClickDoneInAccountsViewController();
}
class EMAccountsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, EMAddAccountViewControllerDelegate {
var delegate:EMAccountsViewControllerDelegate?;
var addController: EMAddAccountViewController?;
var data = [EloAccount]();
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
tableView.delegate = self;
tableView.dataSource = self;
self.prepareData();
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
func prepareData(){
self.data = DataController.sharedInstance.getAccounts();
tableView.reloadData();
}
@IBAction func doneClicked(sender: AnyObject) {
if(delegate != nil){
delegate!.didClickDoneInAccountsViewController()
}
}
@IBAction func addClicked(sender: AnyObject) {
addController = UIStoryboard.init(name: "Shared", bundle: nil).instantiateViewControllerWithIdentifier("AddAccount") as? EMAddAccountViewController;
addController!.delegate = self;
self.presentViewController(addController!, animated: true, completion: {})
}
func doCloseAddAccountView(){
if(addController != nil){
addController!.dismissViewControllerAnimated(true, completion: nil)
addController!.delegate = nil;
addController = nil;
}
}
//pragma mark - UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("AccountCell", forIndexPath: indexPath) as? EMAccountCell;
if(cell == nil) {
cell = EMAccountCell(style: UITableViewCellStyle.Default, reuseIdentifier: "AccountCell");
}
cell!.jidLabel.text = data[indexPath.row].getJid().jid;
cell!.disableSwitch.on = data[indexPath.row].isAutoConnect()
cell!.account = data[indexPath.row];
return cell!;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
//pragma mark - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
addController = UIStoryboard.init(name: "Shared", bundle: nil).instantiateViewControllerWithIdentifier("AddAccount") as? EMAddAccountViewController;
addController!.delegate = self;
addController!.account = data[indexPath.row];
self.presentViewController(addController!, animated: true, completion: {})
}
}
|
f447bacd0d215464ef46ec357a06cdd6
| 31.75 | 156 | 0.660359 | false | false | false | false |
Mrwerdo/QuickShare
|
refs/heads/master
|
LibQuickShare/Sources/Communication/SyncMessage+Actions.swift
|
mit
|
1
|
//
// SyncMessage+Actions.swift
// QuickShare
//
// Copyright (c) 2016 Andrew Thompson
//
// 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 Core
extension SyncMessage : Consumable {
public func consume(group: ShareGroup, message: ControlMessage, center: MessageCenter) {
/*
* Sync Message has this method, which will be called once it's decoded
* inside Message Center.
* It might be better to shift any synchronisation logic into this method
* as it might reduce the size of MessageCenter.
*
* However, the code works at present, and it's probably easier to just
* leave it be for a while.
*/
switch self.type {
case .Sync: /* Request for User Information */
let info = SyncState.Info(didStart: false, detectedUsers: [])
group.syncState = .Syncing(info)
sendUserInformation(group)
updateUserInformation(group, signature: self.signature, shouldReset: true )
case .Info: /* Response for User Information */
updateUserInformation(group, signature: self.signature)
case .Confirm: /* Check everybody's on the same page */
// This means that the originating host wants to
// finish the synchronization.
confirmStatus(group, matching: self.signature, center: center)
}
}
private func sendUserInformation(group: ShareGroup) {
let signature = group.signature
let info = SyncMessage(type: .Info, signature: signature)
group.add(message: info)
}
func updateUserInformation(group: ShareGroup, signature: Signature, shouldReset: Bool = false) {
if let info = group.syncState.syncInfo {
let newFoundPeers: [Signature]
if shouldReset {
newFoundPeers = [signature]
} else {
newFoundPeers = info.detectedUsers + [signature]
}
let newInfo = SyncState.Info(didStart: info.didStart, detectedUsers: newFoundPeers)
group.syncState = .Syncing(newInfo)
} else {
show("warning: \(#function) called when group.transferState.state != .Syncing")
}
}
func confirmStatus(group: ShareGroup, matching signature: Signature, center: MessageCenter) {
if let info = group.syncState.syncInfo {
if !info.didStart {
group.peers = info.detectedUsers.map { $0.user }
}
print("Are the signatures equal? \(group.signature.hash == signature.hash)")
if group.signature.hash == signature.hash {
group.packetCounter = 0
var users = group.peers + [group.user]
users.sortInPlace { $0.time < $1.time }
let controllers = users.filter { $0.isController }
if controllers.count != 1 {
show("resolving conflict in share group controllers")
if let user = users.first {
user.isController = true
show("\(user) is now the controller")
}
for user in users.dropFirst() {
user.isController = false
}
}
if let controller = center.groups[group], let c = controller {
center.update(controller: c, using: group)
}
group.syncState = .Ready
} else {
dump(group)
dump(group.signature)
dump(signature)
}
} else {
show("warning: \(#function) called when group.transferState.state != .Syncing")
}
}
}
|
aef68d83214593a47d6f65179c464eac
| 42.300885 | 100 | 0.596771 | false | false | false | false |
alexandrehcdc/dejavi
|
refs/heads/master
|
dejavi/Movies.swift
|
mit
|
1
|
import Foundation
import RealmSwift
let realm = try! Realm()
class MovieModel: Object {
dynamic var title, year, poster, genre, plot: String?
dynamic var isAlreadyWatched: Bool = false
dynamic var isAlreadySaved: Bool = false
dynamic var imageData: NSData?
func persistMovie(movie: Object) {
try! realm!.write {
realm!.add(movie)
}
}
func removeMovie (movie: Object) {
try! realm!.write {
realm!.delete(movie)
}
}
func setimageData (imageData : NSData?) {
guard imageData != nil else {
return
}
self.imageData = imageData
}
func setMovieValues (title: String, year: String, poster: String, genre: String, plot: String, isAlreadyWatched: Bool, isAlreadySaved: Bool) {
self.title = title
self.year = year
self.poster = poster
self.genre = genre
self.plot = plot
self.isAlreadyWatched = isAlreadyWatched
self.isAlreadySaved = isAlreadySaved
}
}
|
1820bc89356a85f0d008d7fa428259a2
| 24.97561 | 146 | 0.597744 | false | false | false | false |
yajeka/PS
|
refs/heads/master
|
PS/UIViewController+UIAlert.swift
|
lgpl-3.0
|
1
|
//
// UIViewController+UIAlert.swift
// PS
//
// Created by Yauheni Yarotski on 20.03.16.
// Copyright © 2016 hackathon. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
// MARK: - Alerts
public func showAlert(title title: String? = nil, message: String? = nil, error: NSError? = nil, okActionHandler: ((UIAlertAction) -> Void)? = nil)
{
let actions = [UIAlertAction(title: ActionTitle.Ok(), style: .Default, handler: okActionHandler)]
var composedMessage = message
#if DEBUG
if let error = error {
composedMessage += "\n\nDiagnostics: \(error.localizedDescription)"
}
#endif
presentAlert(title: title, message: composedMessage, actions: actions)
}
public func showAlertForNetworkError(error: NSError? = nil, okActionHandler:((UIAlertAction) -> Void)? = nil)
{
showAlert(
title: NSLocalizedString("Network Error", comment: "Network Error title"),
message: NSLocalizedString("There was an error connecting to the server. Please try again later when you have an Internet connection.", comment:"Network Error message"),
error: error,
okActionHandler: okActionHandler
)
}
// MARK: - Dialogs (like alert but with actions > 1)
public func showDialog(title title: String? = nil, message: String? = nil, actions: [UIAlertAction]){
presentAlert(title: title, message: message, actions: actions)
}
public func showDialogForConfirmation(
title title: String? = nil,
message: String? = nil,
cancelActionHandler: ((UIAlertAction) -> Void)? = nil,
confirmActionHandler: ((UIAlertAction) -> Void)? = nil)
{
let actions = [
UIAlertAction(title: ActionTitle.Cancel(), style: .Cancel, handler: cancelActionHandler),
UIAlertAction(title: ActionTitle.Ok(), style: .Default, handler: confirmActionHandler)
]
presentAlert(title: title, message: message, actions: actions)
}
// MARK: - ActionSheets (for iPad automatically convertes into dialog)
public func showActionSheet(title title: String? = nil, message: String? = nil, actions: [UIAlertAction])
{
let isIpad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
presentAlert(title: title, message: message, style: isIpad ? .Alert : .ActionSheet, actions: actions)
}
public func showActionSheetDestructive(
title title: String? = nil,
message: String? = nil,
showTitleAndMessageOnIphone: Bool = true,
cancelActionHandler: ((UIAlertAction) -> Void)? = nil,
destructiveActionHandler: ((UIAlertAction) -> Void)? = nil)
{
let actions = [
UIAlertAction(title: ActionTitle.Cancel(), style: .Cancel, handler: cancelActionHandler),
UIAlertAction(title: ActionTitle.Remove(), style: .Destructive, handler: destructiveActionHandler)
]
let isIpad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
let title = (!showTitleAndMessageOnIphone && !isIpad) ? nil : title
let message = (!showTitleAndMessageOnIphone && !isIpad) ? nil : message
presentAlert(title: title, message: message, style: isIpad ? .Alert : .ActionSheet, actions: actions)
}
// MARK: - Privite methods
private func presentAlert(
title title: String? = nil,
message: String? = nil,
style: UIAlertControllerStyle = .Alert,
actions: [UIAlertAction])
{
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
if !actions.isEmpty {
for action in actions {
alert.addAction(action)
}
}
else {//defaul action if nobody will set at least one action
alert.addAction(UIAlertAction(title: ActionTitle.Ok(), style: .Default, handler: nil))
}
presentViewController(alert, animated: true, completion: nil)
}
}
struct ActionTitle {
static func Ok() -> String {
return NSLocalizedString("OK", comment:"OK button title")
}
static func Cancel() -> String {
return NSLocalizedString("Cancel", comment: "")
}
static func Remove() -> String {
return NSLocalizedString("Remove", comment: "")
}
}
|
4e9021cd23413ef483c352b39e865039
| 35.830645 | 182 | 0.621989 | false | false | false | false |
peferron/algo
|
refs/heads/master
|
EPI/Sorting/Render a calendar/swift/main.swift
|
mit
|
1
|
public typealias Event = (start: Int, end: Int)
typealias Boundary = (time: Int, type: BoundaryType)
enum BoundaryType {
case Start
case End
}
public func maxConcurrentEvents(_ events: [Event]) -> Int {
let boundaries = events
.flatMap { event -> [Boundary] in [
(time: event.start, type: .Start),
(time: event.end, type: .End)
]}
.sorted {
// If multiple boundaries share the same time, process Start boundaries before End
// boundaries. That's because if one event ends at the same time another event starts,
// we consider these two events to overlap each other.
$0.time < $1.time || $0.time == $1.time && $0.type == .Start
}
var currentOverlap = 0
var maxOverlap = 0
for boundary in boundaries {
currentOverlap += boundary.type == .Start ? 1 : -1
maxOverlap = max(currentOverlap, maxOverlap)
}
return maxOverlap
}
|
2187638f05f4acf0d7f44bb3a7d32f51
| 29.5 | 98 | 0.599385 | false | false | false | false |
ahoppen/swift
|
refs/heads/main
|
SwiftCompilerSources/Sources/SIL/ApplySite.swift
|
apache-2.0
|
1
|
//===--- ApplySite.swift - Defines the ApplySite protocols ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 SILBridging
public struct ApplyOperands {
public static let calleeOperandIndex: Int = 0
public static let firstArgumentIndex = 1
}
public protocol ApplySite : Instruction {
var operands: OperandArray { get }
var numArguments: Int { get }
var substitutionMap: SubstitutionMap { get }
func calleeArgIndex(callerArgIndex: Int) -> Int
func callerArgIndex(calleeArgIndex: Int) -> Int?
func getArgumentConvention(calleeArgIndex: Int) -> ArgumentConvention
}
extension ApplySite {
public var callee: Value { operands[ApplyOperands.calleeOperandIndex].value }
public var arguments: LazyMapSequence<OperandArray, Value> {
operands[1..<operands.count].lazy.map { $0.value }
}
public var substitutionMap: SubstitutionMap {
SubstitutionMap(ApplySite_getSubstitutionMap(bridged))
}
public func argumentIndex(of operand: Operand) -> Int? {
let opIdx = operand.index
if opIdx >= ApplyOperands.firstArgumentIndex &&
opIdx <= ApplyOperands.firstArgumentIndex + numArguments {
return opIdx - ApplyOperands.firstArgumentIndex
}
return nil
}
public func getArgumentConvention(calleeArgIndex: Int) -> ArgumentConvention {
return ApplySite_getArgumentConvention(bridged, calleeArgIndex).convention
}
public var referencedFunction: Function? {
if let fri = callee as? FunctionRefInst {
return fri.referencedFunction
}
return nil
}
}
public protocol FullApplySite : ApplySite {
var singleDirectResult: Value? { get }
}
extension FullApplySite {
public func calleeArgIndex(callerArgIndex: Int) -> Int { callerArgIndex }
public func callerArgIndex(calleeArgIndex: Int) -> Int? { calleeArgIndex }
}
|
9ce9d18a8ca3d49f5f3b696ad89c9a61
| 31.558824 | 80 | 0.707317 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Neocom/Neocom/Killboard/zKillboard/ShipPicker.swift
|
lgpl-2.1
|
2
|
//
// ShipPicker.swift
// Neocom
//
// Created by Artem Shimanski on 4/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
import CoreData
struct ShipPicker: View {
var completion: (NSManagedObject) -> Void
@Environment(\.managedObjectContext) private var managedObjectContext
@Environment(\.self) private var environment
@State private var selectedType: SDEInvType?
@EnvironmentObject private var sharedState: SharedState
private func getCategories() -> FetchedResultsController<SDEInvCategory> {
let controller = managedObjectContext.from(SDEInvCategory.self)
.filter((/\SDEInvCategory.categoryID).in([SDECategoryID.ship.rawValue, SDECategoryID.structure.rawValue]))
.sort(by: \SDEInvCategory.categoryName, ascending: true)
.fetchedResultsController(sectionName: /\SDEInvCategory.published)
return FetchedResultsController(controller)
}
private let categories = Lazy<FetchedResultsController<SDEInvCategory>, Never>()
@State private var searchString: String = ""
@State private var searchResults: [FetchedResultsController<SDEInvType>.Section]? = nil
var body: some View {
let categories = self.categories.get(initial: getCategories())
return TypesSearch(searchString: $searchString, searchResults: $searchResults) {
if self.searchResults != nil {
TypePickerTypesContent(types: self.searchResults!, selectedType: self.$selectedType, completion: self.completion)
}
else {
ShipPickerCategoriesContent(categories: categories, completion: self.completion)
}
}
.navigationBarTitle(Text("Categories"))
.sheet(item: $selectedType) { type in
NavigationView {
TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil})
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct ShipPickerCategoriesContent: View {
var categories: FetchedResultsController<SDEInvCategory>
var completion: (NSManagedObject) -> Void
var body: some View {
ForEach(categories.sections, id: \.name) { section in
Section(header: section.name == "0" ? Text("UNPUBLISHED") : Text("PUBLISHED")) {
ForEach(section.objects, id: \.objectID) { category in
NavigationLink(destination: ShipPickerGroups(category: category, completion: self.completion)) {
CategoryCell(category: category)
}
}
}
}
}
}
#if DEBUG
struct ShipPicker_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ShipPicker { _ in
}
}.modifier(ServicesViewModifier.testModifier())
}
}
#endif
|
39e21f1541c5ed40a8809239040833db
| 36.938272 | 129 | 0.654735 | false | false | false | false |
aclissold/Blocker
|
refs/heads/master
|
Blocker.swift
|
mit
|
1
|
import Foundation
let runLoop = NSRunLoop.currentRunLoop()
let distantFuture = NSDate.distantFuture()
var blocking = false
public func block() {
blocking = true
while blocking &&
runLoop.runMode(NSDefaultRunLoopMode, beforeDate: distantFuture) {}
}
public func unblock() {
blocking = false
}
|
f10e831b1dc79f18f61c998e3844ed6c
| 18.75 | 75 | 0.718354 | false | false | false | false |
playbasis/native-sdk-ios
|
refs/heads/master
|
PlaybasisSDK/Classes/PBForm/PBDeviceForm.swift
|
mit
|
1
|
//
// PBDeviceForm.swift
// Playbook
//
// Created by Médéric Petit on 8/15/2559 BE.
// Copyright © 2559 smartsoftasia. All rights reserved.
//
import UIKit
public final class PBDeviceForm: PBForm {
//Required
public var playerId:String!
public var deviceToken:String!
public var deviceDescription:String!
public var deviceName:String!
override public func params() -> [String:String] {
var params:[String:String] = [:]
params["player_id"] = playerId
params["device_token"] = deviceToken
params["device_description"] = deviceDescription
params["device_name"] = deviceName
params["os_type"] = "iOS"
return params
}
}
|
39fc4d86e32764d97ceda055be8db363
| 23.724138 | 56 | 0.640167 | false | false | false | false |
creatubbles/ctb-api-swift
|
refs/heads/develop
|
CreatubblesAPIClientIntegrationTests/Spec/Content/ContentResponseHandlerSpec.swift
|
mit
|
1
|
//
// ContentResponseHandlerSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 Quick
import Nimble
@testable import CreatubblesAPIClient
class ContentResponseHandlerSpec: QuickSpec {
override func spec() {
describe("Content response handler") {
it("Should return recent content after login") {
let request = ContentRequest(type: .Recent, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return trending content after login") {
let request = ContentRequest(type: .Trending, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return Connected contents after login") {
let request = ContentRequest(type: .Connected, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
}
it("Should return User Bubbled Contents after login") {
let request = ContentRequest(type: .BubbledContents, page: 1, perPage: 20, userId: TestConfiguration.testUserIdentifier)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler: ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return Contents By A User after login") {
let request = ContentRequest(type: .ContentsByAUser, page: 1, perPage: 20, userId: TestConfiguration.testUserIdentifier)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler: ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return Contents based on Followed Users after login") {
let request = ContentRequest(type: .Followed, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler: ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return trending creations") {
let request = FetchTrendingCreationsRequest()
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return trending users") {
let request = FetchTrendingUsersRequest()
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return hashtag contents") {
let request = HashtagContentRequest(hashtagName:"lego", page: 1, perPage: 20)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
sender.logout()
done()
})
}
}
}
}
}
|
7d5978582b5da90df18f040c4f173eb9
| 45.958716 | 132 | 0.524763 | false | true | false | false |
RocketChat/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Models/Mapping/MessageModelMapping.swift
|
mit
|
1
|
//
// MessageModelMapping.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 16/01/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
extension Message: ModelMappeable {
//swiftlint:disable cyclomatic_complexity function_body_length
func map(_ values: JSON, realm: Realm?) {
if self.identifier == nil {
self.identifier = values["_id"].stringValue
}
self.rid = values["rid"].stringValue
self.text = values["msg"].stringValue
self.avatar = values["avatar"].string
self.emoji = values["emoji"].string
self.alias = values["alias"].stringValue
self.internalType = values["t"].string ?? "t"
self.role = values["role"].stringValue
self.pinned = values["pinned"].bool ?? false
self.unread = values["unread"].bool ?? false
self.groupable = values["groupable"].bool ?? true
self.snippetName = values["snippetName"].string
self.snippetId = values["snippetId"].string
if let createdAt = values["ts"]["$date"].double {
self.createdAt = Date.dateFromInterval(createdAt)
}
if let createdAt = values["ts"].string {
self.createdAt = Date.dateFromString(createdAt)
}
if let updatedAt = values["_updatedAt"]["$date"].double {
self.updatedAt = Date.dateFromInterval(updatedAt)
}
if let updatedAt = values["_updatedAt"].string {
self.updatedAt = Date.dateFromString(updatedAt)
}
if let userIdentifier = values["u"]["_id"].string {
self.userIdentifier = userIdentifier
if let realm = realm {
if let user = realm.object(ofType: User.self, forPrimaryKey: userIdentifier as AnyObject) {
user.map(values["u"], realm: realm)
realm.add(user, update: true)
} else {
let user = User()
user.map(values["u"], realm: realm)
realm.add(user, update: true)
}
}
}
// Starred
if let starred = values["starred"].array {
self.starred.removeAll()
starred.compactMap({ $0["_id"].string }).forEach(self.starred.append)
}
// Attachments
if let attachments = values["attachments"].array {
self.attachments.removeAll()
attachments.forEach {
guard var attachmentValue = try? $0.merged(with: JSON(dictionaryLiteral: ("messageIdentifier", values["_id"].stringValue))) else {
return
}
if let realm = realm {
var obj: Attachment!
// FA NOTE: We are not using Object.getOrCreate method here on purpose since
// we have to map the local modifications before mapping the current JSON on the object.
if let primaryKey = attachmentValue.rawString()?.md5(), let existingObj = realm.object(ofType: Attachment.self, forPrimaryKey: primaryKey) {
obj = existingObj
attachmentValue["collapsed"] = JSON(existingObj.collapsed)
} else {
obj = Attachment()
}
obj.map(attachmentValue, realm: realm)
realm.add(obj, update: true)
self.attachments.append(obj)
} else {
let obj = Attachment()
obj.map(attachmentValue, realm: realm)
self.attachments.append(obj)
}
}
}
// URLs
if let urls = values["urls"].array {
self.urls.removeAll()
for url in urls {
let obj = MessageURL()
obj.map(url, realm: realm)
self.urls.append(obj)
}
}
// Mentions
if let mentions = values["mentions"].array {
self.mentions.removeAll()
for mention in mentions {
let obj = Mention()
obj.map(mention, realm: realm)
self.mentions.append(obj)
}
}
// Channels
if let channels = values["channels"].array {
self.channels.removeAll()
for channel in channels {
let obj = Channel()
obj.map(channel, realm: realm)
self.channels.append(obj)
}
}
// Reactions
self.reactions.removeAll()
if let reactions = values["reactions"].dictionary {
reactions.enumerated().compactMap {
let reaction = MessageReaction()
reaction.map(emoji: $1.key, json: $1.value)
return reaction
}.forEach(self.reactions.append)
}
// Threads
if let threadMessageId = values["tmid"].string {
self.threadMessageId = threadMessageId
}
if let threadLastMessage = values["tlm"]["$date"].double {
self.threadLastMessage = Date.dateFromInterval(threadLastMessage)
}
if let threadLastMessage = values["tlm"].string {
self.threadLastMessage = Date.dateFromString(threadLastMessage)
}
if let threadMessagesCount = values["tcount"].int {
self.threadMessagesCount = threadMessagesCount
}
if let threadFollowers = values["replies"].arrayObject as? [String] {
if let currentUserId = AuthManager.currentUser()?.identifier {
self.threadIsFollowing = threadFollowers.contains(currentUserId)
}
}
// Discussions
if let discussionRid = values["drid"].string {
self.discussionRid = discussionRid
}
if let discussionLastMessage = values["dlm"]["$date"].double {
self.discussionLastMessage = Date.dateFromInterval(discussionLastMessage)
}
if let discussionLastMessage = values["dlm"].string {
self.discussionLastMessage = Date.dateFromString(discussionLastMessage)
}
if let discussionMessagesCount = values["dcount"].int {
self.discussionMessagesCount = discussionMessagesCount
}
}
}
|
cb7d55dbfc753f17ebdec58713296dde
| 33.751351 | 160 | 0.548608 | false | false | false | false |
sendyhalim/Yomu
|
refs/heads/master
|
Yomu/Screens/ChapterList/ChapterItem.swift
|
mit
|
1
|
//
// MangaChapterCollectionViewItem.swift
// Yomu
//
// Created by Sendy Halim on 6/16/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import AppKit
import RxSwift
class ChapterItem: NSCollectionViewItem {
@IBOutlet weak var chapterTitle: NSTextField!
@IBOutlet weak var chapterNumber: NSTextField!
@IBOutlet weak var chapterPreview: NSImageView!
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
chapterPreview.kf.indicatorType = .activity
}
func didEndDisplaying() {
chapterPreview.image = .none
disposeBag = DisposeBag()
}
func setup(withViewModel viewModel: ChapterViewModel) {
disposeBag = DisposeBag()
// Show activity indicator right now because fetch preview will
// fetch chapter pages first, after the pages are loaded, the first image of the pages
// will be fetched. Activity indicator will be removed automatically by kingfisher
// after image preview is fetched.
chapterPreview.kf.indicator?.startAnimatingView()
viewModel
.fetchPreview() ==> disposeBag
viewModel.title
.drive(chapterTitle.rx.text.orEmpty) ==> disposeBag
viewModel.title
.drive(chapterTitle.rx.text.orEmpty) ==> disposeBag
viewModel
.previewUrl
.drive(onNext: { [weak self] url in
self?.chapterPreview.setImageWithUrl(url)
self?.chapterPreview.kf.indicator?.stopAnimatingView()
}) ==> disposeBag
viewModel.number
.drive(chapterNumber.rx.text.orEmpty) ==> disposeBag
}
override func viewWillLayout() {
let border = Border(position: .bottom, width: 1.0, color: Config.style.borderColor)
view.drawBorder(border)
}
}
|
857bc9a7270a104a65ae6799b6147724
| 25.276923 | 90 | 0.706674 | false | false | false | false |
karstengresch/rw_studies
|
refs/heads/master
|
PaintCode/StopwatchPaintCode/PaintCodeTutorial.swift
|
unlicense
|
1
|
//
// PaintCodeTutorial.swift
// PaintCodeTutorial
//
// Created by Karsten Gresch on 02.10.15.
// Copyright (c) 2015 Closure One. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class PaintCodeTutorial : NSObject {
//// Cache
private struct Cache {
static let color: UIColor = UIColor(red: 0.481, green: 0.631, blue: 0.860, alpha: 1.000)
static var imageOfStopwatch: UIImage?
static var stopwatchTargets: [AnyObject]?
}
//// Colors
public class var color: UIColor { return Cache.color }
//// Drawing Methods
public class func drawStopwatch() {
//// Oval Drawing
let ovalPath = UIBezierPath(ovalInRect: CGRectMake(15, 30, 220, 220))
PaintCodeTutorial.color.setFill()
ovalPath.fill()
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRectMake(114, 7, 22, 29))
PaintCodeTutorial.color.setFill()
rectanglePath.fill()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(214.14, 30))
bezierPath.addLineToPoint(CGPointMake(235.36, 51.21))
bezierPath.addLineToPoint(CGPointMake(221.21, 65.35))
bezierPath.addCurveToPoint(CGPointMake(216.21, 60.35), controlPoint1: CGPointMake(221.21, 65.35), controlPoint2: CGPointMake(219.1, 63.24))
bezierPath.addLineToPoint(CGPointMake(204, 60.35))
bezierPath.addCurveToPoint(CGPointMake(204, 48.14), controlPoint1: CGPointMake(204, 60.35), controlPoint2: CGPointMake(204, 53.76))
bezierPath.addCurveToPoint(CGPointMake(200, 44.14), controlPoint1: CGPointMake(201.64, 45.78), controlPoint2: CGPointMake(200, 44.14))
bezierPath.addLineToPoint(CGPointMake(214.14, 30))
bezierPath.closePath()
PaintCodeTutorial.color.setFill()
bezierPath.fill()
}
public class func drawStopwatch_Hand() {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Bezier 2 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 125, 110)
let bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(4, -84))
bezier2Path.addCurveToPoint(CGPointMake(4, -14.46), controlPoint1: CGPointMake(4, -84), controlPoint2: CGPointMake(4, -46.6))
bezier2Path.addCurveToPoint(CGPointMake(15, 0), controlPoint1: CGPointMake(10.34, -12.71), controlPoint2: CGPointMake(15, -6.9))
bezier2Path.addCurveToPoint(CGPointMake(4, 14.46), controlPoint1: CGPointMake(15, 6.9), controlPoint2: CGPointMake(10.34, 12.71))
bezier2Path.addCurveToPoint(CGPointMake(4, 31), controlPoint1: CGPointMake(4, 24.44), controlPoint2: CGPointMake(4, 31))
bezier2Path.addLineToPoint(CGPointMake(-4, 31))
bezier2Path.addCurveToPoint(CGPointMake(-4, 14.46), controlPoint1: CGPointMake(-4, 31), controlPoint2: CGPointMake(-4, 24.44))
bezier2Path.addCurveToPoint(CGPointMake(-15, 0), controlPoint1: CGPointMake(-10.34, 12.71), controlPoint2: CGPointMake(-15, 6.9))
bezier2Path.addCurveToPoint(CGPointMake(-4, -14.46), controlPoint1: CGPointMake(-15, -6.9), controlPoint2: CGPointMake(-10.34, -12.71))
bezier2Path.addCurveToPoint(CGPointMake(-4, -84), controlPoint1: CGPointMake(-4, -46.6), controlPoint2: CGPointMake(-4, -84))
bezier2Path.addLineToPoint(CGPointMake(4, -84))
bezier2Path.addLineToPoint(CGPointMake(4, -84))
bezier2Path.closePath()
UIColor.whiteColor().setFill()
bezier2Path.fill()
CGContextRestoreGState(context)
}
//// Generated Images
public class var imageOfStopwatch: UIImage {
if Cache.imageOfStopwatch != nil {
return Cache.imageOfStopwatch!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(250, 250), false, 0)
PaintCodeTutorial.drawStopwatch()
Cache.imageOfStopwatch = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfStopwatch!
}
//// Customization Infrastructure
@IBOutlet var stopwatchTargets: [AnyObject]! {
get { return Cache.stopwatchTargets }
set {
Cache.stopwatchTargets = newValue
for target: AnyObject in newValue {
target.performSelector("setImage:", withObject: PaintCodeTutorial.imageOfStopwatch)
}
}
}
}
|
60ad062ec2bdcd88df84f26a00d57a03
| 37.767241 | 147 | 0.675561 | false | false | false | false |
tadasz/MistikA
|
refs/heads/master
|
MistikA/Classes/CountdownViewController.swift
|
mit
|
1
|
//
// CountdownViewController.swift
// MistikA
//
// Created by Tadas Ziemys on 18/08/14.
// Copyright (c) 2014 Tadas. All rights reserved.
//
import UIKit
class CountdownViewController: BaseViewController {
@IBOutlet weak var textLabel: LTMorphingLabel?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var timer: NSTimer?
func updateTimer() {
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = ("dd:MM:yyyy HH:mm:ss")
let date = dateFormater.dateFromString("28:11:2014 19:36:36")
let now = NSDate()
let timeLeft = date!.timeIntervalSinceDate(now)
if timeLeft < 0 {
textLabel?.text = "Išaušo mistinė valanda..."
timer?.invalidate()
timer = nil
GameController.sharedInstance.currentGameStage = GameStage.FinalPuzzle
finishStage()
} else {
textLabel?.text = "\(timeLeft)"
}
// println("time left: \(timeLeft)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
// timer = NSTimer(timeInterval: 1.0, target: nil, selector: "updateTimer", userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func finishStage() {
let button: UIButton = UIButton(type: UIButtonType.Custom)
button.frame = self.view.bounds
button.addTarget(self, action: Selector("bringMeBack"), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
playSoundWin()
}
func bringMeBack() {
dismissViewControllerAnimated(true, completion: nil)
}
/*
// 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.
}
*/
}
|
a82441c34bb587e4f8d0454fdea5a462
| 27.125 | 128 | 0.611717 | false | false | false | false |
SwiftDialog/SwiftDialog
|
refs/heads/master
|
SwiftDialog/RootElement.swift
|
apache-2.0
|
2
|
// Copyright 2014 Thomas K. Dyas
//
// 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
protocol BooleanValuedElement {
var value: Bool { get }
}
public enum SummarizeBy {
case none
case radioGroup(group: String)
case count
}
public class RootElement : BaseElement {
public var sections: ArrayRef<SectionElement>
public var title: String
public var groups: [String: Int]
public var onRefresh: ((RootElement) -> ())?
public var summary: SummarizeBy
public var style: UITableViewStyle
public weak var dialogController: DialogController?
public init(
title: String,
sections: ArrayRef<SectionElement>,
groups: [String: Int] = [:],
onRefresh: ((RootElement) -> ())? = nil,
summary: SummarizeBy = .none,
style: UITableViewStyle = .grouped
) {
self.title = title
self.sections = sections
self.groups = groups
self.onRefresh = onRefresh
self.summary = summary
self.style = style
super.init()
for section in self.sections {
section.parent = self
}
}
public convenience init(
title: String,
elements: ArrayRef<Element>,
groups: [String: Int] = [:],
onRefresh: ((RootElement) -> ())? = nil,
summary: SummarizeBy = .none,
style: UITableViewStyle = .grouped
) {
self.init(
title: title,
sections: [SectionElement(elements: elements)],
groups: groups,
onRefresh: onRefresh,
summary: summary,
style: style
)
}
func indexForRadioElement(_ radioElement: RadioElement) -> Int? {
var index = 0
for section in sections {
for element in section.elements {
if let currentRadioElement = element as? RadioElement {
if currentRadioElement.group == radioElement.group {
if currentRadioElement == radioElement {
return index
}
index += 1
}
}
}
}
return nil
}
public override func getCell(_ tableView: UITableView) -> UITableViewCell! {
let cellKey = "root"
var cell = tableView.dequeueReusableCell(withIdentifier: cellKey) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: cellKey)
cell?.selectionStyle = .default
cell?.accessoryType = .disclosureIndicator
}
cell?.textLabel!.text = title
switch summary {
case .radioGroup(let group):
if let selectedIndex = groups[group] {
var currentIndex = 0
for section in sections {
for element in section.elements {
if let currentRadioElement = element as? RadioElement {
if currentRadioElement.group == group {
if currentIndex == selectedIndex {
cell?.detailTextLabel?.text = currentRadioElement.text
}
currentIndex += 1
}
}
}
}
}
case .count:
var count = 0
for section in sections {
for element in section.elements {
if let boolElement = element as? BooleanValuedElement {
if boolElement.value {
count += 1
}
}
}
}
cell?.detailTextLabel?.text = count.description
case .none:
cell?.detailTextLabel?.text = ""
}
return cell
}
public override func elementSelected(_ dialogController: DialogController, tableView: UITableView, atPath indexPath: IndexPath) {
let vc = DialogViewController(root: self)
dialogController.viewController?.navigationController?.pushViewController(vc, animated: true)
}
func invalidateAll() {
self.dialogController?.viewController?.tableView.reloadData()
}
func invalidateElements(_ invalidatedElements: [Element]) {
var rowsToReload: [IndexPath] = []
outer: for invalidatedElement in invalidatedElements {
guard let sectionOfInvalidatedElement = invalidatedElement.parent as? SectionElement else { continue }
guard let rootOfInvalidatedElement = sectionOfInvalidatedElement.parent as? RootElement else { continue }
if rootOfInvalidatedElement !== self { continue }
for (sectionIndex, section) in sections.enumerated() {
if section !== sectionOfInvalidatedElement { continue }
for (elementIndex, element) in section.elements.enumerated() {
if element === invalidatedElement {
rowsToReload.append(IndexPath(row: elementIndex, section: sectionIndex))
continue outer;
}
}
}
}
self.dialogController?.viewController?.tableView.reloadRows(at: rowsToReload, with: .none)
}
public func sectionIndexForElement(_ element: Element) -> Int? {
guard let sectionOfElement = element.parent as? SectionElement else { return nil }
guard let rootOfElement = sectionOfElement.parent as? RootElement else { return nil }
if rootOfElement !== self { return nil }
for (sectionIndex, section) in sections.enumerated() {
if section === sectionOfElement {
return sectionIndex
}
}
return nil
}
func insert(section: SectionElement, at index: Int) {
sections.insert(newElement: section, at: index)
dialogController?.viewController?.tableView.insertSections(IndexSet(integer: index), with: .none)
}
func remove(section: SectionElement) {
guard let index = sections.index(of: section) else { return }
let _ = sections.remove(at: index)
dialogController?.viewController?.tableView.deleteSections(IndexSet(integer: index), with: .none)
}
}
extension RootElement {
public static func invalidateSummarizedRootOf(element: Element) {
guard let root = element.root else { return }
switch (root.summary) {
case .none:
return
default:
root.root?.invalidateElements([root])
}
}
}
public protocol RootElementBuilder {
func title(_ title: String) -> RootElementBuilder
func sections(_ sections: ArrayRef<SectionElement>) -> RootElementBuilder
func section(_ section: SectionElement) -> RootElementBuilder
func groups(_ groups: [String: Int]) -> RootElementBuilder
func onRefresh(_ closure: @escaping (RootElement) -> ()) -> RootElementBuilder
func summary(_ summary: SummarizeBy) -> RootElementBuilder
func style(_ style: UITableViewStyle) -> RootElementBuilder
func build() -> RootElement
}
extension RootElement {
public static func builder() -> RootElementBuilder {
return BuilderImpl()
}
class BuilderImpl : RootElementBuilder {
private var _title: String = ""
private var _sections: ArrayRef<SectionElement> = ArrayRef<SectionElement>()
private var _groups: [String: Int] = [:]
private var _onRefresh: ((RootElement) -> ())?
private var _summary: SummarizeBy = .none
private var _style: UITableViewStyle = .grouped
func title(_ title: String) -> RootElementBuilder {
_title = title
return self
}
func sections(_ sections: ArrayRef<SectionElement>) -> RootElementBuilder {
_sections = sections
return self
}
func section(_ section: SectionElement) -> RootElementBuilder {
_sections.append(section)
return self
}
func groups(_ groups: [String: Int]) -> RootElementBuilder {
_groups = groups
return self
}
func onRefresh(_ closure: @escaping (RootElement) -> ()) -> RootElementBuilder {
_onRefresh = closure
return self
}
func summary(_ summary: SummarizeBy) -> RootElementBuilder {
_summary = summary
return self
}
func style(_ style: UITableViewStyle) -> RootElementBuilder {
_style = style
return self
}
func build() -> RootElement {
return RootElement(
title: _title,
sections: _sections,
groups: _groups,
onRefresh: _onRefresh,
summary: _summary,
style: _style
)
}
}
}
|
4ed3507efc8e8efaf88512bc8207cbd6
| 32.948097 | 133 | 0.561105 | false | false | false | false |
CatchChat/Yep
|
refs/heads/master
|
Yep/Views/Cells/FeedSkillUsers/FeedSkillUsersCell.swift
|
mit
|
1
|
//
// FeedSkillUsersCell.swift
// Yep
//
// Created by nixzhu on 15/10/23.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class FeedSkillUsersCell: UITableViewCell {
@IBOutlet weak var promptLabel: UILabel!
@IBOutlet weak var avatarImageView1: UIImageView!
@IBOutlet weak var avatarImageView2: UIImageView!
@IBOutlet weak var avatarImageView3: UIImageView!
@IBOutlet weak var accessoryImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
promptLabel.text = NSLocalizedString("People with this skill", comment: "")
accessoryImageView.tintColor = UIColor.yepCellAccessoryImageViewTintColor()
}
func configureWithFeeds(feeds: [DiscoveredFeed]) {
let feedCreators = Array(Set(feeds.map({ $0.creator }))).sort { $0.lastSignInUnixTime > $1.lastSignInUnixTime }
if let creator = feedCreators[safe: 0] {
let plainAvatar = PlainAvatar(avatarURLString: creator.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView1.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
} else {
avatarImageView1.image = nil
}
if let creator = feedCreators[safe: 1] {
let plainAvatar = PlainAvatar(avatarURLString: creator.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView2.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
} else {
avatarImageView2.image = nil
}
if let creator = feedCreators[safe: 2] {
let plainAvatar = PlainAvatar(avatarURLString: creator.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView3.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
} else {
avatarImageView3.image = nil
}
}
}
|
0d5f6b127db6e0752a22e37818ece8cf
| 33.857143 | 119 | 0.698258 | false | false | false | false |
Snowgan/WeiboDemo
|
refs/heads/master
|
WeiboDemo/XLTabBar.swift
|
mit
|
1
|
//
// XLTabBar.swift
// WeiboDemo
//
// Created by Jennifer on 18/11/15.
// Copyright © 2015 Snowgan. All rights reserved.
//
import UIKit
class XLTabBar: UITabBar {
var composeButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
// self.backgroundImage = UIImage(named: "tabbar_backgroud")
self.backgroundColor = UIColor.whiteColor()
composeButton = UIButton()
composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
self.addSubview(composeButton)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let tabbarCount = items!.count
print(tabbarCount)
let tabbarItemW = bounds.width / CGFloat(tabbarCount + 1)
let tabbarItamH = bounds.height
composeButton.bounds.size = composeButton.currentBackgroundImage!.size
composeButton.center = CGPoint(x: tabbarItemW*2.5, y: tabbarItamH*0.5)
print(subviews.count)
if subviews[2].isKindOfClass(NSClassFromString("UITabBarButton")!) {
print("tabbaritem")
}
for i in 2..<(subviews.count-1) {
var indexW = i - 2
if i > 3 {
indexW += 1
}
subviews[i].center = CGPoint(x: tabbarItemW*(CGFloat(indexW)+0.5), y: tabbarItamH*0.5)
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
fa19e13765d80ce862374fac60e8fdcc
| 30.313433 | 117 | 0.618684 | false | false | false | false |
gustavoavena/BandecoUnicamp
|
refs/heads/master
|
BandecoUnicamp/ConfiguracoesTableViewController.swift
|
mit
|
1
|
//
// ConfuiguracoesTableViewController.swift
// BandecoUnicamp
//
// Created by Gustavo Avena on 10/06/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import UIKit
import UserNotifications
class ConfiguracoesTableViewController: UITableViewController {
@IBOutlet weak var dietaSwitch: UISwitch!
@IBOutlet weak var veggieTableViewCell: UITableViewCell!
@IBOutlet weak var notificationSwitch: UISwitch!
@IBOutlet weak var almocoNotificationCell: UITableViewCell!
@IBOutlet weak var jantarNotificationCell: UITableViewCell!
/// Responsavel por atualizar todo o UI relacionado as notificacoes. Toda vez que alguma opcao de notificacao for alterada, esse metodo deve ser chamado para
// garantir que os textos dos horarios estejamo corretos e as linhas das notificacoes das refeicoes aparecam somente se ativadas.
func loadNotificationOptions() {
notificationSwitch.isOn = UserDefaults.standard.bool(forKey: NOTIFICATION_KEY_STRING)
// TODO: setar o numero de linhas e as opcoes de notificacoes (ativadas ou nao, horario, etc) baseadp no User Defaults.
// e.g. notificacao_almoco = "12:00" e notificacao_jantar = nil
if let hora_almoco = UserDefaults.standard.string(forKey: ALMOCO_TIME_KEY_STRING) {
print("Setando horario da notificacao do almoco: \(hora_almoco)")
almocoNotificationCell.detailTextLabel?.text = hora_almoco
} else {
print("Horario pra notificacao do almoco nao encontrado.")
// nao colocar linhas a mais na table view...
}
if let hora_jantar = UserDefaults.standard.string(forKey: JANTAR_TIME_KEY_STRING) {
print("Setando horario da notificacao do jantar: \(hora_jantar)")
jantarNotificationCell.detailTextLabel?.text = hora_jantar
} else {
// nao colocar linhas a mais na table view...
print("Horario pra notificacao do jantar nao encontrado.")
}
}
override func viewDidLoad() {
super.viewDidLoad()
dietaSwitch.isOn = UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: VEGETARIANO_KEY_STRING)
// back button color
self.navigationController?.navigationBar.tintColor = UIColor(red:0.96, green:0.42, blue:0.38, alpha:1.0)
// disable highlight on veggie's cell. its only possible to click on switch
self.veggieTableViewCell.selectionStyle = .none;
tableView.reloadData()
loadNotificationOptions()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
trackScreenView()
}
@IBAction func dietaValueChanged(_ sender: UISwitch) {
UserDefaults(suiteName: "group.bandex.shared")!.set(sender.isOn, forKey: VEGETARIANO_KEY_STRING)
CardapioServices.shared.registerDeviceToken()
}
// Abre o feedback form no Safari
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 && indexPath.row == 0 {
UIApplication.shared.openURL(URL(string: "https://docs.google.com/forms/d/e/1FAIpQLSekvO0HnnfGnk0-FLTX86mVxAOB5Uajq8MPmB0Sv1pXPuQiCg/viewform")!)
tableView.deselectRow(at: indexPath, animated: true)
}
}
// - MARK: notifications
@IBAction func notificationSwitchToggled(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: NOTIFICATION_KEY_STRING)
if(sender.isOn) {
if #available(iOS 10.0, *) {
registerForPushNotifications()
} else {
// Fallback on earlier versions
}
} else { // Desabilitar notificacao
if #available(iOS 10.0, *) {
if let token = UserDefaults.standard.object(forKey: "deviceToken") as? String {
CardapioServices.shared.unregisterDeviceToken(token: token)
UserDefaults.standard.set(nil, forKey: ALMOCO_TIME_KEY_STRING)
UserDefaults.standard.set(nil, forKey: JANTAR_TIME_KEY_STRING)
self.loadNotificationOptions()
} else {
print("Device token nao encontrado para ser removido")
}
} else {
// Fallback on earlier versions
}
}
tableView.reloadData()
}
@available(iOS 10.0, *)
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {
(granted, error) in
// print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
@available(iOS 10.0, *)
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
// print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
// Executing is main queue because of warning from XCode 9 thread sanitizer.
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
// TODO: atualizar opcoes de notificacoes no User Defaults.
if UserDefaults.standard.string(forKey: ALMOCO_TIME_KEY_STRING) == nil {
print("Configurando horario para notificacao do almoco pela primeira vez")
UserDefaults.standard.set("11:00", forKey: ALMOCO_TIME_KEY_STRING)
}
if UserDefaults.standard.string(forKey: JANTAR_TIME_KEY_STRING) == nil{
print("Configurando horario para notificacao do jantar pela primeira vez")
UserDefaults.standard.set("17:00", forKey: JANTAR_TIME_KEY_STRING)
}
// atualizar UI.
self.loadNotificationOptions()
}
}
}
// MARK: Time of notifications
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destiny = segue.destination as? NotificationTimeViewController {
destiny.notificationTimeDisplayDelegate = self
if segue.identifier == "SegueAlmocoTime" {
destiny.refeicao = TipoRefeicao.almoco
destiny.pickerTimeOptions = destiny.ALMOCO_TIME_OPTIONS
//destiny.selectedTime =
}
if segue.identifier == "SegueJantarTime" {
destiny.refeicao = TipoRefeicao.jantar
destiny.pickerTimeOptions = destiny.JANTAR_TIME_OPTIONS
}
}
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if #available(iOS 10, *)
{
} else {
// ios 9 only
if(section == 1){
return 0.01
}
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if(section == 1){
return 0.01
}
}
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = [1,notificationSwitch.isOn ? 3 : 1,2]
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if(section == 1){
rows[section] = 0
}
}
}
return rows[section]
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
var title = super.tableView(tableView, titleForFooterInSection: section)
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if section == 1 {
title = ""
}
}
}
return title
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = super.tableView(tableView, titleForHeaderInSection: section)
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if section == 1 {
title = ""
}
}
}
return title
}
}
extension ConfiguracoesTableViewController: NotificationTimeDisplayDelegate {
func updateTimeString(time: String, refeicao: TipoRefeicao) {
let cell = refeicao == .almoco ? almocoNotificationCell : jantarNotificationCell
cell?.detailTextLabel?.text = time
}
}
|
10445774a509ef6b139d45ec729a7277
| 32.509868 | 161 | 0.558751 | false | false | false | false |
adrfer/swift
|
refs/heads/master
|
test/SILGen/enum_resilience.swift
|
apache-2.0
|
4
|
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s
import resilient_enum
// Resilient enums are always address-only, and switches must include
// a default case
// CHECK-LABEL: sil hidden @_TF15enum_resilience15resilientSwitchFO14resilient_enum6MediumT_ : $@convention(thin) (@in Medium) -> ()
// CHECK: [[BOX:%.*]] = alloc_stack $Medium
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]
// CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb3:
// CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: [[INDIRECT:%.*]] = load [[INDIRECT_ADDR]]
// CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]]
// CHECK-NEXT: strong_release [[INDIRECT]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb4:
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: unreachable
// CHECK: bb6:
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
func resilientSwitch(m: Medium) {
switch m {
case .Paper: ()
case .Canvas: ()
case .Pamphlet: ()
case .Postcard: ()
}
}
// Indirect enums are still address-only, because the discriminator is stored
// as part of the value, so we cannot resiliently make assumptions about the
// enum's size
// CHECK-LABEL: sil hidden @_TF15enum_resilience21indirectResilientEnumFO14resilient_enum16IndirectApproachT_ : $@convention(thin) (@in IndirectApproach) -> ()
func indirectResilientEnum(ia: IndirectApproach) {}
|
70bfb0d6d37f439d2f715e2e713947ea
| 40.470588 | 209 | 0.648227 | false | false | false | false |
dsay/POPDataSource
|
refs/heads/master
|
DataSources/DataSource/EditableCellDataSource.swift
|
mit
|
1
|
import UIKit
public struct EditAction {
let action: DataSource.Action
let title: String
let color: UIColor
}
public protocol EditableCellDataSource {
func editActions() -> [EditAction]
}
extension TableViewDataSource where
Self: EditableCellDataSource & DataContainable & CellContainable,
Self.Configurator: CellSelectable,
Self.Configurator.Item == Self.Item
{
func canEditRow(for tableView: UITableView, at indexPath: IndexPath) -> Bool {
return true
}
func editActions(for tableView: UITableView, at indexPath: IndexPath) -> [UITableViewRowAction]? {
return self.editActions().map { retrive($0, tableView) }
}
private func retrive(_ editAction: EditAction,_ tableView: UITableView) -> UITableViewRowAction {
let action = UITableViewRowAction(style: .normal, title: editAction.title)
{ (action, indexPath) in
let attributes = self.attributes(in: tableView, at: indexPath)
if let selector = self.cellConfigurator?.selectors[editAction.action] {
selector(attributes.cell, indexPath, attributes.item)
}
}
action.backgroundColor = editAction.color
return action
}
private func attributes(in tableView: UITableView, at indexPath: IndexPath) -> (cell: Cell, item: Item) {
let item = self.item(at: indexPath.row)
guard let cell = tableView.cellForRow(at: indexPath) as? Cell else {
fatalError("cell no found")
}
return (cell, item)
}
}
|
f42777e640d5464cb1e4a91fae16fad1
| 32.574468 | 109 | 0.655894 | false | true | false | false |
donnywals/StoryboardsAndXibs
|
refs/heads/master
|
StoryboardsAndXibs/TableViewDataSource.swift
|
mit
|
1
|
//
// TableViewDataSource.swift
// StoryboardsAndXibs
//
// Created by Donny Wals on 10-07-15.
// Copyright (c) 2015 Donny Wals. All rights reserved.
//
import UIKit
class TableViewDataSource: NSObject, UITableViewDataSource {
let items = ["item_1", "item_2", "item_3", "item_4", "item_5"]
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell!
if let c = tableView.dequeueReusableCellWithIdentifier("myCell") as? UITableViewCell {
cell = c
} else {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myCell")
}
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
}
|
9d90d3365621dae5a8c03ccde679852d
| 30.125 | 109 | 0.658635 | false | false | false | false |
SwiftStudies/OysterKit
|
refs/heads/master
|
Sources/stlrc/Options/LanguageOption.swift
|
bsd-2-clause
|
1
|
//
// StlrOptions.swift
// OysterKitPackageDescription
//
// Created by Swift Studies on 08/12/2017.
//
import Foundation
import OysterKit
import STLR
class LanguageOption : Option, IndexableParameterized {
typealias ParameterIndexType = Parameters
/**
Parameters
*/
public enum Parameters : Int, ParameterIndex {
case language = 0
public var parameter: Parameter{
switch self {
case .language:
return Language().one(optional: false)
}
}
public static var all: [Parameter]{
return [
Parameters.language.parameter
]
}
}
public struct Language : ParameterType{
enum Supported : String{
case swift
case swiftIR
case swiftPM
var fileExtension : String? {
switch self {
case .swift:
return rawValue
default:
return nil
}
}
func operations(in scope:STLR, for grammarName:String) throws ->[STLROperation]? {
switch self {
case .swift:
return nil
case .swiftIR:
return try SwiftStructure.generate(for: scope, grammar: grammarName, accessLevel: "public")
case .swiftPM:
return try SwiftPackageManager.generate(for: scope, grammar: grammarName, accessLevel: "public")
}
}
func generate(grammarName: String, from stlr:STLR, optimize:Bool, outputTo:String) throws {
if optimize {
STLR.register(optimizer: InlineIdentifierOptimization())
STLR.register(optimizer: CharacterSetOnlyChoiceOptimizer())
} else {
STLR.removeAllOptimizations()
}
stlr.grammar.optimize()
/// Use operation based generators
if let operations = try operations(in: stlr, for: grammarName) {
let workingDirectory = URL(fileURLWithPath: outputTo).deletingLastPathComponent().path
let context = OperationContext(with: URL(fileURLWithPath: workingDirectory)){
print($0)
}
do {
try operations.perform(in: context)
} catch OperationError.error(let message){
print(message.color(.red))
exit(EXIT_FAILURE)
} catch {
print(error.localizedDescription.color(.red))
exit(EXIT_FAILURE)
}
} else {
switch self {
case .swift:
let file = TextFile(grammarName+".swift")
stlr.swift(in: file)
let workingDirectory = URL(fileURLWithPath: outputTo).deletingLastPathComponent().path
let context = OperationContext(with: URL(fileURLWithPath: workingDirectory)) { (message) in
print(message)
}
try file.perform(in: context)
default:
throw OperationError.error(message: "Language did not produce operations")
}
}
}
}
public var name = "Language"
public func transform(_ argumentValue: String) -> Any? {
return Supported(rawValue: argumentValue)
}
}
init(){
super.init(shortForm: "l", longForm: "language", description: "The language to generate", parameterDefinition: Parameters.all, required: false)
}
}
|
70ec67d65e8a4a2c1788c3e0bbab94ad
| 32.467213 | 151 | 0.480774 | false | false | false | false |
vector-im/vector-ios
|
refs/heads/master
|
RiotSwiftUI/Modules/Common/ViewModel/StateStoreViewModel.swift
|
apache-2.0
|
1
|
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import Foundation
import Combine
/// A constrained and concise interface for interacting with the ViewModel.
///
/// This class is closely bound to`StateStoreViewModel`. It provides the exact interface the view should need to interact
/// ViewModel (as modelled on our previous template architecture with the addition of two-way binding):
/// - The ability read/observe view state
/// - The ability to send view events
/// - The ability to bind state to a specific portion of the view state safely.
/// This class was brought about a little bit by necessity. The most idiomatic way of interacting with SwiftUI is via `@Published`
/// properties which which are property wrappers and therefore can't be defined within protocols.
/// A similar approach is taken in libraries like [CombineFeedback](https://github.com/sergdort/CombineFeedback).
/// It provides a nice layer of consistency and also safety. As we are not passing the `ViewModel` to the view directly, shortcuts/hacks
/// can't be made into the `ViewModel`.
@available(iOS 14, *)
@dynamicMemberLookup
class ViewModelContext<ViewState:BindableState, ViewAction>: ObservableObject {
// MARK: - Properties
// MARK: Private
fileprivate let viewActions: PassthroughSubject<ViewAction, Never>
// MARK: Public
/// Get-able/Observable `Published` property for the `ViewState`
@Published fileprivate(set) var viewState: ViewState
/// Set-able/Bindable access to the bindable state.
subscript<T>(dynamicMember keyPath: WritableKeyPath<ViewState.BindStateType, T>) -> T {
get { viewState.bindings[keyPath: keyPath] }
set { viewState.bindings[keyPath: keyPath] = newValue }
}
// MARK: Setup
init(initialViewState: ViewState) {
self.viewActions = PassthroughSubject()
self.viewState = initialViewState
}
// MARK: Public
/// Send a `ViewAction` to the `ViewModel` for processing.
/// - Parameter viewAction: The `ViewAction` to send to the `ViewModel`.
func send(viewAction: ViewAction) {
viewActions.send(viewAction)
}
}
/// A common ViewModel implementation for handling of `State`, `StateAction`s and `ViewAction`s
///
/// Generic type State is constrained to the BindableState protocol in that it may contain (but doesn't have to)
/// a specific portion of state that can be safely bound to.
/// If we decide to add more features to our state management (like doing state processing off the main thread)
/// we can do it in this centralised place.
@available(iOS 14, *)
class StateStoreViewModel<State: BindableState, StateAction, ViewAction> {
typealias Context = ViewModelContext<State, ViewAction>
// MARK: - Properties
// MARK: Public
/// For storing subscription references.
///
/// Left as public for `ViewModel` implementations convenience.
var cancellables = Set<AnyCancellable>()
/// Constrained interface for passing to Views.
var context: Context
var state: State {
get { context.viewState }
set { context.viewState = newValue }
}
// MARK: Setup
init(initialViewState: State) {
self.context = Context(initialViewState: initialViewState)
self.context.viewActions.sink { [weak self] action in
guard let self = self else { return }
self.process(viewAction: action)
}
.store(in: &cancellables)
}
/// Send state actions to modify the state within the reducer.
/// - Parameter action: The state action to send to the reducer.
@available(*, deprecated, message: "Mutate state directly instead")
func dispatch(action: StateAction) {
Self.reducer(state: &context.viewState, action: action)
}
/// Send state actions from a publisher to modify the state within the reducer.
/// - Parameter actionPublisher: The publisher that produces actions to be sent to the reducer
@available(*, deprecated, message: "Mutate state directly instead")
func dispatch(actionPublisher: AnyPublisher<StateAction, Never>) {
actionPublisher.sink { [weak self] action in
guard let self = self else { return }
Self.reducer(state: &self.context.viewState, action: action)
}
.store(in: &cancellables)
}
/// Override to handle mutations to the `State`
///
/// A redux style reducer, all modifications to state happen here.
/// - Parameters:
/// - state: The `inout` state to be modified,
/// - action: The action that defines which state modification should take place.
class func reducer(state: inout State, action: StateAction) {
//Default implementation, -no-op
}
/// Override to handles incoming `ViewAction`s from the `ViewModel`.
/// - Parameter viewAction: The `ViewAction` to be processed in `ViewModel` implementation.
func process(viewAction: ViewAction) {
//Default implementation, -no-op
}
}
|
e210d6dd139ac2b70a5f3ee5e413ba9d
| 37.868056 | 136 | 0.699839 | false | false | false | false |
Alexandre-Georges/Filterer
|
refs/heads/master
|
Filterer/AGImageProcessor.swift
|
mit
|
1
|
import UIKit
protocol AGFilter {
func applyFilter(image: RGBAImage)
func changePixel(inout pixel: Pixel)
}
class AGColourFilter : AGFilter {
var intensity: Float
var colourFilterFunction: ((inout Pixel) -> Void)? = nil
init (colourToFilter: String, intensity: Float) {
self.intensity = intensity
switch colourToFilter {
case "red": colourFilterFunction = { pixel in
pixel.green = pixel.green - UInt8(Double(pixel.green) * Double(self.intensity) / 100.0)
pixel.blue = pixel.blue - UInt8(Double(pixel.blue) * Double(self.intensity) / 100.0)
}
case "green": colourFilterFunction = { pixel in
pixel.red = pixel.red - UInt8(Double(pixel.red) * Double(self.intensity) / 100.0)
pixel.blue = pixel.blue - UInt8(Double(pixel.blue) * Double(self.intensity) / 100.0)
}
case "blue": colourFilterFunction = { pixel in
pixel.red = pixel.red - UInt8(Double(pixel.red) * Double(self.intensity) / 100.0)
pixel.green = pixel.green - UInt8(Double(pixel.green) * Double(self.intensity) / 100.0)
}
default: colourFilterFunction = { pixel in
}
}
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
self.colourFilterFunction!(&pixel)
}
}
class AGBlackAndWhiteFilter : AGFilter {
var intensity: Float
init (intensity: Float) {
self.intensity = intensity
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
let medianValue = (UInt32(pixel.red) + UInt32(pixel.green) + UInt32(pixel.blue)) / 3
let filteredValue = Pixel(value: (UInt32(medianValue) | (UInt32(medianValue) << 8) | (UInt32(medianValue) << 16) | (UInt32(pixel.alpha) << 24)))
pixel.red = UInt8(Double(pixel.red) + Double(Int(filteredValue.red) - Int(pixel.red)) * Double(self.intensity) / 100)
pixel.green = UInt8(Double(pixel.green) + Double(Int(filteredValue.green) - Int(pixel.green)) * Double(self.intensity) / 100)
pixel.blue = UInt8(Double(pixel.blue) + Double(Int(filteredValue.blue) - Int(pixel.blue)) * Double(self.intensity) / 100)
}
}
class AGSepiaFilter : AGFilter {
var intensity: Float
init (intensity: Float) {
self.intensity = intensity
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
pixel.red = UInt8(min(255,
Double(pixel.red) - (Double(pixel.red) - Double(pixel.red) * 0.393) * Double(self.intensity) / 100 +
Double(pixel.green) - (Double(pixel.green) - Double(pixel.green) * 0.769) * Double(self.intensity) / 100 +
Double(pixel.blue) - (Double(pixel.blue) - Double(pixel.blue) * 0.189) * Double(self.intensity) / 100))
pixel.green = UInt8(min(255,
Double(pixel.red) - (Double(pixel.red) - Double(pixel.red) * 0.349) * Double(self.intensity) / 100 +
Double(pixel.green) - (Double(pixel.green) - Double(pixel.green) * 0.686) * Double(self.intensity) / 100 +
Double(pixel.blue) - (Double(pixel.blue) - Double(pixel.blue) * 0.168) * Double(self.intensity) / 100))
pixel.blue = UInt8(min(255,
Double(pixel.red) - (Double(pixel.red) - Double(pixel.red) * 0.272) * Double(self.intensity) / 100 +
Double(pixel.green) - (Double(pixel.green) - Double(pixel.green) * 0.534) * Double(self.intensity) / 100 +
Double(pixel.blue) - (Double(pixel.blue) - Double(pixel.blue) * 0.131) * Double(self.intensity) / 100))
}
}
class AGBrightnessFilter : AGFilter {
var brightnessDelta: Int = 0
init (intensity: Float) {
self.brightnessDelta = Int(255 * (intensity * 2 - 100) / 100)
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
pixel.red = UInt8(max(0, min(255, Int(pixel.red) + brightnessDelta)))
pixel.green = UInt8(max(0, min(255, Int(pixel.green) + brightnessDelta)))
pixel.blue = UInt8(max(0, min(255, Int(pixel.blue) + brightnessDelta)))
}
}
/*
class AGContrastFilter : AGFilterOld {
var averageRed: Int = 0
var averageGreen: Int = 0
var averageBlue: Int = 0
var deltaCoefficient: Double = 1.0
init (deltaCoefficient: Double) {
self.deltaCoefficient = deltaCoefficient
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
let pixel = image.pixels[index]
self.averageRed += Int(pixel.red)
self.averageGreen += Int(pixel.green)
self.averageBlue += Int(pixel.blue)
}
}
self.averageRed /= (image.width * image.height)
self.averageGreen /= (image.width * image.height)
self.averageBlue /= (image.width * image.height)
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
pixel.red = self.getDelta(UInt8(self.averageRed), value: pixel.red)
pixel.green = self.getDelta(UInt8(self.averageGreen), value: pixel.green)
pixel.blue = self.getDelta(UInt8(self.averageBlue), value: pixel.blue)
}
func getDelta(average: UInt8, value: UInt8) -> UInt8 {
let delta: Int = Int(value) - Int(average)
let theoreticalValue: Int = Int(value) + Int(Double(delta) * self.deltaCoefficient)
return UInt8(max(min(theoreticalValue, 255), 0))
}
}*/
enum AGFilterNames : String {
case Brightness
case ColourRed
case ColourGreen
case ColourBlue
case BlackAndWhite
}
class AGImageProcessor {
var image: RGBAImage? = nil
var filter: AGFilter? = nil
func addFilter(filterName: AGFilterNames, intensity: Float) {
var filter: AGFilter? = nil
switch filterName {
case AGFilterNames.Brightness : filter = AGBrightnessFilter(intensity: intensity)
case AGFilterNames.ColourRed : filter = AGColourFilter(colourToFilter: "red", intensity: intensity)
case AGFilterNames.ColourGreen : filter = AGColourFilter(colourToFilter: "green", intensity: intensity)
case AGFilterNames.ColourBlue : filter = AGColourFilter(colourToFilter: "blue", intensity: intensity)
case AGFilterNames.BlackAndWhite : filter = AGBlackAndWhiteFilter(intensity: intensity)
}
self.filter = filter!
}
func applyFilter() {
self.filter!.applyFilter(self.image!)
}
func getImage() -> UIImage {
return self.image!.toUIImage()!
}
func setImage(image: UIImage) {
self.image = RGBAImage(image: image)!
}
}
|
74ed1bea4954f155cf422841e1aeeea8
| 35.58296 | 152 | 0.596837 | false | false | false | false |
Urinx/SublimeCode
|
refs/heads/master
|
Sublime/Sublime/SSHServerListTableViewController.swift
|
gpl-3.0
|
1
|
//
// SSHServerListTableViewController.swift
// Sublime
//
// Created by Eular on 3/28/16.
// Copyright © 2016 Eular. All rights reserved.
//
import UIKit
class SSHServerListTableViewController: UITableViewController {
let serverPlist = Plist(path: Constant.SublimeRoot+"/etc/ssh_list.plist")
var serverList: [[String: String]] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Servers"
tableView.backgroundColor = Constant.CapeCod
tableView.separatorColor = Constant.NavigationBarAndTabBarColor
tableView.tableFooterView = UIView()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(self.addNewServer))
}
override func viewWillAppear(animated: Bool) {
if let arr = serverPlist.getArrayInPlistFile() {
serverList = arr as! [[String : String]]
tableView.reloadData()
}
}
func addNewServer() {
let addnew = SSHAddNewServerViewController()
navigationController?.pushViewController(addnew, animated: true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return serverList.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return Constant.SSHServerListCellHeight
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
cell.backgroundColor = Constant.NavigationBarAndTabBarColor
cell.selectedBackgroundView = UIView(frame: cell.frame)
cell.selectedBackgroundView?.backgroundColor = Constant.TableCellSelectedColor
cell.accessoryType = .DisclosureIndicator
cell.textLabel?.text = serverList[indexPath.row]["host"]
cell.textLabel?.textColor = UIColor.whiteColor()
cell.detailTextLabel?.text = serverList[indexPath.row]["username"]
cell.detailTextLabel?.textColor = RGB(190, 190, 190)
cell.imageView?.image = UIImage(named: "ssh_server")
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
serverList.removeAtIndex(indexPath.row)
do {
try serverPlist.saveToPlistFile(serverList)
} catch {}
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let terminal = SSHTerminalViewController()
terminal.server = serverList[indexPath.row]
navigationController?.pushViewController(terminal, animated: true)
}
}
|
1cddf624ec93dd56122f6a19cf66522c
| 36.444444 | 157 | 0.683086 | false | false | false | false |
quangvu1994/Exchange
|
refs/heads/master
|
Exchange/View/CollectionTableViewCell.swift
|
mit
|
1
|
//
// CollectionTableViewCell.swift
// Exchange
//
// Created by Quang Vu on 7/20/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
import FirebaseDatabase
class CollectionTableViewCell: UITableViewCell {
var status: String?
var itemList = [String: Any]() {
didSet {
collectionView.reloadData()
}
}
var cashAmount: String?
var controller: DisplayItemDetailHandler?
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension CollectionTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numOfItems = itemList.count
if let _ = cashAmount {
numOfItems += 1
}
if numOfItems == 0 {
let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
emptyLabel.textAlignment = .center
emptyLabel.font = UIFont(name: "Futura", size: 14)
emptyLabel.textColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
emptyLabel.numberOfLines = 2
emptyLabel.text = "No items offered "
collectionView.backgroundView = emptyLabel
}
return numOfItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Item Cell", for: indexPath) as! MyItemPostImageCell
// If there is cash
if let cashAmount = cashAmount {
// if this is the last cell
if indexPath.row == itemList.count {
cell.imageLabel.text = cashAmount
cell.imageLabel.isHidden = false
return cell
}
}
if let controller = controller {
cell.delegate = controller
cell.gestureDisplayingItemDetailWithInfo()
}
let key = Array(itemList.keys)[indexPath.row]
if let itemDataDict = itemList[key] as? [String : Any],
let url = itemDataDict["image_url"] as? String,
let itemTitle = itemDataDict["post_title"] as? String,
let itemDescription = itemDataDict["post_description"] as? String {
let imageURL = URL(string: url)
cell.postImage.kf.setImage(with: imageURL)
cell.itemImageURL = url
cell.itemTitle = itemTitle
cell.itemDescription = itemDescription
}
// Observe the availability of the item
let itemRef = Database.database().reference().child("allItems/\(key)/availability")
itemRef.observe(.value, with: { (snapshot) in
guard let availability = snapshot.value as? Bool else {
return
}
if !availability && self.status != "Confirmed"{
cell.soldLabel.isHidden = false
} else {
cell.soldLabel.isHidden = true
}
})
return cell
}
}
extension CollectionTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.height, height: collectionView.bounds.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
|
b3d3d91efc2797323051def4040d29cf
| 35.537037 | 170 | 0.622402 | false | false | false | false |
TheNounProject/CollectionView
|
refs/heads/main
|
CollectionView/DataStructures/SortDescriptor.swift
|
mit
|
1
|
//
// SortDescriptor.swift
// CollectionView
//
// Created by Wesley Byrne on 2/16/18.
// Copyright © 2018 Noun Project. All rights reserved.
//
import Foundation
/// Sort Descriptor Result
///
/// - same: The two objects are equally compared
/// - ascending: The first object is before the second (ordered)
/// - descending: The second object precedes the first (reversed)
public enum SortDescriptorResult: ExpressibleByBooleanLiteral {
case same
case ascending
case descending
public typealias BooleanLiteralType = Bool
public init(booleanLiteral value: Bool) {
self = value ? .ascending : .descending
}
}
/// a comparator used to compare two objects
public struct SortDescriptor<T> {
public let ascending: Bool
private let comparator: (T, T) -> SortDescriptorResult
/// Initialize a sort descriptor with a custom comparator
///
/// - Parameter keyPath: A keypath for the type being sorted
/// - Parameter ascending: If the comparison should order ascending
public init<V: Comparable>(_ keyPath: KeyPath<T, V>, ascending: Bool = true) {
self.comparator = {
let v1 = $0[keyPath: keyPath]
let v2 = $1[keyPath: keyPath]
if v1 < v2 { return ascending ? .ascending : .descending }
if v1 > v2 { return ascending ? .descending : .ascending }
return .same
}
self.ascending = ascending
}
/// Initialize a sort descriptor with a custom comparator
///
/// - Parameter comparator: A comparator returning a comparison result
public init(_ comparator: @escaping ((T, T) -> SortDescriptorResult)) {
self.comparator = comparator
self.ascending = true
}
/// Compare two objects
///
/// - Parameters:
/// - a: The first object
/// - b: The second object
/// - Returns: A SortDescriptorResult for the two objects.
public func compare(_ a: T, to b: T) -> SortDescriptorResult {
return comparator(a, b)
}
}
extension SortDescriptor where T: Comparable {
public static var ascending: SortDescriptor<T> {
return SortDescriptor({ (a, b) -> SortDescriptorResult in
if a == b { return .same }
if a > b { return .descending }
return .ascending
})
}
public static var descending: SortDescriptor<T> {
return SortDescriptor({ (a, b) -> SortDescriptorResult in
if a == b { return .same }
if a > b { return .descending }
return .ascending
})
}
}
protocol Comparer {
associatedtype Compared
func compare(_ a: Compared, to b: Compared) -> SortDescriptorResult
}
extension SortDescriptor: Comparer { }
extension Sequence where Element: Comparer {
func compare(_ element: Element.Compared, _ other: Element.Compared) -> SortDescriptorResult {
for comparer in self {
switch comparer.compare(element, to: other) {
case .same: break
case .descending: return .descending
case .ascending: return .ascending
}
}
return .same
}
func element(_ element: Element.Compared, isBefore other: Element.Compared) -> Bool {
return self.compare(element, other) == .ascending
}
}
public extension Array {
mutating func sort(using sortDescriptor: SortDescriptor<Element>) {
self.sort { (a, b) -> Bool in
return sortDescriptor.compare(a, to: b) == .ascending
}
}
mutating func sort(using sortDescriptors: [SortDescriptor<Element>]) {
guard !sortDescriptors.isEmpty else { return }
if sortDescriptors.count == 1 {
return self.sort(using: sortDescriptors[0])
}
self.sort { (a, b) -> Bool in
for desc in sortDescriptors {
switch desc.compare(a, to: b) {
case .same: break
case .descending: return false
case .ascending: return true
}
}
return false
}
}
mutating func insert(_ element: Element, using sortDescriptors: [SortDescriptor<Element>]) -> Int {
if !sortDescriptors.isEmpty, let idx = (self.firstIndex { return sortDescriptors.compare(element, $0) != .ascending }) {
self.insert(element, at: idx)
return idx
}
self.append(element)
return self.count - 1
}
// public mutating func insert(_ element: Element, using sortDescriptors: [SortDescriptor<Element>]) -> Int {
// if sortDescriptors.count > 0 {
// for (idx, existing) in self.enumerated() {
// if sortDescriptors.compare(element, existing) != .ascending {
// self.insert(element, at: idx)
// return idx
// }
// }
// }
// self.append(element)
// return self.count - 1
// }
}
extension Sequence {
public func sorted(using sortDescriptor: SortDescriptor<Element>) -> [Element] {
return self.sorted(by: { (a, b) -> Bool in
return sortDescriptor.compare(a, to: b) == .ascending
})
}
public func sorted(using sortDescriptors: [SortDescriptor<Element>]) -> [Element] {
guard !sortDescriptors.isEmpty else { return Array(self) }
if sortDescriptors.count == 1 {
return self.sorted(using: sortDescriptors[0])
}
return self.sorted { (a, b) -> Bool in
return sortDescriptors.element(a, isBefore: b)
}
}
}
|
10f3172035442a10202787d6d215e570
| 31.953216 | 128 | 0.593434 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp
|
refs/heads/master
|
HTWDresden/HTWDresden/Dictionary.swift
|
gpl-2.0
|
1
|
//
// Dictionary.swift
// HTWDresden
//
// Created by Benjamin Herzog on 19/04/16.
// Copyright © 2016 HTW Dresden. All rights reserved.
//
import Foundation
public extension Dictionary {
init < S: SequenceType where S.Generator.Element == (Key, Value) > (_ seq: S) {
self = [:]
self.merge(seq)
}
mutating func merge < S: SequenceType where S.Generator.Element == (Key, Value) > (other: S) {
for (k, v) in other {
self[k] = v
}
}
func mapValues<T>(op: Value -> T) -> [Key: T] {
return [Key: T](flatMap { return ($0, op($1)) })
}
var urlParameterRepresentation: String {
return reduce("") {
"\($0)\($0.isEmpty ? "" : "&")\($1.0)=\($1.1)"
}
}
}
|
537490728c449f827cc6eead546e4796
| 20.25 | 95 | 0.589706 | false | false | false | false |
jvivas/OraChallenge
|
refs/heads/master
|
OraChallenge/OraChallenge/API/UsersManager.swift
|
apache-2.0
|
1
|
//
// UsersManager.swift
// OraChallenge
//
// Created by Jorge Vivas on 3/5/17.
// Copyright © 2017 JorgeVivas. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
@objc protocol UsersDelegate {
@objc optional func onCreateUserResponse(user:User?, errorMessage:String?)
@objc optional func onGetCurrentUser(user:User?, errorMessage:String?)
@objc optional func onUpdateCurrentUser(user:User?, errorMessage:String?)
}
class UsersManager: APIManager {
var delegate:UsersDelegate?
let pathUsers = "users"
let pathCurrentUser = "users/current"
func requestCreate(name:String, email:String, password:String, passwordConfirmation:String) {
let parameters: Parameters = ["name" : name, "email": email, "password": password, "password_confirmation" : passwordConfirmation]
request(path: pathUsers, method: .post, parameters: parameters, onSuccess: { (response: SwiftyJSON.JSON) in
let user = User(json: response["data"])
DefaultsManager.saveUserId(userId: (user?.id)!)
self.delegate?.onCreateUserResponse!(user: user, errorMessage: nil)
}, onFailed: { (response: String, statusCode:Int) in
self.delegate?.onCreateUserResponse!(user: nil, errorMessage: response)
})
}
func requestCurrentUser() {
request(path: pathCurrentUser, method: .get, parameters: nil, onSuccess: { (response: SwiftyJSON.JSON) in
let user = User(json: response["data"])
self.delegate?.onGetCurrentUser!(user: user, errorMessage: nil)
}, onFailed: { (response: String, statusCode:Int) in
self.delegate?.onGetCurrentUser!(user: nil, errorMessage: response)
})
}
func requestUpdateCurrentUser(name:String, email:String) {
let parameters: Parameters = ["name" : name, "email": email]
request(path: pathCurrentUser, method: .patch, parameters: parameters, onSuccess: { (response: SwiftyJSON.JSON) in
let user = User(json: response["data"])
self.delegate?.onUpdateCurrentUser!(user: user, errorMessage: nil)
}, onFailed: { (response: String, statusCode:Int) in
self.delegate?.onUpdateCurrentUser!(user: nil, errorMessage: response)
})
}
}
|
8bf7efa986b22899c46c05a55004c757
| 42.377358 | 138 | 0.670726 | false | false | false | false |
orta/SignalKit
|
refs/heads/master
|
SignalKit/Extensions/UIKit/UIView+Signal.swift
|
mit
|
1
|
//
// UIView+Signal.swift
// SignalKit
//
// Created by Yanko Dimitrov on 8/16/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
public extension SignalType where Item == UIColor {
/**
Bind a UIColor to the background color of UIView
*/
public func bindTo(backgroundColorIn view: UIView) -> Self {
addObserver { [weak view] in
view?.backgroundColor = $0
}
return self
}
}
public extension SignalType where Item == CGFloat {
/**
Bind a CGFloat value to the alpha property of UIView
*/
public func bindTo(alphaIn view: UIView) -> Self {
addObserver { [weak view] in
view?.alpha = $0
}
return self
}
}
public extension SignalType where Item == Bool {
/**
Bind a Boolean value to the hidden property of UIView
*/
public func bindTo(hiddenStateIn view: UIView) -> Self {
addObserver { [weak view] in
view?.hidden = $0
}
return self
}
}
|
f97ece9fabbea708bebbfccf0e07520c
| 18.466667 | 64 | 0.528253 | false | false | false | false |
AlwaysRightInstitute/SwiftySecurity
|
refs/heads/develop
|
SwiftySecurity/PEM.swift
|
mit
|
1
|
//
// PEM.swift
// TestSwiftyDocker
//
// Created by Helge Hess on 08/05/15.
// Copyright (c) 2015 Helge Hess. All rights reserved.
//
import Foundation
// Note: Security.framework really wants certificates, not raw keys
public func GetDataFromPEM(s: String, type: String = "CERTIFICATE") -> NSData? {
// FIXME: lame implementation ;-)
let keyBegin = "-----BEGIN \(type)-----"
let keyEnd = "-----END \(type)-----"
let scanner = NSScanner(string: s)
scanner.scanUpToString(keyBegin, intoString: nil)
scanner.scanString (keyBegin, intoString: nil)
var base64 : NSString?
scanner.scanUpToString(keyEnd, intoString: &base64)
if base64 == nil || base64!.length < 1 { return nil }
let opts = NSDataBase64DecodingOptions.IgnoreUnknownCharacters
return NSData(base64EncodedString: base64! as String, options: opts)
}
public func GetDataFromPEMFile(path: String, type: String = "CERTIFICATE")
-> NSData?
{
let s: NSString?
do {
s = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
} catch _ {
s = nil
};
return s != nil ? GetDataFromPEM(s! as String, type: type) : nil
}
|
d5b8c1cb9e49cfaec638e033c0f65435
| 27.775 | 80 | 0.676803 | false | false | false | false |
ReSwift/ReSwift-Router
|
refs/heads/master
|
ReSwiftRouter/Router.swift
|
mit
|
2
|
//
// Router.swift
// Meet
//
// Created by Benjamin Encz on 11/11/15.
// Copyright © 2015 ReSwift Community. All rights reserved.
//
import Foundation
import ReSwift
open class Router<State>: StoreSubscriber {
public typealias NavigationStateTransform = (Subscription<State>) -> Subscription<NavigationState>
var store: Store<State>
var lastNavigationState = NavigationState()
var routables: [Routable] = []
let waitForRoutingCompletionQueue = DispatchQueue(label: "WaitForRoutingCompletionQueue", attributes: [])
public init(store: Store<State>, rootRoutable: Routable, stateTransform: @escaping NavigationStateTransform) {
self.store = store
self.routables.append(rootRoutable)
self.store.subscribe(self, transform: stateTransform)
}
open func newState(state: NavigationState) {
let routingActions = Router.routingActionsForTransition(from: lastNavigationState.route,
to: state.route)
routingActions.forEach { routingAction in
let semaphore = DispatchSemaphore(value: 0)
// Dispatch all routing actions onto this dedicated queue. This will ensure that
// only one routing action can run at any given time. This is important for using this
// Router with UI frameworks. Whenever a navigation action is triggered, this queue will
// block (using semaphore_wait) until it receives a callback from the Routable
// indicating that the navigation action has completed
waitForRoutingCompletionQueue.async {
switch routingAction {
case let .pop(responsibleRoutableIndex, elementToBePopped):
DispatchQueue.main.async {
self.routables[responsibleRoutableIndex]
.pop(
elementToBePopped,
animated: state.changeRouteAnimated) {
semaphore.signal()
}
self.routables.remove(at: responsibleRoutableIndex + 1)
}
case let .change(responsibleRoutableIndex, elementToBeReplaced, newElement):
DispatchQueue.main.async {
self.routables[responsibleRoutableIndex + 1] =
self.routables[responsibleRoutableIndex]
.change(
elementToBeReplaced,
to: newElement,
animated: state.changeRouteAnimated) {
semaphore.signal()
}
}
case let .push(responsibleRoutableIndex, elementToBePushed):
DispatchQueue.main.async {
self.routables.append(
self.routables[responsibleRoutableIndex]
.push(
elementToBePushed,
animated: state.changeRouteAnimated) {
semaphore.signal()
}
)
}
}
let waitUntil = DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
let result = semaphore.wait(timeout: waitUntil)
if case .timedOut = result {
print("[ReSwiftRouter]: Router is stuck waiting for a" +
" completion handler to be called. Ensure that you have called the" +
" completion handler in each Routable element.")
print("Set a symbolic breakpoint for the `ReSwiftRouterStuck` symbol in order" +
" to halt the program when this happens")
ReSwiftRouterStuck()
}
}
}
lastNavigationState = state
}
// MARK: Route Transformation Logic
static func largestCommonSubroute(_ oldRoute: Route, newRoute: Route) -> Int {
var largestCommonSubroute = -1
while largestCommonSubroute + 1 < newRoute.count &&
largestCommonSubroute + 1 < oldRoute.count &&
newRoute[largestCommonSubroute + 1] == oldRoute[largestCommonSubroute + 1] {
largestCommonSubroute += 1
}
return largestCommonSubroute
}
// Maps Route index to Routable index. Routable index is offset by 1 because the root Routable
// is not represented in the route, e.g.
// route = ["tabBar"]
// routables = [RootRoutable, TabBarRoutable]
static func routableIndex(for element: Int) -> Int {
return element + 1
}
static func routingActionsForTransition(
from oldRoute: Route,
to newRoute: Route) -> [RoutingActions] {
var routingActions: [RoutingActions] = []
// Find the last common subroute between two routes
let commonSubroute = largestCommonSubroute(oldRoute, newRoute: newRoute)
if commonSubroute == oldRoute.count - 1 && commonSubroute == newRoute.count - 1 {
return []
}
// Keeps track which element of the routes we are working on
// We start at the end of the old route
var routeBuildingIndex = oldRoute.count - 1
// Pop all route elements of the old route that are no longer in the new route
// Stop one element ahead of the commonSubroute. When we are one element ahead of the
// commmon subroute we have three options:
//
// 1. The old route had an element after the commonSubroute and the new route does not
// we need to pop the route element after the commonSubroute
// 2. The old route had no element after the commonSubroute and the new route does, we
// we need to push the route element(s) after the commonSubroute
// 3. The new route has a different element after the commonSubroute, we need to replace
// the old route element with the new one
while routeBuildingIndex > commonSubroute + 1 {
let routeElementToPop = oldRoute[routeBuildingIndex]
let popAction = RoutingActions.pop(
responsibleRoutableIndex: routableIndex(for: routeBuildingIndex - 1),
elementToBePopped: routeElementToPop
)
routingActions.append(popAction)
routeBuildingIndex -= 1
}
// This is the 3. case:
// "The new route has a different element after the commonSubroute, we need to replace
// the old route element with the new one"
if oldRoute.count > (commonSubroute + 1) && newRoute.count > (commonSubroute + 1) {
let changeAction = RoutingActions.change(
responsibleRoutableIndex: routableIndex(for: commonSubroute),
elementToBeReplaced: oldRoute[commonSubroute + 1],
newElement: newRoute[commonSubroute + 1])
routingActions.append(changeAction)
}
// This is the 1. case:
// "The old route had an element after the commonSubroute and the new route does not
// we need to pop the route element after the commonSubroute"
else if oldRoute.count > newRoute.count {
let popAction = RoutingActions.pop(
responsibleRoutableIndex: routableIndex(for: routeBuildingIndex - 1),
elementToBePopped: oldRoute[routeBuildingIndex]
)
routingActions.append(popAction)
routeBuildingIndex -= 1
}
// Push remainder of elements in new Route that weren't in old Route, this covers
// the 2. case:
// "The old route had no element after the commonSubroute and the new route does,
// we need to push the route element(s) after the commonSubroute"
let newRouteIndex = newRoute.count - 1
while routeBuildingIndex < newRouteIndex {
let routeElementToPush = newRoute[routeBuildingIndex + 1]
let pushAction = RoutingActions.push(
responsibleRoutableIndex: routableIndex(for: routeBuildingIndex),
elementToBePushed: routeElementToPush
)
routingActions.append(pushAction)
routeBuildingIndex += 1
}
return routingActions
}
}
func ReSwiftRouterStuck() {}
enum RoutingActions {
case push(responsibleRoutableIndex: Int, elementToBePushed: RouteElement)
case pop(responsibleRoutableIndex: Int, elementToBePopped: RouteElement)
case change(responsibleRoutableIndex: Int, elementToBeReplaced: RouteElement,
newElement: RouteElement)
}
|
58a7ca4794c28833cd973f1e9470b386
| 42.242991 | 115 | 0.572509 | false | false | false | false |
burningmantech/ranger-ims-mac
|
refs/heads/master
|
Incidents/Ranger.swift
|
apache-2.0
|
1
|
//
// Ranger.swift
// Incidents
//
// © 2015 Burning Man and its contributors. All rights reserved.
// See the file COPYRIGHT.md for terms.
//
struct Ranger: CustomStringConvertible, Hashable, Comparable {
var handle: String
var name: String?
var status: String?
var hashValue: Int {
// Only handle matters for equality
return handle.hashValue
}
var description: String {
var result = handle
if name != nil { result += " (\(name!))" }
if status == "vintage" { result += "*" }
return result
}
init(
handle: String,
name : String? = nil,
status: String? = nil
) {
self.handle = handle
self.name = name
self.status = status
}
}
func ==(lhs: Ranger, rhs: Ranger) -> Bool {
// Only handle matters for equality
return lhs.handle == rhs.handle
}
func <(lhs: Ranger, rhs: Ranger) -> Bool {
if lhs.handle < rhs.handle {
return true
} else {
return false
}
}
|
6d700c01ac198a91e3bcaf1cae8b102f
| 18.472727 | 65 | 0.543417 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS
|
refs/heads/master
|
Mr-Ride-iOS/Mr-Ride-iOS/HttpHelper.swift
|
mit
|
1
|
//
// HttpHelper.swift
// Mr-Ride-iOS
//
// Created by Derek on 6/16/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import Foundation
import Alamofire
class HttpHelper {
typealias CompletionHandler = () -> Void
var stationList = [Station]()
func getToilet(completion: CompletionHandler) {
Alamofire.request(.GET,
"http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=008ed7cf-2340-4bc4-89b0-e258a5573be2", parameters: nil).responseJSON { reponse in
// print(reponse.request)
print(reponse.response?.statusCode) //status is here (200...etc)
print(reponse.data)
print(reponse.result.isSuccess) //SUCCESS
guard let JSON = reponse.result.value as? [String: AnyObject] else {
// error handling
print("JSON failed")
return
}
print("JSON done")
guard let result = JSON["result"] as? [String: AnyObject] else {
// error handling
print("result failed")
return
}
print("result done")
guard let results = result["results"] as? [[String: String]] else {
// error handling
print("results failed")
return
}
print("results done")
for data in results {
guard let name = data["單位名稱"] else {
// error handleing
print("單位名稱")
continue
}
guard let address = data["地址"] else {
// error handleing
print("地址")
continue
}
guard let lat = data["緯度"] else {
//error handling
print("緯度")
continue
}
guard let latitude = Double(lat) else {
//error handling
print("casting")
continue
}
guard let lng = data["經度"] else {
// error handleing
print("經度")
continue
}
guard let longitude = Double(lng) else {
//error handling
print("casting")
continue
}
guard let cate = data["類別"] else {
// error handleing
print("類別")
continue
}
// let toilet = Toilet(name: name, category: "ddddd", address: address, latitude: latitude, longitude: longitude)
// self.toiletList.append(toilet)
ToiletRecorder.getInstance().writeData(category: cate, name: name, address: address, lat: latitude, lng: longitude)
}
dispatch_async(dispatch_get_main_queue()){
//
// completion()
self.getToiletRiverSide(completion)
}
}
}
func getToiletRiverSide(completion: CompletionHandler) {
Alamofire.request(.GET,
"http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=fe49c753-9358-49dd-8235-1fcadf5bfd3f", parameters: nil).responseJSON { reponse in
// print(reponse.request)
print(reponse.response?.statusCode) //status is here (200...etc)
// print(reponse.data)
// print(reponse.result.isSuccess) //SUCCESS
guard let JSON = reponse.result.value as? [String: AnyObject] else {
// error handling
print("JSON failed")
return
}
print("JSON done")
guard let result = JSON["result"] as? [String: AnyObject] else {
// error handling
print("result failed")
return
}
print("result done")
guard let results = result["results"] as? [[String: String]] else {
// error handling
print("results failed")
return
}
print("results done")
for data in results {
guard let name = data["Location"] else {
// error handleing
print("Location")
continue
}
guard let lat = data["Latitude"] else {
//error handling
print("Latitude")
continue
}
guard let latitude = Double(lat) else {
//error handling
print("casting")
continue
}
guard let lng = data["Longitude"] else {
// error handleing
print("Longitude")
continue
}
guard let longitude = Double(lng) else {
//error handling
print("casting")
continue
}
// let toilet = Toilet(name: name, category: "River Side", address: "", latitude: latitude, longitude: longitude)
// self.toiletList.append(toilet)
ToiletRecorder.getInstance().writeData(category: "河濱", name: name, address: "", lat: latitude, lng: longitude)
}
dispatch_async(dispatch_get_main_queue()){
completion()
}
}
}
func getStations(completion: CompletionHandler) {
Alamofire.request(.GET,
"http://data.taipei/youbike", parameters: nil).validate().responseJSON { reponse in
// print(reponse.request)
// TODO: error handling
print(reponse.response?.statusCode) //status is here (200...etc)
// print(reponse.data)
print(reponse.result.isSuccess) //SUCCESS
// print(reponse.result.value)
guard let JSON = reponse.result.value as? [String: AnyObject] else {
// error handling
print("JSON failed")
return
}
guard let results = JSON["retVal"] as? [String: [String: String]] else {
// error handling
print("result failed")
return
}
for data in results
{
// station name
guard let name = data.1["sna"] else {
// error handleing
print("站名")
continue
}
guard let nameEN = data.1["snaen"] else {
// error handleing
print("站名EN")
continue
}
// loaction around
guard let location = data.1["ar"] else {
// error handleing
print("位置")
continue
}
guard let locationEN = data.1["aren"] else {
// error handleing
print("位置EN")
continue
}
// area around
guard let area = data.1["sarea"] else {
// error handleing
print("區")
continue
}
guard let areaEN = data.1["sareaen"] else {
// error handleing
print("區EN")
continue
}
// latitude
guard let lat = data.1["lat"] else {
//error handling
print("lat")
continue
}
guard let latitude = Double(lat) else {
//error handling
print("casting")
continue
}
// longitude
guard let lng = data.1["lng"] else {
// error handling
print("lng")
continue
}
guard let longitude = Double(lng) else {
//error handling
print("casting")
continue
}
// bike left
guard let bikeL = data.1["sbi"] else {
// error handling
print("bike left")
continue
}
guard let bikeLeft = Int(bikeL) else {
// error handling
print("casting")
continue
}
// parking space
guard let bikeS = data.1["bemp"] else {
//error handling
print("bike space")
continue
}
guard let bikeSpace = Int(bikeS) else {
// error handling
print("casting")
continue
}
// station available
guard let stationAvailability = data.1["act"] else {
//error handling
print("stationAvailability")
continue
}
guard let act = Int(stationAvailability) else {
continue
}
var isAvailable = true
switch act
{
case 0: isAvailable = false
case 1: isAvailable = true
default: isAvailable = true
}
let station = Station( name: name, nameEN: nameEN,
location: location, locarionEN: locationEN,
area: area, areaEN: areaEN,
latitude: latitude,
longitude: longitude,
bikeleft: bikeLeft,
bikeSpace: bikeSpace,
isAvailable: isAvailable)
self.stationList.append(station)
}
dispatch_async(dispatch_get_main_queue()){
completion()
}
}
}
func getStationList() -> [Station] {
return stationList
}
// get stations here
}
extension HttpHelper {
private static var sharedInstance: HttpHelper?
static func getInstance() -> HttpHelper {
if sharedInstance == nil {
sharedInstance = HttpHelper()
}
return sharedInstance!
}
}
|
a9199b649b8bbeac7b138913850c6717
| 35.267606 | 166 | 0.363756 | false | false | false | false |
icylydia/PlayWithLeetCode
|
refs/heads/master
|
95. Unique Binary Search Trees II/solution.swift
|
mit
|
1
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func generateTrees(n: Int) -> [TreeNode?] {
if n == 0 {
return Array<TreeNode?>()
}
let root: TreeNode? = TreeNode(1)
var dp = Array<Array<TreeNode?>>()
let dp0 = Array<TreeNode?>()
dp.append(dp0)
let dp1 = [root]
dp.append(dp1)
if n == 1 {
return dp[1]
}
for i in 2...n {
var tp = Array<TreeNode?>()
// left nil
for right in dp[i-1] {
var mr = TreeNode(1)
mr.left = nil
mr.right = right?.copy()
tp.append(mr)
}
// right nil
for left in dp[i-1] {
var mr = TreeNode(1)
mr.left = left?.copy()
mr.right = nil
tp.append(mr)
}
// left + right
for j in 1..<i-1 {
for left in dp[j] {
for right in dp[i-1-j] {
var mr = TreeNode(1)
mr.left = left?.copy()
mr.right = right?.copy()
tp.append(mr)
}
}
}
dp.append(tp)
}
for tree in dp[n] {
dfs(0, tree)
}
return dp[n]
}
func dfs(base: Int, _ root: TreeNode?) -> Int {
if let root = root {
let left = dfs(base, root.left)
root.val = left + 1
let right = dfs(left + 1, root.right)
return right
} else {
return base
}
}
}
extension TreeNode {
func copy() -> TreeNode {
var root = TreeNode(self.val)
root.left = self.left?.copy()
root.right = self.right?.copy()
return root
}
}
|
287e694575c12094b2bdb5c1b66f045e
| 21.225 | 51 | 0.487338 | false | false | false | false |
ilhanadiyaman/firefox-ios
|
refs/heads/master
|
Storage/SQL/SQLiteHistory.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 Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
class NoSuchRecordError: MaybeErrorType {
let guid: GUID
init(guid: GUID) {
self.guid = guid
}
var description: String {
return "No such record: \(guid)."
}
}
func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Maybe<T>> {
if let err = err {
log.debug("\(op) failed: \(err.localizedDescription)")
return deferMaybe(DatabaseError(err: err))
}
return deferMaybe(val)
}
func failOrSucceed(err: NSError?, op: String) -> Success {
return failOrSucceed(err, op: op, val: ())
}
private var ignoredSchemes = ["about"]
public func isIgnoredURL(url: NSURL) -> Bool {
let scheme = url.scheme
if let _ = ignoredSchemes.indexOf(scheme) {
return true
}
if url.host == "localhost" {
return true
}
return false
}
public func isIgnoredURL(url: String) -> Bool {
if let url = NSURL(string: url) {
return isIgnoredURL(url)
}
return false
}
/*
// Here's the Swift equivalent of the below.
func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double {
let ageMicroseconds = (now - then)
let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion.
let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225)
return Double(visitCount) * max(1.0, f)
}
*/
// The constants in these functions were arrived at by utterly unscientific experimentation.
func getRemoteFrecencySQL() -> String {
let visitCountExpression = "remoteVisitCount"
let now = NSDate.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))"
}
func getLocalFrecencySQL() -> String {
let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))"
let now = NSDate.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))"
}
extension SDRow {
func getTimestamp(column: String) -> Timestamp? {
return (self[column] as? NSNumber)?.unsignedLongLongValue
}
func getBoolean(column: String) -> Bool {
if let val = self[column] as? Int {
return val != 0
}
return false
}
}
/**
* The sqlite-backed implementation of the history protocol.
*/
public class SQLiteHistory {
let db: BrowserDB
let favicons: FaviconsTable<Favicon>
let prefs: Prefs
required public init?(db: BrowserDB, prefs: Prefs) {
self.db = db
self.favicons = FaviconsTable<Favicon>()
self.prefs = prefs
// BrowserTable exists only to perform create/update etc. operations -- it's not
// a queryable thing that needs to stick around.
if !db.createOrUpdate(BrowserTable()) {
return nil
}
}
}
extension SQLiteHistory: BrowserHistory {
public func removeSiteFromTopSites(site: Site) -> Success {
if let host = site.url.asURL?.normalizedHost() {
return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])])
}
return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)"))
}
public func removeHistoryForURL(url: String) -> Success {
let visitArgs: Args = [url]
let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)"
let markArgs: Args = [NSDate.nowNumber(), url]
let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?"
return db.run([(deleteVisits, visitArgs),
(markDeleted, markArgs),
favicons.getCleanupCommands()])
}
// Note: clearing history isn't really a sane concept in the presence of Sync.
// This method should be split to do something else.
// Bug 1162778.
public func clearHistory() -> Success {
return self.db.run([
("DELETE FROM \(TableVisits)", nil),
("DELETE FROM \(TableHistory)", nil),
("DELETE FROM \(TableDomains)", nil),
self.favicons.getCleanupCommands(),
])
// We've probably deleted a lot of stuff. Vacuum now to recover the space.
>>> effect(self.db.vacuum)
}
func recordVisitedSite(site: Site) -> Success {
var error: NSError? = nil
// Don't store visits to sites with about: protocols
if isIgnoredURL(site.url) {
return deferMaybe(IgnoredSiteError())
}
db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in
let now = NSDate.nowNumber()
let i = self.updateSite(site, atTime: now, withConnection: conn)
if i > 0 {
return i
}
// Insert instead.
return self.insertSite(site, atTime: now, withConnection: conn)
}
return failOrSucceed(error, op: "Record site")
}
func updateSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int {
// We know we're adding a new visit, so we'll need to upload this record.
// If we ever switch to per-visit change flags, this should turn into a CASE statement like
// CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END
// so that we don't flag this as changed unless the title changed.
//
// Note that we will never match against a deleted item, because deleted items have no URL,
// so we don't need to unset is_deleted here.
if let host = site.url.asURL?.normalizedHost() {
let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?"
let updateArgs: Args? = [site.title, time, host, site.url]
if Logger.logPII {
log.debug("Setting title to \(site.title) for URL \(site.url)")
}
let error = conn.executeChange(update, withArgs: updateArgs)
if error != nil {
log.warning("Update failed with \(error?.localizedDescription)")
return 0
}
return conn.numberOfRowsModified
}
return 0
}
private func insertSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int {
if let host = site.url.asURL?.normalizedHost() {
if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) {
log.warning("Domain insertion failed with \(error.localizedDescription)")
return 0
}
let insert = "INSERT INTO \(TableHistory) " +
"(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?"
let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host]
if let error = conn.executeChange(insert, withArgs: insertArgs) {
log.warning("Site insertion failed with \(error.localizedDescription)")
return 0
}
return 1
}
if Logger.logPII {
log.warning("Invalid URL \(site.url). Not stored in history.")
}
return 0
}
// TODO: thread siteID into this to avoid the need to do the lookup.
func addLocalVisitForExistingSite(visit: SiteVisit) -> Success {
var error: NSError? = nil
db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in
// INSERT OR IGNORE because we *might* have a clock error that causes a timestamp
// collision with an existing visit, and it would really suck to error out for that reason.
let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" +
"(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)"
let realDate = NSNumber(unsignedLongLong: visit.date)
let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue]
error = conn.executeChange(insert, withArgs: insertArgs)
if error != nil {
log.warning("Visit insertion failed with \(err?.localizedDescription)")
return 0
}
return 1
}
return failOrSucceed(error, op: "Record visit")
}
public func addLocalVisit(visit: SiteVisit) -> Success {
return recordVisitedSite(visit.site)
>>> { self.addLocalVisitForExistingSite(visit) }
}
public func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.getSitesByFrecencyWithLimit(limit, includeIcon: true)
}
public func getSitesByFrecencyWithLimit(limit: Int, includeIcon: Bool) -> Deferred<Maybe<Cursor<Site>>> {
// Exclude redirect domains. Bug 1194852.
let (whereData, groupBy) = self.topSiteClauses()
return self.getFilteredSitesByFrecencyWithLimit(limit, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon)
}
public func getTopSitesWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
let topSitesQuery = "SELECT * FROM \(TableCachedTopSites) ORDER BY frecencies DESC LIMIT (?)"
let factory = SQLiteHistory.iconHistoryColumnFactory
return self.db.runQuery(topSitesQuery, args: [limit], factory: factory)
}
public func setTopSitesNeedsInvalidation() {
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
public func updateTopSitesCacheIfInvalidated() -> Deferred<Maybe<Bool>> {
if prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false {
return deferMaybe(false)
}
return refreshTopSitesCache() >>> always(true)
}
public func setTopSitesCacheSize(size: Int32) {
let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0
if oldValue != size {
prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize)
setTopSitesNeedsInvalidation()
}
}
public func refreshTopSitesCache() -> Success {
let cacheSize = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0)
return self.clearTopSitesCache()
>>> { self.updateTopSitesCacheWithLimit(cacheSize) }
}
private func updateTopSitesCacheWithLimit(limit : Int) -> Success {
let (whereData, groupBy) = self.topSiteClauses()
let (query, args) = self.filteredSitesByFrecencyQueryWithLimit(limit, groupClause: groupBy, whereData: whereData)
let insertQuery = "INSERT INTO \(TableCachedTopSites) \(query)"
return self.clearTopSitesCache() >>> {
self.db.run(insertQuery, withArgs: args) >>> {
self.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
return succeed()
}
}
}
public func clearTopSitesCache() -> Success {
let deleteQuery = "DELETE FROM \(TableCachedTopSites)"
return self.db.run(deleteQuery, withArgs: nil) >>> {
self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid)
return succeed()
}
}
public func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByFrecencyWithLimit(limit, whereURLContains: filter)
}
public func getSitesByLastVisit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true)
}
private class func basicHistoryColumnFactory(row: SDRow) -> Site {
let id = row["historyID"] as! Int
let url = row["url"] as! String
let title = row["title"] as! String
let guid = row["guid"] as! String
let site = Site(url: url, title: title)
site.guid = guid
site.id = id
// Find the most recent visit, regardless of which column it might be in.
let local = row.getTimestamp("localVisitDate") ?? 0
let remote = row.getTimestamp("remoteVisitDate") ?? 0
let either = row.getTimestamp("visitDate") ?? 0
let latest = max(local, remote, either)
if latest > 0 {
site.latestVisit = Visit(date: latest, type: VisitType.Unknown)
}
return site
}
private class func iconColumnFactory(row: SDRow) -> Favicon? {
if let iconType = row["iconType"] as? Int,
let iconURL = row["iconURL"] as? String,
let iconDate = row["iconDate"] as? Double,
let _ = row["iconID"] as? Int {
let date = NSDate(timeIntervalSince1970: iconDate)
return Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!)
}
return nil
}
private class func iconHistoryColumnFactory(row: SDRow) -> Site {
let site = basicHistoryColumnFactory(row)
site.icon = iconColumnFactory(row)
return site
}
private func topSiteClauses() -> (String, String) {
let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') "
let groupBy = "GROUP BY domain_id "
return (whereData, groupBy)
}
private func getFilteredSitesByVisitDateWithLimit(limit: Int,
whereURLContains filter: String? = nil,
includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> {
let args: Args?
let whereClause: String
if let filter = filter {
args = ["%\(filter)%", "%\(filter)%"]
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = "WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) " +
"AND (\(TableHistory).is_deleted = 0)"
} else {
args = []
whereClause = "WHERE (\(TableHistory).is_deleted = 0)"
}
let ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain, " +
"COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate, " +
"COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate, " +
"COALESCE(count(\(TableVisits).is_local), 0) AS visitCount " +
"FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " +
whereClause + " GROUP BY historyID"
let historySQL =
"SELECT historyID, url, title, guid, domain_id, domain, visitCount, " +
"max(localVisitDate) AS localVisitDate, " +
"max(remoteVisitDate) AS remoteVisitDate " +
"FROM (" + ungroupedSQL + ") " +
"WHERE (visitCount > 0) " + // Eliminate dead rows from coalescing.
"GROUP BY historyID " +
"ORDER BY max(localVisitDate, remoteVisitDate) DESC " +
"LIMIT \(limit) "
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = "SELECT " +
"historyID, url, title, guid, domain_id, domain, " +
"localVisitDate, remoteVisitDate, visitCount, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM (\(historySQL)) LEFT OUTER JOIN " +
"view_history_id_favicon ON historyID = view_history_id_favicon.id"
let factory = SQLiteHistory.iconHistoryColumnFactory
return db.runQuery(sql, args: args, factory: factory)
}
let factory = SQLiteHistory.basicHistoryColumnFactory
return db.runQuery(historySQL, args: args, factory: factory)
}
private func getFilteredSitesByFrecencyWithLimit(limit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> {
let factory: (SDRow) -> Site
if includeIcon {
factory = SQLiteHistory.iconHistoryColumnFactory
} else {
factory = SQLiteHistory.basicHistoryColumnFactory
}
let (query, args) = filteredSitesByFrecencyQueryWithLimit(limit,
whereURLContains: filter,
groupClause: groupClause,
whereData: whereData,
includeIcon: includeIcon
)
return db.runQuery(query, args: args, factory: factory)
}
private func filteredSitesByFrecencyQueryWithLimit(limit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> (String, Args?) {
let localFrecencySQL = getLocalFrecencySQL()
let remoteFrecencySQL = getRemoteFrecencySQL()
let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24
let sixMonthsAgo = NSDate.nowMicroseconds() - sixMonthsInMicroseconds
let args: Args?
let whereClause: String
let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))"
if let filter = filter {
args = ["%\(filter)%", "%\(filter)%"]
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = " WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) \(whereFragment)"
} else {
args = []
whereClause = " WHERE (\(TableHistory).is_deleted = 0) \(whereFragment)"
}
// Innermost: grab history items and basic visit/domain metadata.
let ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain" +
", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" +
", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" +
", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" +
", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" +
" FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " +
whereClause + " GROUP BY historyID"
// Next: limit to only those that have been visited at all within the last six months.
// (Don't do that in the innermost: we want to get the full count, even if some visits are older.)
// Discard all but the 1000 most frecent.
// Compute and return the frecency for all 1000 URLs.
let frecenciedSQL =
"SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" +
" FROM (" + ungroupedSQL + ")" +
" WHERE (" +
"((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing.
"((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items.
") ORDER BY frecency DESC" +
" LIMIT 1000" // Don't even look at a huge set. This avoids work.
// Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit.
let historySQL =
"SELECT historyID, url, title, guid, domain_id, domain" +
", max(localVisitDate) AS localVisitDate" +
", max(remoteVisitDate) AS remoteVisitDate" +
", sum(localVisitCount) AS localVisitCount" +
", sum(remoteVisitCount) AS remoteVisitCount" +
", sum(frecency) AS frecencies" +
" FROM (" + frecenciedSQL + ") " +
groupClause + " " +
"ORDER BY frecencies DESC " +
"LIMIT \(limit) "
// Finally: join this small list to the favicon data.
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = "SELECT" +
" historyID, url, title, guid, domain_id, domain" +
", localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount" +
", iconID, iconURL, iconDate, iconType, iconWidth, frecencies" +
" FROM (\(historySQL)) LEFT OUTER JOIN " +
"view_history_id_favicon ON historyID = view_history_id_favicon.id"
return (sql, args)
}
return (historySQL, args)
}
}
extension SQLiteHistory: Favicons {
// These two getter functions are only exposed for testing purposes (and aren't part of the public interface).
func getFaviconsForURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> {
let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " +
"\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " +
"\(TableHistory).id = siteID AND \(TableHistory).url = ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
func getFaviconsForBookmarkedURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> {
let sql = "SELECT \(TableFavicons).id AS id, \(TableFavicons).url AS url, \(TableFavicons).date AS date, \(TableFavicons).type AS type, \(TableFavicons).width AS width FROM \(TableFavicons), \(TableBookmarks) WHERE \(TableBookmarks).faviconID = \(TableFavicons).id AND \(TableBookmarks).url IS ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
public func clearAllFavicons() -> Success {
var err: NSError? = nil
db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil)
if err == nil {
err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil)
}
return 1
}
return failOrSucceed(err, op: "Clear favicons")
}
public func addFavicon(icon: Favicon) -> Deferred<Maybe<Int>> {
var err: NSError?
let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
return id ?? 0
}
if err == nil {
return deferMaybe(res)
}
return deferMaybe(DatabaseError(err: err))
}
/**
* This method assumes that the site has already been recorded
* in the history table.
*/
public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Maybe<Int>> {
if Logger.logPII {
log.verbose("Adding favicon \(icon.url) for site \(site.url).")
}
func doChange(query: String, args: Args?) -> Deferred<Maybe<Int>> {
var err: NSError?
let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
// Now set up the mapping.
err = conn.executeChange(query, withArgs: args)
if let err = err {
log.error("Got error adding icon: \(err).")
return 0
}
// Try to update the favicon ID column in the bookmarks table as well for this favicon
// if this site has been bookmarked
if let id = id {
conn.executeChange("UPDATE \(TableBookmarks) SET faviconID = ? WHERE url = ?", withArgs: [id, site.url])
}
return id ?? 0
}
if res == 0 {
return deferMaybe(DatabaseError(err: err))
}
return deferMaybe(icon.id!)
}
let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)"
let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)"
let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES "
if let iconID = icon.id {
// Easy!
if let siteID = site.id {
// So easy!
let args: Args? = [siteID, iconID]
return doChange("\(insertOrIgnore) (?, ?)", args: args)
}
// Nearly easy.
let args: Args? = [site.url, iconID]
return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args: args)
}
// Sigh.
if let siteID = site.id {
let args: Args? = [siteID, icon.url]
return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args: args)
}
// The worst.
let args: Args? = [site.url, icon.url]
return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args: args)
}
}
extension SQLiteHistory: SyncableHistory {
/**
* TODO:
* When we replace an existing row, we want to create a deleted row with the old
* GUID and switch the new one in -- if the old record has escaped to a Sync server,
* we want to delete it so that we don't have two records with the same URL on the server.
* We will know if it's been uploaded because it'll have a server_modified time.
*/
public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success {
let args: Args = [guid, url, guid]
// The additional IS NOT is to ensure that we don't do a write for no reason.
return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args)
}
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
let args: Args = [guid]
// This relies on ON DELETE CASCADE to remove visits.
return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args)
}
// Fails on non-existence.
private func getSiteIDForGUID(guid: GUID) -> Deferred<Maybe<Int>> {
let args: Args = [guid]
let query = "SELECT id FROM history WHERE guid = ?"
let factory: SDRow -> Int = { return $0["id"] as! Int }
return db.runQuery(query, args: args, factory: factory)
>>== { cursor in
if cursor.count == 0 {
return deferMaybe(NoSuchRecordError(guid: guid))
}
return deferMaybe(cursor[0]!)
}
}
public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success {
return self.getSiteIDForGUID(guid)
>>== { (siteID: Int) -> Success in
let visitArgs = visits.map { (visit: Visit) -> Args in
let realDate = NSNumber(unsignedLongLong: visit.date)
let isLocal = 0
let args: Args = [siteID, realDate, visit.type.rawValue, isLocal]
return args
}
// Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness
// constraint on `visits`: we allow only one row for (siteID, date, type), so if a
// local visit already exists, this silently keeps it. End result? Any new remote
// visits are added with only one query, keeping any existing rows.
return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs)
}
}
private struct HistoryMetadata {
let id: Int
let serverModified: Timestamp?
let localModified: Timestamp?
let isDeleted: Bool
let shouldUpload: Bool
let title: String
}
private func metadataForGUID(guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> {
let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?"
let args: Args = [guid]
let factory = { (row: SDRow) -> HistoryMetadata in
return HistoryMetadata(
id: row["id"] as! Int,
serverModified: row.getTimestamp("server_modified"),
localModified: row.getTimestamp("local_modified"),
isDeleted: row.getBoolean("is_deleted"),
shouldUpload: row.getBoolean("should_upload"),
title: row["title"] as! String
)
}
return db.runQuery(select, args: args, factory: factory) >>== { cursor in
return deferMaybe(cursor[0])
}
}
public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// One of these things will be true here.
// 0. The item is new.
// (a) We have a local place with the same URL but a different GUID.
// (b) We have never visited this place locally.
// In either case, reconcile and proceed.
// 1. The remote place is not modified when compared to our mirror of it. This
// can occur when we redownload after a partial failure.
// (a) And it's not modified locally, either. Nothing to do. Ideally we
// will short-circuit so we don't need to update visits. (TODO)
// (b) It's modified locally. Don't overwrite anything; let the upload happen.
// 2. The remote place is modified (either title or visits).
// (a) And it's not locally modified. Update the local entry.
// (b) And it's locally modified. Preserve the title of whichever was modified last.
// N.B., this is the only instance where we compare two timestamps to see
// which one wins.
// We use this throughout.
let serverModified = NSNumber(unsignedLongLong: modified)
// Check to see if our modified time is unchanged, if the record exists locally, etc.
let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in
if let metadata = metadata {
// The item exists locally (perhaps originally with a different GUID).
if metadata.serverModified == modified {
log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.")
return deferMaybe(place.guid)
}
// Otherwise, the server record must have changed since we last saw it.
if metadata.shouldUpload {
// Uh oh, it changed locally.
// This might well just be a visit change, but we can't tell. Usually this conflict is harmless.
log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!")
if metadata.localModified > modified {
log.debug("Local changes overriding remote.")
// Update server modified time only. (Though it'll be overwritten again after a successful upload.)
let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?"
let args: Args = [serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
log.verbose("Remote changes overriding local.")
// Fall through.
}
// The record didn't change locally. Update it.
log.verbose("Updating local history item for guid \(place.guid).")
let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?"
let args: Args = [place.title, serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
// The record doesn't exist locally. Insert it.
log.verbose("Inserting remote history item for guid \(place.guid).")
if let host = place.url.asURL?.normalizedHost() {
if Logger.logPII {
log.debug("Inserting: \(place.url).")
}
let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)"
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?"
return self.db.run([
(insertDomain, [host]),
(insertHistory, [place.guid, place.url, place.title, serverModified, host])
]) >>> always(place.guid)
} else {
// This is a URL with no domain. Insert it directly.
if Logger.logPII {
log.debug("Inserting: \(place.url) with no domain.")
}
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"VALUES (?, ?, ?, ?, 0, 0, NULL)"
return self.db.run([
(insertHistory, [place.guid, place.url, place.title, serverModified])
]) >>> always(place.guid)
}
}
// Make sure that we only need to compare GUIDs by pre-merging on URL.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> { self.metadataForGUID(place.guid) >>== insertWithMetadata }
}
public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// Use the partial index on should_upload to make this nice and quick.
let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1"
let f: SDRow -> String = { $0["guid"] as! String }
return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) }
}
public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// What we want to do: find all items flagged for update, selecting some number of their
// visits alongside.
//
// A difficulty here: we don't want to fetch *all* visits, only some number of the most recent.
// (It's not enough to only get new ones, because the server record should contain more.)
//
// That's the greatest-N-per-group problem in SQL. Please read and understand the solution
// to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query!
//
// We can do this in a single query, rather than the N+1 that desktop takes.
// We then need to flatten the cursor. We do that by collecting
// places as a side-effect of the factory, producing visits as a result, and merging in memory.
let args: Args = [
20, // Maximum number of visits to retrieve.
]
// Exclude 'unknown' visits, because they're not syncable.
let filter = "history.should_upload = 1 AND v1.type IS NOT 0"
let sql =
"SELECT " +
"history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " +
"v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " +
"FROM " +
"visits AS v1 " +
"JOIN history ON history.id = v1.siteID AND \(filter) " +
"LEFT OUTER JOIN " +
"visits AS v2 " +
"ON v1.siteID = v2.siteID AND v1.date < v2.date " +
"GROUP BY v1.date " +
"HAVING COUNT(*) < ? " +
"ORDER BY v1.siteID, v1.date DESC"
var places = [Int: Place]()
var visits = [Int: [Visit]]()
// Add a place to the accumulator, prepare to accumulate visits, return the ID.
let ensurePlace: SDRow -> Int = { row in
let id = row["siteID"] as! Int
if places[id] == nil {
let guid = row["guid"] as! String
let url = row["url"] as! String
let title = row["title"] as! String
places[id] = Place(guid: guid, url: url, title: title)
visits[id] = Array()
}
return id
}
// Store the place and the visit.
let factory: SDRow -> Int = { row in
let date = row.getTimestamp("visitDate")!
let type = VisitType(rawValue: row["visitType"] as! Int)!
let visit = Visit(date: date, type: type)
let id = ensurePlace(row)
visits[id]?.append(visit)
return id
}
return db.runQuery(sql, args: args, factory: factory)
>>== { c in
// Consume every row, with the side effect of populating the places
// and visit accumulators.
var ids = Set<Int>()
for row in c {
// Collect every ID first, so that we're guaranteed to have
// fully populated the visit lists, and we don't have to
// worry about only collecting each place once.
ids.insert(row!)
}
// Now we're done with the cursor. Close it.
c.close()
// Now collect the return value.
return deferMaybe(ids.map { return (places[$0]!, visits[$0]!) } )
}
}
public func markAsDeleted(guids: [GUID]) -> Success {
// TODO: support longer GUID lists.
assert(guids.count < BrowserDB.MaxVariableNumber)
if guids.isEmpty {
return succeed()
}
log.debug("Wiping \(guids.count) deleted GUIDs.")
// We deliberately don't limit this to records marked as should_upload, just
// in case a coding error leaves records with is_deleted=1 but not flagged for
// upload -- this will catch those and throw them away.
let inClause = BrowserDB.varlist(guids.count)
let sql =
"DELETE FROM \(TableHistory) WHERE " +
"is_deleted = 1 AND guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run(sql, withArgs: args)
}
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO: support longer GUID lists.
assert(guids.count < 99)
if guids.isEmpty {
return deferMaybe(modified)
}
log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).")
let inClause = BrowserDB.varlist(guids.count)
let sql =
"UPDATE \(TableHistory) SET " +
"should_upload = 0, server_modified = \(modified) " +
"WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run(sql, withArgs: args) >>> always(modified)
}
public func doneApplyingRecordsAfterDownload() -> Success {
self.db.checkpoint()
return succeed()
}
public func doneUpdatingMetadataAfterUpload() -> Success {
self.db.checkpoint()
return succeed()
}
}
extension SQLiteHistory: ResettableSyncStorage {
// We don't drop deletions when we reset -- we might need to upload a deleted item
// that never made it to the server.
public func resetClient() -> Success {
let flag = "UPDATE \(TableHistory) SET should_upload = 1, server_modified = NULL"
return self.db.run(flag)
}
}
extension SQLiteHistory: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
log.info("Clearing history metadata and deleted items after account removal.")
let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1"
return self.db.run(discard) >>> self.resetClient
}
}
|
da181f490b3eaff417df6871a775982e
| 42.89666 | 304 | 0.586807 | false | false | false | false |
guoc/excerptor
|
refs/heads/master
|
Excerptor/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// excerptor
//
// Created by Chen Guo on 17/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
import Cocoa
import PreferencePanes
class AppDelegate: NSObject, NSApplicationDelegate {
lazy var preferencesWindowController: PreferencesWindowController = PreferencesWindowController(windowNibName: NSNib.Name(rawValue: "PreferencesWindow"))
func applicationWillFinishLaunching(_ notification: Notification) {
preferencesWindowController.showPreferencesOnlyOnceIfNecessaryAfterDelay(0.3)
let servicesProvider = ServicesProvider()
NSApplication.shared.servicesProvider = servicesProvider
let appleEventManager: NSAppleEventManager = NSAppleEventManager.shared()
appleEventManager.setEventHandler(self, andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func applicationDidBecomeActive(_ notification: Notification) {
preferencesWindowController.showPreferencesOnlyOnceIfNecessaryAfterDelay(0.3)
}
@objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent: NSAppleEventDescriptor) {
PreferencesWindowController.needShowPreferences = false
if let theURLString = event.forKeyword(AEKeyword(keyDirectObject))?.stringValue {
if let link = AnnotationLink(linkString: theURLString) ?? SelectionLink(linkString: theURLString) {
PasteboardHelper.writeExcerptorPasteboardWithLocation(link.location)
let applicationName: String
switch Preferences.sharedPreferences.appForOpenPDF {
case .preview:
applicationName = "Preview.app"
case .skim:
applicationName = "Skim.app"
}
NSWorkspace().openFile(link.getFilePath(), withApplication: applicationName, andDeactivate: true)
}
}
}
}
|
9752a6dee3772b831b7717d36abe2aea
| 41.574468 | 193 | 0.715642 | false | false | false | false |
loudnate/Loop
|
refs/heads/master
|
LoopCore/LoopCompletionFreshness.swift
|
apache-2.0
|
1
|
//
// LoopCompletionFreshness.swift
// Loop
//
// Created by Pete Schwamb on 1/17/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import Foundation
public enum LoopCompletionFreshness {
case fresh
case aging
case stale
case unknown
public var maxAge: TimeInterval? {
switch self {
case .fresh:
return TimeInterval(minutes: 6)
case .aging:
return TimeInterval(minutes: 16)
case .stale:
return TimeInterval(hours: 12)
case .unknown:
return nil
}
}
public init(age: TimeInterval?) {
guard let age = age else {
self = .unknown
return
}
switch age {
case let t where t <= LoopCompletionFreshness.fresh.maxAge!:
self = .fresh
case let t where t <= LoopCompletionFreshness.aging.maxAge!:
self = .aging
case let t where t <= LoopCompletionFreshness.stale.maxAge!:
self = .stale
default:
self = .unknown
}
}
public init(lastCompletion: Date?, at date: Date = Date()) {
guard let lastCompletion = lastCompletion else {
self = .unknown
return
}
self = LoopCompletionFreshness(age: date.timeIntervalSince(lastCompletion))
}
}
|
d42d790ae01132fca1571fc955d88090
| 23.403509 | 83 | 0.556434 | false | false | false | false |
PiXeL16/PasswordTextField
|
refs/heads/master
|
PasswordTextFieldTests/PasswordTextFieldSpecs.swift
|
mit
|
1
|
//
// PasswordTextFieldSpecs.swift
// PasswordTextField
//
// Created by Chris Jimenez on 2/11/16.
// Copyright © 2016 Chris Jimenez. All rights reserved.
//
import Foundation
import Nimble
import Quick
import PasswordTextField
//Specs for the delayer class
class PasswordTextFieldSpecs: QuickSpec {
override func spec() {
let passwordTextField = PasswordTextField()
it("initial values are correct"){
let passwordString = "1234Abcd8988!"
passwordTextField.text = passwordString
passwordTextField.imageTintColor = UIColor.red
passwordTextField.setSecureMode(false)
expect(passwordTextField.isValid()).to(beTrue())
expect(passwordTextField.errorMessage()).toNot(beNil())
expect(passwordTextField.showButtonWhile).to(equal(PasswordTextField.ShowButtonWhile.Editing))
expect(passwordTextField.imageTintColor).to(equal(UIColor.red))
expect(passwordTextField.secureTextButton.tintColor).to(equal(UIColor.red))
expect(passwordTextField.isSecureTextEntry).to(beFalse())
}
it("values are correct after button pressed"){
let passwordString = "love"
passwordTextField.text = passwordString
passwordTextField.secureTextButton.buttonTouch()
expect(passwordTextField.isValid()).to(beFalse())
expect(passwordTextField.errorMessage()).toNot(beNil())
expect(passwordTextField.secureTextButton.isSecure).to(beFalse())
expect(passwordTextField.isSecureTextEntry).to(beFalse())
}
it("validates with custom validator"){
let passwordString = "LOVE"
passwordTextField.text = passwordString
let validationRule = RegexRule(regex:"^[A-Z ]+$", errorMessage: "test")
passwordTextField.validationRule = validationRule
expect(passwordTextField.isValid()).to(beTrue())
expect(passwordTextField.errorMessage()).to(equal("test"))
}
}
}
|
f07268ec86315f00a4f626908f6a39d0
| 29.571429 | 106 | 0.584962 | false | false | false | false |
BrandonMA/SwifterUI
|
refs/heads/master
|
SwifterUI/SwifterUI/UILibrary/Assets/SFColors.swift
|
mit
|
1
|
//
// SFAssets.swift
// SwifterUI
//
// Created by Brandon Maldonado on 25/12/17.
// Copyright © 2017 . All rights reserved.
//
import UIKit
/**
Main colors hand picked to work well on iOS
*/
public struct SFColors {
// MARK: - Static Properties
/**
HexCode: FFFFFF
*/
static public let white: UIColor = UIColor(hex: "FFFFFF")
/**
HexCode: 000000
*/
static public let black: UIColor = UIColor(hex: "000000")
/**
HexCode: E2E2E4
*/
static public let separatorWhite: UIColor = UIColor(hex: "E2E2E4")
/**
HexCode: 2B2B2D
*/
static public let separatorBlack: UIColor = UIColor(hex: "2B2B2D")
/**
HexCode: F7F7F7
*/
static public let alternativeWhite: UIColor = UIColor(hex: "F7F7F7")
/**
HexCode: 1A1A1A
*/
static public let alternativeBlack: UIColor = UIColor(hex: "0D0D0D")
/**
HexCode: E8E8E8
*/
static public let contrastWhite: UIColor = UIColor(hex: "E8E8E8")
/**
HexCode: 0F0F0F
*/
static public let contrastBlack: UIColor = UIColor(hex: "171717")
/**
HexCode: F0F0F0
*/
static public let gray: UIColor = UIColor(hex: "F0F0F0")
/**
HexCode: "CCCCCC"
*/
static public let lightGray: UIColor = UIColor(hex: "808080")
/**
HexCode: 999999
*/
static public let darkGray: UIColor = UIColor(hex: "B3B3B3")
/**
HexCode: FF941A
*/
static public let orange: UIColor = UIColor(hex: "FF941A")
/**
HexCode: 0088FF
*/
static public let blue: UIColor = UIColor(hex: "0088FF")
}
|
e7c13ee3fe9ce3c5039aafc7bcd111e4
| 19.313253 | 72 | 0.569988 | false | false | false | false |
balazs630/Bob-Cat-Runner
|
refs/heads/develop
|
BobRunner/Model and state/Stage.swift
|
apache-2.0
|
1
|
//
// Stage.swift
// BobRunner
//
// Created by Horváth Balázs on 2017. 10. 06..
// Copyright © 2017. Horváth Balázs. All rights reserved.
//
import SpriteKit
struct Stage {
static var maxCount: Int {
var stageNumber = 0
while SKScene(fileNamed: "Stage\(stageNumber + 1)") != nil {
stageNumber += 1
}
return stageNumber
}
static var current: Int {
get {
return UserDefaults.standard.integer(forKey: UserDefaults.Key.actualStage)
}
set(newStage) {
UserDefaults.standard.set(newStage, forKey: UserDefaults.Key.actualStage)
UserDefaults.standard.synchronize()
}
}
static var name: String {
return "Stage\(current)"
}
static var clouds: [String] {
var currentClouds = [String]()
(1...Constant.clouds[current]!).forEach { index in
currentClouds.append("cloud\(index)")
}
return currentClouds
}
static var rainIntensity: Double {
return Constant.rainIntensity[current]!
}
static func isAllCompleted() -> Bool {
return Stage.current == Stage.maxCount
}
}
|
09b963b1b333d81388e963652134f088
| 22.76 | 86 | 0.590909 | false | false | false | false |
ThePacielloGroup/CCA-OSX
|
refs/heads/master
|
Colour Contrast Analyser/CCAColourBrightnessDifferenceController.swift
|
gpl-3.0
|
1
|
//
// ResultsController.swift
// Colour Contrast Analyser
//
// Created by Cédric Trévisan on 27/01/2015.
// Copyright (c) 2015 Cédric Trévisan. All rights reserved.
//
import Cocoa
class CCAColourBrightnessDifferenceController: NSViewController {
@IBOutlet weak var colourDifferenceText: NSTextField!
@IBOutlet weak var brightnessDifferenceText: NSTextField!
@IBOutlet weak var colourBrightnessSample: CCAColourBrightnessDifferenceField!
@IBOutlet weak var menuShowRGBSliders: NSMenuItem!
var fColor: NSColor = NSColor(red: 0, green: 0, blue: 0, alpha: 1.0)
var bColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1.0)
var colourDifferenceValue:Int?
var brightnessDifferenceValue:Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.updateResults()
NotificationCenter.default.addObserver(self, selector: #selector(CCAColourBrightnessDifferenceController.updateForeground(_:)), name: NSNotification.Name(rawValue: "ForegroundColorChangedNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(CCAColourBrightnessDifferenceController.updateBackground(_:)), name: NSNotification.Name(rawValue: "BackgroundColorChangedNotification"), object: nil)
}
func updateResults() {
brightnessDifferenceValue = ColourBrightnessDifference.getBrightnessDifference(self.fColor, bc:self.bColor)
colourDifferenceValue = ColourBrightnessDifference.getColourDifference(self.fColor, bc:self.bColor)
colourDifferenceText.stringValue = String(format: NSLocalizedString("colour_diff", comment:"Colour difference: %d (minimum 500)"), colourDifferenceValue!)
brightnessDifferenceText.stringValue = String(format: NSLocalizedString("brightness_diff", comment:"Brightness difference: %d (minimum 125)"), brightnessDifferenceValue!)
colourBrightnessSample.validateColourBrightnessDifference(brightnessDifferenceValue!, colour: colourDifferenceValue!)
}
@objc func updateForeground(_ notification: Notification) {
self.fColor = notification.userInfo!["colorWithOpacity"] as! NSColor
self.updateResults()
var color:NSColor = self.fColor
// Fix for #3 : use almost black color
if (color.isBlack()) {
color = NSColor(red: 0.000001, green: 0, blue: 0, alpha: 1.0)
}
colourBrightnessSample.textColor = color
}
@objc func updateBackground(_ notification: Notification) {
self.bColor = notification.userInfo!["color"] as! NSColor
self.updateResults()
colourBrightnessSample.backgroundColor = self.bColor
}
}
|
17663438301bbd0b705e51a7e9755437
| 49.314815 | 223 | 0.729481 | false | false | false | false |
keith/radars
|
refs/heads/main
|
LazyCollectionEvaluatedMultipleTimes/LazyCollectionEvaluatedMultipleTimes.swift
|
mit
|
1
|
func g(string: String) -> String {
let result = string == "b" ? "hi" : ""
print("Called with '\(string)' returning '\(result)'")
return result
}
public extension CollectionType {
public func find(includedElement: Generator.Element -> Bool) -> Generator.Element? {
if let index = self.indexOf(includedElement) {
return self[index]
}
return nil
}
}
func f(fields: [String]) {
_ = fields.lazy
.map { g($0) }
.find { !$0.isEmpty }
}
f(["a", "b", "c"])
|
df1b469ab205fe4638ddeb9fe5f10bea
| 21.913043 | 88 | 0.552182 | false | false | false | false |
jngd/advanced-ios10-training
|
refs/heads/master
|
T9E01/T9E01/RecipeListViewController.swift
|
apache-2.0
|
1
|
/**
* Copyright (c) 2016 Juan Garcia
*
* 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
class RecipeListViewController: UIViewController {
var cells: NSArray?
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.bundlePath as NSString
let finalPath = path.appendingPathComponent("recetas.plist")
cells = NSArray(contentsOfFile: finalPath)
}
}
extension RecipeListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (cells?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Recipe", for: indexPath) as! RecipeListCell
let recipeName = ((self.cells![indexPath.row] as AnyObject?)!.object(forKey: "nombre") as? String)!
let recipeImageName = ((self.cells![indexPath.row] as AnyObject?)!.object(forKey: "imagen") as? String)!
let recipeImage: UIImage = UIImage(named: recipeImageName)!
let recipeDescription = ((self.cells![indexPath.row] as AnyObject?)!.object(forKey: "descripcion") as? String)!
cell.recipeName?.text = recipeName
cell.recipeImage?.image = recipeImage
cell.recipeDescription = recipeDescription
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "ViewRecipeDetail" else {
fatalError("Segue identifier not found")
}
guard let cell = sender as! RecipeListCell? else {
fatalError("Recipe list cell cannot be cast")
}
guard let recipeViewController = segue.destination as? RecipeViewController else {
return
}
recipeViewController.recipeImageURL = cell.recipeImage.image?.accessibilityIdentifier
recipeViewController.recipeNameText = cell.recipeName.text
recipeViewController.recipeDescriptionText = cell.recipeDescription
}
}
extension RecipeListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
|
c94ea25776374a5cd6be3655847d84cd
| 35.452381 | 113 | 0.767146 | false | false | false | false |
kpham13/SkaterBrad
|
refs/heads/master
|
SkaterBrad/NewGameMenu.swift
|
bsd-2-clause
|
1
|
//
// NewGrameNode.swift
// SkaterBrad
//
// Copyright (c) 2014 Mother Functions. All rights reserved.
//
import UIKit
import SpriteKit
enum SoundButtonSwitch {
case On
case Off
}
class NewGameNode: SKNode {
var titleLabel: SKLabelNode!
var directionLabel: SKLabelNode!
var playButton: SKSpriteNode!
var soundOnButton: SKSpriteNode!
var soundOffButton: SKSpriteNode!
var gameCenterButton: SKSpriteNode! //xx
init(scene: SKScene, playSound: Bool) {
super.init()
self.titleLabel = SKLabelNode(text: "Skater Brad")
self.titleLabel.fontName = "SkaterDudes"
self.titleLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.8)
self.titleLabel.zPosition = 5
self.directionLabel = SKLabelNode(text: "Swipe up to jump")
self.directionLabel.fontName = "SkaterDudes"
self.directionLabel.zPosition = 5
// New Game Button
self.playButton = SKSpriteNode(imageNamed: "playNow.png")
self.playButton.name = "PlayNow"
self.playButton.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMidY(scene.frame))
self.playButton.zPosition = 10
self.playButton.xScale = 0.6
self.playButton.yScale = 0.6
self.addChild(self.playButton)
// Sound On Button
self.soundOnButton = SKSpriteNode(imageNamed: "SoundOn")
self.soundOnButton.position = CGPoint(x: CGRectGetMaxX(scene.frame) - self.soundOnButton.frame.width / 2, y: CGRectGetMaxY(scene.frame) - self.soundOnButton.frame.height / 2)
self.soundOnButton?.name = "SoundOn"
self.soundOnButton.xScale = 0.40
self.soundOnButton.yScale = 0.40
self.soundOnButton.zPosition = 2.0
// Sound Off Button
self.soundOffButton = SKSpriteNode(imageNamed: "SoundOff")
self.soundOffButton.position = CGPoint(x: CGRectGetMaxX(scene.frame) - self.soundOffButton.frame.width, y: CGRectGetMaxY(scene.frame) - self.soundOffButton.frame.height / 2)
self.soundOffButton?.name = "SoundOff"
self.soundOffButton.xScale = 0.40
self.soundOffButton.yScale = 0.40
self.soundOffButton.zPosition = 2.0
if playSound == true {
self.addChild(self.soundOnButton)
} else {
self.addChild(self.soundOffButton)
}
// Game Center Button [KP] //15
self.gameCenterButton = SKSpriteNode(imageNamed: "GameCenter")
self.gameCenterButton?.name = "GameCenterButton"
self.gameCenterButton?.zPosition = 10
self.gameCenterButton.xScale = 0.8
self.gameCenterButton.yScale = 0.8
self.gameCenterButton?.anchorPoint = CGPointMake(0, 0)
if scene.frame.size.height == 568 {
self.titleLabel.fontSize = 40
self.directionLabel.fontSize = 18
self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.13)
self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.04), CGRectGetMaxY(scene.frame) * (-0.03))
} else if scene.frame.size.height == 667 {
self.titleLabel.fontSize = 45
self.directionLabel.fontSize = 20
self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.11)
self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.01), CGRectGetMaxY(scene.frame) * (-0.025))
} else if scene.frame.size.height == 736 {
println(scene.frame.size.height)
self.titleLabel.fontSize = 50
self.directionLabel.fontSize = 22
self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.11)
self.gameCenterButton.xScale = 1.0
self.gameCenterButton.yScale = 1.0
self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * 0.02, CGRectGetMaxY(scene.frame) * (-0.015))
} else {
self.titleLabel.fontSize = 40
self.titleLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.78)
self.directionLabel.fontSize = 18
self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.15)
self.gameCenterButton.xScale = 0.7
self.gameCenterButton.yScale = 0.7
self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.03), CGRectGetMaxY(scene.frame) * (-0.03))
}
self.addChild(self.titleLabel)
self.addChild(self.directionLabel)
self.addChild(self.gameCenterButton)
}
func turnSoundOnOff(switchButton : SoundButtonSwitch) {
if switchButton == SoundButtonSwitch.On {
println("SoundButtonSwitch.On")
self.soundOffButton.removeFromParent()
self.addChild(self.soundOnButton)
} else {
println("SoundButtonSwitch.Off")
self.soundOnButton.removeFromParent()
self.addChild(self.soundOffButton)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
57357672db4bd47c4d79b8e9f75c13f2
| 42.282258 | 182 | 0.651137 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/WordPressTest/ViewRelated/Post/Controllers/PostListViewControllerTests.swift
|
gpl-2.0
|
1
|
import UIKit
import XCTest
import Nimble
@testable import WordPress
class PostListViewControllerTests: XCTestCase {
private var context: NSManagedObjectContext!
override func setUp() {
context = TestContextManager().mainContext
super.setUp()
}
override func tearDown() {
context = nil
TestContextManager.overrideSharedInstance(nil)
super.tearDown()
}
func testShowsGhostableTableView() {
let blog = BlogBuilder(context).build()
let postListViewController = PostListViewController.controllerWithBlog(blog)
let _ = postListViewController.view
postListViewController.startGhost()
expect(postListViewController.ghostableTableView.isHidden).to(beFalse())
}
func testHidesGhostableTableView() {
let blog = BlogBuilder(context).build()
let postListViewController = PostListViewController.controllerWithBlog(blog)
let _ = postListViewController.view
postListViewController.stopGhost()
expect(postListViewController.ghostableTableView.isHidden).to(beTrue())
}
func testShowTenMockedItemsInGhostableTableView() {
let blog = BlogBuilder(context).build()
let postListViewController = PostListViewController.controllerWithBlog(blog)
let _ = postListViewController.view
postListViewController.startGhost()
expect(postListViewController.ghostableTableView.numberOfRows(inSection: 0)).to(equal(50))
}
func testItCanHandleNewPostUpdatesEvenIfTheGhostViewIsStillVisible() {
// This test simulates and proves that the app will no longer crash on these conditions:
//
// 1. The app is built using Xcode 11 and running on iOS 13.1
// 2. The user has no cached data on the device
// 3. The user navigates to the Post List → Drafts
// 4. The user taps on the plus (+) button which adds a post in the Drafts list
//
// Please see https://git.io/JeK3y for more information about this crash.
//
// This test fails when executed on 00c88b9b
// Given
let blog = BlogBuilder(context).build()
try! context.save()
let postListViewController = PostListViewController.controllerWithBlog(blog)
let _ = postListViewController.view
let draftsIndex = postListViewController.filterTabBar.items.firstIndex(where: { $0.title == i18n("Drafts") }) ?? 1
postListViewController.updateFilter(index: draftsIndex)
postListViewController.startGhost()
// When: Simulate a post being created
// Then: This should not cause a crash
expect {
_ = PostBuilder(self.context, blog: blog).with(status: .draft).build()
try! self.context.save()
}.notTo(raiseException())
}
}
|
0a861d4e757f5d41d8c67a06e8be4970
| 32.916667 | 122 | 0.679888 | false | true | false | false |
blkbrds/intern09_final_project_tung_bien
|
refs/heads/master
|
MyApp/Model/API/Core/ApiManager.swift
|
mit
|
1
|
//
// ApiManager.swift
// MyApp
//
// Created by DaoNV on 4/10/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
import Alamofire
typealias JSObject = [String: Any]
typealias JSArray = [JSObject]
typealias Completion = (Result<Any>) -> Void
let api = ApiManager()
final class ApiManager {
let session = Session()
var defaultHTTPHeaders: [String: String] {
var headers: [String: String] = [:]
headers["Content-Type"] = "application/json"
if let token = Session.shared.getToken() {
headers["Authorization"] = "Bearer \(token)"
}
return headers
}
}
|
8e155e95becd7404b366f58fdd8df990
| 20.225806 | 62 | 0.629179 | false | false | false | false |
babedev/Food-Swift
|
refs/heads/master
|
Food-Swift-iOS/FoodSwift/FoodSwift/PhotoConfirmViewController.swift
|
unlicense
|
1
|
//
// PhotoConfirmViewController.swift
// FoodSwift
//
// Created by NiM on 3/4/2560 BE.
// Copyright © 2560 tryswift. All rights reserved.
//
import UIKit
import MapKit
import SVProgressHUD
class PhotoConfirmViewController: UIViewController {
var image:UIImage?
var userID = "";
var location:CLLocationCoordinate2D?
var placeName = "";
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.imageView.image = self.image;
if let place = FoodLocation.defaultManager.currentPlace?.name {
self.placeName = place;
}
self.title = self.placeName;
var region = MKCoordinateRegion();
region.center = self.location ?? self.mapView.region.center;
var span = MKCoordinateSpan();
span.latitudeDelta = 0.0015;
span.longitudeDelta = 0.0015;
region.span = span;
self.mapView.setRegion(region, animated: true);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sendPhoto() {
if let selectedImage = self.image {
print("Start upload");
SVProgressHUD.show();
FoodPhoto.uploadImage(image: selectedImage, completion: { (url, error) in
SVProgressHUD.dismiss();
print("Finish upload");
if let photoURL = url {
print("Got url \(photoURL)");
FoodPhoto.addNewPost(
imageURL: photoURL,
location: self.location ?? CLLocationCoordinate2DMake(0.0, 0.0),
placeName: self.placeName,
userID: self.userID,
completion: { Void in
self.dismiss(animated: true, completion: nil);
}
);
} else {
print("Finish upload with error - \(error)");
}
})
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
9d7a6a8e6482e971ed1bc720e66b593c
| 29.604651 | 106 | 0.56269 | false | false | false | false |
ra1028/OwnKit
|
refs/heads/master
|
OwnKit/Util/Transition/PushBackTransitionAnimator.swift
|
mit
|
1
|
//
// PushBackTransitionAnimator.swift
// OwnKit
//
// Created by Ryo Aoyama on 1/13/16.
// Copyright © 2016 Ryo Aoyama. All rights reserved.
//
import UIKit
public final class PushBackTransitionAnimator: TransitionAnimator {
public var pushBackScale = 0.95.f
private let backgroundView: UIView = {
let v = UIView()
v.backgroundColor = UIColor.blackColor().alphaColor(0.7)
return v
}()
public init(pushBackScale: CGFloat = 0.95) {
super.init()
duration = 0.6
self.pushBackScale = pushBackScale
}
public override func animatePresentingTransition(transitionContext: UIViewControllerContextTransitioning, from: UIViewController?, to: UIViewController?) {
super.animatePresentingTransition(transitionContext, from: from, to: to)
guard let fromView = from?.view,
toView = to?.view,
containerView = transitionContext.containerView() else {
return
}
backgroundView.frame = containerView.bounds
containerView.addSubview(backgroundView)
containerView.addSubview(toView)
toView.layer.transform = .translation(x: toView.width)
UIView.animate(
duration,
springDamping: 1,
initialVelocity: 0,
animations: {
self.backgroundView.alpha = 0
self.backgroundView.alpha = 1
fromView.layer.transform = .scale(x: self.pushBackScale, y: self.pushBackScale)
toView.layer.transform = .identity
}, completion: { _ in
transitionContext.completeTransition(true)
}
)
}
public override func animateDismissingTransition(transitionContext: UIViewControllerContextTransitioning, from: UIViewController?, to: UIViewController?) {
super.animateDismissingTransition(transitionContext, from: from, to: to)
guard let fromView = from?.view,
toView = to?.view,
containerView = transitionContext.containerView()else {
return
}
containerView.insertSubview(toView, atIndex: 0)
UIView.animate(
duration,
springDamping: 1,
initialVelocity: 0,
animations: {
self.backgroundView.alpha = 1
self.backgroundView.alpha = 0
fromView.layer.transform = .translation(x: fromView.width)
toView.layer.transform = .identity
}, completion: { _ in
fromView.removeFromSuperview()
transitionContext.completeTransition(true)
}
)
}
}
|
a13d7822131f9f1c63ea82cd0274e556
| 33 | 159 | 0.597167 | false | false | false | false |
mownier/Umalahokan
|
refs/heads/master
|
Umalahokan/Source/Transition/MessageWriterTransitioning.swift
|
mit
|
1
|
//
// MessageWriterTransitioning.swift
// Umalahokan
//
// Created by Mounir Ybanez on 15/02/2017.
// Copyright © 2017 Ner. All rights reserved.
//
import UIKit
class MessageWriterTransitioning: NSObject, UIViewControllerTransitioningDelegate {
var composerButtonFrame: CGRect = .zero
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let transition = MessageWriterTransition(style: .presentation)
transition.composerButtonFrame = composerButtonFrame
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let transition = AlphaTransition(style: .dismissal)
return transition
}
}
class MessageWriterTransition: NSObject, UIViewControllerAnimatedTransitioning {
enum Style {
case presentation, dismissal
}
private(set) var style: Style = .presentation
var duration: TimeInterval = 5.5
var composerButtonFrame: CGRect = .zero
init(style: Style) {
super.init()
self.style = style
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using context: UIViewControllerContextTransitioning) {
// Setting up context
let presentedKey: UITransitionContextViewKey = style == .presentation ? .to : .from
let presented = context.view(forKey: presentedKey) as! MessageWriterView
let container = context.containerView
let whiteColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
switch style {
case .presentation:
presented.header.closeButton.alpha = 0
presented.header.titleLabel.alpha = 0
presented.header.inputBackground.alpha = 0
presented.header.inputLabel.alpha = 0
presented.header.inputTextField.alpha = 0
presented.sendView.alpha = 0
presented.backgroundColor = whiteColor.withAlphaComponent(0)
presented.tableView.backgroundColor = UIColor.clear
presented.header.backgroundColor = UIColor.clear
presented.header.backgroundView.frame = composerButtonFrame
presented.header.backgroundView.layer.cornerRadius = composerButtonFrame.width / 2
presented.header.backgroundView.layer.masksToBounds = true
container.addSubview(presented)
presentationAnimation(presented, context: context)
case .dismissal:
break
}
}
func presentationAnimation(_ presented: MessageWriterView, context: UIViewControllerContextTransitioning) {
let whiteColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let color = whiteColor.withAlphaComponent(1)
let duration: TimeInterval = 1.25
UIView.animateKeyframes(withDuration: duration, delay: 0, options: .calculationModeLinear, animations: {
var keyframeDuration: TimeInterval = 0.25
var delay: TimeInterval = 0
var relativeStartTime: TimeInterval = 0 + (delay / duration)
var relativeDuration: TimeInterval = keyframeDuration / duration
var totalKeyframeDuration = keyframeDuration + delay
UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: {
presented.backgroundColor = color
presented.header.backgroundView.frame.origin.y = 0
presented.header.backgroundView.frame.origin.x = (presented.header.frame.width - presented.header.backgroundView.frame.width) / 2
})
keyframeDuration = 0.25
delay = 0
relativeStartTime = relativeDuration + (delay / duration)
relativeDuration += (keyframeDuration / duration)
totalKeyframeDuration += (keyframeDuration + delay)
UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: {
presented.header.backgroundView.transform = CGAffineTransform(scaleX: 10, y: 10)
})
keyframeDuration = 0.25
delay = 0
relativeStartTime = relativeDuration + (delay / duration)
relativeDuration += (keyframeDuration / duration)
totalKeyframeDuration += (keyframeDuration + delay)
UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: {
presented.header.closeButton.alpha = 1
presented.header.titleLabel.alpha = 1
})
keyframeDuration = 0.25
delay = 0.25
relativeStartTime = relativeDuration + (delay / duration)
relativeDuration += (keyframeDuration / duration)
totalKeyframeDuration += (keyframeDuration + delay)
UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: {
presented.header.inputBackground.alpha = 1
presented.header.inputLabel.alpha = 1
presented.header.inputTextField.alpha = 1
presented.sendView.alpha = 1
})
assert(totalKeyframeDuration == duration, "Total keyframe duration is not in sync.")
}) { _ in
context.completeTransition(!context.transitionWasCancelled)
}
perform(#selector(self.reloadTableView(_:)), with: presented, afterDelay: 0.50)
perform(#selector(self.clipToBounds(_:)), with: presented, afterDelay: 0.49)
}
@objc func reloadTableView(_ presented: MessageWriterView) {
presented.isValidToReload = true
presented.tableView.reloadData()
presented.header.inputTextField.becomeFirstResponder()
}
@objc func clipToBounds(_ presented: MessageWriterView) {
presented.header.clipsToBounds = true
}
}
|
04e78851ec90f38fe91258e0e37c83fa
| 40.603896 | 170 | 0.644607 | false | false | false | false |
teambition/CardStyleTableView
|
refs/heads/master
|
CardStyleTableView/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// CardStyleTableView
//
// Created by Xin Hong on 16/1/28.
// Copyright © 2016年 Teambition. All rights reserved.
//
import UIKit
internal struct AssociatedKeys {
static var cardStyleTableViewStyleSource = "CardStyleTableViewStyleSource"
static var cardStyleTableViewCellTableView = "CardStyleTableViewCellTableView"
}
internal struct TableViewSelectors {
static let layoutSubviews = #selector(UITableView.layoutSubviews)
static let swizzledLayoutSubviews = #selector(UITableView.cardStyle_tableViewSwizzledLayoutSubviews)
}
internal struct TableViewCellSelectors {
static let layoutSubviews = #selector(UITableViewCell.layoutSubviews)
static let didMoveToSuperview = #selector(UITableViewCell.didMoveToSuperview)
static let swizzledLayoutSubviews = #selector(UITableViewCell.cardStyle_tableViewCellSwizzledLayoutSubviews)
static let swizzledDidMoveToSuperview = #selector(UITableViewCell.cardStyle_tableViewCellSwizzledDidMoveToSuperview)
}
|
7aac3fdfcea7b6cd94821f0ac250f990
| 37.615385 | 120 | 0.815737 | false | false | false | false |
eraydiler/password-locker
|
refs/heads/master
|
PasswordLockerSwift/Supporting Files/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// PasswordLockerSwift
//
// Created by Eray on 19/01/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
import CoreData
import MagicalRecord
let kPasswordLockerUserDefaultsHasInitialized = "kPasswordLockerUserDefaultsHasInitialized"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
MagicalRecord.setupCoreDataStack()
let managedObjectContext = NSManagedObjectContext.mr_default()
let isAppInitializedWithData = UserDefaults.standard.bool(forKey: kPasswordLockerUserDefaultsHasInitialized)
if (isAppInitializedWithData == false) {
DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Category")
DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Type")
DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Row")
DataFactory.setupInitialData(managedObjectContext)
UserDefaults.standard.set(true, forKey: kPasswordLockerUserDefaultsHasInitialized)
print("Initial Data inserted")
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
guard let splashController = self.window?.rootViewController else {
return
}
guard let aController = splashController.presentedViewController
else {
return
}
guard let tabBarController = aController.presentedViewController else {
return
}
tabBarController.dismiss(animated: false)
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
MagicalRecord.cleanUp()
}
}
|
7c60c37081827cf0dd154c6e02057784
| 39.473684 | 285 | 0.726268 | false | false | false | false |
toohotz/IQKeyboardManager
|
refs/heads/master
|
Demo/Swift_Demo/ViewController/ScrollViewController.swift
|
mit
|
1
|
//
// ScrollViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import Foundation
import UIKit
class ScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate, UIPopoverPresentationControllerDelegate {
@IBOutlet private var scrollViewDemo : UIScrollView!
@IBOutlet private var simpleTableView : UITableView!
@IBOutlet private var scrollViewOfTableViews : UIScrollView!
@IBOutlet private var tableViewInsideScrollView : UITableView!
@IBOutlet private var scrollViewInsideScrollView : UIScrollView!
@IBOutlet private var topTextField : UITextField!
@IBOutlet private var bottomTextField : UITextField!
@IBOutlet private var topTextView : UITextView!
@IBOutlet private var bottomTextView : UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "\(indexPath.section) \(indexPath.row)"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)
cell?.selectionStyle = UITableViewCellSelectionStyle.None
cell?.backgroundColor = UIColor.clearColor()
let textField = UITextField(frame: CGRectInset(cell!.contentView.bounds, 5, 5))
textField.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleWidth]
textField.placeholder = identifier
textField.borderStyle = UITextBorderStyle.RoundedRect
cell?.contentView.addSubview(textField)
}
return cell!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "SettingsNavigationController" {
let controller = segue.destinationViewController
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds));
controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
override func shouldAutorotate() -> Bool {
return true
}
}
|
dcbb41e4fc0369c524b30b58f97a2daa
| 37.360465 | 172 | 0.685965 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/01217-swift-typechecker-resolveidentifiertype.swift
|
apache-2.0
|
13
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
private class B<C> {
let enum S<T> : P {
func f<T>() -> T -> T {
return { x in x 1 {
b[c][c] = 1
}
}
class A {
class func a() -> String {
let d: String = {
return self.a()
}()
}
struct d<f : e, g: e where g.h == f.h> {
}
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
}
struct D : C {
func g<T where T.E == F>(f: B<T>) {
}
protocol A {
}
struct B<T : A> {
|
93d74804770b00ad0b58e3a98b7f4bdc
| 16.117647 | 87 | 0.582474 | false | true | false | false |
fnky/drawling-components
|
refs/heads/master
|
DrawlingComponents/Components/RBScrollView.swift
|
gpl-2.0
|
1
|
//
// RBScrollView.swift
// DrawlingComponents
//
// Created by Christian Petersen
// Copyright (c) 2015 Reversebox. All rights reserved.
//
import Foundation
import UIKit
class RBScrollView : UIScrollView {
// All subviews should conform to this ScrollView's height
// with a aspect ratio.
//let gradient: CAGradientLayer? = nil
/*private func calculateContentSize(views: [AnyObject]) -> CGSize {
var size: CGSize = CGSizeMake(0, 0)
var counter: Int = 0
for view in views {
let x: CGFloat = view.bounds.origin.x
let y: CGFloat = view.bounds.origin.y
let w: CGFloat = view.bounds.size.width
let h: CGFloat = view.bounds.size.height
size.width += w
counter++
}
println("view) \(size)")
return CGSizeMake(size.width, self.frame.size.height)
}*/
private func calculateContentSize(views: [AnyObject]) -> CGSize {
let lo = views.last as UIView
let oy = lo.frame.origin.x
let ht = lo.frame.size.width
var s = CGSizeMake(oy + ht, self.frame.size.height)
println(s)
return s
}
override func layoutIfNeeded() {
}
override func layoutSubviews() {
}
override func addSubview(view: UIView) {
// when adding subview, the given view's size
// set itselfs contentSize accordingly
super.addSubview(view)
self.contentSize = calculateContentSize(self.subviews)
}
override func layoutSublayersOfLayer(layer: CALayer!) {
let gradient: CAGradientLayer = CAGradientLayer(layer: layer)
gradient.frame = self.bounds
gradient.colors = [UIColor(white: 1, alpha: 1).CGColor, UIColor(white: 1, alpha: 0).CGColor]
gradient.locations = [0.8, 1.0]
gradient.startPoint = CGPointMake(0, 0.5)
gradient.endPoint = CGPointMake(1, 0.5)
layer.mask = gradient
}
override func drawRect(rect: CGRect) {
}
}
|
0b0dfe0ec7e107abbcfc84c08dd837fa
| 23.525641 | 96 | 0.650628 | false | false | false | false |
trd-jameshwart/FamilySNIOS
|
refs/heads/master
|
FamilySns/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// FamilySns
//
// Created by Jameshwart Lopez on 12/8/15.
// Copyright © 2015 Minato. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIPopoverPresentationControllerDelegate{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var usernameLabel: UILabel!
@IBAction func showAlertWasTapped(sender: AnyObject) {
let alertController = UIAlertController(title: "Appcoda", message: "Message in alert dialog", preferredStyle: UIAlertControllerStyle.ActionSheet)
let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: {(alert :UIAlertAction!) in
print("Delete button tapped")
})
alertController.addAction(deleteAction)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(alert :UIAlertAction!) in
print("OK button tapped")
})
alertController.addAction(okAction)
alertController.popoverPresentationController?.sourceView = view
alertController.popoverPresentationController?.sourceRect = sender.frame
presentViewController(alertController, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "popoverSegue"{
// dispatch_async(dispatch_get_main_queue(), {
// let popoverViewController = segue.destinationViewController
// popoverViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
// popoverViewController.popoverPresentationController!.delegate = self
// })
let vc = PostModal()
vc.modalPresentationStyle = .Popover
presentViewController(vc, animated: true, completion: nil)
vc.popoverPresentationController?.sourceView = view;
// vc.popoverPresentationController?.sourceRect =
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
override func viewWillAppear(animated: Bool) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//[self setModalPresentationStyle:UIModalPresentationCurrentContext];
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
//self.performSegueWithIdentifier("goto_login", sender: self)
}
@IBAction func profileTapped(sender: AnyObject) {
self.performSegueWithIdentifier("goto_profile", sender: nil)
}
@IBAction func logoutTapped(sender: UIButton) {
self.performSegueWithIdentifier("goto_login", sender: self)
}
//
// func tableView(tableview: UITableView, numberOfRowsInSection section:Int)-> Int{
//
// }
//
// func tableview(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell{
//
// }
//
// func tableView(tableView: UITableView, didSelectRowAtIndexPaht indexPath:NSIndexPath){
//
// }
}
|
bbe7a72c032e8b21acef0f1ec83e4dcd
| 31.718447 | 153 | 0.691691 | false | false | false | false |
AlexanderNey/Futuristics
|
refs/heads/alpha
|
Tests/FunctionCompositionTests.swift
|
mit
|
1
|
//
// FunctionCompositionTests.swift
// Futuristics
//
// Created by Alexander Ney on 05/08/2015.
// Copyright © 2015 Alexander Ney. All rights reserved.
//
import Foundation
import XCTest
import Futuristics
class FunctionCopositionTests : XCTestCase {
enum ConvertError: Error {
case failedToConvertStringToNumber(String)
}
func stringToNumber(_ str: String) throws -> Int {
if let number = Int(str) {
return number
} else {
throw ConvertError.failedToConvertStringToNumber(str)
}
}
func doubleNumber(_ number: Int) throws -> Int {
return number * 2
}
func testBasicFunctionComposition() {
let composition = stringToNumber >>> doubleNumber
do {
let result = try composition("100")
XCTAssertEqual(result, 200)
} catch {
XCTFail("function call not expected to throw")
}
}
func testBasicFunctionCompositionThrowing() {
let composition = stringToNumber >>> doubleNumber
let throwExpectation = expectation(description: "throw expectation")
do {
_ = try composition("abc")
XCTFail("function call expected to throw")
} catch ConvertError.failedToConvertStringToNumber(let str) {
if str == "abc" {
throwExpectation.fulfill()
}
} catch {
XCTFail("generic error not expected")
}
waitForExpectationsWithDefaultTimeout()
}
func testBasicFunctionCompositionInvocation() {
do {
let result = try "100" |> stringToNumber |> doubleNumber
XCTAssertEqual(result, 200)
} catch {
XCTFail("function call not expected to throw")
}
}
func testBasicFunctionCompositionInvocationThrowing() {
let throwExpectation = expectation(description: "throw expectation")
do {
_ = try ( "abc" |> stringToNumber |> doubleNumber )
XCTFail("function call expected to throw")
} catch ConvertError.failedToConvertStringToNumber(let str) {
if str == "abc" {
throwExpectation.fulfill()
}
} catch {
XCTFail("generic error not expected")
}
waitForExpectationsWithDefaultTimeout()
}
}
|
dfdfabb2c24fbaf0597b1b31fd182440
| 26.561798 | 76 | 0.575214 | false | true | false | false |
AsyncNinja/AsyncNinja
|
refs/heads/master
|
Sources/AsyncNinja/appleOS_URLSession.swift
|
mit
|
1
|
//
// Copyright (c) 2016-2017 Anton Mironov
//
// 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.
//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Foundation
/// Conformance URLSessionTask to Cancellable
extension URLSessionTask: Cancellable { }
/// URLSession improved with AsyncNinja
public extension URLSession {
/// Makes data task and returns Future of response
func data(
at url: URL,
cancellationToken: CancellationToken? = nil
) -> Future<(Data?, URLResponse)> {
return dataFuture(cancellationToken: cancellationToken) {
dataTask(with: url, completionHandler: $0)
}
}
/// Makes data task and returns Future of response
func data(
with request: URLRequest,
cancellationToken: CancellationToken? = nil
) -> Future<(Data?, URLResponse)> {
return dataFuture(cancellationToken: cancellationToken) {
dataTask(with: request, completionHandler: $0)
}
}
/// Makes upload task and returns Future of response
func upload(
with request: URLRequest,
fromFile fileURL: URL,
cancellationToken: CancellationToken? = nil
) -> Future<(Data?, URLResponse)> {
return dataFuture(cancellationToken: cancellationToken) {
uploadTask(with: request, fromFile: fileURL, completionHandler: $0)
}
}
/// Makes upload task and returns Future of response
func upload(
with request: URLRequest,
from bodyData: Data?,
cancellationToken: CancellationToken? = nil
) -> Future<(Data?, URLResponse)> {
return dataFuture(cancellationToken: cancellationToken) {
uploadTask(with: request, from: bodyData, completionHandler: $0)
}
}
/// Makes download task and returns Future of response
func download(
at sourceURL: URL,
to destinationURL: URL,
cancellationToken: CancellationToken? = nil
) -> Future<URL> {
return downloadFuture(to: destinationURL, cancellationToken: cancellationToken) {
downloadTask(with: sourceURL, completionHandler: $0)
}
}
/// Makes download task and returns Future of response
func download(
with request: URLRequest,
to destinationURL: URL,
cancellationToken: CancellationToken? = nil
) -> Future<URL> {
return downloadFuture(to: destinationURL, cancellationToken: cancellationToken) {
downloadTask(with: request, completionHandler: $0)
}
}
}
fileprivate extension URLSession {
/// a shortcut to url session callback
typealias URLSessionCallback = (Data?, URLResponse?, Swift.Error?) -> Void
/// a shortcut to url session task construction
typealias MakeURLTask = (@escaping URLSessionCallback) -> URLSessionDataTask
func dataFuture(
cancellationToken: CancellationToken?,
makeTask: MakeURLTask) -> Future<(Data?, URLResponse)> {
let promise = Promise<(Data?, URLResponse)>()
let task = makeTask { [weak promise] (data, response, error) in
guard let promise = promise else { return }
guard let error = error else {
promise.succeed((data, response!), from: nil)
return
}
if let cancellationRepresentable = error as? CancellationRepresentableError,
cancellationRepresentable.representsCancellation {
promise.cancel(from: nil)
} else {
promise.fail(error, from: nil)
}
}
promise._asyncNinja_notifyFinalization { [weak task] in task?.cancel() }
cancellationToken?.add(cancellable: task)
cancellationToken?.add(cancellable: promise)
task.resume()
return promise
}
/// a shortcut to url session callback
typealias DownloadTaskCallback = (URL?, URLResponse?, Swift.Error?) -> Void
/// a shortcut to url session task construction
typealias MakeDownloadTask = (@escaping DownloadTaskCallback) -> URLSessionDownloadTask
func downloadFuture(
to destinationURL: URL,
cancellationToken: CancellationToken?,
makeTask: MakeDownloadTask) -> Future<URL> {
let promise = Promise<URL>()
let task = makeTask { [weak promise] (temporaryURL, _, error) in
guard let promise = promise else { return }
if let error = error {
if let cancellationRepresentable = error as? CancellationRepresentableError,
cancellationRepresentable.representsCancellation {
promise.cancel(from: nil)
} else {
promise.fail(error, from: nil)
}
} else if let temporaryURL = temporaryURL {
do {
try FileManager.default.moveItem(at: temporaryURL, to: destinationURL)
promise.succeed(destinationURL)
} catch { promise.fail(error) }
return
} else {
promise.fail(NSError(domain: URLError.errorDomain, code: URLError.dataNotAllowed.rawValue))
}
}
promise._asyncNinja_notifyFinalization { [weak task] in task?.cancel() }
cancellationToken?.add(cancellable: task)
cancellationToken?.add(cancellable: promise)
task.resume()
return promise
}
}
#endif
|
7e6eca0bd29548171b186d6f4df5f6a5
| 36.329341 | 101 | 0.671158 | false | false | false | false |
qvacua/vimr
|
refs/heads/master
|
Commons/Tests/CommonsTests/ArrayCommonsTest.swift
|
mit
|
1
|
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Nimble
import XCTest
@testable import Commons
private class DummyToken: Comparable {
static func == (left: DummyToken, right: DummyToken) -> Bool {
left.value == right.value
}
static func < (left: DummyToken, right: DummyToken) -> Bool {
left.value < right.value
}
let value: String
init(_ value: String) {
self.value = value
}
}
class ArrayCommonsTest: XCTestCase {
func testTuplesToDict() {
let tuples = [
(1, "1"),
(2, "2"),
(3, "3"),
]
expect(tuplesToDict(tuples)).to(equal(
[
1: "1",
2: "2",
3: "3",
]
))
}
func testToDict() {
let array = [1, 2, 3]
expect(array.toDict { "\($0)" })
.to(equal(
[
1: "1",
2: "2",
3: "3",
]
))
}
func testRemovingDuplicatesPreservingFromBeginning() {
let array = [1, 2, 3, 4, 3, 3, 5, 3]
expect(array.removingDuplicatesPreservingFromBeginning()).to(equal([1, 2, 3, 4, 5]))
}
func testSubstituting1() {
let substitute = [
DummyToken("a0"),
DummyToken("a1"),
DummyToken("a2"),
]
let array = [
DummyToken("b0"),
DummyToken("b1"),
DummyToken("a0"),
DummyToken("a1"),
DummyToken("b4"),
DummyToken("a2"),
]
let result = array.substituting(elements: substitute)
expect(result[2]).to(beIdenticalTo(substitute[0]))
expect(result[3]).to(beIdenticalTo(substitute[1]))
expect(result[5]).to(beIdenticalTo(substitute[2]))
expect(result).to(equal(array))
}
func testSubstituting2() {
let substitute = [
DummyToken("a0"),
DummyToken("a1"),
DummyToken("a2"),
]
let array = [
DummyToken("a0"),
DummyToken("b0"),
DummyToken("a1"),
DummyToken("b1"),
DummyToken("a2"),
DummyToken("b4"),
]
let result = array.substituting(elements: substitute)
expect(result[0]).to(beIdenticalTo(substitute[0]))
expect(result[2]).to(beIdenticalTo(substitute[1]))
expect(result[4]).to(beIdenticalTo(substitute[2]))
expect(result).to(equal(array))
}
func testSubstituting3() {
let substitute = [
DummyToken("a0"),
DummyToken("a1"),
DummyToken("a2"),
]
let array = [
DummyToken("b0"),
DummyToken("b1"),
DummyToken("b4"),
DummyToken("a0"),
DummyToken("a1"),
DummyToken("a2"),
]
let result = array.substituting(elements: substitute)
expect(result[3]).to(beIdenticalTo(substitute[0]))
expect(result[4]).to(beIdenticalTo(substitute[1]))
expect(result[5]).to(beIdenticalTo(substitute[2]))
expect(result).to(equal(array))
}
func testSubstituting4() {
let substitute = [
DummyToken("a0"),
DummyToken("a1"),
DummyToken("a2"),
]
let array = [
DummyToken("a0"),
DummyToken("a1"),
DummyToken("a2"),
DummyToken("b0"),
DummyToken("b1"),
DummyToken("b4"),
]
let result = array.substituting(elements: substitute)
expect(result[0]).to(beIdenticalTo(substitute[0]))
expect(result[1]).to(beIdenticalTo(substitute[1]))
expect(result[2]).to(beIdenticalTo(substitute[2]))
expect(result).to(equal(array))
}
func testSubstituting5() {
let substitute = [
DummyToken("a0"),
DummyToken("something else"),
DummyToken("a1"),
DummyToken("a2"),
]
let array = [
DummyToken("a0"),
DummyToken("b0"),
DummyToken("a1"),
DummyToken("b1"),
DummyToken("a2"),
DummyToken("b4"),
]
let result = array.substituting(elements: substitute)
expect(result[0]).to(beIdenticalTo(substitute[0]))
expect(result[2]).to(beIdenticalTo(substitute[2]))
expect(result[4]).to(beIdenticalTo(substitute[3]))
expect(result).to(equal(array))
}
}
|
01d45ccc09458cbb0840bcf9152ee9be
| 20.318919 | 88 | 0.575051 | false | true | false | false |
kvvzr/Twinkrun
|
refs/heads/master
|
Twinkrun/Models/TWRGame.swift
|
mit
|
2
|
//
// TWRGame.swift
// Twinkrun
//
// Created by Kawazure on 2014/10/09.
// Copyright (c) 2014年 Twinkrun. All rights reserved.
//
import Foundation
import UIKit
import CoreBluetooth
enum TWRGameState {
case Idle
case CountDown
case Started
}
protocol TWRGameDelegate {
func didUpdateCountDown(count: UInt)
func didStartGame()
func didUpdateScore(score: Int)
func didFlash(color: UIColor)
func didUpdateRole(color: UIColor, score: Int)
func didEndGame()
}
class TWRGame: NSObject, CBCentralManagerDelegate, CBPeripheralManagerDelegate {
var player: TWRPlayer
var others: [TWRPlayer]
let option: TWRGameOption
var state = TWRGameState.Idle
var transition: Array<(role: TWRRole, scores: [Int])>?, currentTransition: [Int]?
var score: Int, addScore: Int, flashCount: UInt?, countDown: UInt?
var startTime: NSDate?
var scanTimer: NSTimer?, updateRoleTimer: NSTimer?, updateScoreTimer: NSTimer?, flashTimer: NSTimer?, gameTimer: NSTimer?
unowned var centralManager: CBCentralManager
unowned var peripheralManager: CBPeripheralManager
var delegate: TWRGameDelegate?
init(player: TWRPlayer, others: [TWRPlayer], central: CBCentralManager, peripheral: CBPeripheralManager) {
self.player = player
self.others = others
self.option = TWROption.sharedInstance.gameOption
self.centralManager = central
self.peripheralManager = peripheral
score = option.startScore
addScore = 0
super.init()
centralManager.delegate = self
peripheralManager.delegate = self
}
func start() {
transition = []
currentTransition = []
score = option.startScore
flashCount = 0
countDown = option.countTime
scanTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("countDown:"), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(scanTimer!, forMode: NSRunLoopCommonModes)
countDown(nil)
}
func countDown(timer: NSTimer?) {
state = TWRGameState.CountDown
if countDown! == 0 {
timer?.invalidate()
state = TWRGameState.Started
delegate?.didStartGame()
startTime = NSDate()
let current = UInt(NSDate().timeIntervalSinceDate(startTime!))
let currentRole = player.currentRole(current)
delegate?.didUpdateRole(currentRole.color, score: score)
updateRoleTimer = NSTimer(timeInterval: Double(currentRole.time), target: self, selector: Selector("updateRole:"), userInfo: nil, repeats: false)
updateScoreTimer = NSTimer(timeInterval: Double(option.scanInterval), target: self, selector: Selector("updateScore:"), userInfo: nil, repeats: true)
flashTimer = NSTimer(timeInterval: Double(option.flashStartTime(currentRole.time)), target: self, selector: Selector("flash:"), userInfo: nil, repeats: false)
gameTimer = NSTimer(timeInterval: Double(option.gameTime()), target: self, selector: Selector("end:"), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(flashTimer!, forMode: NSRunLoopCommonModes)
NSRunLoop.mainRunLoop().addTimer(updateRoleTimer!, forMode: NSRunLoopCommonModes)
NSRunLoop.mainRunLoop().addTimer(updateScoreTimer!, forMode: NSRunLoopCommonModes)
NSRunLoop.mainRunLoop().addTimer(gameTimer!, forMode: NSRunLoopCommonModes)
} else {
delegate?.didUpdateCountDown(countDown!)
--countDown!
}
}
func updateRole(timer: NSTimer?) {
let current = UInt(NSDate().timeIntervalSinceDate(startTime!))
let prevRole = player.previousRole(current)
let currentRole = player.currentRole(current)
if let prevRole = prevRole {
transition! += [(role: prevRole, scores: currentTransition!)]
}
flashCount = 0
currentTransition = []
delegate?.didUpdateRole(currentRole.color, score: score)
updateRoleTimer = NSTimer(timeInterval: Double(currentRole.time), target: self, selector: Selector("updateRole:"), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(updateRoleTimer!, forMode: NSRunLoopCommonModes)
flashTimer = NSTimer(timeInterval: Double(option.flashStartTime(currentRole.time)), target: self, selector: Selector("flash:"), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(flashTimer!, forMode: NSRunLoopCommonModes)
}
func updateScore(timer: NSTimer) {
currentTransition!.append(score)
score += addScore
addScore = 0
for player in others {
player.countedScore = false
}
delegate?.didUpdateScore(score)
}
func flash(timer: NSTimer) {
if (flashCount < option.flashCount) {
let current = UInt(NSDate().timeIntervalSinceDate(startTime!))
let nextRole = player.nextRole(current)
if (nextRole == nil) {
return
}
delegate?.didFlash((flashCount! % 2 == 0 ? nextRole! : player.currentRole(current)).color)
self.flashTimer = NSTimer(timeInterval: Double(option.flashInterval()), target: self, selector: Selector("flash:"), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(flashTimer!, forMode: NSRunLoopCommonModes)
}
++flashCount!
}
func end() {
if let startTime = startTime {
let current = UInt(NSDate().timeIntervalSinceDate(startTime))
let prevRole = player.previousRole(current)!
transition! += [(role: prevRole, scores: currentTransition!)]
currentTransition = []
}
if let timer: NSTimer = scanTimer {
timer.invalidate()
}
if let timer: NSTimer = updateRoleTimer {
timer.invalidate()
}
if let timer: NSTimer = updateScoreTimer {
timer.invalidate()
}
if let timer: NSTimer = flashTimer {
timer.invalidate()
}
if let timer: NSTimer = gameTimer {
timer.invalidate()
}
state = TWRGameState.Idle
}
func end(timer: NSTimer) {
end()
delegate?.didEndGame()
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
if let localName = advertisementData["kCBAdvDataLocalName"] as AnyObject? as? String {
if let startTime = startTime {
let current = UInt(NSDate().timeIntervalSinceDate(startTime))
let findPlayer = TWRPlayer(advertisementDataLocalName: localName, identifier: peripheral.identifier)
let other = others.filter { $0 == findPlayer }
if !other.isEmpty {
other.first!.RSSI = RSSI.integerValue
if other.first!.playWith && !other.first!.countedScore && RSSI.integerValue <= 0 {
let point = min(pow(2, (RSSI.floatValue + 45) / 4), 3.0)
addScore -= Int(point * player.currentRole(current).score)
addScore += Int(point * other.first!.currentRole(current).score)
other.first!.countedScore = true
}
}
}
}
}
func centralManagerDidUpdateState(central: CBCentralManager) {
}
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
}
}
|
5d7b5080780b8b64178691f2c9d9b962
| 35.697248 | 170 | 0.610326 | false | false | false | false |
CalQL8ed-K-OS/SwiftProceduralLevelGeneration
|
refs/heads/master
|
Procedural/Code/Scene.swift
|
mit
|
1
|
//
// Scene.swift
// Procedural
//
// Created by Xavi on 3/19/15.
// Copyright (c) 2015 Xavi. All rights reserved.
//
import SpriteKit
class Scene:SKScene {
private let world = SKNode()
private let hud = SKNode()
private let dPad = Scene.createDpad()
private let map = Map()
private var player = Scene.createPlayer()
private let playerShadow = Scene.createShadow()
private let exit = Scene.createExit()
private var isExistingLevel = false
private static let playerSpeed:CGFloat = 100.0
private var lastUpdateTime = NSTimeInterval(0)
override init(size:CGSize) {
super.init(size: size)
backgroundColor = SKColor(hue: 0.5, saturation: 0.5, brightness: 0.5, alpha: 1.0)
setupNodes()
setupPhysics()
}
override func update(currentTime: NSTimeInterval) {
let timeDelta:NSTimeInterval = {
let time = currentTime - lastUpdateTime
return time > 1 ? time : 1.0 / 60.0
}()
lastUpdateTime = currentTime
updatePlayer(timeDelta)
updateCamera()
}
override func didSimulatePhysics() {
player.zRotation = 0.0
playerShadow.position = CGPoint(x: player.position.x, y: player.position.y - 7.0)
}
// Shoutout to Nate Cook for his
// [NS_OPTIONS Bitmasker Generator for Swift](http://natecook.com/blog/2014/07/swift-options-bitmask-generator/)
struct CollisionType : RawOptionSetType {
typealias RawValue = UInt32
private var value: RawValue = 0
init(_ value: RawValue) { self.value = value }
init(rawValue value: RawValue) { self.value = value }
init(nilLiteral: ()) { self.value = 0 }
static var allZeros: CollisionType { return self(0) }
static func fromMask(raw: RawValue) -> CollisionType { return self(raw) }
var rawValue: RawValue { return self.value }
static var Player: CollisionType { return CollisionType(1 << 0) }
static var Wall: CollisionType { return CollisionType(1 << 1) }
static var Exit: CollisionType { return CollisionType(1 << 2) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: SKPhysicsContactDelegate
extension Scene:SKPhysicsContactDelegate {
func didBeginContact(contact: SKPhysicsContact) {
let firstBody:SKPhysicsBody
let secondBody:SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if CollisionType.fromMask( firstBody.categoryBitMask) == CollisionType.Player &&
CollisionType.fromMask(secondBody.categoryBitMask) == CollisionType.Exit
{
resolveExit()
}
}
}
// MARK: Private
private extension Scene {
// MARK: Setup
func setupNodes() {
player.position = map.spawnPosition
exit.position = map.exitPosition
world.addChild(map)
world.addChild(exit)
world.addChild(playerShadow)
world.addChild(player)
hud.addChild(dPad)
self.addChild(world)
self.addChild(hud)
}
func setupPhysics() {
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
}
// MARK: Update cycle
func updatePlayer(timeDelta:NSTimeInterval) {
let playerVelocity = isExistingLevel ? CGPoint.zeroPoint : dPad.velocity
// Position
player.position = CGPoint(x: player.position.x + playerVelocity.x * CGFloat(timeDelta) * Scene.playerSpeed,
y: player.position.y + playerVelocity.y * CGFloat(timeDelta) * Scene.playerSpeed)
if playerVelocity.x != 0.0 {
player.xScale = playerVelocity.x > 0.0 ? -1.0 : 1.0
}
// Animation
let anim:PlayerAnimation = playerVelocity.x != 0.0 ? .Walk : .Idle
let key = anim.key
let action = player.actionForKey(key)
if let action = action {
return
} else {
var action = SKAction.animateWithTextures(anim.frames, timePerFrame: 5.0/60.0, resize: true, restore: false)
if anim == .Walk {
let stepSound = SKAction.playSoundFileNamed("step.wav", waitForCompletion: false)
action = SKAction.group([action, stepSound])
}
player.runAction(action, withKey: key)
}
}
func updateCamera() {
world.position = CGPoint(x: -player.position.x + frame.midX, y: -player.position.y + frame.midY)
}
func resolveExit() {
isExistingLevel = true
playerShadow.removeFromParent()
let move = SKAction.moveTo(map.exitPosition, duration: 0.5)
let rotate = SKAction.rotateByAngle(CGFloat(M_PI * 2), duration: 0.5)
let fade = SKAction.fadeAlphaTo(0.0, duration: 0.5)
let scale = SKAction.scaleXTo(0.0, y: 0.0, duration: 0.5)
let sound = SKAction.playSoundFileNamed("win.wav", waitForCompletion: false)
let presentNextScene = SKAction.runBlock {
self.view!.presentScene(Scene(size: self.size),
transition: SKTransition.doorsCloseVerticalWithDuration(0.5))
}
player.runAction(SKAction.sequence([SKAction.group([move, rotate, fade, scale, sound]),
presentNextScene]))
}
// MARK: Inner types
enum PlayerAnimation {
case Idle, Walk
var key:String {
switch self {
case Idle:
return "anim_idle"
case Walk:
return "anim_walk"
}
}
var frames:[SKTexture] {
switch self {
case Idle:
return Scene.idleTextures
case Walk:
return Scene.walkTextures
}
}
}
// MARK: Sprite creation
static var spriteAtlas:SKTextureAtlas = SKTextureAtlas(named: "sprites")
class func createExit() -> SKSpriteNode {
let exit = SKSpriteNode(texture: self.spriteAtlas.textureNamed("exit"))
exit.physicsBody = {
let size = CGSize(width: exit.texture!.size().width / 2.0,
height: exit.texture!.size().height / 2.0)
var body = SKPhysicsBody(rectangleOfSize: size)
body.categoryBitMask = CollisionType.Exit.rawValue
body.collisionBitMask = 0
return body
}()
return exit
}
class func createPlayer() -> SKSpriteNode {
let player = SKSpriteNode(texture: self.spriteAtlas.textureNamed("idle_0"))
player.physicsBody = {
let body = SKPhysicsBody(rectangleOfSize: player.texture!.size())
body.categoryBitMask = CollisionType.Player.rawValue
body.contactTestBitMask = CollisionType.Exit.rawValue
body.collisionBitMask = CollisionType.Wall.rawValue
body.allowsRotation = false
return body
}()
return player
}
class func createDpad() -> DPad {
let dpad = DPad(rect: CGRect(x: 0, y: 0, width: 64, height: 64))
dpad.position = CGPoint(x: 16, y: 16)
dpad.numberOfDirections = 24
dpad.deadRadius = 8
return dpad
}
class func createShadow() -> SKSpriteNode {
let shadow = SKSpriteNode(texture: self.spriteAtlas.textureNamed("shadow"))
shadow.xScale = 0.6
shadow.yScale = 0.5
shadow.alpha = 0.4
return shadow
}
// MARK: Animation texture array creation
static let idleTextures = Scene.createIdleAnimation()
static let walkTextures = Scene.createWalkAnimation()
class func createIdleAnimation() -> [SKTexture] {
return [self.spriteAtlas.textureNamed("idle_0")]
}
class func createWalkAnimation() -> [SKTexture] {
return [0, 1, 2].map { self.spriteAtlas.textureNamed("walk_\($0)") }
}
}
|
9e1777a98440407a5eb6946c5e5d2276
| 33.05668 | 120 | 0.588564 | false | false | false | false |
loudnate/Loop
|
refs/heads/master
|
LoopUI/Views/LoopCompletionHUDView.swift
|
apache-2.0
|
1
|
//
// LoopCompletionHUDView.swift
// Naterade
//
// Created by Nathan Racklyeft on 5/1/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKitUI
import LoopCore
public final class LoopCompletionHUDView: BaseHUDView {
@IBOutlet private weak var loopStateView: LoopStateView!
override public var orderPriority: HUDViewOrderPriority {
return 1
}
private(set) var freshness = LoopCompletionFreshness.unknown {
didSet {
updateTintColor()
}
}
override public func awakeFromNib() {
super.awakeFromNib()
updateDisplay(nil)
}
public var dosingEnabled = false {
didSet {
loopStateView.open = !dosingEnabled
}
}
public var lastLoopCompleted: Date? {
didSet {
if lastLoopCompleted != oldValue {
loopInProgress = false
}
}
}
public var loopInProgress = false {
didSet {
loopStateView.animated = loopInProgress
if !loopInProgress {
updateTimer = nil
assertTimer()
}
}
}
public func assertTimer(_ active: Bool = true) {
if active && window != nil, let date = lastLoopCompleted {
initTimer(date)
} else {
updateTimer = nil
}
}
override public func stateColorsDidUpdate() {
super.stateColorsDidUpdate()
updateTintColor()
}
private func updateTintColor() {
let tintColor: UIColor?
switch freshness {
case .fresh:
tintColor = stateColors?.normal
case .aging:
tintColor = stateColors?.warning
case .stale:
tintColor = stateColors?.error
case .unknown:
tintColor = stateColors?.unknown
}
self.tintColor = tintColor
}
private func initTimer(_ startDate: Date) {
let updateInterval = TimeInterval(minutes: 1)
let timer = Timer(
fireAt: startDate.addingTimeInterval(2),
interval: updateInterval,
target: self,
selector: #selector(updateDisplay(_:)),
userInfo: nil,
repeats: true
)
updateTimer = timer
RunLoop.main.add(timer, forMode: .default)
}
private var updateTimer: Timer? {
willSet {
if let timer = updateTimer {
timer.invalidate()
}
}
}
private lazy var formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day, .hour, .minute]
formatter.maximumUnitCount = 1
formatter.unitsStyle = .short
return formatter
}()
@objc private func updateDisplay(_: Timer?) {
if let date = lastLoopCompleted {
let ago = abs(min(0, date.timeIntervalSinceNow))
freshness = LoopCompletionFreshness(age: ago)
if let timeString = formatter.string(from: ago) {
switch traitCollection.preferredContentSizeCategory {
case UIContentSizeCategory.extraSmall,
UIContentSizeCategory.small,
UIContentSizeCategory.medium,
UIContentSizeCategory.large:
// Use a longer form only for smaller text sizes
caption.text = String(format: LocalizedString("%@ ago", comment: "Format string describing the time interval since the last completion date. (1: The localized date components"), timeString)
default:
caption.text = timeString
}
accessibilityLabel = String(format: LocalizedString("Loop ran %@ ago", comment: "Accessbility format label describing the time interval since the last completion date. (1: The localized date components)"), timeString)
} else {
caption.text = "—"
accessibilityLabel = nil
}
} else {
caption.text = "—"
accessibilityLabel = LocalizedString("Waiting for first run", comment: "Acessibility label describing completion HUD waiting for first run")
}
if dosingEnabled {
accessibilityHint = LocalizedString("Closed loop", comment: "Accessibility hint describing completion HUD for a closed loop")
} else {
accessibilityHint = LocalizedString("Open loop", comment: "Accessbility hint describing completion HUD for an open loop")
}
}
override public func didMoveToWindow() {
super.didMoveToWindow()
assertTimer()
}
}
|
8d740530f24e1caff92a67ee63c0d4db
| 28.333333 | 233 | 0.583544 | false | false | false | false |
jasperscholten/programmeerproject
|
refs/heads/master
|
JasperScholten-project/MainMenuVC.swift
|
apache-2.0
|
1
|
//
// MainMenuVC.swift
// JasperScholten-project
//
// Created by Jasper Scholten on 11-01-17.
// Copyright © 2017 Jasper Scholten. All rights reserved.
//
// This ViewController handles the presentation of a main menu, which content depends on the type of user that has logged in; an admin will have more options. The main menu also serves as a hub, that sends specific data to other ViewControllers (mainly currentOrganisationID and currenOrganisation name).
import UIKit
import Firebase
class MainMenuVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Constants and variables
let userRef = FIRDatabase.database().reference(withPath: "Users")
let uid = FIRAuth.auth()?.currentUser?.uid
var admin = Bool()
var currentOrganisation = String()
var currentOrganisationID = String()
var currentLocation = String()
var currentName = String()
var menuItems = [String]()
// MARK: - Outlets
@IBOutlet weak var menuTableView: UITableView!
// MARK: - UIViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
userRef.child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChildren() {
let userData = User(snapshot: snapshot)
if userData.uid == self.uid! {
self.currentOrganisation = userData.organisationName!
self.currentOrganisationID = userData.organisationID!
self.currentLocation = userData.locationID!
self.currentName = userData.name!
if userData.admin! == true {
self.menuItems = ["Beoordelen", "Resultaten", "Nieuws (admin)", "Stel lijst samen", "Medewerker verzoeken"]
self.admin = true
} else {
self.menuItems = ["Beoordelingen", "Nieuws"]
// Only allow admins to access settings menu. [1]
self.navigationItem.rightBarButtonItem = nil
}
self.menuTableView.reloadData()
self.resizeTable()
}
}
})
}
override func viewDidAppear(_ animated: Bool) {
resizeTable()
}
// Resize table on device rotation.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in self.resizeTable() },
completion: nil)
}
// MARK: - TableView Population
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = menuTableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as! MainMenuCell
cell.menuItem.text = menuItems[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: menuItems[indexPath.row], sender: self)
menuTableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Segue data specific to current user to chosen menu option.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let employeeResults = segue.destination as? ReviewResultsEmployeeVC {
employeeResults.employee = currentName
employeeResults.employeeID = uid!
} else if let news = segue.destination as? NewsAdminVC {
news.admin = admin
news.location = currentLocation
news.organisationID = currentOrganisationID
} else if let requests = segue.destination as? RequestsVC {
requests.organisationID = currentOrganisationID
} else if let forms = segue.destination as? FormsListVC {
forms.organisation = currentOrganisation
forms.organisationID = currentOrganisationID
} else if let employees = segue.destination as? ReviewEmployeeVC {
employees.organisation = currentOrganisation
employees.organisationID = currentOrganisationID
} else if let results = segue.destination as? ReviewResultsVC {
results.organisation = currentOrganisation
results.organisationID = currentOrganisationID
} else if let settings = segue.destination as? SettingsVC {
settings.organisationName = currentOrganisation
settings.organisationID = currentOrganisationID
}
}
// MARK: - Actions
@IBAction func signOut(_ sender: Any) {
if (try? FIRAuth.auth()?.signOut()) != nil {
self.dismiss(animated: true, completion: {})
} else {
alertSingleOption(titleInput: "Fout bij uitloggen",
messageInput: "Het is niet gelukt om je correct uit te loggen. Probeer het nog een keer.")
}
}
@IBAction func showSettings(_ sender: Any) {
performSegue(withIdentifier: "showSettings", sender: self)
}
// MARK: - Functions
// Resize the rowheight of menu cells, such that they fill the screen and are of equal height. [2]
func resizeTable() {
let heightOfVisibleTableViewArea = view.bounds.height - topLayoutGuide.length - bottomLayoutGuide.length
let numberOfRows = menuTableView.numberOfRows(inSection: 0)
menuTableView.rowHeight = heightOfVisibleTableViewArea / CGFloat(numberOfRows)
menuTableView.reloadData()
}
}
// MARK: - References
// 1. http://stackoverflow.com/questions/27887218/how-to-hide-a-bar-button-item-for-certain-users
// 2. http://stackoverflow.com/questions/34161016/how-to-make-uitableview-to-fill-all-my-view
|
dc87acd8f7fe01c914089ca8405c8fb0
| 41.51049 | 305 | 0.637276 | false | false | false | false |
ZTfer/FlagKit
|
refs/heads/master
|
Sources/FlagKitDemo-iOS/FlagsListViewController.swift
|
mit
|
2
|
//
// Copyright © 2017 Bowtie. All rights reserved.
//
import UIKit
import FlagKit
class FlagsListViewController: UITableViewController {
var style: FlagStyle = .none {
didSet {
tableView.reloadData()
}
}
let stylePicker: UISegmentedControl = {
let items = FlagStyle.all.map({ $0.name })
let control = UISegmentedControl(items: items)
control.selectedSegmentIndex = 0
return control
}()
let flags = Flag.all
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = stylePicker
tableView.backgroundColor = UIColor(red: 0.91, green: 0.96, blue: 0.97, alpha: 1.0)
tableView.separatorColor = UIColor.black.withAlphaComponent(0.1)
tableView.register(FlagTableViewCell.self, forCellReuseIdentifier: FlagTableViewCell.identifier)
stylePicker.addTarget(self, action: #selector(styleDidChange), for: .valueChanged)
}
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return flags.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FlagTableViewCell.identifier, for: indexPath)
let flag = flags[indexPath.row]
cell.textLabel?.text = flag.localizedName
cell.detailTextLabel?.text = flag.countryCode
cell.imageView?.image = flag.image(style: style)
return cell
}
// MARK: Private
@objc private func styleDidChange() {
style = FlagStyle(rawValue: stylePicker.selectedSegmentIndex)!
}
}
|
697013caf08ce7dbd850122ab80b9fd5
| 30.633333 | 110 | 0.651212 | false | false | false | false |
dsonara/DSImageCache
|
refs/heads/master
|
DSImageCache/Classes/Extensions/ImageView+DSImageCache.swift
|
mit
|
1
|
//
// ImageView+DSImageCache.swift
// DSImageCache
//
// Created by Dipak Sonara on 29/03/17.
// Copyright © 2017 Dipak Sonara. All rights reserved.
//
import UIKit
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension DSImageCache where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: DSImageCacheOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
base.image = placeholder
setWebURL(nil)
completionHandler?(nil, nil, .none, nil)
return .empty
}
var options = options ?? DSImageCacheEmptyOptionsInfo
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
if base.shouldPreloadAllGIF() {
options.append(.preloadAllGIFData)
}
let task = DSImageCacheManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL else {
return
}
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
return
}
self.setImageTask(nil)
guard let image = image else {
maybeIndicator?.stopAnimatingView()
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
maybeIndicator?.stopAnimatingView()
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension DSImageCache where Base: ImageView {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL?) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
newIndicator.view.frame = base.frame
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `ds` namespacing instead.
*/
extension ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.setImage` instead.", renamed: "ds.setImage")
@discardableResult
public func ds_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: DSImageCacheOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return ds.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.cancelDownloadTask` instead.", renamed: "ds.cancelDownloadTask")
public func ds_cancelDownloadTask() { ds.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.webURL` instead.", renamed: "ds.webURL")
public var ds_webURL: URL? { return ds.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.indicatorType` instead.", renamed: "ds.indicatorType")
public var ds_indicatorType: IndicatorType {
get { return ds.indicatorType }
set { ds.indicatorType = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.indicator` instead.", renamed: "ds.indicator")
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `ds_indicatorType` is `.none`.
public private(set) var ds_indicator: Indicator? {
get { return ds.indicator }
set { ds.indicator = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "ds.imageTask")
fileprivate var ds_imageTask: RetrieveImageTask? { return ds.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "ds.setImageTask")
fileprivate func ds_setImageTask(_ task: RetrieveImageTask?) { ds.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "ds.setWebURL")
fileprivate func ds_setWebURL(_ url: URL) { ds.setWebURL(url) }
}
extension ImageView {
func shouldPreloadAllGIF() -> Bool { return true }
}
|
2a7d721a83455ebc9c6afcc2c7fa585f
| 44.247191 | 173 | 0.589769 | false | false | false | false |
russelhampton05/MenMew
|
refs/heads/master
|
App Prototypes/App_Prototype_A_001/RegisterViewController.swift
|
mit
|
1
|
//
// RegisterViewController.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 9/28/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
import Firebase
class RegisterViewController: UIViewController, UITextFieldDelegate {
//IBOutlets
@IBOutlet var registerLabel: UILabel!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var emailLabel: UILabel!
@IBOutlet var passwordLabel: UILabel!
@IBOutlet var reenterLabel: UILabel!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
@IBOutlet weak var confirmRegisterButton: UIButton!
@IBOutlet var cancelButton: UIButton!
@IBOutlet var nameLine: UIView!
@IBOutlet var emailLine: UIView!
@IBOutlet var passwordLine: UIView!
@IBOutlet var reenterLine: UIView!
override func viewDidLoad() {
super.viewDidLoad()
usernameField.delegate = self
emailField.delegate = self
passwordField.delegate = self
confirmPasswordField.delegate = self
confirmRegisterButton.isEnabled = false
emailField.keyboardType = UIKeyboardType.emailAddress
passwordField.isSecureTextEntry = true
confirmPasswordField.isSecureTextEntry = true
usernameField.autocorrectionType = UITextAutocorrectionType.no
emailField.autocorrectionType = UITextAutocorrectionType.no
passwordField.autocorrectionType = UITextAutocorrectionType.no
confirmPasswordField.autocorrectionType = UITextAutocorrectionType.no
loadTheme()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
let nextResponder = textField.superview?.viewWithTag(nextTag)
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
}
else {
textField.resignFirstResponder()
}
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
if self.usernameField.text != "" && self.passwordField.text != "" && self.confirmPasswordField.text != "" {
confirmRegisterButton.isEnabled = true
}
}
@IBAction func registerButtonPressed(_ sender: AnyObject) {
if !self.emailField.hasText || !self.usernameField.hasText || !self.passwordField.hasText {
showPopup(message: "Please enter your name, email and password.", isRegister: false)
}
else if self.passwordField.text != self.confirmPasswordField.text {
showPopup(message: "Password entries do not match.", isRegister: false)
self.passwordField.text = ""
self.confirmPasswordField.text = ""
}
else {
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: {(user, error) in
if error == nil {
//Create associated entry on Firebase
let newUser = User(id: (user?.uid)!, email: (user?.email)!, name: self.usernameField.text!, ticket: nil, image: nil, theme: "Salmon", touchEnabled: true, notifications: true)
UserManager.UpdateUser(user: newUser)
currentUser = newUser
self.emailField.text = ""
self.passwordField.text = ""
self.confirmPasswordField.text = ""
self.showPopup(message: "Thank you for registering, " + self.usernameField.text! + "!", isRegister: true)
self.usernameField.text = ""
}
else {
self.showPopup(message: (error?.localizedDescription)!, isRegister: false)
}
})
}
}
@IBAction func cancelButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "UnwindToLoginSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "QRScanSegue" {
_ = segue.destination as! QRViewController
}
}
func showPopup(message: String, isRegister: Bool) {
let loginPopup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Popup") as! PopupViewController
if isRegister {
loginPopup.register = true
}
self.addChildViewController(loginPopup)
loginPopup.view.frame = self.view.frame
self.view.addSubview(loginPopup.view)
loginPopup.didMove(toParentViewController: self)
loginPopup.addMessage(context: message)
}
func loadTheme() {
currentTheme = Theme.init(type: "Salmon")
UIView.animate(withDuration: 0.8, animations: { () -> Void in
//Background and Tint
self.view.backgroundColor = currentTheme!.primary!
self.view.tintColor = currentTheme!.highlight!
//Labels
self.registerLabel.textColor = currentTheme!.highlight!
self.emailLine.backgroundColor = currentTheme!.highlight!
self.passwordLine.backgroundColor = currentTheme!.highlight!
self.nameLine.backgroundColor = currentTheme!.highlight!
self.reenterLine.backgroundColor = currentTheme!.highlight!
self.nameLabel.textColor = currentTheme!.highlight!
self.emailLabel.textColor = currentTheme!.highlight!
self.passwordLabel.textColor = currentTheme!.highlight!
self.reenterLabel.textColor = currentTheme!.highlight!
//Fields
self.usernameField.textColor = currentTheme!.highlight!
self.usernameField.tintColor = currentTheme!.highlight!
self.emailField.textColor = currentTheme!.highlight!
self.emailField.tintColor = currentTheme!.highlight!
self.passwordField.textColor = currentTheme!.highlight!
self.passwordField.tintColor = currentTheme!.highlight!
self.confirmPasswordField.textColor = currentTheme!.highlight!
self.confirmPasswordField.tintColor = currentTheme!.highlight!
//Buttons
self.confirmRegisterButton.backgroundColor = currentTheme!.highlight!
self.confirmRegisterButton.setTitleColor(currentTheme!.primary!, for: .normal)
self.cancelButton.backgroundColor = currentTheme!.highlight!
self.cancelButton.setTitleColor(currentTheme!.primary!, for: .normal)
})
}
}
|
eb036264db48d57420e5a226b07e0f4c
| 38.943503 | 194 | 0.625318 | false | false | false | false |
e78l/swift-corelibs-foundation
|
refs/heads/master
|
TestFoundation/TestProcessInfo.swift
|
apache-2.0
|
2
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
class TestProcessInfo : XCTestCase {
static var allTests: [(String, (TestProcessInfo) -> () throws -> Void)] {
return [
("test_operatingSystemVersion", test_operatingSystemVersion ),
("test_processName", test_processName ),
("test_globallyUniqueString", test_globallyUniqueString ),
("test_environment", test_environment),
]
}
func test_operatingSystemVersion() {
let processInfo = ProcessInfo.processInfo
let versionString = processInfo.operatingSystemVersionString
XCTAssertFalse(versionString.isEmpty)
let version = processInfo.operatingSystemVersion
XCTAssert(version.majorVersion != 0)
#if os(Linux) || canImport(Darwin)
let minVersion = OperatingSystemVersion(majorVersion: 1, minorVersion: 0, patchVersion: 0)
XCTAssertTrue(processInfo.isOperatingSystemAtLeast(minVersion))
#endif
}
func test_processName() {
// Assert that the original process name is "TestFoundation". This test
// will fail if the test target ever gets renamed, so maybe it should
// just test that the initial name is not empty or something?
#if DARWIN_COMPATIBILITY_TESTS
let targetName = "xctest"
#else
let targetName = "TestFoundation"
#endif
let processInfo = ProcessInfo.processInfo
let originalProcessName = processInfo.processName
XCTAssertEqual(originalProcessName, targetName, "\"\(originalProcessName)\" not equal to \"TestFoundation\"")
// Try assigning a new process name.
let newProcessName = "TestProcessName"
processInfo.processName = newProcessName
XCTAssertEqual(processInfo.processName, newProcessName, "\"\(processInfo.processName)\" not equal to \"\(newProcessName)\"")
// Assign back to the original process name.
processInfo.processName = originalProcessName
XCTAssertEqual(processInfo.processName, originalProcessName, "\"\(processInfo.processName)\" not equal to \"\(originalProcessName)\"")
}
func test_globallyUniqueString() {
let uuid = ProcessInfo.processInfo.globallyUniqueString
let parts = uuid.components(separatedBy: "-")
XCTAssertEqual(parts.count, 5)
XCTAssertEqual(parts[0].utf16.count, 8)
XCTAssertEqual(parts[1].utf16.count, 4)
XCTAssertEqual(parts[2].utf16.count, 4)
XCTAssertEqual(parts[3].utf16.count, 4)
XCTAssertEqual(parts[4].utf16.count, 12)
}
func test_environment() {
#if os(Windows)
func setenv(_ key: String, _ value: String, _ overwrite: Int) -> Int32 {
assert(overwrite == 1)
return putenv("\(key)=\(value)")
}
#endif
let preset = ProcessInfo.processInfo.environment["test"]
setenv("test", "worked", 1)
let postset = ProcessInfo.processInfo.environment["test"]
XCTAssertNil(preset)
XCTAssertEqual(postset, "worked")
// Bad values that wont be stored
XCTAssertEqual(setenv("", "", 1), -1)
XCTAssertEqual(setenv("bad1=", "", 1), -1)
XCTAssertEqual(setenv("bad2=", "1", 1) ,-1)
XCTAssertEqual(setenv("bad3=", "=2", 1), -1)
// Good values that will be, check splitting on '='
XCTAssertEqual(setenv("var1", "",1 ), 0)
XCTAssertEqual(setenv("var2", "=", 1), 0)
XCTAssertEqual(setenv("var3", "=x", 1), 0)
XCTAssertEqual(setenv("var4", "x=", 1), 0)
XCTAssertEqual(setenv("var5", "=x=", 1), 0)
let env = ProcessInfo.processInfo.environment
XCTAssertNil(env[""])
XCTAssertNil(env["bad1"])
XCTAssertNil(env["bad1="])
XCTAssertNil(env["bad2"])
XCTAssertNil(env["bad2="])
XCTAssertNil(env["bad3"])
XCTAssertNil(env["bad3="])
XCTAssertEqual(env["var1"], "")
XCTAssertEqual(env["var2"], "=")
XCTAssertEqual(env["var3"], "=x")
XCTAssertEqual(env["var4"], "x=")
XCTAssertEqual(env["var5"], "=x=")
}
}
|
327cdf32d8b7a0f16ba654454a2b5844
| 38.309735 | 142 | 0.6362 | false | true | false | false |
tarrgor/LctvSwift
|
refs/heads/master
|
Sources/LctvAuthViewController.swift
|
mit
|
1
|
//
// LctvAuthViewController.swift
// Pods
//
//
//
import UIKit
import OAuthSwift
public typealias CancelHandler = () -> ()
public final class LctvAuthViewController : OAuthWebViewController {
var webView: UIWebView = UIWebView()
var targetURL: NSURL = NSURL()
var toolbar: UIToolbar = UIToolbar()
var cancelItem: UIBarButtonItem?
public var onCancel: CancelHandler? = nil
public var toolbarTintColor: UIColor = UIColor.blackColor() {
didSet {
toolbar.barTintColor = toolbarTintColor
}
}
public var cancelButtonColor: UIColor = UIColor.whiteColor() {
didSet {
cancelItem?.tintColor = cancelButtonColor
}
}
public override func viewDidLoad() {
super.viewDidLoad()
// white status bar
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
webView.frame = self.view.bounds
webView.scalesPageToFit = true
webView.delegate = self
webView.backgroundColor = UIColor.blackColor()
view.addSubview(webView)
let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height
toolbar.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44 + statusBarHeight)
toolbar.barTintColor = toolbarTintColor
view.addSubview(toolbar)
cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(LctvAuthViewController.cancelButtonPressed(_:)))
cancelItem!.tintColor = UIColor.whiteColor()
toolbar.setItems([cancelItem!], animated: true)
loadAddressUrl()
}
public override func handle(url: NSURL) {
targetURL = url
super.handle(url)
loadAddressUrl()
}
func loadAddressUrl() {
let req = NSURLRequest(URL: targetURL)
webView.loadRequest(req)
}
func cancelButtonPressed(sender: UIBarButtonItem) {
if let callback = onCancel {
callback()
}
self.dismissWebViewController()
}
}
extension LctvAuthViewController : UIWebViewDelegate {
public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.URL where (url.host == "localhost"){
self.dismissWebViewController()
}
return true
}
}
|
492af2a13e670916f4163c8fbb40715d
| 25.229885 | 143 | 0.707274 | false | false | false | false |
matthewcheok/JSONCodable
|
refs/heads/master
|
JSONCodableTests/PropertyItem.swift
|
mit
|
1
|
//
// PropertyItem.swift
// JSONCodable
//
// Created by Richard Fox on 6/19/16.
//
//
import JSONCodable
struct PropertyItem {
let name: String
let long: Double
let lat: Double
let rel: String
let type: String
}
extension PropertyItem: JSONDecodable {
init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
rel = try decoder.decode("rel")
type = try decoder.decode("class")
name = try decoder.decode("properties.name")
long = try decoder.decode("properties.location.coord.long")
lat = try decoder.decode("properties.location.coord.lat")
}
}
extension PropertyItem: JSONEncodable {
func toJSON() throws -> Any {
return try JSONEncoder.create { (encoder) -> Void in
try encoder.encode(rel, key: "rel")
try encoder.encode(type, key: "class")
try encoder.encode(name, key: "properties.name")
try encoder.encode(long, key: "properties.location.coord.long")
try encoder.encode(lat, key: "properties.location.coord.lat")
}
}
}
|
724ed36083fc74db45acb405d40d91db
| 26.725 | 75 | 0.629396 | false | false | false | false |
backslash112/DPEContainer
|
refs/heads/master
|
Example/DPEContainer/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// DPEContainer
//
// Created by backslash112 on 09/18/2015.
// Copyright (c) 2015 backslash112. All rights reserved.
//
import UIKit
import DPEContainer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let container = DPEContainer(frame: self.view.frame)
container.backgroundColor = UIColor.lightGrayColor()
let view1 = UIView(frame: CGRectMake(0, 0, 100, 100))
view1.backgroundColor = UIColor.redColor()
container.addElement(view1)
let view2 = UIView(frame: CGRectMake(0, 0, 50, 100))
view2.backgroundColor = UIColor.greenColor()
container.addElement(view2)
let view3 = UIView(frame: CGRectMake(0, 0, 150, 100))
view3.backgroundColor = UIColor.yellowColor()
container.addElement(view3)
let view4 = UIView(frame: CGRectMake(0, 0, 70, 100))
view4.backgroundColor = UIColor.blueColor()
container.addElement(view4)
let view5 = UIView(frame: CGRectMake(0, 0, 40, 100))
view5.backgroundColor = UIColor.yellowColor()
container.addElement(view5)
let view6 = UIView(frame: CGRectMake(0, 0, 80, 100))
view6.backgroundColor = UIColor.purpleColor()
container.addElement(view6)
let view7 = UIView(frame: CGRectMake(0, 0, 200, 100))
view7.backgroundColor = UIColor.orangeColor()
container.addElement(view7)
let view8 = UIView(frame: CGRectMake(0, 0, 90, 100))
view8.backgroundColor = UIColor.magentaColor()
container.addElement(view8)
//container.elements = [view1, view2, view3, view4, view5]
self.view.addSubview(container)
}
}
|
fcb868bac08ec629839c64b6e5e1261f
| 32.438596 | 80 | 0.63064 | false | false | false | false |
Sticky-Gerbil/furry-adventure
|
refs/heads/master
|
FurryAdventure/API/SpoonacularApiClient.swift
|
apache-2.0
|
1
|
////
//// SpoonacularApiClient.swift
//// FurryAdventure
////
//// Created by Edwin Young on 3/27/17.
//// Copyright © 2017 Sticky Gerbils. All rights reserved.
////
//
//import UIKit
//import AFNetworking
//
//class SpoonacularApiClient: RecipeApiClient, RecipeApiProtocol {
//
// static let shared = SpoonacularApiClient(baseUrlString: "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes", key: "SpoonacularKey", app: nil)
//
// override init(baseUrlString: String!, key: String!, app: String?) {
// super.init(baseUrlString: baseUrlString, key: key, app: app)
//
// EP_RECIPES_SEARCH = "/findByIngredients"
// EP_RECIPE_SEARCH = "/information"
// }
//
// // API requests to Spoonacular API require HTTP headers instead of passing via query string; specifically
// // X-Mashape-Key: ${SPOONACULAR_KEY}
// // Accept: application/json
// func findRecipes(by ingredients: [Ingredient]?) -> [Recipe]? {
// // Modify request headers for API calls
// let requestSerializer = AFNetworking.AFHTTPRequestSerializer()
// requestSerializer.setValue(apiKey!, forHTTPHeaderField: "X-Mashape-Key")
// requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
//
// // Set up API endpoint calls & query string params
// var urlString = apiUrlString + EP_RECIPES_SEARCH + "?";
// var params = [
// "fillIngredients": "false",
// "limitLicense": "false",
// "number": "10",
// "ranking": "2" // this is to minimize the number of missing ingredients
// ]
//
// // API takes the ingredients as a list of comma separated values
// if ingredients != nil && ingredients!.count >= 1 {
// params["ingredients"] = ingredients![0].name
// for i in 1..<ingredients!.count {
// params["ingredients"] = params["ingredients"]! + "," + ingredients![i].name
// }
// } else {
// return nil
// }
//
// // Create & URL encode the ingredients values
// var queryString = ""
// for (key, value) in params {
// queryString = queryString + "\(key)=\(value)&"
// }
// queryString = queryString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
// urlString = urlString + queryString
//
// // Call the API endpoint
// let request = requestSerializer.request(withMethod: "GET", urlString: urlString, parameters: nil, error: nil)
// let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
// let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data: Data?, response: URLResponse?, error: Error?) in
// if let data = data {
// if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// print(dataDictionary)
//
// // Can't even run this bit of code
// // Maybe look into this? Would bypass AFNetworking.AFHTTPRequestSerializer entirely
// // http://stackoverflow.com/a/37245658
// }
// }
// }
// task.resume()
// }
//
// func findRecipe(by id: String!) -> Recipe? {
// let requestSerializer = AFNetworking.AFHTTPRequestSerializer()
// requestSerializer.setValue(apiKey!, forHTTPHeaderField: "X-Mashape-Key")
// requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
//
// // Set up API endpoint calls
// var urlString = apiUrlString + "/" + id + EP_RECIPES_SEARCH;
//
// // Call the API endpoint
// let request = requestSerializer.request(withMethod: "GET", urlString: urlString, parameters: nil, error: nil)
// let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
// let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data: Data?, response: URLResponse?, error: Error?) in
// if let data = data {
// if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// print(dataDictionary)
//
// // Can't even run this bit of code
// }
// }
// }
// task.resume()
//
// return nil
// }
//
//
//
//}
|
c5474b1a837144dec20377924c1194e6
| 37.834951 | 161 | 0.674 | false | false | false | false |
artyom-stv/TextInputKit
|
refs/heads/develop
|
TextInputKit/TextInputKit/Code/TextInputFormat/TextInputFormat+Filter.swift
|
mit
|
1
|
//
// TextInputFormat+Filter.swift
// TextInputKit
//
// Created by Artem Starosvetskiy on 24/11/2016.
// Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//
import Foundation
public extension TextInputFormat {
typealias FilterPredicate = TextInputFormatterType.FilterPredicate
/// Creates a `TextInputFormat` which filters the output of the source formatter
/// (the formatter of the callee format).
///
/// - Parameters:
/// - predicate: The predicate which is used to filter the output of the source formatter.
/// - Returns: The created `TextInputFormat`.
func filter(_ predicate: @escaping FilterPredicate) -> TextInputFormat<Value> {
return TextInputFormat.from(
serializer,
formatter.filter(predicate))
}
}
public extension TextInputFormat {
/// Creates a `TextInputFormat` with a formatter which rejects the output of the source formatter
/// (the formatter of the callee format) if the output contains characters out of the `characterSet`.
///
/// - Parameters:
/// - characterSet: The character set which is used to filter the output of the source formatter.
/// - Returns: The created `TextInputFormat`.
func filter(by characterSet: CharacterSet) -> TextInputFormat<Value> {
let invertedCharacterSet = characterSet.inverted
return filter {
string in
return string.rangeOfCharacter(from: invertedCharacterSet) == nil
}
}
/// Creates a `TextInputFormat` with a formatter which rejects the output of the source formatter
/// (the formatter of the callee format) if the output exceeds the `maxCharactersCount` limit.
///
/// - Parameters:
/// - maxCharactersCount: The maximum characters count which is used to filter the output of the source formatter.
/// - Returns: The created `TextInputFormat`.
func filter(constrainingCharactersCount maxCharactersCount: Int) -> TextInputFormat<Value> {
return filter {
string in
return (string.count <= maxCharactersCount)
}
}
}
|
986e2cfed7290991de878824ec353586
| 34.516667 | 120 | 0.679962 | false | false | false | false |
humblehacker/BarFun
|
refs/heads/master
|
BarFun/FunViewController.swift
|
mit
|
1
|
//
// FunViewController.swift
// BarFun
//
// Created by David Whetstone on 1/11/16.
// Copyright (c) 2016 humblehacker. All rights reserved.
//
import UIKit
class FunViewController: UIViewController
{
override func viewDidLoad()
{
title = "BarFun"
view.backgroundColor = UIColor.redColor()
view.layer.borderColor = UIColor.blackColor().CGColor
view.layer.borderWidth = 2.0
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Present", style: .Plain, target: self, action: "present")
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Dismiss", style: .Plain, target: self, action: "dismiss")
addCenterView()
}
func addCenterView()
{
let centerView = UIView()
centerView.backgroundColor = UIColor.orangeColor()
view.addSubview(centerView)
centerView.snp_makeConstraints
{
make in
make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
}
func present()
{
let nc = UINavigationController(rootViewController: FunViewController())
presentViewController(nc, animated: true, completion: nil)
}
func dismiss()
{
dismissViewControllerAnimated(true, completion: nil)
}
}
|
494ad083ed2e3058b3c892e4a54e8c4b
| 25.16 | 125 | 0.648318 | false | false | false | false |
abunur/quran-ios
|
refs/heads/master
|
Quran/TranslationPageLayoutOperation.swift
|
gpl-3.0
|
2
|
//
// TranslationPageLayoutOperation.swift
// Quran
//
// Created by Mohamed Afifi on 4/1/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import PromiseKit
import UIKit
class TranslationPageLayoutOperation: AbstractPreloadingOperation<TranslationPageLayout> {
let page: TranslationPage
let width: CGFloat
init(request: TranslationPageLayoutRequest) {
self.page = request.page
self.width = request.width - Layout.Translation.horizontalInset * 2
}
override func main() {
autoreleasepool {
let verseLayouts = page.verses.map { verse -> TranslationVerseLayout in
let arabicPrefixLayouts = verse.arabicPrefix.map { arabicLayoutFrom($0) }
let arabicSuffixLayouts = verse.arabicSuffix.map { arabicLayoutFrom($0) }
return TranslationVerseLayout(ayah: verse.ayah,
arabicTextLayout: arabicLayoutFrom(verse.arabicText),
translationLayouts: verse.translations.map { translationTextLayoutFrom($0) },
arabicPrefixLayouts: arabicPrefixLayouts,
arabicSuffixLayouts: arabicSuffixLayouts)
}
let pageLayout = TranslationPageLayout(pageNumber: page.pageNumber, verseLayouts: verseLayouts)
fulfill(pageLayout)
}
}
private func arabicLayoutFrom(_ text: String) -> TranslationArabicTextLayout {
let size = text.size(withFont: .translationArabicQuranText, constrainedToWidth: width)
return TranslationArabicTextLayout(arabicText: text, size: size)
}
private func translationTextLayoutFrom(_ text: TranslationText) -> TranslationTextLayout {
let translatorSize = text.translation.translationName.size(withFont: text.translation.preferredTranslatorNameFont, constrainedToWidth: width)
if text.isLongText {
return longTranslationTextLayoutFrom(text, translatorSize: translatorSize)
} else {
return shortTranslationTextLayoutFrom(text, translatorSize: translatorSize)
}
}
private func shortTranslationTextLayoutFrom(_ text: TranslationText, translatorSize: CGSize) -> TranslationTextLayout {
let size = text.attributedText.stringSize(constrainedToWidth: width)
return TranslationTextLayout(text: text, size: size, longTextLayout: nil, translatorSize: translatorSize)
}
private func longTranslationTextLayoutFrom(_ text: TranslationText, translatorSize: CGSize) -> TranslationTextLayout {
// create the main objects
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize(width: width, height: .infinity))
textContainer.lineFragmentPadding = 0
let textStorage = NSTextStorage(attributedString: text.attributedText)
// connect the objects together
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
// get number of glyphs
let numberOfGlyphs = layoutManager.numberOfGlyphs
let range = NSRange(location: 0, length: numberOfGlyphs)
// get the size in screen
let bounds = layoutManager.boundingRect(forGlyphRange: range, in: textContainer)
let size = CGSize(width: width, height: ceil(bounds.height))
let textLayout = LongTranslationTextLayout(textContainer: textContainer, numberOfGlyphs: numberOfGlyphs)
return TranslationTextLayout(text: text, size: size, longTextLayout: textLayout, translatorSize: translatorSize)
}
}
|
d68e18e9886bbe82ca53282227ed97cd
| 44.641304 | 149 | 0.699929 | false | false | false | false |
crspybits/SyncServerII
|
refs/heads/dev
|
Sources/Server/Database/Repositories.swift
|
mit
|
1
|
//
// Repositories.swift
// Server
//
// Created by Christopher Prince on 2/7/17.
//
//
import Foundation
struct Repositories {
let db: Database
lazy var user = UserRepository(db)
lazy var masterVersion = MasterVersionRepository(db)
lazy var fileIndex = FileIndexRepository(db)
lazy var upload = UploadRepository(db)
lazy var deviceUUID = DeviceUUIDRepository(db)
lazy var sharing = SharingInvitationRepository(db)
lazy var sharingGroup = SharingGroupRepository(db)
lazy var sharingGroupUser = SharingGroupUserRepository(db)
init(db: Database) {
self.db = db
}
}
|
e012649567d82ff9de64f67f5adba3c6
| 23.230769 | 62 | 0.698413 | false | false | false | false |
spacedrabbit/100-days
|
refs/heads/master
|
masks.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
import CoreGraphics
var str = "Hello, playground"
func drawARect() -> UIView {
let view: UIView = UIView(frame: CGRectMake(0.0, 0.0, 100.0, 200.0))
view.backgroundColor = UIColor.yellowColor()
let interiorView: UIView = UIView(frame: CGRectInset(view.frame, 10.0, 10.0))
interiorView.backgroundColor = UIColor.redColor()
view.addSubview(interiorView)
let bezier: UIBezierPath = getSomeCurves()
let mask: CAShapeLayer = makeTheMask(forPath: bezier)
// interiorView.layer.addSublayer(mask)
return view
}
func getSomeCurves() -> UIBezierPath {
let transparentFrame: CGRect = CGRectMake(5.0, 5.0, 20.0, 50.0)
let maskLayerPathBase: UIBezierPath = UIBezierPath(roundedRect: transparentFrame, cornerRadius: 5.0)
let maskLayerPathDefined: UIBezierPath = UIBezierPath(roundedRect: CGRectInset(transparentFrame, 4.0, 4.0), cornerRadius: 4.0)
maskLayerPathBase.appendPath(maskLayerPathDefined)
return maskLayerPathBase
}
func makeTheMask(forPath path: UIBezierPath) -> CAShapeLayer {
let transparentFrameLocation = path.bounds
let maskLayer: CAShapeLayer = CAShapeLayer()
maskLayer.bounds = transparentFrameLocation
maskLayer.frame = transparentFrameLocation
maskLayer.path = path.CGPath
maskLayer.backgroundColor = UIColor.whiteColor().CGColor
maskLayer.fillRule = kCAFillRuleEvenOdd
return maskLayer
}
let rects: UIView = drawARect()
|
c125263b4c8f3ee67f3f525cbc22c453
| 28.36 | 128 | 0.756812 | false | false | false | false |
material-motion/material-motion-swift
|
refs/heads/develop
|
Pods/MaterialMotion/src/operators/gestures/scaled.swift
|
apache-2.0
|
2
|
/*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
extension MotionObservableConvertible where T: UIPinchGestureRecognizer {
/**
Multiplies the current scale by the initial scale and emits the result while the gesture
recognizer is active.
*/
func scaled<O: MotionObservableConvertible>(from initialScale: O) -> MotionObservable<CGFloat> where O.T == CGFloat {
var cachedInitialScale: CGFloat?
var lastInitialScale: CGFloat?
return MotionObservable { observer in
let initialScaleSubscription = initialScale.subscribeToValue { lastInitialScale = $0 }
let upstreamSubscription = self.subscribeAndForward(to: observer) { value in
if value.state == .began || (value.state == .changed && cachedInitialScale == nil) {
cachedInitialScale = lastInitialScale
} else if value.state != .began && value.state != .changed {
cachedInitialScale = nil
}
if let cachedInitialScale = cachedInitialScale {
let scale = value.scale
observer.next(cachedInitialScale * scale)
}
}
return {
upstreamSubscription.unsubscribe()
initialScaleSubscription.unsubscribe()
}
}
}
}
|
207b83975ecdf6b99b32a1c58ff9bc3f
| 33.692308 | 119 | 0.714523 | false | false | false | false |
multinerd/Mia
|
refs/heads/master
|
Mia/Testing/Material/MaterialColorGroupWithAccents.swift
|
mit
|
1
|
//
// MaterialColorGroupWithAccents.swift
// Mia
//
// Created by Michael Hedaitulla on 8/2/18.
//
import Foundation
open class MaterialColorGroupWithAccents: MaterialColorGroup {
open let A100: MaterialColor
open let A200: MaterialColor
open let A400: MaterialColor
open let A700: MaterialColor
open var accents: [MaterialColor] {
return [A100, A200, A400, A700]
}
open override var hashValue: Int {
return super.hashValue + accents.reduce(0) { $0 + $1.hashValue }
}
open override var endIndex: Int {
return colors.count + accents.count
}
open override subscript(i: Int) -> MaterialColor {
return (colors + accents)[i]
}
internal init(name: String,
_ P50: MaterialColor,
_ P100: MaterialColor,
_ P200: MaterialColor,
_ P300: MaterialColor,
_ P400: MaterialColor,
_ P500: MaterialColor,
_ P600: MaterialColor,
_ P700: MaterialColor,
_ P800: MaterialColor,
_ P900: MaterialColor,
_ A100: MaterialColor,
_ A200: MaterialColor,
_ A400: MaterialColor,
_ A700: MaterialColor
) {
self.A100 = A100
self.A200 = A200
self.A400 = A400
self.A700 = A700
super.init(name: name, P50, P100, P200, P300, P400, P500, P600, P700, P800, P900)
}
open override func colorForName(_ name: String) -> MaterialColor? {
return (colors + accents).filter { $0.name == name}.first
}
}
func ==(lhs: MaterialColorGroupWithAccents, rhs: MaterialColorGroupWithAccents) -> Bool {
return (lhs as MaterialColorGroup) == (rhs as MaterialColorGroup) &&
lhs.accents == rhs.accents
}
|
66f93fa354de1c22ce4e0020d0efbec3
| 29.174603 | 89 | 0.56181 | false | false | false | false |
ahayman/RxStream
|
refs/heads/master
|
RxStreamTests/StreamProcessorTests.swift
|
mit
|
1
|
//
// StreamProcessorTests.swift
// RxStream
//
// Created by Aaron Hayman on 4/21/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import XCTest
@testable import Rx
class StreamProcessorTests: XCTestCase {
func testProcessorDoNothing() {
let processor = StreamProcessor<Int>(stream: HotInput<Int>())
processor.process(next: .next(1), withKey: .share)
XCTAssertTrue(true)
}
func testDownStreamProcessorStreamVariable() {
let stream = HotInput<Int>()
let processor = DownstreamProcessor<Int, Int>(stream: stream) { _, _ in }
XCTAssertEqual(stream.id, (processor.stream as! Hot<Int>).id)
}
func testDownStreamProcessorWork() {
var events = [Event<Int>]()
let stream = HotInput<Int>()
let processor = DownstreamProcessor<Int, Int>(stream: stream) { event, _ in
events.append(event)
}
processor.process(next: .next(0), withKey: .share)
XCTAssertEqual(events.count, 1)
processor.process(next: .next(0), withKey: .share)
XCTAssertEqual(events.count, 2)
}
}
|
f2e717ee8fa7f616de22162c9e3be661
| 24.047619 | 79 | 0.681559 | false | true | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Money/Tests/MoneyKitTests/Balance/CryptoCurrencyTests.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
@testable import MoneyKitMock
import XCTest
class CryptoCurrencyTests: XCTestCase {
private var cryptoCurrencyDesiredOrder: [CryptoCurrency] {
[
.bitcoin,
.ethereum,
.bitcoinCash,
.stellar,
.mockCoin(symbol: "A", displaySymbol: "A", name: "Custodial 1", sortIndex: 5),
.mockCoin(symbol: "B", displaySymbol: "B", name: "Custodial 2", sortIndex: 11),
.mockCoin(symbol: "C", displaySymbol: "C", name: "Custodial 3", sortIndex: 12),
.mockCoin(symbol: "D", displaySymbol: "D", name: "Custodial 4", sortIndex: 13),
.mockERC20(symbol: "E", displaySymbol: "E", name: "ERC20 1", sortIndex: 0),
.mockERC20(symbol: "F", displaySymbol: "F", name: "ERC20 2", sortIndex: 1),
.mockERC20(symbol: "G", displaySymbol: "G", name: "ERC20 3", sortIndex: 2),
.mockERC20(symbol: "H", displaySymbol: "H", name: "ERC20 4", sortIndex: 3),
.mockERC20(symbol: "I", displaySymbol: "I", name: "ERC20 5", sortIndex: 4)
]
}
func testSortedCryptoCurrencyArrayIsInCorrectOrder() {
XCTAssertTrue(
cryptoCurrencyDesiredOrder.shuffled().sorted() == cryptoCurrencyDesiredOrder,
"sut.allEnabledCryptoCurrencies.sorted() is not as expected."
)
}
func testUniquenessERC20AssetModelIsBasedSolelyOnSymbol() {
let currencies: [AssetModel] = [
.mockERC20(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0),
.mockERC20(symbol: "A", displaySymbol: "X", name: "X", sortIndex: 1),
.mockERC20(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2)
]
let unique = currencies.unique
XCTAssertEqual(unique.count, 2)
let set = Set(currencies)
XCTAssertEqual(set.count, 2)
}
func testUniquenessCoinAssetModelIsBasedSolelyOnSymbol() {
let currencies: [AssetModel] = [
.mockCoin(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0),
.mockCoin(symbol: "A", displaySymbol: "X", name: "X", sortIndex: 1),
.mockCoin(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2)
]
let unique = currencies.unique
XCTAssertEqual(unique.count, 2)
let set = Set(currencies)
XCTAssertEqual(set.count, 2)
}
func testUniquenessCryptoCurrencyIsBasedSolelyOnSymbol() {
let currencies: [CryptoCurrency] = [
.mockERC20(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0),
.mockERC20(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 1),
.mockERC20(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2),
.mockCoin(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0),
.mockCoin(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 1),
.mockCoin(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2)
]
let unique = currencies.unique
XCTAssertEqual(unique.count, 2)
let set = Set(currencies)
XCTAssertEqual(set.count, 2)
}
}
|
c51ea750fa0caeb936dc0a0e250ef368
| 43.611111 | 91 | 0.5934 | false | true | false | false |
jpchmura/JPCPaperViewController
|
refs/heads/master
|
Source/PaperCollectionViewLayout.swift
|
mit
|
1
|
//
// PaperCollectionViewLayout.swift
// PaperExample
//
// Created by Jon Chmura on 1/31/15.
// Copyright (c) 2015 Thinkering. All rights reserved.
//
import UIKit
public class PaperCollectionViewLayout: UICollectionViewLayout {
internal var _itemSize = CGSizeZero
public var itemSize: CGSize {
get {
return CGSizeZero
}
}
public var activeSection: Int = 0 {
didSet {
self.invalidateLayout()
}
}
public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
if self.collectionView == nil {
return false
}
return !CGSizeEqualToSize(self.collectionView!.frame.size, newBounds.size)
}
internal var attrByPath = [NSIndexPath : UICollectionViewLayoutAttributes]()
internal var totalContentWidth: CGFloat = 0.0
public override func collectionViewContentSize() -> CGSize {
if self.collectionView == nil {
return CGSizeZero
}
return CGSizeMake(totalContentWidth, self.collectionView!.frame.height - UIApplication.sharedApplication().statusBarFrame.height)
}
public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var result = [AnyObject]()
for (indexPath , attr) in self.attrByPath {
if (indexPath.section == self.activeSection) && CGRectIntersectsRect(rect, attr.frame) {
result.append(attr)
}
}
return result
}
public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
return self.attrByPath[indexPath]
}
}
|
8206f9ad02c0cd0dc2342d603dbc08f9
| 27.516129 | 137 | 0.63405 | false | false | false | false |
coderwhy/DouYuZB
|
refs/heads/master
|
DYZB/DYZB/Classes/Home/Controller/AmuseViewController.swift
|
mit
|
1
|
//
// AmuseViewController.swift
// DYZB
//
// Created by 1 on 16/10/10.
// Copyright © 2016年 小码哥. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorViewController {
// MARK: 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
}
// MARK:- 设置UI界面
extension AmuseViewController {
override func setupUI() {
super.setupUI()
// 将菜单的View添加到collectionView中
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 请求数据
extension AmuseViewController {
override func loadData() {
// 1.给父类中ViewModel进行赋值
baseVM = amuseVM
// 2.请求数据
amuseVM.loadAmuseData {
// 2.1.刷新表格
self.collectionView.reloadData()
// 2.2.调整数据
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
// 3.数据请求完成
self.loadDataFinished()
}
}
}
|
958cdf63b6beda9ebf46dd8eddc7d780
| 22.762712 | 97 | 0.600571 | false | false | false | false |
aestesis/Aether
|
refs/heads/master
|
Sources/Aether/Foundation/Size.swift
|
apache-2.0
|
1
|
//
// Size.swift
// Aether
//
// Created by renan jegouzo on 23/02/2016.
// Copyright © 2016 aestesis. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import SwiftyJSON
#if os(macOS) || os(iOS) || os(tvOS)
import CoreGraphics
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Size : CustomStringConvertible,JsonConvertible {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var width:Double
public var height:Double
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var w:Double {
get { return width; }
set(w) { width=w; }
}
public var h:Double {
get { return height; }
set(h) { height=h; }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var ceil: Size {
return Size(Foundation.ceil(width),Foundation.ceil(height))
}
public func crop(_ ratio:Double,margin:Double=0) -> Size {
let dd = ratio
let ds = self.ratio
if ds>dd {
let h=height-margin*2;
let w=dd*h;
return Size(w,h);
} else {
let w=width-margin*2;
let h=w/dd;
return Size(w,h);
}
}
public func extend(_ border:Double) -> Size {
return Size(width+border*2,height+border*2)
}
public func extend(w:Double,h:Double) -> Size {
return Size(width+w*2,height+h*2)
}
public func extend(_ sz:Size) -> Size {
return self + sz*2
}
public var int: SizeI {
return SizeI(Int(width),Int(height))
}
public var floor: Size {
return Size(Foundation.floor(width),Foundation.floor(height))
}
public var length: Double {
return sqrt(width*width+height*height)
}
public func lerp(_ to:Size,coef:Double) -> Size {
return Size(to.width*coef+width*(1-coef),to.height*coef+height*(1-coef))
}
public var normalize: Size {
return Size(width/length,height/length)
}
public func point(_ px:Double,_ py:Double) -> Point {
return Point(width*px,height*py)
}
public var point: Point {
return Point(width,height)
}
public func point(px:Double,py:Double) -> Point {
return Point(width*px,height*py)
}
public var ratio: Double {
return width/height
}
public var round: Size {
return Size(Foundation.round(width),Foundation.round(height))
}
public var rotate: Size {
return Size(height,width)
}
public func scale(_ scale:Double) -> Size {
return Size(width*scale,height*scale)
}
public func scale(_ w:Double,_ h:Double) -> Size {
return Size(width*w,height*h)
}
public var surface:Double {
return width*height;
}
public var transposed:Size {
return Size(h,w)
}
public var description: String {
return "{w:\(width),h:\(height)}"
}
public var json: JSON {
return JSON([w:w,h:h])
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(_ s:CGSize) {
width=Double(s.width)
height=Double(s.height)
}
public init(_ s:SizeI) {
width=Double(s.width)
height=Double(s.height)
}
public init(_ p:PointI) {
width=Double(p.x)
height=Double(p.y)
}
public init(_ square:Double) {
width=square;
height=square;
}
public init(_ w:Double,_ h:Double) {
width=w;
height=h;
}
public init(_ w:Int,_ h:Int) {
width=Double(w);
height=Double(h);
}
public init(json: JSON) {
if let w=json["width"].double {
width=w
} else if let w=json["w"].double {
width=w
} else {
width=0;
}
if let h=json["height"].double {
height=h
} else if let h=json["h"].double {
height=h
} else {
height=0;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var system : CGSize {
return CGSize(width:CGFloat(w),height: CGFloat(h))
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public static var zero: Size {
return Size(0,0)
}
public static var infinity: Size {
return Size(Double.infinity,Double.infinity)
}
public static var unity: Size {
return Size(1,1)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func ==(lhs: Size, rhs: Size) -> Bool {
return (lhs.width==rhs.width)&&(lhs.height==rhs.height);
}
public func !=(lhs: Size, rhs: Size) -> Bool {
return (lhs.width != rhs.width)||(lhs.height != rhs.height);
}
public func +(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w+rhs.w),(lhs.h+rhs.h));
}
public func -(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w-rhs.w),(lhs.h-rhs.h));
}
public func *(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w*rhs.w),(lhs.h*rhs.h));
}
public func *(lhs: Size, rhs: Double) -> Size {
return Size((lhs.w*rhs),(lhs.h*rhs));
}
public func /(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w/rhs.w),(lhs.h/rhs.h));
}
public func /(lhs: Size, rhs: Double) -> Size {
return Size((lhs.w/rhs),(lhs.h/rhs));
}
public prefix func - (size: Size) -> Size {
return Size(-size.w,-size.h)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct SizeI {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var width:Int
public var height:Int
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var w:Int {
get { return width; }
set(w) { width=w; }
}
public var h:Int {
get { return height; }
set(h) { height=h; }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var point: PointI {
return PointI(x:width,y:height)
}
public var surface:Int {
return width*height;
}
public var description: String {
return "{w:\(width),h:\(height)}"
}
public var json: JSON {
return JSON.parse(string: description)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(_ w:Int,_ h:Int) {
width=w;
height=h;
}
public init(json: JSON) {
if let w=json["width"].number {
width=Int(truncating:w)
} else if let w=json["w"].number {
width=Int(truncating:w)
} else {
width=0;
}
if let h=json["height"].number {
height=Int(truncating:h)
} else if let h=json["h"].number {
height=Int(truncating:h)
} else {
height=0;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public static var zero: SizeI {
return SizeI(0,0)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func ==(lhs: SizeI, rhs: SizeI) -> Bool {
return (lhs.width==rhs.width)&&(lhs.height==rhs.height);
}
public func !=(lhs: SizeI, rhs: SizeI) -> Bool {
return (lhs.width != rhs.width)||(lhs.height != rhs.height);
}
public func +(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w+rhs.w),(lhs.h+rhs.h));
}
public func -(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w-rhs.w),(lhs.h-rhs.h));
}
public func *(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w*rhs.w),(lhs.h*rhs.h));
}
public func *(lhs: SizeI, rhs: Int) -> SizeI {
return SizeI((lhs.w*rhs),(lhs.h*rhs));
}
public func /(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w/rhs.w),(lhs.h/rhs.h));
}
public func /(lhs: SizeI, rhs: Int) -> SizeI {
return SizeI((lhs.w/rhs),(lhs.h/rhs));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
|
297782f47036763d0b4829330b0473fb
| 35.964169 | 110 | 0.370021 | false | false | false | false |
ReactiveKit/ReactiveKit
|
refs/heads/master
|
Sources/SignalProtocol+Result.swift
|
mit
|
1
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016-2019 Srdan Rasic (@srdanrasic)
//
// 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
extension SignalProtocol {
/// Map element into a result, propagating success value as a next event or failure as a failed event.
/// Shorthand for `map(transform).getValues()`.
public func tryMap<U>(_ transform: @escaping (Element) -> Result<U, Error>) -> Signal<U, Error> {
return map(transform).getValues()
}
}
extension SignalProtocol where Error == Never {
/// Map element into a result, propagating success value as a next event or failure as a failed event.
/// Shorthand for `map(transform).getValues()`.
public func tryMap<U, E>(_ transform: @escaping (Element) -> Result<U, E>) -> Signal<U, E> {
return castError().map(transform).getValues()
}
}
extension SignalProtocol where Element: _ResultProtocol {
/// Map inner result.
/// Shorthand for `map { $0.map(transform) }`.
public func mapValue<NewSuccess>(_ transform: @escaping (Element.Value) -> NewSuccess) -> Signal<Result<NewSuccess, Element.Error>, Error> {
return map { $0._unbox.map(transform) }
}
}
extension SignalProtocol where Element: _ResultProtocol, Error == Element.Error {
/// Unwraps values from result elements into elements of the signal.
/// A failure result will trigger signal failure.
public func getValues() -> Signal<Element.Value, Error> {
return Signal { observer in
return self.observe { event in
switch event {
case .next(let result):
switch result._unbox {
case .success(let element):
observer.next(element)
case .failure(let error):
observer.failed(error)
}
case .completed:
observer.completed()
case .failed(let error):
observer.failed(error)
}
}
}
}
}
extension SignalProtocol where Element: _ResultProtocol, Error == Never {
/// Unwraps values from result elements into elements of the signal.
/// A failure result will trigger signal failure.
public func getValues() -> Signal<Element.Value, Element.Error> {
return (castError() as Signal<Element, Element.Error>).getValues()
}
}
public protocol _ResultProtocol {
associatedtype Value
associatedtype Error: Swift.Error
var _unbox: Result<Value, Error> { get }
}
extension Result: _ResultProtocol {
public var _unbox: Result {
return self
}
}
|
f15eb34dc4d24440fd9cbfb94ddaeab0
| 36.646465 | 144 | 0.654682 | false | false | false | false |
CodePath2017Group4/travel-app
|
refs/heads/master
|
RoadTripPlanner/TripCell.swift
|
mit
|
1
|
//
// TripCell.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/10/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
class TripCell: UITableViewCell {
@IBOutlet weak var tripImageView: UIImageView!
@IBOutlet weak var tripTitleLabel: UILabel!
@IBOutlet weak var profileImg1: UIImageView!
@IBOutlet weak var profileImg2: UIImageView!
@IBOutlet weak var profileImg3: UIImageView!
var tripCell: TripCell! {
didSet {
if let tripTitle = tripCell.tripTitleLabel {
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
tripImageView.image = UIImage(named: "sf")
tripImageView?.layer.cornerRadius = 3.0
tripImageView?.layer.masksToBounds = true
profileImg1.layer.cornerRadius = profileImg1.frame.height / 2
profileImg2.layer.cornerRadius = profileImg2.frame.height / 2
profileImg3.layer.cornerRadius = profileImg3.frame.height / 2
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
8fc0a2432cc216fa307277bf96274d99
| 22.75 | 69 | 0.607519 | false | false | false | false |
Zero-Xiong/GoogleMapKit
|
refs/heads/master
|
GoogleMapKit/Models/PlaceMarker.swift
|
gpl-3.0
|
1
|
//
// PlaceMarker.swift
// GoogleMapKit
//
// Created by xiong on 4/5/16.
// Copyright © 2016 Zero Inc. All rights reserved.
//
import UIKit
import GoogleMaps
class PlaceMarker: GMSMarker {
let place : GooglePlace
init(place: GooglePlace) {
self.place = place
super.init()
position = place.coordinate
icon = UIImage(named: place.placeType+"_pin")
groundAnchor = CGPoint(x: 0.5, y: 1)
appearAnimation = kGMSMarkerAnimationPop
}
}
|
d47b2d73d3d3e12f79c7f30f8d7c572c
| 17.892857 | 53 | 0.597353 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.