repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/swift | benchmark/single-source/DictionarySubscriptDefault.swift | 10 | 3376 | //===--- DictionarySubscriptDefault.swift ---------------------------------===//
//
// 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 TestsUtils
public let benchmarks = [
BenchmarkInfo(name: "DictionarySubscriptDefaultMutation",
runFunction: run_DictionarySubscriptDefaultMutation,
tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionarySubscriptDefaultMutationArray",
runFunction: run_DictionarySubscriptDefaultMutationArray,
tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionarySubscriptDefaultMutationOfObjects",
runFunction: run_DictionarySubscriptDefaultMutationOfObjects,
tags: [.validation, .api, .Dictionary], legacyFactor: 20),
BenchmarkInfo(name: "DictionarySubscriptDefaultMutationArrayOfObjects",
runFunction:
run_DictionarySubscriptDefaultMutationArrayOfObjects,
tags: [.validation, .api, .Dictionary], legacyFactor: 20),
]
@inline(never)
public func run_DictionarySubscriptDefaultMutation(_ n: Int) {
for _ in 1...n {
var dict = [Int: Int]()
for i in 0..<10_000 {
dict[i % 100, default: 0] += 1
}
check(dict.count == 100)
check(dict[0]! == 100)
}
}
@inline(never)
public func run_DictionarySubscriptDefaultMutationArray(_ n: Int) {
for _ in 1...n {
var dict = [Int: [Int]]()
for i in 0..<10_000 {
dict[i % 100, default: []].append(i)
}
check(dict.count == 100)
check(dict[0]!.count == 100)
}
}
// Hack to workaround the fact that if we attempt to increment the Box's value
// from the subscript, the compiler will just call the subscript's getter (and
// therefore not insert the instance) as it's dealing with a reference type.
// By using a mutating method in a protocol extension, the compiler is forced to
// treat this an actual mutation, so cannot call the getter.
protocol P {
associatedtype T
var value: T { get set }
}
extension P {
mutating func mutateValue(_ mutations: (inout T) -> Void) {
mutations(&value)
}
}
class Box<T : Hashable> : Hashable, P {
var value: T
init(_ v: T) {
value = v
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionarySubscriptDefaultMutationOfObjects(_ n: Int) {
for _ in 1...n {
var dict = [Box<Int>: Box<Int>]()
for i in 0..<500 {
dict[Box(i % 5), default: Box(0)].mutateValue { $0 += 1 }
}
check(dict.count == 5)
check(dict[Box(0)]!.value == 100)
}
}
@inline(never)
public func run_DictionarySubscriptDefaultMutationArrayOfObjects(_ n: Int) {
for _ in 1...n {
var dict = [Box<Int>: [Box<Int>]]()
for i in 0..<500 {
dict[Box(i % 5), default: []].append(Box(i))
}
check(dict.count == 5)
check(dict[Box(0)]!.count == 100)
}
}
| apache-2.0 | e268520a9ac50262e34f90aab7a349c0 | 26.900826 | 80 | 0.623223 | 4.132191 | false | false | false | false |
rnystrom/GitHawk | Classes/Systems/LabelLayoutManager.swift | 1 | 1261 | //
// LabelLayoutManager.swift
// Freetime
//
// Created by Ryan Nystrom on 5/21/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
final class LabelLayoutManager: NSLayoutManager {
override func fillBackgroundRectArray(_ rectArray: UnsafePointer<CGRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: UIColor) {
// Get the attributes for the backgroundColor attribute
var range = charRange
let attributes = textStorage?.attributes(at: charRange.location, effectiveRange: &range)
// Ensure that this is one of our labels we're dealing with, ignore basic backgroundColor attributes
guard attributes?[MarkdownAttribute.label] != nil else {
super.fillBackgroundRectArray(rectArray, count: rectCount, forCharacterRange: charRange, color: color)
return
}
let rawRect = rectArray[0]
let rect = CGRect(
x: floor(rawRect.origin.x),
y: floor(rawRect.origin.y),
width: floor(rawRect.size.width),
height: floor(rawRect.size.height)
).insetBy(dx: -3, dy: 0)
UIBezierPath(roundedRect: rect, cornerRadius: Styles.Sizes.labelCornerRadius).fill()
}
}
| mit | c8b3ec75ac04f39456ffc4cc3bd1556b | 35 | 155 | 0.672222 | 4.581818 | false | false | false | false |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/Uploader/Requests/CLDUploadRequestWrapper.swift | 1 | 8224 | //
// CLDUploadRequestWrapper.swift
//
// Copyright (c) 2017 Cloudinary (http://cloudinary.com)
//
// 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
/**
A `CLDUploadRequestWrapper` object is a wrapper for instances of `CLDUploadRequest`. This is returned as a promise from
several `CLDUploader` functions, in case the actual concrete request cannot yet be created. This is also allows for multiple
concrete requests to be represented as one request. This class is used for preprocessing requests as well as uploda large requests.
*/
internal class CLDUploadRequestWrapper: CLDUploadRequest {
private var state = RequestState.started
fileprivate var requestsCount: Int!
fileprivate var totalLength: Int64!
fileprivate var requestsProgress = [CLDUploadRequest: Int64]()
fileprivate var totalProgress: Progress?
fileprivate var progressHandler: ((Progress) -> Void)?
fileprivate var requests = [CLDUploadRequest]()
fileprivate var result: CLDUploadResult?
fileprivate var error: NSError?
fileprivate let queue = DispatchQueue(label: "RequestsHandlingQueue", attributes: .concurrent)
fileprivate let closureQueue: OperationQueue = {
let operationQueue = OperationQueue()
operationQueue.name = "com.cloudinary.CLDUploadRequestWrapper"
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
return operationQueue
}()
/**
Once the count and total length of the request are known this method should be called.
Without this information the progress closures will not be called.
- parameter count: Number of inner requests expected to be added (or already added).
- parameter totalLength: Total length, in bytes, of the uploaded resource (can be spread across several inner request for `uploadLarge`)
*/
internal func setRequestsData(count: Int, totalLength: Int64?) {
self.totalLength = totalLength ?? 0
self.requestsCount = count
self.totalLength = totalLength ?? 0
self.totalProgress = Progress(totalUnitCount: self.totalLength)
}
/**
Add a requst to be part of the wrapping request.
- parameter request: An upload request to add - This is usually a concrete `CLDDefaultUploadRequest` to be part of this wrapper.
*/
internal func addRequest(_ request: CLDUploadRequest) {
queue.sync() {
guard self.state != RequestState.cancelled && self.state != RequestState.error else {
return
}
if (self.state == RequestState.suspended) {
request.suspend()
}
request.response() { result, error in
guard (self.state != RequestState.cancelled && self.state != RequestState.error) else {
return
}
if (error != nil) {
// single part error fails everything
self.state = RequestState.error
self.cancel()
self.requestDone(nil, error)
} else if self.requestsCount == 1 || (result?.done ?? false) {
// last part arrived successfully
self.state = RequestState.success
self.requestDone(result, nil)
}
}
request.progress() { innerProgress in
guard (self.state != RequestState.cancelled && self.state != RequestState.error) else {
return
}
self.requestsProgress[request] = innerProgress.completedUnitCount
if let totalProgress = self.totalProgress {
totalProgress.completedUnitCount = self.requestsProgress.values.reduce(0, +)
self.progressHandler?(totalProgress)
}
}
self.requests.append(request)
}
}
/**
This is used in case the request fails even without any inner upload request (e.g. when the preprocessing fails).
Once the error is set here it will be send once the completion closures are set.
- parameter error: The NSError to set.
*/
internal func setRequestError(_ error: NSError) {
state = RequestState.error
requestDone(nil, error)
}
fileprivate func requestDone(_ result: CLDUploadResult?, _ error: NSError?) {
self.error = error
self.result = result
requestsProgress.removeAll()
requests.removeAll()
closureQueue.isSuspended = false
}
// MARK: - Public
/**
Resume the request.
*/
open override func resume() {
queue.sync() {
state = RequestState.started
for request in requests {
request.resume()
}
}
}
/**
Suspend the request.
*/
open override func suspend() {
queue.sync() {
state = RequestState.suspended
for request in requests {
request.suspend()
}
}
}
/**
Cancel the request.
*/
open override func cancel() {
queue.sync() {
state = RequestState.cancelled
for request in requests {
request.cancel()
}
}
}
//MARK: Handlers
/**
Set a response closure to be called once the request has finished.
- parameter completionHandler: The closure to be called once the request has finished, holding either the response object or the error.
- returns: The same instance of CldUploadRequestWrapper.
*/
@discardableResult
open override func response(_ completionHandler: @escaping (_ result: CLDUploadResult?, _ error: NSError?) -> ()) -> Self {
closureQueue.addOperation {
completionHandler(self.result, self.error)
}
return self
}
/**
Set a progress closure that is called periodically during the data transfer.
- parameter progressBlock: The closure that is called periodically during the data transfer.
- returns: The same instance of CLDUploadRequestWrapper.
*/
@discardableResult
open override func progress(_ progress: @escaping ((Progress) -> Void)) -> Self {
self.progressHandler = progress
return self
}
/**
Sets a cleanup handler that is called when the request doesn't need it's resources anymore.
This is called whether the request succeeded or not.
- Parameter handler: The closure to be called once cleanup is necessary.
- returns: The same instance of CLDUploadRequestWrapper.
*/
@discardableResult
internal func cleanupHandler(handler: @escaping (_ success: Bool) -> ()) -> Self {
closureQueue.addOperation {
handler(self.state == RequestState.success)
}
return self
}
}
fileprivate enum RequestState: Int {
case started, suspended, cancelled, error, success
}
| mit | 43497dc3cdf06b41c54f63acdb8c1958 | 36.381818 | 145 | 0.631201 | 5.254952 | false | false | false | false |
thehung111/ViSearchSwiftSDK | Example/Example/Lib/ImageLoader/Disk.swift | 3 | 3338 | //
// Disk.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 12/21/14.
// Copyright © 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
extension String {
public func escape() -> String? {
return addingPercentEncoding(withAllowedCharacters: .alphanumerics)
}
}
public class Disk {
var storedData = [String: Data]()
class Directory {
init() {
createDirectory()
}
private func createDirectory() {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: path) {
return
}
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
var path: String {
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let directoryName = "swift.imageloader.disk"
return cacheDirectory + "/" + directoryName
}
}
let directory = Directory()
fileprivate let _subscriptQueue = DispatchQueue(label: "swift.imageloader.queues.disk.subscript", attributes: .concurrent)
fileprivate let _ioQueue = DispatchQueue(label: "swift.imageloader.queues.disk.set")
}
extension Disk {
public class func cleanUp() {
Disk().cleanUp()
}
func cleanUp() {
let manager = FileManager.default
for subpath in manager.subpaths(atPath: directory.path) ?? [] {
let path = directory.path + "/" + subpath
do {
try manager.removeItem(atPath: path)
} catch _ {
}
}
}
public class func get(_ aKey: String) -> Data? {
return Disk().get(aKey)
}
public class func set(_ anObject: Data, forKey aKey: String) {
Disk().set(anObject, forKey: aKey)
}
public func get(_ aKey: String) -> Data? {
if let data = storedData[aKey] {
return data
}
return (try? Data(contentsOf: URL(fileURLWithPath: _path(aKey))))
}
fileprivate func get(_ aKey: URL) -> Data? {
guard let key = aKey.absoluteString.escape() else { return nil }
return get(key)
}
fileprivate func _path(_ name: String) -> String {
return directory.path + "/" + name
}
public func set(_ anObject: Data, forKey aKey: String) {
storedData[aKey] = anObject
let block: () -> Void = {
do {
try anObject.write(to: URL(fileURLWithPath: self._path(aKey)), options: [])
self.storedData[aKey] = nil
} catch _ {}
}
_ioQueue.async(execute: block)
}
fileprivate func set(_ anObject: Data, forKey aKey: URL) {
guard let key = aKey.absoluteString.escape() else { return }
set(anObject, forKey: key)
}
}
extension Disk: ImageLoaderCache {
public subscript (aKey: URL) -> Data? {
get {
var data : Data?
_subscriptQueue.sync {
data = self.get(aKey)
}
return data
}
set {
_subscriptQueue.async {
self.set(newValue!, forKey: aKey)
}
}
}
}
| mit | 3d00a01424e47086fe3bb31e2da24a42 | 24.473282 | 126 | 0.557387 | 4.634722 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Message/Converstaion/ChatViewModel.swift | 1 | 6784 | //
// ChatViewModel.swift
// HiPDA
//
// Created by leizh007 on 2017/7/3.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import JSQMessagesViewController
import RxSwift
import SDWebImage
enum ChatMessageType {
case incoming
case outgoing
}
class ChatViewModel {
let user: User
fileprivate var disposeBag = DisposeBag()
fileprivate var messages = [JSQMessage]()
fileprivate var avatars = [String: JSQMessagesAvatarImage]()
fileprivate var formhash = ""
fileprivate var lastdaterange = ""
fileprivate let dateFormater: DateFormatter = {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-M-d"
return dateFormater
}()
fileprivate let secondDateFormater: DateFormatter = {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-M-d HH:mm:ss"
return dateFormater
}()
init(user: User) {
self.user = user
}
func fetchConversation(with completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) {
guard let account = Settings.shared.activeAccount else {
completion(.failure(NSError(domain: "HiPDA", code: -1, userInfo: [NSLocalizedDescriptionKey: "请登录后再使用"])))
return
}
let group = DispatchGroup()
for user in [self.user, User(name: account.name, uid: account.uid)] {
group.enter()
ChatViewModel.getAvatar(of: user) { image in
self.avatars["\(user.uid)"] = JSQMessagesAvatarImageFactory.avatarImage(withPlaceholder: image, diameter: UInt(max(image.size.width, image.size.height) / C.UI.screenScale))
group.leave()
}
}
var event: (Event<[JSQMessage]>)!
group.enter()
disposeBag = DisposeBag()
HiPDAProvider.request(.privateMessageConversation(uid: user.uid))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInteractive))
.mapGBKString()
.do(onNext: { [weak self] html in
self?.formhash = try HtmlParser.replyValue(for: "formhash", in: html)
self?.lastdaterange = try HtmlParser.replyValue(for: "lastdaterange", in: html)
})
.map { try HtmlParser.chatMessges(from: $0).map(self.transform(message:)) }
.observeOn(MainScheduler.instance)
.subscribe { e in
switch e {
case .next(_):
fallthrough
case .error(_):
event = e
group.leave()
default:
break
}
}.disposed(by: disposeBag)
group.notify(queue: DispatchQueue.main) {
switch event! {
case .next(let messages):
self.messages = messages
completion(.success(()))
case .error(let error):
completion(.failure(error as NSError))
default:
break
}
}
}
private static func getAvatar(of user: User, completion: @escaping (UIImage) -> Void) {
SDWebImageManager.shared().loadImage(with: user.avatarImageURL, options: [], progress: nil) { (image, _, _, _, _, _) in
if let image = image {
completion(image)
} else {
completion(#imageLiteral(resourceName: "avatar_placeholder"))
}
}
}
private func transform(message: ChatMessage) -> JSQMessage {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-M-d HH:mm"
let date = dateFormater.date(from: message.time) ?? Date()
let senderId = message.name == user.name ? user.uid : (Settings.shared.activeAccount?.uid ?? 0)
return JSQMessage(senderId: "\(senderId)", senderDisplayName: message.name, date: date, text: message.content)
}
fileprivate func dateString(of date: Date) -> String {
return dateFormater.string(from: date)
}
func sendMessage(_ message: JSQMessage, with completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) {
messages.append(message)
HiPDAProvider.request(.replypm(uid: user.uid, formhash: formhash, lastdaterange: lastdaterange, message: message.text ?? ""))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInteractive))
.mapGBKString()
.map { html -> Bool in
let messages = try HtmlParser.chatMessges(from: html)
if messages.count == 1 && messages[0].content == message.text {
return true
}
let result = try Regex.firstMatch(in: html, of: "\\[CDATA\\[([^<]+)<")
if result.count == 2 && !result[1].isEmpty {
throw HtmlParserError.underlying("发送失败: \(result[1])")
} else {
throw HtmlParserError.underlying("发送失败")
}
}
.observeOn(MainScheduler.instance)
.subscribe { [weak self] event in
guard let `self` = self else { return }
switch event {
case .next(_):
completion(.success(()))
case .error(let error):
self.messages = self.messages.filter { self.secondDateFormater.string(from: $0.date) != self.secondDateFormater.string(from: message.date) }
completion(.failure(error as NSError))
default:
break
}
}.disposed(by: disposeBag)
}
}
// MARK: - DataSource
extension ChatViewModel {
func numberOfItems() -> Int {
return messages.count
}
func message(at index: Int) -> JSQMessage {
return messages[index]
}
func avatar(at index: Int) -> JSQMessagesAvatarImage? {
return avatars[message(at: index).senderId]
}
func messageType(at index: Int) -> ChatMessageType {
return message(at: index).senderId == "\(user.uid)" ? .incoming : .outgoing
}
func user(at index: Int) -> User {
switch messageType(at: index) {
case .incoming:
return user
case .outgoing:
return User(name: Settings.shared.activeAccount?.name ?? "", uid: Settings.shared.activeAccount?.uid ?? 0)
}
}
func shouldShowCellTopLabel(at index: Int) -> Bool {
if index == 0 {
return true
}
return dateString(at: index - 1) != dateString(at: index)
}
func dateString(at index: Int) -> String {
return dateString(of: message(at: index).date)
}
}
| mit | 4ee8da46e14f14fda5692f42e26df078 | 36.093407 | 188 | 0.567323 | 4.760931 | false | false | false | false |
galv/reddift | reddiftSample/BaseSubredditsViewController.swift | 2 | 744 | //
// BaseSubredditsViewController.swift
// reddift
//
// Created by sonson on 2015/05/04.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class BaseSubredditsViewController: UITableViewController, UISearchBarDelegate {
var session:Session? = nil
var paginator:Paginator? = Paginator()
var loading = false
var task:NSURLSessionDataTask? = nil
var segmentedControl:UISegmentedControl? = nil
var sortTitles:[String] = []
var sortTypes:[SubredditsWhere] = []
var subreddits:[Subreddit] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
}
| mit | 557c1afd802d054ff3496600d6fbb0ae | 25.5 | 90 | 0.698113 | 4.608696 | false | false | false | false |
DingSoung/CCExtension | Sources/Swift/String+regex.swift | 2 | 1573 | // Created by Songwen Ding on 2017/8/3.
// Copyright © 2017年 DingSoung. All rights reserved.
#if canImport(Foundation)
import Foundation.NSRegularExpression
infix operator =~: AdditionPrecedence
private struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
}
func match(input: String) -> Bool {
let matches = regex.matches(in: input,
options: [],
range: NSRange(location: 0, length: input.utf16.count))
return matches.count > 0
}
}
extension String {
static func =~ (str: String, regex: String) -> Bool {
do {
return try RegexHelper(regex).match(input: str as String)
} catch _ {
return false
}
}
public func match(regex: String) -> Bool {
return self =~ regex
}
}
extension String {
/// check is mobile phone number
public var isPRCMobileNumber: Bool {
//前缀0 86 17951 或者没有 中间13* 15* 17* 145 147 后加8个0~9的数
return self =~ "^(0|86|086|17951)?1(3[0-9]|4[57]|7[0-9]|8[0123456789])[0-9]{8}$"
}
/// check is ID if People's Republic of China
public var isPRCIDNumber: Bool {
return self =~ "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"
|| self =~ "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2))(([0|1|2]\\d)|2[0-1])\\d{4}$"
}
}
#endif
| mit | ec57a7a108a03edbea7b5c578e271e3b | 29.235294 | 92 | 0.544099 | 3.528604 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCAccountTableViewCell.swift | 2 | 19492 | //
// NCAccountTableViewCell.swift
// Neocom
//
// Created by Artem Shimanski on 13.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
import Futures
class NCAccountTableViewCell: NCTableViewCell {
@IBOutlet weak var characterNameLabel: UILabel?
@IBOutlet weak var characterImageView: UIImageView?
@IBOutlet weak var corporationLabel: UILabel?
@IBOutlet weak var spLabel: UILabel?
@IBOutlet weak var wealthLabel: UILabel?
@IBOutlet weak var locationLabel: UILabel?
// @IBOutlet weak var subscriptionLabel: UILabel!
@IBOutlet weak var skillLabel: UILabel?
@IBOutlet weak var trainingTimeLabel: UILabel?
@IBOutlet weak var skillQueueLabel: UILabel?
@IBOutlet weak var trainingProgressView: UIProgressView?
@IBOutlet weak var alertLabel: UILabel?
var progressHandler: NCProgressHandler?
override func awakeFromNib() {
super.awakeFromNib()
let layer = self.trainingProgressView?.superview?.layer;
layer?.borderColor = UIColor(number: 0x3d5866ff).cgColor
layer?.borderWidth = 1.0 / UIScreen.main.scale
}
}
extension Prototype {
enum NCAccountTableViewCell {
static let `default` = Prototype(nib: UINib(nibName: "NCAccountTableViewCell", bundle: nil), reuseIdentifier: "NCAccountTableViewCell")
}
}
class NCAccountsNode<Row: NCAccountRow>: TreeNode {
let cachePolicy: URLRequest.CachePolicy
init(context: NSManagedObjectContext, cachePolicy: URLRequest.CachePolicy) {
self.cachePolicy = cachePolicy
super.init()
let defaultAccounts: FetchedResultsNode<NCAccount> = {
let request = NSFetchRequest<NCAccount>(entityName: "Account")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true),
NSSortDescriptor(key: "characterName", ascending: true)]
request.predicate = NSPredicate(format: "folder == nil", "")
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return FetchedResultsNode(resultsController: results, objectNode: Row.self)
}()
let folders: FetchedResultsNode<NCAccountsFolder> = {
let request = NSFetchRequest<NCAccountsFolder>(entityName: "AccountsFolder")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return FetchedResultsNode(resultsController: results, objectNode: NCAccountsFolderSection<Row>.self)
}()
children = [DefaultTreeSection(prototype: Prototype.NCHeaderTableViewCell.default, nodeIdentifier: "Default", title: NSLocalizedString("Default", comment: "").uppercased(), children: [defaultAccounts]), folders]
}
}
class NCAccountsFolderSection<Row: NCAccountRow>: NCFetchedResultsObjectNode<NCAccountsFolder>, CollapseSerializable {
var collapseState: NCCacheSectionCollapse?
var collapseIdentifier: String? {
return self.object.objectID.uriRepresentation().absoluteString
}
required init(object: NCAccountsFolder) {
super.init(object: object)
isExpandable = true
cellIdentifier = Prototype.NCHeaderTableViewCell.default.reuseIdentifier
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCHeaderTableViewCell else {return}
cell.titleLabel?.text = (object.name?.isEmpty == false ? object.name : NSLocalizedString("Unnamed", comment: ""))?.uppercased()
}
override func loadChildren() {
guard let context = object.managedObjectContext else {return}
let request = NSFetchRequest<NCAccount>(entityName: "Account")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true),
NSSortDescriptor(key: "characterName", ascending: true)]
request.predicate = NSPredicate(format: "folder == %@", object)
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
children = [FetchedResultsNode(resultsController: results, objectNode: Row.self)]
}
override func willMoveToTreeController(_ treeController: TreeController?) {
if let collapseState = getCollapseState() {
isExpanded = collapseState.isExpanded
self.collapseState = collapseState
}
else {
self.collapseState = nil
}
super.willMoveToTreeController(treeController)
}
override var isExpanded: Bool {
didSet {
collapseState?.isExpanded = isExpanded
}
}
}
class NCAccountRow: NCFetchedResultsObjectNode<NCAccount> {
private struct LoadingOptions: OptionSet {
var rawValue: Int
static let characterInfo = LoadingOptions(rawValue: 1 << 0)
static let corporationInfo = LoadingOptions(rawValue: 1 << 1)
static let skillQueue = LoadingOptions(rawValue: 1 << 2)
static let skills = LoadingOptions(rawValue: 1 << 3)
static let walletBalance = LoadingOptions(rawValue: 1 << 4)
static let characterLocation = LoadingOptions(rawValue: 1 << 5)
static let characterShip = LoadingOptions(rawValue: 1 << 6)
static let image = LoadingOptions(rawValue: 1 << 7)
var count: Int {
return sequence(first: rawValue) {$0 > 1 ? $0 >> 1 : nil}.reduce(0) {
$0 + (($1 & 1) == 1 ? 1 : 0)
}
}
}
required init(object: NCAccount) {
super.init(object: object)
canMove = true
cellIdentifier = Prototype.NCAccountTableViewCell.default.reuseIdentifier
}
var cachePolicy: URLRequest.CachePolicy {
var parent = self.parent
while parent != nil && !(parent is NCAccountsNode) {
parent = parent?.parent
}
return (parent as? NCAccountsNode)?.cachePolicy ?? .useProtocolCachePolicy
}
lazy var dataManager: NCDataManager = {
return NCDataManager(account: self.object, cachePolicy: self.cachePolicy)
}()
var character: Future<CachedValue<ESI.Character.Information>>?
var corporation: Future<CachedValue<ESI.Corporation.Information>>?
var skillQueue: Future<CachedValue<[ESI.Skills.SkillQueueItem]>>?
var walletBalance: Future<CachedValue<Double>>?
var skills: Future<CachedValue<ESI.Skills.CharacterSkills>>?
var location: Future<CachedValue<ESI.Location.CharacterLocation>>?
var ship: Future<CachedValue<ESI.Location.CharacterShip>>?
var image: Future<CachedValue<UIImage>>?
var isLoaded = false
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCAccountTableViewCell else {return}
cell.object = object
if !isLoaded {
var options = LoadingOptions()
if cell.corporationLabel != nil {
options.insert(.characterInfo)
options.insert(.corporationInfo)
}
if cell.skillQueueLabel != nil {
options.insert(.skillQueue)
}
if cell.skillLabel != nil {
options.insert(.skills)
}
if cell.wealthLabel != nil {
options.insert(.walletBalance)
}
if cell.locationLabel != nil{
options.insert(.characterLocation)
options.insert(.characterShip)
}
if cell.imageView != nil {
options.insert(.image)
}
_ = reload(options: options)
isLoaded = true
}
configureImage(cell: cell)
configureSkills(cell: cell)
configureWallets(cell: cell)
configureLocation(cell: cell)
configureCharacter(cell: cell)
configureSkillQueue(cell: cell)
configureCorporation(cell: cell)
if object.isInvalid {
cell.alertLabel?.isHidden = true
}
else {
if let scopes = object.scopes?.compactMap({($0 as? NCScope)?.name}), Set(ESI.Scope.default.map{$0.rawValue}).isSubset(of: Set(scopes)) {
cell.alertLabel?.isHidden = true
}
else {
cell.alertLabel?.isHidden = false
}
}
}
func configureCharacter(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.characterNameLabel?.text = object.characterName
}
else {
cell.characterNameLabel?.text = " "
character?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
cell.characterNameLabel?.text = result.value?.name ?? " "
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.characterNameLabel?.text = error.localizedDescription
}
}
}
func configureCorporation(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.corporationLabel?.text = NSLocalizedString("Access Token did become invalid", comment: "")
cell.corporationLabel?.textColor = .red
}
else {
cell.corporationLabel?.textColor = .white
cell.corporationLabel?.text = " "
corporation?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
cell.corporationLabel?.text = result.value?.name ?? " "
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.corporationLabel?.text = error.localizedDescription
}
}
}
func configureSkillQueue(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.skillLabel?.text = " "
cell.skillQueueLabel?.text = " "
cell.trainingTimeLabel?.text = " "
cell.trainingProgressView?.progress = 0
}
else {
cell.skillLabel?.text = " "
cell.skillQueueLabel?.text = " "
cell.trainingTimeLabel?.text = " "
cell.trainingProgressView?.progress = 0
skillQueue?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
guard let value = result.value else {return}
let date = Date()
let skillQueue = value.filter {
guard let finishDate = $0.finishDate else {return false}
return finishDate >= date
}
let firstSkill = skillQueue.first { $0.finishDate! > date }
let trainingTime: String
let trainingProgress: Float
let title: NSAttributedString
if let skill = firstSkill {
guard let type = NCDatabase.sharedDatabase?.invTypes[skill.skillID] else {return}
guard let firstTrainingSkill = NCSkill(type: type, skill: skill) else {return}
if !firstTrainingSkill.typeName.isEmpty {
title = NSAttributedString(skillName: firstTrainingSkill.typeName, level: 1 + (firstTrainingSkill.level ?? 0))
}
else {
title = NSAttributedString(string: String(format: NSLocalizedString("Unknown skill %d", comment: ""), firstTrainingSkill.typeID))
}
trainingProgress = firstTrainingSkill.trainingProgress
if let endTime = firstTrainingSkill.trainingEndDate {
trainingTime = NCTimeIntervalFormatter.localizedString(from: endTime.timeIntervalSinceNow, precision: .minutes)
}
else {
trainingTime = " "
}
}
else {
title = NSAttributedString(string: NSLocalizedString("No skills in training", comment: ""), attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightText])
trainingProgress = 0
trainingTime = " "
}
let skillQueueText: String
if let skill = skillQueue.last, let endTime = skill.finishDate {
skillQueueText = String(format: NSLocalizedString("%d skills in queue (%@)", comment: ""), skillQueue.count, NCTimeIntervalFormatter.localizedString(from: endTime.timeIntervalSinceNow, precision: .minutes))
}
else {
skillQueueText = " "
}
cell.skillLabel?.attributedText = title
cell.trainingTimeLabel?.text = trainingTime
cell.trainingProgressView?.progress = trainingProgress
cell.skillQueueLabel?.text = skillQueueText
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.skillLabel?.text = error.localizedDescription
cell.skillQueueLabel?.text = " "
cell.trainingTimeLabel?.text = " "
cell.trainingProgressView?.progress = 0
}
}
}
func configureWallets(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.wealthLabel?.text = " "
}
else {
cell.wealthLabel?.text = " "
walletBalance?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
guard let wealth = result.value else {return}
cell.wealthLabel?.text = NCUnitFormatter.localizedString(from: wealth, unit: .none, style: .short)
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.wealthLabel?.text = error.localizedDescription
}
}
}
func configureSkills(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.spLabel?.text = " "
}
else {
cell.spLabel?.text = " "
skills?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
guard let value = result.value else {return}
cell.spLabel?.text = NCUnitFormatter.localizedString(from: Double(value.totalSP), unit: .none, style: .short)
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.spLabel?.text = error.localizedDescription
}
}
}
func configureLocation(cell: NCAccountTableViewCell) {
if object.isInvalid {
cell.locationLabel?.text = " "
}
else {
all(
self.location?.then(on: .main) { result -> String? in
guard let value = result.value else {return nil}
guard let solarSystem = NCDatabase.sharedDatabase?.mapSolarSystems[value.solarSystemID] else {return nil}
return "\(solarSystem.solarSystemName!) / \(solarSystem.constellation!.region!.regionName!)"
} ?? .init(nil),
self.ship?.then(on: .main) { result -> String? in
guard let value = result.value else {return nil}
guard let type = NCDatabase.sharedDatabase?.invTypes[value.shipTypeID] else {return nil}
return type.typeName
} ?? .init(nil)
).then(on: .main) { (location, ship) in
guard cell.object as? NCAccount == self.object else {return}
if let ship = ship, let location = location {
let s = NSMutableAttributedString()
s.append(NSAttributedString(string: ship, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]))
s.append(NSAttributedString(string: ", \(location)", attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightText]))
cell.locationLabel?.attributedText = s
}
else if let location = location {
let s = NSAttributedString(string: location, attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightText])
cell.locationLabel?.attributedText = s
}
else if let ship = ship {
let s = NSAttributedString(string: ship, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
cell.locationLabel?.attributedText = s
}
else {
cell.locationLabel?.text = " "
}
}.catch(on: .main) { error in
guard cell.object as? NCAccount == self.object else {return}
cell.locationLabel?.text = error.localizedDescription
}
}
}
func configureImage(cell: NCAccountTableViewCell) {
cell.characterImageView?.image = UIImage()
image?.then(on: .main) { result in
guard cell.object as? NCAccount == self.object else {return}
cell.characterImageView?.image = result.value
}
}
private var observer: NCManagedObjectObserver?
private var isLoading: Bool = false
private func reconfigure() {
// guard let cell = self.treeController?.cell(for: self) else {return}
// self.configure(cell: cell)
}
private func reload(options: LoadingOptions) -> Future<Void> {
guard !isLoading else {
return .init(())
}
isLoading = true
if object.isInvalid {
image = dataManager.image(characterID: object.characterID, dimension: 64)
image?.then(on: .main) { result in
self.reconfigure()
self.isLoading = false
}
return .init(())
}
else {
observer = NCManagedObjectObserver() { [weak self] (updated, deleted) in
guard let strongSelf = self else {return}
strongSelf.reconfigure()
}
let dataManager = self.dataManager
let cell = treeController?.cell(for: self)
let progress = cell != nil ? NCProgressHandler(view: cell!, totalUnitCount: Int64(options.count)) : nil
var queue = [Future<Void>]()
if options.contains(.characterInfo) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
character = dataManager.character()
progress?.progress.resignCurrent()
queue.append(
character!.then(on: .main) { result -> Future<Void> in
guard let value = result.value else {throw NCDataManagerError.noCacheData}
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
if options.contains(.corporationInfo) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
self.corporation = dataManager.corporation(corporationID: Int64(value.corporationID))
progress?.progress.resignCurrent()
return self.corporation!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
}
}
else {
return .init(())
}
})
}
if options.contains(.skillQueue) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
skillQueue = dataManager.skillQueue()
progress?.progress.resignCurrent()
queue.append(
skillQueue!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.skills) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
skills = dataManager.skills()
progress?.progress.resignCurrent()
queue.append(
skills!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.walletBalance) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
walletBalance = dataManager.walletBalance()
progress?.progress.resignCurrent()
queue.append(
walletBalance!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
}
)
}
if options.contains(.characterLocation) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
location = dataManager.characterLocation()
progress?.progress.resignCurrent()
queue.append(
location!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.characterShip) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
ship = dataManager.characterShip()
progress?.progress.resignCurrent()
queue.append(
ship!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
if options.contains(.image) {
progress?.progress.becomeCurrent(withPendingUnitCount: 1)
image = dataManager.image(characterID: object.characterID, dimension: 64)
progress?.progress.resignCurrent()
queue.append(
image!.then(on: .main) { result -> Void in
self.observer?.add(managedObject: result.cacheRecord(in: NCCache.sharedCache!.viewContext))
self.reconfigure()
})
}
return all(queue).then { _ -> Void in
}.finally(on: .main) {
progress?.finish()
self.isLoading = false
guard let cell = self.treeController?.cell(for: self) else {return}
self.configure(cell: cell)
}
}
}
}
| lgpl-2.1 | ffd9a57524eb8632845c3b3f7b6ca3f2 | 32.956446 | 213 | 0.705659 | 4.025403 | false | true | false | false |
almazrafi/Metatron | Sources/ID3v2/FrameStuffs/ID3v2Comments.swift | 1 | 2024 | //
// ID3v2Comments.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class ID3v2Comments: ID3v2LocalizedText {
}
public class ID3v2CommentsFormat: ID3v2FrameStuffSubclassFormat {
// MARK: Type Properties
public static let regular = ID3v2CommentsFormat()
// MARK: Instance Methods
public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2Comments {
return ID3v2Comments(fromData: data, version: version)
}
public func createStuffSubclass(fromOther other: ID3v2Comments) -> ID3v2Comments {
let stuff = ID3v2Comments()
stuff.textEncoding = other.textEncoding
stuff.language = other.language
stuff.description = other.description
stuff.content = other.content
return stuff
}
public func createStuffSubclass() -> ID3v2Comments {
return ID3v2Comments()
}
}
| mit | 38a9e595e918e78dec06a4ae1fb02ba7 | 33.896552 | 101 | 0.729249 | 4.2079 | false | true | false | false |
dvxiaofan/Pro-Swift-Learning | Part-02/01-RepeatingValues.playground/Contents.swift | 1 | 339 | //: Playground - noun: a place where people can play
import UIKit
let headeing = "This is a heading"
let underline = String(repeating: "=", count: headeing.characters.count)
let equalsArray = [String](repeating: "=", count: headeing.characters.count)
var board = [[String]](repeating: [String](repeating: "", count: 10), count: 10)
| mit | 31c9c796f2812788988f8df2dae74f28 | 25.076923 | 80 | 0.702065 | 3.606383 | false | false | false | false |
mrchenhao/Queue | Queue/QueueTask.swift | 1 | 7830 | //
// QueueTask.swift
// Queue
//
// Created by ChenHao on 12/10/15.
// Copyright © 2015 HarriesChen. All rights reserved.
//
import Foundation
public typealias TaskCallBack = (QueueTask) -> Void
public typealias TaskCompleteCallback = (QueueTask, Error?) -> Void
public typealias JSONDictionary = [String: Any]
// swiftlint:disable line_length
// swiftlint:disable variable_name
open class QueueTask: Operation {
public let queue: Queue
open var taskID: String
open var taskType: String
open var retries: Int
public let created: Date
open var started: Date?
open var userInfo: Any?
var error: Error?
var _executing: Bool = false
var _finished: Bool = false
open override var name: String? {
get {
return taskID
}
set {
}
}
open override var isExecuting: Bool {
get { return _executing }
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
open override var isFinished: Bool {
get { return _finished }
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
// MARK: - Init
/**
Initializes a new QueueTask with following paramsters
- parameter queue: the queue the execute the task
- parameter taskID: A unique identifer for the task
- parameter taskType: A type that will be used to group tasks together, tasks have to be generic with respect to their type
- parameter userInfo: other infomation
- parameter created: When the task was created
- parameter started: When the task was started first time
- parameter retries: Number of times this task has been retries after failing
- returns: A new QueueTask
*/
fileprivate init(queue: Queue, taskID: String? = nil, taskType: String, userInfo: Any? = nil,
created: Date = Date(), started: Date? = nil ,
retries: Int = 0) {
self.queue = queue
self.taskID = taskID ?? UUID().uuidString
self.taskType = taskType
self.retries = retries
self.created = created
self.userInfo = userInfo
super.init()
}
public convenience init(queue: Queue, type: String, userInfo: Any? = nil, retries: Int = 0) {
self.init(queue: queue, taskType: type, userInfo: userInfo, retries: retries)
}
public convenience init?(dictionary: JSONDictionary, queue: Queue) {
if let taskID = dictionary["taskID"] as? String,
let taskType = dictionary["taskType"] as? String,
let data = dictionary["userInfo"],
let createdStr = dictionary["created"] as? String,
let startedStr = dictionary["started"] as? String,
let retries = dictionary["retries"] as? Int? ?? 0 {
let created = Date(dateString: createdStr) ?? Date()
let started = Date(dateString: startedStr)
self.init(queue: queue, taskID: taskID, taskType: taskType, userInfo: data, created: created,
started: started, retries: retries)
} else {
self.init(queue: queue, taskID: "", taskType: "")
return nil
}
}
public convenience init?(json: String, queue: Queue) {
do {
if let dict = try fromJSON(json) as? [String: Any] {
self.init(dictionary: dict, queue: queue)
} else {
return nil
}
} catch {
return nil
}
}
open func toJSONString() -> String? {
let dict = toDictionary()
let nsdict = NSMutableDictionary(capacity: dict.count)
for (key, value) in dict {
nsdict[key] = value ?? NSNull()
}
do {
let json = try toJSON(nsdict)
return json
} catch {
return nil
}
}
open func toDictionary() -> [String: Any?] {
var dict = [String: Any?]()
dict["taskID"] = self.taskID
dict["taskType"] = self.taskType
dict["created"] = self.created.toISOString()
dict["retries"] = self.retries
dict["userInfo"] = self.userInfo
if let started = self.started {
dict["started"] = started.toISOString()
}
return dict
}
/**
run the task on the queue
*/
func run() {
if isCancelled && !isFinished { isFinished = true }
if isFinished { return }
queue.runTask(self)
}
/**
invoke the method to tell the queue if has error when the task complete
- parameter error: if the task failed, pass an error to indicate why
*/
open func complete(_ error: Error?) {
if !isExecuting {
return
}
if let error = error {
self.error = error
retries += 1
if retries >= queue.maxRetries {
cancel()
queue.log(LogLevel.trace, msg: "Task \(taskID) failed \(queue.taskList.count) tasks left")
return
}
queue.log(LogLevel.debug, msg: "Task \(taskID) retry \(retries) times")
self.run()
} else {
queue.log(LogLevel.trace, msg: "Task \(taskID) completed \(queue.taskList.count) tasks left")
isFinished = true
}
}
// MARK: - overide method
open override func start() {
super.start()
isExecuting = true
run()
}
open override func cancel() {
super.cancel()
isFinished = true
}
}
// MARK: - NSDate extention
extension Date {
init?(dateString: String) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
if let d = formatter.date(from: dateString) {
self.init(timeInterval: 0, since: d)
} else {
self.init(timeInterval: 0, since: Date())
return nil
}
}
var isoFormatter: ISOFormatter {
if let formatter = objc_getAssociatedObject(self, "formatter") as? ISOFormatter {
return formatter
} else {
let formatter = ISOFormatter()
objc_setAssociatedObject(self, "formatter", formatter, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return formatter
}
}
func toISOString() -> String {
return self.isoFormatter.string(from: self)
}
}
class ISOFormatter: DateFormatter {
override init() {
super.init()
self.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
self.timeZone = TimeZone(secondsFromGMT: 0)
self.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - Hepler
private func toJSON(_ obj: Any) throws -> String? {
let json = try JSONSerialization.data(withJSONObject: obj, options: [])
return NSString(data: json, encoding: String.Encoding.utf8.rawValue) as String?
}
private func fromJSON(_ str: String) throws -> Any? {
if let json = str.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let obj: Any = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as Any
return obj
}
return nil
}
private func runInBackgroundAfter(_ seconds: TimeInterval, callback: @escaping () -> Void) {
let delta = DispatchTime.now() + Double(Int64(seconds) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: delta, execute: callback)
}
| mit | 7861c001ea3905874f3cd93eea7385b2 | 30.06746 | 128 | 0.58641 | 4.476272 | false | false | false | false |
sarahlee517/Mr-Ride-iOS | Mr Ride/Mr Ride/Models/RideManager.swift | 1 | 2608 | //
// RunDataModel.swift
// Mr Ride
//
// Created by Sarah on 6/6/16.
// Copyright © 2016 AppWorks School Sarah Lee. All rights reserved.
//
import Foundation
import MapKit
import CoreData
class MyLocation: CLLocation{
let longtitude: Double = 0.0
let latitude: Double = 0.0
}
struct RideData{
var totalTime: Int = 0
var distance: Double = 0.0
var date = NSDate()
var myLocations = [MyLocation]()
}
class RideManager{
static let sharedManager = RideManager()
var distanceForChart = [Double]()
var dateForChart = [String]()
// var myCoordinate = [MyLocation]()
var historyData = [RideData]()
// var fetchResultController
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
//MARK: Get Data From Core Data
func getDataFromCoreData() {
let request = NSFetchRequest(entityName: "RideHistory")
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
do {
let results = try moc.executeFetchRequest(request) as! [RideHistory]
for result in results {
// if let locations = result.locations!.array as? [Locations]{
// for locaton in locations{
// if let _longtitude = locaton.longtitude?.doubleValue,
// _latitude = locaton.latitude?.doubleValue{
//
// myCoordinate.append(
// MyLocation(
// latitude: _latitude,
// longitude: _longtitude
// )
// )
// }
// }
// }
if let distance = result.distance as? Double,
let totalTime = result.totalTime as? Int,
let date = result.date{
RideManager.sharedManager.historyData.append(
RideData(
totalTime: totalTime,
distance: distance,
date: date,
myLocations: [MyLocation]()
)
)
}
}
}catch{
fatalError("Failed to fetch data: \(error)")
}
print("History Count:\(historyData.count)")
print(historyData)
}
}
| mit | abf30e5b48ac58bc8f1b560c1e5779bc | 28.965517 | 95 | 0.477177 | 5.331288 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RouteManager/RouteManagerTableView.swift | 12 | 868 | final class RouteManagerTableView: UITableView {
@IBOutlet private weak var tableViewHeight: NSLayoutConstraint!
enum HeightUpdateStyle {
case animated
case deferred
case off
}
var heightUpdateStyle = HeightUpdateStyle.deferred
private var scheduledUpdate: DispatchWorkItem?
override var contentSize: CGSize {
didSet {
guard contentSize != oldValue else { return }
scheduledUpdate?.cancel()
let update = { [weak self] in
guard let s = self else { return }
s.tableViewHeight.constant = s.contentSize.height
}
switch heightUpdateStyle {
case .animated: superview?.animateConstraints(animations: update)
case .deferred:
scheduledUpdate = DispatchWorkItem(block: update)
DispatchQueue.main.async(execute: scheduledUpdate!)
case .off: break
}
}
}
}
| apache-2.0 | 9350ce6ace198530d6b392c9666b1462 | 27 | 71 | 0.686636 | 4.931818 | false | true | false | false |
klundberg/swift-corelibs-foundation | Foundation/NSURLSession.swift | 1 | 40609 | // 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
//
/*
NSURLSession is a replacement API for NSURLConnection. It provides
options that affect the policy of, and various aspects of the
mechanism by which NSURLRequest objects are retrieved from the
network.
An NSURLSession may be bound to a delegate object. The delegate is
invoked for certain events during the lifetime of a session, such as
server authentication or determining whether a resource to be loaded
should be converted into a download.
NSURLSession instances are threadsafe.
The default NSURLSession uses a system provided delegate and is
appropriate to use in place of existing code that uses
+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]
An NSURLSession creates NSURLSessionTask objects which represent the
action of a resource being loaded. These are analogous to
NSURLConnection objects but provide for more control and a unified
delegate model.
NSURLSessionTask objects are always created in a suspended state and
must be sent the -resume message before they will execute.
Subclasses of NSURLSessionTask are used to syntactically
differentiate between data and file downloads.
An NSURLSessionDataTask receives the resource as a series of calls to
the URLSession:dataTask:didReceiveData: delegate method. This is type of
task most commonly associated with retrieving objects for immediate parsing
by the consumer.
An NSURLSessionUploadTask differs from an NSURLSessionDataTask
in how its instance is constructed. Upload tasks are explicitly created
by referencing a file or data object to upload, or by utilizing the
-URLSession:task:needNewBodyStream: delegate message to supply an upload
body.
An NSURLSessionDownloadTask will directly write the response data to
a temporary file. When completed, the delegate is sent
URLSession:downloadTask:didFinishDownloadingToURL: and given an opportunity
to move this file to a permanent location in its sandboxed container, or to
otherwise read the file. If canceled, an NSURLSessionDownloadTask can
produce a data blob that can be used to resume a download at a later
time.
Beginning with iOS 9 and Mac OS X 10.11, NSURLSessionStream is
available as a task type. This allows for direct TCP/IP connection
to a given host and port with optional secure handshaking and
navigation of proxies. Data tasks may also be upgraded to a
NSURLSessionStream task via the HTTP Upgrade: header and appropriate
use of the pipelining option of NSURLSessionConfiguration. See RFC
2817 and RFC 6455 for information about the Upgrade: header, and
comments below on turning data tasks into stream tasks.
*/
/* DataTask objects receive the payload through zero or more delegate messages */
/* UploadTask objects receive periodic progress updates but do not return a body */
/* DownloadTask objects represent an active download to disk. They can provide resume data when canceled. */
/* StreamTask objects may be used to create NSInput and NSOutputStreams, or used directly in reading and writing. */
/*
NSURLSession is not available for i386 targets before Mac OS X 10.10.
*/
public let NSURLSessionTransferSizeUnknown: Int64 = -1
public class URLSession: NSObject {
/*
* The shared session uses the currently set global NSURLCache,
* NSHTTPCookieStorage and NSURLCredentialStorage objects.
*/
public class func sharedSession() -> URLSession { NSUnimplemented() }
/*
* Customization of NSURLSession occurs during creation of a new session.
* If you only need to use the convenience routines with custom
* configuration options it is not necessary to specify a delegate.
* If you do specify a delegate, the delegate will be retained until after
* the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
*/
public /*not inherited*/ init(configuration: URLSessionConfiguration) { NSUnimplemented() }
public /*not inherited*/ init(configuration: URLSessionConfiguration, delegate: URLSessionDelegate?, delegateQueue queue: OperationQueue?) { NSUnimplemented() }
public var delegateQueue: OperationQueue { NSUnimplemented() }
public var delegate: URLSessionDelegate? { NSUnimplemented() }
/*@NSCopying*/ public var configuration: URLSessionConfiguration { NSUnimplemented() }
/*
* The sessionDescription property is available for the developer to
* provide a descriptive label for the session.
*/
public var sessionDescription: String?
/* -finishTasksAndInvalidate returns immediately and existing tasks will be allowed
* to run to completion. New tasks may not be created. The session
* will continue to make delegate callbacks until URLSession:didBecomeInvalidWithError:
* has been issued.
*
* -finishTasksAndInvalidate and -invalidateAndCancel do not
* have any effect on the shared session singleton.
*
* When invalidating a background session, it is not safe to create another background
* session with the same identifier until URLSession:didBecomeInvalidWithError: has
* been issued.
*/
public func finishTasksAndInvalidate() { NSUnimplemented() }
/* -invalidateAndCancel acts as -finishTasksAndInvalidate, but issues
* -cancel to all outstanding tasks for this session. Note task
* cancellation is subject to the state of the task, and some tasks may
* have already have completed at the time they are sent -cancel.
*/
public func invalidateAndCancel() { NSUnimplemented() }
public func resetWithCompletionHandler(_ completionHandler: () -> Void) { NSUnimplemented() }/* empty all cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:. Invokes completionHandler() on the delegate queue if not nil. */
public func flushWithCompletionHandler(_ completionHandler: () -> Void) { NSUnimplemented() }/* flush storage to disk and clear transient network caches. Invokes completionHandler() on the delegate queue if not nil. */
public func getTasksWithCompletionHandler(_ completionHandler: ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) -> Void) { NSUnimplemented() }/* invokes completionHandler with outstanding data, upload and download tasks. */
public func getAllTasksWithCompletionHandler(_ completionHandler: ([URLSessionTask]) -> Void) { NSUnimplemented() }/* invokes completionHandler with all outstanding tasks. */
/*
* NSURLSessionTask objects are always created in a suspended state and
* must be sent the -resume message before they will execute.
*/
/* Creates a data task with the given request. The request may have a body stream. */
public func dataTaskWithRequest(_ request: URLRequest) -> URLSessionDataTask { NSUnimplemented() }
/* Creates a data task to retrieve the contents of the given URL. */
public func dataTaskWithURL(_ url: URL) -> URLSessionDataTask { NSUnimplemented() }
/* Creates an upload task with the given request. The body of the request will be created from the file referenced by fileURL */
public func uploadTaskWithRequest(_ request: URLRequest, fromFile fileURL: URL) -> URLSessionUploadTask { NSUnimplemented() }
/* Creates an upload task with the given request. The body of the request is provided from the bodyData. */
public func uploadTaskWithRequest(_ request: URLRequest, fromData bodyData: Data) -> URLSessionUploadTask { NSUnimplemented() }
/* Creates an upload task with the given request. The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
public func uploadTaskWithStreamedRequest(_ request: URLRequest) -> URLSessionUploadTask { NSUnimplemented() }
/* Creates a download task with the given request. */
public func downloadTaskWithRequest(_ request: URLRequest) -> URLSessionDownloadTask { NSUnimplemented() }
/* Creates a download task to download the contents of the given URL. */
public func downloadTaskWithURL(_ url: URL) -> URLSessionDownloadTask { NSUnimplemented() }
/* Creates a download task with the resume data. If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
public func downloadTaskWithResumeData(_ resumeData: Data) -> URLSessionDownloadTask { NSUnimplemented() }
/* Creates a bidirectional stream task to a given host and port.
*/
public func streamTaskWithHostName(_ hostname: String, port: Int) -> URLSessionStreamTask { NSUnimplemented() }
}
/*
* NSURLSession convenience routines deliver results to
* a completion handler block. These convenience routines
* are not available to NSURLSessions that are configured
* as background sessions.
*
* Task objects are always created in a suspended state and
* must be sent the -resume message before they will execute.
*/
extension URLSession {
/*
* data task convenience methods. These methods create tasks that
* bypass the normal delegate calls for response and data delivery,
* and provide a simple cancelable asynchronous interface to receiving
* data. Errors will be returned in the NSURLErrorDomain,
* see <Foundation/NSURLError.h>. The delegate, if any, will still be
* called for authentication challenges.
*/
public func dataTaskWithRequest(_ request: URLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionDataTask { NSUnimplemented() }
public func dataTaskWithURL(_ url: URL, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionDataTask { NSUnimplemented() }
/*
* upload convenience method.
*/
public func uploadTaskWithRequest(_ request: URLRequest, fromFile fileURL: NSURL, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionUploadTask { NSUnimplemented() }
public func uploadTaskWithRequest(_ request: URLRequest, fromData bodyData: Data?, completionHandler: (Data?, URLResponse?, NSError?) -> Void) -> URLSessionUploadTask { NSUnimplemented() }
/*
* download task convenience methods. When a download successfully
* completes, the NSURL will point to a file that must be read or
* copied during the invocation of the completion routine. The file
* will be removed automatically.
*/
public func downloadTaskWithRequest(_ request: URLRequest, completionHandler: (NSURL?, URLResponse?, NSError?) -> Void) -> URLSessionDownloadTask { NSUnimplemented() }
public func downloadTaskWithURL(_ url: NSURL, completionHandler: (NSURL?, URLResponse?, NSError?) -> Void) -> URLSessionDownloadTask { NSUnimplemented() }
public func downloadTaskWithResumeData(_ resumeData: Data, completionHandler: (NSURL?, URLResponse?, NSError?) -> Void) -> URLSessionDownloadTask { NSUnimplemented() }
}
extension URLSessionTask {
public enum State: Int {
case running /* The task is currently being serviced by the session */
case suspended
case canceling /* The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message. */
case completed /* The task has completed and the session will receive no more delegate notifications */
}
}
/*
* NSURLSessionTask - a cancelable object that refers to the lifetime
* of processing a given request.
*/
public class URLSessionTask: NSObject, NSCopying {
public override init() {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
NSUnimplemented()
}
public var taskIdentifier: Int { NSUnimplemented() } /* an identifier for this task, assigned by and unique to the owning session */
/*@NSCopying*/ public var originalRequest: URLRequest? { NSUnimplemented() } /* may be nil if this is a stream task */
/*@NSCopying*/ public var currentRequest: URLRequest? { NSUnimplemented() } /* may differ from originalRequest due to http server redirection */
/*@NSCopying*/ public var response: URLResponse? { NSUnimplemented() } /* may be nil if no response has been received */
/* Byte count properties may be zero if no body is expected,
* or NSURLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/* number of body bytes already received */
public var countOfBytesReceived: Int64 { NSUnimplemented() }
/* number of body bytes already sent */
public var countOfBytesSent: Int64 { NSUnimplemented() }
/* number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
public var countOfBytesExpectedToSend: Int64 { NSUnimplemented() }
/* number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
public var countOfBytesExpectedToReceive: Int64 { NSUnimplemented() }
/*
* The taskDescription property is available for the developer to
* provide a descriptive label for the task.
*/
public var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
public func cancel() { NSUnimplemented() }
/*
* The current state of the task within the session.
*/
public var state: State { NSUnimplemented() }
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ public var error: NSError? { NSUnimplemented() }
/*
* Suspending a task will prevent the NSURLSession from continuing to
* load data. There may still be delegate calls made on behalf of
* this task (for instance, to report data received while suspending)
* but no further transmissions will be made on behalf of the task
* until -resume is sent. The timeout timer associated with the task
* will be disabled while a task is suspended. -suspend and -resume are
* nestable.
*/
public func suspend() { NSUnimplemented() }
public func resume() { NSUnimplemented() }
/*
* Sets a scaling factor for the priority of the task. The scaling factor is a
* value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
* priority and 1.0 is considered the highest.
*
* The priority is a hint and not a hard requirement of task performance. The
* priority of a task may be changed using this API at any time, but not all
* protocols support this; in these cases, the last priority that took effect
* will be used.
*
* If no priority is specified, the task will operate with the default priority
* as defined by the constant NSURLSessionTaskPriorityDefault. Two additional
* priority levels are provided: NSURLSessionTaskPriorityLow and
* NSURLSessionTaskPriorityHigh, but use is not restricted to these.
*/
public var priority: Float
}
public let NSURLSessionTaskPriorityDefault: Float = 0.0 // NSUnimplemented
public let NSURLSessionTaskPriorityLow: Float = 0.0 // NSUnimplemented
public let NSURLSessionTaskPriorityHigh: Float = 0.0 // NSUnimplemented
/*
* An NSURLSessionDataTask does not provide any additional
* functionality over an NSURLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
public class URLSessionDataTask: URLSessionTask {
}
/*
* An NSURLSessionUploadTask does not currently provide any additional
* functionality over an NSURLSessionDataTask. All delegate messages
* that may be sent referencing an NSURLSessionDataTask equally apply
* to NSURLSessionUploadTasks.
*/
public class URLSessionUploadTask: URLSessionDataTask {
}
/*
* NSURLSessionDownloadTask is a task that represents a download to
* local storage.
*/
public class URLSessionDownloadTask: URLSessionTask {
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
public func cancelByProducingResumeData(_ completionHandler: (Data?) -> Void) { NSUnimplemented() }
}
/*
* An NSURLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via NSURLSession. This task
* may be explicitly created from an NSURLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* NSURLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create NSInputStream and NSOutputStream
* instances from an NSURLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
public class URLSessionStreamTask: URLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
public func readDataOfMinLength(_ minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: (Data?, Bool, NSError?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
public func writeData(_ data: Data, timeout: TimeInterval, completionHandler: (NSError?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
public func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
public func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
public func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
public func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
public func stopSecureConnection() { NSUnimplemented() }
}
/*
* Configuration options for an NSURLSession. When a session is
* created, a copy of the configuration object is made - you cannot
* modify the configuration of a session after it has been created.
*
* The shared session uses the global singleton credential, cache
* and cookie storage objects.
*
* An ephemeral session has no persistent disk storage for cookies,
* cache or credentials.
*
* A background session can be used to perform networking operations
* on behalf of a suspended application, within certain constraints.
*/
public class URLSessionConfiguration: NSObject, NSCopying {
public override init() {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
NSUnimplemented()
}
public class func defaultSessionConfiguration() -> URLSessionConfiguration { NSUnimplemented() }
public class func ephemeralSessionConfiguration() -> URLSessionConfiguration { NSUnimplemented() }
public class func backgroundSessionConfigurationWithIdentifier(_ identifier: String) -> URLSessionConfiguration { NSUnimplemented() }
/* identifier for the background session configuration */
public var identifier: String? { NSUnimplemented() }
/* default cache policy for requests */
public var requestCachePolicy: NSURLRequest.CachePolicy
/* default timeout for requests. This will cause a timeout if no data is transmitted for the given timeout value, and is reset whenever data is transmitted. */
public var timeoutIntervalForRequest: TimeInterval
/* default timeout for requests. This will cause a timeout if a resource is not able to be retrieved within a given timeout. */
public var timeoutIntervalForResource: TimeInterval
/* type of service for requests. */
public var networkServiceType: URLRequest.NetworkServiceType
/* allow request to route over cellular. */
public var allowsCellularAccess: Bool
/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
public var discretionary: Bool
/* The identifier of the shared data container into which files in background sessions should be downloaded.
* App extensions wishing to use background sessions *must* set this property to a valid container identifier, or
* all transfers in that session will fail with NSURLErrorBackgroundSessionRequiresSharedContainer.
*/
public var sharedContainerIdentifier: String?
/*
* Allows the app to be resumed or launched in the background when tasks in background sessions complete
* or when auth is required. This only applies to configurations created with +backgroundSessionConfigurationWithIdentifier:
* and the default value is YES.
*/
/* The proxy dictionary, as described by <CFNetwork/CFHTTPStream.h> */
public var connectionProxyDictionary: [NSObject : AnyObject]?
// TODO: We don't have the SSLProtocol type from Security
/*
/* The minimum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
public var TLSMinimumSupportedProtocol: SSLProtocol
/* The maximum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
public var TLSMaximumSupportedProtocol: SSLProtocol
*/
/* Allow the use of HTTP pipelining */
public var HTTPShouldUsePipelining: Bool
/* Allow the session to set cookies on requests */
public var HTTPShouldSetCookies: Bool
/* Policy for accepting cookies. This overrides the policy otherwise specified by the cookie storage. */
public var httpCookieAcceptPolicy: HTTPCookie.AcceptPolicy
/* Specifies additional headers which will be set on outgoing requests.
Note that these headers are added to the request only if not already present. */
public var HTTPAdditionalHeaders: [NSObject : AnyObject]?
/* The maximum number of simultanous persistent connections per host */
public var HTTPMaximumConnectionsPerHost: Int
/* The cookie storage object to use, or nil to indicate that no cookies should be handled */
public var httpCookieStorage: HTTPCookieStorage?
/* The credential storage object, or nil to indicate that no credential storage is to be used */
public var urlCredentialStorage: URLCredentialStorage?
/* The URL resource cache, or nil to indicate that no caching is to be performed */
public var urlCache: URLCache?
/* Enable extended background idle mode for any tcp sockets created. Enabling this mode asks the system to keep the socket open
* and delay reclaiming it when the process moves to the background (see https://developer.apple.com/library/ios/technotes/tn2277/_index.html)
*/
public var shouldUseExtendedBackgroundIdleMode: Bool
/* An optional array of Class objects which subclass NSURLProtocol.
The Class will be sent +canInitWithRequest: when determining if
an instance of the class can be used for a given URL scheme.
You should not use +[NSURLProtocol registerClass:], as that
method will register your class with the default session rather
than with an instance of NSURLSession.
Custom NSURLProtocol subclasses are not available to background
sessions.
*/
public var protocolClasses: [AnyClass]?
}
/*
* Disposition options for various delegate messages
*/
extension URLSession {
public enum AuthChallengeDisposition: Int {
case useCredential /* Use the specified credential, which may be nil */
case performDefaultHandling /* Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored. */
case cancelAuthenticationChallenge /* The entire request will be canceled; the credential parameter is ignored. */
case rejectProtectionSpace /* This challenge is rejected and the next authentication protection space should be tried; the credential parameter is ignored. */
}
public enum ResponseDisposition: Int {
case cancel /* Cancel the load, this is the same as -[task cancel] */
case allow /* Allow the load to continue */
case becomeDownload /* Turn this request into a download */
case becomeStream /* Turn this task into a stream task */
}
}
/*
* NSURLSessionDelegate specifies the methods that a session delegate
* may respond to. There are both session specific messages (for
* example, connection based auth) as well as task based messages.
*/
/*
* Messages related to the URL session as a whole
*/
public protocol URLSessionDelegate : NSObjectProtocol {
/* The last message a session receives. A session will only become
* invalid because of a systemic error or when it has been
* explicitly invalidated, in which case the error parameter will be nil.
*/
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: NSError?)
/* If implemented, when a connection level authentication challenge
* has occurred, this delegate will be given the opportunity to
* provide authentication credentials to the underlying
* connection. Some types of authentication will apply to more than
* one request on a given connection to a server (SSL Server Trust
* challenges). If this delegate message is not implemented, the
* behavior will be to use the default handling, which may involve user
* interaction.
*/
func urlSession(_ session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
}
extension URLSessionDelegate {
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: NSError?) { }
func urlSession(_ session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { }
}
/* If an application has received an
* -application:handleEventsForBackgroundURLSession:completionHandler:
* message, the session delegate will receive this message to indicate
* that all messages previously enqueued for this session have been
* delivered. At this time it is safe to invoke the previously stored
* completion handler, or to begin any internal updates that will
* result in invoking the completion handler.
*/
/*
* Messages related to the operation of a specific task.
*/
public protocol URLSessionTaskDelegate : URLSessionDelegate {
/* An HTTP request is attempting to perform a redirection to a different
* URL. You must invoke the completion routine to allow the
* redirection, allow the redirection with a modified request, or
* pass nil to the completionHandler to cause the body of the redirection
* response to be delivered as the payload of this request. The default
* is to follow redirections.
*
* For tasks in background sessions, redirections will always be followed and this method will not be called.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: URLRequest, completionHandler: (URLRequest?) -> Void)
/* The task has received a request specific authentication challenge.
* If this delegate is not implemented, the session specific authentication challenge
* will *NOT* be called and the behavior will be the same as using the default handling
* disposition.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
/* Sent if a task requires a new, unopened body stream. This may be
* necessary when authentication has failed for any request that
* involves a body stream.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (InputStream?) -> Void)
/* Sent periodically to notify the delegate of upload progress. This
* information is also available as properties of the task.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
/* Sent as the last message related to a specific task. Error may be
* nil, which implies that no error occurred and this task is complete.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?)
}
extension URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: URLRequest, completionHandler: (URLRequest?) -> Void) { }
func urlSession(_ session: URLSession, task: URLSessionTask, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { }
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (InputStream?) -> Void) { }
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { }
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) { }
}
/*
* Messages related to the operation of a task that delivers data
* directly to the delegate.
*/
public protocol URLSessionDataDelegate : URLSessionTaskDelegate {
/* The task has received a response and no further messages will be
* received until the completion block is called. The disposition
* allows you to cancel a request or to turn a data task into a
* download task. This delegate message is optional - if you do not
* implement it, you can get the response as a property of the task.
*
* This method will not be called for background upload tasks (which cannot be converted to download tasks).
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void)
/* Notification that a data task has become a download task. No
* future messages will be sent to the data task.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeDownloadTask downloadTask: URLSessionDownloadTask)
/*
* Notification that a data task has become a bidirectional stream
* task. No future messages will be sent to the data task. The newly
* created streamTask will carry the original request and response as
* properties.
*
* For requests that were pipelined, the stream object will only allow
* reading, and the object will immediately issue a
* -URLSession:writeClosedForStream:. Pipelining can be disabled for
* all requests in a session, or by the NSURLRequest
* HTTPShouldUsePipelining property.
*
* The underlying connection is no longer considered part of the HTTP
* connection cache and won't count against the total number of
* connections per host.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeStreamTask streamTask: URLSessionStreamTask)
/* Sent when data is available for the delegate to consume. It is
* assumed that the delegate will retain and not copy the data. As
* the data may be discontiguous, you should use
* [NSData enumerateByteRangesUsingBlock:] to access it.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: Data)
/* Invoke the completion routine with a valid NSCachedURLResponse to
* allow the resulting data to be cached, or pass nil to prevent
* caching. Note that there is no guarantee that caching will be
* attempted for a given resource, and you should not rely on this
* message to receive the resource data.
*/
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: (CachedURLResponse?) -> Void)
}
extension URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeDownloadTask downloadTask: URLSessionDownloadTask) { }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecomeStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: (CachedURLResponse?) -> Void) { }
}
/*
* Messages related to the operation of a task that writes data to a
* file and notifies the delegate upon completion.
*/
public protocol URLSessionDownloadDelegate : URLSessionTaskDelegate {
/* Sent when a download task that has completed a download. The delegate should
* copy or move the file at the given location to a new location as it will be
* removed when the delegate message returns. URLSession:task:didCompleteWithError: will
* still be called.
*/
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingToURL location: URL)
/* Sent periodically to notify the delegate of download progress. */
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
/* Sent when a download has been resumed. If a download failed with an
* error, the -userInfo dictionary of the error will contain an
* NSURLSessionDownloadTaskResumeData key, whose value is the resume
* data.
*/
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
}
extension URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { }
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { }
}
public protocol URLSessionStreamDelegate : URLSessionTaskDelegate {
/* Indiciates that the read side of a connection has been closed. Any
* outstanding reads complete, but future reads will immediately fail.
* This may be sent even when no reads are in progress. However, when
* this delegate message is received, there may still be bytes
* available. You only know that no more bytes are available when you
* are able to read until EOF. */
func urlSession(_ session: URLSession, readClosedForStreamTask streamTask: URLSessionStreamTask)
/* Indiciates that the write side of a connection has been closed.
* Any outstanding writes complete, but future writes will immediately
* fail.
*/
func urlSession(_ session: URLSession, writeClosedForStreamTask streamTask: URLSessionStreamTask)
/* A notification that the system has determined that a better route
* to the host has been detected (eg, a wi-fi interface becoming
* available.) This is a hint to the delegate that it may be
* desirable to create a new task for subsequent work. Note that
* there is no guarantee that the future task will be able to connect
* to the host, so callers should should be prepared for failure of
* reads and writes over any new interface. */
func urlSession(_ session: URLSession, betterRouteDiscoveredForStreamTask streamTask: URLSessionStreamTask)
/* The given task has been completed, and unopened NSInputStream and
* NSOutputStream objects are created from the underlying network
* connection. This will only be invoked after all enqueued IO has
* completed (including any necessary handshakes.) The streamTask
* will not receive any further delegate messages.
*/
func urlSession(_ session: URLSession, streamTask: URLSessionStreamTask, didBecomeInputStream inputStream: InputStream, outputStream: NSOutputStream)
}
extension URLSessionStreamDelegate {
func urlSession(_ session: URLSession, readClosedForStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, writeClosedForStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, betterRouteDiscoveredForStreamTask streamTask: URLSessionStreamTask) { }
func urlSession(_ session: URLSession, streamTask: URLSessionStreamTask, didBecomeInputStream inputStream: InputStream, outputStream: NSOutputStream) { }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let NSURLSessionDownloadTaskResumeData: String = "" // NSUnimplemented
| apache-2.0 | 8dbad0d83ed493f12de926c6b1bb5c76 | 49.445963 | 270 | 0.737078 | 5.412368 | false | false | false | false |
eugenepavlyuk/swift-algorithm-club | GCD/GCD.playground/Contents.swift | 8 | 577 | //: Playground - noun: a place where people can play
// Recursive version
func gcd(_ a: Int, _ b: Int) -> Int {
let r = a % b
if r != 0 {
return gcd(b, r)
} else {
return b
}
}
/*
// Iterative version
func gcd(m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
*/
func lcm(_ m: Int, _ n: Int) -> Int {
return m*n / gcd(m, n)
}
gcd(52, 39) // 13
gcd(228, 36) // 12
gcd(51357, 3819) // 57
gcd(841, 299) // 1
lcm(2, 3) // 6
lcm(10, 8) // 40
| mit | 5a3ae8c1691b4b9bb0309c4b70944995 | 13.794872 | 52 | 0.467938 | 2.42437 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application | Chula Expo 2017/Chula Expo 2017/FacultyDescCell.swift | 1 | 1390 | //
// FacultyDescCell.swift
// Chula Expo 2017
//
// Created by NOT on 2/26/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
class FacultyDescCell: UITableViewCell {
var facityTitle: String? {
didSet{
updateUI()
}
}
var facityDesc: String? {
didSet{
updateUI()
}
}
var facTag: String?{
didSet{
if let tag = facTag{
tagCap.setText(name: tag)
}
else{
tagCap.text = nil
}
}
}
@IBOutlet var titleLabel: UILabel!
@IBOutlet var descLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBOutlet var tagCap: CapsuleUILabel!
private func updateUI(){
titleLabel.text = nil
descLabel.text = nil
if let title = facityTitle {
titleLabel.text = title
}
if let desc = facityDesc {
descLabel.text = desc
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 100d43f1ef2a7a9ff788a1199df27607 | 18.842857 | 78 | 0.5018 | 4.839721 | false | false | false | false |
tottakai/RxSwift | RxCocoa/macOS/NSTextField+Rx.swift | 8 | 3223 | //
// NSTextField+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 5/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(macOS)
import Foundation
import Cocoa
#if !RX_NO_MODULE
import RxSwift
#endif
/// Delegate proxy for `NSTextField`.
///
/// For more information take a look at `DelegateProxyType`.
public class RxTextFieldDelegateProxy
: DelegateProxy
, NSTextFieldDelegate
, DelegateProxyType {
fileprivate let textSubject = PublishSubject<String?>()
/// Typed parent object.
public weak private(set) var textField: NSTextField?
/// Initializes `RxTextFieldDelegateProxy`
///
/// - parameter parentObject: Parent object for delegate proxy.
public required init(parentObject: AnyObject) {
self.textField = (parentObject as! NSTextField)
super.init(parentObject: parentObject)
}
// MARK: Delegate methods
public override func controlTextDidChange(_ notification: Notification) {
let textField = notification.object as! NSTextField
let nextValue = textField.stringValue
self.textSubject.on(.next(nextValue))
}
// MARK: Delegate proxy methods
/// For more information take a look at `DelegateProxyType`.
public override class func createProxyForObject(_ object: AnyObject) -> AnyObject {
let control = (object as! NSTextField)
return castOrFatalError(control.createRxDelegateProxy())
}
/// For more information take a look at `DelegateProxyType`.
public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let textField: NSTextField = castOrFatalError(object)
return textField.delegate
}
/// For more information take a look at `DelegateProxyType`.
public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let textField: NSTextField = castOrFatalError(object)
textField.delegate = castOptionalOrFatalError(delegate)
}
}
extension NSTextField {
/// Factory method that enables subclasses to implement their own `delegate`.
///
/// - returns: Instance of delegate proxy that wraps `delegate`.
public func createRxDelegateProxy() -> RxTextFieldDelegateProxy {
return RxTextFieldDelegateProxy(parentObject: self)
}
}
extension Reactive where Base: NSTextField {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy {
return RxTextFieldDelegateProxy.proxyForObject(base)
}
/// Reactive wrapper for `text` property.
public var text: ControlProperty<String?> {
let delegate = RxTextFieldDelegateProxy.proxyForObject(base)
let source = Observable.deferred { [weak textField = self.base] in
delegate.textSubject.startWith(textField?.stringValue)
}.takeUntil(deallocated)
let observer = UIBindingObserver(UIElement: base) { (control, value: String?) in
control.stringValue = value ?? ""
}
return ControlProperty(values: source, valueSink: observer.asObserver())
}
}
#endif
| mit | 356cb9cf3c1580370f7c466d07a62df9 | 29.685714 | 94 | 0.691496 | 5.264706 | false | false | false | false |
thewisecity/declarehome-ios | CookedApp/TableViewControllers/GroupsCheckboxTableViewController.swift | 1 | 3960 | //
// GroupsCheckboxTableViewController.swift
// CookedApp
//
// Created by Dexter Lohnes on 11/2/15.
// Copyright © 2015 The Wise City. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class GroupsCheckboxTableViewController: PFQueryTableViewController, GroupCheckboxDelegate {
var delegate: GroupCheckboxTableViewDelegate?
var selectedGroups: NSMutableArray
required init?(coder aDecoder: NSCoder) {
selectedGroups = NSMutableArray()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 54.0
self.title = "Select Groups for Alert"
}
func addNavBarDoneButton() -> Void
{
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "finishGroupSelection"), animated: true)
}
func finishGroupSelection() -> Void
{
delegate?.finishedChoosingGroups(selectedGroups as AnyObject as! [Group])
print("Finished")
}
func removeNavBarDoneButton() -> Void
{
self.navigationItem.setRightBarButtonItem(nil, animated: true)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func queryForTable() -> PFQuery
{
let query = PFQuery(className: self.parseClassName!)
query.orderByAscending("city")
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell?
{
let cellIdentifier = "GroupCheckboxCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? GroupCheckboxCell
if cell == nil {
cell = GroupCheckboxCell(style: .Subtitle, reuseIdentifier: cellIdentifier)
}
// We don't want these cells to light up when we touch them
cell?.selectionStyle = .None
// Configure the cell to show todo item with a priority at the bottom
if let group = object as? Group {
cell?.group = group
}
cell?.delegate = self
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let cell:GroupCheckboxCell = self.tableView(tableView, cellForRowAtIndexPath: indexPath) as! GroupCheckboxCell
// cell.checkSwitch.removeFromSuperview()
// cell.checkSwitch.setOn(true, animated: true)
// cell.checkSwitch.setNeedsDisplay()
//
// let selectedGroup = objectAtIndexPath(indexPath) as? Group
// performSegueWithIdentifier("ViewMessageWallSegue", sender: selectedGroup)
}
// 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.
if let selectedGroup = sender as? Group{
if let destinationController = segue.destinationViewController as? MessageWallViewController {
destinationController.group = selectedGroup
}
}
}
// Delegate methods
func groupCheckChanged(cell: GroupCheckboxCell, isChecked: Bool) -> Void
{
if(isChecked == true)
{
selectedGroups.addObject(cell.group)
}
else
{
selectedGroups.removeObject(cell.group)
}
if(selectedGroups.count > 0)
{
addNavBarDoneButton()
}
else
{
removeNavBarDoneButton()
}
}
}
| gpl-3.0 | 0816de4f5b15ca7bf5be6aa017dce9a0 | 30.672 | 177 | 0.649659 | 5.34278 | false | false | false | false |
andreamazz/Tropos | Sources/Tropos/ViewControllers/TextViewController.swift | 3 | 764 | import UIKit
class TextViewController: UIViewController {
@IBOutlet var textView: UITextView!
@objc var text: String?
override func viewDidLoad() {
super.viewDidLoad()
textView.contentInset = UIEdgeInsets.zero
textView.textContainerInset = UIEdgeInsets(
top: 20.0,
left: 20.0,
bottom: 20.0,
right: 20.0
)
textView.font = UIFont.defaultRegularFont(size: 14)
textView.textColor = .lightText
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.text = text
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
textView.contentOffset = .zero
}
}
| mit | eb3a027eeac41bce64ef0aae7463ac25 | 24.466667 | 59 | 0.617801 | 5.059603 | false | false | false | false |
nsagora/validation-toolkit | Sources/Predicates/Standard/BlockPredicate.swift | 1 | 1971 | import Foundation
/**
The `BlockPredicate` struct defines a closure based condition used to evaluate generic inputs.
```swift
let predicate = BlockPredicate<Int> {
$0 % 2 == 0
}
let isEven = even.evaluate(with: 2)
```
*/
public struct BlockPredicate<T>: Predicate {
public typealias InputType = T
private let evaluationBlock: (InputType) -> Bool
/**
Returns a new `BlockPredicate` instance.
```swift
let predicate = BlockPredicate<Int> {
$0 % 2 == 0
}
let isEven = even.evaluate(with: 2)
```
- parameter evaluationBlock: A closure describing a custom validation condition.
- parameter input: The input against which to evaluate the receiver.
*/
public init(evaluationBlock: @escaping (_ input: InputType) -> Bool) {
self.evaluationBlock = evaluationBlock
}
/**
Returns a `Boolean` value that indicates whether a given input matches the evaluation closure specified by the receiver.
- parameter input: The input against which to evaluate the receiver.
- returns: `true` if input matches the validation closure specified by the receiver, otherwise `false`.
*/
public func evaluate(with input: InputType) -> Bool {
return evaluationBlock(input)
}
}
// MARK: - Dynamic Lookup Extension
extension Predicate {
/**
Returns a new `BlockPredicate` instance.
```swift
let predicate: BlockPredicate<Int> = .block {
$0 % 2 == 0
}
let isEven = even.evaluate(with: 2)
```
- parameter evaluationBlock: A closure describing a custom validation condition.
- parameter input: The input against which to evaluate the receiver.
*/
public static func block<T>(evaluationBlock: @escaping (_ input: T) -> Bool) -> Self where Self == BlockPredicate<T> {
BlockPredicate(evaluationBlock: evaluationBlock)
}
}
| mit | e319ee127a147c9e5251fe6b91e8ec03 | 27.157143 | 125 | 0.638255 | 4.830882 | false | false | false | false |
otanistudio/NaiveHTTP | NaiveHTTPTests/UtilityTests.swift | 1 | 1331 | //
// NormalizedURLTests.swift
// NaiveHTTP
//
// Created by Robert Otani on 9/6/15.
// Copyright © 2015 otanistudio.com. All rights reserved.
//
import XCTest
import NaiveHTTP
class UtilityTests: XCTestCase {
func testNormalizedURLInit() {
let testQueryParams = ["a":"123","b":"456"]
let url = URL(string: "http://example.com", params: testQueryParams)
XCTAssertEqual(URL(string: "http://example.com?a=123&b=456"), url)
}
func testNormalizedURLWithExistingQueryParameters() {
let testQueryParams = ["a":"123","b":"456"]
let url = URL(string: "http://example.com?c=xxx&d=yyy", params: testQueryParams)
XCTAssertEqual(URL(string: "http://example.com?a=123&b=456&c=xxx&d=yyy"), url)
}
func testNormalizedURLWithNilQueryParam() {
let url = URL(string: "http://example.com", params: nil)
let expectedURL = URL(string: "http://example.com")
XCTAssertEqual(expectedURL, url)
}
// func testFilteredJSON() {
// let str: String = "while(1);\n[\"bleh\", \"blah\"]"
// let data: Data = str.data(using: String.Encoding.utf8)!
// let json = SwiftyHTTP.filteredJSON("while(1);", data: data)
// let expected: JSON = ["bleh", "blah"]
// XCTAssertEqual(expected, json)
// }
}
| mit | 3f8450af213d7646263fe439070ae0bf | 33.102564 | 88 | 0.61203 | 3.518519 | false | true | false | false |
GitTennis/SuccessFramework | Templates/_BusinessAppSwift_/_BusinessAppSwift_/Factories/ViewControllerFactory.swift | 2 | 18650 | //
// ViewControllerFactory.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 06/09/16.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
class ViewControllerFactory: ViewControllerFactoryProtocol {
// MARK: ViewControllerFactoryProtocol
required init(managerFactory: ManagerFactoryProtocol) {
_managerFactory = managerFactory
}
// MARK: Intro
func launchViewController(context: Any?)->LaunchViewController {
let vc = viewControllerFromXib(classType: LaunchViewController.self, context: context) as! LaunchViewController
vc.model = self.model(classType: LaunchModel.self as AnyClass, context: context) as? LaunchModel
return vc
}
func walkthroughViewController(context: Any?)->WalkthroughViewController {
let vc = viewControllerFromXib(classType: WalkthroughViewController.self, context: context) as! WalkthroughViewController
vc.model = self.model(classType: WalkthroughModel.self as AnyClass, context: context) as? WalkthroughModel
return vc
}
// MARK: Content
func homeViewController(context: Any?)->HomeViewController {
let vc = viewControllerFromSb(classType: HomeViewController.self, context: context) as! HomeViewController
vc.model = self.model(classType: HomeModel.self as AnyClass, context: context) as? HomeModel
return vc
}
func photoDetailsViewController(context: Any?)->PhotoDetailsViewController {
let vc = viewControllerFromSb(classType: PhotoDetailsViewController.self, context: context) as! PhotoDetailsViewController
vc.model = self.model(classType: PhotoDetailsModel.self as AnyClass, context: context) as? PhotoDetailsModel
return vc
}
// MARK: User
func startViewController(context: Any?)->StartViewController {
let vc = viewControllerFromSb(classType: StartViewController.self, context: context) as! StartViewController
vc.model = self.model(classType: StartModel.self as AnyClass, context: context) as? StartModel
return vc
}
func userContainerViewController(context: Any?)->UserContainerViewController {
let vc = viewControllerFromSb(classType: UserContainerViewController.self, context: context) as! UserContainerViewController
vc.model = self.model(classType: UserContainerModel.self as AnyClass, context: context) as? UserContainerModel
vc.startVC = self.startViewController(context: nil)
vc.startVC?.delegate = vc
vc.loginVc = self.userLoginViewController(context: nil)
vc.loginVc?.delegate = vc
return vc
}
func userLoginViewController(context: Any?)->UserLoginViewController {
let vc = viewControllerFromSb(classType: UserLoginViewController.self, context: context) as! UserLoginViewController
vc.model = self.model(classType: UserLoginModel.self as AnyClass, context: context) as? UserLoginModel
return vc
}
func userSignUpViewController(context: Any?)->UserSignUpViewController {
let vc = viewControllerFromSb(classType: UserSignUpViewController.self, context: context) as! UserSignUpViewController
vc.model = self.model(classType: SignUpModel.self as AnyClass, context: context) as? SignUpModel
return vc
}
func userResetPasswordViewController(context: Any?)->UserResetPasswordViewController {
let vc = viewControllerFromSb(classType: UserResetPasswordViewController.self, context: context) as! UserResetPasswordViewController
vc.model = self.model(classType: UserResetPasswordModel.self as AnyClass, context: context) as? UserResetPasswordModel
return vc
}
func userProfileViewController(context: Any?)->UserProfileViewController {
let vc = viewControllerFromSb(classType: UserProfileViewController.self, context: context) as! UserProfileViewController
vc.model = self.model(classType: UserProfileModel.self as AnyClass, context: context) as? UserProfileModel
return vc
}
// Legal
func termsConditionsViewController(context: Any?)->TermsConditionsViewController {
let vc = viewControllerFromSb(classType: TermsConditionsViewController.self, context: context) as! TermsConditionsViewController
vc.model = self.model(classType: TermsConditionsModel.self as AnyClass, context: context) as? TermsConditionsModel
return vc
}
func privacyPolicyViewController(context: Any?)->PrivacyPolicyViewController {
let vc = viewControllerFromSb(classType: PrivacyPolicyViewController.self, context: context) as! PrivacyPolicyViewController
vc.model = self.model(classType: PrivacyPolicyModel.self as AnyClass, context: context) as? PrivacyPolicyModel
return vc
}
// MARK: Maps
func mapsViewController(context: Any?)->MapsViewController {
let vc = viewControllerFromSb(classType: MapsViewController.self, context: context) as! MapsViewController
vc.model = self.model(classType: MapsModel.self as AnyClass, context: context) as? MapsModel
return vc
}
// MARK: Menu
func menuViewController(context: Any?)->MenuViewController {
let vc = viewControllerFromSb(classType: MenuViewController.self, context: context) as! MenuViewController
vc.model = self.model(classType: MenuModel.self as AnyClass, context: context) as? MenuModel
vc.model?.viewControllerFactory = self
return vc
}
// MARK: Reusable
func countryPickerViewController(context: Any?)->CountryPickerViewController {
let vc = viewControllerFromSb(classType: CountryPickerViewController.self, context: context) as! CountryPickerViewController
vc.model = self.model(classType: CountryPickerModel.self as AnyClass, context: context) as? CountryPickerModel
return vc
}
func contactViewController(context: Any?)->ContactViewController {
let vc = viewControllerFromSb(classType: ContactViewController.self, context: context) as! ContactViewController
vc.model = self.model(classType: ContactModel.self as AnyClass, context: context) as? ContactModel
return vc
}
func settingsViewController(context: Any?)->SettingsViewController {
let vc = viewControllerFromSb(classType: SettingsViewController.self, context: context) as! SettingsViewController
vc.model = self.model(classType: SettingsModel.self as AnyClass, context: context) as? SettingsModel
return vc
}
// MARK: Demo
func tableViewExampleViewController(context: Any?)->TableViewExampleViewController {
let vc = viewControllerFromSb(classType: TableViewExampleViewController.self, context: context) as! TableViewExampleViewController
vc.model = self.model(classType: TableViewExampleModel.self as AnyClass, context: context) as? TableViewExampleModel
return vc
}
func tableWithSearchViewController(context: Any?)->TableWithSearchViewController {
let vc = viewControllerFromSb(classType: TableWithSearchViewController.self, context: context) as! TableWithSearchViewController
vc.model = self.model(classType: TableWithSearchModel.self as AnyClass, context: context) as? TableWithSearchModel
return vc
}
// MARK:
// MARK: Internal
// MARK:
internal var _managerFactory: ManagerFactoryProtocol
// Returns true if viewController had property and it was injected with the value
// The approach used from: https://thatthinginswift.com/dependency-injection-storyboards-swift/
// Using Mirror for reflection and KVO for injecting
internal func needsDependency(viewController: UIViewController, propertyName: String)->Bool {
var result: Bool = false
let vcMirror = Mirror(reflecting: viewController)
let superVcMirror: Mirror? = vcMirror.superclassMirror
let superSuperVcMirror: Mirror? = superVcMirror?.superclassMirror
let superSuperSuperVcMirror: Mirror? = superSuperVcMirror?.superclassMirror
result = self.containsProperty(mirror: vcMirror, propertyName: propertyName)
result = result || self.containsProperty(mirror: superVcMirror, propertyName: propertyName)
result = result || self.containsProperty(mirror: superSuperVcMirror, propertyName: propertyName)
result = result || self.containsProperty(mirror: superSuperSuperVcMirror, propertyName: propertyName)
return result
}
internal func containsProperty(mirror: Mirror?, propertyName: String) -> Bool {
var result: Bool = false
if let mirror = mirror {
let vcProperties = mirror.children.filter { ($0.label ?? "").isEqual(propertyName) }
if vcProperties.first != nil {
result = true
}
}
return result
}
internal func name(viewControllerClassType: AnyClass)->String {
var viewControllerClassName: String = NSStringFromClass(viewControllerClassType)
// Autopick depending on platform
if isIpad {
viewControllerClassName = viewControllerClassName + "_ipad"
} else if isIphone {
viewControllerClassName = viewControllerClassName + "_iphone"
}
return viewControllerClassName
}
internal func viewControllerFromSb(classType: AnyClass, context: Any?)->UIViewController {
var viewControllerClassName: String = self.name(viewControllerClassType: classType)
viewControllerClassName = viewControllerClassName.components(separatedBy: ".").last!
let storyboard = UIStoryboard(name: viewControllerClassName, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: viewControllerClassName)
injectDependencies(viewController: vc, context: context)
return vc
}
internal func viewControllerFromXib(classType: AnyClass, context: Any?)->UIViewController {
let viewControllerClassName: String = self.name(viewControllerClassType: classType)
//let deviceClass: AnyClass? = NSClassFromString(viewControllerClassName);
let deviceClass = NSClassFromString(viewControllerClassName) as! UIViewController.Type
let vc: UIViewController = deviceClass.init()
injectDependencies(viewController: vc, context: context)
return vc
}
/*override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var vc = segue.destination as! GenericViewControllerProtocol;
self.injectDependencies(viewController: &vc);
//if (segue.identifier == "Load View") {
// pass data to next view
//}
}*/
func injectDependencies(viewController: UIViewController, context: Any?) {
if self.needsDependency(viewController: viewController, propertyName: "context") {
(viewController as! GenericViewControllerProtocol).context = context
}
if self.needsDependency(viewController: viewController, propertyName: "viewLoader") {
(viewController as! GenericViewControllerProtocol).viewLoader = self.viewLoader()
}
if self.needsDependency(viewController: viewController, propertyName: "crashManager") {
(viewController as! GenericViewControllerProtocol).crashManager = self._managerFactory.crashManager
}
if self.needsDependency(viewController: viewController, propertyName: "analyticsManager") {
(viewController as! GenericViewControllerProtocol).analyticsManager = self._managerFactory.analyticsManager
}
if self.needsDependency(viewController: viewController, propertyName: "messageBarManager") {
(viewController as! GenericViewControllerProtocol).messageBarManager = self._managerFactory.messageBarManager
}
if self.needsDependency(viewController: viewController, propertyName: "viewControllerFactory") {
(viewController as! GenericViewControllerProtocol).viewControllerFactory = self
}
if self.needsDependency(viewController: viewController, propertyName: "localizationManager") {
(viewController as! GenericViewControllerProtocol).localizationManager = self._managerFactory.localizationManager
}
if self.needsDependency(viewController: viewController, propertyName: "userManager") {
(viewController as! GenericViewControllerProtocol).userManager = self._managerFactory.userManager
}
if self.needsDependency(viewController: viewController, propertyName: "reachabilityManager") {
(viewController as! GenericViewControllerProtocol).reachabilityManager = self._managerFactory.reachabilityManager
self.addNetworkStatusObserving(viewController: viewController as! GenericViewControllerProtocol)
}
}
func addNetworkStatusObserving(viewController: GenericViewControllerProtocol) {
weak var weakGenericViewController = viewController
weak var weakViewController = (viewController as! UIViewController)
// TODO: not calling after second on/off switch
self._managerFactory.reachabilityManager.addServiceObserver(observer: weakViewController as! ReachabilityManagerObserver, notificationType: ReachabilityManagerNotificationType.internetDidBecomeOn, callback: { /*[weak self]*/ (success, result, context, error) in
let lastVc = weakViewController?.navigationController?.viewControllers.last
// Check for error and only handle once, inside last screen
if (lastVc == weakViewController) {
weakGenericViewController?.viewLoader?.hideNoInternetConnectionLabel(containerView: (weakViewController?.view)!)
}
}, context: nil)
self._managerFactory.reachabilityManager.addServiceObserver(observer: weakViewController as! ReachabilityManagerObserver
, notificationType: ReachabilityManagerNotificationType.internetDidBecomeOff, callback: { /*[weak self]*/ (success, result, context, error) in
weakGenericViewController?.viewLoader?.showNoInternetConnectionLabel(containerView: (weakViewController?.view)!)
}, context: nil)
// Subscribe and handle network errors
let notificationCenter: NotificationCenter = NotificationCenter.default
notificationCenter.addObserver(forName: NetworkRequestError.notification, object: self, queue: nil) { [weak self] (notification) in
if let info = notification.userInfo as? Dictionary<String,Error> {
let error: ErrorEntity? = info[NetworkRequestError.notificationUserInfoErrorKey] as? ErrorEntity
if let error = error {
// Check for error and only handle once, inside last screen
if (weakViewController?.navigationController?.viewControllers.last == weakViewController) {
if (error.code == NetworkRequestError.unauthorized.code) {
// Go to start
weakGenericViewController?.logoutAndGoBackToAppStart(error: error)
} else {
self?._managerFactory.messageBarManager.showMessage(title: " ", description: error.message, type: MessageBarMessageType.error)
}
}
}
}
}
}
internal func model(classType: AnyClass, context: Any?) -> BaseModel {
let className: String = NSStringFromClass(classType)
let deviceClass = NSClassFromString(className) as! BaseModel.Type
let model: BaseModel = deviceClass.init()
model.userManager = _managerFactory.userManager
model.settingsManager = _managerFactory.settingsManager
model.networkOperationFactory = _managerFactory.networkOperationFactory
model.reachabilityManager = _managerFactory.reachabilityManager
model.analyticsManager = _managerFactory.analyticsManager
model.context = context
model.commonInit()
return model
}
internal func viewLoader()->ViewLoader {
let loader: ViewLoader = ViewLoader()
return loader
}
}
| mit | 2354507baa8e256d350c591692611336 | 42.066975 | 269 | 0.670957 | 6.003863 | false | false | false | false |
zhuozhuo/ZHChat | SwiftExample/ZHChatSwift/ZHRootTableViewController.swift | 1 | 2367 | //
// ZHRootTableViewController.swift
// ZHChatSwift
//
// Created by aimoke on 16/12/15.
// Copyright © 2016年 zhuo. All rights reserved.
//
import UIKit
class ZHRootTableViewController: UITableViewController {
var dataArray: [String] = ["Push","Present"];
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView.init();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RootreuseIdentifier", for: indexPath);
cell.textLabel?.text = dataArray[indexPath.row];
// Configure the cell...
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row);
switch indexPath.row {
case 0:
let messagesVC: ZHCDemoMessagesViewController = ZHCDemoMessagesViewController.init();
messagesVC.presentBool = false;
self.navigationController?.pushViewController(messagesVC, animated: true);
case 1:
let messagesVC: ZHCDemoMessagesViewController = ZHCDemoMessagesViewController.init();
messagesVC.presentBool = true;
let nav: UINavigationController = UINavigationController.init(rootViewController: messagesVC);
self.navigationController?.present(nav, animated: true, completion: nil);
default:
break;
}
}
/*
// 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.
}
*/
}
| mit | 4b616d81ca8c09079d992fbd1b539a2e | 30.105263 | 109 | 0.661591 | 5.300448 | false | false | false | false |
mightydeveloper/swift | stdlib/public/core/Policy.swift | 9 | 15662 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The empty tuple type.
///
/// This is the default return type of functions for which no explicit
/// return type is specified.
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
// Integer literals are limited to 2048 bits.
// The intent is to have arbitrary-precision literals, but implementing that
// requires more work.
//
// Rationale: 1024 bits are enough to represent the absolute value of min/max
// IEEE Binary64, and we need 1 bit to represent the sign. Instead of using
// 1025, we use the next round number -- 2048.
public typealias _MaxBuiltinIntegerType = Builtin.Int2048
#if arch(i386) || arch(x86_64)
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
/// The protocol to which all types implicitly conform.
public typealias Any = protocol<>
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// When used as a concrete type, all known `@objc` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyObject`. For
/// example:
///
/// class C {
/// @objc func getCValue() -> Int { return 42 }
/// }
///
/// // If x has a method @objc getValue()->Int, call it and
/// // return the result. Otherwise, return nil.
/// func getCValue1(x: AnyObject) -> Int? {
/// if let f: ()->Int = x.getCValue { // <===
/// return f()
/// }
/// return nil
/// }
///
/// // A more idiomatic implementation using "optional chaining"
/// func getCValue2(x: AnyObject) -> Int? {
/// return x.getCValue?() // <===
/// }
///
/// // An implementation that assumes the required method is present
/// func getCValue3(x: AnyObject) -> Int { // <===
/// return x.getCValue() // x.getCValue is implicitly unwrapped. // <===
/// }
///
/// - SeeAlso: `AnyClass`
@objc
public protocol AnyObject : class {}
#else
/// The protocol to which all classes implicitly conform.
///
/// - SeeAlso: `AnyClass`
public protocol AnyObject : class {}
#endif
// Implementation note: the `AnyObject` protocol *must* not have any method or
// property requirements.
// FIXME: AnyObject should have an alternate version for non-objc without
// the @objc attribute, but AnyObject needs to be not be an address-only
// type to be able to be the target of castToNativeObject and an empty
// non-objc protocol appears not to be. There needs to be another way to make
// this the right kind of object.
/// The protocol to which all class types implicitly conform.
///
/// When used as a concrete type, all known `@objc` `class` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyClass`. For
/// example:
///
/// class C {
/// @objc class var cValue: Int { return 42 }
/// }
///
/// // If x has an @objc cValue: Int, return its value.
/// // Otherwise, return nil.
/// func getCValue(x: AnyClass) -> Int? {
/// return x.cValue // <===
/// }
///
/// - SeeAlso: `AnyObject`
public typealias AnyClass = AnyObject.Type
@warn_unused_result
public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return Bool(Builtin.cmp_eq_RawPointer(
Builtin.bridgeToRawPointer(Builtin.castToNativeObject(l)),
Builtin.bridgeToRawPointer(Builtin.castToNativeObject(r))
))
case (nil, nil):
return true
default:
return false
}
}
@warn_unused_result
public func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
return !(lhs === rhs)
}
//
// Equatable
//
/// Instances of conforming types can be compared for value equality
/// using operators `==` and `!=`.
///
/// When adopting `Equatable`, only the `==` operator is required to be
/// implemented. The standard library provides an implementation for `!=`.
public protocol Equatable {
/// Return true if `lhs` is equal to `rhs`.
///
/// **Equality implies substitutability**. When `x == y`, `x` and
/// `y` are interchangeable in any code that only depends on their
/// values.
///
/// Class instance identity as distinguished by triple-equals `===`
/// is notably not part of an instance's value. Exposing other
/// non-value aspects of `Equatable` types is discouraged, and any
/// that *are* exposed should be explicitly pointed out in
/// documentation.
///
/// **Equality is an equivalence relation**
///
/// - `x == x` is `true`
/// - `x == y` implies `y == x`
/// - `x == y` and `y == z` implies `x == z`
///
/// **Inequality is the inverse of equality**, i.e. `!(x == y)` iff
/// `x != y`.
@warn_unused_result
func == (lhs: Self, rhs: Self) -> Bool
}
@warn_unused_result
public func != <T : Equatable>(lhs: T, rhs: T) -> Bool {
return !(lhs == rhs)
}
//
// Comparable
//
@warn_unused_result
public func > <T : Comparable>(lhs: T, rhs: T) -> Bool {
return rhs < lhs
}
@warn_unused_result
public func <= <T : Comparable>(lhs: T, rhs: T) -> Bool {
return !(rhs < lhs)
}
@warn_unused_result
public func >= <T : Comparable>(lhs: T, rhs: T) -> Bool {
return !(lhs < rhs)
}
/// Instances of conforming types can be compared using relational
/// operators, which define a [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order).
///
/// A type conforming to `Comparable` need only supply the `<` and
/// `==` operators; default implementations of `<=`, `>`, `>=`, and
/// `!=` are supplied by the standard library:
///
/// struct Singular : Comparable {}
/// func ==(x: Singular, y: Singular) -> Bool { return true }
/// func <(x: Singular, y: Singular) -> Bool { return false }
///
/// **Axioms**, in addition to those of `Equatable`:
///
/// - `x == y` implies `x <= y`, `x >= y`, `!(x < y)`, and `!(x > y)`
/// - `x < y` implies `x <= y` and `y > x`
/// - `x > y` implies `x >= y` and `y < x`
/// - `x <= y` implies `y >= x`
/// - `x >= y` implies `y <= x`
public protocol Comparable : Equatable {
/// A [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order)
/// over instances of `Self`.
@warn_unused_result
func < (lhs: Self, rhs: Self) -> Bool
@warn_unused_result
func <= (lhs: Self, rhs: Self) -> Bool
@warn_unused_result
func >= (lhs: Self, rhs: Self) -> Bool
@warn_unused_result
func > (lhs: Self, rhs: Self) -> Bool
}
/// A set type with O(1) standard bitwise operators.
///
/// Each instance is a subset of `~Self.allZeros`.
///
/// **Axioms**, where `x` is an instance of `Self`:
///
/// - `x | Self.allZeros == x`
/// - `x ^ Self.allZeros == x`
/// - `x & Self.allZeros == .allZeros`
/// - `x & ~Self.allZeros == x`
/// - `~x == x ^ ~Self.allZeros`
public protocol BitwiseOperationsType {
/// Returns the intersection of bits set in `lhs` and `rhs`.
///
/// - Complexity: O(1).
@warn_unused_result
func & (lhs: Self, rhs: Self) -> Self
/// Returns the union of bits set in `lhs` and `rhs`.
///
/// - Complexity: O(1).
@warn_unused_result
func | (lhs: Self, rhs: Self) -> Self
/// Returns the bits that are set in exactly one of `lhs` and `rhs`.
///
/// - Complexity: O(1).
@warn_unused_result
func ^ (lhs: Self, rhs: Self) -> Self
/// Returns `x ^ ~Self.allZeros`.
///
/// - Complexity: O(1).
@warn_unused_result
prefix func ~ (x: Self) -> Self
/// The empty bitset.
///
/// Also the [identity element](http://en.wikipedia.org/wiki/Identity_element) for `|` and
/// `^`, and the [fixed point](http://en.wikipedia.org/wiki/Fixed_point_(mathematics)) for
/// `&`.
static var allZeros: Self { get }
}
@warn_unused_result
public func |= <T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
lhs = lhs | rhs
}
@warn_unused_result
public func &= <T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
lhs = lhs & rhs
}
@warn_unused_result
public func ^= <T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
lhs = lhs ^ rhs
}
/// Instances of conforming types provide an integer `hashValue` and
/// can be used as `Dictionary` keys.
public protocol Hashable : Equatable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
var hashValue: Int { get }
}
public protocol _SinkType {}
@available(*, unavailable, message="SinkType has been removed. Use (T)->() closures directly instead.")
public typealias SinkType = _SinkType
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
// Equatable types can be matched in patterns by value equality.
@_transparent
@warn_unused_result
public func ~= <T : Equatable> (a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ++ {}
postfix operator -- {}
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator ! {}
// Standard prefix operators.
prefix operator ++ {}
prefix operator -- {}
prefix operator ! {}
prefix operator ~ {}
prefix operator + {}
prefix operator - {}
// Standard infix operators.
// "Exponentiative"
infix operator << { associativity none precedence 160 }
infix operator >> { associativity none precedence 160 }
// "Multiplicative"
infix operator * { associativity left precedence 150 }
infix operator &* { associativity left precedence 150 }
infix operator / { associativity left precedence 150 }
infix operator % { associativity left precedence 150 }
infix operator & { associativity left precedence 150 }
// "Additive"
infix operator + { associativity left precedence 140 }
infix operator &+ { associativity left precedence 140 }
infix operator - { associativity left precedence 140 }
infix operator &- { associativity left precedence 140 }
infix operator | { associativity left precedence 140 }
infix operator ^ { associativity left precedence 140 }
// FIXME: is this the right precedence level for "..." ?
infix operator ... { associativity none precedence 135 }
infix operator ..< { associativity none precedence 135 }
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as { associativity none precedence 132 }
// "Coalescing"
infix operator ?? { associativity right precedence 131 }
// "Comparative"
infix operator < { associativity none precedence 130 }
infix operator <= { associativity none precedence 130 }
infix operator > { associativity none precedence 130 }
infix operator >= { associativity none precedence 130 }
infix operator == { associativity none precedence 130 }
infix operator != { associativity none precedence 130 }
infix operator === { associativity none precedence 130 }
infix operator !== { associativity none precedence 130 }
// FIXME: ~= will be built into the compiler.
infix operator ~= { associativity none precedence 130 }
// "Conjunctive"
infix operator && { associativity left precedence 120 }
// "Disjunctive"
infix operator || { associativity left precedence 110 }
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : { associativity right precedence 100 }
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator = { associativity right precedence 90 }
// Compound
infix operator *= { associativity right precedence 90 assignment }
infix operator /= { associativity right precedence 90 assignment }
infix operator %= { associativity right precedence 90 assignment }
infix operator += { associativity right precedence 90 assignment }
infix operator -= { associativity right precedence 90 assignment }
infix operator <<= { associativity right precedence 90 assignment }
infix operator >>= { associativity right precedence 90 assignment }
infix operator &= { associativity right precedence 90 assignment }
infix operator ^= { associativity right precedence 90 assignment }
infix operator |= { associativity right precedence 90 assignment }
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~> { associativity left precedence 255 }
| apache-2.0 | dc8666e5b481b133a64d21c303748885 | 33.804444 | 112 | 0.61761 | 4.328911 | false | false | false | false |
plushcube/Learning | Swift/Functional Swift Book/CoreImageFilter.playground/Contents.swift | 1 | 1931 | import UIKit
typealias Filter = (CIImage) -> CIImage
func blur(radius: Double) -> Filter {
return { image in
let parameters: [String: Any] = [
kCIInputRadiusKey: radius,
kCIInputImageKey: image
]
guard let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: parameters) else { fatalError() }
guard let outputImage = filter.outputImage else { fatalError() }
return outputImage
}
}
func generate(color: UIColor) -> Filter {
return { image in
let parameters = [ kCIInputColorKey: CIColor(cgColor: color.cgColor) ]
guard let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters) else { fatalError() }
guard let outputImage = filter.outputImage else { fatalError() }
return outputImage.cropping(to: image.extent)
}
}
func compositeSourceOver(overlay: CIImage) -> Filter {
return { image in
let parameters: [String: Any] = [
kCIInputBackgroundImageKey: image,
kCIInputImageKey: overlay
]
guard let filter = CIFilter(name: "CISourceOverCompositing", withInputParameters: parameters) else { fatalError() }
guard let outputImage = filter.outputImage else { fatalError() }
return outputImage.cropping(to: image.extent)
}
}
func overlay(color: UIColor) -> Filter {
return { image in
let overlay = generate(color: color)(image)
return compositeSourceOver(overlay: overlay)(image)
}
}
infix operator >>>
func >>>(filter1: @escaping Filter, filter2: @escaping Filter) -> Filter {
return { image in filter2(filter1(image)) }
}
let url = URL(string: "http://www.objc.io/images/covers/16.jpg")!
let image = CIImage(contentsOf: url)!
let radius = 5.0
let color = UIColor.red.withAlphaComponent(0.2)
let filter = blur(radius: radius) >>> overlay(color: color)
let result = filter(image)
| mit | 24950c900c893f5996c5ec0c3f5db938 | 32.877193 | 124 | 0.665976 | 4.319911 | false | false | false | false |
ukitaka/FPRealm | Tests/AnyRealmIOSpec.swift | 2 | 2430 | //
// AnyRealmIOSpec.swift
// RealmIO
//
// Created by ukitaka on 2017/05/31.
// Copyright © 2017年 waft. All rights reserved.
//
import RealmSwift
import RealmIO
import XCTest
import Quick
import Nimble
class AnyRealmIOSpec: QuickSpec {
let realm = try! Realm(configuration: Realm.Configuration(fileURL: nil, inMemoryIdentifier: "for test"))
override func spec() {
super.spec()
it("works well with `init(io:)`") {
let read = AnyRealmIO(io: RealmRO<Void> { _ in })
expect(read.isReadOnly).to(beTrue())
expect(try! self.realm.run(io: read)).notTo(throwError())
let write = AnyRealmIO(io: RealmRW<Void> { _ in })
expect(write.isReadWrite).to(beTrue())
expect(try! self.realm.run(io: write)).notTo(throwError())
}
it("works well with `init(error:isReadOnly)`") {
struct MyError: Error { }
let error = MyError()
let read = AnyRealmIO<Void>(error: error)
expect(read.isReadOnly).to(beTrue())
expect { try self.realm.run(io: read) }.to(throwError())
let write = AnyRealmIO<Void>(error: error, isReadOnly: false)
expect(write.isReadWrite).to(beTrue())
expect { try self.realm.run(io: write) }.to(throwError())
}
it("works well with `map` operator") {
let read = AnyRealmIO<Void>(io: RealmRO<Void> { _ in }).map { _ in "hello" }
expect(try! self.realm.run(io: read)).to(equal("hello"))
}
it("works well with `flatMap` operator") {
let read = RealmRO<String> { _ in "read" }
let write = RealmRW<String> { _ in "write" }
let io1 = AnyRealmIO(io: read).flatMap { _ in write }
expect(io1).to(beAnInstanceOf(RealmRW<String>.self))
expect(try! self.realm.run(io: io1)).to(equal("write"))
let io2 = AnyRealmIO(io: read).flatMap { _ in read }
expect(io2).to(beAnInstanceOf(AnyRealmIO<String>.self))
expect(try! self.realm.run(io: io2)).to(equal("read"))
}
it("works well with `ask` operator") {
let read = RealmRO<String> { _ in "read" }
let io = AnyRealmIO(io: read).ask()
expect(io).to(beAnInstanceOf(AnyRealmIO<Realm>.self))
expect(try! self.realm.run(io: io)).to(equal(self.realm))
}
}
}
| mit | 428c92466c65f83aa17ad0eea55c1111 | 35.223881 | 108 | 0.570663 | 3.756966 | false | false | false | false |
pawan007/SmartZip | SmartZip/Controllers/History/HistoryVC.swift | 1 | 5387 | //
// HistoryVC.swift
// SmartZip
//
// Created by Pawan Dhawan on 21/07/16.
// Copyright © 2016 Pawan Kumar. All rights reserved.
//
import UIKit
class HistoryVC: UIViewController {
// don't forget to hook this up from the storyboard
@IBOutlet var tableView: UITableView!
// Data model: These strings will be the data for the table view cells
var fileNames: [String] = []
var filePaths: [String] = []
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
// Register the table view cell class and its reuse id
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// self.navigationController?.navigationBarHidden = true
self.automaticallyAdjustsScrollViewInsets = false
getZipFileList()
}
// number of rows in table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.fileNames.count
}
// create a cell for each table view row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = fileNames[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
showActionSheet(indexPath.row)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{
return false
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
if editingStyle == .Delete {
let path = filePaths[indexPath.row]
print(path)
try! kFileManager.removeItemAtPath(filePaths[indexPath.row])
filePaths.removeAtIndex(indexPath.row)
fileNames.removeAtIndex(indexPath.row)
tableView.reloadData()
}
}
@IBAction func menuButtonAction(sender: AnyObject) {
if let container = SideMenuManager.sharedManager().container {
container.toggleDrawerSide(.Left, animated: true) { (val) -> Void in
}
}
}
func getZipFileList() -> Void {
let directoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
if let enumerator = kFileManager.enumeratorAtPath(directoryPath!) {
while let fileName = enumerator.nextObject() as? String {
if fileName.containsString(".zip") {
fileNames.append(fileName)
filePaths.append("\(directoryPath!)/\(fileName)")
}
}
}
tableView.reloadData()
}
func showActionSheet(index:Int) {
//Create the AlertController
let actionSheetController: UIAlertController = UIAlertController(title: kAlertTitle, message: "", preferredStyle: .ActionSheet)
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
CommonFunctions.sharedInstance.getFreeDiscSpase()
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
let takePictureAction: UIAlertAction = UIAlertAction(title: "Share", style: .Default) { action -> Void in
//Code for launching the camera goes here
let path = self.filePaths[index]
print(path)
CommonFunctions.sharedInstance.shareMyFile(path, vc: self)
}
actionSheetController.addAction(takePictureAction)
//Create and add a second option action
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Delete", style: .Default) { action -> Void in
//Code for picking from camera roll goes here
let path = self.filePaths[index]
print(path)
try! kFileManager.removeItemAtPath(self.filePaths[index])
self.filePaths.removeAtIndex(index)
self.fileNames.removeAtIndex(index)
self.tableView.reloadData()
}
actionSheetController.addAction(choosePictureAction)
if let popoverPresentationController = actionSheetController.popoverPresentationController {
popoverPresentationController.sourceView = self.view
var rect=self.view.frame
rect.origin.y = rect.height
popoverPresentationController.sourceRect = rect
}
//Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
}
| mit | ef8c0c4778390562dfa9b668e65e5d32 | 36.402778 | 147 | 0.63368 | 5.766595 | false | false | false | false |
mauryat/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 69873 | /* 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
@testable import Storage
import Deferred
import XCTest
let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000
let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000)
// Start everything three months ago.
let baseInstantInMillis = Date.now() - threeMonthsInMillis
let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros
func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp {
return timestamp + UInt64(by)
}
func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp {
return timestamp + UInt64(by)
}
extension Site {
func asPlace() -> Place {
return Place(guid: self.guid!, url: self.url, title: self.title)
}
}
class BaseHistoricalBrowserSchema: Schema {
var name: String { return "BROWSER" }
var version: Int { return -1 }
func update(_ db: SQLiteDBConnection, from: Int) -> Bool {
fatalError("Should never be called.")
}
func create(_ db: SQLiteDBConnection) -> Bool {
return false
}
func drop(_ db: SQLiteDBConnection) -> Bool {
return false
}
var supportsPartialIndices: Bool {
let v = sqlite3_libversion_number()
return v >= 3008000 // 3.8.0.
}
let oldFaviconsSQL =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool {
if let sql = sql {
let err = db.executeChange(sql, withArgs: args)
return err == nil
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
for sql in queries {
if let sql = sql {
if !run(db, sql: sql) {
return false
}
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
}
// Versions of BrowserSchema that we care about:
// v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015.
// This is when we first started caring about database versions.
//
// v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles.
//
// v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons.
//
// v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9.
//
// These tests snapshot the table creation code at each of these points.
class BrowserSchemaV6: BaseHistoricalBrowserSchema {
override var version: Int { return 6 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func CreateHistoryTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func CreateDomainsTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func CreateQueueTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
CreateDomainsTable(),
CreateHistoryTable(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
CreateQueueTable(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV7: BaseHistoricalBrowserSchema {
override var version: Int { return 7 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
override func create(_ db: SQLiteDBConnection) -> Bool {
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
getDomainsTableCreationString(),
getHistoryTableCreationString(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV8: BaseHistoricalBrowserSchema {
override var version: Int { return 8 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV10: BaseHistoricalBrowserSchema {
override var version: Int { return 10 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended.
// Record/envelope metadata that'll allow us to do merges.
", server_modified INTEGER NOT NULL" + // Milliseconds.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted.
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " +
"( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON visits (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class TestSQLiteHistory: XCTestCase {
let files = MockFiles()
fileprivate func deleteDatabases() {
for v in ["6", "7", "8", "10", "6-data"] {
do {
try files.remove("browser-v\(v).db")
} catch {}
}
do {
try files.remove("browser.db")
try files.remove("historysynced.db")
} catch {}
}
override func tearDown() {
super.tearDown()
self.deleteDatabases()
}
override func setUp() {
super.setUp()
// Just in case tearDown didn't run or succeed last time!
self.deleteDatabases()
}
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link)
let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link)
let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> { history.getSitesByFrecencyWithHistoryLimit(3)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let sources: [(Int, Schema)] = [
(6, BrowserSchemaV6()),
(7, BrowserSchemaV7()),
(8, BrowserSchemaV8()),
(10, BrowserSchemaV10()),
]
let destination = BrowserSchema()
for (version, table) in sources {
let db = BrowserDB(filename: "browser-v\(version).db", files: files)
XCTAssertTrue(
db.runWithConnection { (conn, err) in
XCTAssertTrue(table.create(conn), "Creating browser table version \(version)")
// And we can upgrade to the current version.
XCTAssertTrue(destination.update(conn, from: table.version), "Upgrading browser table from version \(version)")
}.value.isSuccess
)
db.forceClose()
}
}
func testUpgradesWithData() {
let db = BrowserDB(filename: "browser-v6-data.db", files: files)
XCTAssertTrue(db.prepareSchema(BrowserSchemaV6()) == .success, "Creating browser schema version 6")
// Insert some data.
let queries = [
"INSERT INTO domains (id, domain) VALUES (1, 'example.com')",
"INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)",
"INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)",
"INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)",
"INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)",
"INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')"
]
XCTAssertTrue(db.run(queries).value.isSuccess)
// And we can upgrade to the current version.
XCTAssertTrue(db.prepareSchema(BrowserSchema()) == .success, "Upgrading browser schema from version 6")
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let results = history.getSitesByLastVisit(10).value.successValue
XCTAssertNotNil(results)
XCTAssertEqual(results![0]?.url, "http://www.example.com")
db.forceClose()
}
func testDomainUpgrade() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
var err: NSError? = nil
// Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden.
let _ = db.withConnection(&err, callback: { (connection, err) -> Int in
let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"?, ?, ?, ?, ?, ?, ?"
let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1]
err = connection.executeChange(insert, withArgs: args)
return 0
})
// Now insert it again. This should update the domain
history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded()
// DomainID isn't normally exposed, so we manually query to get it
let results = db.withConnection(&err, callback: { (connection, err) -> Cursor<Int> in
let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: IntFactory, withArgs: args)
})
XCTAssertNotEqual(results[0]!, -1, "Domain id was updated")
}
func testDomains() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectation(description: "First.")
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds())
}).bind({ guid in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).bind({ (sites: Maybe<Cursor<Site>>) -> Success in
XCTAssert(sites.successValue!.count == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).upon({ (sites: Maybe<Cursor<Site>>) in
XCTAssert(sites.successValue!.count == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testHistoryIsSynced() {
let db = BrowserDB(filename: "historysynced.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGUID = Bytes.generateGUID()
let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title")
XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true)
XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess)
XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false)
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10)
>>== f
}
}
func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(10)
>>== f
}
}
func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10, whereURLContains: filter)
>>== f
}
}
func checkDeletedCount(_ expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>> { history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>> { history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>> { history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testFaviconTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
XCTAssertTrue(db.prepareSchema(BrowserSchema()) == .success)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: Date(), type: .icon)
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.testFactory.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesFrecencyOrder() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Create a new site thats for an existing domain but a different URL.
let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url")
site.guid = "abc\(5)defhi"
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).value
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesFiltersGoogle() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
func createTopSite(url: String, guid: String) {
let site = Site(url: url, title: "Hi")
site.guid = guid
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).value
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
}
createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite
createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite
createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite
createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite
// make sure all other google guids are not in the topsites array
topSites.forEach {
let guid: String = $0!.guid! // type checking is hard
XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].index(of: guid))
}
XCTAssertEqual(topSites.count, 20)
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesCache() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Make sure that we get back the top sites
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
XCTAssertEqual(topSites[1]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testPinnedTopSites() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// add 2 sites to pinned topsite
// get pinned site and make sure it exists in the right order
// remove pinned sites
// make sure pinned sites dont exist
// create pinned sites.
let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)")
site1.id = 1
site1.guid = "abc\(1)def"
addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now())
let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)")
site2.id = 2
site2.guid = "abc\(2)def"
addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now())
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func addPinnedSites() -> Success {
return history.addPinnedTopSite(site1) >>== {
return history.addPinnedTopSite(site2)
}
}
func checkPinnedSites() -> Success {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 2)
XCTAssertEqual(pinnedSites[0]!.url, site2.url)
XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last")
return succeed()
}
}
func removePinnedSites() -> Success {
return history.removeFromPinnedTopSites(site2) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func dupePinnedSite() -> Success {
return history.addPinnedTopSite(site1) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func removeHistory() -> Success {
return history.clearHistory() >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear")
return succeed()
}
}
}
addPinnedSites()
>>> checkPinnedSites
>>> removePinnedSites
>>> dupePinnedSite
>>> removeHistory
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.clearHistory().succeeded()
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded()
let ts: MicrosecondTimestamp = baseInstantInMicros
let local = SiteVisit(site: site, date: ts, type: VisitType.link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFilterSplitting: XCTestCase {
let history: SQLiteHistory = {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
return SQLiteHistory(db: db, prefs: prefs)
}()
func testWithSingleWord() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithDistinctWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithDistinctWordsAndWhitespace() {
let (fragment, args) = history.computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithSubstrings() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
func testWithSubstringsAndIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool {
return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in
return (oneElement as! String) == (otherElement as! String)
})
}
}
// MARK - Private Test Helper Methods
enum VisitOrigin {
case local
case remote
}
private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) {
for i in 0...count {
let site = Site(url: "http://s\(i)ite\(i).com/foo", title: "A \(i)")
site.guid = "abc\(i)def"
let baseMillis: UInt64 = baseInstantInMillis - 20000
history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).succeeded()
for j in 0...20 {
let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j))
addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime - 100)
}
}
}
func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) {
let visit = SiteVisit(site: site, date: atTime, type: VisitType.link)
switch from {
case .local:
history.addLocalVisit(visit).succeeded()
case .remote:
history.storeRemoteVisits([visit], forGUID: site.guid!).succeeded()
}
}
| mpl-2.0 | b6e3ddc6fbbde62cf9b375c1453d985d | 42.588896 | 231 | 0.588024 | 4.882809 | false | false | false | false |
MrDeveloper4/TestProject-GitHubAPI | TestProject-GitHubAPI/Pods/RealmSwift/RealmSwift/SortDescriptor.swift | 10 | 4018 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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 Realm
/**
A `SortDescriptor` stores a property name and a sort order for use with
`sorted(sortDescriptors:)`. It is similar to `NSSortDescriptor`, but supports
only the subset of functionality which can be efficiently run by Realm's query
engine.
*/
public struct SortDescriptor {
// MARK: Properties
/// The name of the property which the sort descriptor orders results by.
public let property: String
/// Whether the descriptor sorts in ascending or descending order.
public let ascending: Bool
/// Converts the receiver to an `RLMSortDescriptor`
internal var rlmSortDescriptorValue: RLMSortDescriptor {
return RLMSortDescriptor(property: property, ascending: ascending)
}
// MARK: Initializers
/**
Initializes a sort descriptor with the given property and sort order values.
- parameter property: The name of the property which the sort descriptor orders results by.
- parameter ascending: Whether the descriptor sorts in ascending or descending order.
*/
public init(property: String, ascending: Bool = true) {
self.property = property
self.ascending = ascending
}
// MARK: Functions
/// Returns a copy of the sort descriptor with the sort order reversed.
public func reversed() -> SortDescriptor {
return SortDescriptor(property: property, ascending: !ascending)
}
}
// MARK: CustomStringConvertible
extension SortDescriptor: CustomStringConvertible {
/// Returns a human-readable description of the sort descriptor.
public var description: String {
let direction = ascending ? "ascending" : "descending"
return "SortDescriptor (property: \(property), direction: \(direction))"
}
}
// MARK: Equatable
extension SortDescriptor: Equatable {}
/// Returns whether the two sort descriptors are equal.
public func == (lhs: SortDescriptor, rhs: SortDescriptor) -> Bool {
// swiftlint:disable:previous valid_docs
return lhs.property == rhs.property &&
lhs.ascending == lhs.ascending
}
// MARK: StringLiteralConvertible
extension SortDescriptor: StringLiteralConvertible {
/// `StringLiteralType`. Required for `StringLiteralConvertible` conformance.
public typealias UnicodeScalarLiteralType = StringLiteralType
/// `StringLiteralType`. Required for `StringLiteralConvertible` conformance.
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
/**
Creates a `SortDescriptor` from a `UnicodeScalarLiteralType`.
- parameter unicodeScalarLiteral: Property name literal.
*/
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(property: value)
}
/**
Creates a `SortDescriptor` from an `ExtendedGraphemeClusterLiteralType`.
- parameter extendedGraphemeClusterLiteral: Property name literal.
*/
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(property: value)
}
/**
Creates a `SortDescriptor` from a `StringLiteralType`.
- parameter stringLiteral: Property name literal.
*/
public init(stringLiteral value: StringLiteralType) {
self.init(property: value)
}
}
| mit | 25e7ac49e3c234dcc665916fec0c5fbc | 32.206612 | 96 | 0.69562 | 5.422402 | false | false | false | false |
MateuszKarwat/Napi | Napi/Models/Subtitle Format/Supported Subtitle Formats/TMPlayerSubtitleFormat.swift | 1 | 2581 | //
// Created by Mateusz Karwat on 06/02/16.
// Copyright © 2016 Mateusz Karwat. All rights reserved.
//
import Foundation
/// Represents TMPlayer Subtitle Format.
/// TMPlayer Subtitle Format looks like this:
///
/// 01:12:33:First line of a text.|Seconds line of a text.
struct TMPlayerSubtitleFormat: SubtitleFormat {
static let fileExtension = "txt"
static let isTimeBased = true
static let regexPattern = "(\\d{1,2}):(\\d{1,2}):(\\d{1,2}):(.+)"
static func decode(_ aString: String) -> [Subtitle] {
var decodedSubtitles = [Subtitle]()
self.enumerateMatches(in: aString) { match in
let hours = Int(match.capturedSubstrings[0])!.hours
let minutes = Int(match.capturedSubstrings[1])!.minutes
let seconds = Int(match.capturedSubstrings[2])!.seconds
let timestamp = hours + minutes + seconds
let newSubtitle = Subtitle(startTimestamp: timestamp,
stopTimestamp: timestamp + 5.seconds,
text: match.capturedSubstrings[3])
decodedSubtitles.append(newSubtitle)
}
if decodedSubtitles.count > 1 {
for i in 0 ..< decodedSubtitles.count - 1 {
let currentStopTimestamp = decodedSubtitles[i].stopTimestamp.baseValue
let followingStartTimestamp = decodedSubtitles[i + 1].startTimestamp.baseValue
if currentStopTimestamp > followingStartTimestamp {
decodedSubtitles[i].stopTimestamp = decodedSubtitles[i + 1].startTimestamp - 1.milliseconds
}
}
}
return decodedSubtitles
}
static func encode(_ subtitles: [Subtitle]) -> [String] {
var encodedSubtitles = [String]()
for subtitle in subtitles {
encodedSubtitles.append("\(subtitle.startTimestamp.stringFormat()):\(subtitle.text)")
}
return encodedSubtitles
}
}
fileprivate extension Timestamp {
/// Returns a `String` which is in format required by TMPlayer Subtitle Format.
func stringFormat() -> String {
let minutes = self - Timestamp(value: self.numberOfFull(.hours), unit: .hours)
let seconds = minutes - Timestamp(value: minutes.numberOfFull(.minutes), unit: .minutes)
return
"\(self.numberOfFull(.hours).toString(leadingZeros: 2)):" +
"\(minutes.numberOfFull(.minutes).toString(leadingZeros: 2)):" +
"\(seconds.numberOfFull(.seconds).toString(leadingZeros: 2))"
}
}
| mit | d980923bff1f59051da34d7e29b25b08 | 35.338028 | 111 | 0.617054 | 4.867925 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/ImagePicker/Source/ImageGallery/ImageGalleryView.swift | 1 | 7732 | import UIKit
import Photos
protocol ImageGalleryPanGestureDelegate: class {
func panGestureDidStart()
func panGestureDidChange(translation: CGPoint)
func panGestureDidEnd(translation: CGPoint, velocity: CGPoint)
}
public class ImageGalleryView: UIView {
struct Dimensions {
static let galleryHeight: CGFloat = 160
static let galleryBarHeight: CGFloat = 24
static let indicatorWidth: CGFloat = 41
static let indicatorHeight: CGFloat = 8
}
lazy public var collectionView: UICollectionView = { [unowned self] in
let collectionView = UICollectionView(frame: CGRectZero,
collectionViewLayout: self.collectionViewLayout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = Configuration.mainColor
collectionView.showsHorizontalScrollIndicator = false
collectionView.dataSource = self
collectionView.delegate = self
return collectionView
}()
lazy var collectionViewLayout: UICollectionViewLayout = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
layout.minimumInteritemSpacing = Configuration.cellSpacing
layout.minimumLineSpacing = 2
layout.sectionInset = UIEdgeInsetsZero
return layout
}()
lazy var topSeparator: UIView = { [unowned self] in
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.addGestureRecognizer(self.panGestureRecognizer)
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
return view
}()
lazy var indicator: UIView = {
let view = UIView()
view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.6)
view.layer.cornerRadius = Dimensions.indicatorHeight / 2
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in
let gesture = UIPanGestureRecognizer()
gesture.addTarget(self, action: #selector(handlePanGestureRecognizer(_:)))
return gesture
}()
public lazy var noImagesLabel: UILabel = { [unowned self] in
let label = UILabel()
label.font = Configuration.noImagesFont
label.textColor = Configuration.noImagesColor
label.text = Configuration.noImagesTitle
label.alpha = 0
label.sizeToFit()
self.addSubview(label)
return label
}()
public lazy var selectedStack = ImageStack()
lazy var assets = [PHAsset]()
weak var delegate: ImageGalleryPanGestureDelegate?
var collectionSize: CGSize?
var shouldTransform = false
var imagesBeforeLoading = 0
var fetchResult: PHFetchResult?
var canFetchImages = false
var imageLimit = 0
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Configuration.mainColor
collectionView.registerClass(ImageGalleryViewCell.self,
forCellWithReuseIdentifier: CollectionView.reusableIdentifier)
[collectionView, topSeparator].forEach { addSubview($0) }
topSeparator.addSubview(indicator)
imagesBeforeLoading = 0
fetchPhotos()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
updateNoImagesLabel()
}
func updateFrames() {
let totalWidth = UIScreen.mainScreen().bounds.width
frame.size.width = totalWidth
let collectionFrame = frame.height == Dimensions.galleryBarHeight ? 100 + Dimensions.galleryBarHeight : frame.height
topSeparator.frame = CGRect(x: 0, y: 0, width: totalWidth, height: Dimensions.galleryBarHeight)
topSeparator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleWidth]
indicator.frame = CGRect(x: (totalWidth - Dimensions.indicatorWidth) / 2, y: (topSeparator.frame.height - Dimensions.indicatorHeight) / 2,
width: Dimensions.indicatorWidth, height: Dimensions.indicatorHeight)
collectionView.frame = CGRect(x: 0, y: topSeparator.frame.height, width: totalWidth, height: collectionFrame - topSeparator.frame.height)
collectionSize = CGSize(width: collectionView.frame.height, height: collectionView.frame.height)
collectionView.reloadData()
}
func updateNoImagesLabel() {
let height = CGRectGetHeight(bounds)
let threshold = Dimensions.galleryBarHeight * 2
UIView.animateWithDuration(0.25) {
if threshold > height || self.collectionView.alpha != 0 {
self.noImagesLabel.alpha = 0
} else {
self.noImagesLabel.center = CGPoint(x: CGRectGetWidth(self.bounds) / 2, y: height / 2)
self.noImagesLabel.alpha = (height > threshold) ? 1 : (height - Dimensions.galleryBarHeight) / threshold
}
}
}
// MARK: - Photos handler
func fetchPhotos(completion: (() -> Void)? = nil) {
ImagePicker.fetch { assets in
self.assets.removeAll()
self.assets.appendContentsOf(assets)
self.collectionView.reloadData()
completion?()
}
}
// MARK: - Pan gesture recognizer
func handlePanGestureRecognizer(gesture: UIPanGestureRecognizer) {
guard let superview = superview else { return }
let translation = gesture.translationInView(superview)
let velocity = gesture.velocityInView(superview)
switch gesture.state {
case .Began:
delegate?.panGestureDidStart()
case .Changed:
delegate?.panGestureDidChange(translation)
case .Ended:
delegate?.panGestureDidEnd(translation, velocity: velocity)
default: break
}
}
func displayNoImagesMessage(hideCollectionView: Bool) {
collectionView.alpha = hideCollectionView ? 0 : 1
updateNoImagesLabel()
}
}
// MARK: CollectionViewFlowLayout delegate methods
extension ImageGalleryView: UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard let collectionSize = collectionSize else { return CGSizeZero }
return collectionSize
}
}
// MARK: CollectionView delegate methods
extension ImageGalleryView: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let cell = collectionView.cellForItemAtIndexPath(indexPath)
as? ImageGalleryViewCell else { return }
let asset = assets[indexPath.row]
ImagePicker.resolveAsset(asset) { image in
guard let _ = image else { return }
if cell.selectedImageView.image != nil {
UIView.animateWithDuration(0.2, animations: {
cell.selectedImageView.transform = CGAffineTransformMakeScale(0.1, 0.1)
}) { _ in
cell.selectedImageView.image = nil
}
self.selectedStack.dropAsset(asset)
} else if self.imageLimit == 0 || self.imageLimit > self.selectedStack.assets.count {
cell.selectedImageView.image = AssetManager.getImage("selectedImageGallery")
cell.selectedImageView.transform = CGAffineTransformMakeScale(0, 0)
UIView.animateWithDuration(0.2) { _ in
cell.selectedImageView.transform = CGAffineTransformIdentity
}
self.selectedStack.pushAsset(asset)
}
}
}
public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath) {
guard indexPath.row + 10 >= assets.count
&& indexPath.row < fetchResult?.count
&& canFetchImages else { return }
fetchPhotos()
canFetchImages = false
}
}
| apache-2.0 | 7e6303dcced8abeabec70fbd1924e2e2 | 31.624473 | 142 | 0.727108 | 5.343469 | false | false | false | false |
Reality-Virtually-Hackathon/Team-2 | WorkspaceAR/Connectivity/ConnectivityManager.swift | 1 | 5951 | //
// ConnectivityManager.swift
// WorkspaceAR
//
// Created by Joe Crotchett on 10/7/17.
// Copyright © 2017 Apple. All rights reserved.
//
import Foundation
import MultipeerConnectivity
protocol ConnectivityManagerDelegate {
// Called when a peer has changed it's connection status
func connectedDevicesChanged(manager : ConnectivityManager,
connectedDevices: [String])
// Called when data has been recieved from a peer
func dataReceived(manager: ConnectivityManager,
data: Data)
}
class ConnectivityManager : NSObject {
let ServiceType = "WorkspaceAR"
let myPeerId = MCPeerID(displayName: UIDevice.current.name)
var advertiser: MCNearbyServiceAdvertiser?
var browser: MCNearbyServiceBrowser?
var delegate : ConnectivityManagerDelegate?
lazy var session : MCSession = {
let session = MCSession(peer: self.myPeerId,
securityIdentity: nil,
encryptionPreference: .none)
session.delegate = self
return session
}()
deinit {
if let advertiser = advertiser {
advertiser.stopAdvertisingPeer()
}
if let browser = browser {
browser.stopBrowsingForPeers()
}
}
// Act as the host
func startAdvertising() {
advertiser = MCNearbyServiceAdvertiser(peer: myPeerId,
discoveryInfo: nil,
serviceType: ServiceType)
if let advertiser = advertiser {
advertiser.delegate = self
advertiser.startAdvertisingPeer()
}
}
// Act as the client
func startBrowsing() {
browser = MCNearbyServiceBrowser(peer: myPeerId,
serviceType: ServiceType)
if let browser = browser {
browser.delegate = self
browser.startBrowsingForPeers()
}
}
// Broadcast data to all peers
func sendTestString() {
print("Sending test string")
if session.connectedPeers.count > 0 {
do {
try self.session.send("test string".data(using: .utf8)!,
toPeers: session.connectedPeers,
with: .reliable)
}
catch let error {
print("%@", "Error for sending: \(error)")
}
}
}
// Broadcast data to all peers
func sendData(data: Data) {
if session.connectedPeers.count > 0 {
do {
try self.session.send(data, toPeers: session.connectedPeers, with: .reliable)
}
catch let error {
print("%@", "Error for sending: \(error)")
}
}
}
}
//MARK: MCNearbyServiceAdvertiserDelegate
extension ConnectivityManager: MCNearbyServiceAdvertiserDelegate {
func advertiser(_ advertiser: MCNearbyServiceAdvertiser,
didNotStartAdvertisingPeer error: Error) {
print("%@", "didNotStartAdvertisingPeer: \(error)")
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser,
didReceiveInvitationFromPeer peerID: MCPeerID,
withContext context: Data?,
invitationHandler: @escaping (Bool, MCSession?) -> Void) {
print("%@", "didReceiveInvitationFromPeer \(peerID)")
invitationHandler(true, self.session)
}
}
//MARK: MCNearbyServiceBrowserDelegate
extension ConnectivityManager : MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser,
didNotStartBrowsingForPeers error: Error) {
print("%@", "didNotStartBrowsingForPeers: \(error)")
}
func browser(_ browser: MCNearbyServiceBrowser,
foundPeer peerID: MCPeerID,
withDiscoveryInfo info: [String : String]?) {
print("%@", "foundPeer: \(peerID)")
print("%@", "invitePeer: \(peerID)")
browser.invitePeer(peerID,
to: self.session,
withContext: nil,
timeout: 10)
}
func browser(_ browser: MCNearbyServiceBrowser,
lostPeer peerID: MCPeerID) {
print("%@", "lostPeer: \(peerID)")
}
}
//MARK: MCSessionDelegate
extension ConnectivityManager : MCSessionDelegate {
func session(_ session: MCSession,
peer peerID: MCPeerID,
didChange state: MCSessionState) {
print("%@", "peer \(peerID) didChangeState: \(state)")
self.delegate?.connectedDevicesChanged(manager: self,
connectedDevices: session.connectedPeers.map{$0.displayName})
}
func session(_ session: MCSession,
didReceive data: Data,
fromPeer peerID: MCPeerID) {
print("%@", "didReceiveData: \(data)")
self.delegate?.dataReceived(manager: self, data: data)
}
func session(_ session:
MCSession, didReceive stream:
InputStream, withName streamName:
String, fromPeer peerID: MCPeerID) {
assert(true, "not impelemented")
}
func session(_ session: MCSession,
didStartReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID,
with progress: Progress) {
assert(true, "not impelemented")
}
func session(_ session: MCSession,
didFinishReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID,
at localURL: URL?,
withError error: Error?) {
assert(true, "not impelemented")
}
}
| mit | 2300f37458d9a6a2073b8dc4cb51d88b | 31.513661 | 108 | 0.56084 | 5.979899 | false | false | false | false |
pauljohanneskraft/Math | CoreMath/Classes/Numbers/Numbers.swift | 1 | 968 | //
// Numbers.swift
// Math
//
// Created by Paul Kraft on 03.08.16.
// Copyright © 2016 pauljohanneskraft. All rights reserved.
//
import Foundation
// swiftlint:disable type_name
public typealias R = Double
public typealias N = UInt
public typealias Z = Int
// swiftlint:enable type_name
public func Z_(_ v: UInt) -> Set<UInt> {
return Set<UInt>(0..<v)
}
public func Z_(_ v: Int) -> Set<Int> {
return Set<Int>(0..<v)
}
public protocol Ordered: Comparable {
static var min: Self { get }
static var max: Self { get }
}
extension Ordered {
static var range: ClosedRange<Self> {
return min...max
}
}
public protocol Randomizable: Comparable {
static func random(inside: ClosedRange<Self>) -> Self
}
infix operator =~ : ComparisonPrecedence
extension Double {
public static func =~ (lhs: Double, rhs: Double) -> Bool {
let inacc = Swift.max(lhs.inaccuracy, rhs.inaccuracy)
return (lhs - rhs).abs <= inacc
}
}
| mit | 379b9bc849a85ce50b91ef60b710e6b6 | 19.574468 | 62 | 0.658738 | 3.453571 | false | false | false | false |
gradyzhuo/GZImageLayoutView | GZImageEditorPositionView.swift | 1 | 7499 | //
// GZImageEditorPositionView.swift
// Flingy
//
// Created by Grady Zhuo on 7/2/15.
// Copyright (c) 2015 Skytiger Studio. All rights reserved.
//
import Foundation
import UIKit
internal let GZImageEditorDefaultZoomScale : CGFloat = 1.0
public class GZImageEditorPositionView:GZPositionView {
public var minZoomScale : CGFloat = GZImageEditorDefaultZoomScale
public var maxZoomScale : CGFloat = 3.0
internal var ratio:CGFloat = 1.0
private var privateObjectInfo = ObjectInfo()
public var delegate:GZImageEditorPositionViewDelegate?
internal var resizeContentMode:GZImageEditorResizeContentMode = .AspectFill
public var metaData:GZPositionViewMetaData{
set{
self.resizeContentMode = newValue.resizeContentMode
self.imageMetaData = newValue.imageMetaData
self.scrollViewMetaData = newValue.scrollViewMetaData
self.privateObjectInfo.metaData = newValue
}
get{
self.privateObjectInfo.metaData = GZPositionViewMetaData(resizeContentMode: self.resizeContentMode, imageMetaData: self.imageMetaData, scrollViewMetaData: self.scrollViewMetaData)
return self.privateObjectInfo.metaData
}
}
public var scrollViewMetaData:GZScrollViewMetaData{
set{
self.scrollView.zoomScale = newValue.zoomScale
self.scrollView.contentSize = newValue.contentSize
self.scrollView.contentOffset = newValue.contentOffset
}
get{
return GZScrollViewMetaData(scrollView: self.scrollView, imageRatio: self.ratio)
}
}
public var imageMetaData:GZPositionViewImageMetaData{
set{
self.setImage(self.resizeContentMode ,image: newValue.image, needResetScrollView: true)
}
get{
return GZPositionViewImageMetaData(identifier: self.identifier, image: self.image)
}
}
public var image:UIImage?{
set{
self.setImage(self.resizeContentMode, image: newValue, needResetScrollView: true)
}
get{
return self.scrollView.imageView.image
}
}
private lazy var scrollView:GZImageCropperScrollView = {
var scrollView = GZImageCropperScrollView(imageEditorPositionView: self)
scrollView.scrollsToTop = false
scrollView.delaysContentTouches = false
scrollView.minimumZoomScale = self.minZoomScale
scrollView.maximumZoomScale = self.maxZoomScale
return scrollView
}()
// public internal(set) lazy var imageView:UIImageView = {
//
// var imageView = UIImageView()
// imageView.contentMode = UIViewContentMode.ScaleAspectFill
//
//
// return imageView
// }()
override func configure(position: GZPosition!) {
super.configure(position)
self.addSubview(self.scrollView)
// self.scrollView.addSubview(self.imageView)
self.scrollView.frame = self.bounds
}
internal override var layoutView:GZImageLayoutView?{
didSet{
let image = layoutView?.imageForPosition(self.identifier)
if image == nil && self.image != nil {
layoutView?.setImage(self.image, forPosition: self.identifier)
}
}
}
public func setImage(resizeContentMode: GZImageEditorResizeContentMode,image:UIImage?, needResetScrollView reset:Bool){
self.scrollView.imageView.image = image
if reset{
self.resetScrollView(resizeContentMode, scrollView: self.scrollView, image: image)
}
if let parentLayoutView = self.layoutView {
var imageMetaData = parentLayoutView.imageMetaDataContent
if let newImage = image {
imageMetaData[self.identifier] = newImage
}else{
imageMetaData.removeValueForKey(self.identifier)
}
parentLayoutView.imageMetaDataContent = imageMetaData
}
}
override public func layoutSubviews() {
super.layoutSubviews()
self.scrollView.frame = self.bounds
let metaData = self.privateObjectInfo.metaData ?? self.metaData
self.imageMetaData = metaData.imageMetaData
self.scrollViewMetaData = metaData.scrollViewMetaData
}
struct ObjectInfo {
var metaData:GZPositionViewMetaData! = nil
}
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if let touch = touches.first {
let point = touch.locationInView(self)
let hitView = self.hitTest(point, withEvent: event)
if hitView == self.scrollView {
self.delegate?.imageEditorPositionViewWillBeginEditing(self)
}
}
}
}
//MARK: - Crop & Resize support
extension GZImageEditorPositionView {
internal func resetResizeContentMode(resizeContentMode : GZImageEditorResizeContentMode = .AspectFill){
self.resetScrollView(resizeContentMode, scrollView: self.scrollView, image: self.image)
}
internal func resetScrollView(resizeContentMode : GZImageEditorResizeContentMode = .AspectFill, scrollView:UIScrollView, image:UIImage?){
self.initializeScrollView(scrollView)
if let vaildImage = image{
//預先取出所需的屬性值
let scrollViewWidth = scrollView.frame.width
let scrollViewHeight = scrollView.frame.height
// let vaildImageWidth = vaildImage.size.width
// let vaildImageHeight = vaildImage.size.height
var zoomScaleToFillScreen:CGFloat = 1.0
var targetSize = CGSize.zero
(self.ratio, targetSize, zoomScaleToFillScreen) = resizeContentMode.targetContentSize(scrollSize: scrollView.frame.size, imageSize: vaildImage.size)
scrollView.maximumZoomScale = ceil(zoomScaleToFillScreen) + 2
//
scrollView.contentSize = targetSize
//
self.scrollView.imageView.frame.size = targetSize
let xOffsetToCenter:CGFloat = (targetSize.width - scrollViewWidth)/2
let yOffsetToCenter:CGFloat = (targetSize.height - scrollViewHeight)/2
scrollView.contentOffset.x += xOffsetToCenter
scrollView.contentOffset.y += yOffsetToCenter
scrollView.setZoomScale(zoomScaleToFillScreen, animated: false)
}
}
internal func initializeScrollView(scrollView:UIScrollView, contentSize:CGSize = CGSizeZero){
scrollView.zoomScale = self.minZoomScale
scrollView.contentOffset = CGPointZero
scrollView.contentSize = CGSizeZero
}
}
| apache-2.0 | 065017e38f6850cc202c486b518487c9 | 29.036145 | 191 | 0.604091 | 5.907583 | false | false | false | false |
kaxilisi/DouYu | DYZB/DYZB/Classes/Home/ViewModel/RecommendViewModel.swift | 1 | 3633 | //
// RecommendViewModel.swift
// DYZB
//
// Created by apple on 2016/10/29.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
class RecommendViewModel{
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
lazy var cycleModels : [CycleModel] = [CycleModel]()
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup()
}
//MARK:- 发送网络请求
extension RecommendViewModel{
func requestData(_ finishCallback : @escaping () -> ()){
let parameters = ["limit" : "4","offset":"0","time" : NSDate.getCurrentTime()]
//第一部分数据
let dGroup = DispatchGroup()
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time": NSDate.getCurrentTime()]) { (result) in
guard let resultDict = result as? [String : NSObject] else {return}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
for dict in dataArray{
let anchor = AnchorModel(dict)
self.bigDataGroup.anchors.append(anchor)
}
dGroup.leave()
}
//第二部分数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in
guard let resultDict = result as? [String : NSObject] else {return}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
for dict in dataArray{
let anchor = AnchorModel(dict)
self.prettyGroup.anchors.append(anchor)
}
dGroup.leave()
}
//第三部分数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in
guard let resultDict = result as? [String : NSObject] else {return}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
for dict in dataArray{
let group = AnchorGroup(dict)
if group.push_vertical_screen == "0"{
self.anchorGroups.append(group)
}
}
dGroup.leave()
}
dGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
func requestCycleData(_ finishCallback : @escaping () -> ()){
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/slide/6", parameters: ["version" : "2.401"]){ (result) in
guard let resultDict = result as? [String : NSObject] else {return}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//字典转模型
for dict in dataArray {
self.cycleModels.append(CycleModel(dict))
}
finishCallback()
}
}
}
| mit | 39d825842ae9015dec19836ffcdc86b7 | 35.742268 | 159 | 0.555275 | 4.822733 | false | false | false | false |
jairoeli/Habit | Zero/Sources/Utils/Reorder/ReorderController+DestinationRow.swift | 1 | 4789 | //
// Copyright (c) 2016 Adam Shin
//
// 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
extension CGRect {
init(center: CGPoint, size: CGSize) {
self.init(x: center.x - (size.width / 2), y: center.y - (size.height / 2), width: size.width, height: size.height)
}
}
extension ReorderController {
func updateDestinationRow() {
guard case let .reordering(sourceRow, destinationRow, snapshotOffset) = reorderState,
let tableView = tableView,
let newDestinationRow = newDestinationRow(),
newDestinationRow != destinationRow
else { return }
reorderState = .reordering(
sourceRow: sourceRow,
destinationRow: newDestinationRow,
snapshotOffset: snapshotOffset
)
delegate?.tableView(tableView, reorderRowAt: destinationRow, to: newDestinationRow)
tableView.beginUpdates()
tableView.deleteRows(at: [destinationRow], with: .fade)
tableView.insertRows(at: [newDestinationRow], with: .fade)
tableView.endUpdates()
}
func newDestinationRow() -> IndexPath? {
guard case let .reordering(_, destinationRow, _) = reorderState,
let delegate = delegate,
let tableView = tableView,
let snapshotView = snapshotView
else { return nil }
let snapshotFrame = CGRect(center: snapshotView.center, size: snapshotView.bounds.size)
let visibleRows = tableView.indexPathsForVisibleRows ?? []
let rowSnapDistances = visibleRows.map { path -> (path: IndexPath, distance: CGFloat) in
let rect = tableView.rectForRow(at: path)
if destinationRow.compare(path) == .orderedAscending {
return (path, abs(snapshotFrame.maxY - rect.maxY))
} else {
return (path, abs(snapshotFrame.minY - rect.minY))
}
}
let sectionIndexes = 0..<tableView.numberOfSections
let sectionSnapDistances = sectionIndexes.flatMap { section -> (path: IndexPath, distance: CGFloat)? in
let rowsInSection = tableView.numberOfRows(inSection: section)
if section > destinationRow.section {
let rect: CGRect
if rowsInSection == 0 {
rect = rectForEmptySection(section)
} else {
rect = tableView.rectForRow(at: IndexPath(row: 0, section: section))
}
let path = IndexPath(row: 0, section: section)
return (path, abs(snapshotFrame.maxY - rect.minY))
} else if section < destinationRow.section {
let rect: CGRect
if rowsInSection == 0 {
rect = rectForEmptySection(section)
} else {
rect = tableView.rectForRow(at: IndexPath(row: rowsInSection - 1, section: section))
}
let path = IndexPath(row: rowsInSection, section: section)
return (path, abs(snapshotFrame.minY - rect.maxY))
} else {
return nil
}
}
let snapDistances = rowSnapDistances + sectionSnapDistances
let availableSnapDistances = snapDistances.filter { delegate.tableView(tableView, canReorderRowAt: $0.path) != false }
return availableSnapDistances.min(by: { $0.distance < $1.distance })?.path
}
func rectForEmptySection(_ section: Int) -> CGRect {
guard let tableView = tableView else { return .zero }
let sectionRect = tableView.rectForHeader(inSection: section)
return UIEdgeInsetsInsetRect(sectionRect, UIEdgeInsets(top: sectionRect.height, left: 0, bottom: 0, right: 0))
}
}
| mit | 9de3d0c56f99fec7c2dbe1c8a6ab22f6 | 40.284483 | 126 | 0.640635 | 4.942208 | false | false | false | false |
openxc/openxc-ios-framework | openxc-ios-framework/VehicleMessageUnit.swift | 1 | 1957 | //
// VehicleMessageUnit.swift
// openxc-ios-framework
//
// Created by Ranjan, Kumar sahu (K.) on 12/03/18.
// Copyright © 2018 Ford Motor Company. All rights reserved.
//
import UIKit
open class VehicleMessageUnit: NSObject {
static let sharedNetwork = VehicleMessageUnit()
// Initialization
static open let sharedInstance: VehicleMessageUnit = {
let instance = VehicleMessageUnit()
return instance
}()
fileprivate override init() {
// connecting = false
}
public func getMesurementUnit(key:String , value:Any) -> Any{
let stringValue = String(describing: value)
let measurementType = key
var measurmentUnit : String = ""
switch measurementType {
case acceleratorPedal:
measurmentUnit = stringValue + " %"
return measurmentUnit
case enginespeed:
measurmentUnit = stringValue + " RPM"
return measurmentUnit
case fuelConsumed:
measurmentUnit = stringValue + " L"
return measurmentUnit
case fuelLevel:
measurmentUnit = stringValue + " %"
return measurmentUnit
case latitude:
measurmentUnit = stringValue + " °"
return measurmentUnit
case longitude:
measurmentUnit = stringValue + " °"
return measurmentUnit
case odometer:
measurmentUnit = stringValue + " km"
return measurmentUnit
case steeringWheelAngle:
measurmentUnit = stringValue + " °"
return measurmentUnit
case torqueTransmission:
measurmentUnit = stringValue + " Nm"
return measurmentUnit
case vehicleSpeed:
measurmentUnit = stringValue + " km/hr"
return measurmentUnit
default:
return value
}
//return value
}
}
| bsd-3-clause | 3502f5c5756eab51f163ba8ec7ed1ac5 | 28.590909 | 65 | 0.586278 | 5.677326 | false | false | false | false |
wess/reddift | reddiftSample/UserViewController.swift | 1 | 4883 | //
// UserViewController.swift
// reddift
//
// Created by sonson on 2015/04/14.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class UserViewController: UITableViewController {
var session:Session?
@IBOutlet var expireCell:UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
}
func updateExpireCell(sender:AnyObject?) {
println(NSThread.isMainThread())
if let token = session?.token {
expireCell.detailTextLabel?.text = NSDate(timeIntervalSinceReferenceDate:token.expiresDate).description
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
if indexPath.row == 2 && indexPath.section == 0 {
if let token = session?.token as? OAuth2Token {
token.refresh({ (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
if let newToken = result.value {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if var session = self.session {
session.token = newToken
}
self.updateExpireCell(nil)
OAuth2TokenRepository.saveIntoKeychainToken(newToken)
})
}
}
})
}
}
if indexPath.row == 3 && indexPath.section == 0 {
if let token = session?.token as? OAuth2Token {
token.revoke({ (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
OAuth2TokenRepository.removeFromKeychainTokenWithName(token.name)
self.navigationController?.popToRootViewControllerAnimated(true)
})
}
})
}
}
if indexPath.section == 3 {
if let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserContentViewController") as? UserContentViewController {
let content = [
UserContent.Overview,
UserContent.Submitted,
UserContent.Comments,
UserContent.Liked,
UserContent.Disliked,
UserContent.Hidden,
UserContent.Saved,
UserContent.Gilded
]
vc.userContent = content[indexPath.row]
vc.session = self.session
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
override func viewWillAppear(animated: Bool) {
updateExpireCell(nil)
}
override func viewDidAppear(animated: Bool) {
println(session)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ToProfileViewController" {
if let con = segue.destinationViewController as? ProfileViewController {
con.session = self.session
}
}
else if segue.identifier == "ToFrontViewController" {
if let con = segue.destinationViewController as? LinkViewController {
con.session = self.session
}
}
else if segue.identifier == "ToSubredditsListViewController" {
if let con = segue.destinationViewController as? SubredditsListViewController {
con.session = self.session
}
}
else if segue.identifier == "ToSubredditsViewController" {
if let con = segue.destinationViewController as? SubredditsViewController {
con.session = self.session
}
}
else if segue.identifier == "OpenInbox" {
if let con = segue.destinationViewController as? MessageViewController {
con.session = self.session
con.messageWhere = .Inbox
}
}
else if segue.identifier == "OpenSent" {
if let con = segue.destinationViewController as? MessageViewController {
con.session = self.session
con.messageWhere = .Sent
}
}
else if segue.identifier == "OpenUnread" {
if let con = segue.destinationViewController as? MessageViewController {
con.session = self.session
con.messageWhere = .Unread
}
}
}
}
| mit | c7b253c7529c89da82e3e5701eec58e7 | 35.977273 | 141 | 0.549068 | 5.571918 | false | false | false | false |
taku0/swift3-mode | test/swift-files/declarations.swift | 1 | 4884 | // swift3-mode:test:eval (setq-local swift3-mode:basic-offset 4)
// swift3-mode:test:eval (setq-local swift3-mode:parenthesized-expression-offset 2)
// swift3-mode:test:eval (setq-local swift3-mode:multiline-statement-offset 2)
// swift3-mode:test:eval (setq-local swift3-mode:switch-case-offset 0)
// Constant declarations
let
foo
.bar
=
bar
.baz
class Foo {
@ABC
open
weak
let
(
x,
y
)
:
(
Int,
Int
)
=
xx
@ABC
final
unowned(safe)
fileprivate
let
Foo
.Bar(x)
:
Foo
.Bar
=
xx
let f
= g
:
(
Int,
Int
)
->
throws
[
X
]
let x = 1,
y = 1,
z = 1
let
x = 1,
y = 1,
z = 1
let x = 1
, y = 1
, z = 1
// Declaring multiple variables with single `let` statement doesn't seem to
// be popular. Rather, we choose saving columns for the first variable.
private final let x = foo
.foo // This is intended.
.foo,
y = foo
.then { x // This is intended.
in
foo
return foo
}
.then { x
in
foo
return foo
},
z = foo
.foo
.foo
}
// Variable declarations
class Foo {
internal var x = foo
.foo
.foo,
y = foo
.foo
.foo,
z = foo
.foo
.foo
internal var x
: (Int, Int) {
foo()
return foo()
}
internal var x
: (Int, Int) {
@A
mutating
get {
foo()
return foo()
}
@A
mutating
set
(it) {
foo()
foo(it)
}
}
internal var x
: (Int, Int) {
@A
mutating
get
@A
mutating
set
}
internal var x
:
(Int, Int)
=
foo
.bar {
return thisIsFunctionBlock
} {
// This is bad, but cannot decide indentation without looking forward
// tokens.
@A
willSet(a) {
foo()
foo()
}
@A
didSet(a) {
foo()
foo()
}
} // This is bad
internal var x
:
(Int, Int) {
@A
willSet(a) {
foo()
foo()
}
@A
didSet(a) {
foo()
foo()
}
}
}
// Type alias declaration
class Foo {
typealias A<B> = C
.D
@A
private typealias A<B>
=
C
.D
}
// Function declarations
@A
private
final
func
foo<A, B>(
x:
Int
y:
Int
=
1
z
w:
Int
...
)
throws
->
[A]
where
A:
C,
B =
C<D> {
foo()
foo()
}
func
foo()
->
@A
B {
foo()
foo()
}
// Enumeration declarations
fileprivate
indirect
enum
Foo<A, B>
: X,
Y,
Z
where
A:
C,
B =
D<E> {
@A
case A
case B
case C,
D,
E
indirect
case
F(
x:
X,
y:
Y
),
G,
H
func foo() {
}
case I
case J
}
fileprivate
enum
Foo<A, B>
:
Int
where
A:
C,
B =
D<E> {
case A =
1, // swift3-mode:test:known-bug
B =
2,
C =
3
case D
= 1, // swift3-mode:test:known-bug
E
= 2,
F
= 3
func foo() {
}
}
enum Foo
: X,
Y,
Z {
}
enum Foo
: X
, Y
, Z
{
}
// Struct declarations
@A
fileprivate
struct
Foo<A, B>
: Bar<A, B>,
Baz<A, B>,
AAA<A, B>
where
A:
C,
B =
D<E> {
func foo()
func foo()
}
// Protocol declarations
protocol Foo {
func foo(x, y) -> throws (A, B)
init<A, B>(x: Int) throws
where
A: C
subscript(x: Int) -> Int {
get
set
}
associatedtype AAA = BBB
convenience
init(x: Int, y, Int)
}
// Operator declarations
infix
operator
+++
:
precedenceGroupName
prefix
operator
+++
postfix
operator
+++
precedencegroup
precedenceGroupName {
higherThan:
lowerGroupName
lowerThan:
higherGroupName
assignment:
false
associativity:
left
}
| gpl-3.0 | df1062796d71509570c4231e958d51a9 | 11.989362 | 83 | 0.373055 | 3.951456 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/FileDownload.swift | 1 | 857 | //
// FileDownload.swift
// Pelican
//
// Created by Ido Constantine on 22/03/2018.
//
import Foundation
/**
Represents a file ready to be downloaded. Use the API method `getFile` to request a FileDownload type.
*/
public struct FileDownload: Codable {
/// Unique identifier for the file.
var fileID: String
/// The file size, if known
var fileSize: Int?
/// The path that can be used to download the file, using https://api.telegram.org/file/bot<token>/<file_path>.
var filePath: String?
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case fileID = "file_id"
case fileSize = "file_size"
case filePath = "file_path"
}
public init(fileID: String, fileSize: Int? = nil, filePath: String? = nil) {
self.fileID = fileID
self.fileSize = fileSize
self.filePath = filePath
}
}
| mit | 19b6b5fe7570a2640d268befe6172ae1 | 22.805556 | 112 | 0.694282 | 3.455645 | false | false | false | false |
redlock/JAYSON | JAYSON/Classes/Reflection/Get.swift | 2 | 631 | /// Get value for key from instance
public func get(_ key: String, from instance: Any) throws -> Any! {
// guard let value = try properties(instance).first(where: { $0.key == key })?.value else {
// throw ReflectionError.instanceHasNoKey(type: type(of: instance), key: key)
// }
// return value
return nil
}
/// Get value for key from instance as type `T`
public func get<T>(_ key: String, from instance: Any) throws -> T {
let any: Any = try get(key, from: instance)
guard let value = any as? T else {
throw ReflectionError.valueIsNotType(value: any, theType: T.self)
}
return value
}
| mit | 344b2bb976014cfc0fe65918c845e4ee | 36.117647 | 94 | 0.646593 | 3.544944 | false | false | false | false |
shhuangtwn/ProjectLynla | Pods/FacebookLogin/Sources/Login/LoginButtonDelegateBridge.swift | 2 | 2085 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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
import FBSDKLoginKit
internal class LoginButtonDelegateBridge: NSObject {
internal weak var loginButton: LoginButton?
func setupAsDelegateFor(sdkLoginButton: FBSDKLoginButton, loginButton: LoginButton) {
self.loginButton = loginButton
sdkLoginButton.delegate = self
}
}
extension LoginButtonDelegateBridge: FBSDKLoginButtonDelegate {
func loginButton(sdkButton: FBSDKLoginButton!, didCompleteWithResult sdkResult: FBSDKLoginManagerLoginResult?, error: NSError?) {
guard
let loginButton = loginButton,
let delegate = loginButton.delegate else {
return
}
let result = LoginResult(sdkResult: sdkResult, error: error)
delegate.loginButtonDidCompleteLogin(loginButton, result: result)
}
func loginButtonDidLogOut(sdkButton: FBSDKLoginButton!) {
guard
let loginButton = loginButton,
let delegate = loginButton.delegate else {
return
}
delegate.loginButtonDidLogOut(loginButton)
}
}
| mit | 70167f73f5a53637ae3ceda83a3da51c | 38.339623 | 131 | 0.761631 | 4.952494 | false | false | false | false |
slxl/ReactKit | ReactKit/Error.swift | 1 | 764 | //
// Error.swift
// ReactKit
//
// Created by Yasuhiro Inami on 2014/12/02.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
public enum ReactKitError: Int {
public static let Domain = "ReactKitErrorDomain"
case cancelled = 0
case cancelledByDeinit = 1
case cancelledByUpstream = 2
case cancelledByTriggerStream = 3
case cancelledByInternalStream = 4
case rejectedByInternalTask = 1000
}
/// helper
internal func _RKError(_ error: ReactKitError, _ localizedDescriptionKey: String) -> NSError {
return NSError(
domain: ReactKitError.Domain,
code: error.rawValue,
userInfo: [
NSLocalizedDescriptionKey : localizedDescriptionKey
]
)
}
| mit | 9aeaa6dbd1f8d422beac914130ff769e | 22.8125 | 94 | 0.677165 | 4.37931 | false | false | false | false |
nathawes/swift | test/SILGen/cf_members.swift | 8 | 14727 | // RUN: %target-swift-emit-silgen -I %S/../IDE/Inputs/custom-modules %s -enable-objc-interop -I %S/Inputs/usr/include | %FileCheck %s
import ImportAsMember
func makeMetatype() -> Struct1.Type { return Struct1.self }
// CHECK-LABEL: sil [ossa] @$s10cf_members17importAsUnaryInityyF
public func importAsUnaryInit() {
// CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply
var a = CCPowerSupply(dangerous: ())
let f: (()) -> CCPowerSupply = CCPowerSupply.init(dangerous:)
a = f(())
}
// CHECK-LABEL: sil [ossa] @$s10cf_members3foo{{[_0-9a-zA-Z]*}}F
public func foo(_ x: Double) {
// CHECK: bb0([[X:%.*]] : $Double):
// CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBALVAR]] : $*Double
// CHECK: [[ZZ:%.*]] = load [trivial] [[READ]]
let zz = Struct1.globalVar
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBALVAR]] : $*Double
// CHECK: assign [[ZZ]] to [[WRITE]]
Struct1.globalVar = zz
// CHECK: [[Z:%.*]] = project_box
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: apply [[FN]]([[X]])
var z = Struct1(value: x)
// The metatype expression should still be evaluated even if it isn't
// used.
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: apply [[FN]]([[X]])
z = makeMetatype().init(value: x)
// CHECK: [[FN:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcfu_ : $@convention(thin) (Double) -> Struct1
// CHECK: [[A:%.*]] = thin_to_thick_function [[FN]]
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]]
// CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
// CHECK: [[BORROWED_A2:%.*]] = begin_borrow [[A_COPY]]
let a: (Double) -> Struct1 = Struct1.init(value:)
// CHECK: apply [[BORROWED_A2]]([[X]])
// CHECK: destroy_value [[A_COPY]]
// CHECK: end_borrow [[BORROWED_A]]
z = a(x)
// TODO: Support @convention(c) references that only capture thin metatype
// let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:)
// z = b(x)
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace
// CHECK: apply [[FN]]([[WRITE]])
z.invert()
// CHECK: [[WRITE:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[WRITE]]
// CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] :
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1
// CHECK: apply [[FN]]([[ZTMP]], [[X]])
z = z.translate(radians: x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu0_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1
// CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]])
// CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
// CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]]
// CHECK: [[BORROWED_C2:%.*]] = begin_borrow [[C_COPY]]
let c: (Double) -> Struct1 = z.translate(radians:)
// CHECK: apply [[BORROWED_C2]]([[X]])
// CHECK: destroy_value [[C_COPY]]
// CHECK: end_borrow [[BORROWED_C]]
z = c(x)
// CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu2_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1
// CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]]
// CHECK: [[BORROW:%.*]] = begin_borrow [[THICK]]
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[BORROW_COPY:%.*]] = begin_borrow [[COPY]]
// CHECK: apply [[BORROW_COPY]]([[ZVAL]])
// CHECK: destroy_value [[COPY]]
z = d(z)(x)
// TODO: If we implement SE-0042, this should thunk the value Struct1 param
// to a const* param to the underlying C symbol.
//
// let e: @convention(c) (Struct1, Double) -> Struct1
// = Struct1.translate(radians:)
// z = e(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale
// CHECK: apply [[FN]]([[ZVAL]], [[X]])
z = z.scale(x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu4_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1
// CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]])
// CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
// CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]]
// CHECK: [[BORROWED_F2:%.*]] = begin_borrow [[F_COPY]]
let f = z.scale
// CHECK: apply [[BORROWED_F2]]([[X]])
// CHECK: destroy_value [[F_COPY]]
// CHECK: end_borrow [[BORROWED_F]]
z = f(x)
// CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu6_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1
// CHECK: thin_to_thick_function [[THUNK]]
let g = Struct1.scale
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
z = g(z)(x)
// TODO: If we implement SE-0042, this should directly reference the
// underlying C function.
// let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale
// z = h(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] :
// CHECK: [[ZVAL_2:%.*]] = load [trivial] [[ZTMP]]
// CHECK: store [[ZVAL_2]] to [trivial] [[ZTMP_2:%.*]] :
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double
// CHECK: apply [[GET]]([[ZTMP_2]])
_ = z.radius
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> ()
// CHECK: apply [[SET]]([[ZVAL]], [[X]])
z.radius = x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.altitude
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> ()
// CHECK: apply [[SET]]([[WRITE]], [[X]])
z.altitude = x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.magnitude
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: apply [[FN]]()
var y = Struct1.staticMethod()
// CHECK: [[SELF:%.*]] = metatype
// CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFs5Int32VycSo10IAMStruct1Vmcfu8_ : $@convention(thin) (@thin Struct1.Type) -> @owned @callee_guaranteed () -> Int32
// CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]])
// CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]]
// CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]]
// CHECK: [[BORROWED_I2:%.*]] = begin_borrow [[I_COPY]]
let i = Struct1.staticMethod
// CHECK: apply [[BORROWED_I2]]()
// CHECK: destroy_value [[I_COPY]]
// CHECK: end_borrow [[BORROWED_I]]
y = i()
// TODO: Support @convention(c) references that only capture thin metatype
// let j: @convention(c) () -> Int32 = Struct1.staticMethod
// y = j()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = Struct1.property
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
Struct1.property = y
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = Struct1.getOnlyProperty
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().property
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
makeMetatype().property = y
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().getOnlyProperty
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> ()
// CHECK: apply [[FN]]([[X]], [[ZVAL]])
z.selfComesLast(x: x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
let k: (Double) -> () = z.selfComesLast(x:)
k(x)
let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
l(z)(x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:)
// m(z, x)
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
// CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> ()
// CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]])
z.selfComesThird(a: y, b: 0, x: x)
let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:)
n(y, 0, x)
let o: (Struct1) -> (Int32, Float, Double) -> ()
= Struct1.selfComesThird(a:b:x:)
o(z)(y, 0, x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let p: @convention(c) (Struct1, Int, Float, Double) -> ()
// = Struct1.selfComesThird(a:b:x:)
// p(z, y, 0, x)
}
// CHECK: } // end sil function '$s10cf_members3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcfu_ : $@convention(thin) (Double) -> Struct1 {
// CHECK: bb0([[X:%.*]] : $Double):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu0_ADSdcfu1_ : $@convention(thin) (Double, Struct1) -> Struct1 {
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] :
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu4_ADSdcfu5_ : $@convention(thin) (Double, Struct1) -> Struct1 {
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFs5Int32VycSo10IAMStruct1Vmcfu8_ADycfu9_ : $@convention(thin) (@thin Struct1.Type) -> Int32 {
// CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: [[RET:%.*]] = apply [[CFUNC]]()
// CHECK: return [[RET]]
// CHECK-LABEL:sil private [ossa] @$s10cf_members3fooyySdFySdcSo10IAMStruct1Vcfu10_ySdcfu11_ : $@convention(thin) (Double, Struct1) -> () {
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast
// CHECK: apply [[CFUNC]]([[X]], [[SELF]])
// CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFys5Int32V_SfSdtcSo10IAMStruct1Vcfu14_yAD_SfSdtcfu15_ : $@convention(thin) (Int32, Float, Double, Struct1) -> () {
// CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird
// CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]])
// CHECK-LABEL: sil [ossa] @$s10cf_members3bar{{[_0-9a-zA-Z]*}}F
public func bar(_ x: Double) {
// CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply
let ps = CCPowerSupply(watts: x)
// CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator
let fridge = CCRefrigerator(powerSupply: ps)
// CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> ()
fridge.open()
// CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply
let ps2 = fridge.powerSupply
// CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> ()
fridge.powerSupply = ps2
let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:)
let _ = a(x)
let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open
b(fridge)()
let c = fridge.open
c()
}
// CHECK-LABEL: sil [ossa] @$s10cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F
public func importGlobalVarsAsProperties()
-> (Double, CCPowerSupply, CCPowerSupply?) {
// CHECK: global_addr @kCCPowerSupplyDC
// CHECK: global_addr @kCCPowerSupplyAC
// CHECK: global_addr @kCCPowerSupplyDefaultPower
return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC)
}
| apache-2.0 | 618233cefcfb6b482ff7c5bccf4764b4 | 47.92691 | 179 | 0.590955 | 3.332654 | false | false | false | false |
ngageoint/mage-ios | MageTests/Authentication/SignupViewControllerTests.swift | 1 | 15743 | //
// SignupViewControllerTests.swift
// MAGETests
//
// Created by Daniel Barela on 10/7/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import Quick
import Nimble
import OHHTTPStubs
import Kingfisher
@testable import MAGE
@available(iOS 13.0, *)
class MockSignUpDelegate: NSObject, SignupDelegate {
var signupParameters: [AnyHashable : Any]?;
var url: URL?;
var signUpCalled = false;
var signupCanceledCalled = false;
var getCaptchaCalled = false;
var captchaUsername: String?;
func getCaptcha(_ username: String, completion: @escaping (String) -> Void) {
getCaptchaCalled = true;
captchaUsername = username;
}
func signup(withParameters parameters: [AnyHashable : Any], completion: @escaping (HTTPURLResponse) -> Void) {
signUpCalled = true;
signupParameters = parameters;
}
func signupCanceled() {
signupCanceledCalled = true;
}
}
class SignUpViewControllerTests: KIFSpec {
override func spec() {
describe("SignUpViewControllerTests") {
var window: UIWindow?;
var view: SignUpViewController?;
var delegate: MockSignUpDelegate?;
var navigationController: UINavigationController?;
beforeEach {
TestHelpers.clearAndSetUpStack();
UserDefaults.standard.baseServerUrl = "https://magetest";
MageCoreDataFixtures.addEvent();
Server.setCurrentEventId(1);
delegate = MockSignUpDelegate();
navigationController = UINavigationController();
window = TestHelpers.getKeyWindowVisible();
window!.rootViewController = navigationController;
}
afterEach {
navigationController?.viewControllers = [];
window?.rootViewController?.dismiss(animated: false, completion: nil);
window?.rootViewController = nil;
navigationController = nil;
view = nil;
delegate = nil;
HTTPStubs.removeAllStubs();
TestHelpers.clearAndSetUpStack();
}
it("should load the SignUpViewCOntroller server version 5") {
view = SignUpViewController_Server5(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
expect(navigationController?.topViewController).to(beAnInstanceOf(SignUpViewController_Server5.self));
expect(viewTester().usingLabel("Username")?.view).toNot(beNil());
expect(viewTester().usingLabel("Display Name")?.view).toNot(beNil());
expect(viewTester().usingLabel("Email")?.view).toNot(beNil());
expect(viewTester().usingLabel("Phone")?.view).toNot(beNil());
expect(viewTester().usingLabel("Password")?.view).toNot(beNil());
expect(viewTester().usingLabel("Confirm Password")?.view).toNot(beNil());
expect(viewTester().usingLabel("CANCEL")?.view).toNot(beNil());
expect(viewTester().usingLabel("SIGN UP")?.view).toNot(beNil());
tester().waitForView(withAccessibilityLabel: "Version");
let versionString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String;
tester().expect(viewTester().usingLabel("Version").view, toContainText: "v\(versionString)");
tester().expect(viewTester().usingLabel("Server URL").view, toContainText: "https://magetest");
}
it("should load the SignUpViewController") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
expect(navigationController?.topViewController).to(beAnInstanceOf(SignUpViewController.self));
expect(viewTester().usingLabel("Username")?.view).toNot(beNil());
expect(viewTester().usingLabel("Display Name")?.view).toNot(beNil());
expect(viewTester().usingLabel("Email")?.view).toNot(beNil());
expect(viewTester().usingLabel("Phone")?.view).toNot(beNil());
expect(viewTester().usingLabel("Password")?.view).toNot(beNil());
expect(viewTester().usingLabel("Confirm Password")?.view).toNot(beNil());
expect(viewTester().usingLabel("CANCEL")?.view).toNot(beNil());
expect(viewTester().usingLabel("SIGN UP")?.view).toNot(beNil());
expect(viewTester().usingLabel("Captcha")?.view).toNot(beNil());
tester().waitForView(withAccessibilityLabel: "Version");
let versionString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String;
tester().expect(viewTester().usingLabel("Version").view, toContainText: "v\(versionString)");
tester().expect(viewTester().usingLabel("Server URL").view, toContainText: "https://magetest");
}
it("should not allow signup without required fields") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Sign Up");
tester().tapView(withAccessibilityLabel: "Sign Up");
tester().waitForTappableView(withAccessibilityLabel: "Missing Required Fields");
let alert: UIAlertController = (navigationController?.presentedViewController as! UIAlertController);
expect(alert.title).to(equal("Missing Required Fields"));
expect(alert.message).to(contain("Password"));
expect(alert.message).to(contain("Confirm Password"));
expect(alert.message).to(contain("Username"));
expect(alert.message).to(contain("Display Name"));
tester().tapView(withAccessibilityLabel: "OK");
}
it("should not allow signup with passwords that do not match") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Sign Up");
tester().setText("username", intoViewWithAccessibilityLabel: "Username");
tester().setText("display", intoViewWithAccessibilityLabel: "Display Name");
tester().setText("password", intoViewWithAccessibilityLabel: "Password");
tester().setText("passwordsthatdonotmatch", intoViewWithAccessibilityLabel: "Confirm Password");
tester().tapView(withAccessibilityLabel: "Sign Up");
tester().waitForTappableView(withAccessibilityLabel: "Passwords Do Not Match");
let alert: UIAlertController = (navigationController?.presentedViewController as! UIAlertController);
expect(alert.title).to(equal("Passwords Do Not Match"));
expect(alert.message).to(contain("Please update password fields to match."));
tester().tapView(withAccessibilityLabel: "OK");
}
it("should signup") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Sign Up");
tester().setText("username", intoViewWithAccessibilityLabel: "Username");
tester().setText("display", intoViewWithAccessibilityLabel: "Display Name");
tester().setText("password", intoViewWithAccessibilityLabel: "Password");
tester().setText("password", intoViewWithAccessibilityLabel: "Confirm Password");
tester().enterText("5555555555", intoViewWithAccessibilityLabel: "Phone", traits: .none, expectedResult: "(555) 555-5555");
tester().setText("[email protected]", intoViewWithAccessibilityLabel: "Email");
tester().setText("captcha", intoViewWithAccessibilityLabel: "Captcha");
tester().tapView(withAccessibilityLabel: "Sign Up");
expect(delegate?.signUpCalled).to(beTrue());
expect(delegate?.signupParameters as? [String: String]).to(equal([
"username": "username",
"password": "password",
"passwordconfirm": "password",
"phone": "(555) 555-5555",
"email": "[email protected]",
"displayName": "display",
"captchaText": "captcha"
]))
}
it("should cancel") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "CANCEL");
tester().tapView(withAccessibilityLabel: "CANCEL");
expect(delegate?.signupCanceledCalled).to(beTrue());
}
it("should show the password") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Show Password");
let passwordField: UITextField = viewTester().usingLabel("Password").view as! UITextField;
let passwordConfirmField: UITextField = viewTester().usingLabel("Confirm Password").view as! UITextField;
tester().setText("password", intoViewWithAccessibilityLabel: "Password");
tester().setText("password", intoViewWithAccessibilityLabel: "Confirm Password");
expect(passwordField.isSecureTextEntry).to(beTrue());
expect(passwordConfirmField.isSecureTextEntry).to(beTrue());
tester().setOn(true, forSwitchWithAccessibilityLabel: "Show Password");
expect(passwordField.isSecureTextEntry).to(beFalse());
expect(passwordConfirmField.isSecureTextEntry).to(beFalse());
}
it("should update the password strength meter") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Password");
// this is entirely to stop iOS from suggesting a password
tester().setOn(true, forSwitchWithAccessibilityLabel: "Show Password");
tester().enterText("turtle", intoViewWithAccessibilityLabel: "Password");
tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Weak");
tester().clearTextFromView(withAccessibilityLabel: "Password");
tester().enterText("Turt", intoViewWithAccessibilityLabel: "Password");
tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Fair");
tester().clearTextFromView(withAccessibilityLabel: "Password");
tester().enterText("Turt3", intoViewWithAccessibilityLabel: "Password");
tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Good");
tester().clearTextFromView(withAccessibilityLabel: "Password");
tester().enterText("Turt3!", intoViewWithAccessibilityLabel: "Password");
tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Strong");
tester().clearTextFromView(withAccessibilityLabel: "Password");
tester().enterText("Turt3!@@", intoViewWithAccessibilityLabel: "Password");
tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Excellent");
}
it("should update the phone number field as it is typed") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Phone");
tester().enterText("5555555555", intoViewWithAccessibilityLabel: "Phone", traits: .none, expectedResult: "(555) 555-5555");
tester().expect(viewTester().usingLabel("Phone")?.view, toContainText: "(555) 555-5555");
}
// cannot fully test this due to being unable to disable the password auto-suggest
it("should proceed to each field in order") {
view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme());
navigationController?.pushViewController(view!, animated: false);
tester().waitForView(withAccessibilityLabel: "Sign Up");
tester().enterText("username\n", intoViewWithAccessibilityLabel: "Username");
tester().waitForFirstResponder(withAccessibilityLabel: "Display Name");
tester().enterText("display\n", intoViewWithAccessibilityLabel: "Display Name");
tester().waitForFirstResponder(withAccessibilityLabel: "Email");
tester().enterText("[email protected]\n", intoViewWithAccessibilityLabel: "Email");
tester().waitForFirstResponder(withAccessibilityLabel: "Phone");
tester().enterText("5555555555", intoViewWithAccessibilityLabel: "Phone", traits: .none, expectedResult: "(555) 555-5555");
tester().setText("password", intoViewWithAccessibilityLabel: "Password");
tester().setText("password", intoViewWithAccessibilityLabel: "Confirm Password");
tester().setText("captcha", intoViewWithAccessibilityLabel: "Captcha");
tester().tapView(withAccessibilityLabel: "Sign Up")
expect(delegate?.signUpCalled).to(beTrue());
expect(delegate?.signupParameters as? [String: String]).toEventually(equal([
"username": "username",
"password": "password",
"passwordconfirm": "password",
"phone": "(555) 555-5555",
"email": "[email protected]",
"displayName": "display",
"captchaText": "captcha"
]))
}
}
}
}
| apache-2.0 | 049f554b435b8303debcfc10969c74a3 | 54.041958 | 139 | 0.591094 | 6.362975 | false | true | false | false |
iOSDevLog/iOSDevLog | 169. Camera/Camera/ExposureViewController.swift | 1 | 3008 | //
// ExposureViewController.swift
// Camera
//
// Created by Matteo Caldari on 05/02/15.
// Copyright (c) 2015 Matteo Caldari. All rights reserved.
//
import UIKit
import CoreMedia
class ExposureViewController: UIViewController, CameraControlsViewControllerProtocol, CameraSettingValueObserver {
@IBOutlet var modeSwitch:UISwitch!
@IBOutlet var biasSlider:UISlider!
@IBOutlet var durationSlider:UISlider!
@IBOutlet var isoSlider:UISlider!
var cameraController:CameraController? {
willSet {
if let cameraController = cameraController {
cameraController.unregisterObserver(self, property: CameraControlObservableSettingExposureTargetOffset)
cameraController.unregisterObserver(self, property: CameraControlObservableSettingExposureDuration)
cameraController.unregisterObserver(self, property: CameraControlObservableSettingISO)
}
}
didSet {
if let cameraController = cameraController {
cameraController.registerObserver(self, property: CameraControlObservableSettingExposureTargetOffset)
cameraController.registerObserver(self, property: CameraControlObservableSettingExposureDuration)
cameraController.registerObserver(self, property: CameraControlObservableSettingISO)
}
}
}
override func viewDidLoad() {
setInitialValues()
}
@IBAction func modeSwitchValueChanged(sender:UISwitch) {
if sender.on {
cameraController?.enableContinuousAutoExposure()
}
else {
cameraController?.setCustomExposureWithDuration(durationSlider.value)
}
updateSliders()
}
@IBAction func sliderValueChanged(sender:UISlider) {
switch sender {
case biasSlider:
cameraController?.setExposureTargetBias(sender.value)
case durationSlider:
cameraController?.setCustomExposureWithDuration(sender.value)
case isoSlider:
cameraController?.setCustomExposureWithISO(sender.value)
default: break
}
}
func cameraSetting(setting: String, valueChanged value: AnyObject) {
if setting == CameraControlObservableSettingExposureDuration {
if let durationValue = value as? NSValue {
let duration = CMTimeGetSeconds(durationValue.CMTimeValue)
durationSlider.value = Float(duration)
}
}
else if setting == CameraControlObservableSettingISO {
if let iso = value as? Float {
isoSlider.value = Float(iso)
}
}
}
func setInitialValues() {
if isViewLoaded() && cameraController != nil {
if let autoExposure = cameraController?.isContinuousAutoExposureEnabled() {
modeSwitch.on = autoExposure
updateSliders()
}
if let currentDuration = cameraController?.currentExposureDuration() {
durationSlider.value = currentDuration
}
if let currentISO = cameraController?.currentISO() {
isoSlider.value = currentISO
}
if let currentBias = cameraController?.currentExposureTargetOffset() {
biasSlider.value = currentBias
}
}
}
func updateSliders() {
for slider in [durationSlider, isoSlider] as [UISlider] {
slider.enabled = !modeSwitch.on
}
}
}
| mit | 1e1bef2c5ca4841ec490b4ba1abfc66e | 26.851852 | 114 | 0.762633 | 4.462908 | false | false | false | false |
X140Yu/Lemon | Lemon/Library/Protocol/SharebleViewController.swift | 1 | 1241 | import UIKit
import RxSwift
import RxCocoa
protocol Shareble {
var shareButton: UIButton { get }
var shareItems: [Any] { get set }
}
class SharebleViewControllerProvider: Shareble {
var shareItems = [Any]()
private weak var viewController: UIViewController?
private let bag = DisposeBag()
var shareButton = UIButton()
init(viewController: UIViewController) {
self.viewController = viewController
shareButton.setImage(#imageLiteral(resourceName: "share"), for: .normal)
shareButton.rx.controlEvent(.touchUpInside)
.filter{ _ in return self.shareItems.count > 0}
.map { _ in return self.shareItems }
.subscribe(onNext: { [weak self] items in
guard let `self` = self else { return }
guard let vc = self.viewController else { return }
let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = vc.view
vc.present(activityViewController, animated: true, completion: nil)
}).addDisposableTo(bag)
let shareBarButton = UIBarButtonItem(customView: shareButton)
viewController.navigationItem.rightBarButtonItem = shareBarButton
}
}
| gpl-3.0 | 5214ebfc4faf058933d37c675cfead35 | 33.472222 | 111 | 0.730862 | 4.964 | false | false | false | false |
keyeMyria/edx-app-ios | Source/CourseCardViewModel.swift | 4 | 1879 | //
// CourseCardViewModel.swift
// edX
//
// Created by Michael Katz on 8/31/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
@objc class CourseCardViewModel : NSObject {
class func applyCourse(course: OEXCourse, to infoView: CourseDashboardCourseInfoView) {
infoView.course = course
infoView.titleText = course.name
infoView.detailText = (course.org ?? "") + (course.number != nil ? course.number! + " | " : "") // Show course ced
var bannerText: String? = nil
// If start date is older than current date
if course.isStartDateOld && course.end != nil {
let formattedEndDate = OEXDateFormatting.formatAsMonthDayString(course.end)
// If Old date is older than current date
if course.isEndDateOld {
bannerText = OEXLocalizedString("ENDED", nil) + " - " + formattedEndDate
} else {
bannerText = OEXLocalizedString("ENDING", nil).oex_uppercaseStringInCurrentLocale() + " - " + formattedEndDate
}
} else { // Start date is newer than current date
let error_code = course.courseware_access!.error_code
let startDateNil: Bool = course.start_display_info.date == nil
let displayInfoTime: Bool = error_code != OEXAccessError.StartDateError || course.start_display_info.type == OEXStartType.Timestamp
if !course.isStartDateOld && !startDateNil && displayInfoTime {
let formattedStartDate = OEXDateFormatting.formatAsMonthDayString(course.start_display_info.date)
bannerText = OEXLocalizedString("STARTING", nil).oex_uppercaseStringInCurrentLocale() + " - " + formattedStartDate
}
}
infoView.bannerText = bannerText
infoView.setCoverImage()
}
} | apache-2.0 | 7acf100e807cda8bdd88bd4596c9357c | 41.727273 | 143 | 0.62959 | 4.744949 | false | false | false | false |
cuappdev/eatery | Eatery Watch App Extension/UI/Eateries/CampusEateriesView.swift | 1 | 6277 | //
// CampusEateriesView.swift
// Eatery Watch App Extension
//
// Created by William Ma on 1/5/20.
// Copyright © 2020 CUAppDev. All rights reserved.
//
import Combine
import CoreLocation
import SwiftUI
private class CampusEateriesData: ObservableObject {
@Published var campusEateries: [CampusEatery] = []
@Published var openEateries: [CampusEatery] = []
@Published var closedEateries: [CampusEatery] = []
private let locationProxy = LocationProxy()
@Published var userLocation: CLLocation?
var cancellables: Set<AnyCancellable> = []
init() {
$campusEateries.sink(receiveValue: self.reloadEateries).store(in: &self.cancellables)
Timer.publish(every: 60, on: .current, in: .common).autoconnect().sink { _ in
self.reloadEateries(self.campusEateries)
}.store(in: &self.cancellables)
}
private func reloadEateries(_ eateries: [CampusEatery]) {
self.openEateries = eateries.filter {
!EateryStatus.equalsIgnoreAssociatedValue($0.currentStatus(), rhs: .closed)
}
self.closedEateries = eateries.filter {
EateryStatus.equalsIgnoreAssociatedValue($0.currentStatus(), rhs: .closed)
}
}
func fetchCampusEateries(_ presentError: @escaping (Error) -> Void) {
NetworkManager.shared.getCampusEateries { [weak self] (campusEateries, error) in
guard let self = self else { return }
if let campusEateries = campusEateries {
self.campusEateries = campusEateries
} else if let error = error {
presentError(error)
}
}
}
func fetchLocation(_ presentError: @escaping (Error) -> Void) {
self.locationProxy.fetchLocation { result in
switch result {
case .success(let location):
self.userLocation = location
case .failure(let error):
presentError(error)
}
}
}
}
private class ErrorInfo: Identifiable {
let title: String
let error: Error
init(title: String, error: Error) {
self.title = title
self.error = error
}
}
/// Presents a list of campus eateries, along with sort and filter settings.
struct CampusEateriesView: View {
@ObservedObject private var viewData = CampusEateriesData()
@State private var sortMethod: SortMethod = .name
@State private var areaFilter: Area?
@State private var errorInfo: ErrorInfo?
@State private var firstAppearance = true
var body: some View {
let openEateries = sorted(filter(self.viewData.openEateries))
let closedEateries = sorted(filter(self.viewData.closedEateries))
return ScrollView {
SortMethodView(self.$sortMethod) {
if self.sortMethod == .distance {
self.viewData.fetchLocation { error in
if self.sortMethod == .distance {
self.sortMethod = .name
self.errorInfo = ErrorInfo(title: "Could not get location.", error: error)
}
}
}
}
.animation(nil)
AreaFilterView(self.$areaFilter).animation(nil)
HStack {
Text("Open").font(.headline)
Spacer()
}
if !openEateries.isEmpty {
self.eateriesView(openEateries)
} else {
Group {
Text("No Open Eateries")
}
}
HStack {
Text("Closed").font(.headline)
Spacer()
}
if !closedEateries.isEmpty {
self.eateriesView(closedEateries)
} else {
Group {
Text("No Closed Eateries")
}
}
}
.navigationBarTitle("Eateries")
.animation(.easeOut(duration: 0.25))
.contextMenu {
Button(action: {
self.viewData.fetchCampusEateries { error in
self.errorInfo = ErrorInfo(title: "Could not fetch eateries.", error: error)
}
}, label: {
VStack{
Image(systemName: "arrow.clockwise")
.font(.title)
Text("Refresh Eateries")
}
})
}
.alert(item: self.$errorInfo) { errorInfo -> Alert in
Alert(title: Text("Error: ") + Text(errorInfo.title),
message: Text(errorInfo.error.localizedDescription),
dismissButton: .default(Text("OK")))
}
.onAppear {
if self.firstAppearance {
self.viewData.fetchCampusEateries { error in
self.errorInfo = ErrorInfo(title: "Could not fetch eateries.", error: error)
}
self.firstAppearance = false
}
}
}
func eateriesView(_ eateries: [CampusEatery]) -> some View {
ForEach(eateries) { eatery in
NavigationLink(destination: CampusEateryView(eatery: eatery)) {
CampusEateryRow(eatery: eatery, userLocation: self.sortMethod == .distance ? self.viewData.userLocation : nil)
}
}
}
private func filter(_ eateries: [CampusEatery]) -> [CampusEatery] {
if let areaFilter = self.areaFilter {
return eateries.filter { eatery in
eatery.area == areaFilter
}
} else {
return eateries
}
}
private func sorted(_ eateries: [CampusEatery]) -> [CampusEatery] {
switch (self.sortMethod, self.viewData.userLocation) {
case (.name, _), (.distance, .none):
return eateries.sorted { (lhs, rhs) in
lhs.displayName < rhs.displayName
}
case (.distance, .some(let location)):
return eateries.sorted { (lhs, rhs) in
lhs.location.distance(from: location).converted(to: .meters).value <
rhs.location.distance(from: location).converted(to: .meters).value
}
}
}
}
| mit | 9b07692870569437c5e1277278ab1e0f | 30.223881 | 126 | 0.549713 | 4.973059 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ColumnarCollectionViewControllerLayoutCache.swift | 1 | 3193 | private extension CGFloat {
var roundedColumnWidth: Int {
return Int(self*100)
}
}
class ColumnarCollectionViewControllerLayoutCache {
private var cachedHeights: [String: [Int: CGFloat]] = [:]
private var cacheKeysByGroupKey: [WMFInMemoryURLKey: Set<String>] = [:]
private var cacheKeysByArticleKey: [WMFInMemoryURLKey: Set<String>] = [:]
private var groupKeysByArticleKey: [WMFInMemoryURLKey: Set<WMFInMemoryURLKey>] = [:]
private func cacheKeyForCellWithIdentifier(_ identifier: String, userInfo: String) -> String {
return "\(identifier)-\(userInfo)"
}
public func setHeight(_ height: CGFloat, forCellWithIdentifier identifier: String, columnWidth: CGFloat, groupKey: WMFInMemoryURLKey? = nil, articleKey: WMFInMemoryURLKey? = nil, userInfo: String) {
let cacheKey = cacheKeyForCellWithIdentifier(identifier, userInfo: userInfo)
if let groupKey = groupKey {
cacheKeysByGroupKey[groupKey, default: []].insert(cacheKey)
}
if let articleKey = articleKey {
cacheKeysByArticleKey[articleKey, default: []].insert(cacheKey)
if let groupKey = groupKey {
groupKeysByArticleKey[articleKey, default: []].insert(groupKey)
}
}
cachedHeights[cacheKey, default: [:]][columnWidth.roundedColumnWidth] = height
}
public func cachedHeightForCellWithIdentifier(_ identifier: String, columnWidth: CGFloat, userInfo: String) -> CGFloat? {
let cacheKey = cacheKeyForCellWithIdentifier(identifier, userInfo: userInfo)
return cachedHeights[cacheKey]?[columnWidth.roundedColumnWidth]
}
public func removeCachedHeightsForCellWithIdentifier(_ identifier: String, userInfo: String) {
let cacheKey = cacheKeyForCellWithIdentifier(identifier, userInfo: userInfo)
cachedHeights.removeValue(forKey: cacheKey)
}
public func reset() {
cachedHeights.removeAll(keepingCapacity: true)
cacheKeysByArticleKey.removeAll(keepingCapacity: true)
cacheKeysByGroupKey.removeAll(keepingCapacity: true)
}
@discardableResult public func invalidateArticleKey(_ articleKey: WMFInMemoryURLKey?) -> Bool {
guard let articleKey = articleKey else {
return false
}
if let cacheKeys = cacheKeysByArticleKey[articleKey] {
for cacheKey in cacheKeys {
cachedHeights.removeValue(forKey: cacheKey)
}
cacheKeysByArticleKey.removeValue(forKey: articleKey)
}
guard let groupKeys = groupKeysByArticleKey[articleKey] else {
return false
}
for groupKey in groupKeys {
invalidateGroupKey(groupKey)
}
return true
}
public func invalidateGroupKey(_ groupKey: WMFInMemoryURLKey?) {
guard let groupKey = groupKey, let cacheKeys = cacheKeysByGroupKey[groupKey] else {
return
}
for cacheKey in cacheKeys {
cachedHeights.removeValue(forKey: cacheKey)
}
cacheKeysByGroupKey.removeValue(forKey: groupKey)
}
}
| mit | eb573505293418e740058516a0e705ff | 39.935897 | 202 | 0.663326 | 5.671403 | false | false | false | false |
ikesyo/Swiftz | Swiftz/Arrow.swift | 3 | 6437 | //
// Arrow.swift
// Swiftz
//
// Created by Robert Widmann on 1/18/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// An Arrow is most famous for being a "Generalization of a Monad". They're probably better
/// described as a more general view of computation. Where a monad M<A> yields a value of type A
/// given some context, an Arrow A<B, C> is a function from B -> C in some context A. Functions are
/// the simplest kind of Arrow (pun intended). Their context parameter, A, is essentially empty.
/// From there, the B -> C part of the arrow gets alpha-reduced to the A -> B part of the function
/// type.
///
/// Arrows can be modelled with circuit-esque diagrams, and indeed that can often be a better way to
/// envision the various arrow operators.
///
/// - >>> a -> [ f ] -> b -> [ g ] -> c
/// - <<< a -> [ g ] -> b -> [ f ] -> c
///
/// - arr a -> [ f ] -> b
///
/// - first a -> [ f ] -> b
/// c - - - - - -> c
///
/// - second c - - - - - -> c
/// a -> [ f ] -> b
///
///
/// - *** a - [ f ] -> b - •
/// \
/// o - -> (b, d)
/// /
/// c - [ g ] -> d - •
///
///
/// • a - [ f ] -> b - •
/// | \
/// - &&& a - o o - -> (b, c)
/// | /
/// • a - [ g ] -> c - •
///
/// Arrows inherit from Category so we can get Composition For Free™.
public protocol Arrow : Category {
/// Some arbitrary target our arrow can compose with.
typealias D
/// Some arbitrary target our arrow can compose with.
typealias E
/// Type of the result of first().
typealias FIRST = K2<(A, D), (B, D)>
/// Type of the result of second().
typealias SECOND = K2<(D, A), (D, B)>
/// Some arrow with an arbitrary target and source. Used in split().
typealias ADE = K2<D, E>
/// Type of the result of ***.
typealias SPLIT = K2<(A, D), (B, E)>
/// Some arrow from our target to some other arbitrary target. Used in fanout().
typealias ABD = K2<A, D>
/// Type of the result of &&&.
typealias FANOUT = K2<B, (B, D)>
/// Lift a function to an arrow.
static func arr(_ : A -> B) -> Self
/// Splits the arrow into two tuples that model a computation that applies our Arrow to an
/// argument on the "left side" and sends the "right side" through unchanged.
///
/// The mirror image of second().
func first() -> FIRST
/// Splits the arrow into two tuples that model a computation that applies our Arrow to an
/// argument on the "right side" and sends the "left side" through unchanged.
///
/// The mirror image of first().
func second() -> SECOND
/// Split | Splits two computations and combines the result into one Arrow yielding a tuple of
/// the result of each side.
func ***(_ : Self, _ : ADE) -> SPLIT
/// Fanout | Given two functions with the same source but different targets, this function
/// splits the computation and combines the result of each Arrow into a tuple of the result of
/// each side.
func &&&(_ : Self, _ : ABD) -> FANOUT
}
/// Arrows that can produce an identity arrow.
public protocol ArrowZero : Arrow {
/// An arrow from A -> B. Colloquially, the "zero arrow".
typealias ABC = K2<A, B>
/// The identity arrow.
static func zeroArrow() -> ABC
}
/// A monoid for Arrows.
public protocol ArrowPlus : ArrowZero {
/// A binary function that combines two arrows.
func <+>(_ : ABC, _ : ABC) -> ABC
}
/// Arrows that permit "choice" or selecting which side of the input to apply themselves to.
///
/// - left a - - [ f ] - - > b
/// |
/// a - [f] -> b - o------EITHER------
/// |
/// d - - - - - - - > d
///
/// - right d - - - - - - - > d
/// |
/// a - [f] -> b - o------EITHER------
/// |
/// a - - [ f ] - - > b
///
/// - +++ a - [ f ] -> b - • • a - [ f ] -> b
/// \ |
/// o - -> o-----EITHER-----
/// / |
/// d - [ g ] -> e - • • d - [ g ] -> e
///
/// - ||| a - [ f ] -> c - • • a - [ f ] -> c •
/// \ | \
/// o - -> o-----EITHER-------o - -> c
/// / | /
/// b - [ g ] -> c - • • b - [ g ] -> c •
///
public protocol ArrowChoice : Arrow {
/// The result of left
typealias LEFT = K2<Either<A, D>, Either<B, D>>
/// The result of right
typealias RIGHT = K2<Either<D, A>, Either<D, B>>
/// The result of +++
typealias SPLAT = K2<Either<A, D>, Either<B, E>>
/// Some arrow from a different source and target for fanin.
typealias ACD = K2<B, D>
/// The result of |||
typealias FANIN = K2<Either<A, B>, D>
/// Feed marked inputs through the argument arrow, passing the rest through unchanged to the
/// output.
func left() -> LEFT
/// The mirror image of left.
func right() -> RIGHT
/// Splat | Split the input between both argument arrows, then retag and merge their outputs
/// into Eithers.
func +++(_ : Self, _ : ADE) -> SPLAT
/// Fanin | Split the input between two argument arrows and merge their ouputs.
func |||(_ : ABD, _ : ACD) -> FANIN
}
/// Arrows that allow application of arrow inputs to other inputs. Such arrows are equivalent to
/// monads.
///
/// - app (f : a -> b) - •
/// \
/// o - a - [ f ] -> b
/// /
/// a -------> a - •
///
public protocol ArrowApply : Arrow {
typealias APP = K2<(Self, A), B>
static func app() -> APP
}
/// Arrows that admit right-tightening recursion.
///
/// The 'loop' operator expresses computations in which an output value is fed back as input,
/// although the computation occurs only once.
///
/// •-------•
/// | |
/// - loop a - - [ f ] - -> b
/// | |
/// d-------•
///
public protocol ArrowLoop : Arrow {
typealias LOOP = K2<(A, D), (B, D)>
static func loop(_ : LOOP) -> Self
}
| bsd-3-clause | 0318ad2d69c3da7818344c34fff9a813 | 32.471204 | 100 | 0.48381 | 3.60372 | false | false | false | false |
bcylin/QuickTableViewController | Source/Views/SwitchCell.swift | 1 | 4032 | //
// SwitchCell.swift
// QuickTableViewController
//
// Created by Ben on 03/09/2015.
// Copyright (c) 2015 bcylin.
//
// 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
/// The `SwitchCellDelegate` protocol allows the adopting delegate to respond to the UI interaction. Not available on tvOS.
@available(tvOS, unavailable, message: "SwitchCellDelegate is not available on tvOS.")
public protocol SwitchCellDelegate: AnyObject {
/// Tells the delegate that the switch control is toggled.
func switchCell(_ cell: SwitchCell, didToggleSwitch isOn: Bool)
}
// MARK: -
/// A `UITableViewCell` subclass that shows a `UISwitch` as the `accessoryView`.
open class SwitchCell: UITableViewCell, Configurable {
#if os(iOS)
/// A `UISwitch` as the `accessoryView`. Not available on tvOS.
@available(tvOS, unavailable, message: "switchControl is not available on tvOS.")
public private(set) lazy var switchControl: UISwitch = {
let control = UISwitch()
control.addTarget(self, action: #selector(SwitchCell.didToggleSwitch(_:)), for: .valueChanged)
return control
}()
#endif
/// The switch cell's delegate object, which should conform to `SwitchCellDelegate`. Not available on tvOS.
@available(tvOS, unavailable, message: "SwitchCellDelegate is not available on tvOS.")
open weak var delegate: SwitchCellDelegate?
// MARK: - Initializer
/**
Overrides `UITableViewCell`'s designated initializer.
- parameter style: A constant indicating a cell style.
- parameter reuseIdentifier: A string used to identify the cell object if it is to be reused for drawing multiple rows of a table view.
- returns: An initialized `SwitchCell` object.
*/
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpAppearance()
}
/**
Overrides the designated initializer that returns an object initialized from data in a given unarchiver.
- parameter aDecoder: An unarchiver object.
- returns: `self`, initialized using the data in decoder.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpAppearance()
}
// MARK: - Configurable
/// Set up the switch control (iOS) or accessory type (tvOS) with the provided row.
open func configure(with row: Row & RowStyle) {
#if os(iOS)
if let row = row as? SwitchRowCompatible {
switchControl.isOn = row.switchValue
}
accessoryView = switchControl
#elseif os(tvOS)
accessoryView = nil
accessoryType = row.accessoryType
#endif
}
// MARK: - Private
@available(tvOS, unavailable, message: "UISwitch is not available on tvOS.")
@objc
private func didToggleSwitch(_ sender: UISwitch) {
delegate?.switchCell(self, didToggleSwitch: sender.isOn)
}
private func setUpAppearance() {
textLabel?.numberOfLines = 0
detailTextLabel?.numberOfLines = 0
}
}
| mit | fc2a07769583e1f90ce134837123af4d | 35 | 138 | 0.725198 | 4.535433 | false | false | false | false |
Daniel-Lopez/EZSwiftExtensions | Sources/UIViewControllerExtensions.swift | 1 | 8271 | //
// UIViewControllerExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension UIViewController {
// MARK: - Notifications
//TODO: Document this part
public func addNotificationObserver(name: String, selector: Selector) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: nil)
}
public func removeNotificationObserver(name: String) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: name, object: nil)
}
public func removeNotificationObserver() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public func addKeyboardWillShowNotification() {
self.addNotificationObserver(UIKeyboardWillShowNotification, selector: #selector(UIViewController.keyboardWillShowNotification(_:)))
}
public func addKeyboardDidShowNotification() {
self.addNotificationObserver(UIKeyboardDidShowNotification, selector: #selector(UIViewController.keyboardDidShowNotification(_:)))
}
public func addKeyboardWillHideNotification() {
self.addNotificationObserver(UIKeyboardWillHideNotification, selector: #selector(UIViewController.keyboardWillHideNotification(_:)))
}
public func addKeyboardDidHideNotification() {
self.addNotificationObserver(UIKeyboardDidHideNotification, selector: #selector(UIViewController.keyboardDidHideNotification(_:)))
}
public func removeKeyboardWillShowNotification() {
self.removeNotificationObserver(UIKeyboardWillShowNotification)
}
public func removeKeyboardDidShowNotification() {
self.removeNotificationObserver(UIKeyboardDidShowNotification)
}
public func removeKeyboardWillHideNotification() {
self.removeNotificationObserver(UIKeyboardWillHideNotification)
}
public func removeKeyboardDidHideNotification() {
self.removeNotificationObserver(UIKeyboardDidHideNotification)
}
public func keyboardDidShowNotification(notification: NSNotification) {
if let nInfo = notification.userInfo,
let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
keyboardDidShowWithFrame(frame)
}
}
public func keyboardWillShowNotification(notification: NSNotification) {
if let nInfo = notification.userInfo,
let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
keyboardWillShowWithFrame(frame)
}
}
public func keyboardWillHideNotification(notification: NSNotification) {
if let nInfo = notification.userInfo,
let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
keyboardWillHideWithFrame(frame)
}
}
public func keyboardDidHideNotification(notification: NSNotification) {
if let nInfo = notification.userInfo,
let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
keyboardDidHideWithFrame(frame)
}
}
public func keyboardWillShowWithFrame(frame: CGRect) {
}
public func keyboardDidShowWithFrame(frame: CGRect) {
}
public func keyboardWillHideWithFrame(frame: CGRect) {
}
public func keyboardDidHideWithFrame(frame: CGRect) {
}
//EZSE: Makes the UIViewController register tap events and hides keyboard when clicked somewhere in the ViewController.
public func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
public func dismissKeyboard() {
view.endEditing(true)
}
// MARK: - VC Container
/// EZSwiftExtensions
public var top: CGFloat {
get {
if let me = self as? UINavigationController,
let visibleViewController = me.visibleViewController {
return visibleViewController.top
}
if let nav = self.navigationController {
if nav.navigationBarHidden {
return view.top
} else {
return nav.navigationBar.bottom
}
} else {
return view.top
}
}
}
/// EZSwiftExtensions
public var bottom: CGFloat {
get {
if let me = self as? UINavigationController,
let visibleViewController = me.visibleViewController {
return visibleViewController.bottom
}
if let tab = tabBarController {
if tab.tabBar.hidden {
return view.bottom
} else {
return tab.tabBar.top
}
} else {
return view.bottom
}
}
}
/// EZSwiftExtensions
public var tabBarHeight: CGFloat {
get {
if let me = self as? UINavigationController,
let visibleViewController = me.visibleViewController {
return visibleViewController.tabBarHeight
}
if let tab = self.tabBarController {
return tab.tabBar.frame.size.height
}
return 0
}
}
/// EZSwiftExtensions
public var navigationBarHeight: CGFloat {
get {
if let me = self as? UINavigationController,
let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarHeight
}
if let nav = self.navigationController {
return nav.navigationBar.h
}
return 0
}
}
/// EZSwiftExtensions
public var navigationBarColor: UIColor? {
get {
if let me = self as? UINavigationController,
let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarColor
}
return navigationController?.navigationBar.tintColor
} set(value) {
navigationController?.navigationBar.barTintColor = value
}
}
/// EZSwiftExtensions
public var navBar: UINavigationBar? {
get {
return navigationController?.navigationBar
}
}
/// EZSwiftExtensions
public var applicationFrame: CGRect {
get {
return CGRect(x: view.x, y: top, width: view.w, height: bottom - top)
}
}
// MARK: - VC Flow
/// EZSwiftExtensions
public func pushVC(vc: UIViewController) {
navigationController?.pushViewController(vc, animated: true)
}
/// EZSwiftExtensions
public func popVC() {
navigationController?.popViewControllerAnimated(true)
}
/// EZSwiftExtensions
public func presentVC(vc: UIViewController) {
presentViewController(vc, animated: true, completion: nil)
}
/// EZSwiftExtensions
public func dismissVC(completion completion: (() -> Void)? ) {
dismissViewControllerAnimated(true, completion: completion)
}
/// EZSwiftExtensions
public func addAsChildViewController(vc: UIViewController, toView: UIView) {
toView.addSubview(vc.view)
self.addChildViewController(vc)
vc.didMoveToParentViewController(self)
}
///EZSE: Adds image named: as a UIImageView in the Background
func setBackgroundImage(named: String) {
let image = UIImage(named: named)
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
///EZSE: Adds UIImage as a UIImageView in the Background
@nonobjc func setBackgroundImage(image: UIImage) {
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
}
| mit | 3d66047449a63e31ca857bdcec9fccc4 | 30.811538 | 140 | 0.645025 | 6.086093 | false | false | false | false |
wircho/SwiftyNotification | SwiftyNotification/SwiftyNotification.swift | 1 | 1979 | //---
import Foundation
// MARK: Notification Protocol
public protocol Notification {
associatedtype P
static var name:String { get }
static func note(params:P) throws -> NSNotification
static func parameters(note:NSNotification) throws -> P
}
extension Notification {
public static func note(params:P) throws -> NSNotification {
throw NotificationError.MethodNotImplemented
}
public static func register<T:AnyObject>(listener:T, object:AnyObject? = nil, queue: NSOperationQueue? = nil, closure:(T,P)->Void) -> NotificationToken {
var token:NotificationToken? = nil
let observer = NSNotificationCenter.defaultCenter().addObserverForName(name, object: object, queue: queue) {
note in
guard let actualToken = token else { return }
guard let listener = actualToken.listener as? T else {
actualToken.cancel()
token = nil
return
}
guard let params = try? parameters(note) else { return }
closure(listener,params)
}
token = NotificationToken(listener: listener, observer: observer)
return token!
}
public static func post(params:P) throws -> Void {
let note = try self.note(params)
NSNotificationCenter.defaultCenter().postNotification(note)
}
}
// MARK: Notification Token
public class NotificationToken {
private weak var listener:AnyObject?
private var observer:NSObjectProtocol?
private init(listener:AnyObject, observer:NSObjectProtocol) {
self.listener = listener
self.observer = observer
}
deinit {
self.cancel()
}
func cancel() {
guard let observer = observer else { return }
self.observer = nil
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
}
// MARK: Notification Error
public enum NotificationError: ErrorType {
case MethodNotImplemented
}
| mit | 1a231f2635dc6512b2ed34f9e81350e9 | 30.412698 | 157 | 0.657403 | 5.010127 | false | false | false | false |
kingslay/KSJSONHelp | Core/Source/PropertyData.swift | 1 | 5102 | //
// PropertyData.swift
// SwiftyDB
//
// Created by Øyvind Grimnes on 20/12/15.
//
import Foundation
internal struct PropertyData {
internal let isOptional: Bool
internal var type: Any.Type
internal var bindingType: Binding.Type?
internal var name: String?
lazy internal var bindingValue: Binding? = self.toBinding(self.value)
internal let value: Any
internal var isValid: Bool {
return name != nil
}
internal init(property: Mirror.Child) {
self.name = property.label
let mirror = Mirror(reflecting: property.value)
self.type = mirror.subjectType
isOptional = mirror.displayStyle == .optional
if isOptional {
if mirror.children.count == 1 {
self.value = mirror.children.first!.value
}else{
self.value = property.value
}
}else{
self.value = property.value
}
bindingType = typeForMirror(mirror)
}
internal func typeForMirror(_ mirror: Mirror) -> Binding.Type? {
if !isOptional {
if mirror.displayStyle == .collection {
return NSArray.self
}
if mirror.displayStyle == .dictionary {
return NSDictionary.self
}
return mirror.subjectType as? Binding.Type
}
// TODO: Find a better way to unwrap optional types
// Can easily be done using mirror if the encapsulated value is not nil
switch mirror.subjectType {
case is Optional<String>.Type: return String.self
case is Optional<NSString>.Type: return NSString.self
case is Optional<Character>.Type: return Character.self
case is Optional<Date>.Type: return Date.self
case is Optional<NSNumber>.Type: return NSNumber.self
case is Optional<Data>.Type: return Data.self
case is Optional<Bool>.Type: return Bool.self
case is Optional<Int>.Type: return Int.self
case is Optional<Int8>.Type: return Int8.self
case is Optional<Int16>.Type: return Int16.self
case is Optional<Int32>.Type: return Int32.self
case is Optional<Int64>.Type: return Int64.self
case is Optional<UInt>.Type: return UInt.self
case is Optional<UInt8>.Type: return UInt8.self
case is Optional<UInt16>.Type: return UInt16.self
case is Optional<UInt32>.Type: return UInt32.self
case is Optional<UInt64>.Type: return UInt64.self
case is Optional<Float>.Type: return Float.self
case is Optional<Double>.Type: return Double.self
case is Optional<NSArray>.Type: return NSArray.self
case is Optional<NSDictionary>.Type: return NSDictionary.self
default: return nil
}
}
/**
Unwraps any value
- parameter value: The value to unwrap
*/
fileprivate func toBinding(_ value: Any) -> Binding? {
let mirror = Mirror(reflecting: value)
if mirror.displayStyle == .collection {
return NSKeyedArchiver.archivedData(withRootObject: value as! NSArray)
}
if mirror.displayStyle == .dictionary {
return NSKeyedArchiver.archivedData(withRootObject: value as! NSDictionary)
}
/* Raw value */
if mirror.displayStyle != .optional {
return value as? Binding
}
/* The encapsulated optional value if not nil, otherwise nil */
if let value = mirror.children.first?.value {
return toBinding(value)
}else{
return nil
}
}
}
extension PropertyData {
internal static func validPropertyDataForObject (_ object: Any) -> [PropertyData] {
var ignoredProperties = Set<String>()
return validPropertyDataForMirror(Mirror(reflecting: object), ignoredProperties: &ignoredProperties)
}
fileprivate static func validPropertyDataForMirror(_ mirror: Mirror, ignoredProperties: inout Set<String>) -> [PropertyData] {
if mirror.subjectType is IgnoredPropertieProtocol.Type {
ignoredProperties = ignoredProperties.union((mirror.subjectType as! IgnoredPropertieProtocol.Type).ignoredProperties())
}
var propertyData: [PropertyData] = []
if let superclassMirror = mirror.superclassMirror {
propertyData += validPropertyDataForMirror(superclassMirror, ignoredProperties: &ignoredProperties)
}
/* Map children to property data and filter out ignored or invalid properties */
propertyData += mirror.children.map {
PropertyData(property: $0)
}.filter({
$0.isValid && !ignoredProperties.contains($0.name!)
})
return propertyData
}
}
| mit | 0ce97e701c6464c930f42b583022acc7 | 34.671329 | 131 | 0.594197 | 5.020669 | false | false | false | false |
hoowang/SWiftQRScanner | SWiftQRScanner/SWiftQRScanner/QRCodeScanner/QRCodeScannerController.swift | 1 | 1129 | //
// QRCodeScannerController.swift
// WKWeibo
//
// Created by hooge on 15/9/16.
// Copyright © 2015年 hoowang. All rights reserved.
//
import UIKit
class QRCodeScannerController: UIViewController {
@IBOutlet weak var scanLineView: UIImageView!
@IBOutlet weak var scanLineTopConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func CloseScanner(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
startScanAnimation()
}
private func startScanAnimation()
{
let basicAnimation = CABasicAnimation()
basicAnimation.keyPath = "position.y"
basicAnimation.toValue = scanLineView.bounds.height
basicAnimation.fromValue = 0.0
basicAnimation.duration = 1.0
basicAnimation.repeatCount = MAXFLOAT
basicAnimation.removedOnCompletion = false
scanLineView.layer.addAnimation(basicAnimation, forKey: "")
scanLineView.startAnimating()
}
}
| mit | 85727622933c558f99290271b6af1f4f | 25.809524 | 67 | 0.692718 | 5.004444 | false | false | false | false |
kirsteins/BigInteger | Source/Operators.swift | 1 | 4810 | //
// Operators.swift
// BigInteger
//
// Created by Jānis Kiršteins on 17/09/14.
// Copyright (c) 2014 Jānis Kiršteins. All rights reserved.
//
// MARK: - comparison
public func == (lhs: Int, rhs: BigInteger) -> Bool {
return BigInteger(lhs) == rhs
}
public func == (lhs: BigInteger, rhs: Int) -> Bool {
return lhs == BigInteger(rhs)
}
public func >= (lhs: Int, rhs: BigInteger) -> Bool {
return BigInteger(lhs) >= rhs
}
public func >= (lhs: BigInteger, rhs: Int) -> Bool {
return lhs >= BigInteger(rhs)
}
public func <= (lhs: Int, rhs: BigInteger) -> Bool {
return BigInteger(lhs) <= rhs
}
public func <= (lhs: BigInteger, rhs: Int) -> Bool {
return lhs <= BigInteger(rhs)
}
public func > (lhs: Int, rhs: BigInteger) -> Bool {
return BigInteger(lhs) > rhs
}
public func > (lhs: BigInteger, rhs: Int) -> Bool {
return lhs > BigInteger(rhs)
}
public func < (lhs: Int, rhs: BigInteger) -> Bool {
return BigInteger(lhs) < rhs
}
public func < (lhs: BigInteger, rhs: Int) -> Bool {
return lhs < BigInteger(rhs)
}
// MARK: - add
public func + (lhs: BigInteger, rhs: BigInteger) -> BigInteger {
return lhs.add(rhs)
}
public func + (lhs: BigInteger, rhs: Int) -> BigInteger {
return lhs.add(rhs)
}
public func + (lhs: Int, rhs: BigInteger) -> BigInteger {
return rhs.add(lhs)
}
public func += (inout lhs: BigInteger, rhs: BigInteger) {
lhs = lhs.add(rhs)
}
public func += (inout lhs: BigInteger, rhs: Int) {
lhs = lhs.add(rhs)
}
// MARK: - subtract
public func - (lhs: BigInteger, rhs: BigInteger) -> BigInteger {
return lhs.subtract(rhs)
}
public func - (lhs: BigInteger, rhs: Int) -> BigInteger {
return lhs.subtract(rhs)
}
public func - (lhs: Int, rhs: BigInteger) -> BigInteger {
return rhs.negate().add(lhs)
}
public func -= (inout lhs: BigInteger, rhs: BigInteger) {
lhs = lhs.subtract(rhs)
}
public func -= (inout lhs: BigInteger, rhs: Int) {
lhs = lhs.subtract(rhs)
}
// MARK: - multiply
public func * (lhs: BigInteger, rhs: BigInteger) -> BigInteger {
return lhs.multiplyBy(rhs)
}
public func * (lhs: BigInteger, rhs: Int) -> BigInteger {
return lhs.multiplyBy(rhs)
}
public func * (lhs: Int, rhs: BigInteger) -> BigInteger {
return rhs.multiplyBy(lhs)
}
public func *= (inout lhs: BigInteger, rhs: BigInteger) {
lhs = lhs.multiplyBy(rhs)
}
public func *= (inout lhs: BigInteger, rhs: Int) {
lhs = lhs.multiplyBy(rhs)
}
// MARK: - divide
public func / (lhs: BigInteger, rhs: BigInteger) -> BigInteger? {
return lhs.divideBy(rhs)
}
public func / (lhs: BigInteger, rhs: Int) -> BigInteger? {
return lhs.divideBy(rhs)
}
// MARK: - reminder
public func % (lhs: BigInteger, rhs: BigInteger) -> BigInteger? {
return lhs.reminder(rhs)
}
public func % (lhs: BigInteger, rhs: Int) -> BigInteger? {
return lhs.reminder(rhs)
}
// MARK: - negate
public prefix func - (operand: BigInteger) -> BigInteger {
return operand.negate()
}
// MARK: - xor
public func ^ (lhs: BigInteger, rhs: BigInteger) -> BigInteger {
return lhs.bitwiseXor(rhs)
}
public func ^ (lhs: BigInteger, rhs: Int) -> BigInteger {
return lhs.bitwiseXor(rhs)
}
public func ^ (lhs: Int, rhs: BigInteger) -> BigInteger {
return rhs.bitwiseXor(lhs)
}
public func ^= (inout lhs: BigInteger, rhs: BigInteger) {
lhs = lhs.bitwiseXor(rhs)
}
public func ^= (inout lhs: BigInteger, rhs: Int) {
lhs = lhs.bitwiseXor(rhs)
}
// MARK: - or
public func | (lhs: BigInteger, rhs: BigInteger) -> BigInteger {
return lhs.bitwiseOr(rhs)
}
public func | (lhs: BigInteger, rhs: Int) -> BigInteger {
return lhs.bitwiseOr(rhs)
}
public func | (lhs: Int, rhs: BigInteger) -> BigInteger {
return rhs.bitwiseOr(lhs)
}
public func |= (inout lhs: BigInteger, rhs: BigInteger) {
lhs = lhs.bitwiseOr(rhs)
}
public func |= (inout lhs: BigInteger, rhs: Int) {
lhs = lhs.bitwiseOr(rhs)
}
// MARK: - and
public func & (lhs: BigInteger, rhs: BigInteger) -> BigInteger {
return lhs.bitwiseAnd(rhs)
}
public func & (lhs: BigInteger, rhs: Int) -> BigInteger {
return lhs.bitwiseAnd(rhs)
}
public func & (lhs: Int, rhs: BigInteger) -> BigInteger {
return rhs.bitwiseAnd(lhs)
}
public func &= (inout lhs: BigInteger, rhs: BigInteger) {
lhs = lhs.bitwiseAnd(rhs)
}
public func &= (inout lhs: BigInteger, rhs: Int) {
lhs = lhs.bitwiseAnd(rhs)
}
// MARK: - shiftLeft
public func << (lhs: BigInteger, rhs: Int32) -> BigInteger {
return lhs.shiftLeft(rhs)
}
public func <<= (inout lhs: BigInteger, rhs: Int32) {
lhs = lhs.shiftLeft(rhs)
}
// MARK: - shiftRight
public func >> (lhs: BigInteger, rhs: Int32) -> BigInteger {
return lhs.shiftRight(rhs)
}
public func >>= (inout lhs: BigInteger, rhs: Int32) {
lhs = lhs.shiftRight(rhs)
}
| mit | c36de036c71127e648c5b775586db025 | 20.171806 | 65 | 0.642738 | 3.247297 | false | false | false | false |
moozzyk/SignalR-Client-Swift | Examples/Playground/Playground.playground/Contents.swift | 1 | 1762 | import Cocoa
import SignalRClient
let hubConnection = HubConnectionBuilder(url: URL(string: "http://localhost:5000/playground")!)
.withLogging(minLogLevel: .info)
.build()
hubConnection.on(method: "AddMessage") {(user: String, message: String) in
print(">>> \(user): \(message)")
}
hubConnection.start()
// NOTE: break here before to make this sample work and prevent errors
// caused by trying to invoke server side methods before starting the
// connection completed
// invoking a hub method and receiving a result
hubConnection.invoke(method: "Add", 2, 3, resultType: Int.self) { result, error in
if let error = error {
print("error: \(error)")
} else {
print("Add result: \(result!)")
}
}
// invoking a hub method that does not return a result
hubConnection.invoke(method: "Broadcast", "Playground user", "Sending a message") { error in
if let error = error {
print("error: \(error)")
} else {
print("Broadcast invocation completed without errors")
}
}
hubConnection.send(method: "Broadcast", "Playground user", "Testing send") { error in
if let error = error {
print("Send failed: \(error)")
}
}
let streamHandle = hubConnection.stream(method: "StreamNumbers", 1, 10000, streamItemReceived: { (item: Int) in print(">>> \(item)") }) { error in
print("Stream closed.")
if let error = error {
print("Error: \(error)")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
hubConnection.cancelStreamInvocation(streamHandle: streamHandle) { error in
print("Canceling stream invocation failed: \(error)")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
hubConnection.stop()
}
| mit | 50e670f63f0e71da23839db46c0fe844 | 30.464286 | 146 | 0.660045 | 4.032037 | false | false | false | false |
Eonil/EditorLegacy | Modules/EditorFileTreeNavigationFeature/EditorFileTreeNavigationFeature/FileNavigating/FileTreeViewController.swift | 2 | 4019 | ////
//// FileTreeViewController.swift
//// RustCodeEditor
////
//// Created by Hoon H. on 11/11/14.
//// Copyright (c) 2014 Eonil. All rights reserved.
////
//
//import Foundation
//import AppKit
//
//class FileTreeViewController : NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
//
// let userIsWantingToEditFileAtPath = Notifier<String>()
//
// private var _root:FileNode1?
//
// var pathRepresentation:String? {
// get {
// return self.representedObject as String?
// }
// set(v) {
// self.representedObject = v
// }
// }
// override var representedObject:AnyObject? {
// get {
// return super.representedObject
// }
// set(v) {
// precondition(v is String)
// super.representedObject = v
//
// if let v2 = v as String? {
// _root = FileNode1(path: pathRepresentation!)
// } else {
// _root = nil
// }
//
// self.outlineView.reloadData()
// }
// }
//
// var outlineView:NSOutlineView {
// get {
// return self.view as NSOutlineView
// }
// set(v) {
// self.view = v
// }
// }
//
// override func loadView() {
// super.view = NSOutlineView()
// }
// override func viewDidLoad() {
// super.viewDidLoad()
//
// let col1 = NSTableColumn(identifier: NAME, title: "Name", width: 100)
//
// outlineView.focusRingType = NSFocusRingType.None
// outlineView.headerView = nil
// outlineView.addTableColumn <<< col1
// outlineView.outlineTableColumn = col1
// outlineView.rowSizeStyle = NSTableViewRowSizeStyle.Small
// outlineView.selectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList
// outlineView.sizeLastColumnToFit()
//
// outlineView.setDataSource(self)
// outlineView.setDelegate(self)
//
// }
//
//
//
//
//// func outlineView(outlineView: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat {
//// return 16
//// }
//
// func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
// let n1 = item as FileNode1?
// if let n2 = n1 {
// if let ns3 = n2.subnodes {
// return ns3.count
// } else {
// return 0
// }
// } else {
// return _root == nil ? 0 : 1
// }
// }
// func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
// let n1 = item as FileNode1?
// if let n2 = n1 {
// let ns3 = n2.subnodes!
// return ns3[index]
// } else {
// return _root!
// }
// }
//// func outlineView(outlineView: NSOutlineView, isGroupItem item: AnyObject) -> Bool {
//// let n1 = item as FileNode1
//// let ns2 = n1.subnodes
//// return ns2 != nil
//// }
// func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
// let n1 = item as FileNode1
// let ns2 = n1.subnodes
// return ns2 != nil
// }
//// func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? {
//// let n1 = item as FileNode1
//// return n1.relativePath
//// }
// func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? {
// let tv1 = NSTextField()
// let iv1 = NSImageView()
// let cv1 = NSTableCellView()
// cv1.textField = tv1
// cv1.imageView = iv1
// cv1.addSubview(tv1)
// cv1.addSubview(iv1)
//
// let n1 = item as FileNode1
// assert(n1.existing)
// iv1.image = NSWorkspace.sharedWorkspace().iconForFile(n1.absolutePath)
// cv1.textField!.stringValue = n1.displayName
// cv1.textField!.bordered = false
// cv1.textField!.backgroundColor = NSColor.clearColor()
// cv1.textField!.editable = false
// (cv1.textField!.cell() as NSCell).lineBreakMode = NSLineBreakMode.ByTruncatingHead
// return cv1
// }
//
//
//
// func outlineViewSelectionDidChange(notification: NSNotification) {
// let idx1 = self.outlineView.selectedRow
// let n1 = self.outlineView.itemAtRow(idx1) as FileNode1
// userIsWantingToEditFileAtPath.signal(n1.absolutePath)
// }
//}
//
//
//
//
//
//
//
//
//private let NAME = "NAME"
//
| mit | a9d1e318e92891d7e2ab85212749a10e | 25.267974 | 145 | 0.657129 | 2.858464 | false | false | false | false |
malaonline/iOS | mala-ios/View/OrderForm/OrderFormOperatingView.swift | 1 | 9522 | //
// OrderFormOperatingView.swift
// mala-ios
//
// Created by 王新宇 on 16/5/13.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
public protocol OrderFormOperatingViewDelegate: class {
/// 立即支付
func orderFormPayment()
/// 再次购买
func orderFormBuyAgain()
/// 取消订单
func orderFormCancel()
/// 申请退费
func requestRefund()
}
class OrderFormOperatingView: UIView {
// MARK: - Property
/// 需支付金额
var price: Int = 0 {
didSet{
priceLabel.text = price.amountCNY
}
}
/// 订单详情模型
var model: OrderForm? {
didSet {
/// 渲染底部视图UI
isTeacherPublished = model?.isTeacherPublished
orderStatus = model?.orderStatus ?? .confirm
price = isForConfirm ? MalaCurrentCourse.getAmount() ?? 0 : model?.amount ?? 0
}
}
/// 标识是否为确认订单状态
var isForConfirm: Bool = false {
didSet {
/// 渲染底部视图UI
if isForConfirm {
orderStatus = .confirm
}
}
}
/// 订单状态
var orderStatus: MalaOrderStatus = .canceled {
didSet {
DispatchQueue.main.async {
self.changeDisplayMode()
}
}
}
/// 老师上架状态标记
var isTeacherPublished: Bool?
weak var delegate: OrderFormOperatingViewDelegate?
// MARK: - Components
/// 价格容器
private lazy var priceContainer: UIView = {
let view = UIView(UIColor.white)
return view
}()
/// 合计标签
private lazy var stringLabel: UILabel = {
let label = UILabel(
text: "合计:",
font: FontFamily.PingFangSC.Light.font(13),
textColor: UIColor(named: .ArticleTitle)
)
return label
}()
/// 金额标签
private lazy var priceLabel: UILabel = {
let label = UILabel(
text: "¥0.00",
font: FontFamily.PingFangSC.Light.font(18),
textColor: UIColor(named: .ThemeRed)
)
return label
}()
/// 确定按钮(确认支付、再次购买、重新购买)
private lazy var confirmButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
return button
}()
/// 取消按钮(取消订单)
private lazy var cancelButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
return button
}()
// MARK: - Constructed
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private method
private func setupUserInterface() {
// Style
backgroundColor = UIColor.white
// SubViews
addSubview(priceContainer)
priceContainer.addSubview(stringLabel)
priceContainer.addSubview(priceLabel)
addSubview(cancelButton)
addSubview(confirmButton)
// Autolayout
priceContainer.snp.makeConstraints{ (maker) -> Void in
maker.top.equalTo(self)
maker.left.equalTo(self)
maker.width.equalTo(self).multipliedBy(0.44)
maker.height.equalTo(44)
maker.bottom.equalTo(self)
}
stringLabel.snp.makeConstraints { (maker) in
maker.right.equalTo(priceLabel.snp.left)
maker.centerY.equalTo(priceContainer)
maker.height.equalTo(18.5)
}
priceLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(priceContainer)
maker.centerX.equalTo(priceContainer).offset(17)
maker.height.equalTo(25)
}
confirmButton.snp.makeConstraints { (maker) in
maker.right.equalTo(self)
maker.centerY.equalTo(self)
maker.width.equalTo(self).multipliedBy(0.28)
maker.height.equalTo(self)
}
cancelButton.snp.makeConstraints { (maker) in
maker.right.equalTo(confirmButton.snp.left)
maker.centerY.equalTo(self)
maker.width.equalTo(self).multipliedBy(0.28)
maker.height.equalTo(self)
}
}
/// 根据当前订单状态,渲染对应UI样式
private func changeDisplayMode() {
// 仅当订单金额已支付, 课程类型为一对一课程时
// 老师下架状态才会生效
if let isLiveCourse = model?.isLiveCourse, isLiveCourse == false &&
isTeacherPublished == false && orderStatus != .penging && orderStatus != .confirm {
setTeacherDisable()
return
}
switch orderStatus {
case .penging: setOrderPending()
case .paid: setOrderPaid()
case .paidRefundable: setOrderPaidRefundable()
case .finished: setOrderFinished()
case .refunding: setOrderRefunding()
case .refund: setOrderRefund()
case .canceled: setOrderCanceled()
case .confirm: setOrderConfirm()
}
}
/// 待支付样式
private func setOrderPending() {
cancelButton.isHidden = false
cancelButton.setTitle(L10n.cancelOrder, for: .normal)
cancelButton.setTitleColor(UIColor.white, for: .normal)
cancelButton.setBackgroundImage(UIImage.withColor(UIColor(named: .ThemeBlue)), for: .normal)
cancelButton.addTarget(self, action: #selector(OrderFormOperatingView.cancelOrderForm), for: .touchUpInside)
setButton("去支付", UIColor(named: .ThemeBlue), enabled: false, action: #selector(OrderFormOperatingView.pay), relayout: false)
}
/// 进行中不可退费样式(only for private tuition)
private func setOrderPaid() {
setButton("再次购买", UIColor(named: .ThemeRed), action: #selector(OrderFormOperatingView.buyAgain))
}
/// 进行中可退费样式(only for live course)
private func setOrderPaidRefundable() {
setButton("申请退费", UIColor(named: .ThemeGreen), action: #selector(OrderFormOperatingView.requestRefund))
}
/// 已完成样式(only for live course)
private func setOrderFinished() {
setButton("再次购买", UIColor(named: .ThemeRed), hidden: true, action: #selector(OrderFormOperatingView.buyAgain))
cancelButton.isHidden = true
}
/// 退费审核中样式(only for live course)
private func setOrderRefunding() {
setButton("审核中...", UIColor(named: .Disabled), enabled: false)
}
/// 已退费样式
private func setOrderRefund() {
setButton("已退费", UIColor(named: .ThemeGreen), enabled: false)
}
/// 已取消样式
private func setOrderCanceled() {
var color = UIColor(named: .Disabled)
var action: Selector?
var enable = true
var string = "重新购买"
if let isLive = model?.isLiveCourse, isLive == true {
string = "订单已关闭"
enable = false
}else {
color = UIColor(named: .ThemeRed)
action = #selector(OrderFormOperatingView.buyAgain)
}
setButton(string, color, enabled: enable, action: action)
}
/// 订单预览样式
private func setOrderConfirm() {
setButton("提交订单", UIColor(named: .ThemeRed), action: #selector(OrderFormOperatingView.pay))
}
/// 教师已下架样式
private func setTeacherDisable() {
setButton("该老师已下架", UIColor(named: .Disabled), enabled: false)
}
private func setButton( _ title: String, _ bgColor: UIColor, _ titleColor: UIColor = UIColor.white, enabled: Bool? = nil, hidden: Bool = false,
action: Selector? = nil, relayout: Bool = true) {
cancelButton.isHidden = true
confirmButton.isHidden = hidden
if let enabled = enabled {
confirmButton.isEnabled = enabled
}
if let action = action {
confirmButton.addTarget(self, action: action, for: .touchUpInside)
}
confirmButton.setTitle(title, for: .normal)
confirmButton.setBackgroundImage(UIImage.withColor(bgColor), for: .normal)
confirmButton.setTitleColor(titleColor, for: .normal)
guard relayout == true else { return }
confirmButton.snp.remakeConstraints { (maker) in
maker.right.equalTo(self)
maker.centerY.equalTo(self)
maker.width.equalTo(self).multipliedBy(0.5)
maker.height.equalTo(self)
}
}
// MARK: - Event Response
/// 立即支付
@objc func pay() {
delegate?.orderFormPayment()
}
/// 再次购买
@objc func buyAgain() {
delegate?.orderFormBuyAgain()
}
/// 取消订单
@objc func cancelOrderForm() {
delegate?.orderFormCancel()
}
/// 申请退费
@objc func requestRefund() {
delegate?.requestRefund()
}
deinit {
println("Order Form Operation View Deinit")
}
}
| mit | d71bc7f0886b79b880aaaa04e23ac02f | 29.658703 | 147 | 0.581766 | 4.518612 | false | false | false | false |
futomtom/DynoOrder | Dyno/DynoOrder/ItemCell.swift | 1 | 907 | //
// ItemCell.swift
// DynoOrder
//
// Created by alexfu on 10/20/16.
// Copyright © 2016 Alex. All rights reserved.
//
import UIKit
class ItemCell: UICollectionViewCell {
@IBOutlet weak var imageV: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var stepper: UIStepper!
@IBOutlet weak var number: UILabel!
let colors = [UIColor.blue, UIColor.red, UIColor.yellow, UIColor.cyan, UIColor.gray,UIColor.brown, UIColor.orange ]
override func awakeFromNib() {
layer.borderColor=UIColor.darkGray.cgColor
layer.borderWidth=1
layer.cornerRadius = 4
}
func setData(item: Product, index:Int) {
// imageV.image = UIImage(name: " ")
name.text = NSLocalizedString("my book",comment:"")
stepper.tag = index
// backgroundColor = colors[index%colors.count]
}
}
| mit | 9179e1e1e61d3578fb95987bfdac6281 | 20.571429 | 119 | 0.628035 | 4.175115 | false | false | false | false |
mbeloded/beaconDemo | PassKitApp/PassKitApp/Classes/Managers/CoreDataManager/CoreDataManager.swift | 1 | 12527 | //
// CoreDataManager.swift
// PassKitApp
//
// Created by Alexandr Chernyy on 10/6/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import UIKit
import CoreData
class CoreDataManager: NSManagedObject {
class var sharedManager : CoreDataManager {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : CoreDataManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = CoreDataManager()
}
return Static.instance!
}
//var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var contxt:NSManagedObjectContext! = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
init() {
self.contxt = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
}
func start()
{
// self.appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// self.contxt = appDelegate.managedObjectContext
}
func initNewObject(requestType:RequestType)->AnyObject
{
var object:AnyObject!
switch(requestType)
{
case RequestType.VERSION:
let en = NSEntityDescription.entityForName("Version", inManagedObjectContext: self.contxt)
object = en
break;
default:
break;
}
return object
}
func saveData(saveArray savedArray:Array<AnyObject>, requestType:RequestType)
{
switch(requestType)
{
case .VERSION:
self.removeData(.VERSION)
for object in savedArray
{
let en = NSEntityDescription.entityForName("Version", inManagedObjectContext: self.contxt)
var newItem = Version(entity: en!, insertIntoManagedObjectContext: contxt)
newItem.version = (object as PFObject)["version"] as String
newItem.createdAt = (object as PFObject).createdAt
newItem.updatedAt = (object as PFObject).updatedAt
}
break;
case .CATEGORY:
self.removeData(.CATEGORY)
for object in savedArray
{
let en = NSEntityDescription.entityForName("CategoryModel", inManagedObjectContext: self.contxt)
var newItem = CategoryModel(entity: en!, insertIntoManagedObjectContext: contxt)
var object1:PFObject = (object as PFObject)
var icon:PFFile = (object as PFObject)["icon"] as PFFile
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(icon.name)");
var imageData:NSData = icon.getData()
imageData.writeToFile(pngPath, atomically: true)
newItem.id = (object as PFObject).objectId
newItem.name = (object as PFObject)["name"] as? String
newItem.icon = ((object as PFObject)["icon"] as? PFFile)?.url
newItem.createdAt = (object as PFObject).createdAt
newItem.updatedAt = (object as PFObject).updatedAt
}
break;
case .MALL:
self.removeData(.MALL)
for object in savedArray
{
let en = NSEntityDescription.entityForName("MallModel", inManagedObjectContext: self.contxt)
var newItem = MallModel(entity: en!, insertIntoManagedObjectContext: contxt)
var object1:PFObject = (object as PFObject)
newItem.id = (object as PFObject).objectId
newItem.name = (object as PFObject)["name"] as? String
newItem.beacon_id = (object as PFObject)["beacon_id"] as? String
newItem.information = (object as PFObject)["information"] as? String
newItem.location = (object as PFObject)["location"] as? String
newItem.createdAt = (object as PFObject).createdAt
newItem.updatedAt = (object as PFObject).updatedAt
}
break;
case .BANNER:
self.removeData(.BANNER)
for object in savedArray
{
let en = NSEntityDescription.entityForName("BannerModel", inManagedObjectContext: self.contxt)
var newItem = BannerModel(entity: en!, insertIntoManagedObjectContext: contxt)
var object1:PFObject = (object as PFObject)
var icon:PFFile = (object as PFObject)["image"] as PFFile
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(icon.name)");
var imageData:NSData = icon.getData()
imageData.writeToFile(pngPath, atomically: true)
newItem.id = (object as PFObject).objectId
newItem.type_id = (object as PFObject)["type_id"] as? String
newItem.image = ((object as PFObject)["image"] as? PFFile)?.url
newItem.createdAt = (object as PFObject).createdAt
newItem.updatedAt = (object as PFObject).updatedAt
}
break;
case .MALL_BANNER:
self.removeData(.MALL_BANNER)
for object in savedArray
{
let en = NSEntityDescription.entityForName("MallBannerModel", inManagedObjectContext: self.contxt)
var newItem = MallBannerModel(entity: en!, insertIntoManagedObjectContext: contxt)
newItem.id = (object as PFObject).objectId
newItem.mall_id = (object as PFObject)["mall_id"] as? String
newItem.banner_id = (object as PFObject)["banner_id"] as? String
newItem.createdAt = (object as PFObject).createdAt
newItem.updatedAt = (object as PFObject).updatedAt
}
break;
case .STORE:
self.removeData(.STORE)
for object in savedArray
{
let en = NSEntityDescription.entityForName("StoreModel", inManagedObjectContext: self.contxt)
var newItem = StoreModel(entity: en!, insertIntoManagedObjectContext: contxt)
newItem.id = (object as PFObject).objectId
newItem.name = (object as PFObject)["name"] as? String
newItem.details = (object as PFObject)["details"] as? String
newItem.banner_id = (object as PFObject)["banner_id"] as? String
newItem.beacon_id = (object as PFObject)["beacon_id"] as? String
newItem.location = (object as PFObject)["location"] as? String
newItem.category_id = (object as PFObject)["category_id"] as? String
newItem.createdAt = (object as PFObject).createdAt
newItem.updatedAt = (object as PFObject).updatedAt
}
break;
default:
break;
}
contxt.save(nil)
}
func loadData(requestType:RequestType)->Array<AnyObject>
{
var data:Array<AnyObject>? = []
var freq:NSFetchRequest!
switch(requestType)
{
case RequestType.VERSION:
freq = NSFetchRequest(entityName: "Version")
break;
case .CATEGORY:
freq = NSFetchRequest(entityName: "CategoryModel")
break;
case .MALL:
freq = NSFetchRequest(entityName: "MallModel")
break;
case .BANNER:
freq = NSFetchRequest(entityName: "BannerModel")
break;
case .MALL_BANNER:
freq = NSFetchRequest(entityName: "MallBannerModel")
break;
case .STORE:
freq = NSFetchRequest(entityName: "StoreModel")
break;
default:
break;
}
if self.contxt != nil {
data = self.contxt.executeFetchRequest(freq, error: nil)!
}
return data!
}
func loadData(requestType:RequestType, key:String)->Array<AnyObject>
{
var data:Array<AnyObject>? = []
var freq:NSFetchRequest!
switch(requestType)
{
case RequestType.VERSION:
freq = NSFetchRequest(entityName: "Version")
break;
case .CATEGORY:
freq = NSFetchRequest(entityName: "CategoryModel")
break;
case .MALL:
freq = NSFetchRequest(entityName: "MallModel")
break;
case .BANNER:
freq = NSFetchRequest(entityName: "BannerModel")
let predicate = NSPredicate(format: "id == %@", key)
println(predicate)
freq.predicate = predicate
break;
case .MALL_BANNER:
freq = NSFetchRequest(entityName: "MallBannerModel")
let predicate = NSPredicate(format: "mall_id == %@", key)
println(predicate)
freq.predicate = predicate
break;
case .STORE:
freq = NSFetchRequest(entityName: "StoreModel")
let predicate = NSPredicate(format: "category_id == %@", key)
println(predicate)
freq.predicate = predicate
break;
default:
break;
}
if self.contxt != nil {
data = self.contxt.executeFetchRequest(freq, error: nil)!
}
return data!
}
func removeData(requestType:RequestType)
{
var freq:NSFetchRequest!
switch(requestType)
{
case RequestType.VERSION:
freq = NSFetchRequest(entityName: "Version")
var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)!
if(results.count > 0)
{
for object in results {
self.contxt.deleteObject(object as NSManagedObject)
self.contxt.save(nil)
}
}
break;
case .CATEGORY:
freq = NSFetchRequest(entityName: "CategoryModel")
var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)!
if(results.count > 0)
{
for object in results {
self.contxt.deleteObject(object as NSManagedObject)
self.contxt.save(nil)
}
}
break;
case .MALL:
freq = NSFetchRequest(entityName: "MallModel")
var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)!
if(results.count > 0)
{
for object in results {
self.contxt.deleteObject(object as NSManagedObject)
self.contxt.save(nil)
}
}
break;
case .BANNER:
freq = NSFetchRequest(entityName: "BannerModel")
var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)!
if(results.count > 0)
{
for object in results {
self.contxt.deleteObject(object as NSManagedObject)
self.contxt.save(nil)
}
}
break;
case .MALL_BANNER:
freq = NSFetchRequest(entityName: "MallBannerModel")
var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)!
if(results.count > 0)
{
for object in results {
self.contxt.deleteObject(object as NSManagedObject)
self.contxt.save(nil)
}
}
break;
case .STORE:
freq = NSFetchRequest(entityName: "StoreModel")
var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)!
if(results.count > 0)
{
for object in results {
self.contxt.deleteObject(object as NSManagedObject)
self.contxt.save(nil)
}
}
break;
default:
break;
}
}
}
| gpl-2.0 | b420c071e8d67f2f96b4fd2828972465 | 37.903727 | 122 | 0.544105 | 5.614971 | false | false | false | false |
malaonline/iOS | mala-ios/Extension/Extension+UIColor.swift | 1 | 742 | //
// Extension+UIColor.swift
// mala-ios
//
// Created by Elors on 15/12/20.
// Copyright © 2015年 Mala Online. All rights reserved.
//
import UIKit
// MARK: - Convenience
extension UIColor {
/// Convenience Function to Create UIColor With Hex RGBValue
///
/// - parameter rgbHexValue: Hex RGBValue
/// - parameter alpha: Alpha
///
/// - returns: UIColor
convenience init(rgbHexValue: UInt32 = 0xFFFFFF, alpha: Double = 1.0) {
let red = CGFloat((rgbHexValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbHexValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbHexValue & 0xFF)/256.0
self.init(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
}
| mit | d1e7a0fd597cc8b35fcb6e24a25d152e | 27.423077 | 75 | 0.61705 | 3.587379 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Components/Controllers/DefaultNavigationBar.swift | 1 | 3776 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireCommonComponents
class DefaultNavigationBar: UINavigationBar, DynamicTypeCapable {
func redrawFont() {
titleTextAttributes?[.font] = FontSpec.smallSemiboldFont.font!
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
var colorSchemeVariant: ColorSchemeVariant {
return ColorScheme.default.variant
}
func configure() {
tintColor = SemanticColors.Label.textDefault
titleTextAttributes = DefaultNavigationBar.titleTextAttributes(for: colorSchemeVariant)
configureBackground()
let backIndicatorInsets = UIEdgeInsets(top: 0, left: 4, bottom: 2.5, right: 0)
backIndicatorImage = StyleKitIcon.backArrow.makeImage(size: .tiny, color: SemanticColors.Icon.foregroundDefault).with(insets: backIndicatorInsets, backgroundColor: .clear)
backIndicatorTransitionMaskImage = StyleKitIcon.backArrow.makeImage(size: .tiny, color: SemanticColors.Icon.foregroundDefault).with(insets: backIndicatorInsets, backgroundColor: .clear)
}
func configureBackground() {
isTranslucent = false
barTintColor = SemanticColors.View.backgroundDefault
shadowImage = UIImage.singlePixelImage(with: UIColor.clear)
}
static func titleTextAttributes(for variant: ColorSchemeVariant) -> [NSAttributedString.Key: Any] {
return [.font: FontSpec.smallSemiboldFont.font!,
.foregroundColor: SemanticColors.Label.textDefault,
.baselineOffset: 1.0]
}
static func titleTextAttributes(for color: UIColor) -> [NSAttributedString.Key: Any] {
return [.font: FontSpec.smallSemiboldFont.font!,
.foregroundColor: color,
.baselineOffset: 1.0]
}
}
extension UIViewController {
func wrapInNavigationController(navigationControllerClass: UINavigationController.Type = RotationAwareNavigationController.self,
navigationBarClass: AnyClass? = DefaultNavigationBar.self,
setBackgroundColor: Bool = false) -> UINavigationController {
let navigationController = navigationControllerClass.init(navigationBarClass: navigationBarClass, toolbarClass: nil)
navigationController.setViewControllers([self], animated: false)
if #available(iOS 15, *), setBackgroundColor {
navigationController.view.backgroundColor = SemanticColors.View.backgroundDefault
}
return navigationController
}
// MARK: - present
func wrapInNavigationControllerAndPresent(from viewController: UIViewController) -> UINavigationController {
let navigationController = wrapInNavigationController()
navigationController.modalPresentationStyle = .formSheet
viewController.present(navigationController, animated: true)
return navigationController
}
}
| gpl-3.0 | 4de077ee1abac000722284d4fdc5f0aa | 39.170213 | 193 | 0.713453 | 5.402003 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | Sources/EventsTracker/UniqueViewTokenizer.swift | 1 | 2944 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import Foundation
/// The signature of a Tokenize function, for converting a string to a different string.
typealias Tokenizer = (String) -> String
/// A struct for generating a unique view token, based on a salt and a content string.
/// Given the same salt & content, the same viewToken will be generated.
struct UniqueViewTokenizer {
let salt: String
/**
Create a new UniqueViewTokenizer. Will fail if the provided salt is empty.
*/
init?(salt: String) {
guard salt.isEmpty == false else {
return nil
}
self.salt = salt
}
/**
Takes a content string, combines with the Tokenizer's salt, and hashes into a new string.
- parameter content: A string that will be tokenized.
*/
func tokenize(_ content: String) -> String {
let str = salt + content
let data = str.data(using: .utf8, allowLossyConversion: true) ?? Data()
return Data(Array(data.md5()).prefix(8)).base64EncodedString()
}
}
extension UniqueViewTokenizer {
/// The key to access the salt from the dataStore. This is named as such for legacy reasons.
private static let saltKey = "ShopGunSDK.EventsTracker.ClientId"
/**
Loads the ViewTokenizer whose `salt` is cached in the dataStore.
If no salt exist, then creates a new one and saves it to the store.
If no store is provided then a new salt will be generated, but not stored.
- parameter dataStore: An instance of a ShopGunSDKDataStore, from which the salt is read, and into which new salts are written.
*/
static func load(from dataStore: ShopGunSDKDataStore?) -> UniqueViewTokenizer {
let salt: String
if let storedSalt = dataStore?.get(for: self.saltKey), storedSalt.isEmpty == false {
salt = storedSalt
} else {
// Make a new salt
salt = UUID().uuidString
dataStore?.set(value: salt, for: self.saltKey)
}
// we are sure salt is non-empty at this point, so no exceptions.
return UniqueViewTokenizer(salt: salt)!
}
/**
First resets the cached salt in the dataStore, then uses `load(from:)` to create a new one.
- parameter dataStore: An instance of a ShopGunSDKDataStore, from which the salt is read, and into which new salts are written.
*/
static func reload(from dataStore: ShopGunSDKDataStore?) -> UniqueViewTokenizer {
dataStore?.set(value: nil, for: self.saltKey)
return load(from: dataStore)
}
}
| mit | 6fec9966764b2931f4d939ca1c30c770 | 36.835616 | 132 | 0.617668 | 4.349606 | false | false | false | false |
woodcockjosh/FastContact | FastContact/Constant.swift | 1 | 766 | //
// Constant.swift
// FastContact
//
// Created by Josh Woodcock on 8/23/15.
// Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved.
//
import UIKit
public struct FastContactConstant {
public static let IOS_MAIN_VERSION: Double = {
var systemVersion = UIDevice.currentDevice().systemVersion;
var numbers = split(systemVersion) {$0 == "."}
var numStrings = Array<String>();
var i = 0;
for num in numbers {
i++;
if(i <= 2) {
numStrings.append(num);
}else{
break;
}
}
var numString = ".".join(numStrings);
var numNum = (numString as NSString).doubleValue;
return numNum;
}();
}
| mit | a0e8586bafb0280e213fbdd5c6ecb071 | 24.533333 | 70 | 0.54047 | 4.27933 | false | false | false | false |
tsolomko/SWCompression | Sources/swcomp/Archives/LZ4Command.swift | 1 | 3901 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import SWCompression
import SwiftCLI
final class LZ4Command: Command {
let name = "lz4"
let shortDescription = "Creates or extracts a LZ4 archive"
@Flag("-c", "--compress", description: "Compress an input file into a LZ4 archive")
var compress: Bool
@Flag("-d", "--decompress", description: "Decompress a LZ4 archive")
var decompress: Bool
@Flag("--dependent-blocks", description: "(Compression only) Use dependent blocks")
var dependentBlocks: Bool
@Flag("--block-checksums", description: "(Compression only) Save checksums for compressed blocks")
var blockChecksums: Bool
@Flag("--no-content-checksum", description: "(Compression only) Don't save the checksum of the uncompressed data")
var noContentChecksum: Bool
@Flag("--content-size", description: "(Compression only) Save the size of the uncompressed data")
var contentSize: Bool
@Key("--block-size", description: "(Compression only) Use specified block size (in bytes; default and max: 4194304)")
var blockSize: Int?
@Key("-D", "--dict", description: "Path to a dictionary to use in decompression or compression")
var dictionary: String?
@Key("--dictID", description: "Optional dictionary ID (max: 4294967295)")
var dictionaryID: Int?
var optionGroups: [OptionGroup] {
return [.exactlyOne($compress, $decompress)]
}
@Param var input: String
@Param var output: String?
func execute() throws {
let dictID: UInt32?
if let dictionaryID = dictionaryID {
guard dictionaryID <= UInt32.max
else { swcompExit(.lz4BigDictId) }
dictID = UInt32(truncatingIfNeeded: dictionaryID)
} else {
dictID = nil
}
let dictData: Data?
if let dictionary = dictionary {
dictData = try Data(contentsOf: URL(fileURLWithPath: dictionary), options: .mappedIfSafe)
} else {
dictData = nil
}
guard dictID == nil || dictData != nil
else { swcompExit(.lz4NoDict) }
if decompress {
let inputURL = URL(fileURLWithPath: self.input)
let outputURL: URL
if let outputPath = output {
outputURL = URL(fileURLWithPath: outputPath)
} else if inputURL.pathExtension == "lz4" {
outputURL = inputURL.deletingPathExtension()
} else {
swcompExit(.noOutputPath)
}
let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe)
let decompressedData = try LZ4.decompress(data: fileData, dictionary: dictData, dictionaryID: dictID)
try decompressedData.write(to: outputURL)
} else if compress {
let inputURL = URL(fileURLWithPath: self.input)
let outputURL: URL
if let outputPath = output {
outputURL = URL(fileURLWithPath: outputPath)
} else {
outputURL = inputURL.appendingPathExtension("lz4")
}
let bs: Int
if let blockSize = blockSize {
guard blockSize < 4194304
else { swcompExit(.lz4BigBlockSize) }
bs = blockSize
} else {
bs = 4 * 1024 * 1024
}
let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe)
let compressedData = LZ4.compress(data: fileData, independentBlocks: !dependentBlocks,
blockChecksums: blockChecksums, contentChecksum: !noContentChecksum,
contentSize: contentSize, blockSize: bs, dictionary: dictData, dictionaryID: dictID)
try compressedData.write(to: outputURL)
}
}
}
| mit | e68f4b3d74b50d53e34acfcd5815cb5d | 34.144144 | 121 | 0.613945 | 4.994878 | false | false | false | false |
vivekvpandya/GetSwifter | FunChallengeDetailsVC.swift | 2 | 5106 | //
// FunChallengeDetailsVC.swift
// GetSwifter
//
// Created by Vivek Pandya on 9/20/14.
// Copyright (c) 2014 Vivek Pandya. All rights reserved.
//
import UIKit
import Alamofire
class FunChallengeDetailsVC: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var challengeLabel: UILabel!
@IBOutlet weak var regEndDateLabel: UILabel!
@IBOutlet weak var subEndDateLabel: UILabel!
@IBOutlet weak var technologyLabel: UILabel!
@IBOutlet weak var detailsWebView: UIWebView!
@IBOutlet weak var platformLabel: UILabel!
@IBOutlet weak var registerButton: UIButton!
var serviceEndPoint : String = "http://api.topcoder.com/v2/develop/challenges/" // here challenge id will be appended at the end
var challengeID : NSString = "" // This value will be set by prepareForSegue method of RealWorldChallengesTVC
var directURL : NSString = "" // this will be used to open topcoder challenge page in Safari
override func viewDidLoad() {
super.viewDidLoad()
self.registerButton.enabled = false
getChallengeDetails()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getChallengeDetails(){
activityIndicator.startAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
var apiURLString = "\(serviceEndPoint)\(challengeID)"
println(apiURLString)
Alamofire.request(.GET,apiURLString, encoding : .JSON).responseJSON
{ (request,response,JSON,error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if (error == nil){
if response?.statusCode == 200{
self.activityIndicator.stopAnimating()
var challengeDetails : NSDictionary = JSON as NSDictionary
self.directURL = challengeDetails.objectForKey("directUrl") as NSString
println(challengeDetails)
self.challengeLabel.text = challengeDetails.objectForKey("challengeName") as NSString
self.technologyLabel.text = (challengeDetails.objectForKey("technology") as NSArray).componentsJoinedByString(",")
self.platformLabel.text = (challengeDetails.objectForKey("platforms") as NSArray).componentsJoinedByString(",")
self.detailsWebView.loadHTMLString(challengeDetails.objectForKey("detailedRequirements") as NSString, baseURL:nil)
var dateFormater : NSDateFormatter = NSDateFormatter()
dateFormater.dateFormat = "M dd yyyy , hh:mm "
dateFormater.timeZone = NSTimeZone(name:"UTC")
// var regEnd:NSDate = dateFormater.dateFromString( challengeDetails.objectForKey("registrationEndDate") as NSString!)!
// self.regEndDateLabel.text = dateFormater.stringFromDate(regEnd)
self.registerButton.enabled = true
}
else{
self.activityIndicator.stopAnimating()
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
}
}
else{
self.activityIndicator.stopAnimating()
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
}
}
}
/*
// 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.
}
*/
@IBAction func registerForChallenge(sender: AnyObject) {
if self.directURL != ""{
println("in")
var url = NSURL(string: self.directURL)
UIApplication.sharedApplication().openURL(url)
}
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
self.navigationController?.popViewControllerAnimated(true)
}
}
| mit | 1742de904e7ed0a1e12d910e7d0e5922 | 36.822222 | 154 | 0.568351 | 6.319307 | false | false | false | false |
airspeedswift/swift-compiler-crashes | crashes-duplicates/00214-swift-typebase-gettypeofmember.swift | 12 | 2557 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}
{
m) {
n }
}
protocol f {
class func i()
}
class e: f{ class func i {}
func n<j>() -> (j, j -> j) -> j {
var m: ((j> j)!
f m
}
protocol k {
typealias m
}
struct e<j : k> {n: j
let i: j.m
}
l
func f() {
({})
}
protocol f : f {
}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
ol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
}
class d {
func l<j where j: h, j: d>(l: j) {
l.k()
}
func i(k: b) -> <j>(() -> j) -> b {
f { m m "\(k): \(m())" }
}
protocol h
func r<t>() {
f f {
i i
}
}
struct i<o : u> {
o f: o
}
func r<o>() -> [i<o>] {
p []
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
typealias h = n
protocol g {
func i() -> l func o() -> m {
q""
}
}
func j<t k t: g, t: n>(s: t) {
s.i()
}
protocol r {
}
protocol f : r {
}
protocol i : r {
}
j
var x1 =I Bool !(a)
}
func prefix(with: Strin) -> <T>(() -> T) in
// Distributed under the terms of the MIT license
d)
func e(h: b) -> <f>(() -> f) -> b {
return { c):h())" }
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
clas-> i) -> i) {
b {
(h -> i) d $k
}
let e: Int = 1, 1)
class g<j :g
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
)
e
protocol g : e { func e
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
n)
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
o m = j
m()
class m {
func r((Any, m))(j: (Any, AnyObject)) {
r(j)
}
}
func m< f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typ typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
a
}
struct e : f {
i f = g
}
func i<g : g, e : g> : g {
typealias f = h
typealias e = a<c<h>, f>
func b<d {
enum b {
func c
var _ = c
}
}
| mit | f5e7b7d2a330c15b10d6feb2aee9aeda | 12.317708 | 87 | 0.440751 | 2.374188 | false | false | false | false |
liufengting/FTChatMessageDemoProject | FTChatMessage/FTChatMessageHeader/FTChatMessageHeader.swift | 1 | 3018 | //
// FTChatMessageHeader.swift
// FTChatMessage
//
// Created by liufengting on 16/2/28.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
protocol FTChatMessageHeaderDelegate {
func ft_chatMessageHeaderDidTappedOnIcon(_ messageSenderModel : FTChatMessageUserModel)
}
class FTChatMessageHeader: UILabel {
var iconButton : UIButton!
var messageSenderModel : FTChatMessageUserModel!
var headerViewDelegate : FTChatMessageHeaderDelegate?
lazy var messageSenderNameLabel: UILabel! = {
let label = UILabel(frame: CGRect.zero)
label.font = FTDefaultTimeLabelFont
label.textAlignment = .center
label.textColor = UIColor.lightGray
return label
}()
convenience init(frame: CGRect, senderModel: FTChatMessageUserModel ) {
self.init(frame : frame)
messageSenderModel = senderModel;
self.setupHeader( senderModel, isSender: senderModel.isUserSelf)
}
fileprivate func setupHeader(_ user : FTChatMessageUserModel, isSender: Bool){
self.backgroundColor = UIColor.clear
let iconRect = isSender ? CGRect(x: self.frame.width-FTDefaultMargin-FTDefaultIconSize, y: FTDefaultMargin, width: FTDefaultIconSize, height: FTDefaultIconSize) : CGRect(x: FTDefaultMargin, y: FTDefaultMargin, width: FTDefaultIconSize, height: FTDefaultIconSize)
iconButton = UIButton(frame: iconRect)
iconButton.backgroundColor = isSender ? FTDefaultOutgoingColor : FTDefaultIncomingColor
iconButton.layer.cornerRadius = FTDefaultIconSize/2;
iconButton.clipsToBounds = true
iconButton.isUserInteractionEnabled = true
iconButton.addTarget(self, action: #selector(self.iconTapped), for: UIControlEvents.touchUpInside)
self.addSubview(iconButton)
if (user.senderIconUrl != nil) {
// iconButton.kf.setBackgroundImage(with: URL(string : user.senderIconUrl!), for: .normal, placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
}
// var nameLabelRect = CGRect( x: 0, y: 0 , width: FTScreenWidth - (FTDefaultMargin*2 + FTDefaultIconSize), height: FTDefaultSectionHeight)
// var nameLabelTextAlignment : NSTextAlignment = .right
//
// if isSender == false {
// nameLabelRect.origin.x = FTDefaultMargin + FTDefaultIconSize + FTDefaultMargin
// nameLabelTextAlignment = .left
// }
//
// messageSenderNameLabel.frame = nameLabelRect
// messageSenderNameLabel.text = user.senderName
// messageSenderNameLabel.textAlignment = nameLabelTextAlignment
// self.addSubview(messageSenderNameLabel)
}
@objc func iconTapped() {
if (headerViewDelegate != nil) {
headerViewDelegate?.ft_chatMessageHeaderDidTappedOnIcon(messageSenderModel)
}
}
}
| mit | 67610b57ad55c05f189e62ecf5086f3e | 34.05814 | 270 | 0.679602 | 4.942623 | false | false | false | false |
xcadaverx/ABPlayer | Example/Example/ViewController.swift | 1 | 1583 | //
// ViewController.swift
// Example
//
// Copyright © 2016 Dandom. All rights reserved.
//
import UIKit
import ABPlayer
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var abPlayerView: ABPlayerView!
@IBAction func tap(sender: UIButton) {
// let config = ABPlayerConfiguration(sliderViewWidth: 20, labelPadding: 10, sliderViewBackgroundColor: .green, beforeText: "beforez", beforeColor: .purple, afterText: "aftaazz", afterColor: .green)
//
// abPlayerView.set(configuration: config)
abPlayerView.play()
}
override func viewDidLoad() {
super.viewDidLoad()
guard let sampleAPath = Bundle.main.path(forResource: "sampleA", ofType: "mp4") else { return }
guard let sampleBPath = Bundle.main.path(forResource: "sampleB", ofType: "mov") else { return }
let sampleAURL = URL(fileURLWithPath: sampleAPath)
let sampleBURL = URL(fileURLWithPath: sampleBPath)
let playerItemA = AVPlayerItem(url: sampleAURL)
let playerItemB = AVPlayerItem(url: sampleBURL)
abPlayerView.load(playerItemA, playerItemB, usingVolumeFrom: .playerA)
let config = ABPlayerConfiguration(sliderViewWidth: 10, labelPadding: 20, sliderViewBackgroundColor: .blue, beforeText: "befo", beforeColor: .red, afterText: "afta", afterColor: .purple)
abPlayerView.set(configuration: config)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
abPlayerView.play()
}
}
| mit | 9d6088f786835dfd5f0c5afe8f5bbfe4 | 31.285714 | 205 | 0.67952 | 4.275676 | false | true | false | false |
iscriptology/swamp | Example/Pods/CryptoSwift/Sources/CryptoSwift/CSArrayType+Extensions.swift | 2 | 2133 | //
// _ArrayType+Extensions.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/10/15.
// Copyright © 2015 Marcin Krzyzanowski. All rights reserved.
//
public protocol CSArrayType: Collection, RangeReplaceableCollection {
func cs_arrayValue() -> [Iterator.Element]
}
extension Array: CSArrayType {
public func cs_arrayValue() -> [Iterator.Element] {
return self
}
}
public extension CSArrayType where Iterator.Element == UInt8 {
public func toHexString() -> String {
return self.lazy.reduce("") {
var s = String($1, radix: 16)
if s.characters.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
public extension CSArrayType where Iterator.Element == UInt8 {
public func md5() -> [Iterator.Element] {
return Digest.md5(cs_arrayValue())
}
public func sha1() -> [Iterator.Element] {
return Digest.sha1(cs_arrayValue())
}
public func sha224() -> [Iterator.Element] {
return Digest.sha224(cs_arrayValue())
}
public func sha256() -> [Iterator.Element] {
return Digest.sha256(cs_arrayValue())
}
public func sha384() -> [Iterator.Element] {
return Digest.sha384(cs_arrayValue())
}
public func sha512() -> [Iterator.Element] {
return Digest.sha512(cs_arrayValue())
}
public func crc32(seed: UInt32? = nil, reflect : Bool = true) -> UInt32 {
return Checksum.crc32(cs_arrayValue(), seed: seed, reflect: reflect)
}
public func crc16(seed: UInt16? = nil) -> UInt16 {
return Checksum.crc16(cs_arrayValue(), seed: seed)
}
public func encrypt(cipher: Cipher) throws -> [Iterator.Element] {
return try cipher.encrypt(cs_arrayValue())
}
public func decrypt(cipher: Cipher) throws -> [Iterator.Element] {
return try cipher.decrypt(cs_arrayValue())
}
public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Iterator.Element] {
return try authenticator.authenticate(cs_arrayValue())
}
}
| mit | 366e59f5e31892257bedc2fbaa91c6ed | 27.426667 | 100 | 0.609287 | 4.084291 | false | false | false | false |
tinmnguyen/swiftLIFX | SwiftLifx/DetailViewController.swift | 1 | 3776 | //
// DetailViewController.swift
// SwiftLifx
//
// Created by Tin Nguyen on 10/4/14.
// Copyright (c) 2014 Tin Nguyen. All rights reserved.
//
import UIKit
public class DetailViewController: UIViewController, LFXLightObserver {
public var light: LFXLight!
@IBOutlet var brightnessSlider: UISlider!
@IBOutlet var powerButton: UIButton!
@IBOutlet var colorPicker: HRColorMapView!
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
// Do any additional setup after loading the view.
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.updateBrightnessSlider()
if light.powerState() == LFXPowerState.Off {
self.powerButton.setTitle("Power on", forState: .Normal)
}
else {
self.powerButton.setTitle("Power off", forState: .Normal)
}
self.title = light.label()
colorPicker.addTarget(self, action: "colorChanged:" , forControlEvents: UIControlEvents.ValueChanged)
colorPicker.brightness = 1.0
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
light.addLightObserver(self)
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sliderValueDidChange(slider: UISlider) {
self.light.setColor(self.light.color().colorWithBrightness(CGFloat(slider.value)))
if light.powerState() == .Off {
self.light.setPowerState(.On)
self.powerButton.setTitle("Power off", forState: .Normal)
}
}
@IBAction func powerButtonDidPress(button: UIButton) {
if self.light.powerState() == .Off {
self.light.setPowerState(.On)
self.updateBrightnessSlider()
self.powerButton.setTitle("Power off", forState: .Normal)
}
else {
self.light.setPowerState(.Off)
self.powerButton.setTitle("Power on", forState: .Normal)
self.brightnessSlider.setValue(0.0, animated: true)
}
var color = UIColor.blueColor()
var hsv = color.getHSV()
}
func updateBrightnessSlider() {
let color = light.color()
self.brightnessSlider.setValue(Float(color.brightness), animated: true)
self.colorPicker.color = UIColor(hue: color.hue / LFXHSBKColorMaxHue, saturation: color.saturation, brightness: color.brightness, alpha: 1.0)
}
public func light(light: LFXLight!, didChangeReachability reachability: LFXDeviceReachability) {
switch reachability {
case LFXDeviceReachability.Unreachable:
println("disconnected")
case LFXDeviceReachability.Reachable:
println("yo")
default:
println("no")
}
}
func colorChanged(mapView: HRColorMapView) {
var hsv = mapView.color.getHSV()
var hsbk: LFXHSBKColor = light.color()
hsbk.hue = hsv.hue
hsbk.brightness = hsv.value
hsbk.saturation = hsv.saturation
self.light.setColor(hsbk)
}
/*
// 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.
}
*/
}
| mit | c4f443771286a1271ea9e3813ac6ad26 | 30.466667 | 149 | 0.625265 | 4.779747 | false | false | false | false |
zhixingxi/JJA_Swift | JJA_Swift/JJA_Swift/AppDelegate/AppDelegate.swift | 1 | 3863 | //
// AppDelegate.swift
// JJA_Swift
//
// Created by MQL-IT on 2017/5/16.
// Copyright © 2017年 MQL-IT. All rights reserved.
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖镇楼 BUG辟易
// 佛曰:
// 写字楼里写字间,写字间里程序员;
// 程序人员写程序,又拿程序换酒钱。
// 酒醒只在网上坐,酒醉还来网下眠;
// 酒醉酒醒日复日,网上网下年复年。
// 但愿老死电脑间,不愿鞠躬老板前;
// 奔驰宝马贵者趣,公交自行程序员。
// 别人笑我忒疯癫,我笑自己命太贱;
// 不见满街漂亮妹,哪个归得程序员?
import UIKit
import HandyJSON
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = MainTabBarController()
loadAppConfigerInformation()
setupAdditions()
window?.makeKeyAndVisible()
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active 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:.
}
}
| mit | 0eef5ef5b382aeb3b170b62853bcb175 | 42.228916 | 285 | 0.53233 | 4.302158 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Modules/Submit/TextFieldCell.swift | 1 | 4072 | //
// TextFieldTableViewCell.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import DrapierLayout
class TextFieldCell : UITableViewCell {
let textField = UITextField()
let separatorView = UIView()
let insets = UIEdgeInsets(top: 16.0, left: 8.0, bottom: 16.0, right: 0.0)
var separatorHeight: CGFloat = 0.0
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(textField)
contentView.addSubview(separatorView)
textField.keyboardType = .Default
textField.autocapitalizationType = .None
textField.autocorrectionType = .No
textField.spellCheckingType = .No
textField.enablesReturnKeyAutomatically = false
textField.clearButtonMode = .WhileEditing
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView.addSubview(textField)
contentView.addSubview(separatorView)
textField.keyboardType = .Default
textField.autocapitalizationType = .None
textField.autocorrectionType = .No
textField.spellCheckingType = .No
textField.enablesReturnKeyAutomatically = false
textField.clearButtonMode = .WhileEditing
}
deinit {
textField.delegate = nil
textField.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
}
override func prepareForReuse() {
super.prepareForReuse()
textField.delegate = nil
textField.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = generateLayout(contentView.bounds)
textField.frame = layout.textFieldFrame
separatorView.frame = layout.separatorFrame
}
override func sizeThatFits(size: CGSize) -> CGSize {
let layout = generateLayout(size.rect())
let fitSize = CGSizeMake(size.width, layout.separatorFrame.bottom)
return fitSize
}
private struct ViewLayout {
let textFieldFrame: CGRect
let separatorFrame: CGRect
}
private func generateLayout(bounds: CGRect) -> ViewLayout {
let textFieldFrame = textField.layout(
Leading(equalTo: bounds.leading(insets)),
Trailing(equalTo: bounds.trailing(insets)),
Top(equalTo: bounds.top(insets))
)
let separatorFrame = separatorView.layout(
Leading(equalTo: bounds.leading(insets)),
Trailing(equalTo: bounds.trailing),
Bottom(equalTo: textFieldFrame.bottom + insets.bottom),
Height(equalTo: separatorHeight)
)
return ViewLayout(
textFieldFrame: textFieldFrame,
separatorFrame: separatorFrame
)
}
}
| mit | 2ba6d7b2ecb9c9cb6601d86f968f2fbe | 35.684685 | 80 | 0.680992 | 5.213828 | false | false | false | false |
thisjeremiah/all-ashore | AllAshore/AppDelegate.swift | 1 | 6224 | //
// AppDelegate.swift
// AllAshore
//
// Created by Jeremiah Montoya on 4/24/15.
// Copyright (c) 2015 Jeremiah Montoya. All rights reserved.
//
import UIKit
import CoreData
// declare globals
var taxonomy : [String: [String:[String]]] = Taxonomy().model
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "me.jeremiahmontoya.AllAshore" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("AllAshore", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AllAshore.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | edd27b2cc6ead1e60127c8e02a4f3321 | 54.079646 | 290 | 0.715938 | 5.66333 | false | false | false | false |
artemkalinovsky/JSQCoreDataKit | JSQCoreDataKit/JSQCoreDataKit/CoreDataExtensions.swift | 1 | 6098 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://www.jessesquires.com/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright (c) 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import CoreData
/// A tuple value that describes the results of saving a managed object context.
///
/// :param: success A boolean value indicating whether the save succeeded. It is `true` if successful, otherwise `false`.
/// :param: error An error object if an error occurred, otherwise `nil`.
public typealias ContextSaveResult = (success:Bool, error:NSError?)
/// Attempts to commit unsaved changes to registered objects to the specified context's parent store.
/// This method is performed *synchronously* in a block on the context's queue.
/// If the context returns `false` from `hasChanges`, this function returns immediately.
///
/// :param: context The managed object context to save.
///
/// :returns: A `ContextSaveResult` instance indicating the result from saving the context.
public func saveContextAndWait(context: NSManagedObjectContext) -> ContextSaveResult {
if !context.hasChanges {
return (true, nil)
}
var success = false
var error: NSError?
context.performBlockAndWait {
() -> Void in
success = context.save(&error)
if !success {
println("*** ERROR: [\(__LINE__)] \(__FUNCTION__) Could not save managed object context: \(error)")
}
}
return (success, error)
}
/// Attempts to commit unsaved changes to registered objects to the specified context's parent store.
/// This method is performed *asynchronously* in a block on the context's queue.
/// If the context returns `false` from `hasChanges`, this function returns immediately.
///
/// :param: context The managed object context to save.
/// :param: completion The closure to be executed when the save operation completes.
public func saveContext(context: NSManagedObjectContext, completion: (ContextSaveResult) -> Void) {
if !context.hasChanges {
completion((true, nil))
return
}
context.performBlock {
() -> Void in
var error: NSError?
let success = context.save(&error)
if !success {
println("*** ERROR: [\(__LINE__)] \(__FUNCTION__) Could not save managed object context: \(error)")
}
completion((success, error))
}
}
/// Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator.
///
/// :param: name The name of an entity.
/// :param: context The managed object context to use.
///
/// :returns: The entity with the specified name from the managed object model associated with context’s persistent store coordinator.
public func entity(#name: String, #context: NSManagedObjectContext) -> NSEntityDescription {
return NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
}
/// An instance of `FetchRequest <T: NSManagedObject>` describes search criteria used to retrieve data from a persistent store.
/// This is a subclass of `NSFetchRequest` that adds a type parameter specifying the type of managed objects for the fetch request.
/// The type parameter acts as a phantom type.
public class FetchRequest<T:NSManagedObject>: NSFetchRequest {
/// Constructs a new `FetchRequest` instance.
///
/// :param: entity The entity description for the entities that this request fetches.
///
/// :returns: A new `FetchRequest` instance.
public init(entity: NSEntityDescription) {
super.init()
self.entity = entity
}
}
/// A `FetchResult` represents the result of executing a fetch request.
/// It has one type parameter that specifies the type of managed objects that were fetched.
public struct FetchResult<T:NSManagedObject> {
/// Specifies whether or not the fetch succeeded.
public let success: Bool
/// An array of objects that meet the criteria specified by the fetch request.
/// If the fetch is unsuccessful, this array will be empty.
public let objects: [T]
/// If unsuccessful, specifies an error that describes the problem executing the fetch. Otherwise, this value is `nil`.
public let error: NSError?
}
/// Executes the fetch request in the given context and returns the result.
///
/// :param: request A fetch request that specifies the search criteria for the fetch.
/// :param: context The managed object context in which to search.
///
/// :returns: A instance of `FetchResult` describing the results of executing the request.
public func fetch<T:NSManagedObject>(#request: FetchRequest<T>, inContext context: NSManagedObjectContext) -> FetchResult<T> {
var error: NSError?
var results: [AnyObject]?
context.performBlockAndWait {
() -> Void in
results = context.executeFetchRequest(request, error: &error)
}
if let results = results {
return FetchResult(success: true, objects: map(results, { $0 as! T }), error: error)
} else {
println("*** ERROR: [\(__LINE__)] \(__FUNCTION__) Error while executing fetch request: \(error)")
}
return FetchResult(success: false, objects: [], error: error)
}
/// Deletes the objects from the specified context.
/// When changes are committed, the objects will be removed from their persistent store.
/// You must save the context after calling this function to remove objects from the store.
///
/// :param: objects The managed objects to be deleted.
/// :param: context The context to which the objects belong.
public func deleteObjects<T:NSManagedObject>(objects: [T], inContext context: NSManagedObjectContext) {
if objects.count == 0 {
return
}
context.performBlockAndWait {
() -> Void in
for each in objects {
context.deleteObject(each)
}
}
}
| mit | 6842fadf8adcd33c1ecbf99d011a83f2 | 34.225434 | 162 | 0.690679 | 4.534226 | false | false | false | false |
fl0549/UberManagerSwift | Pod/Classes/Models/Payment.swift | 1 | 1058 | //
// Payment.swift
// UberManagerSwift
//
// Created by Florian Pygmalion on 25/02/2016.
// Copyright © 2016 Florian Pygmalion. All rights reserved.
//
import UIKit
import SwiftyJSON
public class Payment {
public var description = ""
public var payment_method_id = ""
public var type = ""
}
extension Payment {
private func fillWithDict(hash: JSON) {
if hash["description"].object as? String != nil {
description = hash["description"].stringValue
}
if hash["payment_method_id"].object as? String != nil {
payment_method_id = hash["payment_method_id"].stringValue
}
if hash["type"].object as? String != nil {
type = hash["type"].stringValue
}
}
class func createPaymentFromJSON(hash: JSON) -> Payment? {
if hash.type == .Dictionary {
let payment = Payment()
payment.fillWithDict(hash)
return payment
}
return nil
}
}
| mit | 6bf14014b48f9f632fa682f86f9ccc00 | 21.489362 | 69 | 0.557237 | 4.422594 | false | false | false | false |
kzaher/RxFeedback | Examples/Examples/Todo.swift | 1 | 2736 | //
// Todo.swift
// RxFeedback
//
// Created by Krunoslav Zaher on 5/11/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.UUID
import struct Foundation.Date
enum SyncState {
case syncing
case success
case failed(Error)
}
struct Task {
let id: UUID
let created: Date
var title: String
var isCompleted: Bool
var isArchived: Bool // we never delete anything ;)
var state: SyncState
static func create(title: String, date: Date) -> Task {
return Task(id: UUID(), created: date, title: title, isCompleted: false, isArchived: false, state: .syncing)
}
}
struct Todo {
enum Event {
case created(Version<Task>)
case toggleCompleted(Version<Task>)
case archive(Version<Task>)
case synchronizationChanged(Version<Task>, SyncState)
case toggleEditingMode
}
var tasks: Storage<Version<Task>> = Storage()
var isEditing: Bool = false
}
extension Todo {
static func reduce(state: Todo, event: Event) -> Todo {
switch event {
case .created(let task):
return state.map(task: task, transform: Version<Task>.mutate { _ in })
case .toggleCompleted(let task):
return state.map(task: task, transform: Version<Task>.mutate { $0.isCompleted = !$0.isCompleted })
case .archive(let task):
return state.map(task: task, transform: Version<Task>.mutate { $0.isArchived = true })
case .synchronizationChanged(let task, let synchronizationState):
return state.map(task: task, transform: Version<Task>.mutate { $0.state = synchronizationState })
case .toggleEditingMode:
return state.map { $0.isEditing = !$0.isEditing }
}
}
}
extension Todo {
static func `for`(tasks: [Task]) -> Todo {
return tasks.reduce(Todo()) { (all, task) in
Todo.reduce(state: all, event: .created(Version(task)))
}
}
}
// queries
extension Todo {
var tasksByDate: [Version<Task>] {
return self.tasks
.sorted(key: { $0.value.created })
}
var completedTasks: [Version<Task>] {
return tasksByDate
.filter { $0.value.isCompleted && !$0.value.isArchived }
}
var unfinishedTasks: [Version<Task>] {
return tasksByDate
.filter { !$0.value.isCompleted && !$0.value.isArchived }
}
var tasksToSynchronize: Set<Version<Task>> {
return Set(self.tasksByDate.filter { $0.value.needsSynchronization }.prefix(1))
}
}
extension Task {
var needsSynchronization: Bool {
if case .syncing = self.state {
return true
}
return false
}
}
| mit | 854491081221f1ce2e377cd1e90c7dfa | 26.35 | 116 | 0.616088 | 4.063893 | false | false | false | false |
AlexLittlejohn/ALCameraViewController | ALCameraViewController/Utilities/Utilities.swift | 1 | 4214 | //
// ALUtilities.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/25.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import AVFoundation
internal func radians(_ degrees: CGFloat) -> CGFloat {
return degrees / 180 * .pi
}
internal func localizedString(_ key: String) -> String {
var bundle: Bundle {
if Bundle.main.path(forResource: CameraGlobals.shared.stringsTable, ofType: "strings") != nil {
return Bundle.main
}
return CameraGlobals.shared.bundle
}
return NSLocalizedString(key, tableName: CameraGlobals.shared.stringsTable, bundle: bundle, comment: key)
}
internal func currentRotation(_ oldOrientation: UIInterfaceOrientation, newOrientation: UIInterfaceOrientation) -> CGFloat {
switch oldOrientation {
case .portrait:
switch newOrientation {
case .landscapeLeft: return 90
case .landscapeRight: return -90
case .portraitUpsideDown: return 180
default: return 0
}
case .landscapeLeft:
switch newOrientation {
case .portrait: return -90
case .landscapeRight: return 180
case .portraitUpsideDown: return 90
default: return 0
}
case .landscapeRight:
switch newOrientation {
case .portrait: return 90
case .landscapeLeft: return 180
case .portraitUpsideDown: return -90
default: return 0
}
default: return 0
}
}
internal func largestPhotoSize() -> CGSize {
let scale = UIScreen.main.scale
let screenSize = UIScreen.main.bounds.size
let size = CGSize(width: screenSize.width * scale, height: screenSize.height * scale)
return size
}
internal func errorWithKey(_ key: String, domain: String) -> NSError {
let errorString = localizedString(key)
let errorInfo = [NSLocalizedDescriptionKey: errorString]
let error = NSError(domain: domain, code: 0, userInfo: errorInfo)
return error
}
internal func normalizedRect(_ rect: CGRect, orientation: UIImage.Orientation) -> CGRect {
let normalizedX = rect.origin.x
let normalizedY = rect.origin.y
let normalizedWidth = rect.width
let normalizedHeight = rect.height
var normalizedRect: CGRect
switch orientation {
case .up, .upMirrored:
normalizedRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight)
case .down, .downMirrored:
normalizedRect = CGRect(x: 1-normalizedX-normalizedWidth, y: 1-normalizedY-normalizedHeight, width: normalizedWidth, height: normalizedHeight)
case .left, .leftMirrored:
normalizedRect = CGRect(x: 1-normalizedY-normalizedHeight, y: normalizedX, width: normalizedHeight, height: normalizedWidth)
case .right, .rightMirrored:
normalizedRect = CGRect(x: normalizedY, y: 1-normalizedX-normalizedWidth, width: normalizedHeight, height: normalizedWidth)
@unknown default:
normalizedRect = .zero
}
return normalizedRect
}
internal func flashImage(_ mode: AVCaptureDevice.FlashMode) -> String {
let image: String
switch mode {
case .auto:
image = "flashAutoIcon"
case .on:
image = "flashOnIcon"
case .off:
image = "flashOffIcon"
@unknown default:
image = "flashOffIcon"
}
return image
}
struct ScreenSize {
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceConfig {
static let SCREEN_MULTIPLIER : CGFloat = {
if UIDevice.current.userInterfaceIdiom == .phone {
switch ScreenSize.SCREEN_MAX_LENGTH {
case 568.0: return 1.5
case 667.0: return 2.0
case 736.0: return 4.0
default: return 1.0
}
} else {
return 1.0
}
}()
}
| mit | a92d79bacf0229cbead764b8db805ed1 | 31.415385 | 150 | 0.634314 | 4.766968 | false | false | false | false |
werner-freytag/DockTime | ClockBundle-Subway/ClockView.swift | 1 | 3240 | // The MIT License
//
// Copyright 2012-2021 Werner Freytag
//
// 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 AppKit
class ClockView: NSView {
lazy var bundle = Bundle(for: type(of: self))
let defaults = UserDefaults.shared
override func draw(_: NSRect) {
let components = Calendar.current.dateComponents([.hour, .minute, .second], from: Date())
var imageName: String
var image: NSImage
image = bundle.image(named: "Background")!
image.draw(at: .init(x: 9, y: 8), from: .zero, operation: .copy, fraction: 1)
imageName = String(format: "%ld", components.hour! / 10)
image = bundle.image(named: imageName)!
image.draw(at: CGPoint(x: 28, y: 50), from: .zero, operation: .sourceOver, fraction: 1)
imageName = String(format: "%ld", components.hour! % 10)
image = bundle.image(named: imageName)!
image.draw(at: CGPoint(x: 45, y: 50), from: .zero, operation: .sourceOver, fraction: 1)
imageName = String(format: "%ld", components.minute! / 10)
image = bundle.image(named: imageName)!
image.draw(at: CGPoint(x: 67, y: 50), from: .zero, operation: .sourceOver, fraction: 1)
imageName = String(format: "%ld", components.minute! % 10)
image = bundle.image(named: imageName)!
image.draw(at: CGPoint(x: 84, y: 50), from: .zero, operation: .sourceOver, fraction: 1)
if defaults.showSeconds {
image = bundle.image(named: "Dot")!
let center = CGPoint(x: 62.5, y: 62.5)
for i in 0 ... components.second! {
let angle = CGFloat(i) * .pi * 2 / 60
image.draw(at: center.applying(angle: angle, distance: 42), from: .zero, operation: .sourceOver, fraction: 1)
if i % 5 == 0 {
image.draw(at: center.applying(angle: angle, distance: 46), from: .zero, operation: .sourceOver, fraction: 1)
}
}
}
}
}
extension CGPoint {
func applying(angle: CGFloat, distance: CGFloat) -> CGPoint {
let x = sin(angle) * distance
let y = cos(angle) * distance
return applying(.init(translationX: x, y: y))
}
}
| mit | d518adec96d41c33fe43218a453d01d8 | 42.783784 | 129 | 0.647531 | 4.024845 | false | false | false | false |
schluchter/berlin-transport | berlin-transport/berlin-trnsprtTests/BTConReqBuilderTests.swift | 1 | 1077 | import Quick
import Nimble
import berlin_trnsprt
class BTConReqBuilderTests: QuickSpec {
override func spec() {
describe("The date and time printer") {
context("when given my birthday") {
let comps = NSDateComponents()
let calendar = NSCalendar.currentCalendar()
comps.year = 1980
comps.month = 1
comps.day = 1
comps.hour = 11
comps.minute = 15
comps.second = 30
let date = calendar.dateFromComponents(comps)
println(date)
let output = BTRequestBuilder.requestDataFromDate(date!)
// it("should print the correct date string") {
// expect(output.day).to(equal("19800101"))
// }
//
// it("should print the correct time string") {
// expect(output.time).to(equal("11:15:30"))
// }
}
}
}
}
| mit | fba07e13599c8ecc6d1136ab3e6653b2 | 30.676471 | 72 | 0.463324 | 5.177885 | false | false | false | false |
siuying/SignalKit | SignalKit/Utilities/IncrementalKeyGenerator.swift | 1 | 1193 | //
// IncrementalKeyGenerator.swift
// SignalKit
//
// Created by Yanko Dimitrov on 7/15/15.
// Copyright (c) 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
/**
Generates an incremental unique sequence of tokens based on the
number of generated tokens and a step limit.
For example a generator with step limit of <3> will produce
the following sequence of tokens:
["1", "2", "3", "31", "32", "33", "331"...].
*/
internal struct IncrementalKeyGenerator: TokenGeneratorType {
private let stepLimit: UInt16
private var counter: UInt16 = 0
private var tokenPrefix = ""
private var token: Token {
return tokenPrefix + String(counter)
}
init(stepLimit: UInt16) {
assert(stepLimit > 0, "Step limit should be greather than zero")
self.stepLimit = stepLimit
}
init() {
self.init(stepLimit: UInt16.max)
}
mutating func nextToken() -> Token {
if counter >= stepLimit {
tokenPrefix += String(stepLimit)
counter = 0
}
counter += 1
return token
}
}
| mit | d0c3db260e4d5cda87ad44f4cbc7825c | 21.942308 | 72 | 0.582565 | 4.484962 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Dates/ISO8601DateFormatter.swift | 2 | 2082 | //
// ISO8601DateFormatter.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Converts date and time textual representations within the ISO8601
/// date specification into `Date` objects
class ISO8601DateFormatter: DateFormatter {
let dateFormats = [
"yyyy-mm-dd'T'hh:mm",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ",
"yyyy-MM-dd'T'HH:mmSSZZZZZ"
]
override init() {
super.init()
self.timeZone = TimeZone(secondsFromGMT: 0)
self.locale = Locale(identifier: "en_US_POSIX")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func date(from string: String) -> Date? {
for dateFormat in self.dateFormats {
self.dateFormat = dateFormat
if let date = super.date(from: string) {
return date
}
}
return nil
}
}
| mit | 25dee231f5ac6ca3bac4b3783468b041 | 34.896552 | 82 | 0.673391 | 4.206061 | false | false | false | false |
tonyarnold/Differ | Sources/Differ/ExtendedDiff.swift | 1 | 7629 | /// A sequence of deletions, insertions, and moves where deletions point to locations in the source and insertions point to locations in the output.
/// Examples:
/// ```
/// "12" -> "": D(0)D(1)
/// "" -> "12": I(0)I(1)
/// ```
/// - SeeAlso: Diff
public struct ExtendedDiff: DiffProtocol {
public typealias Index = Int
public enum Element {
case insert(at: Int)
case delete(at: Int)
case move(from: Int, to: Int)
}
/// Returns the position immediately after the given index.
///
/// - Parameters:
/// - i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i + 1
}
/// Diff used to compute an instance
public let source: Diff
/// An array which holds indices of diff elements in the source diff (i.e. diff without moves).
let sourceIndex: [Int]
/// An array which holds indices of diff elements in a diff where move's subelements (deletion and insertion) are ordered accordingly
let reorderedIndex: [Int]
/// An array of particular diff operations
public let elements: [ExtendedDiff.Element]
let moveIndices: Set<Int>
}
extension ExtendedDiff.Element {
init(_ diffElement: Diff.Element) {
switch diffElement {
case let .delete(at):
self = .delete(at: at)
case let .insert(at):
self = .insert(at: at)
}
}
}
public extension Collection {
/// Creates an extended diff between the callee and `other` collection
///
/// - Complexity: O((N+M)*D). There's additional cost of O(D^2) to compute the moves.
///
/// - Parameters:
/// - other: a collection to compare the callee to
/// - isEqual: instance comparator closure
/// - Returns: ExtendedDiff between the callee and `other` collection
func extendedDiff(_ other: Self, isEqual: EqualityChecker<Self>) -> ExtendedDiff {
return extendedDiff(from: diff(other, isEqual: isEqual), other: other, isEqual: isEqual)
}
/// Creates an extended diff between the callee and `other` collection
///
/// - Complexity: O(D^2). where D is number of elements in diff.
///
/// - Parameters:
/// - diff: source diff
/// - other: a collection to compare the callee to
/// - isEqual: instance comparator closure
/// - Returns: ExtendedDiff between the callee and `other` collection
func extendedDiff(from diff: Diff, other: Self, isEqual: EqualityChecker<Self>) -> ExtendedDiff {
var elements: [ExtendedDiff.Element] = []
var moveOriginIndices = Set<Int>()
var moveTargetIndices = Set<Int>()
// It maps indices after reordering (e.g. bringing move origin and target next to each other in the output) to their positions in the source Diff
var sourceIndex = [Int]()
// Complexity O(d^2) where d is the length of the diff
/*
* 1. Iterate all objects
* 2. For every iteration find the next matching element
a) if it's not found insert the element as is to the output array
b) if it's found calculate move as in 3
* 3. Calculating the move.
We call the first element a *candidate* and the second element a *match*
1. The position of the candidate never changes
2. The position of the match is equal to its initial position + m where m is equal to -d + i where d = deletions between candidate and match and i = insertions between candidate and match
* 4. Remove the candidate and match and insert the move in the place of the candidate
*
*/
for candidateIndex in diff.indices {
if !moveTargetIndices.contains(candidateIndex) && !moveOriginIndices.contains(candidateIndex) {
let candidate = diff[candidateIndex]
let match = firstMatch(diff, dirtyIndices: moveTargetIndices.union(moveOriginIndices), candidate: candidate, candidateIndex: candidateIndex, other: other, isEqual: isEqual)
if let match = match {
switch match.0 {
case let .move(from, _):
if from == candidate.at() {
sourceIndex.append(candidateIndex)
sourceIndex.append(match.1)
moveOriginIndices.insert(candidateIndex)
moveTargetIndices.insert(match.1)
} else {
sourceIndex.append(match.1)
sourceIndex.append(candidateIndex)
moveOriginIndices.insert(match.1)
moveTargetIndices.insert(candidateIndex)
}
default: fatalError()
}
elements.append(match.0)
} else {
sourceIndex.append(candidateIndex)
elements.append(ExtendedDiff.Element(candidate))
}
}
}
let reorderedIndices = flip(array: sourceIndex)
return ExtendedDiff(
source: diff,
sourceIndex: sourceIndex,
reorderedIndex: reorderedIndices,
elements: elements,
moveIndices: moveOriginIndices
)
}
func firstMatch(
_ diff: Diff,
dirtyIndices: Set<Diff.Index>,
candidate: Diff.Element,
candidateIndex: Diff.Index,
other: Self,
isEqual: EqualityChecker<Self>
) -> (ExtendedDiff.Element, Diff.Index)? {
for matchIndex in (candidateIndex + 1) ..< diff.endIndex {
if !dirtyIndices.contains(matchIndex) {
let match = diff[matchIndex]
if let move = createMatch(candidate, match: match, other: other, isEqual: isEqual) {
return (move, matchIndex)
}
}
}
return nil
}
func createMatch(_ candidate: Diff.Element, match: Diff.Element, other: Self, isEqual: EqualityChecker<Self>) -> ExtendedDiff.Element? {
switch (candidate, match) {
case (.delete, .insert):
if isEqual(itemOnStartIndex(advancedBy: candidate.at()), other.itemOnStartIndex(advancedBy: match.at())) {
return .move(from: candidate.at(), to: match.at())
}
case (.insert, .delete):
if isEqual(itemOnStartIndex(advancedBy: match.at()), other.itemOnStartIndex(advancedBy: candidate.at())) {
return .move(from: match.at(), to: candidate.at())
}
default: return nil
}
return nil
}
}
public extension Collection where Element: Equatable {
/// - SeeAlso: `extendedDiff(_:isEqual:)`
func extendedDiff(_ other: Self) -> ExtendedDiff {
return extendedDiff(other, isEqual: { $0 == $1 })
}
}
extension Collection {
func itemOnStartIndex(advancedBy n: Int) -> Element {
return self[self.index(startIndex, offsetBy: n)]
}
}
func flip(array: [Int]) -> [Int] {
return zip(array, array.indices)
.sorted { $0.0 < $1.0 }
.map { $0.1 }
}
extension ExtendedDiff.Element: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .delete(at):
return "D(\(at))"
case let .insert(at):
return "I(\(at))"
case let .move(from, to):
return "M(\(from),\(to))"
}
}
}
| mit | 5a51f460d3449e3ecdf9412341221701 | 36.767327 | 196 | 0.585005 | 4.686118 | false | false | false | false |
tkremenek/swift | validation-test/compiler_crashers_2_fixed/0151-rdar-39040593.swift | 39 | 457 | // RUN: %target-typecheck-verify-swift
class A {
func foo() {
class B {
let question: String = "ultimate question"
let answer: Int? = 42
lazy var bar: () -> String = { [weak self] in
guard let self = self else {
return "Unknown"
}
if let answer = self.answer {
return "\(self.question) = \(answer)"
} else {
return "<\(self.question) />"
}
}
}
}
}
| apache-2.0 | dbe9ef51fae146d47a03ad75589526a6 | 19.772727 | 51 | 0.483589 | 3.939655 | false | false | false | false |
mrr1vfe/FBLA | customCellTableViewCell.swift | 1 | 2010 | //
// customCellTableViewCell.swift
// FBLA
//
// Created by Yi Chen on 15/11/8.
// Copyright © 2015年 Yi Chen. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class customCellTableViewCell: UITableViewCell {
@IBOutlet weak var userAvatar: PFImageView!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var createdAt: UILabel!
@IBOutlet weak var composedImage: PFImageView!
@IBOutlet weak var composedMessage: UILabel!
@IBOutlet weak var topBarView: UIView!
@IBOutlet weak var thumbIcon: UIImageView!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var likeLabel: UILabel!
var parseObject:PFObject?
override func awakeFromNib() {
super.awakeFromNib()
thumbIcon.hidden = true
userAvatar.layer.cornerRadius = userAvatar.frame.width/2
userAvatar.layer.masksToBounds = true
// Initialization code
}
@IBAction func clickLike(sender: AnyObject) {
if(parseObject != nil) {
self.thumbIcon?.alpha = 0
if var votes:Int? = parseObject!.objectForKey("Likes") as? Int {
votes!++
parseObject!.setObject(votes!, forKey: "Likes");
parseObject!.saveInBackground();
likeLabel?.text = "\(votes!) ♥️";
}
}
thumbIcon?.hidden = false
thumbIcon?.alpha = 1.0
UIView.animateWithDuration(1, delay: 0.5, options:[], animations: {
self.thumbIcon?.alpha = 0
}, completion: {
(value:Bool) in
self.thumbIcon?.hidden = true
})
}
@IBAction func clickComment(sender: AnyObject) {
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | e71d09311a02ce06b7cbafefa3c846d0 | 24.0375 | 76 | 0.581628 | 4.897311 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/registration/RegistrationInfo.swift | 1 | 1269 | //
// RegistrationInfo.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 09/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
public struct RegistrationInfo: Codable
{
let name: String
let expirationDate: Date
let trial: Bool
let registered: Bool
// public init?(jSON: JSON_Object) {
//
// //{"Name":"TV","ExpirationDate":"2015-11-15","IsTrial":true,"IsRegistered":false}
//
// if let name = jSON["Name"] as? String,
// let expirationString = jSON["ExpirationDate"] as? String,
// let trial = jSON["IsTrial"] as? Bool,
// let registered = jSON["IsRegistered"] as? Bool
// {
// self.name = name
// self.trial = trial
// self.registered = registered
//
// let formatter = DateFormatter()
// formatter.dateFormat = "yyyy-MM-dd"
// self.expirationDate = formatter.date(from: expirationString)! as NSDate
// }
// else {
// return nil
// }
// }
enum CodingKeys: String, CodingKey
{
case name = "Name"
case expirationDate = "ExpirationDate"
case trial = "Trial"
case registered = "Registered"
}
}
| mit | f966a7b442e4b0f4b84fcc7a10844f25 | 25.416667 | 91 | 0.559937 | 4 | false | false | false | false |
mariopavlovic/advent-of-code | 2015/advent-of-codeTests/Day7Specs.swift | 1 | 6420 | import Quick
import Nimble
@testable import advent_of_code
class Day7Specs: QuickSpec {
override func spec() {
var sut: Day7!
beforeEach {
sut = Day7()
}
describe("Given Day7 task") {
describe("when transfering input to instructions (domain)", {
it("should read from file", closure: {
let results = sut.readInput("day7")
expect(results.count).to(equal(339))
if let first = results.first,
let last = results.last {
expect(first).to(equal("lf AND lq -> ls"))
expect(last).to(equal("he RSHIFT 5 -> hh"))
}
})
it("should map input to instructions", closure: {
let input = ["123 -> x", "x AND y -> d", "x OR y -> e", "x LSHIFT 2 -> f", "y RSHIFT 2 -> g", "NOT x -> h"]
let result = sut.parseInstructions(input: input)
expect(result.count).to(equal(6))
let first = result.first!
expect(first.leftWire).to(equal("123"))
expect(first.outputWire).to(equal("x"))
let last = result.last!
expect(last.rightWire).to(equal("x"))
expect(last.outputWire).to(equal("h"))
})
})
describe("when running single operation systems", {
it("should work correctly on direct value", closure: {
var instruction = Day7.Instruction()
instruction.leftWire = "3"
instruction.operation = .AND
instruction.rightWire = "3"
instruction.outputWire = "x"
let result = sut.outputValue(onWire: "x", model: [instruction])
expect(result).to(equal(3))
})
it("should work correctly on AND operation", closure: {
var instruction = Day7.Instruction()
instruction.leftWire = "123"
instruction.operation = .AND
instruction.rightWire = "456"
instruction.outputWire = "x"
let result = sut.outputValue(onWire: "x", model: [instruction])
expect(result).to(equal(72))
})
it("should work correctly on OR operation", closure: {
var instruction = Day7.Instruction()
instruction.leftWire = "123"
instruction.operation = .OR
instruction.rightWire = "456"
instruction.outputWire = "x"
let result = sut.outputValue(onWire: "x", model: [instruction])
expect(result).to(equal(507))
})
it("should work correctly on LSHIFT operation", closure: {
var instruction = Day7.Instruction()
instruction.leftWire = "123"
instruction.operation = .LSHIFT
instruction.rightWire = "2"
instruction.outputWire = "x"
let result = sut.outputValue(onWire: "x", model: [instruction])
expect(result).to(equal(492))
})
it("should work correctly on RSHIFT operation", closure: {
var instruction = Day7.Instruction()
instruction.leftWire = "456"
instruction.operation = .RSHIFT
instruction.rightWire = "2"
instruction.outputWire = "x"
let result = sut.outputValue(onWire: "x", model: [instruction])
expect(result).to(equal(114))
})
it("should work correctly on NOT operation", closure: {
var instruction = Day7.Instruction()
instruction.operation = .NOT
instruction.rightWire = "123"
instruction.outputWire = "x"
let result = sut.outputValue(onWire: "x", model: [instruction])
expect(result).to(equal(65412))
})
})
describe("when running the circuit", {
it("should give wire output value for desired wire", closure: {
let input = ["123 -> x", "456 -> y", "x AND y -> d", "x OR y -> e", "x LSHIFT 2 -> f", "y RSHIFT 2 -> g", "NOT x -> h", "NOT y -> i"]
let d = sut.outputSignal(onWire: "d", input: input)
let e = sut.outputSignal(onWire: "e", input: input)
let f = sut.outputSignal(onWire: "f", input: input)
let g = sut.outputSignal(onWire: "g", input: input)
let h = sut.outputSignal(onWire: "h", input: input)
let i = sut.outputSignal(onWire: "i", input: input)
let x = sut.outputSignal(onWire: "x", input: input)
let y = sut.outputSignal(onWire: "y", input: input)
expect(d).to(equal(72))
expect(e).to(equal(507))
expect(f).to(equal(492))
expect(g).to(equal(114))
expect(h).to(equal(65412))
expect(i).to(equal(65079))
expect(x).to(equal(123))
expect(y).to(equal(456))
})
it("should find a solution for day 7 tasks - part 1", closure: {
let result = sut.runCircut(resultOnWire: "a", filePath: "day7")
expect(result).to(equal(16076))
})
it("should find a solution for day 7 tasks - part 2", closure: {
let result = sut.runCircut(resultOnWire: "a", filePath: "day7-part2")
expect(result).to(equal(2797))
})
})
}
}
}
| mit | f4b9fbf79051a85775ca44e531b55a57 | 43.583333 | 153 | 0.442679 | 5.115538 | false | false | false | false |
GYLibrary/A_Y_T | GYVideo/GYVideo/VideoPlayer/MediaManager.swift | 1 | 2456 | //
// MediaManager.swift
// EZPlayerExample
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import UIKit
import EZPlayer
class MediaManager {
var player: EZPlayer?
var mediaItem: MediaItem?
var embeddedContentView: UIView?
static let sharedInstance = MediaManager()
private init(){
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.EZPlayerPlaybackDidFinish, object: nil)
}
func playEmbeddedVideo(url: URL, embeddedContentView contentView: UIView? = nil, userinfo: [AnyHashable : Any]? = nil) {
var mediaItem = MediaItem()
mediaItem.url = url
self.playEmbeddedVideo(mediaItem: mediaItem, embeddedContentView: contentView, userinfo: userinfo )
}
func playEmbeddedVideo(mediaItem: MediaItem, embeddedContentView contentView: UIView? = nil , userinfo: [AnyHashable : Any]? = nil ) {
//stop
self.releasePlayer()
if let skinView = userinfo?["skin"] as? UIView{
self.player = EZPlayer(controlView: skinView)
}else{
self.player = EZPlayer()
}
if let autoPlay = userinfo?["autoPlay"] as? Bool{
self.player!.autoPlay = autoPlay
}
if let fullScreenMode = userinfo?["fullScreenMode"] as? EZPlayerFullScreenMode{
self.player!.fullScreenMode = fullScreenMode
}
self.player!.backButtonBlock = { fromDisplayMode in
if fromDisplayMode == .embedded {
self.releasePlayer()
}else if fromDisplayMode == .fullscreen {
if self.embeddedContentView == nil && self.player!.lastDisplayMode != .float{
self.releasePlayer()
}
}else if fromDisplayMode == .float {
self.releasePlayer()
}
}
self.embeddedContentView = contentView
self.player!.playWithURL(mediaItem.url! , embeddedContentView: self.embeddedContentView)
}
func releasePlayer(){
self.player?.stop()
self.player?.view.removeFromSuperview()
self.player = nil
self.embeddedContentView = nil
self.mediaItem = nil
}
@objc func playerDidPlayToEnd(_ notifiaction: Notification) {
//结束播放关闭播放器
//self.releasePlayer()
}
}
| mit | 6c03f37a74db4ebdfd6d9bf70df6deea | 26.359551 | 168 | 0.623819 | 4.87976 | false | false | false | false |
wesj/Project105 | FirefoxPasswords/ActionRequestHandler.swift | 1 | 4079 | //
// ActionRequestHandler.swift
// FirefoxPasswords
//
// Created by Wes Johnston on 10/17/14.
// Copyright (c) 2014 Wes Johnston. All rights reserved.
//
import UIKit
import MobileCoreServices
class ActionRequestHandler: NSObject, NSExtensionRequestHandling {
var extensionContext: NSExtensionContext?
func beginRequestWithExtensionContext(context: NSExtensionContext) {
// Do not call super in an Action extension with no user interface
self.extensionContext = context
var found = false
// Find the item containing the results from the JavaScript preprocessing.
outer:
for item: AnyObject in context.inputItems {
let extItem = item as NSExtensionItem
if let attachments = extItem.attachments {
for itemProvider: AnyObject in attachments {
if itemProvider.hasItemConformingToTypeIdentifier(String(kUTTypePropertyList)) {
itemProvider.loadItemForTypeIdentifier(String(kUTTypePropertyList), options: nil, completionHandler: { (item, error) in
let dictionary = item as NSDictionary
NSOperationQueue.mainQueue().addOperationWithBlock {
self.itemLoadCompletedWithPreprocessingResults(dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as [NSObject: AnyObject])
}
found = true
})
if found {
break outer
}
}
}
}
}
if !found {
self.doneWithResults(nil)
}
}
func itemLoadCompletedWithPreprocessingResults(javaScriptPreprocessingResults: [NSObject: AnyObject]) {
// Here, do something, potentially asynchronously, with the preprocessing
// results.
// In this very simple example, the JavaScript will have passed us the
// current background color style, if there is one. We will construct a
// dictionary to send back with a desired new background color style.
let bgColor: AnyObject? = javaScriptPreprocessingResults["currentBackgroundColor"]
if bgColor == nil || bgColor! as String == "" {
// No specific background color? Request setting the background to red.
self.doneWithResults(["newBackgroundColor": "red"])
} else {
// Specific background color is set? Request replacing it with green.
self.doneWithResults(["newBackgroundColor": "green"])
}
}
func doneWithResults(resultsForJavaScriptFinalizeArg: [NSObject: AnyObject]?) {
if let resultsForJavaScriptFinalize = resultsForJavaScriptFinalizeArg {
// Construct an NSExtensionItem of the appropriate type to return our
// results dictionary in.
// These will be used as the arguments to the JavaScript finalize()
// method.
var resultsDictionary = [NSExtensionJavaScriptFinalizeArgumentKey: resultsForJavaScriptFinalize]
var resultsProvider = NSItemProvider(item: resultsDictionary, typeIdentifier: String(kUTTypePropertyList))
var resultsItem = NSExtensionItem()
resultsItem.attachments = [resultsProvider]
// Signal that we're complete, returning our results.
self.extensionContext!.completeRequestReturningItems([resultsItem], completionHandler: nil)
} else {
// We still need to signal that we're done even if we have nothing to
// pass back.
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
}
// Don't hold on to this after we finished with it.
self.extensionContext = nil
}
}
| mpl-2.0 | 44a56c289ad03dc0749bc76de925ac76 | 42.860215 | 165 | 0.604315 | 6.547352 | false | false | false | false |
moltin/ios-sdk | Tests/moltin iOS Tests/CartTests.swift | 1 | 9568 | //
// CartTests.swift
// moltin iOS
//
// Created by Craig Tweedy on 26/02/2018.
//
import XCTest
@testable
import moltin
class CartTests: XCTestCase {
func testGettingANewCart() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
_ = request.get(forID: "3333") { (result) in
switch result {
case .success(let cart):
XCTAssert(cart.id == "3333")
XCTAssert(type(of: cart) == moltin.Cart.self)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func testGettingCartItems() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
_ = request.items(forCartID: "3333") { (result) in
switch result {
case .success(let cartItems):
XCTAssert(cartItems.data?[0].id == "abc123")
XCTAssert(type(of: cartItems.data) == Optional<[moltin.CartItem]>.self)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func testGettingCartItemsWithTaxes() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsWithTaxesData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
_ = request.items(forCartID: "3333") { (result) in
switch result {
case .success(let cartItems):
XCTAssert(cartItems.data?[0].id == "abc123")
XCTAssert(type(of: cartItems.data) == Optional<[moltin.CartItem]>.self)
XCTAssert(cartItems.data?[0].relationships != nil)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func testAddingAProductToCart() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
let cartID = "3333"
let productID = "12345"
_ = request.addProduct(withID: productID, ofQuantity: 5, toCart: cartID) { (result) in
switch result {
case .success(let cartItems):
XCTAssert(cartItems[0].id == "abc123")
XCTAssert(type(of: cartItems) == [moltin.CartItem].self)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func testBuildingACartItem() {
let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345"))
let item = request.buildCartItem(withID: "12345", ofQuantity: 5)
XCTAssert(item["type"] as? String == "cart_item")
XCTAssert(item["id"] as? String == "12345")
XCTAssert(item["quantity"] as? Int == 5)
}
func testAddingACustomItem() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
let cartID: String = "3333"
let customCartPrice = CartItemPrice(amount: 111, includes_tax: false)
let customItem = CustomCartItem(withName: "testItem", sku: "1231", quantity: 1, description: "test desc", price: customCartPrice)
_ = request.addCustomItem(customItem, toCart: cartID) { (result) in
switch result {
case .success(let cart):
XCTAssert(type(of: cart) == [moltin.CartItem].self)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func testAddingAPromotion() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
let cartID: String = "3333"
_ = request.addPromotion("12345", toCart: cartID) { (result) in
switch result {
case .success(let cart):
XCTAssert(type(of: cart) == [moltin.CartItem].self)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func testBuildingAPromotionItem() {
let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345"))
let item = request.buildCartItem(withID: "12345", ofType: .promotionItem)
XCTAssert(item["type"] as? String == "promotion_item")
XCTAssert(item["code"] as? String == "12345")
}
func testRemovingAnItemFromCart() {
}
func testUpdatingAnItemInCart() {
}
func testCheckingOutCart() {
}
func testBuildingCheckoutCartDataWithoutShippingAddressWorks() {
let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345"))
let customer = Customer(withID: "12345")
let billingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy")
billingAddress.line1 = "7 Patterdale Terrace"
let item = request.buildCartCheckoutData(withCustomer: customer, withBillingAddress: billingAddress, withShippingAddress: nil)
let customerDetails = item["customer"] as? [String: Any] ?? [:]
let shippingDetails = item["shipping_address"] as? [String: Any] ?? [:]
let billingDetails = item["billing_address"] as? [String: Any] ?? [:]
XCTAssert(customerDetails["id"] as? String == "12345")
XCTAssert(shippingDetails["line_1"] as? String == "7 Patterdale Terrace")
XCTAssert(billingDetails["line_1"] as? String == "7 Patterdale Terrace")
}
func testBuildingCheckoutCartDataWithShippingAddressWorks() {
let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345"))
let customer = Customer(withID: "12345")
let billingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy")
billingAddress.line1 = "7 Patterdale Terrace"
let shippingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy")
shippingAddress.line1 = "8 Patterdale Terrace"
let item = request.buildCartCheckoutData(withCustomer: customer, withBillingAddress: billingAddress, withShippingAddress: shippingAddress)
let customerDetails = item["customer"] as? [String: Any] ?? [:]
let shippingDetails = item["shipping_address"] as? [String: Any] ?? [:]
let billingDetails = item["billing_address"] as? [String: Any] ?? [:]
XCTAssert(customerDetails["id"] as? String == "12345")
XCTAssert(shippingDetails["line_1"] as? String == "8 Patterdale Terrace")
XCTAssert(billingDetails["line_1"] as? String == "7 Patterdale Terrace")
}
func testDeletingCart() {
let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.deletedCartData)
let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure")
let cartID: String = "3333"
_ = request.deleteCart(cartID) { (result) in
switch result {
case .success(let cart):
XCTAssert(type(of: cart) == [moltin.Cart].self)
case .failure(let error):
XCTFail(error.localizedDescription)
}
expectationToFulfill.fulfill()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
}
| mit | 0be08954bcb8393b055a70143fb350db | 37.425703 | 146 | 0.614235 | 5.051742 | false | true | false | false |
zhxnlai/wwdc | Zhixuan Lai/Zhixuan Lai/ZLSectionHeaderView.swift | 1 | 1654 | //
// ZLCollectionViewHeaderView.swift
// Zhixuan Lai
//
// Created by Zhixuan Lai on 4/25/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
import TTTAttributedLabel
class ZLSectionHeaderView: UICollectionReusableView {
static let labelInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
static let labelMaxSize = CGSize(width: UIScreen.mainScreen().bounds.width-ZLSectionHeaderView.labelInset.left-ZLSectionHeaderView.labelInset.right, height: CGFloat.max)
var label = TTTAttributedLabel()
var attributedText: NSAttributedString? {
didSet {
if let attributedText = attributedText {
label.setText(attributedText.string, afterInheritingLabelAttributesAndConfiguringWithBlock: { (string) -> NSMutableAttributedString in
NSMutableAttributedString(attributedString: attributedText)
})
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
label.numberOfLines = 0
label.userInteractionEnabled = true
label.enabledTextCheckingTypes = NSDataDetector(types: NSTextCheckingType.Link.rawValue | NSTextCheckingType.Dash.rawValue, error: nil)!.checkingTypes
addSubview(label)
self.userInteractionEnabled = true
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = UIEdgeInsetsInsetRect(self.bounds, ZLSectionHeaderView.labelInset)
}
}
| mit | c6ce4f185fcdc5f2a07ab2f247e897e1 | 32.08 | 173 | 0.675333 | 5.16875 | false | false | false | false |
inket/stts | stts/Services/Super/CachetService.swift | 1 | 2381 | //
// CachetService.swift
// stts
//
import Foundation
typealias CachetService = BaseCachetService & RequiredServiceProperties
class BaseCachetService: BaseService {
private enum ComponentStatus: Int, ComparableStatus {
// https://docs.cachethq.io/docs/component-statuses
case operational = 1
case performanceIssues = 2
case partialOutage = 3
case majorOutage = 4
var description: String {
switch self {
case .operational:
return "Operational"
case .performanceIssues:
return "Performance Issues"
case .partialOutage:
return "Partial Outage"
case .majorOutage:
return "Major Outage"
}
}
var serviceStatus: ServiceStatus {
switch self {
case .operational:
return .good
case .performanceIssues:
return .notice
case .partialOutage:
return .minor
case .majorOutage:
return .major
}
}
}
override func updateStatus(callback: @escaping (BaseService) -> Void) {
guard let realSelf = self as? CachetService else {
fatalError("BaseCachetService should not be used directly.")
}
let apiComponentsURL = realSelf.url.appendingPathComponent("api/v1/components")
loadData(with: apiComponentsURL) { [weak self] data, _, error in
guard let strongSelf = self else { return }
defer { callback(strongSelf) }
guard let data = data else { return strongSelf._fail(error) }
let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard let components = (json as? [String: Any])?["data"] as? [[String: Any]] else {
return strongSelf._fail("Unexpected data")
}
guard !components.isEmpty else { return strongSelf._fail("Unexpected data") }
let statuses = components.compactMap({ $0["status"] as? Int }).compactMap(ComponentStatus.init(rawValue:))
let highestStatus = statuses.max()
strongSelf.status = highestStatus?.serviceStatus ?? .undetermined
strongSelf.message = highestStatus?.description ?? "Undetermined"
}
}
}
| mit | 8ec7d7d589ff52185d578c73dd609d03 | 32.535211 | 118 | 0.582528 | 5.131466 | false | false | false | false |
j-pk/grub-api | Sources/App/Models/User.swift | 1 | 5524 | //
// User.swift
// GrubAPI
//
// Created by Jameson Kirby on 2/8/17.
//
//
import Vapor
import Auth
import Turnstile
import VaporJWT
import Foundation
final class User: Model {
var id: Node?
var exists: Bool = false
var username: String
var password: String
var token: String?
init(username: String, password: String) {
self.id = nil
self.username = username
self.password = password
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
username = try node.extract("username")
password = try node.extract("password")
token = try node.extract("token")
}
init(credentials: UsernamePassword) {
self.username = credentials.username
self.password = credentials.password
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"password": password,
"token": token
])
}
static func prepare(_ database: Database) throws {
try database.create("users") { users in
users.id()
users.string("username")
users.string("password")
users.string("token", optional: true)
}
}
static func revert(_ database: Database) throws {
try database.delete("users")
}
}
struct Authentication {
static let AccessTokenSigningKey = "secret"
static func generateExpirationDate() -> Date {
return Date() + (60 * 5) // 5 Minutes later
}
func decodeJWT(_ token: String) -> JWT? {
guard let jwt = try? JWT(token: token),
let _ = try? jwt.verifySignatureWith(HS256(key: Authentication.AccessTokenSigningKey.makeBytes())) else {
return nil
}
return jwt
}
}
extension User: Auth.User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: User?
switch credentials {
case let userNamePassword as UsernamePassword:
let fetchedUser = try User.query().filter("username", userNamePassword.username).first()
guard let user = fetchedUser else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "User does not exist")
}
if userNamePassword.password == user.password {
return user
} else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "Invalid user name or password")
}
case let id as Identifier:
guard let user = try User.find(id.id) else {
throw Abort.custom(status: .forbidden, message: "Invalid user id")
}
return user
case let accessToken as AccessToken:
user = try User.query().filter("token", accessToken.string).first()
default:
throw IncorrectCredentialsError()
}
if var user = user {
// Check if we have an accessToken first, if not, lets create a new one
if let accessToken = user.token {
// Check if our authentication token has expired, if so, lets generate a new one as this is a fresh login
let receivedJWT = try JWT(token: accessToken)
// Validate it's time stamp
if !receivedJWT.verifyClaims([ExpirationTimeClaim()]) {
try user.generateToken()
}
} else {
// We don't have a valid access token
try user.generateToken()
}
try user.save()
return user
} else {
throw IncorrectCredentialsError()
}
}
static func register(credentials: Credentials) throws -> Auth.User {
var newUser: User
switch credentials {
case let credentials as UsernamePassword:
newUser = User(credentials: credentials)
default: throw UnsupportedCredentialsError()
}
if try User.query().filter("username", newUser.username).first() == nil {
try newUser.generateToken()
try newUser.save()
return newUser
} else {
throw AccountTakenError()
}
}
func generateToken() throws {
let payload = Node.object(["username": .string(username),
"expires" : .number(.double(Authentication.generateExpirationDate().timeIntervalSinceReferenceDate))])
let jwt = try JWT(payload: payload, signer: HS256(key: Authentication.AccessTokenSigningKey.makeBytes()))
self.token = try jwt.createToken()
}
func validateToken() throws -> Bool {
guard let token = self.token else { return false }
// Validate our current access token
let receivedJWT = try JWT(token: token)
if try receivedJWT.verifySignatureWith(HS256(key: Authentication.AccessTokenSigningKey.makeBytes())) {
// If we need a new token, lets generate one
if !receivedJWT.verifyClaims([ExpirationTimeClaim()]) {
try self.generateToken()
return true
}
}
return false
}
}
| mit | 3b3b405e01acc0f054803b4695836589 | 30.386364 | 137 | 0.556662 | 5.186854 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/ReaderTopicService+FollowedInterests.swift | 1 | 4906 | import Foundation
// MARK: - ReaderFollowedInterestsService
/// Protocol representing a service that retrieves the users followed interests/tags
protocol ReaderFollowedInterestsService: AnyObject {
/// Fetches the users locally followed interests
/// - Parameter completion: Called after a fetch, will return nil if the user has no interests or an error occurred
func fetchFollowedInterestsLocally(completion: @escaping ([ReaderTagTopic]?) -> Void)
/// Fetches the users followed interests from the network, then returns the sync'd interests
/// - Parameter completion: Called after a fetch, will return nil if the user has no interests or an error occurred
func fetchFollowedInterestsRemotely(completion: @escaping ([ReaderTagTopic]?) -> Void)
/// Follow the provided interests
/// If the user is not logged into a WP.com account, the interests will only be saved locally.
func followInterests(_ interests: [RemoteReaderInterest],
success: @escaping ([ReaderTagTopic]?) -> Void,
failure: @escaping (Error) -> Void,
isLoggedIn: Bool)
/// Returns the API path of a given slug
func path(slug: String) -> String
}
// MARK: - CoreData Fetching
extension ReaderTopicService: ReaderFollowedInterestsService {
public func fetchFollowedInterestsLocally(completion: @escaping ([ReaderTagTopic]?) -> Void) {
completion(followedInterests())
}
public func fetchFollowedInterestsRemotely(completion: @escaping ([ReaderTagTopic]?) -> Void) {
fetchReaderMenu(success: { [weak self] in
self?.fetchFollowedInterestsLocally(completion: completion)
}) { [weak self] error in
DDLogError("Could not fetch remotely followed interests: \(String(describing: error))")
self?.fetchFollowedInterestsLocally(completion: completion)
}
}
func followInterests(_ interests: [RemoteReaderInterest],
success: @escaping ([ReaderTagTopic]?) -> Void,
failure: @escaping (Error) -> Void,
isLoggedIn: Bool) {
// If the user is logged in, attempt to save the interests on the server
// If the user is not logged in, save the interests locally
if isLoggedIn {
let slugs = interests.map { $0.slug }
let topicService = ReaderTopicServiceRemote(wordPressComRestApi: apiRequest())
topicService.followInterests(withSlugs: slugs, success: { [weak self] in
self?.fetchFollowedInterestsRemotely(completion: success)
}) { error in
failure(error)
}
} else {
followInterestsLocally(interests, success: success, failure: failure)
}
}
func path(slug: String) -> String {
// We create a "remote" service to get an accurate path for the tag
// https://public-api.../tags/_tag_/posts
let service = ReaderTopicServiceRemote(wordPressComRestApi: apiRequest())
return service.pathForTopic(slug: slug)
}
private func followInterestsLocally(_ interests: [RemoteReaderInterest],
success: @escaping ([ReaderTagTopic]?) -> Void,
failure: @escaping (Error) -> Void) {
interests.forEach { interest in
let topic = ReaderTagTopic(remoteInterest: interest, context: managedObjectContext, isFollowing: true)
topic.path = path(slug: interest.slug)
}
ContextManager.sharedInstance().save(managedObjectContext, withCompletionBlock: { [weak self] in
self?.fetchFollowedInterestsLocally(completion: success)
})
}
private func apiRequest() -> WordPressComRestApi {
let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: managedObjectContext)
let token: String? = defaultAccount?.authToken
return WordPressComRestApi.defaultApi(oAuthToken: token,
userAgent: WPUserAgent.wordPress())
}
// MARK: - Private: Fetching Helpers
private func followedInterestsFetchRequest() -> NSFetchRequest<ReaderTagTopic> {
let entityName = "ReaderTagTopic"
let predicate = NSPredicate(format: "following = YES AND showInMenu = YES")
let fetchRequest = NSFetchRequest<ReaderTagTopic>(entityName: entityName)
fetchRequest.predicate = predicate
return fetchRequest
}
private func followedInterests() -> [ReaderTagTopic]? {
let fetchRequest = followedInterestsFetchRequest()
do {
return try managedObjectContext.fetch(fetchRequest)
} catch {
DDLogError("Could not fetch followed interests: \(String(describing: error))")
return nil
}
}
}
| gpl-2.0 | 5467811dbe459b45cbc990a5f846f537 | 42.803571 | 119 | 0.648594 | 5.524775 | false | false | false | false |
bmichotte/HSTracker | HSTracker/UIs/Preferences/OpponentTrackersPreferences.swift | 1 | 4967 | //
// TrackersPreferences.swift
// HSTracker
//
// Created by Benjamin Michotte on 29/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import MASPreferences
class OpponentTrackersPreferences: NSViewController {
@IBOutlet weak var showOpponentTracker: NSButton!
@IBOutlet weak var showCardHuds: NSButton!
@IBOutlet weak var clearTrackersOnGameEnd: NSButton!
@IBOutlet weak var showOpponentCardCount: NSButton!
@IBOutlet weak var showOpponentDrawChance: NSButton!
@IBOutlet weak var showCthunCounter: NSButton!
@IBOutlet weak var showSpellCounter: NSButton!
@IBOutlet weak var includeCreated: NSButton!
@IBOutlet weak var showDeathrattleCounter: NSButton!
@IBOutlet weak var showPlayerClass: NSButton!
@IBOutlet weak var showBoardDamage: NSButton!
@IBOutlet weak var showGraveyard: NSButton!
@IBOutlet weak var showGraveyardDetails: NSButton!
@IBOutlet weak var showJadeCounter: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
showOpponentTracker.state = Settings.showOpponentTracker ? NSOnState : NSOffState
showCardHuds.state = Settings.showCardHuds ? NSOnState : NSOffState
clearTrackersOnGameEnd.state = Settings.clearTrackersOnGameEnd ? NSOnState : NSOffState
showOpponentCardCount.state = Settings.showOpponentCardCount ? NSOnState : NSOffState
showOpponentDrawChance.state = Settings.showOpponentDrawChance ? NSOnState : NSOffState
showCthunCounter.state = Settings.showOpponentCthun ? NSOnState : NSOffState
showSpellCounter.state = Settings.showOpponentSpell ? NSOnState : NSOffState
includeCreated.state = Settings.showOpponentCreated ? NSOnState : NSOffState
showDeathrattleCounter.state = Settings.showOpponentDeathrattle ? NSOnState : NSOffState
showPlayerClass.state = Settings.showOpponentClassInTracker ? NSOnState : NSOffState
showBoardDamage.state = Settings.opponentBoardDamage ? NSOnState : NSOffState
showGraveyard.state = Settings.showOpponentGraveyard ? NSOnState : NSOffState
showGraveyardDetails.state = Settings.showOpponentGraveyardDetails ? NSOnState : NSOffState
showGraveyardDetails.isEnabled = showGraveyard.state == NSOnState
showJadeCounter.state = Settings.showOpponentJadeCounter ? NSOnState : NSOffState
}
@IBAction func checkboxClicked(_ sender: NSButton) {
if sender == showOpponentTracker {
Settings.showOpponentTracker = showOpponentTracker.state == NSOnState
} else if sender == showCardHuds {
Settings.showCardHuds = showCardHuds.state == NSOnState
} else if sender == clearTrackersOnGameEnd {
Settings.clearTrackersOnGameEnd = clearTrackersOnGameEnd.state == NSOnState
} else if sender == showOpponentCardCount {
Settings.showOpponentCardCount = showOpponentCardCount.state == NSOnState
} else if sender == showOpponentDrawChance {
Settings.showOpponentDrawChance = showOpponentDrawChance.state == NSOnState
} else if sender == showCthunCounter {
Settings.showOpponentCthun = showCthunCounter.state == NSOnState
} else if sender == showSpellCounter {
Settings.showOpponentSpell = showSpellCounter.state == NSOnState
} else if sender == includeCreated {
Settings.showOpponentCreated = includeCreated.state == NSOnState
} else if sender == showDeathrattleCounter {
Settings.showOpponentDeathrattle = showDeathrattleCounter.state == NSOnState
} else if sender == showPlayerClass {
Settings.showOpponentClassInTracker = showPlayerClass.state == NSOnState
} else if sender == showBoardDamage {
Settings.opponentBoardDamage = showBoardDamage.state == NSOnState
} else if sender == showGraveyard {
Settings.showOpponentGraveyard = showGraveyard.state == NSOnState
if showGraveyard.state == NSOnState {
showGraveyardDetails.isEnabled = true
} else {
showGraveyardDetails.isEnabled = false
}
} else if sender == showGraveyardDetails {
Settings.showOpponentGraveyardDetails = showGraveyardDetails.state == NSOnState
} else if sender == showJadeCounter {
Settings.showOpponentJadeCounter = showJadeCounter.state == NSOnState
}
}
}
// MARK: - MASPreferencesViewController
extension OpponentTrackersPreferences: MASPreferencesViewController {
override var identifier: String? {
get {
return "opponent_trackers"
}
set {
super.identifier = newValue
}
}
var toolbarItemImage: NSImage? {
return NSImage(named: NSImageNameAdvanced)
}
var toolbarItemLabel: String? {
return NSLocalizedString("Opponent tracker", comment: "")
}
}
| mit | d28911754f338fd5b5278f4137e38311 | 46.75 | 99 | 0.71023 | 5.876923 | false | false | false | false |
daisysomus/swift-algorithm-club | Radix Sort/radixSort.swift | 1 | 1049 | /*
Sorting Algorithm that sorts an input array of integers digit by digit.
*/
// NOTE: This implementation does not handle negative numbers
func radixSort(_ array: inout [Int] ) {
let radix = 10 //Here we define our radix to be 10
var done = false
var index: Int
var digit = 1 //Which digit are we on?
while !done { //While our sorting is not completed
done = true //Assume it is done for now
var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets
for _ in 1...radix {
buckets.append([])
}
for number in array {
index = number / digit //Which bucket will we access?
buckets[index % radix].append(number)
if done && index > 0 { //If we arent done, continue to finish, otherwise we are done
done = false
}
}
var i = 0
for j in 0..<radix {
let bucket = buckets[j]
for number in bucket {
array[i] = number
i += 1
}
}
digit *= radix //Move to the next digit
}
}
| mit | eed4948fc94e7cef1fb62431847bc66b | 21.804348 | 103 | 0.596759 | 3.899628 | false | false | false | false |
finder39/Swimgur | Swimgur/Controllers/ImgurLoginController.swift | 1 | 5567 | //
// ImgurLoginController.swift
// Swimgur
//
// Created by Joseph Neuman on 8/5/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import UIKit
import SWNetworking
// Type of authentication
public enum ImgurLoginAuthType:String {
case ImgurLoginAuthTypeToken = "token"
case ImgurLoginAuthTypePin = "pin"
case ImgurLoginAuthTypeCode = "code"
}
class ImgurLoginController : NSObject, UIWebViewDelegate {
var authorizationClosure:SWBoolBlock?
var authType:ImgurLoginAuthType = .ImgurLoginAuthTypeCode
var imgurLoginViewController:UIViewController = UIViewController()
var webView:UIWebView = UIWebView()
override init() {
webView.frame = imgurLoginViewController.view.frame
imgurLoginViewController.view.addSubview(webView)
}
func authorizeWithViewController(viewController:UIViewController, completionBlock:SWBoolBlock) {
authorizationClosure = completionBlock
// https://api.imgur.com/oauth2/authorize?client_id=541fb8cc243d820&response_type=code&state=auth
let urlString = "\(SWNetworking.sharedInstance.restConfig.serviceAuthorizeEndpoint)/\(SWNetworking.sharedInstance.restConfig.authorizeURI)?client_id=\(Constants.ImgurControllerConfigClientID)&response_type=\(authType.rawValue)&state=auth"
webView.delegate = self
webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
if viewController.view.window != nil {
viewController.presentViewController(imgurLoginViewController, animated: true, completion: nil)
}
}
// TODO: verifyStoredAccountWithCompletionBlock
func verifyStoredAccount(#onCompletion:SWBoolBlock) {
self.authorizationClosure = onCompletion
var token:Token? = SIUserDefaults().token
//if code == "" { code = nil }
if let token = token {
self.getTokensFromRefresh(token)
} else {
onCompletion(success: false)
}
}
private func authorizationSucceeded(success:Bool) {
// remove webview from view controller
//webView.removeFromSuperview()
//webView = UIWebView() // reinitiate
// fire completion block
if let authorizationClosureUnwrapped = authorizationClosure {
authorizationClosureUnwrapped(success: success)
authorizationClosure = nil;
}
}
private func parseQuery(string:String) -> Dictionary<String, String> {
let components:[String] = string.componentsSeparatedByString("&")
var recievedDict:Dictionary<String, String> = Dictionary()
for component in components {
let parts = component.componentsSeparatedByString("=")
if parts.count == 2 {
recievedDict[parts[0]] = parts[1]
}
}
return recievedDict
}
private func getTokensFromCode(code:String) {
var form = CodeForm()
form.code = code
form.clientID = Constants.ImgurControllerConfigClientID
form.clientSecret = Constants.ImgurControllerConfigSecret
form.grantType = "authorization_code"
SWNetworking.sharedInstance.getTokensWithForm(form, onCompletion: { (token) -> () in
self.getAccount()
}) { (error, description) -> () in
self.authorizationSucceeded(false)
}
}
private func getTokensFromRefresh(token:Token) {
var form = RefreshTokenForm()
form.refreshToken = token.refreshToken
form.clientID = Constants.ImgurControllerConfigClientID
form.clientSecret = Constants.ImgurControllerConfigSecret
form.grantType = "refresh_token"
SWNetworking.sharedInstance.getTokensWithForm(form, onCompletion: { (token) -> () in
self.getAccount()
}) { (error, description) -> () in
self.authorizationSucceeded(false)
}
}
private func getAccount() {
SWNetworking.sharedInstance.getAccountWithCompletion({ (account) -> () in
SIUserDefaults().account = account
self.authorizationSucceeded(true)
/*if account != nil {
//println("Retrieved account information: \(account.description)")
SIUserDefaults().username = account.username // TODO: store the whole account
self.authorizationSucceeded(true)
} else {
self.authorizationSucceeded(false)
}*/
}, onError: { (error, description) -> () in
println("Failed to retrieve account information")
self.authorizationSucceeded(false)
})
}
private func webView(webView:UIWebView, didAuthenticateWithRedirectURLString redirectURLString:String) {
let responseDictionary = parseQuery(redirectURLString)
let code = responseDictionary["code"]
SIUserDefaults().code = code
self.getTokensFromCode(code!) // TODO: check it can explicitly unwrap
}
// MARK: UIWebViewDelegate
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
// Once user logs in we will get their goodies in the ridirect URL. Example:
// https://imgur.com/?state=auth&code=860381d0651a8c24079aa13c8732567d8a3f7bab
let redirectedURLString = request.URL.absoluteString!.URLDecodedString() // explicit unwrap new for beta 6
if redirectedURLString.rangeOfString("code=")?.startIndex != nil {
self.webView(webView, didAuthenticateWithRedirectURLString: redirectedURLString)
webView.stopLoading()
imgurLoginViewController.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
return true
}
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
// self.authorizationSucceeded(false) // causing failure of login
}
} | mit | 30a293e63116bfcbef78a5139cb70cb1 | 35.155844 | 242 | 0.719238 | 4.866259 | false | false | false | false |
alessandro-martin/SimpleSideController | SimpleSideController/Source/SimpleSideController.swift | 1 | 22594 | //
// SimpleSideController.swift
// SimpleSideController
//
// Created by Alessandro Martin on 21/08/16.
// Copyright © 2016 Alessandro Martin. All rights reserved.
//
import UIKit
public protocol SimpleSideControllerDelegate: class {
func sideController(_ sideController: SimpleSideController, willChangeTo state: SimpleSideController.Presenting)
func sideController(_ sideController: SimpleSideController, didChangeTo state: SimpleSideController.Presenting)
}
public struct Border {
let thickness: CGFloat
let color: UIColor
public init(thickness: CGFloat, color: UIColor){
self.thickness = thickness
self.color = color
}
}
public struct Shadow {
let opacity: CGFloat
let radius: CGFloat
let width: CGFloat
public init(opacity: CGFloat, radius: CGFloat, width: CGFloat) {
self.opacity = opacity
self.radius = radius
self.width = width
}
}
public class SimpleSideController: UIViewController {
public enum Presenting {
case front
case side
case transitioning
}
public enum Background {
case opaque(color: UIColor, shadow: Shadow?)
case translucent(style: UIBlurEffectStyle, color: UIColor)
case vibrant(style: UIBlurEffectStyle, color: UIColor)
}
static let speedThreshold: CGFloat = 300.0
fileprivate let sideContainerView = UIView()
fileprivate var sideContainerWidthConstraint: NSLayoutConstraint?
fileprivate var sideContainerHorizontalConstraint: NSLayoutConstraint?
fileprivate let borderView = UIView()
fileprivate var borderWidthConstraint: NSLayoutConstraint?
//MARK: Public properties
public weak var delegate: SimpleSideControllerDelegate?
public var state: Presenting {
return self._state
}
public var border: Border? {
didSet {
self.borderView.backgroundColor = (border?.color) ?? .lightGray
self.borderWidthConstraint?.constant = (border?.thickness) ?? 0.0
self.sideContainerView.layoutIfNeeded()
}
}
//MARK: Private properties
fileprivate(set) var _state: Presenting {
willSet(newState) {
self.performTransition(to: newState)
self.delegate?.sideController(self, willChangeTo: newState)
}
didSet {
switch self._state {
case .front:
self.disableTapGesture()
self.frontController.view.isUserInteractionEnabled = true
case .side:
self.enablePanGesture()
self.frontController.view.isUserInteractionEnabled = false
default:
break
}
}
}
fileprivate var shadow: Shadow? {
didSet {
if self._state == .side {
self.sideContainerView.layer.shadowOpacity = Float((self.shadow?.opacity) ?? 0.3)
self.sideContainerView.layer.shadowRadius = (self.shadow?.radius) ?? 5.0
self.sideContainerView.layer.shadowOffset = CGSize(width: ((self.shadow?.width) ?? 7.0) * (self.view.isRightToLeftLanguage() ? -1.0 : 1.0),
height: 0.0)
}
}
}
fileprivate var background: Background {
didSet {
switch self.background {
case let .opaque(color, shadow):
self.sideContainerView.backgroundColor = color
self.shadow = shadow
case let .translucent(_, color), let .vibrant(_, color):
self.sideContainerView.backgroundColor = color
}
}
}
fileprivate var frontController: UIViewController
fileprivate var sideController: UIViewController
fileprivate var panGestureRecognizer: UIPanGestureRecognizer?
fileprivate var panPreviousLocation: CGPoint = .zero
fileprivate var panPreviousVelocity: CGPoint = .zero
fileprivate var tapGestureRecognizer: UITapGestureRecognizer?
fileprivate var sideContainerWidth: CGFloat
fileprivate var blurView: UIVisualEffectView?
fileprivate var vibrancyView: UIVisualEffectView?
fileprivate lazy var presentedSideHorizontalPosition: CGFloat = {
let isRTL = self.view.isRightToLeftLanguage()
return isRTL ? UIScreen.main.bounds.width : self.sideContainerWidth
}()
fileprivate lazy var initialSideHorizontalPosition: CGFloat = {
let isRTL = self.view.isRightToLeftLanguage()
return isRTL ? UIScreen.main.bounds.width + self.sideContainerWidth : 0.0
}()
required public init(frontController: UIViewController, sideController: UIViewController, sideContainerWidth: CGFloat, background: Background) {
self.frontController = frontController
self.sideController = sideController
self.sideContainerWidth = sideContainerWidth
self.background = background
self._state = .front
super.init(nibName: nil, bundle: nil)
}
// Objective-C compatible init:
public init(frontController: UIViewController, sideController: UIViewController, sideContainerWidth: CGFloat,
backgroundColor: UIColor, blurEffectStyle: UIBlurEffectStyle) {
self.frontController = frontController
self.sideController = sideController
self.sideContainerWidth = sideContainerWidth
self.background = .translucent(style: blurEffectStyle, color: backgroundColor)
self._state = .front
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
}
//MARK: Public API
extension SimpleSideController {
public func showFrontController() {
self._state = .front
}
public func showSideController() {
self._state = .side
}
public func isPanGestureEnabled() -> Bool {
return self.panGestureRecognizer?.isEnabled ?? false
}
public func disablePanGesture() {
self.panGestureRecognizer?.isEnabled = false
}
public func enablePanGesture() {
self.panGestureRecognizer?.isEnabled = true
}
public func isTapGestureEnabled() -> Bool {
return self.tapGestureRecognizer?.isEnabled ?? false
}
public func disableTapGesture() {
self.tapGestureRecognizer?.isEnabled = false
}
public func enableTapGesture() {
self.tapGestureRecognizer?.isEnabled = true
}
@objc public func isSideControllerVisible() -> Bool {
return self._state == .side
}
}
//MARK: Gesture management
extension SimpleSideController {
@objc fileprivate func handleTapGesture(gr: UITapGestureRecognizer) {
switch self._state {
case .front:
self._state = .side
case .side:
self._state = .front
case .transitioning:
break
}
}
@objc fileprivate func handlePanGesture(gr: UIPanGestureRecognizer) {
switch gr.state {
case .began:
if let opacity = self.shadow?.opacity, self._state == .front {
self.sideContainerView.displayShadow(opacity: opacity)
}
self._state = .transitioning
self.handlePanGestureBegan(with: gr)
case .changed:
self.handlePanGestureChanged(with: gr)
default:
self.handlePanGestureEnded(with: gr)
}
}
private func handlePanGestureBegan(with recognizer: UIPanGestureRecognizer) {
self.panPreviousLocation = recognizer.location(in: self.view)
}
private func handlePanGestureChanged(with recognizer: UIPanGestureRecognizer) {
guard let constraint = self.sideContainerHorizontalConstraint else { return }
let currentLocation = recognizer.location(in: self.view)
self.panPreviousVelocity = recognizer.velocity(in: self.view)
self.sideContainerHorizontalConstraint?.constant += currentLocation.x - self.panPreviousLocation.x
self.sideContainerHorizontalConstraint?.constant = clamp(lowerBound: 0.0,
value: constraint.constant,
upperBound: self.sideContainerWidth)
self.panPreviousLocation = currentLocation
}
private func handlePanGestureEnded(with recognizer: UIPanGestureRecognizer) {
guard let constraint = self.sideContainerHorizontalConstraint else { return }
let xSideLocation = constraint.constant
let xSpeed = self.panPreviousVelocity.x
if xSpeed > SimpleSideController.speedThreshold {
self._state = .side
} else if xSpeed < -SimpleSideController.speedThreshold {
self._state = .front
} else if xSideLocation > self.sideContainerWidth / 2.0 {
self._state = .side
} else {
self._state = .front
}
self.panPreviousLocation = .zero
self.panPreviousVelocity = .zero
}
}
//MARK: Setup
extension SimpleSideController {
fileprivate func setup() {
self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(gr:)))
self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(gr:)))
self.tapGestureRecognizer?.delegate = self
self.view.addGestureRecognizer(self.panGestureRecognizer!)
self.panGestureRecognizer?.maximumNumberOfTouches = 1
self.view.addGestureRecognizer(self.tapGestureRecognizer!)
self.tapGestureRecognizer?.isEnabled = false
self.addChildViewController(self.frontController)
self.view.addSubview(self.frontController.view)
self.frontController.view.frame = self.view.bounds
self.frontController.didMove(toParentViewController: self)
self.view.addSubview(self.sideContainerView)
self.constrainSideContainerView()
self.sideContainerView.addSubview(self.borderView)
self.constrainBorderView()
self.view.bringSubview(toFront: self.sideContainerView)
self.sideContainerView.hideShadow(animation: 0.0)
switch self.background {
case let .translucent(style, color):
self.sideContainerView.backgroundColor = color
let blurEffect = UIBlurEffect(style: style)
self.blurView = UIVisualEffectView(effect: blurEffect)
self.sideContainerView.insertSubview(self.blurView!, at: 0)
self.pinIntoSideContainer(view: self.blurView!)
self.addChildViewController(self.sideController)
self.blurView?.contentView.addSubview(self.sideController.view)
self.pinIntoSuperView(view: self.sideController.view)
self.sideController.didMove(toParentViewController: self)
case let .vibrant(style, color):
self.sideContainerView.backgroundColor = color
let blurEffect = UIBlurEffect(style: style)
self.blurView = UIVisualEffectView(effect: blurEffect)
let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
self.vibrancyView = UIVisualEffectView(effect: vibrancyEffect)
self.sideContainerView.insertSubview(self.blurView!, at: 0)
self.pinIntoSideContainer(view: self.blurView!)
self.addChildViewController(self.sideController)
self.blurView?.contentView.addSubview(self.vibrancyView!)
self.pinIntoSuperView(view: self.vibrancyView!)
self.vibrancyView?.contentView.addSubview(self.sideController.view)
self.pinIntoSuperView(view: self.sideController.view)
self.sideController.didMove(toParentViewController: self)
case let .opaque(color, shadow):
self.sideController.view.backgroundColor = color
self.shadow = shadow
self.addChildViewController(self.sideController)
self.sideContainerView.addSubview(self.sideController.view)
self.pinIntoSideContainer(view: self.sideController.view)
self.sideController.didMove(toParentViewController: self)
}
}
}
extension SimpleSideController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return gestureRecognizer == self.tapGestureRecognizer &&
!self.sideContainerView.frame.contains(touch.location(in: self.view))
}
}
//MARK: Utilities
extension SimpleSideController {
fileprivate func performTransition(to state: Presenting) {
switch state {
case .front:
self.view.layoutIfNeeded()
self.sideContainerHorizontalConstraint?.constant = self.initialSideHorizontalPosition
self.tapGestureRecognizer?.isEnabled = false
self.sideContainerView.hideShadow()
UIView.animate(withDuration: 0.25,
delay: 0.0,
options: .curveEaseIn,
animations: {
self.view.layoutIfNeeded()
}) { finished in
if finished {
self.delegate?.sideController(self, didChangeTo: state)
}
}
case .side:
self.view.layoutIfNeeded()
self.sideContainerHorizontalConstraint?.constant = self.presentedSideHorizontalPosition
self.tapGestureRecognizer?.isEnabled = true
if let opacity = self.shadow?.opacity {
self.sideContainerView.displayShadow(opacity: opacity)
}
UIView.animate(withDuration: 0.25,
delay: 0.0,
options: .curveEaseOut,
animations: {
self.view.layoutIfNeeded()
}) { finished in
if finished {
self.delegate?.sideController(self, didChangeTo: state)
}
}
case .transitioning:
break
}
}
fileprivate func pinIntoSideContainer(view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: view,
attribute: .top,
relatedBy: .equal,
toItem: self.sideContainerView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
let bottom = NSLayoutConstraint(item: view,
attribute: .bottom,
relatedBy: .equal,
toItem: self.sideContainerView,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
let leading = NSLayoutConstraint(item: view,
attribute: .leading,
relatedBy: .equal,
toItem: self.sideContainerView,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
let trailing = NSLayoutConstraint(item: view,
attribute: .trailing,
relatedBy: .equal,
toItem: self.borderView,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
NSLayoutConstraint.activate([top, bottom, leading, trailing])
}
fileprivate func pinIntoSuperView(view : UIView) {
guard let superView = view.superview else { fatalError("\(view) does not have a superView!") }
view.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: view,
attribute: .top,
relatedBy: .equal,
toItem: superView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
let bottom = NSLayoutConstraint(item: view,
attribute: .bottom,
relatedBy: .equal,
toItem: superView,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
let leading = NSLayoutConstraint(item: view,
attribute: .leading,
relatedBy: .equal,
toItem: superView,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
let trailing = NSLayoutConstraint(item: view,
attribute: .trailing,
relatedBy: .equal,
toItem: superView,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
NSLayoutConstraint.activate([top, bottom, leading, trailing])
}
fileprivate func constrainSideContainerView() {
self.sideContainerView.translatesAutoresizingMaskIntoConstraints = false
let height = NSLayoutConstraint(item: self.sideContainerView,
attribute: .height,
relatedBy: .equal,
toItem: self.view,
attribute: .height,
multiplier: 1.0,
constant: 0.0)
let centerY = NSLayoutConstraint(item: self.sideContainerView,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0)
self.sideContainerWidthConstraint = NSLayoutConstraint(item: self.sideContainerView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: self.sideContainerWidth)
self.sideContainerHorizontalConstraint = NSLayoutConstraint(item: self.sideContainerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: self.initialSideHorizontalPosition)
NSLayoutConstraint.activate([height, centerY, self.sideContainerWidthConstraint!, self.sideContainerHorizontalConstraint!])
}
fileprivate func constrainBorderView() {
self.borderView.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: self.borderView,
attribute: .top,
relatedBy: .equal,
toItem: self.sideContainerView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
let bottom = NSLayoutConstraint(item: self.borderView,
attribute: .bottom,
relatedBy: .equal,
toItem: self.sideContainerView,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
self.borderWidthConstraint = NSLayoutConstraint(item: self.borderView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: self.border?.thickness ?? 0.0)
let side = NSLayoutConstraint(item: self.borderView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.sideContainerView,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
NSLayoutConstraint.activate([top, bottom, self.borderWidthConstraint!, side])
}
}
| mit | 4c2fd3ab953d77bd7d7a10fecce2afd5 | 42.531792 | 155 | 0.538662 | 6.389423 | false | false | false | false |