repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
leftdal/youslow | refs/heads/master | iOS/YouTubeView/YTPlayerView.swift | gpl-3.0 | 1 | //
// YTPlayerView.swift
// Demo
//
// Created by to0 on 2/1/15.
// Copyright (c) 2015 to0. All rights reserved.
//
import UIKit
protocol YTPlayerDelegate {
// func playerHadIframeApiReady(playerView: YTPlayerView)
func playerDidBecomeReady(playerView: YTPlayerView)
func playerDidChangeToState(playerView: YTPlayerView, state: YTPlayerState)
func playerDidChangeToQuality(playerView: YTPlayerView, quality: YTPlayerQuality)
}
class YTPlayerView: UIView, UIWebViewDelegate {
let originalUrl = "about:blank"
var videoId = ""
var delegate: YTPlayerDelegate?
var webView: UIWebView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// loadPlayerWithOptions(nil)
}
override init(frame: CGRect) {
super.init(frame: frame)
// loadPlayerWithOptions(nil)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
func loadVideoById(id: String) {
let js = "player.loadVideoById('\(id)', 0, 'medium');"
self.evaluateJavaScript(js)
}
func loadPlayerWithOptions(id: String) -> Bool {
let bundle = NSBundle.mainBundle();
let path = NSBundle.mainBundle().pathForResource("YTPlayerIframeTemplate", ofType: "html")
if path == nil {
return false
}
var err: NSError?
// let template = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) as! String
// let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: NSStringCompareOptions.allZeros, range: nil)
let template = try! String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: [], range: nil)
if err != nil {
return false
}
newWebView()
webView?.loadHTMLString(iframe, baseURL: NSURL(string: originalUrl))
webView?.delegate = self
// self.webView?.allowsInlineMediaPlayback = true
// self.webView?.mediaPlaybackRequiresUserAction = false
return true
}
func playVideo() {
evaluateJavaScript("player.playVideo();")
}
func destroyPlayer() {
evaluateJavaScript("player.destroy();")
}
func getVideoDuration() -> String? {
return evaluateJavaScript("player.getDuration().toString();")
}
func getVideoLoadedFraction() -> String? {
return evaluateJavaScript("player.getVideoLoadedFraction().toString();")
}
func getAvailableQualityLevelsString() -> String? {
return evaluateJavaScript("player.getAvailableQualityLevels().toString();")
}
private func evaluateJavaScript(js: String) -> String? {
return self.webView?.stringByEvaluatingJavaScriptFromString(js)
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print(error)
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url: NSURL
if request.URL == nil {
return false
}
url = request.URL!
if url.host == originalUrl {
return true
}
else if url.scheme == "http" || url.scheme == "https" {
return shouldNavigateToUrl(url)
}
if url.scheme == "ytplayer" {
delegateEvents(url)
return false
}
return true
}
func webViewDidStartLoad(webView: UIWebView) {
print(webView.request?.URL)
}
private func shouldNavigateToUrl(url: NSURL) -> Bool {
return true
}
/**
* Private method to handle "navigation" to a callback URL of the format
* ytplayer://action?data=someData
*/
private func delegateEvents(event: NSURL) {
let action: String = event.host!
let callback: YTPlayerCallback? = YTPlayerCallback(rawValue: action)
let query = event.query
let data = query?.substringFromIndex(query!.startIndex.advancedBy(5))
if callback == nil {
return
}
switch callback! {
case .OnYouTubeIframeAPIReady:
print("api ready")
// delegate?.playerHadIframeApiReady(self)
case .OnReady:
delegate?.playerDidBecomeReady(self)
case .OnStateChange:
if let state = YTPlayerState(rawValue: data!) {
delegate?.playerDidChangeToState(self, state: state)
}
case .OnPlaybackQualityChange:
if let quality = YTPlayerQuality(rawValue: data!) {
delegate?.playerDidChangeToQuality(self, quality: quality)
}
default:
print("error: \(data)")
}
}
// add and remove webview
private func newWebView() {
removeWebView()
let newWebView = UIWebView(frame: self.bounds)
newWebView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
newWebView.scrollView.scrollEnabled = false
newWebView.scrollView.bounces = false
newWebView.allowsInlineMediaPlayback = true
newWebView.mediaPlaybackRequiresUserAction = false
newWebView.translatesAutoresizingMaskIntoConstraints = false
webView = newWebView
addSubview(self.webView!)
}
func removeWebView() {
destroyPlayer()
webView?.loadHTMLString("", baseURL: NSURL(string: originalUrl))
webView?.stopLoading()
webView?.delegate = nil
webView?.removeFromSuperview()
webView = nil
}
}
| 95647ad0d607dc00a8d308d92b098bf8 | 32.933333 | 154 | 0.614113 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Cliqz/Frontend/Browser/HistorySwiper.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
class HistorySwiper : NSObject {
var topLevelView: UIView!
var webViewContainer: UIView!
func setup(_ topLevelView: UIView, webViewContainer: UIView) {
self.topLevelView = topLevelView
self.webViewContainer = webViewContainer
goBackSwipe.delegate = self
goForwardSwipe.delegate = self
}
lazy var goBackSwipe: UIGestureRecognizer = {
let pan = UIPanGestureRecognizer(target: self, action: #selector(HistorySwiper.screenLeftEdgeSwiped(_:)))
self.topLevelView.addGestureRecognizer(pan)
return pan
}()
lazy var goForwardSwipe: UIGestureRecognizer = {
let pan = UIPanGestureRecognizer(target: self, action: #selector(HistorySwiper.screenRightEdgeSwiped(_:)))
self.topLevelView.addGestureRecognizer(pan)
return pan
}()
@objc func updateDetected() {
restoreWebview()
}
func screenWidth() -> CGFloat {
return topLevelView.frame.width
}
fileprivate func handleSwipe(_ recognizer: UIGestureRecognizer) {
if getApp().browserViewController.homePanelController != nil {
return
}
guard let tab = getApp().browserViewController.tabManager.selectedTab, let webview = tab.webView else { return }
let p = recognizer.location(in: recognizer.view)
let shouldReturnToZero = recognizer == goBackSwipe ? p.x < screenWidth() / 2.0 : p.x > screenWidth() / 2.0
if recognizer.state == .ended || recognizer.state == .cancelled || recognizer.state == .failed {
UIView.animate(withDuration: 0.25, animations: {
if shouldReturnToZero {
self.webViewContainer.transform = CGAffineTransform(translationX: 0, y: self.webViewContainer.transform.ty)
} else {
let x = recognizer == self.goBackSwipe ? self.screenWidth() : -self.screenWidth()
self.webViewContainer.transform = CGAffineTransform(translationX: x, y: self.webViewContainer.transform.ty)
self.webViewContainer.alpha = 0
}
}, completion: { (Bool) -> Void in
if !shouldReturnToZero {
if recognizer == self.goBackSwipe {
getApp().browserViewController.goBack()
} else {
getApp().browserViewController.goForward()
}
self.webViewContainer.transform = CGAffineTransform(translationX: 0, y: self.webViewContainer.transform.ty)
// when content size is updated
postAsyncToMain(3.0) {
self.restoreWebview()
}
NotificationCenter.default.removeObserver(self)
NotificationCenter.default.addObserver(self, selector: #selector(HistorySwiper.updateDetected), name: NSNotification.Name(rawValue: CliqzWebViewConstants.kNotificationPageInteractive), object: webview)
NotificationCenter.default.addObserver(self, selector: #selector(HistorySwiper.updateDetected), name: NSNotification.Name(rawValue: CliqzWebViewConstants.kNotificationWebViewLoadCompleteOrFailed), object: webview)
}
})
} else {
let tx = recognizer == goBackSwipe ? p.x : p.x - screenWidth()
webViewContainer.transform = CGAffineTransform(translationX: tx, y: self.webViewContainer.transform.ty)
}
}
func restoreWebview() {
NotificationCenter.default.removeObserver(self)
postAsyncToMain(0.4) { // after a render detected, allow ample time for drawing to complete
UIView.animate(withDuration: 0.2, animations: {
self.webViewContainer.alpha = 1.0
})
}
}
@objc func screenRightEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
handleSwipe(recognizer)
}
@objc func screenLeftEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
handleSwipe(recognizer)
}
}
extension HistorySwiper : UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {
guard let tab = getApp().browserViewController.tabManager.selectedTab else { return false}
if (recognizer == goBackSwipe && !tab.canGoBack) ||
(recognizer == goForwardSwipe && !tab.canGoForward) {
return false
}
guard let recognizer = recognizer as? UIPanGestureRecognizer else { return false }
let v = recognizer.velocity(in: recognizer.view)
if fabs(v.x) < fabs(v.y) {
return false
}
let tolerance = CGFloat(30.0)
let p = recognizer.location(in: recognizer.view)
return recognizer == goBackSwipe ? p.x < tolerance : p.x > screenWidth() - tolerance
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| 518ab3f04c5c9873a55e8ae10e8c1191 | 44.916667 | 237 | 0.615426 | false | false | false | false |
ApplauseOSS/Swifjection | refs/heads/master | Sources/Swifjection/Classes/SwifjectorSpec.swift | mit | 1 | import Quick
import Nimble
@testable import Swifjection
class InjectingSpec: QuickSpec {
override func spec() {
var injector: Swifjector!
var bindings: Bindings!
beforeEach {
bindings = Bindings()
injector = Swifjector(bindings: bindings)
}
describe("getObject(withType:)") {
context("without any bindings") {
it("should not return object conforming to protocol") {
expect(injector.getObject(withType: EmptySwiftProtocol.self)).to(beNil())
}
it("should not return empty swift object") {
expect(injector.getObject(withType: EmptySwiftClass.self)).to(beNil())
}
it("should return injectable object") {
expect(injector.getObject(withType: InjectableClass.self)).notTo(beNil())
}
it("should inject dependencies in injectable object") {
expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beTrue())
}
it("should return injectable ObjC object") {
expect(injector.getObject(withType: InjectableObjCClass.self)).to(beAKindOf(InjectableObjCClass.self))
}
it("should inject dependencies in injectable ObjC object") {
expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beTrue())
}
it("should return ObjC object") {
expect(injector.getObject(withType: ObjCClass.self)).to(beAKindOf(ObjCClass.self))
}
}
context("with bindings with implicitly unwrapped objects") {
var objectConformingToProtocol: ClassConformingToProtocol!
var structConformingToProtocol: StructConformingToProtocol!
var emptySwiftObject: EmptySwiftClass!
var injectableObject: InjectableClass!
var injectableObjCObject: InjectableObjCClass!
var objCObject: ObjCClass!
beforeEach {
objectConformingToProtocol = ClassConformingToProtocol()
structConformingToProtocol = StructConformingToProtocol()
emptySwiftObject = EmptySwiftClass()
injectableObject = InjectableClass(injector: injector)
injectableObjCObject = InjectableObjCClass(injector: injector)
objCObject = ObjCClass()
}
context("for object conforming to protocol") {
beforeEach {
bindings.bind(object: objectConformingToProtocol, toType: EmptySwiftProtocol.self)
}
it("should have object conforming to protocol injected") {
let object = injector.getObject(withType: EmptySwiftProtocol.self)
expect(object).to(beIdenticalTo(objectConformingToProtocol))
}
}
context("for struct conforming to protocol") {
beforeEach {
bindings.bind(object: structConformingToProtocol, toType: EmptySwiftProtocol.self)
}
it("should have struct conforming to protocol injected") {
let object = injector.getObject(withType: EmptySwiftProtocol.self)
expect(object).to(beAnInstanceOf(StructConformingToProtocol.self))
}
}
context("for other cases") {
beforeEach {
bindings.bind(object: emptySwiftObject, toType: EmptySwiftClass.self)
bindings.bind(object: injectableObject, toType: InjectableClass.self)
bindings.bind(object: injectableObjCObject, toType: InjectableObjCClass.self)
bindings.bind(object: objCObject, toType: ObjCClass.self)
}
it("should have empty swift object injected") {
expect(injector.getObject(withType: EmptySwiftClass.self)).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(injector.getObject(withType: InjectableClass.self)).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beFalse())
}
it("should have injectable ObjC object injected") {
expect(injector.getObject(withType: InjectableObjCClass.self)).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beFalse())
}
it("should have ObjC object injected") {
expect(injector.getObject(withType: ObjCClass.self)).to(beIdenticalTo(objCObject))
}
}
}
context("with bindings") {
var objectConformingToProtocol: ClassConformingToProtocol?
var emptySwiftObject: EmptySwiftClass?
var injectableObject: InjectableClass?
var injectableObjCObject: InjectableObjCClass?
var objCObject: ObjCClass?
beforeEach {
objectConformingToProtocol = ClassConformingToProtocol()
emptySwiftObject = EmptySwiftClass()
injectableObject = InjectableClass(injector: injector)
injectableObjCObject = InjectableObjCClass(injector: injector)
objCObject = ObjCClass()
}
context("object bindings") {
beforeEach {
bindings.bind(object: objectConformingToProtocol!, toType: EmptySwiftProtocol.self)
bindings.bind(object: emptySwiftObject!, toType: EmptySwiftClass.self)
bindings.bind(object: injectableObject!, toType: InjectableClass.self)
bindings.bind(object: injectableObjCObject!, toType: InjectableObjCClass.self)
bindings.bind(object: objCObject!, toType: ObjCClass.self)
}
it("should have object conforming to protocol injected") {
expect(injector.getObject(withType: EmptySwiftProtocol.self)).to(beIdenticalTo(objectConformingToProtocol))
}
it("should have empty swift object injected") {
expect(injector.getObject(withType: EmptySwiftClass.self)).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(injector.getObject(withType: InjectableClass.self)).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beFalse())
}
it("should have injectable ObjC object injected") {
expect(injector.getObject(withType: InjectableObjCClass.self)).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beFalse())
}
it("should have ObjC object injected") {
expect(injector.getObject(withType: ObjCClass.self)).to(beIdenticalTo(objCObject))
}
}
context("closure bindings") {
beforeEach {
injectableObject?.injectDependencies(injector: injector)
injectableObjCObject?.injectDependencies(injector: injector)
bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in
return objectConformingToProtocol!
}
bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in
return emptySwiftObject!
}
bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in
return injectableObject!
}
bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in
return injectableObjCObject!
}
bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in
return objCObject!
}
}
it("should not have object conforming to protocol injected") {
expect(injector.getObject(withType: EmptySwiftProtocol.self)).to(beIdenticalTo(objectConformingToProtocol))
}
it("should not have empty swift object injected") {
expect(injector.getObject(withType: EmptySwiftClass.self)).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(injector.getObject(withType: InjectableClass.self)).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(injector.getObject(withType: InjectableObjCClass.self)).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(injector.getObject(withType: ObjCClass.self)).to(beIdenticalTo(objCObject))
}
}
context("closure bindings with new instances") {
beforeEach {
bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in
return ClassConformingToProtocol()
}
bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in
return EmptySwiftClass()
}
bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in
let injectableObject = InjectableClass()
injectableObject.injectDependencies(injector: injector)
return injectableObject
}
bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in
let injectableObjCObject = InjectableObjCClass()
injectableObjCObject.injectDependencies(injector: injector)
return injectableObjCObject
}
bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in
return ObjCClass()
}
}
it("should not have object conforming to protocol injected") {
expect(injector.getObject(withType: EmptySwiftProtocol.self)).notTo(beNil())
}
it("should not have empty swift object injected") {
expect(injector.getObject(withType: EmptySwiftClass.self)).notTo(beNil())
}
it("should have injectable object injected") {
expect(injector.getObject(withType: InjectableClass.self)).notTo(beNil())
}
it("should inject dependencies in injectable object") {
expect(injector.getObject(withType: InjectableClass.self)!.injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(injector.getObject(withType: InjectableObjCClass.self)).to(beAKindOf(InjectableObjCClass.self))
}
it("should inject dependencies in injectable ObjC object") {
expect(injector.getObject(withType: InjectableObjCClass.self)!.injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(injector.getObject(withType: ObjCClass.self)).to(beAKindOf(ObjCClass.self))
}
}
}
}
describe("subscript") {
context("without any bindings") {
it("should not return object conforming to protocol") {
expect(injector[EmptySwiftProtocol.self]).to(beNil())
}
it("should not return empty swift object") {
expect(injector[EmptySwiftClass.self]).to(beNil())
}
it("should return injectable object") {
expect(injector[InjectableClass.self]).notTo(beNil())
}
it("should inject dependencies in injectable object") {
expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beTrue())
}
it("should return injectable ObjC object") {
let object = injector[InjectableObjCClass.self as Injectable.Type]
expect(object).to(beAKindOf(InjectableObjCClass.self))
}
it("should inject dependencies in injectable ObjC object") {
expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beTrue())
}
it("should return ObjC object") {
expect(injector[ObjCClass.self]).to(beAKindOf(ObjCClass.self))
}
}
context("with bindings") {
var objectConformingToProtocol: ClassConformingToProtocol?
var emptySwiftObject: EmptySwiftClass?
var injectableObject: InjectableClass?
var injectableObjCObject: InjectableObjCClass?
var objCObject: ObjCClass?
beforeEach {
objectConformingToProtocol = ClassConformingToProtocol()
emptySwiftObject = EmptySwiftClass()
injectableObject = InjectableClass(injector: injector)
injectableObjCObject = InjectableObjCClass(injector: injector)
objCObject = ObjCClass()
}
context("object bindings") {
beforeEach {
bindings.bind(object: objectConformingToProtocol!, toType: EmptySwiftProtocol.self)
bindings.bind(object: emptySwiftObject!, toType: EmptySwiftClass.self)
bindings.bind(object: injectableObject!, toType: InjectableClass.self)
bindings.bind(object: injectableObjCObject!, toType: InjectableObjCClass.self)
bindings.bind(object: objCObject!, toType: ObjCClass.self)
}
it("should not have object conforming to protocol injected") {
expect(injector[EmptySwiftProtocol.self]).to(beIdenticalTo(objectConformingToProtocol))
}
it("should not have empty swift object injected") {
expect(injector[EmptySwiftClass.self]).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(injector[InjectableClass.self]).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beFalse())
}
it("should have injectable ObjC object injected") {
expect(injector[InjectableObjCClass.self as Injectable.Type]).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beFalse())
}
it("should have ObjC object injected") {
expect(injector[ObjCClass.self]).to(beIdenticalTo(objCObject))
}
}
context("closure bindings") {
beforeEach {
injectableObject?.injectDependencies(injector: injector)
injectableObjCObject?.injectDependencies(injector: injector)
bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in
return objectConformingToProtocol!
}
bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in
return emptySwiftObject!
}
bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in
return injectableObject!
}
bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in
return injectableObjCObject!
}
bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in
return objCObject!
}
}
it("should not have object conforming to protocol injected") {
expect(injector[EmptySwiftProtocol.self]).to(beIdenticalTo(objectConformingToProtocol))
}
it("should not have empty swift object injected") {
expect(injector[EmptySwiftClass.self]).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(injector[InjectableClass.self]).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(injector[InjectableObjCClass.self as Injectable.Type]).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(injector[ObjCClass.self]).to(beIdenticalTo(objCObject))
}
}
context("closure bindings with new instances") {
beforeEach {
bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in
return ClassConformingToProtocol()
}
bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in
return EmptySwiftClass()
}
bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in
let injectableObject = InjectableClass()
injectableObject.injectDependencies(injector: injector)
return injectableObject
}
bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in
let injectableObjCObject = InjectableObjCClass()
injectableObjCObject.injectDependencies(injector: injector)
return injectableObjCObject
}
bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in
return ObjCClass()
}
}
it("should not have object conforming to protocol injected") {
expect(injector[EmptySwiftProtocol.self]).notTo(beNil())
}
it("should not have empty swift object injected") {
expect(injector[EmptySwiftClass.self]).notTo(beNil())
}
it("should have injectable object injected") {
expect(injector[InjectableClass.self]).notTo(beNil())
}
it("should inject dependencies in injectable object") {
expect((injector[InjectableClass.self]! as! InjectableClass).injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(injector[InjectableObjCClass.self as Injectable.Type]).to(beAKindOf(InjectableObjCClass.self))
}
it("should inject dependencies in injectable ObjC object") {
expect((injector[InjectableObjCClass.self as Injectable.Type]! as! InjectableObjCClass).injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(injector[ObjCClass.self]).to(beAKindOf(ObjCClass.self))
}
}
}
}
describe("injecting dependencies in objects using injectDependencies(injector:) with the injector") {
var objectWithDependencies: ClassWithDependencies!
context("without any bindings") {
beforeEach {
objectWithDependencies = ClassWithDependencies(injector: injector)
objectWithDependencies?.injectDependencies(injector: injector)
}
it("should not have object conforming to protocol injected") {
expect(objectWithDependencies.objectConformingToProtocol).to(beNil())
}
it("should not have empty swift object injected") {
expect(objectWithDependencies.emptySwiftObject).to(beNil())
}
it("should have injectable object injected") {
expect(objectWithDependencies.injectableObject).notTo(beNil())
}
it("should inject dependencies in injectable object") {
expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(objectWithDependencies.injectableObjCObject).to(beAKindOf(InjectableObjCClass.self))
}
it("should inject dependencies in injectable ObjC object") {
expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(objectWithDependencies.objCObject).to(beAKindOf(ObjCClass.self))
}
}
context("with bindings") {
var objectConformingToProtocol: ClassConformingToProtocol?
var emptySwiftObject: EmptySwiftClass?
var injectableObject: InjectableClass?
var injectableObjCObject: InjectableObjCClass?
var objCObject: ObjCClass?
beforeEach {
objectConformingToProtocol = ClassConformingToProtocol()
emptySwiftObject = EmptySwiftClass()
injectableObject = InjectableClass(injector: injector)
injectableObjCObject = InjectableObjCClass(injector: injector)
objCObject = ObjCClass()
}
context("object bindings") {
beforeEach {
bindings.bind(object: objectConformingToProtocol!, toType: EmptySwiftProtocol.self)
bindings.bind(object: emptySwiftObject!, toType: EmptySwiftClass.self)
bindings.bind(object: injectableObject!, toType: InjectableClass.self)
bindings.bind(object: injectableObjCObject!, toType: InjectableObjCClass.self)
bindings.bind(object: objCObject!, toType: ObjCClass.self)
objectWithDependencies = ClassWithDependencies(injector: injector)
objectWithDependencies?.injectDependencies(injector: injector)
}
it("should not have object conforming to protocol injected") {
expect(objectWithDependencies.objectConformingToProtocol).to(beIdenticalTo(objectConformingToProtocol))
}
it("should not have empty swift object injected") {
expect(objectWithDependencies.emptySwiftObject).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(objectWithDependencies.injectableObject).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beFalse())
}
it("should have injectable ObjC object injected") {
expect(objectWithDependencies.injectableObjCObject).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beFalse())
}
it("should have ObjC object injected") {
expect(objectWithDependencies.objCObject).to(beIdenticalTo(objCObject))
}
}
context("closure bindings") {
beforeEach {
injectableObject?.injectDependencies(injector: injector)
injectableObjCObject?.injectDependencies(injector: injector)
bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in
return objectConformingToProtocol!
}
bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in
return emptySwiftObject!
}
bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in
return injectableObject!
}
bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in
return injectableObjCObject!
}
bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in
return objCObject!
}
objectWithDependencies = ClassWithDependencies(injector: injector)
objectWithDependencies?.injectDependencies(injector: injector)
}
it("should not have object conforming to protocol injected") {
expect(objectWithDependencies.objectConformingToProtocol).to(beIdenticalTo(objectConformingToProtocol))
}
it("should not have empty swift object injected") {
expect(objectWithDependencies.emptySwiftObject).to(beIdenticalTo(emptySwiftObject))
}
it("should have injectable object injected") {
expect(objectWithDependencies.injectableObject).to(beIdenticalTo(injectableObject))
}
it("should inject dependencies in injectable object") {
expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(objectWithDependencies.injectableObjCObject).to(beIdenticalTo(injectableObjCObject))
}
it("should inject dependencies in injectable ObjC object") {
expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(objectWithDependencies.objCObject).to(beIdenticalTo(objCObject))
}
}
context("closure bindings with new instances") {
beforeEach {
bindings.bind(type: EmptySwiftProtocol.self) { (injector: Injecting) -> AnyObject in
return ClassConformingToProtocol()
}
bindings.bind(type: EmptySwiftClass.self) { (injector: Injecting) -> AnyObject in
return EmptySwiftClass()
}
bindings.bind(type: InjectableClass.self) { (injector: Injecting) -> AnyObject in
let injectableObject = InjectableClass()
injectableObject.injectDependencies(injector: injector)
return injectableObject
}
bindings.bind(type: InjectableObjCClass.self) { (injector: Injecting) -> AnyObject in
let injectableObjCObject = InjectableObjCClass()
injectableObjCObject.injectDependencies(injector: injector)
return injectableObjCObject
}
bindings.bind(type: ObjCClass.self) { (injector: Injecting) -> AnyObject in
return ObjCClass()
}
objectWithDependencies = ClassWithDependencies(injector: injector)
objectWithDependencies?.injectDependencies(injector: injector)
}
it("should not have object conforming to protocol injected") {
expect(objectWithDependencies.objectConformingToProtocol).notTo(beNil())
}
it("should not have empty swift object injected") {
expect(objectWithDependencies.emptySwiftObject).notTo(beNil())
}
it("should have injectable object injected") {
expect(objectWithDependencies.injectableObject).notTo(beNil())
}
it("should inject dependencies in injectable object") {
expect(objectWithDependencies.injectableObject!.injectDependenciesCalled).to(beTrue())
}
it("should have injectable ObjC object injected") {
expect(objectWithDependencies.injectableObjCObject).to(beAKindOf(InjectableObjCClass.self))
}
it("should inject dependencies in injectable ObjC object") {
expect(objectWithDependencies.injectableObjCObject!.injectDependenciesCalled).to(beTrue())
}
it("should have ObjC object injected") {
expect(objectWithDependencies.objCObject).to(beAKindOf(ObjCClass.self))
}
}
}
}
}
}
| e9433cb933281c19b167687cfce76968 | 48.943604 | 151 | 0.509874 | false | false | false | false |
erhoffex/SwiftAnyPic | refs/heads/master | SwiftAnyPic/PAPWelcomeViewController.swift | cc0-1.0 | 3 | import UIKit
import Synchronized
import ParseFacebookUtils
class PAPWelcomeViewController: UIViewController, PAPLogInViewControllerDelegate {
private var _presentedLoginViewController: Bool = false
private var _facebookResponseCount: Int = 0
private var _expectedFacebookResponseCount: Int = 0
private var _profilePicData: NSMutableData? = nil
// MARK:- UIViewController
override func loadView() {
let backgroundImageView: UIImageView = UIImageView(frame: UIScreen.mainScreen().bounds)
backgroundImageView.image = UIImage(named: "Default.png")
self.view = backgroundImageView
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() == nil {
presentLoginViewController(false)
return
}
// Present Anypic UI
(UIApplication.sharedApplication().delegate as! AppDelegate).presentTabBarController()
// Refresh current user with server side data -- checks if user is still valid and so on
_facebookResponseCount = 0
PFUser.currentUser()?.fetchInBackgroundWithTarget(self, selector: Selector("refreshCurrentUserCallbackWithResult:error:"))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK:- PAPWelcomeViewController
func presentLoginViewController(animated: Bool) {
if _presentedLoginViewController {
return
}
_presentedLoginViewController = true
let loginViewController = PAPLogInViewController()
loginViewController.delegate = self
presentViewController(loginViewController, animated: animated, completion: nil)
}
// MARK:- PAPLoginViewControllerDelegate
func logInViewControllerDidLogUserIn(logInViewController: PAPLogInViewController) {
if _presentedLoginViewController {
_presentedLoginViewController = false
self.dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK:- ()
func processedFacebookResponse() {
// Once we handled all necessary facebook batch responses, save everything necessary and continue
synchronized(self) {
_facebookResponseCount++;
if (_facebookResponseCount != _expectedFacebookResponseCount) {
return
}
}
_facebookResponseCount = 0;
print("done processing all Facebook requests")
PFUser.currentUser()!.saveInBackgroundWithBlock { (succeeded, error) in
if !succeeded {
print("Failed save in background of user, \(error)")
} else {
print("saved current parse user")
}
}
}
func refreshCurrentUserCallbackWithResult(refreshedObject: PFObject, error: NSError?) {
// This fetches the most recent data from FB, and syncs up all data with the server including profile pic and friends list from FB.
// A kPFErrorObjectNotFound error on currentUser refresh signals a deleted user
if error != nil && error!.code == PFErrorCode.ErrorObjectNotFound.rawValue {
print("User does not exist.")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
let session: FBSession = PFFacebookUtils.session()!
if !session.isOpen {
print("FB Session does not exist, logout")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
if session.accessTokenData.userID == nil {
print("userID on FB Session does not exist, logout")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
guard let currentParseUser: PFUser = PFUser.currentUser() else {
print("Current Parse user does not exist, logout")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
let facebookId = currentParseUser.objectForKey(kPAPUserFacebookIDKey) as? String
if facebookId == nil || facebookId!.length == 0 {
// set the parse user's FBID
currentParseUser.setObject(session.accessTokenData.userID, forKey: kPAPUserFacebookIDKey)
}
if PAPUtility.userHasValidFacebookData(currentParseUser) == false {
print("User does not have valid facebook ID. PFUser's FBID: \(currentParseUser.objectForKey(kPAPUserFacebookIDKey)), FBSessions FBID: \(session.accessTokenData.userID). logout")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
// Finished checking for invalid stuff
// Refresh FB Session (When we link up the FB access token with the parse user, information other than the access token string is dropped
// By going through a refresh, we populate useful parameters on FBAccessTokenData such as permissions.
PFFacebookUtils.session()!.refreshPermissionsWithCompletionHandler { (session, error) in
if (error != nil) {
print("Failed refresh of FB Session, logging out: \(error)")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
// refreshed
print("refreshed permissions: \(session)")
self._expectedFacebookResponseCount = 0
let permissions: NSArray = session.accessTokenData.permissions
// FIXME: How to use "contains" in Swift Array? Replace the NSArray with Swift array
if permissions.containsObject("public_profile") {
// Logged in with FB
// Create batch request for all the stuff
let connection = FBRequestConnection()
self._expectedFacebookResponseCount++
connection.addRequest(FBRequest.requestForMe(), completionHandler: { (connection, result, error) in
if error != nil {
// Failed to fetch me data.. logout to be safe
print("couldn't fetch facebook /me data: \(error), logout")
(UIApplication.sharedApplication().delegate as! AppDelegate).logOut()
return
}
if let facebookName = result["name"] as? String where facebookName.length > 0 {
currentParseUser.setObject(facebookName, forKey: kPAPUserDisplayNameKey)
}
self.processedFacebookResponse()
})
// profile pic request
self._expectedFacebookResponseCount++
connection.addRequest(FBRequest(graphPath: "me", parameters: ["fields": "picture.width(500).height(500)"], HTTPMethod: "GET"), completionHandler: { (connection, result, error) in
if error == nil {
// result is a dictionary with the user's Facebook data
// FIXME: Really need to be this ugly???
// let userData = result as? [String : [String : [String : String]]]
// let profilePictureURL = NSURL(string: userData!["picture"]!["data"]!["url"]!)
// // Now add the data to the UI elements
// let profilePictureURLRequest: NSURLRequest = NSURLRequest(URL: profilePictureURL!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10.0) // Facebook profile picture cache policy: Expires in 2 weeks
// NSURLConnection(request: profilePictureURLRequest, delegate: self)
if let userData = result as? [NSObject: AnyObject] {
if let picture = userData["picture"] as? [NSObject: AnyObject] {
if let data = picture["data"] as? [NSObject: AnyObject] {
if let profilePictureURL = data["url"] as? String {
// Now add the data to the UI elements
let profilePictureURLRequest: NSURLRequest = NSURLRequest(URL: NSURL(string: profilePictureURL)!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10.0) // Facebook profile picture cache policy: Expires in 2 weeks
NSURLConnection(request: profilePictureURLRequest, delegate: self)
}
}
}
}
} else {
print("Error getting profile pic url, setting as default avatar: \(error)")
let profilePictureData: NSData = UIImagePNGRepresentation(UIImage(named: "AvatarPlaceholder.png")!)!
PAPUtility.processFacebookProfilePictureData(profilePictureData)
}
self.processedFacebookResponse()
})
if permissions.containsObject("user_friends") {
// Fetch FB Friends + me
self._expectedFacebookResponseCount++
connection.addRequest(FBRequest.requestForMyFriends(), completionHandler: { (connection, result, error) in
print("processing Facebook friends")
if error != nil {
// just clear the FB friend cache
PAPCache.sharedCache.clear()
} else {
let data = result.objectForKey("data") as? NSArray
let facebookIds: NSMutableArray = NSMutableArray(capacity: data!.count)
for friendData in data! {
if let facebookId = friendData["id"] {
facebookIds.addObject(facebookId!)
}
}
// cache friend data
PAPCache.sharedCache.setFacebookFriends(facebookIds)
if currentParseUser.objectForKey(kPAPUserFacebookFriendsKey) != nil {
currentParseUser.removeObjectForKey(kPAPUserFacebookFriendsKey)
}
if currentParseUser.objectForKey(kPAPUserAlreadyAutoFollowedFacebookFriendsKey) != nil {
(UIApplication.sharedApplication().delegate as! AppDelegate).autoFollowUsers()
}
}
self.processedFacebookResponse()
})
}
connection.start()
} else {
let profilePictureData: NSData = UIImagePNGRepresentation(UIImage(named: "AvatarPlaceholder.png")!)!
PAPUtility.processFacebookProfilePictureData(profilePictureData)
PAPCache.sharedCache.clear()
currentParseUser.setObject("Someone", forKey: kPAPUserDisplayNameKey)
self._expectedFacebookResponseCount++
self.processedFacebookResponse()
}
}
}
// MARK:- NSURLConnectionDataDelegate
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
_profilePicData = NSMutableData()
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
_profilePicData!.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection) {
PAPUtility.processFacebookProfilePictureData(_profilePicData!)
}
// MARK:- NSURLConnectionDelegate
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
print("Connection error downloading profile pic data: \(error)")
}
}
| 0f50b1fab896d05393096fa91070827c | 47.673152 | 282 | 0.585019 | false | false | false | false |
Oscareli98/Moya | refs/heads/master | Demo/Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Switch.swift | mit | 3 | //
// Switch.swift
// Rx
//
// Created by Krunoslav Zaher on 3/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Switch_<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = Observable<O.Element>
typealias Parent = Switch<O.Element>
typealias SwitchState = (
subscription: SingleAssignmentDisposable,
innerSubscription: SerialDisposable,
stopped: Bool,
latest: Int,
hasLatest: Bool
)
let parent: Parent
var lock = NSRecursiveLock()
var switchState: SwitchState
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
self.switchState = (
subscription: SingleAssignmentDisposable(),
innerSubscription: SerialDisposable(),
stopped: false,
latest: 0,
hasLatest: false
)
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = self.parent.sources.subscribeSafe(self)
let switchState = self.switchState
switchState.subscription.disposable = subscription
return CompositeDisposable(switchState.subscription, switchState.innerSubscription)
}
func on(event: Event<Element>) {
switch event {
case .Next(let observable):
let latest: Int = self.lock.calculateLocked {
self.switchState.hasLatest = true
self.switchState.latest = self.switchState.latest + 1
return self.switchState.latest
}
let d = SingleAssignmentDisposable()
self.switchState.innerSubscription.setDisposable(d)
let observer = SwitchIter(parent: self, id: latest, _self: d)
let disposable = observable.value.subscribeSafe(observer)
d.disposable = disposable
case .Error(let error):
self.lock.performLocked {
trySendError(observer, error)
self.dispose()
}
case .Completed:
self.lock.performLocked {
self.switchState.stopped = true
self.switchState.subscription.dispose()
if !self.switchState.hasLatest {
trySendCompleted(observer)
self.dispose()
}
}
}
}
}
class SwitchIter<O: ObserverType> : ObserverType {
typealias Element = O.Element
typealias Parent = Switch_<O>
let parent: Parent
let id: Int
let _self: Disposable
init(parent: Parent, id: Int, _self: Disposable) {
self.parent = parent
self.id = id
self._self = _self
}
func on(event: Event<Element>) {
return parent.lock.calculateLocked { state in
let switchState = self.parent.switchState
switch event {
case .Next: break
case .Error: fallthrough
case .Completed: self._self.dispose()
}
if switchState.latest != self.id {
return
}
let observer = self.parent.observer
switch event {
case .Next:
trySend(observer, event)
case .Error:
trySend(observer, event)
self.parent.dispose()
case .Completed:
parent.switchState.hasLatest = false
if switchState.stopped {
trySend(observer, event)
self.parent.dispose()
}
}
}
}
}
class Switch<Element> : Producer<Element> {
let sources: Observable<Observable<Element>>
init(sources: Observable<Observable<Element>>) {
self.sources = sources
}
override func run<O : ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Switch_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | 659e2038f4fc54f430d4fd7f03640933 | 29.276596 | 146 | 0.549672 | false | true | false | false |
el-hoshino/NotAutoLayout | refs/heads/master | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/CenterTopMiddle.Individual.swift | apache-2.0 | 1 | //
// CenterTopMiddle.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct CenterTopMiddle {
let center: LayoutElement.Horizontal
let top: LayoutElement.Vertical
let middle: LayoutElement.Vertical
}
}
// MARK: - Make Frame
extension IndividualProperty.CenterTopMiddle {
private func makeFrame(center: Float, top: Float, middle: Float, width: Float) -> Rect {
let x = center - width.half
let y = top
let height = (middle - top).double
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.CenterTopMiddle: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let center = self.center.evaluated(from: parameters)
let top = self.top.evaluated(from: parameters)
let middle = self.middle.evaluated(from: parameters)
let height = (middle - top).double
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(center: center, top: top, middle: middle, width: width)
}
}
| c33879aa541343dfc92ee249ad48c929 | 22.263158 | 115 | 0.717195 | false | false | false | false |
iamyuiwong/swift-sqlite | refs/heads/master | sqlite/SQLiteValueType.swift | lgpl-3.0 | 1 | // SQLiteValueType.swift
// 15/10/12.
import Foundation
/* sqlite 3
#define SQLITE_INTEGER 1
#define SQLITE_FLOAT 2
#define SQLITE_BLOB 4
#define SQLITE_NULL 5
#ifdef SQLITE_TEXT
# undef SQLITE_TEXT
#else
# define SQLITE_TEXT 3
#endif
#define SQLITE3_TEXT 3
*/
public enum SQLiteValueType: Int32 {
public static func get (byValue v: Int32 = 3) -> SQLiteValueType {
switch (v) {
case 1:
return INTEGER
case 2:
return FLOAT
case 4:
return BLOB
case 5:
return NULL
case 3:
fallthrough
default:
return TEXT
}
}
case INTEGER = 1
case FLOAT = 2
case TEXT = 3
case BLOB = 4
case NULL = 5
case DATETIME = 6
} | 59dee72acd67ab427665f1d1e1bdae42 | 13.170213 | 67 | 0.66015 | false | false | false | false |
corchwll/amos-ss15-proj5_ios | refs/heads/master | MobileTimeAccounting/BusinessLogic/CSV/SessionsCSVExporter.swift | agpl-3.0 | 1 | /*
Mobile Time Accounting
Copyright (C) 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
class SessionsCSVExporter
{
let csvBuilder = CSVBuilder()
let dateFormatter = NSDateFormatter()
let calendar = NSCalendar.currentCalendar()
var month = 0
var year = 0
var projects = [Project]()
var sessions = [[Session]]()
/*
Constructor, setting up date formatter.
@methodtype Constructor
@pre Date formatter has been initialized
@post Date formatter is set up
*/
init()
{
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
}
/*
Exports all sessions of a given month in a given year as csv file.
@methodtype Helper
@pre Valid values for month (>0) and year
@post Returns csv file as NSData
*/
func exportCSV(month: Int, year: Int)->NSData
{
self.month = month
self.year = year
let csvString = doExportCSV()
return csvString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
/*
Exports all sessions of a given month in a given year as csv string by using CSVBuilder.
@methodtype Command
@pre CSVBuilder has been initialized
@post Returns csv string
*/
func doExportCSV()->String
{
setHeading()
setProjectsRow()
setSessionRows()
return csvBuilder.build()
}
/*
Sets heading of csv file like: 'profile_firstname','profile_lastname','month','year'
@methodtype Command
@pre Profile has been set
@post Heading is set
*/
private func setHeading()
{
let profile = profileDAO.getProfile()!
csvBuilder.addRow(profile.firstname, profile.lastname, String(month), String(year))
}
/*
Sets all active projects of the given month into a row like: '','project1','project2',...
@methodtype Command
@pre Active projects are available
@post Projects are added into row
*/
private func setProjectsRow()
{
projects = projectDAO.getProjects(month, year: year)
csvBuilder.addRow("")
for project in projects
{
csvBuilder.addRowItem(1, rowItem: project.name)
sessions.append(sessionDAO.getSessions(project, month: month, year: year))
}
}
/*
Sets all dates of all session rows of the given month like: '1/1/2015','8'
'1/2/2015','0'
...
@methodtype Command
@pre -
@post All session rows are set
*/
private func setSessionRows()
{
var currentRow = 2
let startOfMonth = NSDate(month: month, year: year, calendar: calendar).startOfMonth()!
let endOfMonth = NSDate(month: month, year: year, calendar: calendar).endOfMonth()!
for var date = startOfMonth; date.timeIntervalSince1970 < endOfMonth.timeIntervalSince1970; date = date.dateByAddingDays(1)!
{
csvBuilder.addRow(dateFormatter.stringFromDate(date))
setSessionRow(date, rowIndex: currentRow)
currentRow++
}
}
/*
Sets accumulated times of all sessions into csv rows.
@methodtype Command
@pre -
@post Accumulated times of all sessions are set
*/
private func setSessionRow(date: NSDate, rowIndex: Int)
{
for var columnIndex = 1; columnIndex <= sessions.count; ++columnIndex
{
var accumulatedTime = 0
for session in sessions[columnIndex-1]
{
if calendar.components(.CalendarUnitDay, fromDate: session.startTime).day == calendar.components(.CalendarUnitDay, fromDate: date).day
{
accumulatedTime += (Int(session.endTime.timeIntervalSince1970 - session.startTime.timeIntervalSince1970))/60/60
}
}
csvBuilder.setRowItem(rowIndex, rowItemIndex: columnIndex, rowItem: String(accumulatedTime))
}
}
} | 418513d0b25293b9add17c048c5196be | 30.306748 | 150 | 0.601137 | false | false | false | false |
elationfoundation/Reporta-iOS | refs/heads/master | IWMF/TableViewCell/CheckInDetailTableViewCell.swift | gpl-3.0 | 1 | //
// CheckInLocationTableViewCell.swift
// IWMF
//
//
//
//
import Foundation
import UIKit
class CheckInDetailTableViewCell: UITableViewCell, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
var identity : String! = ""
var value : NSString! = ""
var title : String! = ""
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func intialize()
{
textView.selectable = false
if value != nil{
if value.length > 0{
self.textView.text = value as String
self.textView.textColor = UIColor.blackColor()
}else{
self.textView.text = title
self.textView.textColor = UIColor.lightGrayColor()
}
}else{
self.textView.text = title
self.textView.textColor = UIColor.lightGrayColor()
}
self.textView.font = Utility.setFont()
}
func textViewDidBeginEditing(textView: UITextView)
{
}
func textViewDidEndEditing(textView: UITextView)
{
}
} | 205a5451f3203dcfc2e295b42ff2187b | 23.96 | 75 | 0.573376 | false | false | false | false |
LNTUORG/LntuOnline-iOS-Swift | refs/heads/master | eduadmin/ShowWebViewController.swift | gpl-2.0 | 1 | //
// ShowWebViewController.swift
// eduadmin
//
// Created by Li Jie on 10/20/15.
// Copyright © 2015 PUPBOSS. All rights reserved.
//
import UIKit
class ShowWebViewController: UIViewController, UIWebViewDelegate {
var webUrl = ""
// MARK: - Outlets
@IBOutlet weak var goBackButton: UIBarButtonItem!
@IBOutlet weak var goNextButton: UIBarButtonItem!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var actionButton: UIBarButtonItem!
// MARK: - Actions
@IBAction func goBack(sender: UIBarButtonItem) {
self.webView.goBack()
}
@IBAction func goNext(sender: UIBarButtonItem) {
self.webView.goForward()
}
@IBAction func goToSafari(sender: UIBarButtonItem) {
}
override func viewDidLoad() {
super.viewDidLoad()
self.webView.loadRequest(NSURLRequest.init(URL: NSURL.init(string: self.webUrl)!))
if self.webUrl == Constants.NOTICE_URL {
self.actionButton.enabled = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print(error)
}
func webViewDidStartLoad(webView: UIWebView) {
if self.webUrl == Constants.NOTICE_URL {
MBProgressHUD.showMessage("点击右上角用 Safari 访问")
} else {
if self.webView.canGoBack {
self.goBackButton.enabled = true
} else {
self.goBackButton.enabled = false
}
if self.webView.canGoForward {
self.goNextButton.enabled = true
} else {
self.goNextButton.enabled = false
}
MBProgressHUD.showMessage(Constants.Notification.LOADING)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
MBProgressHUD.hideHUD()
}
}
}
func webViewDidFinishLoad(webView: UIWebView) {
MBProgressHUD.hideHUD()
}
}
| bd0c7c0aa14496a855f015ef7334fb9c | 23.515152 | 130 | 0.548826 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | WMF Framework/CacheController.swift | mit | 1 | import Foundation
public enum CacheControllerError: Error {
case unableToCreateBackgroundCacheContext
case atLeastOneItemFailedInFileWriter(Error)
case failureToGenerateItemResult
case atLeastOneItemFailedInSync(Error)
}
public class CacheController {
#if TEST
public static var temporaryCacheURL: URL? = nil
#endif
static let cacheURL: URL = {
#if TEST
if let temporaryCacheURL = temporaryCacheURL {
return temporaryCacheURL
}
#endif
var url = FileManager.default.wmf_containerURL().appendingPathComponent("Permanent Cache", isDirectory: true)
var values = URLResourceValues()
values.isExcludedFromBackup = true
do {
try url.setResourceValues(values)
} catch {
return url
}
return url
}()
// todo: Settings hook, logout don't sync hook, etc.
public static var totalCacheSizeInBytes: Int64 {
return FileManager.default.sizeOfDirectory(at: cacheURL)
}
/// Performs any necessary migrations on the CacheController's internal storage
static func setupCoreDataStack(_ completion: @escaping (NSManagedObjectContext?, CacheControllerError?) -> Void) {
// Expensive file & db operations happen as a part of this migration, so async it to a non-main queue
DispatchQueue.global(qos: .default).async {
// Instantiating the moc will perform the migrations in CacheItemMigrationPolicy
guard let moc = createCacheContext(cacheURL: cacheURL) else {
completion(nil, .unableToCreateBackgroundCacheContext)
return
}
// do a moc.perform in case anything else needs to be run before the context is ready
moc.perform {
DispatchQueue.main.async {
completion(moc, nil)
}
}
}
}
static func createCacheContext(cacheURL: URL) -> NSManagedObjectContext? {
// create cacheURL directory
do {
try FileManager.default.createDirectory(at: cacheURL, withIntermediateDirectories: true, attributes: nil)
} catch let error {
assertionFailure("Error creating permanent cache: \(error)")
return nil
}
// create ManagedObjectModel based on Cache.momd
guard let modelURL = Bundle.wmf.url(forResource: "Cache", withExtension: "momd"),
let model = NSManagedObjectModel(contentsOf: modelURL) else {
assertionFailure("Failure to create managed object model")
return nil
}
// create persistent store coordinator / persistent store
let dbURL = cacheURL.appendingPathComponent("Cache.sqlite", isDirectory: false)
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
let options = [
NSMigratePersistentStoresAutomaticallyOption: NSNumber(booleanLiteral: true),
NSInferMappingModelAutomaticallyOption: NSNumber(booleanLiteral: true)
]
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: options)
} catch {
do {
try FileManager.default.removeItem(at: dbURL)
} catch {
assertionFailure("Failure to remove old db file")
}
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: options)
} catch {
assertionFailure("Failure to add persistent store to coordinator")
return nil
}
}
let cacheBackgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
cacheBackgroundContext.persistentStoreCoordinator = persistentStoreCoordinator
return cacheBackgroundContext
}
public typealias ItemKey = String
public typealias GroupKey = String
public typealias UniqueKey = String // combo of item key + variant
public typealias IndividualCompletionBlock = (FinalIndividualResult) -> Void
public typealias GroupCompletionBlock = (FinalGroupResult) -> Void
public struct ItemKeyAndVariant: Hashable {
let itemKey: CacheController.ItemKey
let variant: String?
init?(itemKey: CacheController.ItemKey?, variant: String?) {
guard let itemKey = itemKey else {
return nil
}
self.itemKey = itemKey
self.variant = variant
}
}
public enum FinalIndividualResult {
case success(uniqueKey: CacheController.UniqueKey)
case failure(error: Error)
}
public enum FinalGroupResult {
case success(uniqueKeys: [CacheController.UniqueKey])
case failure(error: Error)
}
let dbWriter: CacheDBWriting
let fileWriter: CacheFileWriter
let gatekeeper = CacheGatekeeper()
init(dbWriter: CacheDBWriting, fileWriter: CacheFileWriter) {
self.dbWriter = dbWriter
self.fileWriter = fileWriter
}
public func add(url: URL, groupKey: GroupKey, individualCompletion: @escaping IndividualCompletionBlock, groupCompletion: @escaping GroupCompletionBlock) {
if gatekeeper.shouldQueueAddCompletion(groupKey: groupKey) {
gatekeeper.queueAddCompletion(groupKey: groupKey) {
self.add(url: url, groupKey: groupKey, individualCompletion: individualCompletion, groupCompletion: groupCompletion)
return
}
} else {
gatekeeper.addCurrentlyAddingGroupKey(groupKey)
}
if gatekeeper.numberOfQueuedGroupCompletions(for: groupKey) > 0 {
gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion)
return
}
gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion)
dbWriter.add(url: url, groupKey: groupKey) { [weak self] (result) in
self?.finishDBAdd(groupKey: groupKey, individualCompletion: individualCompletion, groupCompletion: groupCompletion, result: result)
}
}
public func cancelTasks(groupKey: String) {
dbWriter.cancelTasks(for: groupKey)
fileWriter.cancelTasks(for: groupKey)
}
public func cancelAllTasks() {
dbWriter.cancelAllTasks()
fileWriter.cancelAllTasks()
}
func shouldDownloadVariantForAllVariantItems(variant: String?, _ allVariantItems: [CacheController.ItemKeyAndVariant]) -> Bool {
return dbWriter.shouldDownloadVariantForAllVariantItems(variant: variant, allVariantItems)
}
func finishDBAdd(groupKey: GroupKey, individualCompletion: @escaping IndividualCompletionBlock, groupCompletion: @escaping GroupCompletionBlock, result: CacheDBWritingResultWithURLRequests) {
let groupCompleteBlock = { (groupResult: FinalGroupResult) in
self.gatekeeper.runAndRemoveGroupCompletions(groupKey: groupKey, groupResult: groupResult)
self.gatekeeper.removeCurrentlyAddingGroupKey(groupKey)
self.gatekeeper.runAndRemoveQueuedRemoves(groupKey: groupKey)
}
switch result {
case .success(let urlRequests):
var successfulKeys: [CacheController.UniqueKey] = []
var failedKeys: [(CacheController.UniqueKey, Error)] = []
let group = DispatchGroup()
for urlRequest in urlRequests {
guard let uniqueKey = fileWriter.uniqueFileNameForURLRequest(urlRequest),
let url = urlRequest.url else {
continue
}
group.enter()
if gatekeeper.numberOfQueuedIndividualCompletions(for: uniqueKey) > 0 {
defer {
group.leave()
}
gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion)
continue
}
gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion)
guard dbWriter.shouldDownloadVariant(urlRequest: urlRequest) else {
group.leave()
continue
}
fileWriter.add(groupKey: groupKey, urlRequest: urlRequest) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let response, let data):
self.dbWriter.markDownloaded(urlRequest: urlRequest, response: response) { (result) in
defer {
group.leave()
}
let individualResult: FinalIndividualResult
switch result {
case .success:
successfulKeys.append(uniqueKey)
individualResult = FinalIndividualResult.success(uniqueKey: uniqueKey)
case .failure(let error):
failedKeys.append((uniqueKey, error))
individualResult = FinalIndividualResult.failure(error: error)
}
self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult)
}
self.finishFileSave(data: data, mimeType: response.mimeType, uniqueKey: uniqueKey, url: url)
case .failure(let error):
defer {
group.leave()
}
failedKeys.append((uniqueKey, error))
let individualResult = FinalIndividualResult.failure(error: error)
self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult)
}
}
group.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
let groupResult: FinalGroupResult
if let error = failedKeys.first?.1 {
groupResult = FinalGroupResult.failure(error: CacheControllerError.atLeastOneItemFailedInFileWriter(error))
} else {
groupResult = FinalGroupResult.success(uniqueKeys: successfulKeys)
}
groupCompleteBlock(groupResult)
}
}
case .failure(let error):
let groupResult = FinalGroupResult.failure(error: error)
groupCompleteBlock(groupResult)
}
}
func finishFileSave(data: Data, mimeType: String?, uniqueKey: CacheController.UniqueKey, url: URL) {
// hook to allow subclasses to do any additional work with data
}
public func remove(groupKey: GroupKey, individualCompletion: @escaping IndividualCompletionBlock, groupCompletion: @escaping GroupCompletionBlock) {
if gatekeeper.shouldQueueRemoveCompletion(groupKey: groupKey) {
gatekeeper.queueRemoveCompletion(groupKey: groupKey) {
self.remove(groupKey: groupKey, individualCompletion: individualCompletion, groupCompletion: groupCompletion)
return
}
} else {
gatekeeper.addCurrentlyRemovingGroupKey(groupKey)
}
if gatekeeper.numberOfQueuedGroupCompletions(for: groupKey) > 0 {
gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion)
return
}
gatekeeper.queueGroupCompletion(groupKey: groupKey, groupCompletion: groupCompletion)
cancelTasks(groupKey: groupKey)
let groupCompleteBlock = { (groupResult: FinalGroupResult) in
self.gatekeeper.runAndRemoveGroupCompletions(groupKey: groupKey, groupResult: groupResult)
self.gatekeeper.removeCurrentlyRemovingGroupKey(groupKey)
self.gatekeeper.runAndRemoveQueuedAdds(groupKey: groupKey)
}
dbWriter.fetchKeysToRemove(for: groupKey) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let keys):
var successfulKeys: [CacheController.UniqueKey] = []
var failedKeys: [(CacheController.UniqueKey, Error)] = []
let group = DispatchGroup()
for key in keys {
guard let uniqueKey = self.fileWriter.uniqueFileNameForItemKey(key.itemKey, variant: key.variant) else {
continue
}
group.enter()
if self.gatekeeper.numberOfQueuedIndividualCompletions(for: uniqueKey) > 0 {
defer {
group.leave()
}
self.gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion)
continue
}
self.gatekeeper.queueIndividualCompletion(uniqueKey: uniqueKey, individualCompletion: individualCompletion)
self.fileWriter.remove(itemKey: key.itemKey, variant: key.variant) { (result) in
switch result {
case .success:
self.dbWriter.remove(itemAndVariantKey: key) { (result) in
defer {
group.leave()
}
var individualResult: FinalIndividualResult
switch result {
case .success:
successfulKeys.append(uniqueKey)
individualResult = FinalIndividualResult.success(uniqueKey: uniqueKey)
case .failure(let error):
failedKeys.append((uniqueKey, error))
individualResult = FinalIndividualResult.failure(error: error)
}
self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult)
}
case .failure(let error):
failedKeys.append((uniqueKey, error))
let individualResult = FinalIndividualResult.failure(error: error)
self.gatekeeper.runAndRemoveIndividualCompletions(uniqueKey: uniqueKey, individualResult: individualResult)
group.leave()
}
}
}
group.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
if let error = failedKeys.first?.1 {
let groupResult = FinalGroupResult.failure(error: CacheControllerError.atLeastOneItemFailedInFileWriter(error))
groupCompleteBlock(groupResult)
return
}
self.dbWriter.remove(groupKey: groupKey, completion: { (result) in
var groupResult: FinalGroupResult
switch result {
case .success:
groupResult = FinalGroupResult.success(uniqueKeys: successfulKeys)
case .failure(let error):
groupResult = FinalGroupResult.failure(error: error)
}
groupCompleteBlock(groupResult)
})
}
case .failure(let error):
let groupResult = FinalGroupResult.failure(error: error)
groupCompleteBlock(groupResult)
}
}
}
}
| 65592013729e25965b3bcce162bd6434 | 40.958025 | 195 | 0.568587 | false | false | false | false |
pulsarSMB/TagView | refs/heads/master | TagView/Classes/TagButton.swift | mit | 1 | //
// TagButton.swift
// TagViewDemo
//
// Created by pulsar on 08.09.17.
// Copyright © 2017 pulsar. All rights reserved.
//
import UIKit
public class TagButton: UIButton {
var style: ButtonStyles? {
didSet { oldValue != nil ? setStyle() : nil }
}
convenience init(title: String, style: ButtonStyles) {
self.init(type: .system)
self.style = style
self.setTitle(title, for: .normal)
}
public override func setTitle(_ title: String?, for state: UIControlState) {
super.setTitle(title, for: state)
setStyle()
}
private func setStyle() {
guard let style = style else { return }
self.backgroundColor = style.backgroundColor
self.tintColor = style.tintColor
self.titleLabel?.font = style.titleFont
self.sizeToFit()
self.frame.size.height = (self.titleLabel?.font.pointSize)! + style.margin
let radius = self.frame.height * 0.5 * style.percentCornerRadius
self.layer.masksToBounds = true
self.layer.cornerRadius = radius
self.frame.size.width += radius + style.margin
}
}
| 806baf653ab44e88ed9983b261232c56 | 22.933333 | 78 | 0.666667 | false | false | false | false |
MetalheadSanya/GtkSwift | refs/heads/master | src/AssistantPageType.swift | bsd-3-clause | 1 | //
// AssistantPageType.swift
// GTK-swift
//
// Created by Alexander Zalutskiy on 13.04.16.
//
//
import CGTK
public enum AssistantPageType: RawRepresentable {
case Content, Intro, Confirm, Summary, Progress, Custom
public typealias RawValue = GtkAssistantPageType
public var rawValue: RawValue {
switch self {
case .Content:
return GTK_ASSISTANT_PAGE_CONTENT
case .Intro:
return GTK_ASSISTANT_PAGE_INTRO
case .Confirm:
return GTK_ASSISTANT_PAGE_CONFIRM
case .Summary:
return GTK_ASSISTANT_PAGE_SUMMARY
case .Progress:
return GTK_ASSISTANT_PAGE_PROGRESS
case .Custom:
return GTK_ASSISTANT_PAGE_CUSTOM
}
}
public init?(rawValue: RawValue) {
switch rawValue {
case GTK_ASSISTANT_PAGE_CONTENT:
self = .Content
case GTK_ASSISTANT_PAGE_INTRO:
self = .Intro
case GTK_ASSISTANT_PAGE_CONFIRM:
self = .Confirm
case GTK_ASSISTANT_PAGE_SUMMARY:
self = .Summary
case GTK_ASSISTANT_PAGE_PROGRESS:
self = .Progress
case GTK_ASSISTANT_PAGE_CUSTOM:
self = .Custom
default:
return nil
}
}
}
| e19b71a0bababb0e5fb3e052b70d095f | 19.882353 | 56 | 0.709859 | false | false | false | false |
Incipia/Goalie | refs/heads/master | Goalie/GoalieAccessory.swift | apache-2.0 | 1 | //
// GoalieAccessory.swift
// Goalie
//
// Created by Gregory Klein on 3/28/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import Foundation
enum GoalieAccessory
{
case bricks, weight, jumprope, waterBottle, clock, plant, soda, homeWindow, workClock, computer, lamp, workWindow, unknown
func drawRect(_ frame: CGRect, priority: TaskPriority)
{
switch self {
case .bricks: BricksAccessoryKit.drawWithFrame(frame, priority: priority)
case .weight: WeightAccessoryKit.drawWithFrame(frame, priority: priority)
case .jumprope: JumpropeAccessoryKit.drawWithFrame(frame, priority: priority)
case .waterBottle: WaterBottleAccessoryKit.drawWithFrame(frame, priority: priority)
case .clock: ClockAccessoryKit.drawWithFrame(frame, priority: priority)
case .plant: PlantAccessoryKit.drawWithFrame(frame, priority: priority)
case .soda: SodaAccessoryKit.drawWithFrame(frame, priority: priority)
case .homeWindow: HomeWindowAccessoryKit.drawWithFrame(frame, priority: priority)
case .workClock: WorkClockAccessoryKit.drawWithFrame(frame, priority: priority)
case .computer: ComputerAccessoryKit.drawWithFrame(frame, priority: priority)
case .lamp: LampAccessoryKit.drawWithFrame(frame, priority: priority)
case .workWindow: WorkWindowAccessoryKit.drawWithFrame(frame, priority: priority)
case .unknown: _drawPurpleRect(frame)
}
}
fileprivate func _drawPurpleRect(_ rect: CGRect)
{
UIColor.purple.setFill()
UIRectFill(rect)
}
}
extension CGSize
{
init(accessory: GoalieAccessory)
{
var size: (w: Int, h: Int)
switch accessory
{
case .bricks: size = (79, 40)
case .weight: size = (60, 30)
case .jumprope: size = (36, 58)
case .waterBottle: size = (22, 40)
case .clock: size = (42, 44)
case .plant: size = (26, 54)
case .soda: size = (22, 36)
case .homeWindow: size = (58, 56)
case .workClock: size = (42, 42)
case .computer: size = (70, 39)
case .lamp: size = (42, 48)
case .workWindow: size = (77, 50)
case .unknown: size = (100, 100)
}
self.init(width: size.w, height: size.h)
}
}
| c8fac30c82e88ccb506f0f4579bc5c3b | 33.890625 | 125 | 0.673533 | false | false | false | false |
LFL2018/swiftSmpleCode | refs/heads/master | playground_Code/MapAndFlatMap.playground/Contents.swift | mit | 1 | // 6.12 2016 LFL
//map 和 flatMap
//:swift3后,将flatten()重命名为joined()
import UIKit
/// map
let numberArrarys = [1,2,3,4,5,6]
let resultNumbers = numberArrarys.map { $0 + 2}
/**
* @brief map 方法接受一个闭包作为参数, 然后它会遍历整个 numbers 数组,并对数组中每一个元素执行闭包中定义的操作。 相当于对数组中的所有元素做了一个映射
func map<T>(transform: (Self.Generator.Element) -> T) rethrows -> [T]
Self.Generator.Element :当前元素的类型
注意:这个闭包的返回值,是可以和传递进来的值不同
*/
print("map latter\(resultNumbers)")
let resultString = numberArrarys.map { "LFL->\($0)" }
print(resultString)
// resultString.dynamicType // String数组
///flatMap
let flatNumber = numberArrarys.flatMap{$0 + 2}
print(flatNumber) // 和map一样
// 区别
let numbersCompound = [[1,2,3],[4,5,6]];
var res = numbersCompound.map { $0.map{ $0 + 2 } }
/**
这个调用实际上是遍历了这里两个数组元素 [1,2,3] 和 [4,5,6]。 因为这两个元素依然是数组,所以我们可以对他们再次调用 map 函数:$0.map{ $0 + 2 }。 这个内部的调用最终将数组中所有的元素加 2
*/
// [[3, 4, 5], [6, 7, 8]]
var flatRes = numbersCompound.flatMap { $0.map{ $0 + 2 } }
/**
flatMap 依然会遍历数组的元素,并对这些元素执行闭包中定义的操作。 但唯一不同的是,它对最终的结果进行了所谓的 "降维" 操作。 本来原始数组是一个二维的, 但经过 flatMap 之后,它变成一维的了。
*/
// [3, 4, 5, 6, 7, 8] 降为一唯数组
/**
1.和 map 不同, flatMap 有两个重载
func flatMap<S : SequenceType>(transform: (Self.Generator.Element) -> S) -> [S.Generator.Element]
flatMap的闭包接受的是数组的元素,但返回SequenceType 类型,也就是另外一个数组。
我们传入给 flatMap 一个闭包 $0.map{ $0 + 2 } , 这个闭包中,又对 $0 调用了 map 方法, 从 map 方法的定义中我们能够知道,它返回的还是一个集合类型,也就是 SequenceType。 所以我们这个 flatMap 的调用对应的就是第二个重载形式
*/
//查阅源码
/**
文件位置: swift/stdlib/public/core/SequenceAlgorithms.swift.gyb
extension Sequence {
public func flatMap<S : Sequence>(
@noescape transform: (${GElement}) throws -> S
) rethrows -> [S.${GElement}] {
var result: [S.${GElement}] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
1.对遍历的每一个元素调用try transform(element)。 transform 函数就是我们传递进来的闭包
2.然后将闭包的返回值通过 result.append(contentsOf:) 函数添加到 result 数组中。
2.1 名词简单说就是将一个集合中的所有元素,添加到另一个集合。
}
*/
// 2 func flatMap<T>(transform: (Self.Generator.Element) -> T?) -> [T]
/**
它的闭包接收的是 Self.Generator.Element 类型, 返回的是一个 T? 。 我们都知道,在 Swift 中类型后面跟随一个 ?, 代表的是 Optional 值。 也就是说这个重载中接收的闭包返回的是一个 Optional 值。 更进一步来说,就是闭包可以返回 nil
*/
let optionalArray: [String?] = ["AA", nil, "BB", "CC"];
var optionalResult = optionalArray.flatMap{ $0 }
// ["AA", "BB", "CC"]
//而使用 print 函数输出 flatMap 的结果集时,会得到这样的输出:
//["AA", "BB", "CC"]
//也就是说原始数组的类型是 [String?] 而 flatMap 调用后变成了 [String]。 这也是 flatMap 和 map 的一个重大区别
//适用;过滤无效数据
var imageNames = ["1.png", "2.png", "nil.png"];
imageNames.flatMap{ UIImage(named: $0) }
//查阅源码
/**
* 依然是遍历所有元素,并应用 try transform(element) 闭包的调用, 但关键一点是,这里面用到了 if let 语句, 对那些只有解包成功的元素,才会添加到结果集中:
if let newElement = try transform(element) {
result.append(newElement)
}
*/
//
let numbers_1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let joined = numbers_1.joined(separator: [-1, -2])
print(Array(joined))
| ca3566ab001f08126828910dcecd88c4 | 26.198113 | 145 | 0.677072 | false | false | false | false |
ustwo/mongolabkit-swift | refs/heads/master | MongoLabKit/MongoLabKitTests/DocumentsServiceTests.swift | mit | 1 | //
// MongoLabKitTests.swift
// MongoLabKitTests
//
// Created by luca strazzullo on 18/05/16.
//
//
import XCTest
@testable import MongoLabKit
class MongoLabKit_DocumentsService_iOSTests: XCTestCase {
private var service: DocumentsService?
func testLoadDocuments() {
let mockConfiguration = MongoLabApiV1Configuration(databaseName: "fakeName", apiKey: "fakeApiKey")
let response = [["_id": ["$oid": "5743ab370a00b27cd1d10c92"]]]
let mockResult = MongoLabClient.Result.success(response: response as AnyObject)
loadDocumentsWithMongoLab(mockResult: mockResult, configuration: mockConfiguration) {
result in
switch result {
case let .Success(response):
XCTAssertEqual(response.first?.id, "5743ab370a00b27cd1d10c92")
case let .Failure(error):
XCTFail(error.description())
}
}
}
func testLoadDocumentsWithParsingError() {
let mockConfiguration = MongoLabApiV1Configuration(databaseName: "fakeName", apiKey: "fakeApiKey")
let response = [["$oid": "5743ab370a00b27cd1d10c92"]]
let mockResult = MongoLabClient.Result.success(response: response as AnyObject)
loadDocumentsWithMongoLab(mockResult: mockResult, configuration: mockConfiguration) {
result in
switch result {
case .Success:
XCTFail()
case let .Failure(error):
XCTAssertEqual(error.description(), MongoLabError.parserError.description())
}
}
}
func testLoadDocumentsWithConfigurationError() {
let mockConfiguration = MongoLabApiV1Configuration(databaseName: "", apiKey: "")
let response = [["$oid": "5743ab370a00b27cd1d10c92"]]
let mockResult = MongoLabClient.Result.success(response: response as AnyObject)
loadDocumentsWithMongoLab(mockResult: mockResult, configuration: mockConfiguration) {
result in
switch result {
case .Success:
XCTFail()
case let .Failure(error):
XCTAssertEqual(error.description(), RequestError.configuration.description())
}
}
}
// MARK: - Private helper methods
private func loadDocumentsWithMongoLab(mockResult: MongoLabClient.Result, configuration: MongoLabApiV1Configuration, completion: @escaping MockDocumentServiceDelegate.Completion) {
let asynchronousExpectation = expectation(description: "asynchronous")
let mockClient = MockMongoLabClient(result: mockResult)
let mockDelegate = MockDocumentServiceDelegate() {
result in
asynchronousExpectation.fulfill()
completion(result)
}
loadDocumentsWith(client: mockClient, configuration: configuration, delegate: mockDelegate)
waitForExpectations(timeout: 10, handler: nil)
}
private func loadDocumentsWith(client: MongoLabClient, configuration: MongoLabApiV1Configuration, delegate: ServiceDelegate) {
service = DocumentsService(client: client, configuration: configuration, delegate: delegate)
service?.loadDocuments(for: "collection")
}
// MARK: - Mocked client
private class MockMongoLabClient: MongoLabClient {
var result: MongoLabClient.Result
init (result: MongoLabClient.Result) {
self.result = result
}
override func perform(_ request: URLRequest, completion: @escaping MongoLabClient.Completion) -> URLSessionTask {
completion(result)
return URLSessionTask()
}
}
// MARK: - Mocked delegate
class MockDocumentServiceDelegate: ServiceDelegate {
enum Result {
case Success(response: Documents)
case Failure(error: ErrorDescribable)
}
typealias Completion = (_ result: Result) -> ()
let completion: Completion
func serviceWillLoad<DataType>(_ service: Service<DataType>) {}
func service<DataType>(_ service: Service<DataType>, didLoad data: DataType) {
if let documents = data as? Documents {
completion(Result.Success(response: documents))
}
}
func service<DataType>(_ service: Service<DataType>, didFailWith error: ErrorDescribable) {
completion(Result.Failure(error: error))
}
init(completion: @escaping Completion) {
self.completion = completion
}
}
}
| 3661b0aead5ae64ee3439da1235bdcfd | 27.8125 | 184 | 0.641432 | false | true | false | false |
carping/Postal | refs/heads/master | Postal/Libetpan+Util.swift | mit | 1 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 Snips
//
// 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
import libetpan
extension String {
static func fromZeroSizedCStringMimeHeader(_ bytes: UnsafeMutablePointer<Int8>?) -> String? {
guard bytes != nil else { return nil }
let length = Int(strlen(bytes))
return fromCStringMimeHeader(bytes, length: length)
}
static func fromCStringMimeHeader(_ bytes: UnsafeMutablePointer<Int8>?, length: Int) -> String? {
let DEFAULT_INCOMING_CHARSET = "iso-8859-1"
let DEFAULT_DISPLAY_CHARSET = "utf-8"
guard let bytes = bytes, bytes[0] != 0 else { return nil }
var hasEncoding = false
if strstr(bytes, "=?") != nil {
if strcasestr(bytes, "?Q?") != nil || strcasestr(bytes, "?B?") != nil {
hasEncoding = true
}
}
if !hasEncoding {
return String.stringFromCStringDetectingEncoding(bytes, length: length)?.string
}
var decoded: UnsafeMutablePointer<CChar>? = nil
var cur_token: size_t = 0
mailmime_encoded_phrase_parse(DEFAULT_INCOMING_CHARSET, bytes, Int(strlen(bytes)), &cur_token, DEFAULT_DISPLAY_CHARSET, &decoded)
defer { free(decoded) }
guard let actuallyDecoded = decoded else { return nil }
return String.fromUTF8CString(actuallyDecoded)
}
}
// MARK: Sequences
extension Sequence {
func unreleasedClist<T>(_ transferOwnership: (Iterator.Element) -> UnsafeMutablePointer<T>) -> UnsafeMutablePointer<clist> {
let list = clist_new()
map(transferOwnership).forEach { (item: UnsafeMutablePointer<T>) in
clist_append(list, item)
}
return list!
}
}
private func pointerListGenerator<Element>(unsafeList list: UnsafePointer<clist>, of: Element.Type) -> AnyIterator<UnsafePointer<Element>> {
var current = list.pointee.first?.pointee
return AnyIterator<UnsafePointer<Element>> {
while current != nil && current?.data == nil { // while data is unavailable skip to next
current = current?.next?.pointee
}
guard let cur = current else { return nil } // if iterator is nil, list is over, just finish
defer { current = current?.next?.pointee } // after returning move current to next
return UnsafePointer<Element>(cur.data.assumingMemoryBound(to: Element.self)) // return current data as Element (unsafe: type cannot be checked because of C)
}
}
private func listGenerator<Element>(unsafeList list: UnsafePointer<clist>, of: Element.Type) -> AnyIterator<Element> {
let gen = pointerListGenerator(unsafeList: list, of: of)
return AnyIterator {
return gen.next()?.pointee
}
}
private func arrayGenerator<Element>(unsafeArray array: UnsafePointer<carray>, of: Element.Type) -> AnyIterator<Element> {
var idx: UInt32 = 0
let len = carray_count(array)
return AnyIterator {
guard idx < len else { return nil }
defer { idx = idx + 1 }
return carray_get(array, idx).assumingMemoryBound(to: Element.self).pointee
}
}
func sequence<Element>(_ unsafeList: UnsafePointer<clist>, of: Element.Type) -> AnySequence<Element> {
return AnySequence { return listGenerator(unsafeList: unsafeList, of: of) }
}
func pointerSequence<Element>(_ unsafeList: UnsafePointer<clist>, of: Element.Type) -> AnySequence<UnsafePointer<Element>> {
return AnySequence { return pointerListGenerator(unsafeList: unsafeList, of: of) }
}
func sequence<Element>(_ unsafeArray: UnsafePointer<carray>, of: Element.Type) -> AnySequence<Element> {
return AnySequence { return arrayGenerator(unsafeArray: unsafeArray, of: of) }
}
// MARK: Dates
extension Date {
var unreleasedMailimapDate: UnsafeMutablePointer<mailimap_date>? {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([ .year, .month, .day ], from: self)
guard let day = components.day, let month = components.month, let year = components.year else { return nil }
return mailimap_date_new(Int32(day), Int32(month), Int32(year))
}
}
extension mailimf_date_time {
var date: Date? {
var dateComponent = DateComponents()
dateComponent.calendar = Calendar(identifier: .gregorian)
dateComponent.second = Int(dt_sec)
dateComponent.minute = Int(dt_min)
dateComponent.hour = Int(dt_min)
dateComponent.hour = Int(dt_hour)
dateComponent.day = Int(dt_day)
dateComponent.month = Int(dt_month)
if dt_year < 1000 {
// workaround when century is not given in year
dateComponent.year = Int(dt_year + 2000)
} else {
dateComponent.year = Int(dt_year)
}
let zoneHour: Int
let zoneMin: Int
if dt_zone >= 0 {
zoneHour = Int(dt_zone / 100)
zoneMin = Int(dt_zone % 100)
} else {
zoneHour = Int(-((-dt_zone) / 100))
zoneMin = Int(-((-dt_zone) % 100))
}
dateComponent.timeZone = TimeZone(secondsFromGMT: zoneHour * 3600 + zoneMin * 60)
return dateComponent.date
}
}
extension mailimap_date_time {
var date: Date? {
var dateComponent = DateComponents()
dateComponent.calendar = Calendar(identifier: .gregorian)
dateComponent.second = Int(dt_sec)
dateComponent.minute = Int(dt_min)
dateComponent.hour = Int(dt_min)
dateComponent.hour = Int(dt_hour)
dateComponent.day = Int(dt_day)
dateComponent.month = Int(dt_month)
if dt_year < 1000 {
// workaround when century is not given in year
dateComponent.year = Int(dt_year + 2000)
} else {
dateComponent.year = Int(dt_year)
}
let zoneHour: Int
let zoneMin: Int
if dt_zone >= 0 {
zoneHour = Int(dt_zone / 100)
zoneMin = Int(dt_zone % 100)
} else {
zoneHour = Int(-((-dt_zone) / 100))
zoneMin = Int(-((-dt_zone) % 100))
}
dateComponent.timeZone = TimeZone(secondsFromGMT: zoneHour * 3600 + zoneMin * 60)
return dateComponent.date
}
}
// MARK: Set
extension mailimap_set {
var indexSet: IndexSet {
var result: IndexSet = IndexSet()
sequence(set_list, of: mailimap_set_item.self)
.map { (item: mailimap_set_item) -> CountableClosedRange<Int> in
return Int(item.set_first)...Int(item.set_last)
}
.forEach { (range: CountableClosedRange<Int>) in
result.insert(integersIn: range)
}
return result
}
var array: [Int] {
var result: [Int] = []
sequence(set_list, of: mailimap_set_item.self)
.map { (item: mailimap_set_item) -> CountableClosedRange<Int> in
return Int(item.set_first)...Int(item.set_last)
}
.forEach { (range: CountableClosedRange<Int>) in
result.append(contentsOf: range)
}
return result
}
}
| 8f7e21138a5e58566edf82dfc369be50 | 36.334821 | 165 | 0.627646 | false | false | false | false |
nunosans/currency | refs/heads/master | Currency/UI Classes/CalculatorButton.swift | mit | 1 | //
// CalculatorButton.swift
// Currency
//
// Created by Nuno Coelho Santos on 25/02/2016.
// Copyright © 2016 Nuno Coelho Santos. All rights reserved.
//
import Foundation
import UIKit
class CalculatorButton: UIButton {
let borderColor: CGColor! = UIColor(red:0.85, green:0.85, blue:0.85, alpha:1.00).cgColor
let normalStateColor: CGColor! = UIColor(red:0, green:0, blue:0, alpha:0).cgColor
let highlightStateColor: CGColor! = UIColor(red:0, green:0, blue:0, alpha:0.08).cgColor
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.layer.borderWidth = 0.25
self.layer.borderColor = borderColor
self.layer.masksToBounds = true
self.backgroundColor = UIColor(cgColor: normalStateColor)
}
override var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
if newValue {
let fadeIn = CABasicAnimation(keyPath: "backgroundColor")
fadeIn.fromValue = normalStateColor
fadeIn.toValue = highlightStateColor
fadeIn.duration = 0.12
fadeIn.autoreverses = false
fadeIn.repeatCount = 1
self.layer.add(fadeIn, forKey: "fadeIn")
self.backgroundColor = UIColor(cgColor: highlightStateColor)
}
else {
let fadeOut = CABasicAnimation(keyPath: "backgroundColor")
fadeOut.fromValue = highlightStateColor
fadeOut.toValue = normalStateColor
fadeOut.duration = 0.12
fadeOut.autoreverses = false
fadeOut.repeatCount = 1
self.layer.add(fadeOut, forKey: "fadeOut")
self.backgroundColor = UIColor(cgColor: normalStateColor)
}
super.isHighlighted = newValue
}
}
}
| 9f6c9e13d1b8f2d21459a10b9e80a990 | 32.305085 | 92 | 0.581679 | false | false | false | false |
JasonPan/ADSSocialFeedScrollView | refs/heads/master | ADSSocialFeedScrollView/Providers/Facebook/Data/FacebookPage.swift | mit | 1 | //
// FacebookPage.swift
// ADSSocialFeedScrollView
//
// Created by Jason Pan on 13/02/2016.
// Copyright © 2016 ANT Development Studios. All rights reserved.
//
import UIKit
import FBSDKCoreKit
class FacebookPage: PostCollectionProtocol {
private(set) var id : String!
private(set) var name : String!
private(set) var profilePhotoURL : String!
private(set) var coverPhotoURL : String!
var feed : Array<FacebookPost>!
//*********************************************************************************************************
// MARK: - Constructors
//*********************************************************************************************************
init(id: String) {
self.id = id
}
//*********************************************************************************************************
// MARK: - Data retrievers
//*********************************************************************************************************
func fetchProfileInfoInBackgroundWithCompletionHandler(block: (() -> Void)?) {
//SIDENOTE: Facebook iOS SDK requires requests to be sent from main queue?? Bug?
dispatch_async(dispatch_get_main_queue(), {
FBSDKGraphRequest.init(graphPath: self.id, parameters: ["access_token": ADSSocialFeedFacebookAccountProvider.authKey, "fields": "name, picture, cover"]).startWithCompletionHandler({
connection, result, error in
if error == nil {
if let dictionary = result as? Dictionary<String, AnyObject> {
let name = dictionary["name"] as? String
let picture = dictionary["picture"]?["data"]??["url"] as? String
let cover = dictionary["cover"]?["source"] as? String
self.name = name
self.profilePhotoURL = picture
self.coverPhotoURL = cover
}
}else {
NSLog("[ADSSocialFeedScrollView][Facebook] An error occurred while fetching profile info: \(error?.description)");
}
self.fetchPostsInBackgroundWithCompletionHandler(block)
})
})
}
private func fetchPostsInBackgroundWithCompletionHandler(block: (() -> Void)?) {
//SIDENOTE: Facebook iOS SDK requires requests to be sent from main queue?? Bug?
dispatch_async(dispatch_get_main_queue(), {
FBSDKGraphRequest.init(graphPath: self.id + "/posts", parameters: ["access_token": ADSSocialFeedFacebookAccountProvider.authKey, "fields": "created_time, id, message, picture, attachments"]).startWithCompletionHandler({
connection, result, error in
if error == nil {
let JSON_data: Dictionary<String, AnyObject>? = result as? Dictionary<String, AnyObject>
guard JSON_data != nil else {
return
}
if let feedData_JSON: Array<Dictionary<String, AnyObject>> = JSON_data?["data"] as? Array<Dictionary<String, AnyObject>> {
var feedArray: Array<FacebookPost> = Array<FacebookPost>()
for dictionary in feedData_JSON {
let id = dictionary["id"] as? String
let created_time = dictionary["created_time"] as? String
let message = dictionary["message"] as? String
var picture = dictionary["picture"] as? String
if let attachments = dictionary["attachments"] as? NSDictionary {
if let data = attachments["data"] as? NSArray {
if let media = data[0]["media"] as? NSDictionary {
if let image = media["image"] {
if let src = image["src"] as? String {
picture = src
}
}
}
}
}
let facebookPost: FacebookPost = FacebookPost(id: id!, createdTime: created_time!, message: message, image: picture, owner: self)
feedArray.append(facebookPost)
}
self.feed = feedArray
}
}else {
NSLog("[ADSSocialFeedScrollView][Facebook] An error occurred while fetching posts: \(error?.description)");
self.feed = Array<FacebookPost>()
}
block?()
})
})
}
//*********************************************************************************************************
// MARK: - PostCollectionProtocol
//*********************************************************************************************************
var postItems: [PostProtocol]? {
// See: https://stackoverflow.com/a/30101004/699963
return self.feed.map({ $0 as PostProtocol })
}
}
| f2ea63c47b13a7e1d3603cb7b79ef02a | 46.35 | 231 | 0.421331 | false | false | false | false |
agconti/good-as-old-phones | refs/heads/master | GoodAsOldPhones/ProductsTableViewController.swift | mit | 1 | //
// ProductsTableViewController.swift
// GoodAsOldPhones
//
// Created by Andrew Conti on 1/14/16.
// Copyright © 2016 agconit. All rights reserved.
//
import UIKit
class ProductsTableViewController: UITableViewController {
let productCellIdentifier: String = "ProductCell"
let numVisibleCells: Int = 5
var products: [Product]?
override func viewDidLoad() {
super.viewDidLoad()
products = [ Product(name: "1927 Hand Dial Phone", productImage: "phone-fullscreen1", cellImage: "image-cell1")
, Product(name: "1950 Office Phone", productImage: "phone-fullscreen2", cellImage: "image-cell2")
, Product(name: "1980 Car Phone", productImage: "phone-fullscreen3", cellImage: "image-cell3")
, Product(name: "1940 Military Phone", productImage: "phone-fullscreen4", cellImage: "image-cell4")
]
}
override func tableView(tabelView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let products = products {
return products.count
}
return 0
}
override func tableView(tabelView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(productCellIdentifier, forIndexPath: indexPath)
let product = products?[indexPath.row]
cell.textLabel?.text = product?.name
if let cellImage = product?.cellImage{
cell.imageView?.image = UIImage(named: cellImage)
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowProduct" {
guard let vc = segue.destinationViewController as? ProductViewController,
let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPathForCell(cell) else {
return
}
vc.product = products?[indexPath.row]
}
}
}
| 9e474e67a48b853caaf79fbb1199422f | 32.65625 | 120 | 0.607242 | false | false | false | false |
ElectricWizardry/iSub | refs/heads/master | Classes/StoreViewController.swift | gpl-3.0 | 2 | //
// StoreViewController.swift
// iSub
//
// Created by Ben Baron on 12/15/10.
// Copyright 2010 Ben Baron. All rights reserved.
//
import Foundation
import UIKit
public class StoreViewController : CustomUITableViewController {
private lazy var _appDelegate = iSubAppDelegate.sharedInstance()
private let _settings = SavedSettings.sharedInstance()
private let _viewObjects = ViewObjectsSingleton.sharedInstance()
private let _reuseIdentifier = "Store Cell"
private let _storeManager: MKStoreManager = MKStoreManager.sharedManager()
private var _storeItems: [AnyObject] = MKStoreManager.sharedManager().purchasableObjects
private var _checkProductsTimer: NSTimer?
// MARK: - Rotation -
public override func shouldAutorotate() -> Bool {
if _settings.isRotationLockEnabled && UIDevice.currentDevice().orientation != UIDeviceOrientation.Portrait {
return false
}
return true
}
public override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
self.tableView.reloadData()
}
// MARK: - LifeCycle -
public override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "_storePurchaseComplete:", name: ISMSNotification_StorePurchaseComplete, object: nil)
if _storeItems.count == 0 {
_viewObjects.showAlbumLoadingScreen(_appDelegate.window, sender: self)
self._checkProductsTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "a_checkProducts", userInfo: nil, repeats: true)
self.a_checkProducts(nil)
} else {
self._organizeList()
self.tableView.reloadData()
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ISMSNotification_StorePurchaseComplete, object: nil)
}
// MARK: - Notifications -
func _storePurchaseComplete(notification: NSNotification?) {
self.tableView.reloadData()
}
// MARK: - Actions -
func a_checkProducts(sender: AnyObject?) {
_storeItems = _storeManager.purchasableObjects
if _storeItems.count > 0 {
_checkProductsTimer?.invalidate()
_checkProductsTimer = nil
_viewObjects.hideLoadingScreen()
self._organizeList()
self.tableView.reloadData()
}
}
// MARK: - Loading -
public func cancelLoad() {
_checkProductsTimer?.invalidate()
_checkProductsTimer = nil
_viewObjects.hideLoadingScreen()
}
func _organizeList() {
// Place purchased products at the the end of the list
var sorted: [SKProduct] = []
var purchased: [SKProduct] = []
for item in _storeItems {
if let product = item as? SKProduct {
var array = MKStoreManager.isFeaturePurchased(product.productIdentifier) ? purchased : sorted
array.append(product)
}
}
sorted.extend(purchased)
_storeItems = sorted
}
}
// MARK: - Table view data source
extension StoreViewController : UITableViewDelegate, UITableViewDataSource {
public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return indexPath.row == 0 ? 75.0 : 150.0
}
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _storeItems.count + 1
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NoReuse")
cell.textLabel?.text = "Restore previous purchases"
return cell
} else {
let adjustedRow = indexPath.row - 1
let cell = StoreUITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NoReuse")
cell.product = _storeItems[adjustedRow] as? SKProduct
return cell
}
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
_storeManager.restorePreviousTransactions()
} else {
let adjustedRow = indexPath.row - 1
let product: SKProduct = _storeItems[adjustedRow] as SKProduct
let identifier: String = product.productIdentifier
if !MKStoreManager.isFeaturePurchased(identifier) {
_storeManager.buyFeature(identifier)
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} | 1a7b24cf33f44c3fe10b6c85a3a63bb4 | 32.242038 | 158 | 0.636451 | false | false | false | false |
harenbrs/swix | refs/heads/master | swixUseCases/swix-iOS/swix/matrix/image.swift | mit | 4 | //
// twoD-image.swift
// swix
//
// Created by Scott Sievert on 7/30/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
/*
* some other useful tips that need an iOS app to use:
* 1. UIImage to raw array[0]:
* 2. raw array to UIImage[1]:
*
* for a working implementation, see[2] (to be published shortly)
*
* [0]:http://stackoverflow.com/a/1262893/1141256
* [1]:http://stackoverflow.com/a/12868860/1141256
* [2]:https://github.com/scottsievert/saliency/blob/master/AVCam/AVCam/saliency/imageToRawArray.m
*
*
*/
import Foundation
func rgb2hsv_pixel(R:Double, G:Double, B:Double)->(Double, Double, Double){
// tested against wikipedia/HSL_and_HSV. returns (H, S_hsv, V)
var M = max(array(R, G, B))
var m = min(array(R, G, B))
var C = M - m
var Hp:Double = 0
if M==R {Hp = ((G-B)/C) % 6}
else if M==G {Hp = ((B-R)/C) + 2}
else if M==B {Hp = ((R-G)/C) + 4}
var H = 60 * Hp
var V = M
var S = 0.0
if !(V==0) {S = C/V}
return (H, S, V)
}
func rgb2hsv(r:matrix, g:matrix, b:matrix)->(matrix, matrix, matrix){
assert(r.shape.0 == g.shape.0)
assert(b.shape.0 == g.shape.0)
assert(r.shape.1 == g.shape.1)
assert(b.shape.1 == g.shape.1)
var h = zeros_like(r)
var s = zeros_like(g)
var v = zeros_like(b)
for i in 0..<r.shape.0{
for j in 0..<r.shape.1{
var (h_p, s_p, v_p) = rgb2hsv_pixel(r[i,j], g[i,j], b[i,j])
h[i,j] = h_p
s[i,j] = s_p
v[i,j] = v_p
}
}
return (h, s, v)
}
func rgb2_hsv_vplane(r:matrix, g:matrix, b:matrix)->matrix{
return max(max(r, g), b)
}
func savefig(x:matrix, filename:String, save:Bool=true, show:Bool=false){
// assumes Python is on your $PATH and pylab/etc are installed
// prefix should point to the swix folder!
// prefix is defined in numbers.swift
// assumes python is on your path
write_csv(x, filename:"swix/temp.csv")
system("cd "+S2_PREFIX+"; "+PYTHON_PATH + " imshow.py \(filename) \(save) \(show)")
system("rm "+S2_PREFIX+"temp.csv")
}
func imshow(x: matrix){
savefig(x, "junk", save:false, show:true)
}
//func UIImageToRGBA(image:UIImage)->(matrix, matrix, matrix, matrix){
// // returns red, green, blue and alpha channels
//
// // init'ing
// var imageRef = image.CGImage
// var width = CGImageGetWidth(imageRef)
// var height = CGImageGetHeight(imageRef)
// var colorSpace = CGColorSpaceCreateDeviceRGB()
// var bytesPerPixel = 4
// var bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(width)
// var bitsPerComponent:UInt = 8
// var pix = Int(width) * Int(height)
// var count:Int = 4*Int(pix)
//
// // pulling the color out of the image
// var rawData:[CUnsignedChar] = Array(count:count, repeatedValue:0)
// var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())!
// var context = CGBitmapContextCreate(&rawData, UInt(width), UInt(height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
// CGContextDrawImage(context, CGRectMake(0,0,CGFloat(width), CGFloat(height)), imageRef)
//
//
// // unsigned char to double conversion
// var rawDataArray = zeros(count)-1
// vDSP_vfltu8D(&rawData, 1, &rawDataArray.grid, 1, count.length)
//
// // pulling the RGBA channels out of the color
// var i = arange(pix)
// var r = zeros((Int(height), Int(width)))-1;
// r.flat = rawDataArray[4*i+0]
//
// var g = zeros((Int(height), Int(width)));
// g.flat = rawDataArray[4*i+1]
//
// var b = zeros((Int(height), Int(width)));
// b.flat = rawDataArray[4*i+2]
//
// var a = zeros((Int(height), Int(width)));
// a.flat = rawDataArray[4*i+3]
// return (r, g, b, a)
//}
//func RGBAToUIImage(r:matrix, g:matrix, b:matrix, a:matrix)->UIImage{
// // setup
// var height = r.shape.0
// var width = r.shape.1
// var area = height * width
// var componentsPerPixel = 4 // rgba
// var compressedPixelData = zeros(4*area)
// var N = width * height
//
// // double to unsigned int
// var i = arange(N)
// compressedPixelData[4*i+0] = r.flat
// compressedPixelData[4*i+1] = g.flat
// compressedPixelData[4*i+2] = b.flat
// compressedPixelData[4*i+3] = a.flat
// var pixelData:[CUnsignedChar] = Array(count:area*componentsPerPixel, repeatedValue:0)
// vDSP_vfixu8D(&compressedPixelData.grid, 1, &pixelData, 1, vDSP_Length(componentsPerPixel*area))
//
// // creating the bitmap context
// var colorSpace = CGColorSpaceCreateDeviceRGB()
// var bitsPerComponent = 8
// var bytesPerRow = ((bitsPerComponent * width) / 8) * componentsPerPixel
// var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())!
// var context = CGBitmapContextCreate(&pixelData, UInt(width), UInt(height), UInt(bitsPerComponent), UInt(bytesPerRow), colorSpace, bitmapInfo)
//
// // creating the image
// var toCGImage = CGBitmapContextCreateImage(context)
// var image:UIImage = UIImage.init(CGImage:toCGImage)
// return image
//}
//func resizeImage(image:UIImage, shape:(Int, Int)) -> UIImage{
// // nice variables
// var (height, width) = shape
// var cgSize = CGSizeMake(width, height)
//
// // draw on new CGSize
// UIGraphicsBeginImageContextWithOptions(cgSize, false, 0.0)
// image.drawInRect(CGRectMake(0, 0, width, height))
// var newImage = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
// return newImage
//}
| 1b86895b6b6af50a414e45e2f2c1f271 | 33.8125 | 147 | 0.623339 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift | refs/heads/master | Network/Network/NetworkProvider.swift | mit | 2 | //
// NetworkProvider.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 16.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Domain
final class NetworkProvider {
private let apiEndpoint: String
public init() {
apiEndpoint = "https://jsonplaceholder.typicode.com"
}
public func makeAlbumsNetwork() -> AlbumsNetwork {
let network = Network<Album>(apiEndpoint)
return AlbumsNetwork(network: network)
}
public func makeCommentsNetwork() -> CommentsNetwork {
let network = Network<Comment>(apiEndpoint)
return CommentsNetwork(network: network)
}
public func makePhotosNetwork() -> PhotosNetwork {
let network = Network<Photo>(apiEndpoint)
return PhotosNetwork(network: network)
}
public func makePostsNetwork() -> PostsNetwork {
let network = Network<Post>(apiEndpoint)
return PostsNetwork(network: network)
}
public func makeTodosNetwork() -> TodosNetwork {
let network = Network<Todo>(apiEndpoint)
return TodosNetwork(network: network)
}
public func makeUsersNetwork() -> UsersNetwork {
let network = Network<User>(apiEndpoint)
return UsersNetwork(network: network)
}
}
| 76a546befcf5f9bd84050728697cce16 | 26.297872 | 60 | 0.671863 | false | false | false | false |
WeMadeCode/ZXPageView | refs/heads/master | Example/ZXPageView/ZXHorizontalViewController.swift | mit | 1 | //
// ZXWaterViewController.swift
// ZXPageView_Example
//
// Created by Anthony on 2019/3/15.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import ZXPageView
import SwifterSwift
private let kCollectionViewCellID = "kCollectionViewCellID"
class ZXHorizontalViewController: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
self.view.backgroundColor = UIColor.white
// 1.创建需要的样式
let style = ZXPageStyle()
style.isLongStyle = false
// 2.获取所有的标题
let titles = ["推荐", "游戏游戏游戏游戏", "热门"] //, "趣玩"
// 3.创建布局
let layout = ZXHorizontalViewLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.lineSpacing = 10
layout.itemSpacing = 10
layout.cols = 4
layout.rows = 2
// 4.创建Water
let pageFrame = CGRect(x: 0, y: self.safeY, width: self.view.bounds.width, height: 300)
let pageView = ZXHorizontalView(frame: pageFrame, style: style, titles: titles, layout : layout)
pageView.dataSource = self
pageView.delegate = self
pageView.registerCell(UICollectionViewCell.self, identifier: kCollectionViewCellID)
pageView.backgroundColor = UIColor.orange
view.addSubview(pageView)
}
deinit {
print("deinit")
}
}
extension ZXHorizontalViewController : ZXHorizontalViewDataSource {
func numberOfSectionsInWaterView(_ waterView: ZXHorizontalView) -> Int {
return 3
}
func waterView(_ waterView: ZXHorizontalView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 12
} else if section == 1 {
return 30
} else if section == 2 {
return 7
}else{
return 13
}
}
func waterView(_ waterView: ZXHorizontalView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let cell = waterView.dequeueReusableCell(withReuseIdentifier: kCollectionViewCellID, for: indexPath)
cell.backgroundColor = UIColor.random
return cell
}
}
extension ZXHorizontalViewController : ZXHorizontalViewDelegate {
func waterView(_ waterView: ZXHorizontalView, didSelectedAtIndexPath indexPath: IndexPath) {
print(indexPath)
}
}
| 79265dd67e5cd112c6d9c8fd894a98a1 | 23.401961 | 120 | 0.6364 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT | refs/heads/master | WeiBo/WeiBo/Classes/Tools(工具类)/UIButton+convenience.swift | mit | 1 | //
// UIButton+extension.swift
// WeiBo
//
// Created by chenWei on 2017/4/2.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(title: String?,
titleColor: UIColor? = UIColor.gray,
fontSize: CGFloat? = 15,
target: AnyObject? = nil,
selector: Selector? = nil,
events: UIControlEvents? = .touchUpInside,
image: String? = nil,
bgImage: String? = nil) {
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
if let fontSize = fontSize {
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
}
if let target = target, let selector = selector {
self.addTarget(target, action: selector, for: events!)
}
if let image = image {
self.setImage(UIImage(named: "\(image)"), for: .normal)
self.setImage(UIImage(named: "\(image)_highlighted"), for: .highlighted)
}
if let bgImage = bgImage {
self.setBackgroundImage(UIImage(named: "\(bgImage)"), for: .normal)
self.setBackgroundImage(UIImage(named: "\(bgImage)_highlighted"), for: .highlighted)
}
}
}
| 74f3a5e128248efb03c82d56abb7d057 | 27.78 | 96 | 0.516331 | false | false | false | false |
xzhflying/IOS_Calculator | refs/heads/master | Calculator/ViewController.swift | mit | 1 | //
// ViewController.swift
// Calculator
//
// Created by xzhflying on 15/11/5.
// Copyright © 2015年 xzhflying. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var display: UILabel!
var userIsInputing: Bool = false
var theCore = CalculatorCore()
@IBAction func appendDigit(sender: UIButton) {
let digit = firstButtonValue(sender.currentTitle!)
appendToLabel(digit)
}
@IBAction func addButtonOptionalValue(sender :UILongPressGestureRecognizer) {
if(sender.state == .Ended)
{
appendToLabel("(")
}
}
@IBAction func minusButtonOptionalValue(sender :UILongPressGestureRecognizer) {
if(sender.state == .Ended)
{
appendToLabel(")")
}
}
@IBAction func clearInput(sender: UIButton) {
display.text = "0"
userIsInputing = false
theCore.digitStack.removeAll()
theCore.operatorStack.removeAll()
}
@IBAction func deleteLastInput(sender: UIButton) {
if (userIsInputing && display.text!.characters.count > 1)
{
display.text!.removeAtIndex(display.text!.endIndex.predecessor())
}
else if (userIsInputing)
{
display.text! = "0"
userIsInputing = false
}
}
@IBAction func theResult(sender: AnyObject) {
let result = theCore.calculate()
if result != nil
{
display.text = String(result!)
}
}
func appendToLabel(str :String){
if( userIsInputing )
{
display.text = display.text! + str
}
else
{
display.text = str
userIsInputing = true
}
}
func firstButtonValue(str :String) -> String{
if (str.containsString("/"))
{
let index = str.startIndex.advancedBy(1)
return str.substringToIndex(index)
}
else
{
return str
}
}
// Unused for now
func secondButtonValue(str :String) -> String?{
if (str.containsString("/"))
{
let startIndex = str.startIndex.advancedBy(1)
let endIndex = str.startIndex.advancedBy(2)
let range = Range(start: startIndex, end: endIndex)
return str.substringWithRange(range)
}
else
{
return nil
}
}
}
| 5bffd521ae1eb12be9d68f12fd655cd4 | 23.153846 | 83 | 0.548169 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Tests/Source/Data Model/ServiceUserTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2021 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 XCTest
@testable import WireSyncEngine
final class DummyServiceUser: NSObject, ServiceUser {
func cancelConnectionRequest(completion: @escaping (Error?) -> Void) {
}
func connect(completion: @escaping (Error?) -> Void) {
}
func block(completion: @escaping (Error?) -> Void) {
}
func accept(completion: @escaping (Error?) -> Void) {
}
func ignore(completion: @escaping (Error?) -> Void) {
}
var remoteIdentifier: UUID?
var isIgnored: Bool = false
var hasTeam: Bool = false
var isTrusted: Bool = false
var hasLegalHoldRequest: Bool = false
var needsRichProfileUpdate: Bool = false
var availability: AvailabilityKind = .none
var teamName: String?
var isBlocked: Bool = false
var blockState: ZMBlockState = .none
var isExpired: Bool = false
var isPendingApprovalBySelfUser: Bool = false
var isPendingApprovalByOtherUser: Bool = false
var isWirelessUser: Bool = false
var isUnderLegalHold: Bool = false
var allClients: [UserClientType] = []
var expiresAfter: TimeInterval = 0
var readReceiptsEnabled: Bool = true
var isVerified: Bool = false
var richProfile: [UserRichProfileField] = []
/// Whether the user can create conversations.
@objc
func canCreateConversation(type: ZMConversationType) -> Bool {
return true
}
var canCreateService: Bool = false
var canManageTeam: Bool = false
func canAccessCompanyInformation(of user: UserType) -> Bool {
return false
}
func canAddUser(to conversation: ConversationLike) -> Bool {
return false
}
func canRemoveUser(from conversation: ZMConversation) -> Bool {
return false
}
func canAddService(to conversation: ZMConversation) -> Bool {
return false
}
func canDeleteConversation(_ conversation: ZMConversation) -> Bool {
return false
}
func canRemoveService(from conversation: ZMConversation) -> Bool {
return false
}
func canModifyReadReceiptSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyEphemeralSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyNotificationSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyAccessControlSettings(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyTitle(in conversation: ConversationLike) -> Bool {
return false
}
func canModifyOtherMember(in conversation: ZMConversation) -> Bool {
return false
}
func canLeave(_ conversation: ZMConversation) -> Bool {
return false
}
func isGroupAdmin(in conversation: ConversationLike) -> Bool {
return false
}
var domain: String?
var previewImageData: Data?
var completeImageData: Data?
var name: String? = "Service user"
var displayName: String = "Service"
var initials: String? = "S"
var handle: String? = "service"
var emailAddress: String? = "[email protected]"
var phoneNumber: String?
var isSelfUser: Bool = false
var smallProfileImageCacheKey: String? = ""
var mediumProfileImageCacheKey: String? = ""
var isConnected: Bool = false
var oneToOneConversation: ZMConversation?
var accentColorValue: ZMAccentColor = ZMAccentColor.brightOrange
var imageMediumData: Data! = Data()
var imageSmallProfileData: Data! = Data()
var imageSmallProfileIdentifier: String! = ""
var imageMediumIdentifier: String! = ""
var isTeamMember: Bool = false
var hasDigitalSignatureEnabled: Bool = false
var teamRole: TeamRole = .member
var canBeConnected: Bool = false
var isServiceUser: Bool = true
var isFederated: Bool = false
var usesCompanyLogin: Bool = false
var isAccountDeleted: Bool = false
var managedByWire: Bool = true
var extendedMetadata: [[String: String]]?
var activeConversations: Set<ZMConversation> = Set()
func requestPreviewProfileImage() {
}
func requestCompleteProfileImage() {
}
func imageData(for size: ProfileImageSize, queue: DispatchQueue, completion: @escaping (Data?) -> Void) {
}
func refreshData() {
}
func refreshRichProfile() {
}
func refreshMembership() {
}
func refreshTeamData() {
}
func isGuest(in conversation: ConversationLike) -> Bool {
return false
}
var connectionRequestMessage: String? = ""
var totalCommonConnections: UInt = 0
var serviceIdentifier: String?
var providerIdentifier: String?
init(serviceIdentifier: String, providerIdentifier: String) {
self.serviceIdentifier = serviceIdentifier
self.providerIdentifier = providerIdentifier
super.init()
}
}
final class ServiceUserTests: IntegrationTest {
public override func setUp() {
super.setUp()
self.createSelfUserAndConversation()
self.createExtraUsersAndConversations()
XCTAssertTrue(self.login())
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
}
func createService() -> ServiceUser {
var mockServiceId: String!
var mockProviderId: String!
mockTransportSession.performRemoteChanges { (remoteChanges) in
let mockService = remoteChanges.insertService(withName: "Service A",
identifier: UUID().transportString(),
provider: UUID().transportString())
mockServiceId = mockService.identifier
mockProviderId = mockService.provider
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
return DummyServiceUser(serviceIdentifier: mockServiceId, providerIdentifier: mockProviderId)
}
func testThatItAddsServiceToExistingConversation() throws {
// given
let jobIsDone = expectation(description: "service is added")
let service = self.createService()
let conversation = self.conversation(for: self.groupConversation)!
// when
conversation.add(serviceUser: service, in: userSession!) { (result) in
XCTAssertNil(result.error)
jobIsDone.fulfill()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5))
}
func testThatItCreatesConversationAndAddsUser() {
// given
let jobIsDone = expectation(description: "service is added")
let service = self.createService()
// when
service.createConversation(in: userSession!) { (result) in
XCTAssertNotNil(result.value)
jobIsDone.fulfill()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5))
}
func testThatItDetectsTheConversationFullResponse() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 403, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .tooManyParticipants)
}
func testThatItDetectsBotRejectedResponse() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 419, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .botRejected)
}
func testThatItDetectsBotNotResponding() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 502, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .botNotResponding)
}
func testThatItDetectsGeneralError() {
// GIVEN
let response = ZMTransportResponse(payload: nil, httpStatus: 500, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
let error = AddBotError(response: response)
// THEN
XCTAssertEqual(error, .general)
}
}
| 406a06c1be85eeaf79ff06c8cc355dc5 | 25.065341 | 137 | 0.663433 | false | false | false | false |
alldne/PolarKit | refs/heads/master | Example/Tests/Tests.swift | mit | 1 | // https://github.com/Quick/Quick
import Quick
import Nimble
@testable import PolarKit
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("math") {
describe("CGVector extension") {
it("can calculate the angle between two vectors") {
let v1 = CGVector(dx: 1, dy: 1)
let v2 = CGVector(dx: 1, dy: 1)
expect(v1.getAngle(v2)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors") {
let v1 = CGVector(dx: -1.333343505859375, dy: -2.5)
let v2 = CGVector(dx: -1.333343505859375, dy: -2.5)
expect(v1.getAngle(v2)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: 1, dy: 1)
let v2 = CGVector(dx: 1, dy: 1)
let hint = 0.0
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: -1.333343505859375, dy: -2.5)
let v2 = CGVector(dx: -1.333343505859375, dy: -2.5)
let hint = 0.0
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(0))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: 1, dy: 1)
let v2 = CGVector(dx: 1, dy: 1)
let hint = 3 * Double.pi - 1
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(2 * .pi))
}
it("can calculate the angle between two vectors which is nearby with given hint") {
let v1 = CGVector(dx: 1, dy: 0)
let v2 = CGVector(dx: 0, dy: 1)
let hint = -2 * Double.pi
expect(v1.getNearbyAngle(v2, hint: hint)).to(beCloseTo(-.pi * 3 / 2))
}
}
describe("bound function") {
describe("bound input") {
context("range [0, 10] with margin 2") {
let bound = makeBoundFunction(lower: 0, upper: 10, margin: 2).bound
it("bypass input in range") {
expect(bound(5)).to(beCloseTo(5))
}
it("bypass input in range") {
expect(bound(10)).to(beCloseTo(10))
}
it("returns smaller value than input within the margin") {
expect(bound(11)).to(beLessThanOrEqualTo(11))
}
it("returns smaller value than input within the margin") {
expect(bound(10.0001)).to(beLessThanOrEqualTo(10.0001))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(15)).to(beLessThanOrEqualTo(12))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(20)).to(beLessThanOrEqualTo(12))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(10*1000000)).to(beLessThanOrEqualTo(12))
}
it("should not return the value smaller than lower bound - margin") {
expect(bound(-10*1000000)).to(beGreaterThanOrEqualTo(-2))
}
}
context("range [-100, 10] with margin 10") {
let bound = makeBoundFunction(lower: -100, upper: 10, margin: 10).bound
it("bypass input in range") {
expect(bound(5)).to(beCloseTo(5))
}
it("bypass input in range") {
expect(bound(-100)).to(beCloseTo(-100))
}
it("bypass input in range") {
expect(bound(10)).to(beCloseTo(10))
}
it("should not return the value bigger than upper bound + margin") {
expect(bound(10*1000000)).to(beLessThanOrEqualTo(20))
}
it("should not return the value smaller than lower bound - margin") {
expect(bound(-10*1000000)).to(beGreaterThanOrEqualTo(-110))
}
}
}
describe("inverse of bound function") {
let functions = makeBoundFunction(lower: 0, upper: 10, margin: 2)
let bound = functions.bound
let inverse = functions.inverse
it("should work in the opposite way to the bound") {
expect(inverse(bound(10))).to(beCloseTo(10))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(11))).to(beCloseTo(11))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(11.999))).to(beCloseTo(11.999))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(-1.999))).to(beCloseTo(-1.999))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(10*1000))).to(beCloseTo(10*1000))
}
it("should work in the opposite way to the bound") {
expect(inverse(bound(-10*1000))).to(beCloseTo(-10*1000))
}
}
}
}
}
}
| 87214d0bcc1e1b76f742bdf78fac1e67 | 41.904762 | 99 | 0.445378 | false | false | false | false |
grpc/grpc-swift | refs/heads/main | Sources/protoc-gen-grpc-swift/main.swift | apache-2.0 | 1 | /*
* Copyright 2017, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import SwiftProtobuf
import SwiftProtobufPluginLibrary
func Log(_ message: String) {
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
}
// from apple/swift-protobuf/Sources/protoc-gen-swift/StringUtils.swift
func splitPath(pathname: String) -> (dir: String, base: String, suffix: String) {
var dir = ""
var base = ""
var suffix = ""
#if swift(>=3.2)
let pathnameChars = pathname
#else
let pathnameChars = pathname.characters
#endif
for c in pathnameChars {
if c == "/" {
dir += base + suffix + String(c)
base = ""
suffix = ""
} else if c == "." {
base += suffix
suffix = String(c)
} else {
suffix += String(c)
}
}
#if swift(>=3.2)
let validSuffix = suffix.isEmpty || suffix.first == "."
#else
let validSuffix = suffix.isEmpty || suffix.characters.first == "."
#endif
if !validSuffix {
base += suffix
suffix = ""
}
return (dir: dir, base: base, suffix: suffix)
}
enum FileNaming: String {
case FullPath
case PathToUnderscores
case DropPath
}
func outputFileName(
component: String,
fileDescriptor: FileDescriptor,
fileNamingOption: FileNaming
) -> String {
let ext = "." + component + ".swift"
let pathParts = splitPath(pathname: fileDescriptor.name)
switch fileNamingOption {
case .FullPath:
return pathParts.dir + pathParts.base + ext
case .PathToUnderscores:
let dirWithUnderscores =
pathParts.dir.replacingOccurrences(of: "/", with: "_")
return dirWithUnderscores + pathParts.base + ext
case .DropPath:
return pathParts.base + ext
}
}
func uniqueOutputFileName(
component: String,
fileDescriptor: FileDescriptor,
fileNamingOption: FileNaming,
generatedFiles: inout [String: Int]
) -> String {
let defaultName = outputFileName(
component: component,
fileDescriptor: fileDescriptor,
fileNamingOption: fileNamingOption
)
if let count = generatedFiles[defaultName] {
generatedFiles[defaultName] = count + 1
return outputFileName(
component: "\(count)." + component,
fileDescriptor: fileDescriptor,
fileNamingOption: fileNamingOption
)
} else {
generatedFiles[defaultName] = 1
return defaultName
}
}
func main() throws {
// initialize responses
var response = Google_Protobuf_Compiler_CodeGeneratorResponse(
files: [],
supportedFeatures: [.proto3Optional]
)
// read plugin input
let rawRequest = FileHandle.standardInput.readDataToEndOfFile()
let request = try Google_Protobuf_Compiler_CodeGeneratorRequest(serializedData: rawRequest)
let options = try GeneratorOptions(parameter: request.parameter)
// Build the SwiftProtobufPluginLibrary model of the plugin input
let descriptorSet = DescriptorSet(protos: request.protoFile)
// A count of generated files by desired name (actual name may differ to avoid collisions).
var generatedFiles: [String: Int] = [:]
// Only generate output for services.
for name in request.fileToGenerate {
if let fileDescriptor = descriptorSet.fileDescriptor(named: name),
!fileDescriptor.services.isEmpty {
let grpcFileName = uniqueOutputFileName(
component: "grpc",
fileDescriptor: fileDescriptor,
fileNamingOption: options.fileNaming,
generatedFiles: &generatedFiles
)
let grpcGenerator = Generator(fileDescriptor, options: options)
var grpcFile = Google_Protobuf_Compiler_CodeGeneratorResponse.File()
grpcFile.name = grpcFileName
grpcFile.content = grpcGenerator.code
response.file.append(grpcFile)
}
}
// return everything to the caller
let serializedResponse = try response.serializedData()
FileHandle.standardOutput.write(serializedResponse)
}
do {
try main()
} catch {
Log("ERROR: \(error)")
}
| 3899ef96022658776acf6965fd22b586 | 28.058824 | 93 | 0.70108 | false | false | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Editor Toolbar/ProfileEditorWindowToolbarItemExport.swift | mit | 1 | //
// ProfileEditorWindowToolbarItemExport.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class ProfileEditorWindowToolbarItemExport: NSView {
// MARK: -
// MARK: Variables
let toolbarItem: NSToolbarItem
let disclosureTriangle: NSImageView
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(profile: Profile, editor: ProfileEditor) {
// ---------------------------------------------------------------------
// Create the size of the toolbar item
// ---------------------------------------------------------------------
let rect = NSRect(x: 0, y: 0, width: 40, height: 32)
// ---------------------------------------------------------------------
// Create the actual toolbar item
// ---------------------------------------------------------------------
self.toolbarItem = NSToolbarItem(itemIdentifier: .editorExport)
self.toolbarItem.toolTip = NSLocalizedString("Export profile", comment: "")
// ---------------------------------------------------------------------
// Create the disclosure triangle overlay
// ---------------------------------------------------------------------
self.disclosureTriangle = NSImageView()
self.disclosureTriangle.translatesAutoresizingMaskIntoConstraints = false
self.disclosureTriangle.image = NSImage(named: "ArrowDown")
self.disclosureTriangle.imageScaling = .scaleProportionallyUpOrDown
self.disclosureTriangle.isHidden = true
// ---------------------------------------------------------------------
// Initialize self after the class variables have been instantiated
// ---------------------------------------------------------------------
super.init(frame: rect)
// ---------------------------------------------------------------------
// Create the button instance and add it to the toolbar item view
// ---------------------------------------------------------------------
self.addSubview(ProfileEditorWindowToolbarItemExportButton(frame: rect, profile: profile))
// ---------------------------------------------------------------------
// Add disclosure triangle to the toolbar item view
// ---------------------------------------------------------------------
self.addSubview(self.disclosureTriangle)
// ---------------------------------------------------------------------
// Setup the disclosure triangle constraints
// ---------------------------------------------------------------------
self.addConstraintsForDisclosureTriangle()
// ---------------------------------------------------------------------
// Set the toolbar item view
// ---------------------------------------------------------------------
self.toolbarItem.view = self
}
func disclosureTriangle(show: Bool) {
self.disclosureTriangle.isHidden = !show
}
func addConstraintsForDisclosureTriangle() {
var constraints = [NSLayoutConstraint]()
// Width
constraints.append(NSLayoutConstraint(item: self.disclosureTriangle,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 9))
// Height == Width
constraints.append(NSLayoutConstraint(item: self.disclosureTriangle,
attribute: .height,
relatedBy: .equal,
toItem: self.disclosureTriangle,
attribute: .width,
multiplier: 1,
constant: 0))
// Bottom
constraints.append(NSLayoutConstraint(item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: self.disclosureTriangle,
attribute: .bottom,
multiplier: 1,
constant: 6))
// Trailing
constraints.append(NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: self.disclosureTriangle,
attribute: .trailing,
multiplier: 1,
constant: 3))
NSLayoutConstraint.activate(constraints)
}
}
class ProfileEditorWindowToolbarItemExportButton: NSButton {
// MARK: -
// MARK: Variables
weak var profile: Profile?
let buttonMenu = NSMenu()
let menuDelay = 0.2
var trackingArea: NSTrackingArea?
var mouseIsDown = false
var menuWasShownForLastMouseDown = false
var mouseDownUniquenessCounter = 0
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(frame frameRect: NSRect, profile: Profile) {
self.init(frame: frameRect)
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
self.profile = profile
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
// ---------------------------------------------------------------------
// Setup Self (Toolbar Item)
// ---------------------------------------------------------------------
self.bezelStyle = .texturedRounded
self.image = NSImage(named: NSImage.shareTemplateName)
self.target = self
self.action = #selector(self.clicked(button:))
self.imageScaling = .scaleProportionallyDown
self.imagePosition = .imageOnly
self.isEnabled = true
// ---------------------------------------------------------------------
// Setup the button menu
// ---------------------------------------------------------------------
self.setupButtonMenu()
}
func setupButtonMenu() {
self.buttonMenu.delegate = self
// ---------------------------------------------------------------------
// Add item: "Export Profile"
// ---------------------------------------------------------------------
let menuItemExportProfile = NSMenuItem()
menuItemExportProfile.identifier = NSUserInterfaceItemIdentifier("export")
menuItemExportProfile.title = NSLocalizedString("Export Profile", comment: "")
menuItemExportProfile.isEnabled = true
menuItemExportProfile.target = self
menuItemExportProfile.action = #selector(self.exportProfile(menuItem:))
self.buttonMenu.addItem(menuItemExportProfile)
// ---------------------------------------------------------------------
// Add item: "Export Plist"
// ---------------------------------------------------------------------
let menuItemExportPlist = NSMenuItem()
menuItemExportPlist.identifier = NSUserInterfaceItemIdentifier("exportPlist")
menuItemExportPlist.title = NSLocalizedString("Export Plist", comment: "")
menuItemExportPlist.isEnabled = true
menuItemExportPlist.target = self
menuItemExportPlist.action = #selector(self.exportPlist(menuItem:))
self.buttonMenu.addItem(menuItemExportPlist)
}
// MARK: -
// MARK: Button/Menu Actions
@objc func clicked(button: NSButton) {
if self.isEnabled {
// -----------------------------------------------------------------
// If only button was clicked, call 'exportProfile'
// -----------------------------------------------------------------
self.exportProfile(menuItem: nil)
}
}
@objc func exportPlist(menuItem: NSMenuItem?) {
guard
let profile = self.profile,
let windowController = profile.windowControllers.first as? ProfileEditorWindowController,
let window = windowController.window else { return }
ProfileController.sharedInstance.exportPlist(profile: profile, promptWindow: window)
}
@objc func exportProfile(menuItem: NSMenuItem?) {
guard
let profile = self.profile,
let windowController = profile.windowControllers.first as? ProfileEditorWindowController,
let window = windowController.window else { return }
ProfileController.sharedInstance.export(profile: profile, promptWindow: window)
}
/*
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let mainWindowController = self.window?.windowController as? MainWindowController else { return false }
// FIXME: Add a constant for each menuItem
switch menuItem.identifier?.rawValue {
case "export":
return mainWindowController.splitView.tableViewController.selectedProfileIdentitifers?.count == 1
default:
return true
}
}
*/
// MARK: -
// MARK: NSControl/NSResponder Methods
override func mouseEntered(with event: NSEvent) {
if self.isEnabled, let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: true)
}
}
override func mouseExited(with event: NSEvent) {
if !self.mouseIsDown {
if let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: false)
}
}
}
override func mouseDown(with event: NSEvent) {
// ---------------------------------------------------------------------
// Reset mouse variables
// ---------------------------------------------------------------------
self.mouseIsDown = true
self.menuWasShownForLastMouseDown = false
self.mouseDownUniquenessCounter += 1
let mouseDownUniquenessCounterCopy = self.mouseDownUniquenessCounter
// ---------------------------------------------------------------------
// Show the button is being pressed
// ---------------------------------------------------------------------
self.highlight(true)
// ---------------------------------------------------------------------
// Wait 'menuDelay' before showing the context menu
// If button has been released before time runs out, it's considered a normal button press
// ---------------------------------------------------------------------
DispatchQueue.main.asyncAfter(deadline: .now() + self.menuDelay) {
if self.mouseIsDown && mouseDownUniquenessCounterCopy == self.mouseDownUniquenessCounter {
self.menuWasShownForLastMouseDown = true
guard let menuOrigin = self.superview?.convert(NSPoint(x: self.frame.origin.x + self.frame.size.width - 16,
y: self.frame.origin.y + 2), to: nil) else {
return
}
guard let event = NSEvent.mouseEvent(with: event.type,
location: menuOrigin,
modifierFlags: event.modifierFlags,
timestamp: event.timestamp,
windowNumber: event.windowNumber,
context: nil,
eventNumber: event.eventNumber,
clickCount: event.clickCount,
pressure: event.pressure) else {
return
}
NSMenu.popUpContextMenu(self.buttonMenu, with: event, for: self)
}
}
}
override func mouseUp(with event: NSEvent) {
// ---------------------------------------------------------------------
// Reset mouse variables
// ---------------------------------------------------------------------
self.mouseIsDown = false
if !self.menuWasShownForLastMouseDown {
if let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: false)
}
self.sendAction(self.action, to: self.target)
}
// ---------------------------------------------------------------------
// Hide the button is being pressed
// ---------------------------------------------------------------------
self.highlight(false)
}
// MARK: -
// MARK: NSView Methods
override func updateTrackingAreas() {
// ---------------------------------------------------------------------
// Remove previous tracking area if it was set
// ---------------------------------------------------------------------
if let trackingArea = self.trackingArea {
self.removeTrackingArea(trackingArea)
}
// ---------------------------------------------------------------------
// Create a new tracking area
// ---------------------------------------------------------------------
let trackingOptions = NSTrackingArea.Options(rawValue: (NSTrackingArea.Options.mouseEnteredAndExited.rawValue | NSTrackingArea.Options.activeAlways.rawValue))
self.trackingArea = NSTrackingArea(rect: self.bounds, options: trackingOptions, owner: self, userInfo: nil)
// ---------------------------------------------------------------------
// Add the new tracking area to the button
// ---------------------------------------------------------------------
self.addTrackingArea(self.trackingArea!)
}
}
// MARK: -
// MARK: NSMenuDelegate
extension ProfileEditorWindowToolbarItemExportButton: NSMenuDelegate {
func menuDidClose(_ menu: NSMenu) {
// ---------------------------------------------------------------------
// Reset mouse variables
// ---------------------------------------------------------------------
self.mouseIsDown = false
self.menuWasShownForLastMouseDown = false
self.mouseDownUniquenessCounter = 0
// ---------------------------------------------------------------------
// Turn of highlighting and disclosure triangle when the menu closes
// ---------------------------------------------------------------------
self.highlight(false)
if let parent = self.superview, let toolbarItemExport = parent as? ProfileEditorWindowToolbarItemExport {
toolbarItemExport.disclosureTriangle(show: false)
}
}
}
| 87d46c392168fbf04b1addbe98f0d375 | 42.483696 | 166 | 0.437945 | false | false | false | false |
Draveness/RbSwift | refs/heads/master | RbSwift/String/String+Case.swift | mit | 2 | //
// Case.swift
// RbSwift
//
// Created by draveness on 19/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
// MARK: - Case
public extension String {
/// Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.
///
/// "Hello".downcase #=> "hello"
/// "HellHEo".downcase #=> "hellheo"
///
var downcase: String {
return self.lowercased()
}
/// Downcases the contents of the receiver
///
/// var hello = "Hello"
/// hello.downcased() #=> "hello"
/// hello #=> "hello"
///
/// - Returns: Self
@discardableResult
mutating func downcased() -> String {
self = downcase
return self
}
/// Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.
///
/// "Hello".upcase #=> "HELLO"
/// "HellHEo".upcase #=> "HELLHEO"
///
var upcase: String {
return self.uppercased()
}
/// Upcases the contents of the receiver
///
/// var hello = "Hello"
/// hello.upcased() #=> "HELLO"
/// hello #=> "HELLO"
///
/// - Returns: Self
@discardableResult
mutating func upcased() -> String {
self = upcase
return self
}
/// Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
///
/// "HellHEo".swapcase #=> "hELLheO"
///
var swapcase: String {
return self.chars.map { $0.isUpcase ? $0.downcase : $0.upcase }.joined()
}
/// Equivalent to `swapcase`, but modifies the receiver in place.
///
/// let hello = "HellHEo"
/// hello.swapcased() #=> "hELLheO"
/// hello #=> "hELLheO"
///
/// - Returns: Self
@discardableResult
mutating func swapcased() -> String {
self = swapcase
return self
}
}
| 374289ae3dd3b59d4b8c38d869e9b235 | 25.844156 | 138 | 0.53314 | false | false | false | false |
colemancda/HTTP-Server | refs/heads/master | Mustache/Goodies/JavascriptEscape.swift | mit | 3 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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.
class JavascriptEscape : MustacheBoxable {
var mustacheBox: MustacheBox {
// Return a multi-facetted box, because JavascriptEscape interacts in
// various ways with Mustache rendering.
return Box(
// It has a value:
value: self,
// JavascriptEscape can be used as a filter: {{ javascriptEscape(x) }}:
filter: Filter(filter),
// JavascriptEscape escapes all variable tags: {{# javascriptEscape }}...{{ x }}...{{/ javascriptEscape }}
willRender: willRender)
}
// This function is used for evaluating `javascriptEscape(x)` expressions.
private func filter(rendering: Rendering) throws -> Rendering {
return Rendering(JavascriptEscape.escapeJavascript(rendering.string), rendering.contentType)
}
// A WillRenderFunction: this function lets JavascriptEscape change values that
// are about to be rendered to their escaped counterpart.
//
// It is activated as soon as the formatter enters the context stack, when
// used in a section {{# javascriptEscape }}...{{/ javascriptEscape }}.
private func willRender(tag: Tag, box: MustacheBox) -> MustacheBox {
switch tag.type {
case .Variable:
// We don't know if the box contains a String, so let's escape its
// rendering.
return Box(render: { (info: RenderingInfo) -> Rendering in
let rendering = try box.render(info: info)
return try self.filter(rendering)
})
case .Section:
return box
}
}
private class func escapeJavascript(string: String) -> String {
// This table comes from https://github.com/django/django/commit/8c4a525871df19163d5bfdf5939eff33b544c2e2#django/template/defaultfilters.py
//
// Quoting Malcolm Tredinnick:
// > Added extra robustness to the escapejs filter so that all invalid
// > characters are correctly escaped. This avoids any chance to inject
// > raw HTML inside <script> tags. Thanks to Mike Wiacek for the patch
// > and Collin Grady for the tests.
//
// Quoting Mike Wiacek from https://code.djangoproject.com/ticket/7177
// > The escapejs filter currently escapes a small subset of characters
// > to prevent JavaScript injection. However, the resulting strings can
// > still contain valid HTML, leading to XSS vulnerabilities. Using hex
// > encoding as opposed to backslash escaping, effectively prevents
// > Javascript injection and also helps prevent XSS. Attached is a
// > small patch that modifies the _js_escapes tuple to use hex encoding
// > on an expanded set of characters.
//
// The initial django commit used `\xNN` syntax. The \u syntax was
// introduced later for JSON compatibility.
let escapeTable: [Character: String] = [
"\0": "\\u0000",
"\u{01}": "\\u0001",
"\u{02}": "\\u0002",
"\u{03}": "\\u0003",
"\u{04}": "\\u0004",
"\u{05}": "\\u0005",
"\u{06}": "\\u0006",
"\u{07}": "\\u0007",
"\u{08}": "\\u0008",
"\u{09}": "\\u0009",
"\u{0A}": "\\u000A",
"\u{0B}": "\\u000B",
"\u{0C}": "\\u000C",
"\u{0D}": "\\u000D",
"\u{0E}": "\\u000E",
"\u{0F}": "\\u000F",
"\u{10}": "\\u0010",
"\u{11}": "\\u0011",
"\u{12}": "\\u0012",
"\u{13}": "\\u0013",
"\u{14}": "\\u0014",
"\u{15}": "\\u0015",
"\u{16}": "\\u0016",
"\u{17}": "\\u0017",
"\u{18}": "\\u0018",
"\u{19}": "\\u0019",
"\u{1A}": "\\u001A",
"\u{1B}": "\\u001B",
"\u{1C}": "\\u001C",
"\u{1D}": "\\u001D",
"\u{1E}": "\\u001E",
"\u{1F}": "\\u001F",
"\\": "\\u005C",
"'": "\\u0027",
"\"": "\\u0022",
">": "\\u003E",
"<": "\\u003C",
"&": "\\u0026",
"=": "\\u003D",
"-": "\\u002D",
";": "\\u003B",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
// Required to pass GRMustache suite test "`javascript.escape` escapes control characters"
"\r\n": "\\u000D\\u000A",
]
var escaped = ""
for c in string.characters {
if let escapedString = escapeTable[c] {
escaped += escapedString
} else {
escaped.append(c)
}
}
return escaped
}
}
| dcbcff2548661d4caad7d02e530ef1a2 | 41.120567 | 147 | 0.55447 | false | false | false | false |
TsvetanMilanov/BG-Tourist-Guide | refs/heads/master | BG-Tourist-Guide/ViewControllers/VisitTouristSiteViewController.swift | mit | 1 | //
// VisitTouristSiteViewController.swift
// BG-Tourist-Guide
//
// Created by Hakintosh on 2/7/16.
// Copyright © 2016 Hakintosh. All rights reserved.
//
import UIKit
import AVFoundation
import QRCodeReader
import CoreLocation
class VisitTouristSiteViewController: UIViewController, QRCodeReaderViewControllerDelegate, CLLocationManagerDelegate {
var locationManager : CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}
@IBAction func btnScanQRCodeTap(sender: AnyObject) {
if (UIImagePickerController.isSourceTypeAvailable(.Camera))
{
let reader: QRCodeReaderViewController = {
let builder = QRCodeViewControllerBuilder { builder in
builder.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode])
builder.showTorchButton = true
}
return QRCodeReaderViewController(builder: builder)
}()
if QRCodeReader.supportsMetadataObjectTypes() {
reader.modalPresentationStyle = .FormSheet
reader.delegate = self
reader.completionBlock = { (result: QRCodeReaderResult?) in
if let result = result {
print("Completion with result: \(result.value) of type \(result.metadataType)")
}
}
presentViewController(reader, animated: true, completion: nil)
}
else {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "Your device does not have a camera. Please ask for the code of the tourist site and enter it.", uiViewController: self, andHandler: nil);
}
}
else {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "Your device does not have a camera. Please ask for the code of the tourist site and enter it.", uiViewController: self, andHandler: nil)
}
}
@IBAction func btnEnterCodeTap(sender: AnyObject) {
let weakSelf = self
TMAlertControllerFactory.showTextInputDialogWithTitle("Enter the code:", controller: self) { (text) in
weakSelf.locationManager.requestWhenInUseAuthorization()
weakSelf.locationManager.requestLocation()
let requester = TMRequester()
let loadingBar = TMActivityIndicatorFactory.activityIndicatorWithParentView(self.view)
loadingBar.startAnimating()
requester.postJSONWithUrl("/api/TouristSites/Visit?id=\(text)", data: nil, andBlock: { (err, result) in
loadingBar.stopAnimating()
if err != nil {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "There was an error on the server. Please try again later.", uiViewController: self, andHandler: nil)
return;
}
TMAlertControllerFactory.showAlertDialogWithTitle("Success", message: "The tourist site was visited successsfully.", uiViewController: self, andHandler: nil)
})
}
}
func reader(reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
self.dismissViewControllerAnimated(true, completion: { [weak self] in
let requester = TMRequester()
let loadingBar = TMActivityIndicatorFactory.activityIndicatorWithParentView(self!.view)
requester.postJSONWithUrl(result.value, data: nil, andBlock: { (err, result) in
loadingBar.stopAnimating()
if err != nil {
TMAlertControllerFactory.showAlertDialogWithTitle("Error", message: "There was an error on the server. Please try again later.", uiViewController: self!, andHandler: nil)
return;
}
TMAlertControllerFactory.showAlertDialogWithTitle("Success", message: "The tourist site was visited successsfully.", uiViewController: self!, andHandler: nil)
})
})
}
func readerDidCancel(reader: QRCodeReaderViewController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
print("\(newLocation)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("\(error)")
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
print("\(location)")
}
}
}
| 3d363688931975fb102d4b46b551c89b | 40.75 | 222 | 0.623141 | false | false | false | false |
coderwjq/swiftweibo | refs/heads/master | SwiftWeibo/SwiftWeibo/Classes/Compose/PicPicker/PicPickerCollectionView.swift | apache-2.0 | 1 | //
// PicPickerCollectionView.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/9.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
private let picPickerCell = "picPickerCell"
private let edgeMargin: CGFloat = 15
class PicPickerCollectionView: UICollectionView {
// MARK:- 定义属性
var images: [UIImage] = [UIImage]() {
didSet {
reloadData()
}
}
// MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置collectionView的layout
let layout = collectionViewLayout as! UICollectionViewFlowLayout
let itemWH = (UIScreen.main.bounds.width - 4 * edgeMargin) / 3
layout.itemSize = CGSize(width: itemWH, height: itemWH)
layout.minimumLineSpacing = edgeMargin
layout.minimumInteritemSpacing = edgeMargin
// 设置collectionView的属性
register(UINib(nibName: "PicPickerViewCell", bundle: nil), forCellWithReuseIdentifier: picPickerCell)
dataSource = self
// 设置collectionView的内边距
contentInset = UIEdgeInsets(top: edgeMargin, left: edgeMargin, bottom: edgeMargin, right: edgeMargin)
}
}
// MARK:- 数据源代理方法
extension PicPickerCollectionView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count + 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picPickerCell, for: indexPath) as! PicPickerViewCell
// 给cell设置数据
cell.backgroundColor = UIColor.red
cell.image = (indexPath as NSIndexPath).item <= images.count - 1 ? images[(indexPath as NSIndexPath).item] : nil
// 返回cell
return cell
}
}
| 07821be38a719a3e6a29c44f60a6b975 | 30.786885 | 127 | 0.66426 | false | false | false | false |
yoheiMune/swift-sample-code | refs/heads/master | swift-sample-code/ViewController.swift | mit | 1 | //
// ViewController.swift
// swift-sample-code
//
// Created by Munesada Yohei on 2015/04/26.
// Copyright (c) 2015 Munesada Yohei. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView = UITableView()
//MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.addUIComponents()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK : UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel?.text = String(indexPath.row)
return cell
}
//MARK : Private Functions
/**
UIコンポーネントをViewに配置する
*/
private func addUIComponents() {
tableView.frame = self.view.frame
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
}
| 27dc9a6e0512ec42050a1ca482f077b4 | 21.634615 | 109 | 0.659303 | false | false | false | false |
ulidev/WWDC2015 | refs/heads/master | Joan Molinas/Joan Molinas/LeftCustomSegue.swift | mit | 1 | //
// LeftCustomSegue.swift
// Joan Molinas
//
// Created by Joan Molinas on 14/4/15.
// Copyright (c) 2015 Joan. All rights reserved.
//
import UIKit
class LeftCustomSegue: UIStoryboardSegue {
override func perform() {
var firstVC = self.sourceViewController.view as UIView!
var secondVC = self.destinationViewController.view as UIView!
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
secondVC.frame = CGRectMake(-screenWidth, 0, screenWidth, screenHeight)
let window = UIApplication.sharedApplication().keyWindow
window?.insertSubview(secondVC, aboveSubview: firstVC)
UIView.animateWithDuration(0.4, animations: { () -> Void in
firstVC.frame = CGRectMake(+screenWidth, 0, screenWidth, screenHeight)
secondVC.frame = CGRectMake(0, 0, screenWidth, screenHeight)
}) { (Finished) -> Void in
self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
animated: false,
completion: nil)
}
}
}
| 75cee998f9b919adb7fa913784fb0d7d | 34.2 | 116 | 0.637987 | false | false | false | false |
matthewpurcell/firefox-ios | refs/heads/master | Storage/SQL/SQLiteLogins.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let IndexLoginsOverrideHostname = "idx_loginsM_is_overridden_hostname"
let IndexLoginsDeletedHostname = "idx_loginsL_is_deleted_hostname"
let AllLoginTables: [String] = [TableLoginsMirror, TableLoginsLocal]
private let OverriddenHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsOverrideHostname) ON \(TableLoginsMirror) (is_overridden, hostname)"
private let DeletedHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsDeletedHostname) ON \(TableLoginsLocal) (is_deleted, hostname)"
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 3 }
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(db: SQLiteDBConnection) -> Bool {
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.Synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local, OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
func updateTable(db: SQLiteDBConnection, from: Int) -> Bool {
let to = self.version
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from < 3 && to >= 3 {
log.debug("Updating logins tables to include version 3 indices")
return self.run(db, queries: [OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db)
}
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)", withArgs: nil)
return err == nil
}
}
public class SQLiteLogins: BrowserLogins {
private let db: BrowserDB
private static let MainColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
private static let MainWithLastUsedColumns = MainColumns + ", timeLastUsed, timesUsed"
private static let LoginColumns = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(LoginsTable())
}
private class func populateLogin(login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
private class func constructLogin<T: Login>(row: SDRow, c: T.Type) -> T {
let credential = NSURLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: NSURLCredentialPersistence.None)
// There was a bug in previous versions of the app where we saved only the hostname and not the
// scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and
// hostname by converting to a URL first. If there is no valid hostname or scheme for the URL,
// fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace
// to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
let hostnameString = (row["hostname"] as? String) ?? ""
let hostnameURL = hostnameString.asURL
let scheme = hostnameURL?.scheme
let port = hostnameURL?.port?.integerValue ?? 0
// Check for malformed hostname urls in the DB
let host: String
var malformedHostname = false
if let h = hostnameURL?.host {
host = h
} else {
host = hostnameString
malformedHostname = true
}
let protectionSpace = NSURLProtectionSpace(host: host,
port: port,
`protocol`: scheme,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
login.hasMalformedHostname = malformedHostname
return login
}
class func LocalLoginFactory(row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
private class func LoginFactory(row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
private class func LoginDataFactory(row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
private class func LoginUsageDataFactory(row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
let notification = NSNotification(name: NotificationDataLoginDidChange, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
public func getLoginDataForGUID(guid: GUID) -> Deferred<Maybe<Login>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overriden IS NOT 1 AND guid = ? " +
"ORDER BY hostname ASC " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
>>== { value in
if let login = value[0] {
return deferMaybe(login)
} else {
return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)"))
}
}
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
// Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB.
// In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without
// a scheme. Check for these as well.
let args: Args = [
protectionSpace.urlString(),
protectionSpace.host,
protectionSpace.urlString(),
protectionSpace.host,
]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [
protectionSpace.urlString(), username, protectionSpace.host,
protectionSpace.urlString(), username, protectionSpace.host
]
usernameMatch = "username = ?"
} else {
args = [
protectionSpace.urlString(), protectionSpace.host,
protectionSpace.urlString(), protectionSpace.host
]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login: \(username), \(args[0])")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
public func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> {
return searchLoginsWithQuery(nil)
}
public func searchLoginsWithQuery(query: String?) -> Deferred<Maybe<Cursor<Login>>> {
let projection = SQLiteLogins.LoginColumns
var searchClauses = [String]()
var args: Args? = nil
if let query = query where !query.isEmpty {
// Add wildcards to change query to 'contains in' and add them to args. We need 6 args because
// we include the where clause twice: Once for the local table and another for the remote.
args = (0..<6).map { _ in
return "%\(query)%" as String?
}
searchClauses.append(" username LIKE ? ")
searchClauses.append(" password LIKE ? ")
searchClauses.append(" hostname LIKE ? ")
}
let whereSearchClause = searchClauses.count > 0 ? "AND" + searchClauses.joinWithSeparator("OR") : ""
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 " + whereSearchClause +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 " + whereSearchClause +
"ORDER BY hostname ASC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
}
public func addLogin(login: LoginData) -> Success {
if let error = login.isValid.failureValue {
return deferMaybe(error)
}
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.New.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
private func cloneMirrorToOverlay(whereClause whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password "
let local = ", local_modified, is_deleted, sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM \(TableLoginsMirror) \(whereClause ?? "")"
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
private func ensureLocalOverlayExistsForGUID(guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { row in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
private func cloneMirrorToOverlay(guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
private func markMirrorAsOverridden(guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
if let error = new.isValid.failureValue {
return deferMaybe(error)
}
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [NSNumber(unsignedLongLong: nowMicro), NSNumber(unsignedLongLong: nowMilli), guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
public func removeLoginByGUID(guid: GUID) -> Success {
return removeLoginsWithGUIDs([guid])
}
public func removeLoginsWithGUIDs(guids: [GUID]) -> Success {
if guids.isEmpty {
return succeed()
}
let nowMillis = NSDate.now()
let inClause = BrowserDB.varlist(guids.count)
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.New.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.Changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid IN \(inClause)"
let markMirrorAsOverridden =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid IN \(inClause)"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run([
(delete, args),
(update, args),
(markMirrorAsOverridden, args),
(insert, args)
]) >>> effect(self.notifyLoginDidChange)
}
public func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.New.rawValue)"
let nowMillis = NSDate.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.Changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
private func storeReconciledLogin(login: Login) -> Success {
let dateMilli = NSNumber(unsignedLongLong: NSDate.now())
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.Changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
private func applyChangedLogin(upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
private func mirrorArgs(login: ServerLogin) -> Args {
let args: Args = [
NSNumber(unsignedLongLong: login.serverModified),
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
NSNumber(unsignedLongLong: login.timeCreated),
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
private func updateMirrorToLogin(login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
private func insertNewMirror(login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
private func findLocalRecordByContent(login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch (cursor.count) {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
private func resolveConflictBetween(local local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
private func resolveConflictWithoutParentBetween(local local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.Synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted(guids: [GUID]) -> Success {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
let checkLoginsMirror = "SELECT 1 FROM \(TableLoginsMirror)"
let checkLoginsLocal = "SELECT 1 FROM \(TableLoginsLocal) WHERE sync_status IS NOT \(SyncStatus.New.rawValue)"
let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)"
return self.db.queryReturnsResults(sql)
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.New.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
| ec5c809be8f2dc0af9a7c745c541e2ad | 42.104418 | 204 | 0.61092 | false | false | false | false |
yarshure/Surf | refs/heads/UIKitForMac | Surf/CountrySelectController.swift | bsd-3-clause | 1 | //
// CountrySelectController.swift
// Surf
//
// Created by yarshure on 16/2/22.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
protocol CountryDelegate:class {
func countrySelected(controller: CountrySelectController, code:String)//
}
class CountrySelectController: SFTableViewController {
var list:[String] = []
weak var delegate:CountryDelegate?
//var code:String!
func loadCountrys(){
let path = Bundle.main.path(forResource: "ISO_3166.txt", ofType: nil)
do {
let str = try String.init(contentsOfFile: path!, encoding: .utf8)
list = str.components(separatedBy: "\n")
}catch let error {
alertMessageAction("\(error.localizedDescription)",complete: nil)
}
}
override func viewDidLoad() {
self.title = "Select Country"
loadCountrys()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = list[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.delegate?.countrySelected(controller: self, code: list[indexPath.row])
_ = self.navigationController?.popViewController(animated: true)
}
}
| 60369e27489dade238039a69a58d7c58 | 34.528302 | 109 | 0.667552 | false | false | false | false |
RayTW/Swift8ComicSDK | refs/heads/master | Pods/Swift8ComicSDK/Swift8ComicSDK/Classes/StringUtility.swift | mit | 2 | //
// File.swift
// Pods
//
// Created by ray.lee on 2017/6/12.
//
//
import Foundation
open class StringUtility{
open static let ENCODE_BIG5 = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.big5_HKSCS_1999.rawValue))
open static let ENCODE_GB2312 = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))
public init() {
}
open class func count(_ source : String) -> Int{
return source.characters.count
}
open class func indexOf(source : String, search : String) -> Range<String.Index>?{
return source.range(of: search)
}
open class func lastIndexOf( source : String, target: String) -> Int {
let ret = source.range(of: target, options: .backwards)
if( ret != nil){
let result = source.characters.distance(from: source.characters.startIndex, to: (ret?.lowerBound)!)
return result
}
return -1
}
open class func indexOfInt(_ source : String, _ search : String) -> Int{
let range = source.range(of: search)
let result = source.characters.distance(from: source.characters.startIndex, to: (range?.lowerBound)!)
return result;
}
open class func indexOfUpper(source : String, search : String) -> String.Index?{
let range = source.range(of: search)
guard range != nil else {
return nil
}
return range?.upperBound;
}
open class func indexOfLower(source : String, search : String) -> String.Index?{
let range = source.range(of: search)
guard range != nil else {
return nil
}
return range?.lowerBound;
}
open class func substring(source : String, upper : String.Index, lower : String.Index) -> String{
let range = upper ..< lower
return String(source[range])
}
open class func substring(_ source : String,_ upperString : String,_ lowerString : String ) -> String?{
let upper : String.Index? = indexOfUpper(source: source, search: upperString)
let lower : String.Index? = indexOfLower(source: source, search: lowerString)
if(upper != nil && lower != nil){
let range = upper! ..< lower!
return String(source[range])
}
return nil
}
open class func lastSubstring(_ source : String,_ upperString : String,_ lowerString : String ) -> String?{
let upperIndex = lastIndexOf(source: source, target: upperString)
let lowerIndex = lastIndexOf(source: source, target: lowerString)
if(upperIndex != -1 && lowerIndex != -1){
return substring(source, upperIndex + upperString.characters.count, lowerIndex)
}
return nil
}
open class func substring(source : String, beginIndex : String.Index) -> String{
return String(source[beginIndex...])
//source.substring(from: beginIndex)
}
//like JAVA String.substring(beginIndex, endIndex)
open class func substring(_ source : String, _ beginIndex : Int, _ endIndex : Int ) -> String{
let subLen : Int = endIndex - beginIndex
if(subLen < 0){
return ""
}
let beginInx = source.index(source.startIndex, offsetBy: beginIndex)
let endInx = source.index(source.startIndex, offsetBy: endIndex)
let range = beginInx ..< endInx
return String(source[range])
}
open class func dataToStringBig5(data : Data) -> String{
let string = NSString.init(data: data, encoding: ENCODE_BIG5)
return string! as String;
}
open class func dataToStringGB2312(data : Data) -> String{
let string = NSString.init(data: data, encoding: ENCODE_GB2312)
return string! as String;
}
open class func split(_ source : String, separatedBy : String) -> [String]{
return source.components(separatedBy: separatedBy)
}
open class func trim(_ source : String) -> String{
return source.trimmingCharacters(in: .whitespaces)
}
open class func replace(_ source : String, _ of : String,_ with : String) -> String{
return source.replacingOccurrences(of: of, with: with)
}
open class func urlEncodeUsingBIG5(_ source : String) -> String{
return urlEncode(source, ENCODE_BIG5)
}
open class func urlEncodeUsingGB2312(_ source : String) -> String{
return urlEncode(source, ENCODE_GB2312)
}
open class func urlEncode(_ source : String,_ encode: UInt) -> String{
let encodeUrlString = source.data(using: String.Encoding(rawValue: encode), allowLossyConversion: true)
return encodeUrlString!.hexEncodedString()
}
}
extension Data {
func hexEncodedString() -> String {
return map { String(format: "%%%02hhX", $0) }.joined()
}
}
| 3a0204c499ebafb3ce4e45f8f60ad742 | 31.443038 | 137 | 0.602224 | false | false | false | false |
pinterest/PINCache | refs/heads/master | Carthage/Checkouts/PINCache/Carthage/Checkouts/PINOperation/Example/PINOperationExample/AppDelegate.swift | apache-2.0 | 4 | //
// AppDelegate.swift
// PINOperationExample
//
// Created by Martin Púčik on 02/05/2020.
// Copyright © 2020 Pinterest. All rights reserved.
//
import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
private let queue: PINOperationQueue = PINOperationQueue(maxConcurrentOperations: 5)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let operationCount = 100
let group = DispatchGroup()
for _ in 0..<operationCount {
group.enter()
queue.scheduleOperation({
group.leave()
}, with: .default)
}
let success = group.wait(timeout: .now() + 20)
if success != .success {
fatalError("Timed out before completing 100 operations")
}
return true
}
}
| 31ce758508ab6a83542f4b62355d80e2 | 28.709677 | 145 | 0.643865 | false | false | false | false |
ubclaunchpad/RocketCast | refs/heads/master | RocketCast/EpisodeHeaderTableViewCell.swift | mit | 1 | //
// EpisodeHeaderTableViewCell.swift
// RocketCast
//
// Created by Milton Leung on 2016-11-08.
// Copyright © 2016 UBCLaunchPad. All rights reserved.
//
import UIKit
class EpisodeHeaderTableViewCell: UITableViewCell {
@IBOutlet weak var podcastTitle: UILabel!
@IBOutlet weak var podcastAuthor: UILabel!
@IBOutlet weak var podcastSummary: UILabel!
@IBOutlet weak var coverPhotoView: UIView!
var listOfEpisodes = [Episode]()
var podcast: Podcast! {
didSet {
setupPodcastInfo()
}
}
func setupPodcastInfo() {
let effectsLayer = coverPhotoView.layer
effectsLayer.cornerRadius = 18
effectsLayer.shadowColor = UIColor.black.cgColor
effectsLayer.shadowOffset = CGSize(width: 0, height: 0)
effectsLayer.shadowRadius = 4
effectsLayer.shadowOpacity = 0.4
effectsLayer.shadowPath = UIBezierPath(roundedRect: coverPhotoView.bounds, cornerRadius: coverPhotoView.layer.cornerRadius).cgPath
podcastTitle.text = podcast.title
podcastAuthor.text = podcast.author
podcastSummary.text = podcast.summary
let url = URL(string: (podcast.imageURL)!)
DispatchQueue.global().async {
do {
let data = try Data(contentsOf: url!)
let coverPhoto = UIImageView()
coverPhoto.frame = self.coverPhotoView.bounds
coverPhoto.layer.cornerRadius = 18
coverPhoto.layer.masksToBounds = true
DispatchQueue.main.async {
coverPhoto.image = UIImage(data: data)
self.coverPhotoView.addSubview(coverPhoto)
}
} catch let error as NSError{
Log.error("Error: " + error.debugDescription)
}
}
}
}
| f7bda305d45322eb24aa864f16738062 | 32.428571 | 138 | 0.612714 | false | false | false | false |
mortorqrobotics/MorTeam-ios | refs/heads/master | MorTeam/User.swift | mit | 1 | //
// User.swift
// MorTeam
//
// Created by arvin zadeh on 10/1/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import Foundation
class User {
let _id: String
let firstname: String
let lastname: String
let username: String
let email: String
let phone: String
let position: String
let team: String?
let profPicPath: String
let groups: [String]? //maybe populate later, how to make optional
init(userJSON: JSON){
var allGroupIds = [String]()
self._id = String( describing: userJSON["_id"] )
self.firstname = String( describing: userJSON["firstname"] )
self.lastname = String( describing: userJSON["lastname"] )
self.username = String( describing: userJSON["username"] )
self.position = String( describing: userJSON["position"] )
self.team = String( describing: userJSON["team"] )
self.email = String( describing: userJSON["email"] )
self.phone = String( describing: userJSON["phone"] )
self.profPicPath = String( describing: userJSON["profpicpath"] )
for(_, json):(String, JSON) in userJSON["groups"] {
allGroupIds.append(String(describing: json))
}
self.groups = allGroupIds
}
init(_id: String, firstname: String, lastname: String, username: String, email: String, phone: String, profPicPath: String, team: String, position: String){
self._id = _id
self.firstname = firstname
self.lastname = lastname
self.username = username
self.team = team
self.email = email
self.position = position
self.phone = phone
self.profPicPath = profPicPath
self.groups = [String]() //hmm
}
}
| c96d1ad86c8b918edb51d319573dfde4 | 33.196078 | 160 | 0.62328 | false | false | false | false |
abeschneider/stem | refs/heads/master | Sources/Op/TanhOp.swift | mit | 1 | //
// tanh.swift
// stem
//
// Created by Schneider, Abraham R. on 11/12/16.
// Copyright © 2016 none. All rights reserved.
//
import Foundation
import Tensor
open class TanhOp<S:Storage>: Op<S> where S.ElementType:FloatNumericType {
var _input:Tensor<S> { return inputs[0].output }
public init() {
super.init(inputs: ["input"], outputs: ["output"])
outputs["output"] = [Tensor<S>()]
setAction("input", action: self.inputSet)
}
public init(size:Int) {
super.init(inputs: ["input"], outputs: ["output"])
outputs["output"] = [Tensor<S>(Extent(size))]
setAction("input", action: self.inputSet)
}
// required for Copyable
public required init(op:Op<S>, shared:Bool) {
super.init(inputs: ["input"], outputs: ["output"])
outputs["output"] = [Tensor<S>(op.output.shape)]
}
func inputSet(_ label:String, input:[Source<S>]) {
setInput(to: input[0])
output.resize(input[0].output.shape)
}
open override func apply() {
tanh(_input, output: output)
}
}
open class TanhGrad<S:Storage>: Op<S>, Gradient where S.ElementType:FloatNumericType {
public typealias OpType = TanhOp<S>
open var _tanh:Tensor<S> { return inputs[0].output }
open var _input:Tensor<S> { return inputs[1].output }
open var _gradOutput:Tensor<S> { return inputs[2].output }
public required init(op:TanhOp<S>) {
let input:Source<S> = op.inputs[0]
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
connect(from: op, "output", to: self, "op")
connect(from: input.op!, "output", to: self, "input")
output = Tensor<S>(op.output.shape)
}
public init(size:Int) {
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
output = Tensor<S>(Extent(size))
}
public init(op:TanhOp<S>, input:Op<S>, gradInput:Op<S>) {
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
connect(from: op, "output", to: self, "op")
connect(from: input, "output", to: self, "input")
connect(from: gradInput, to: self, "gradOutput")
output = Tensor<S>(op.output.shape)
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
/*
dtanh(x)/dx = (1 - tanh^2 x)*dx
*/
open override func apply() {
let result = _tanh * _tanh
result *= -1
add(S.ElementType(1.0), result, result: result)
result *= _gradOutput
output += result
}
open override func reset() {
fill(output, value: 0)
}
}
extension TanhOp: Differentiable {
public func gradient() -> GradientType {
return TanhGrad<S>(op: self)
}
}
| c96f2fea6877b42fef13a37465c00de3 | 28.07 | 86 | 0.570003 | false | false | false | false |
einsteinx2/iSub | refs/heads/master | Carthage/Checkouts/XCGLogger/Sources/XCGLogger/Destinations/AutoRotatingFileDestination.swift | gpl-3.0 | 1 | //
// AutoRotatingFileDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2017-03-31.
// Copyright © 2017 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
// MARK: - AutoRotatingFileDestination
/// A destination that outputs log details to files in a log folder, with auto-rotate options (by size or by time)
open class AutoRotatingFileDestination: FileDestination {
// MARK: - Constants
static let autoRotatingFileDefaultMaxFileSize: UInt64 = 1_048_576
static let autoRotatingFileDefaultMaxTimeInterval: TimeInterval = 600
// MARK: - Properties
/// Option: desired maximum size of a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize {
didSet {
if targetMaxFileSize < 1 {
targetMaxFileSize = .max
}
}
}
/// Option: desired maximum time in seconds stored in a log file, if 0, no maximum (log files may exceed this, it's a guideline only)
open var targetMaxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval {
didSet {
if targetMaxTimeInterval < 1 {
targetMaxTimeInterval = 0
}
}
}
/// Option: the desired number of archived log files to keep (number of log files may exceed this, it's a guideline only)
open var targetMaxLogFiles: UInt8 = 10 {
didSet {
cleanUpLogFiles()
}
}
/// Option: the URL of the folder to store archived log files (defaults to the same folder as the initial log file)
open var archiveFolderURL: URL? = nil {
didSet {
guard let archiveFolderURL = archiveFolderURL else { return }
try? FileManager.default.createDirectory(at: archiveFolderURL, withIntermediateDirectories: true)
}
}
/// Option: an optional closure to execute whenever the log is auto rotated
open var autoRotationCompletion: ((_ success: Bool) -> Void)? = nil
/// A custom date formatter object to use as the suffix of archived log files
internal var _customArchiveSuffixDateFormatter: DateFormatter? = nil
/// The date formatter object to use as the suffix of archived log files
open var archiveSuffixDateFormatter: DateFormatter! {
get {
guard _customArchiveSuffixDateFormatter == nil else { return _customArchiveSuffixDateFormatter }
struct Statics {
static var archiveSuffixDateFormatter: DateFormatter = {
let defaultArchiveSuffixDateFormatter = DateFormatter()
defaultArchiveSuffixDateFormatter.locale = NSLocale.current
defaultArchiveSuffixDateFormatter.dateFormat = "_yyyy-MM-dd_HHmmss"
return defaultArchiveSuffixDateFormatter
}()
}
return Statics.archiveSuffixDateFormatter
}
set {
_customArchiveSuffixDateFormatter = newValue
}
}
/// Size of the current log file
internal var currentLogFileSize: UInt64 = 0
/// Start time of the current log file
internal var currentLogStartTimeInterval: TimeInterval = 0
/// The base file name of the log file
internal var baseFileName: String = "xcglogger"
/// The extension of the log file name
internal var fileExtension: String = "log"
// MARK: - Class Properties
/// A default folder for storing archived logs if one isn't supplied
open class var defaultLogFolderURL: URL {
#if os(OSX)
let defaultLogFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#elseif os(iOS) || os(tvOS) || os(watchOS)
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let defaultLogFolderURL = urls[urls.endIndex - 1].appendingPathComponent("log")
try? FileManager.default.createDirectory(at: defaultLogFolderURL, withIntermediateDirectories: true)
return defaultLogFolderURL
#endif
}
// MARK: - Life Cycle
public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [String: Any]? = nil, maxFileSize: UInt64 = autoRotatingFileDefaultMaxFileSize, maxTimeInterval: TimeInterval = autoRotatingFileDefaultMaxTimeInterval, archiveSuffixDateFormatter: DateFormatter? = nil) {
super.init(owner: owner, writeToFile: writeToFile, identifier: identifier, shouldAppend: true, appendMarker: shouldAppend ? appendMarker : nil, attributes: attributes)
currentLogStartTimeInterval = Date().timeIntervalSince1970
self.archiveSuffixDateFormatter = archiveSuffixDateFormatter
self.shouldAppend = shouldAppend
self.targetMaxFileSize = maxFileSize
self.targetMaxTimeInterval = maxTimeInterval
guard let writeToFileURL = writeToFileURL else { return }
// Calculate some details for naming archived logs based on the current log file path/name
fileExtension = writeToFileURL.pathExtension
baseFileName = writeToFileURL.lastPathComponent
if let fileExtensionRange: Range = baseFileName.range(of: ".\(fileExtension)", options: .backwards),
fileExtensionRange.upperBound >= baseFileName.endIndex {
baseFileName = baseFileName[baseFileName.startIndex ..< fileExtensionRange.lowerBound]
}
let filePath: String = writeToFileURL.path
let logFileName: String = "\(baseFileName).\(fileExtension)"
if let logFileNameRange: Range = filePath.range(of: logFileName, options: .backwards),
logFileNameRange.upperBound >= filePath.endIndex {
let archiveFolderPath: String = filePath[filePath.startIndex ..< logFileNameRange.lowerBound]
archiveFolderURL = URL(fileURLWithPath: "\(archiveFolderPath)")
}
if archiveFolderURL == nil {
archiveFolderURL = type(of: self).defaultLogFolderURL
}
do {
// Initialize starting values for file size and start time so shouldRotate calculations are valid
let fileAttributes: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: filePath)
currentLogFileSize = fileAttributes[.size] as? UInt64 ?? 0
currentLogStartTimeInterval = (fileAttributes[.creationDate] as? Date ?? Date()).timeIntervalSince1970
}
catch let error as NSError {
owner?._logln("Unable to determine current file attributes of log file: \(error.localizedDescription)", level: .warning)
}
// Because we always start by appending, regardless of the shouldAppend setting, we now need to handle the cases where we don't want to append or that we have now reached the rotation threshold for our current log file
if !shouldAppend || shouldRotate() {
rotateFile()
}
}
/// Scan the log folder and delete log files that are no longer relevant.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func cleanUpLogFiles() {
var archivedFileURLs: [URL] = self.archivedFileURLs()
guard archivedFileURLs.count > Int(targetMaxLogFiles) else { return }
archivedFileURLs.removeFirst(Int(targetMaxLogFiles))
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Delete all archived log files.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func purgeArchivedLogFiles() {
let fileManager: FileManager = FileManager.default
for archivedFileURL in archivedFileURLs() {
do {
try fileManager.removeItem(at: archivedFileURL)
}
catch let error as NSError {
owner?._logln("Unable to delete old archived log file \(archivedFileURL.path): \(error.localizedDescription)", level: .error)
}
}
}
/// Get the URLs of the archived log files.
///
/// - Parameters: None.
///
/// - Returns: An array of file URLs pointing to previously archived log files, sorted with the most recent logs first.
///
open func archivedFileURLs() -> [URL] {
let archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: archiveFolderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) else { return [] }
guard let identifierData: Data = identifier.data(using: .utf8) else { return [] }
var archivedDetails: [(url: URL, timestamp: String)] = []
for fileURL in fileURLs {
guard let archivedLogIdentifierOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey) else { continue }
guard let archivedLogIdentifierData = archivedLogIdentifierOptionalData else { continue }
guard archivedLogIdentifierData == identifierData else { continue }
guard let timestampOptionalData = try? fileURL.extendedAttribute(forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey) else { continue }
guard let timestampData = timestampOptionalData else { continue }
guard let timestamp = String(data: timestampData, encoding: .utf8) else { continue }
archivedDetails.append((fileURL, timestamp))
}
archivedDetails.sort(by: { (lhs, rhs) -> Bool in lhs.timestamp > rhs.timestamp })
var archivedFileURLs: [URL] = []
for archivedDetail in archivedDetails {
archivedFileURLs.append(archivedDetail.url)
}
return archivedFileURLs
}
/// Rotate the current log file.
///
/// - Parameters: None.
///
/// - Returns: Nothing.
///
open func rotateFile() {
var archiveFolderURL: URL = (self.archiveFolderURL ?? type(of: self).defaultLogFolderURL)
archiveFolderURL = archiveFolderURL.appendingPathComponent("\(baseFileName)\(archiveSuffixDateFormatter.string(from: Date()))")
archiveFolderURL = archiveFolderURL.appendingPathExtension(fileExtension)
rotateFile(to: archiveFolderURL, closure: autoRotationCompletion)
currentLogStartTimeInterval = Date().timeIntervalSince1970
currentLogFileSize = 0
cleanUpLogFiles()
}
/// Determine if the log file should be rotated.
///
/// - Parameters: None.
///
/// - Returns:
/// - true: The log file should be rotated.
/// - false: The log file doesn't have to be rotated.
///
open func shouldRotate() -> Bool {
// Do not rotate until critical setup has been completed so that we do not accidentally rotate once to the defaultLogFolderURL before determining the desired log location
guard archiveFolderURL != nil else { return false }
// File Size
guard currentLogFileSize < targetMaxFileSize else { return true }
// Time Interval, zero = never rotate
guard targetMaxTimeInterval > 0 else { return false }
// Time Interval, else check time
guard Date().timeIntervalSince1970 - currentLogStartTimeInterval < targetMaxTimeInterval else { return true }
return false
}
// MARK: - Overridden Methods
/// Write the log to the log file.
///
/// - Parameters:
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func write(message: String) {
currentLogFileSize += UInt64(message.characters.count)
super.write(message: message)
if shouldRotate() {
rotateFile()
}
}
}
| 1bd485918fdd643f729b38492cc03517 | 43.178947 | 369 | 0.662219 | false | false | false | false |
renshu16/DouyuSwift | refs/heads/master | DouyuSwift/DouyuSwift/Classes/Main/View/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// DouyuSwift
//
// Created by ToothBond on 16/11/10.
// Copyright © 2016年 ToothBond. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class{
func pageContentView(_ contentView : PageContentView, progress : CGFloat, startIndex : Int, targetIndex : Int);
}
private let CollectionCellIdentify : String = "ccIdentify"
class PageContentView: UIView {
fileprivate var childVCs : [UIViewController]
fileprivate var parentViewController : UIViewController
fileprivate var orginScrollX : CGFloat = 0
weak var delegate : PageContentViewDelegate?
fileprivate var isScrollFromClick : Bool = false
fileprivate lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CollectionCellIdentify)
return collectionView
}()
init(frame: CGRect, childVCs : [UIViewController], parentViewController: UIViewController) {
self.childVCs = childVCs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
fileprivate func setupUI() {
for child in childVCs {
parentViewController.addChildViewController(child)
}
collectionView.frame = self.bounds
addSubview(collectionView)
}
}
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionCellIdentify, for: indexPath)
let childVC = childVCs[indexPath.item]
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
childVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVC.view)
return cell
}
}
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isScrollFromClick = false
orginScrollX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isScrollFromClick {
return
}
//判断是左滑 or 右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width;
var progress : CGFloat = 0
var startIndex : Int = 0
var targetIndex : Int = 0
if currentOffsetX > orginScrollX {
//左滑
progress = currentOffsetX / scrollViewW - floor(currentOffsetX/scrollViewW)
startIndex = Int(currentOffsetX / scrollViewW)
targetIndex = startIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
if currentOffsetX - orginScrollX == scrollViewW {
progress = 1
targetIndex = startIndex
}
} else {
//右滑
progress = (orginScrollX - currentOffsetX)/scrollViewW
targetIndex = Int(currentOffsetX / scrollViewW)
startIndex = targetIndex + 1
if startIndex < 0 {
startIndex = 0
}
if startIndex >= childVCs.count {
startIndex = childVCs.count - 1
}
if orginScrollX - currentOffsetX == scrollViewW {
progress = 1
startIndex = targetIndex
}
}
// print("progress = \(progress); startIndex = \(startIndex); targetIndex = \(targetIndex)")
delegate?.pageContentView(self, progress: progress, startIndex: startIndex, targetIndex: targetIndex)
}
}
extension PageContentView {
func setCurrentIndex(_ currentIndex:Int) {
isScrollFromClick = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y:0), animated: false)
}
}
| 3b7fe59cff0c4a249e65ad76cd6c7e96 | 31.730769 | 121 | 0.632785 | false | false | false | false |
chromium/chromium | refs/heads/main | tensorflow_lite_support/ios/test/task/vision/image_segmenter/TFLImageSegmenterTests.swift | apache-2.0 | 9 | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import GMLImageUtils
import XCTest
@testable import TFLImageSegmenter
class ImageSegmenterTests: XCTestCase {
static let bundle = Bundle(for: ImageSegmenterTests.self)
static let modelPath = bundle.path(
forResource: "deeplabv3",
ofType: "tflite")
// The maximum fraction of pixels in the candidate mask that can have a
// different class than the golden mask for the test to pass.
let kGoldenMaskTolerance: Float = 1e-2
// Magnification factor used when creating the golden category masks to make
// them more human-friendly. Each pixel in the golden masks has its value
// multiplied by this factor, i.e. a value of 10 means class index 1, a value of
// 20 means class index 2, etc.
let kGoldenMaskMagnificationFactor: UInt8 = 10
let deepLabV3SegmentationWidth = 257
let deepLabV3SegmentationHeight = 257
func verifyDeeplabV3PartialSegmentationResult(_ coloredLabels: [ColoredLabel]) {
self.verifyColoredLabel(
coloredLabels[0],
expectedR: 0,
expectedG: 0,
expectedB: 0,
expectedLabel: "background")
self.verifyColoredLabel(
coloredLabels[1],
expectedR: 128,
expectedG: 0,
expectedB: 0,
expectedLabel: "aeroplane")
self.verifyColoredLabel(
coloredLabels[2],
expectedR: 0,
expectedG: 128,
expectedB: 0,
expectedLabel: "bicycle")
self.verifyColoredLabel(
coloredLabels[3],
expectedR: 128,
expectedG: 128,
expectedB: 0,
expectedLabel: "bird")
self.verifyColoredLabel(
coloredLabels[4],
expectedR: 0,
expectedG: 0,
expectedB: 128,
expectedLabel: "boat")
self.verifyColoredLabel(
coloredLabels[5],
expectedR: 128,
expectedG: 0,
expectedB: 128,
expectedLabel: "bottle")
self.verifyColoredLabel(
coloredLabels[6],
expectedR: 0,
expectedG: 128,
expectedB: 128,
expectedLabel: "bus")
self.verifyColoredLabel(
coloredLabels[7],
expectedR: 128,
expectedG: 128,
expectedB: 128,
expectedLabel: "car")
self.verifyColoredLabel(
coloredLabels[8],
expectedR: 64,
expectedG: 0,
expectedB: 0,
expectedLabel: "cat")
self.verifyColoredLabel(
coloredLabels[9],
expectedR: 192,
expectedG: 0,
expectedB: 0,
expectedLabel: "chair")
self.verifyColoredLabel(
coloredLabels[10],
expectedR: 64,
expectedG: 128,
expectedB: 0,
expectedLabel: "cow")
self.verifyColoredLabel(
coloredLabels[11],
expectedR: 192,
expectedG: 128,
expectedB: 0,
expectedLabel: "dining table")
self.verifyColoredLabel(
coloredLabels[12],
expectedR: 64,
expectedG: 0,
expectedB: 128,
expectedLabel: "dog")
self.verifyColoredLabel(
coloredLabels[13],
expectedR: 192,
expectedG: 0,
expectedB: 128,
expectedLabel: "horse")
self.verifyColoredLabel(
coloredLabels[14],
expectedR: 64,
expectedG: 128,
expectedB: 128,
expectedLabel: "motorbike")
self.verifyColoredLabel(
coloredLabels[15],
expectedR: 192,
expectedG: 128,
expectedB: 128,
expectedLabel: "person")
self.verifyColoredLabel(
coloredLabels[16],
expectedR: 0,
expectedG: 64,
expectedB: 0,
expectedLabel: "potted plant")
self.verifyColoredLabel(
coloredLabels[17],
expectedR: 128,
expectedG: 64,
expectedB: 0,
expectedLabel: "sheep")
self.verifyColoredLabel(
coloredLabels[18],
expectedR: 0,
expectedG: 192,
expectedB: 0,
expectedLabel: "sofa")
self.verifyColoredLabel(
coloredLabels[19],
expectedR: 128,
expectedG: 192,
expectedB: 0,
expectedLabel: "train")
self.verifyColoredLabel(
coloredLabels[20],
expectedR: 0,
expectedG: 64,
expectedB: 128,
expectedLabel: "tv")
}
func verifyColoredLabel(
_ coloredLabel: ColoredLabel,
expectedR: UInt,
expectedG: UInt,
expectedB: UInt,
expectedLabel: String
) {
XCTAssertEqual(
coloredLabel.r,
expectedR)
XCTAssertEqual(
coloredLabel.g,
expectedG)
XCTAssertEqual(
coloredLabel.b,
expectedB)
XCTAssertEqual(
coloredLabel.label,
expectedLabel)
}
func testSuccessfullInferenceOnMLImageWithUIImage() throws {
let modelPath = try XCTUnwrap(ImageSegmenterTests.modelPath)
let imageSegmenterOptions = ImageSegmenterOptions(modelPath: modelPath)
let imageSegmenter =
try ImageSegmenter.segmenter(options: imageSegmenterOptions)
let gmlImage = try XCTUnwrap(
MLImage.imageFromBundle(
class: type(of: self),
filename: "segmentation_input_rotation0",
type: "jpg"))
let segmentationResult: SegmentationResult =
try XCTUnwrap(imageSegmenter.segment(mlImage: gmlImage))
XCTAssertEqual(segmentationResult.segmentations.count, 1)
let coloredLabels = try XCTUnwrap(segmentationResult.segmentations[0].coloredLabels)
verifyDeeplabV3PartialSegmentationResult(coloredLabels)
let categoryMask = try XCTUnwrap(segmentationResult.segmentations[0].categoryMask)
XCTAssertEqual(deepLabV3SegmentationWidth, categoryMask.width)
XCTAssertEqual(deepLabV3SegmentationHeight, categoryMask.height)
let goldenMaskImage = try XCTUnwrap(
MLImage.imageFromBundle(
class: type(of: self),
filename: "segmentation_golden_rotation0",
type: "png"))
let pixelBuffer = goldenMaskImage.grayScalePixelBuffer().takeRetainedValue()
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
let pixelBufferBaseAddress = (try XCTUnwrap(CVPixelBufferGetBaseAddress(pixelBuffer)))
.assumingMemoryBound(to: UInt8.self)
let numPixels = deepLabV3SegmentationWidth * deepLabV3SegmentationHeight
let mask = try XCTUnwrap(categoryMask.mask)
var inconsistentPixels: Float = 0.0
for i in 0..<numPixels {
if mask[i] * kGoldenMaskMagnificationFactor != pixelBufferBaseAddress[i] {
inconsistentPixels += 1
}
}
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
XCTAssertLessThan(inconsistentPixels / Float(numPixels), kGoldenMaskTolerance)
}
}
| 0064af46de696bbbb8c3bc8dd4d537db | 25.563433 | 90 | 0.672707 | false | false | false | false |
beckjing/contacts | refs/heads/master | contacts/contacts/contact/View/JYCContactEditBasicInfoTableViewCell/JYCContactEditBasicInfoTableViewCell.swift | mit | 1 | //
// JYCContactEditBasicInfoTableViewCell.swift
// contacts
//
// Created by yuecheng on 24/06/2017.
// Copyright © 2017 yuecheng. All rights reserved.
//
import UIKit
import AddressBook
typealias openPhotoCallBack = () -> Void
class JYCContactEditBasicInfoTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var userImageButton: UIButton!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var companyTextField: UITextField!
var record:JYCContactModel?
var originalHashValue:Int?
var openPhoto:openPhotoCallBack?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configView(record:JYCContactModel) {
self.record = record
self.originalHashValue = record.hashValue
self.userImageButton.setBackgroundImage( record.userImage, for: UIControlState.normal)
if record.hasUserImage! {
self.userImageButton.setTitle("", for: UIControlState.normal)
}
else {
self.userImageButton.setTitle("添加\n照片", for: UIControlState.normal)
}
self.firstNameTextField.text = record.firstName
self.lastNameTextField.text = record.lastName
self.companyTextField.text = record.company
self.firstNameTextField.delegate = self
self.lastNameTextField.delegate = self
self.companyTextField.delegate = self
}
@IBAction func clickImageButton(_ sender: UIButton) {
if self.openPhoto != nil {
self.openPhoto!()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == self.firstNameTextField {
self.record?.firstName = textField.text
}
else if textField == self.lastNameTextField {
self.record?.lastName = textField.text
}
else if textField == self.companyTextField {
self.record?.company = textField.text
}
}
}
| 660c006adc4fc92d11578aef33ad53d4 | 29.972603 | 94 | 0.66077 | false | false | false | false |
ChristianKienle/highway | refs/heads/master | Sources/Task/Model/Termination.swift | mit | 1 | import Foundation
public struct Termination {
// MARK: - Types
public typealias Reason = Process.TerminationReason
// MARK: - Convenience
public static let success = Termination(reason: .exit, status: EXIT_SUCCESS)
public static let failure = Termination(reason: .exit, status: EXIT_FAILURE)
// MARK: - Init
public init(describing process: Process) {
self.init(reason: process.terminationReason, status: process.terminationStatus)
}
init(reason: Reason, status: Int32) {
self.reason = reason
self.status = status
}
// MARK: - Properties
public let reason: Reason
public let status: Int32
public var isSuccess: Bool { return status == EXIT_SUCCESS }
}
extension Termination: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "[\(isSuccess ? "SUCCESS" : "ERROR")] Status: \(status), Reason: \(reason)"
}
public var debugDescription: String { return description }
}
extension Termination: Equatable {
public static func ==(lhs: Termination, rhs: Termination) -> Bool {
return lhs.status == rhs.status && lhs.reason == rhs.reason
}
}
extension Process.TerminationReason: CustomStringConvertible {
public var description: String {
switch self {
case .exit: return "Exited normally."
case .uncaughtSignal: return "Exited due to an uncaught signal."
}
}
}
| ca4b16a81c77535f1262fe8007da40ca | 30.869565 | 90 | 0.670532 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/DescriptionWelcomePanelViewController.swift | mit | 1 |
class DescriptionWelcomePanelViewController: UIViewController, Themeable {
private var theme = Theme.standard
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
scrollViewGradientView.apply(theme: theme)
titleLabel.textColor = theme.colors.primaryText
bottomLabel.textColor = theme.colors.primaryText
nextButton.backgroundColor = theme.colors.link
}
@IBOutlet private var containerView:UIView!
@IBOutlet private var titleLabel:UILabel!
@IBOutlet private var bottomLabel:UILabel!
@IBOutlet private var nextButton:AutoLayoutSafeMultiLineButton!
@IBOutlet private var scrollView:UIScrollView!
@IBOutlet private var scrollViewGradientView:WelcomePanelScrollViewGradient!
@IBOutlet private var nextButtonContainerView:UIView!
private var viewControllerForContainerView:UIViewController? = nil
var pageType:DescriptionWelcomePageType = .intro
override func viewDidLoad() {
super.viewDidLoad()
apply(theme: theme)
embedContainerControllerView()
updateUIStrings()
// If the button itself was directly an arranged stackview subview we couldn't
// set padding contraints and also get clean collapsing when enabling isHidden.
nextButtonContainerView.isHidden = pageType != .exploration
view.wmf_configureSubviewsForDynamicType()
}
private func embedContainerControllerView() {
let containerController = DescriptionWelcomeContentsViewController.wmf_viewControllerFromDescriptionWelcomeStoryboard()
containerController.pageType = pageType
addChild(containerController)
containerView.wmf_addSubviewWithConstraintsToEdges(containerController.view)
containerController.apply(theme: theme)
containerController.didMove(toParent: self)
}
private func updateUIStrings(){
switch pageType {
case .intro:
titleLabel.text = WMFLocalizedString("description-welcome-descriptions-title", value:"Title descriptions", comment:"Title text explaining title descriptions")
case .exploration:
titleLabel.text = WMFLocalizedString("description-welcome-concise-title", value:"Keep it short", comment:"Title text explaining descriptions should be concise")
}
bottomLabel.text = CommonStrings.welcomePromiseTitle
nextButton.setTitle(WMFLocalizedString("description-welcome-start-editing-button", value:"Start editing", comment:"Text for button for dismissing description editing welcome screens"), for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if scrollView.wmf_contentSizeHeightExceedsBoundsHeight() {
scrollView.wmf_flashVerticalScrollIndicatorAfterDelay(1.5)
}
}
}
private extension UIScrollView {
func wmf_contentSizeHeightExceedsBoundsHeight() -> Bool {
return contentSize.height - bounds.size.height > 0
}
func wmf_flashVerticalScrollIndicatorAfterDelay(_ delay: TimeInterval) {
dispatchOnMainQueueAfterDelayInSeconds(delay) {
self.flashScrollIndicators()
}
}
}
class WelcomePanelScrollViewGradient : UIView, Themeable {
private var theme = Theme.standard
func apply(theme: Theme) {
self.theme = theme
layer.backgroundColor = theme.colors.midBackground.cgColor
}
private let fadeHeight = 6.0
private var normalizedFadeHeight: Double {
return bounds.size.height > 0 ? fadeHeight / Double(bounds.size.height) : 0
}
private lazy var gradientMask: CAGradientLayer = {
let mask = CAGradientLayer()
mask.startPoint = .zero
mask.endPoint = CGPoint(x: 0, y: 1)
mask.colors = [
UIColor.black.cgColor,
UIColor.clear.cgColor,
UIColor.clear.cgColor,
UIColor.black.cgColor
]
layer.mask = mask
return mask
}()
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
guard layer == gradientMask.superlayer else {
assertionFailure("Unexpected superlayer")
return
}
gradientMask.locations = [ // Keep fade heights fixed to `fadeHeight` regardless of text view height
0.0,
NSNumber(value: normalizedFadeHeight), // upper stop
NSNumber(value: 1.0 - normalizedFadeHeight), // lower stop
1.0
]
gradientMask.frame = bounds
}
}
| 7a5dfd83652ab22a205d5174e41878f6 | 37.916667 | 206 | 0.682013 | false | false | false | false |
LYM-mg/MGDS_Swift | refs/heads/master | IQKeyboardManagerSwift/IQTextView/IQTextView.swift | mit | 2 | //
// IQTextView.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// 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
/** @abstract UITextView with placeholder support */
@available(iOSApplicationExtension, unavailable)
@objc open class IQTextView: UITextView {
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
}
@objc override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
}
@objc override open func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: UITextView.textDidChangeNotification, object: self)
}
deinit {
IQ_PlaceholderLabel.removeFromSuperview()
}
private var placeholderInsets: UIEdgeInsets {
return UIEdgeInsets(top: self.textContainerInset.top, left: self.textContainerInset.left + self.textContainer.lineFragmentPadding, bottom: self.textContainerInset.bottom, right: self.textContainerInset.right + self.textContainer.lineFragmentPadding)
}
private var placeholderExpectedFrame: CGRect {
let placeholderInsets = self.placeholderInsets
let maxWidth = self.frame.width-placeholderInsets.left-placeholderInsets.right
let expectedSize = IQ_PlaceholderLabel.sizeThatFits(CGSize(width: maxWidth, height: self.frame.height-placeholderInsets.top-placeholderInsets.bottom))
return CGRect(x: placeholderInsets.left, y: placeholderInsets.top, width: maxWidth, height: expectedSize.height)
}
lazy var IQ_PlaceholderLabel: UILabel = {
let label = UILabel()
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.font = self.font
label.textAlignment = self.textAlignment
label.backgroundColor = UIColor.clear
label.isAccessibilityElement = false
#if swift(>=5.1)
label.textColor = UIColor.systemGray
#else
label.textColor = UIColor.lightText
#endif
label.alpha = 0
self.addSubview(label)
return label
}()
/** @abstract To set textView's placeholder text color. */
@IBInspectable open var placeholderTextColor: UIColor? {
get {
return IQ_PlaceholderLabel.textColor
}
set {
IQ_PlaceholderLabel.textColor = newValue
}
}
/** @abstract To set textView's placeholder text. Default is nil. */
@IBInspectable open var placeholder: String? {
get {
return IQ_PlaceholderLabel.text
}
set {
IQ_PlaceholderLabel.text = newValue
refreshPlaceholder()
}
}
/** @abstract To set textView's placeholder attributed text. Default is nil. */
open var attributedPlaceholder: NSAttributedString? {
get {
return IQ_PlaceholderLabel.attributedText
}
set {
IQ_PlaceholderLabel.attributedText = newValue
refreshPlaceholder()
}
}
@objc override open func layoutSubviews() {
super.layoutSubviews()
IQ_PlaceholderLabel.frame = placeholderExpectedFrame
}
@objc internal func refreshPlaceholder() {
if !text.isEmpty || !attributedText.string.isEmpty {
IQ_PlaceholderLabel.alpha = 0
} else {
IQ_PlaceholderLabel.alpha = 1
}
}
@objc override open var text: String! {
didSet {
refreshPlaceholder()
}
}
open override var attributedText: NSAttributedString! {
didSet {
refreshPlaceholder()
}
}
@objc override open var font: UIFont? {
didSet {
if let unwrappedFont = font {
IQ_PlaceholderLabel.font = unwrappedFont
} else {
IQ_PlaceholderLabel.font = UIFont.systemFont(ofSize: 12)
}
}
}
@objc override open var textAlignment: NSTextAlignment {
didSet {
IQ_PlaceholderLabel.textAlignment = textAlignment
}
}
@objc override weak open var delegate: UITextViewDelegate? {
get {
refreshPlaceholder()
return super.delegate
}
set {
super.delegate = newValue
}
}
@objc override open var intrinsicContentSize: CGSize {
guard !hasText else {
return super.intrinsicContentSize
}
var newSize = super.intrinsicContentSize
let placeholderInsets = self.placeholderInsets
newSize.height = placeholderExpectedFrame.height + placeholderInsets.top + placeholderInsets.bottom
return newSize
}
}
| 4bb04a0da89b4e3a74d394d75c76a82b | 32.148148 | 257 | 0.669753 | false | false | false | false |
pennlabs/penn-mobile-ios | refs/heads/main | PennMobile/Dining/SwiftUI/Views/Venue/DiningVenueView.swift | mit | 1 | //
// DiningVenueView.swift
// PennMobile
//
// Created by CHOI Jongmin on 9/6/2020.
// Copyright © 2020 PennLabs. All rights reserved.
//
import SwiftUI
struct DiningVenueView: View {
@EnvironmentObject var diningVM: DiningViewModelSwiftUI
@StateObject var diningAnalyticsViewModel = DiningAnalyticsViewModel()
var body: some View {
List {
Section(header: CustomHeader(name: "Dining Balance", refreshButton: true).environmentObject(diningAnalyticsViewModel), content: {
Section(header: DiningViewHeader().environmentObject(diningAnalyticsViewModel), content: {})
})
ForEach(diningVM.ordering, id: \.self) { venueType in
Section(header: CustomHeader(name: venueType.fullDisplayName).environmentObject(diningAnalyticsViewModel)) {
ForEach(diningVM.diningVenues[venueType] ?? []) { venue in
NavigationLink(destination: DiningVenueDetailView(for: venue).environmentObject(diningVM)) {
DiningVenueRow(for: venue)
.padding(.vertical, 4)
}
}
}
}
}
.task {
await diningVM.refreshVenues()
await diningVM.refreshBalance()
}
.navigationBarHidden(false)
.listStyle(.plain)
}
}
struct CustomHeader: View {
let name: String
var refreshButton = false
@State var didError = false
@State var showMissingDiningTokenAlert = false
@State var showDiningLoginView = false
@Environment(\.presentationMode) var presentationMode
@EnvironmentObject var diningAnalyticsViewModel: DiningAnalyticsViewModel
func showCorrectAlert () -> Alert {
if !Account.isLoggedIn {
return Alert(title: Text("You must log in to access this feature."), message: Text("Please login on the \"More\" tab."), dismissButton: .default(Text("Ok")))
} else {
return Alert(title: Text("\"Penn Mobile\" requires you to login to Campus Express to use this feature."),
message: Text("Would you like to continue to campus express?"),
primaryButton: .default(Text("Continue"), action: {showDiningLoginView = true}),
secondaryButton: .cancel({ presentationMode.wrappedValue.dismiss() }))
}
}
var body: some View {
HStack {
Text(name)
.font(.system(size: 21, weight: .semibold))
.foregroundColor(.primary)
Spacer()
if refreshButton {
Button(action: {
guard Account.isLoggedIn, KeychainAccessible.instance.getDiningToken() != nil, let diningExpiration = UserDefaults.standard.getDiningTokenExpiration(), Date() <= diningExpiration else {
print("Should show alert")
showMissingDiningTokenAlert = true
return
}
Task.init() {
await DiningViewModelSwiftUI.instance.refreshBalance()
}
}, label: {
Image(systemName: "arrow.counterclockwise")
})
}
}
.padding()
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.background(Color(UIColor.uiBackground))
// Default Text Case for Header is Caps Lock
.textCase(nil)
.sheet(isPresented: $showDiningLoginView) {
DiningLoginNavigationView()
.environmentObject(diningAnalyticsViewModel)
}
// Note: The Alert view is soon to be deprecated, but .alert(_:isPresented:presenting:actions:message:) is available in iOS15+
.alert(isPresented: $showMissingDiningTokenAlert) {
showCorrectAlert()
}
// iOS 15+ implementation
/* .alert(Account.isLoggedIn ? "\"Penn Mobile\" requires you to login to Campus Express to use this feature." : "You must log in to access this feature.", isPresented: $showMissingDiningTokenAlert
) {
if (!Account.isLoggedIn) {
Button("OK") {}
} else {
Button("Continue") { showDiningLoginView = true }
Button("Cancel") { presentationMode.wrappedValue.dismiss() }
}
} message: {
if (!Account.isLoggedIn) {
Text("Please login on the \"More\" tab.")
} else {
Text("Would you like to continue to Campus Express?")
}
} */
}
}
| 334e01e58b04357d303b954a0df87b50 | 40.192982 | 205 | 0.57517 | false | false | false | false |
walterscarborough/LibSpacey | refs/heads/master | platforms/xcode/LibSpaceyTests/FlashcardGraderTests.swift | mit | 1 | import XCTest
@testable import LibSpacey
class LibSpaceyTests: XCTestCase {
func test_flashcardGrader_canGrade_flashcards() {
let flashcardWrapper = FlashcardWrapper()
if let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Unknown, currentDate: Date()) {
XCTAssertNotNil(gradedFlashcardWrapper)
}
else {
XCTFail()
}
}
func test_flashcardGrader_grade0() {
let october_24_2016 = 1477294292;
let october_25_2016 = 1477380692;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Unknown, currentDate: Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 0)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 1.7)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_25_2016)))
}
func test_flashcardGrader_grade1() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.VeryHard, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 0)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 1.96)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade2() {
let october_24_2016 = 1477294292;
let october_25_2016 = 1477380692;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_24_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Hard, currentDate: Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 0)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.18)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_25_2016)))
}
func test_flashcardGrader_grade3() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Medium, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 1)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.36)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade4() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.Easy, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 1)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.5)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade5() {
let october_23_2016 = 1477207892;
let october_24_2016 = 1477294292;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.VeryEasy, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 1)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 1)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.6)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_24_2016)))
}
func test_flashcardGrader_grade_long_repetition() {
let october_23_2016 = 1477207892;
let october_27_2016 = 1477553492;
let flashcardWrapper = FlashcardWrapper()
flashcardWrapper.interval = 6
flashcardWrapper.repetition = 6
flashcardWrapper.previousDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
flashcardWrapper.nextDate = Date(timeIntervalSince1970: TimeInterval(october_23_2016))
let gradedFlashcardWrapper = FlashcardWrapperGrader.gradeFlashcardWrapper(flashcardWrapper, grade: Grade.VeryEasy, currentDate: Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.repetition, 7)
XCTAssertEqual(gradedFlashcardWrapper?.interval, 4)
XCTAssertEqual(gradedFlashcardWrapper?.easinessFactor, 2.6)
XCTAssertEqual(gradedFlashcardWrapper?.previousDate, Date(timeIntervalSince1970: TimeInterval(october_23_2016)))
XCTAssertEqual(gradedFlashcardWrapper?.nextDate, Date(timeIntervalSince1970: TimeInterval(october_27_2016)))
}
}
| d1e35accccfe8d4a7a577f1b9abb00a8 | 51.506944 | 195 | 0.758101 | false | true | false | false |
hackiftekhar/IQKeyboardManager | refs/heads/master | IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift | mit | 1 | //
// IQToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// 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
/** @abstract IQToolbar for IQKeyboardManager. */
@available(iOSApplicationExtension, unavailable)
@objc open class IQToolbar: UIToolbar, UIInputViewAudioFeedback {
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
sizeToFit()
autoresizingMask = .flexibleWidth
self.isTranslucent = true
self.barTintColor = nil
let positions: [UIBarPosition] = [.any, .bottom, .top, .topAttached]
for position in positions {
self.setBackgroundImage(nil, forToolbarPosition: position, barMetrics: .default)
self.setShadowImage(nil, forToolbarPosition: .any)
}
//Background color
self.backgroundColor = nil
}
/**
Previous bar button of toolbar.
*/
private var privatePreviousBarButton: IQBarButtonItem?
@objc open var previousBarButton: IQBarButtonItem {
get {
if privatePreviousBarButton == nil {
privatePreviousBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
}
return privatePreviousBarButton!
}
set (newValue) {
privatePreviousBarButton = newValue
}
}
/**
Next bar button of toolbar.
*/
private var privateNextBarButton: IQBarButtonItem?
@objc open var nextBarButton: IQBarButtonItem {
get {
if privateNextBarButton == nil {
privateNextBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
}
return privateNextBarButton!
}
set (newValue) {
privateNextBarButton = newValue
}
}
/**
Title bar button of toolbar.
*/
private var privateTitleBarButton: IQTitleBarButtonItem?
@objc open var titleBarButton: IQTitleBarButtonItem {
get {
if privateTitleBarButton == nil {
privateTitleBarButton = IQTitleBarButtonItem(title: nil)
privateTitleBarButton?.accessibilityLabel = "Title"
privateTitleBarButton?.accessibilityIdentifier = privateTitleBarButton?.accessibilityLabel
}
return privateTitleBarButton!
}
set (newValue) {
privateTitleBarButton = newValue
}
}
/**
Done bar button of toolbar.
*/
private var privateDoneBarButton: IQBarButtonItem?
@objc open var doneBarButton: IQBarButtonItem {
get {
if privateDoneBarButton == nil {
privateDoneBarButton = IQBarButtonItem(title: nil, style: .done, target: nil, action: nil)
}
return privateDoneBarButton!
}
set (newValue) {
privateDoneBarButton = newValue
}
}
/**
Fixed space bar button of toolbar.
*/
private var privateFixedSpaceBarButton: IQBarButtonItem?
@objc open var fixedSpaceBarButton: IQBarButtonItem {
get {
if privateFixedSpaceBarButton == nil {
privateFixedSpaceBarButton = IQBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
}
privateFixedSpaceBarButton!.isSystemItem = true
if #available(iOS 10, *) {
privateFixedSpaceBarButton!.width = 6
} else {
privateFixedSpaceBarButton!.width = 20
}
return privateFixedSpaceBarButton!
}
set (newValue) {
privateFixedSpaceBarButton = newValue
}
}
@objc override open func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFit = super.sizeThatFits(size)
sizeThatFit.height = 44
return sizeThatFit
}
@objc override open var tintColor: UIColor! {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems {
item.tintColor = tintColor
}
}
}
}
@objc override open func layoutSubviews() {
super.layoutSubviews()
if #available(iOS 11, *) {
return
} else if let customTitleView = titleBarButton.customView {
var leftRect = CGRect.null
var rightRect = CGRect.null
var isTitleBarButtonFound = false
let sortedSubviews = self.subviews.sorted(by: { (view1: UIView, view2: UIView) -> Bool in
if view1.frame.minX != view2.frame.minX {
return view1.frame.minX < view2.frame.minX
} else {
return view1.frame.minY < view2.frame.minY
}
})
for barButtonItemView in sortedSubviews {
if isTitleBarButtonFound {
rightRect = barButtonItemView.frame
break
} else if barButtonItemView === customTitleView {
isTitleBarButtonFound = true
//If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem)
} else if barButtonItemView.isKind(of: UIControl.self) {
leftRect = barButtonItemView.frame
}
}
let titleMargin: CGFloat = 16
let maxWidth: CGFloat = self.frame.width - titleMargin*2 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
let maxHeight = self.frame.height
let sizeThatFits = customTitleView.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
var titleRect: CGRect
if sizeThatFits.width > 0, sizeThatFits.height > 0 {
let width = min(sizeThatFits.width, maxWidth)
let height = min(sizeThatFits.height, maxHeight)
var xPosition: CGFloat
if !leftRect.isNull {
xPosition = titleMargin + leftRect.maxX + ((maxWidth - width)/2)
} else {
xPosition = titleMargin
}
let yPosition = (maxHeight - height)/2
titleRect = CGRect(x: xPosition, y: yPosition, width: width, height: height)
} else {
var xPosition: CGFloat
if !leftRect.isNull {
xPosition = titleMargin + leftRect.maxX
} else {
xPosition = titleMargin
}
let width: CGFloat = self.frame.width - titleMargin*2 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX)
titleRect = CGRect(x: xPosition, y: 0, width: width, height: maxHeight)
}
customTitleView.frame = titleRect
}
}
@objc open var enableInputClicksWhenVisible: Bool {
return true
}
}
| 09835f6ca33d25e7f19b7401544940c4 | 31.948413 | 170 | 0.599061 | false | false | false | false |
stefanilie/swift-playground | refs/heads/master | Swift3 and iOS10/Playgrounds/LearnSwift.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
print("Hello Playground")
//this is a constant
let straw = "berry";
//this is a simple variable
var blue = "berry";
//you can it's value
blue = "sofa"
//This is a declaration of a variable containg the type of the variable
var declaredType: Double = 50
//if you want to make combine values, you have to cast them
var combined: String = blue + String(declaredType)
//You can even add the string inline by doing this:
print("The number of sofas is \(String(declaredType))");
//this is a list
var list = ["this", "is", "a", "list"];
//This a dict
var dict = [
"this": 4,
"dict": 4,
"is": 2
]
//ControlFlow
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0;
for score in individualScores {
if score < 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//Optional values
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello \(name)"
}
//The bellow example is a perfect representation of
//how to use the ?? operator
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "hi \(nickName ?? fullName)"
//Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raising and make ants on a log")
case "cucumber", "watercress":
print("That would make a good tea sandwich")
case let x where x.hasSuffix("pepper"):
print("It's a nice and spicy \(x)")
default:
print("Everything tastes like soup")
}
// To demonstrate the control flow, here's a simple example of a guess game
//First, here is the number we have to guess
//let diceRoll = Int(arc4random_uniform(20)+1);
//var hasBeenGuessed: Bool = false;
//var numberOfTryes: Float = 0;
//var readNumber: Int;
| e7e021b2bb7df1b7363cf4363fd1f1a4 | 19.787234 | 75 | 0.676561 | false | false | false | false |
mysangle/algorithm-study | refs/heads/master | range-sum-query-mutable/FenwickTree.swift | mit | 1 | /**
* array = [3,9,5,6,10,8,7,1,2,4]의 1 ~ 6 사이의 합을 구하는 예
*
* let fenwick = FenwickTree(array)
* fenwick.range(1, 6)
*/
public class FenwickTree {
var orig: [Int];
var tree: [Int];
init(_ orig: [Int]) {
self.orig = orig
// 0번은 사용하지 않는다. 1번부터 사용한다. 그래야 비트 연산이 가능해진다.
self.tree = [Int](repeating: 0, count: orig.count + 1)
for i in 0..<orig.count {
add(i, orig[i])
}
print(tree)
}
private func add(_ pos: Int, _ val: Int) {
var position = pos + 1
while position < tree.count {
tree[position] += val;
// 가장 하위의 비트값을 더한다.
position += (position & -position)
}
}
public func sum(_ pos: Int) -> Int {
var position = pos + 1
var sum = 0
while position > 0 {
sum += tree[position]
// 가장 하위의 비트값을 뺀다.
position &= (position - 1)
}
return sum
}
public func update(_ pos: Int, _ val: Int) {
let diff = val - orig[pos]
orig[pos] = val
add(pos, diff)
}
public func range(_ leftBound: Int, _ rightBound: Int) -> Int {
return sum(rightBound) - sum(leftBound - 1)
}
}
| 4e8f2ffa747f46479d38bc9f696dece4 | 23.326923 | 67 | 0.472727 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Reader/ReaderDetailViewController.swift | gpl-2.0 | 1 | import Foundation
import CocoaLumberjack
import WordPressShared
import QuartzCore
open class ReaderDetailViewController: UIViewController, UIViewControllerRestoration {
static let restorablePostObjectURLhKey: String = "RestorablePostObjectURLKey"
// Structs for Constants
fileprivate struct DetailConstants {
static let LikeCountKeyPath = "likeCount"
static let MarginOffset = CGFloat(8.0)
}
fileprivate struct DetailAnalyticsConstants {
static let TypeKey = "post_detail_type"
static let TypeNormal = "normal"
static let TypePreviewSite = "preview_site"
static let OfflineKey = "offline_view"
static let PixelStatReferrer = "https://wordpress.com/"
}
// MARK: - Properties & Accessors
// Footer views
@IBOutlet fileprivate weak var footerView: UIView!
@IBOutlet fileprivate weak var tagButton: UIButton!
@IBOutlet fileprivate weak var commentButton: UIButton!
@IBOutlet fileprivate weak var likeButton: UIButton!
@IBOutlet fileprivate weak var footerViewHeightConstraint: NSLayoutConstraint!
// Wrapper views
@IBOutlet fileprivate weak var textHeaderStackView: UIStackView!
@IBOutlet fileprivate weak var textFooterStackView: UIStackView!
fileprivate weak var textFooterTopConstraint: NSLayoutConstraint!
// Header realated Views
@IBOutlet fileprivate weak var headerView: UIView!
@IBOutlet fileprivate weak var blavatarImageView: UIImageView!
@IBOutlet fileprivate weak var blogNameButton: UIButton!
@IBOutlet fileprivate weak var blogURLLabel: UILabel!
@IBOutlet fileprivate weak var menuButton: UIButton!
// Content views
@IBOutlet fileprivate weak var featuredImageView: UIImageView!
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var bylineView: UIView!
@IBOutlet fileprivate weak var avatarImageView: CircularImageView!
@IBOutlet fileprivate weak var bylineLabel: UILabel!
@IBOutlet fileprivate weak var textView: WPRichContentView!
@IBOutlet fileprivate weak var attributionView: ReaderCardDiscoverAttributionView!
// Spacers
@IBOutlet fileprivate weak var featuredImageBottomPaddingView: UIView!
@IBOutlet fileprivate weak var titleBottomPaddingView: UIView!
@IBOutlet fileprivate weak var bylineBottomPaddingView: UIView!
open var shouldHideComments = false
fileprivate var didBumpStats = false
fileprivate var didBumpPageViews = false
fileprivate var footerViewHeightConstraintConstant = CGFloat(0.0)
fileprivate let sharingController = PostSharingController()
var currentPreferredStatusBarStyle = UIStatusBarStyle.lightContent {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return currentPreferredStatusBarStyle
}
open var post: ReaderPost? {
didSet {
oldValue?.removeObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath)
oldValue?.inUse = false
if let newPost = post, let context = newPost.managedObjectContext {
newPost.inUse = true
ContextManager.sharedInstance().save(context)
newPost.addObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath, options: .new, context: nil)
}
if isViewLoaded {
configureView()
}
}
}
fileprivate var isLoaded: Bool {
return post != nil
}
// MARK: - Convenience Factories
/// Convenience method for instantiating an instance of ReaderDetailViewController
/// for a particular topic.
///
/// - Parameters:
/// - topic: The reader topic for the list.
///
/// - Return: A ReaderListViewController instance.
///
open class func controllerWithPost(_ post: ReaderPost) -> ReaderDetailViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: "ReaderDetailViewController") as! ReaderDetailViewController
controller.post = post
return controller
}
open class func controllerWithPostID(_ postID: NSNumber, siteID: NSNumber) -> ReaderDetailViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: "ReaderDetailViewController") as! ReaderDetailViewController
controller.setupWithPostID(postID, siteID: siteID)
return controller
}
// MARK: - State Restoration
open static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? {
guard let path = coder.decodeObject(forKey: restorablePostObjectURLhKey) as? String else {
return nil
}
let context = ContextManager.sharedInstance().mainContext
guard let url = URL(string: path),
let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: url) else {
return nil
}
guard let post = (try? context.existingObject(with: objectID)) as? ReaderPost else {
return nil
}
return controllerWithPost(post)
}
open override func encodeRestorableState(with coder: NSCoder) {
if let post = post {
coder.encode(post.objectID.uriRepresentation().absoluteString, forKey: type(of: self).restorablePostObjectURLhKey)
}
super.encodeRestorableState(with: coder)
}
// MARK: - LifeCycle Methods
deinit {
if let post = post, let context = post.managedObjectContext {
post.inUse = false
ContextManager.sharedInstance().save(context)
post.removeObserver(self, forKeyPath: DetailConstants.LikeCountKeyPath)
}
NotificationCenter.default.removeObserver(self)
}
open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
restorationClass = type(of: self)
return super.awakeAfter(using: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
setupContentHeaderAndFooter()
textView.alpha = 0
footerView.isHidden = true
// Hide the featured image and its padding until we know there is one to load.
featuredImageView.isHidden = true
featuredImageBottomPaddingView.isHidden = true
// Styles
applyStyles()
setupNavBar()
if let _ = post {
configureView()
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// The UIApplicationDidBecomeActiveNotification notification is broadcast
// when the app is resumed as a part of split screen multitasking on the iPad.
NotificationCenter.default.addObserver(self, selector: #selector(ReaderDetailViewController.handleApplicationDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
bumpStats()
bumpPageViewsForPost()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
setBarsHidden(false, animated: animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// This is something we do to help with the resizing that can occur with
// split screen multitasking on the iPad.
view.layoutIfNeeded()
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let y = textView.contentOffset.y
let position = textView.closestPosition(to: CGPoint(x: 0.0, y: y))
coordinator.animate(
alongsideTransition: { (_) in
if let position = position, let textRange = self.textView.textRange(from: position, to: position) {
let rect = self.textView.firstRect(for: textRange)
self.textView.setContentOffset(CGPoint(x: 0.0, y: rect.origin.y), animated: false)
}
},
completion: { (_) in
self.updateContentInsets()
self.updateTextViewMargins()
})
// Make sure that the bars are visible after switching from landscape
// to portrait orientation. The content might have been scrollable in landscape
// orientation, but it might not be in portrait orientation. We'll assume the bars
// should be visible for safety sake and for performance since WPRichTextView updates
// its intrinsicContentSize too late for get an accurate scrollWiew.contentSize
// in the completion handler below.
if size.height > size.width {
self.setBarsHidden(false)
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (object! as! NSObject == post!) && (keyPath! == DetailConstants.LikeCountKeyPath) {
// Note: The intent here is to update the action buttons, specifically the
// like button, *after* both likeCount and isLiked has changed. The order
// of the properties is important.
configureLikeActionButton(true)
}
}
// MARK: - Multitasking Splitview Support
func handleApplicationDidBecomeActive(_ notification: Foundation.Notification) {
view.layoutIfNeeded()
}
// MARK: - Setup
open func setupWithPostID(_ postID: NSNumber, siteID: NSNumber) {
let title = NSLocalizedString("Loading Post...", comment: "Text displayed while loading a post.")
WPNoResultsView.displayAnimatedBox(withTitle: title, message: nil, view: view)
textView.alpha = 0.0
let context = ContextManager.sharedInstance().mainContext
let service = ReaderPostService(managedObjectContext: context)
service.fetchPost(
postID.uintValue,
forSite: siteID.uintValue,
success: {[weak self] (post: ReaderPost?) in
WPNoResultsView.remove(from: self?.view)
self?.textView.alpha = 1.0
self?.post = post
}, failure: {[weak self] (error: Error?) in
DDLogError("Error fetching post for detail: \(String(describing: error?.localizedDescription))")
let title = NSLocalizedString("Error Loading Post", comment: "Text displayed when load post fails.")
WPNoResultsView.displayAnimatedBox(withTitle: title, message: nil, view: self?.view)
}
)
}
/// Composes the views for the post header and Discover attribution.
fileprivate func setupContentHeaderAndFooter() {
// Add the footer first so its behind the header. This way the header
// obscures the footer until its properly positioned.
textView.addSubview(textFooterStackView)
textView.addSubview(textHeaderStackView)
textHeaderStackView.topAnchor.constraint(equalTo: textView.topAnchor).isActive = true
textFooterTopConstraint = NSLayoutConstraint(item: textFooterStackView,
attribute: .top,
relatedBy: .equal,
toItem: textView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
textView.addConstraint(textFooterTopConstraint)
textFooterTopConstraint.constant = textFooterYOffset()
textView.setContentOffset(CGPoint.zero, animated: false)
}
/// Sets the left and right textContainerInset to preserve readable content margins.
fileprivate func updateContentInsets() {
var insets = textView.textContainerInset
let margin = view.readableContentGuide.layoutFrame.origin.x
insets.left = margin - DetailConstants.MarginOffset
insets.right = margin - DetailConstants.MarginOffset
textView.textContainerInset = insets
textView.layoutIfNeeded()
}
/// Returns the y position for the textfooter. Assign to the textFooter's top
/// constraint constant to correctly position the view.
fileprivate func textFooterYOffset() -> CGFloat {
let length = textView.textStorage.length
if length == 0 {
return textView.contentSize.height - textFooterStackView.frame.height
}
let range = NSRange(location: length - 1, length: 0)
let frame = textView.frameForTextInRange(range)
if frame.minY == CGFloat.infinity {
// A value of infinity can occur when a device is rotated 180 degrees.
// It will sort it self out as the rotation aniation progresses,
// so just return the existing constant.
return textFooterTopConstraint.constant
}
return frame.minY
}
/// Updates the bounds of the placeholder top and bottom text attachments so
/// there is enough vertical space for the text header and footer views.
fileprivate func updateTextViewMargins() {
textView.topMargin = textHeaderStackView.frame.height
textView.bottomMargin = textFooterStackView.frame.height
textFooterTopConstraint.constant = textFooterYOffset()
}
fileprivate func setupNavBar() {
configureNavTitle()
// Don't show 'Reader' in the next-view back button
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
}
// MARK: - Configuration
/**
Applies the default styles to the cell's subviews
*/
fileprivate func applyStyles() {
WPStyleGuide.applyReaderCardSiteButtonStyle(blogNameButton)
WPStyleGuide.applyReaderCardBylineLabelStyle(bylineLabel)
WPStyleGuide.applyReaderCardBylineLabelStyle(blogURLLabel)
WPStyleGuide.applyReaderCardTitleLabelStyle(titleLabel)
WPStyleGuide.applyReaderCardTagButtonStyle(tagButton)
WPStyleGuide.applyReaderCardActionButtonStyle(commentButton)
WPStyleGuide.applyReaderCardActionButtonStyle(likeButton)
}
fileprivate func configureView() {
textView.alpha = 1
configureNavTitle()
configureShareButton()
configureHeader()
configureFeaturedImage()
configureTitle()
configureByLine()
configureRichText()
configureDiscoverAttribution()
configureTag()
configureActionButtons()
configureFooterIfNeeded()
adjustInsetsForTextDirection()
bumpStats()
bumpPageViewsForPost()
NotificationCenter.default.addObserver(self,
selector: #selector(ReaderDetailViewController.handleBlockSiteNotification(_:)),
name: NSNotification.Name(rawValue: ReaderPostMenu.BlockSiteNotification),
object: nil)
view.layoutIfNeeded()
textView.setContentOffset(CGPoint.zero, animated: false)
}
fileprivate func configureNavTitle() {
let placeholder = NSLocalizedString("Post", comment: "Placeholder title for ReaderPostDetails.")
self.title = post?.postTitle ?? placeholder
}
fileprivate func configureShareButton() {
// Share button.
let image = UIImage(named: "icon-posts-share")!.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let button = CustomHighlightButton(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
button.setImage(image, for: UIControlState())
button.addTarget(self, action: #selector(ReaderDetailViewController.didTapShareButton(_:)), for: .touchUpInside)
let shareButton = UIBarButtonItem(customView: button)
shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Spoken accessibility label")
WPStyleGuide.setRightBarButtonItemWithCorrectSpacing(shareButton, for: navigationItem)
}
fileprivate func configureHeader() {
// Blavatar
let placeholder = UIImage(named: "post-blavatar-placeholder")
blavatarImageView.image = placeholder
let size = blavatarImageView.frame.size.width * UIScreen.main.scale
if let url = post?.siteIconForDisplay(ofSize: Int(size)) {
blavatarImageView.setImageWith(url, placeholderImage: placeholder)
}
// Site name
let blogName = post?.blogNameForDisplay()
blogNameButton.setTitle(blogName, for: UIControlState())
blogNameButton.setTitle(blogName, for: .highlighted)
blogNameButton.setTitle(blogName, for: .disabled)
// Enable button only if not previewing a site.
if let topic = post!.topic {
blogNameButton.isEnabled = !ReaderHelpers.isTopicSite(topic)
}
// If the button is enabled also listen for taps on the avatar.
if blogNameButton.isEnabled {
let tgr = UITapGestureRecognizer(target: self, action: #selector(ReaderDetailViewController.didTapHeaderAvatar(_:)))
blavatarImageView.addGestureRecognizer(tgr)
}
if let siteURL: NSString = post!.siteURLForDisplay() as NSString? {
blogURLLabel.text = siteURL.components(separatedBy: "//").last
}
}
fileprivate func configureFeaturedImage() {
var url = post!.featuredImageURLForDisplay()
guard url != nil else {
return
}
// Do not display the featured image if it exists in the content.
if post!.contentIncludesFeaturedImage() {
return
}
var request: URLRequest
if !(post!.isPrivate()) {
let size = CGSize(width: featuredImageView.frame.width, height: 0)
url = PhotonImageURLHelper.photonURL(with: size, forImageURL: url)
request = URLRequest(url: url!)
} else if (url?.host != nil) && (url?.host!.hasSuffix("wordpress.com"))! {
// private wpcom image needs special handling.
request = requestForURL(url!)
} else {
// private but not a wpcom hosted image
request = URLRequest(url: url!)
}
// Define a success block to make the image visible and update its aspect ratio constraint
let successBlock: ((URLRequest, HTTPURLResponse?, UIImage) -> Void) = { [weak self] (request: URLRequest, response: HTTPURLResponse?, image: UIImage) in
guard self != nil else {
return
}
self!.configureFeaturedImageWithImage(image)
}
featuredImageView.setImageWith(request, placeholderImage: nil, success: successBlock, failure: nil)
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateContentInsets()
updateTextViewMargins()
}
fileprivate func configureFeaturedImageWithImage(_ image: UIImage) {
// Unhide the views
featuredImageView.isHidden = false
featuredImageBottomPaddingView.isHidden = false
// Now that we have the image, create an aspect ratio constraint for
// the featuredImageView
let ratio = image.size.height / image.size.width
let constraint = NSLayoutConstraint(item: featuredImageView,
attribute: .height,
relatedBy: .equal,
toItem: featuredImageView,
attribute: .width,
multiplier: ratio,
constant: 0)
constraint.priority = UILayoutPriorityDefaultHigh
featuredImageView.addConstraint(constraint)
featuredImageView.setNeedsUpdateConstraints()
featuredImageView.image = image
// Listen for taps so we can display the image detail
let tgr = UITapGestureRecognizer(target: self, action: #selector(ReaderDetailViewController.didTapFeaturedImage(_:)))
featuredImageView.addGestureRecognizer(tgr)
view.layoutIfNeeded()
updateTextViewMargins()
}
fileprivate func requestForURL(_ url: URL) -> URLRequest {
var requestURL = url
let absoluteString = requestURL.absoluteString
if !absoluteString.hasPrefix("https") {
let sslURL = absoluteString.replacingOccurrences(of: "http", with: "https")
requestURL = URL(string: sslURL)!
}
let request = NSMutableURLRequest(url: requestURL)
let acctServ = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext)
if let account = acctServ.defaultWordPressComAccount() {
let token = account.authToken
let headerValue = String(format: "Bearer %@", token!)
request.addValue(headerValue, forHTTPHeaderField: "Authorization")
}
return request as URLRequest
}
fileprivate func configureTitle() {
if let title = post?.titleForDisplay() {
titleLabel.attributedText = NSAttributedString(string: title, attributes: WPStyleGuide.readerDetailTitleAttributes())
titleLabel.isHidden = false
} else {
titleLabel.attributedText = nil
titleLabel.isHidden = true
}
}
fileprivate func configureByLine() {
// Avatar
let placeholder = UIImage(named: "gravatar")
if let avatarURLString = post?.authorAvatarURL,
let url = URL(string: avatarURLString) {
avatarImageView.setImageWith(url, placeholderImage: placeholder)
}
// Byline
let author = post?.authorForDisplay()
let dateAsString = post?.dateForDisplay()?.mediumString()
let byline: String
if let author = author, let date = dateAsString {
byline = author + " · " + date
} else {
byline = author ?? dateAsString ?? String()
}
bylineLabel.text = byline
}
fileprivate func configureRichText() {
guard let post = post else {
return
}
textView.isPrivate = post.isPrivate()
textView.content = post.contentForDisplay()
updateTextViewMargins()
}
fileprivate func configureDiscoverAttribution() {
if post?.sourceAttributionStyle() == SourceAttributionStyle.none {
attributionView.isHidden = true
} else {
attributionView.configureViewWithVerboseSiteAttribution(post!)
attributionView.delegate = self
}
}
fileprivate func configureTag() {
var tag = ""
if let rawTag = post?.primaryTag {
if rawTag.characters.count > 0 {
tag = "#\(rawTag)"
}
}
tagButton.isHidden = tag.characters.count == 0
tagButton.setTitle(tag, for: UIControlState())
tagButton.setTitle(tag, for: .highlighted)
}
fileprivate func configureActionButtons() {
resetActionButton(likeButton)
resetActionButton(commentButton)
guard let post = post else {
assertionFailure()
return
}
// Show likes if logged in, or if likes exist, but not if external
if (ReaderHelpers.isLoggedIn() || post.likeCount.intValue > 0) && !post.isExternal {
configureLikeActionButton()
}
// Show comments if logged in and comments are enabled, or if comments exist.
// But only if it is from wpcom (jetpack and external is not yet supported).
// Nesting this conditional cos it seems clearer that way
if post.isWPCom && !shouldHideComments {
let commentCount = post.commentCount?.intValue ?? 0
if (ReaderHelpers.isLoggedIn() && post.commentsOpen) || commentCount > 0 {
configureCommentActionButton()
}
}
}
fileprivate func resetActionButton(_ button: UIButton) {
button.setTitle(nil, for: UIControlState())
button.setTitle(nil, for: .highlighted)
button.setTitle(nil, for: .disabled)
button.setImage(nil, for: UIControlState())
button.setImage(nil, for: .highlighted)
button.setImage(nil, for: .disabled)
button.isSelected = false
button.isHidden = true
button.isEnabled = true
}
fileprivate func configureActionButton(_ button: UIButton, title: String?, image: UIImage?, highlightedImage: UIImage?, selected: Bool) {
button.setTitle(title, for: UIControlState())
button.setTitle(title, for: .highlighted)
button.setTitle(title, for: .disabled)
button.setImage(image, for: UIControlState())
button.setImage(highlightedImage, for: .highlighted)
button.setImage(image, for: .disabled)
button.isSelected = selected
button.isHidden = false
}
fileprivate func configureLikeActionButton(_ animated: Bool = false) {
likeButton.isEnabled = ReaderHelpers.isLoggedIn()
let title = post!.likeCountForDisplay()
let imageName = post!.isLiked ? "icon-reader-liked" : "icon-reader-like"
let image = UIImage(named: imageName)
let highlightImage = UIImage(named: "icon-reader-like-highlight")
let selected = post!.isLiked
configureActionButton(likeButton, title: title, image: image, highlightedImage: highlightImage, selected: selected)
if animated {
playLikeButtonAnimation()
}
}
fileprivate func playLikeButtonAnimation() {
let likeImageView = likeButton.imageView!
let frame = likeButton.convert(likeImageView.frame, from: likeImageView)
let imageView = UIImageView(image: UIImage(named: "icon-reader-liked"))
imageView.frame = frame
likeButton.addSubview(imageView)
let animationDuration = 0.3
if likeButton.isSelected {
// Prep a mask to hide the likeButton's image, since changes to visiblility and alpha are ignored
let mask = UIView(frame: frame)
mask.backgroundColor = view.backgroundColor
likeButton.addSubview(mask)
likeButton.bringSubview(toFront: imageView)
// Configure starting state
imageView.alpha = 0.0
let angle = (-270.0 * CGFloat.pi) / 180.0
let rotate = CGAffineTransform(rotationAngle: angle)
let scale = CGAffineTransform(scaleX: 3.0, y: 3.0)
imageView.transform = rotate.concatenating(scale)
// Perform the animations
UIView.animate(withDuration: animationDuration,
animations: { () in
let angle = (1.0 * CGFloat.pi) / 180.0
let rotate = CGAffineTransform(rotationAngle: angle)
let scale = CGAffineTransform(scaleX: 0.75, y: 0.75)
imageView.transform = rotate.concatenating(scale)
imageView.alpha = 1.0
imageView.center = likeImageView.center // In case the button's imageView shifted position
},
completion: { (_) in
UIView.animate(withDuration: animationDuration,
animations: { () in
imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
},
completion: { (_) in
mask.removeFromSuperview()
imageView.removeFromSuperview()
})
})
} else {
UIView .animate(withDuration: animationDuration,
animations: { () -> Void in
let angle = (120.0 * CGFloat.pi) / 180.0
let rotate = CGAffineTransform(rotationAngle: angle)
let scale = CGAffineTransform(scaleX: 3.0, y: 3.0)
imageView.transform = rotate.concatenating(scale)
imageView.alpha = 0
},
completion: { (_) in
imageView.removeFromSuperview()
})
}
}
fileprivate func configureCommentActionButton() {
let title = post!.commentCount.stringValue
let image = UIImage(named: "icon-reader-comment")
let highlightImage = UIImage(named: "icon-reader-comment-highlight")
configureActionButton(commentButton, title: title, image: image, highlightedImage: highlightImage, selected: false)
}
fileprivate func configureFooterIfNeeded() {
self.footerView.isHidden = tagButton.isHidden && likeButton.isHidden && commentButton.isHidden
if self.footerView.isHidden {
footerViewHeightConstraint.constant = 0
}
footerViewHeightConstraintConstant = footerViewHeightConstraint.constant
}
fileprivate func adjustInsetsForTextDirection() {
let buttonsToAdjust: [UIButton] = [
likeButton,
commentButton]
for button in buttonsToAdjust {
button.flipInsetsForRightToLeftLayoutDirection()
}
}
// MARK: - Instance Methods
func presentWebViewControllerWithURL(_ url: URL) {
var url = url
if url.host == nil {
if let postURLString = post?.permaLink {
let postURL = URL(string: postURLString)
url = URL(string: url.absoluteString, relativeTo: postURL)!
}
}
let controller = WPWebViewController.authenticatedWebViewController(url)
controller.addsWPComReferrer = true
let navController = UINavigationController(rootViewController: controller)
present(navController, animated: true, completion: nil)
}
func previewSite() {
let controller = ReaderStreamViewController.controllerWithSiteID(post!.siteID, isFeed: post!.isExternal)
navigationController?.pushViewController(controller, animated: true)
let properties = ReaderHelpers.statsPropertiesForPost(post!, andValue: post!.blogURL as AnyObject?, forKey: "URL")
WPAppAnalytics.track(.readerSitePreviewed, withProperties: properties)
}
func setBarsHidden(_ hidden: Bool, animated: Bool = true) {
if (navigationController?.isNavigationBarHidden == hidden) {
return
}
if (hidden) {
// Hides the navbar and footer view
navigationController?.setNavigationBarHidden(true, animated: animated)
currentPreferredStatusBarStyle = .default
footerViewHeightConstraint.constant = 0.0
UIView.animate(withDuration: animated ? 0.2 : 0,
delay: 0.0,
options: [.beginFromCurrentState, .allowUserInteraction],
animations: {
self.view.layoutIfNeeded()
}, completion: nil)
} else {
// Shows the navbar and footer view
let pinToBottom = isScrollViewAtBottom()
currentPreferredStatusBarStyle = .lightContent
footerViewHeightConstraint.constant = footerViewHeightConstraintConstant
UIView.animate(withDuration: animated ? 0.2 : 0,
delay: 0.0,
options: [.beginFromCurrentState, .allowUserInteraction],
animations: {
self.view.layoutIfNeeded()
self.navigationController?.setNavigationBarHidden(false, animated: animated)
if pinToBottom {
let y = self.textView.contentSize.height - self.textView.frame.height
self.textView.setContentOffset(CGPoint(x: 0, y: y), animated: false)
}
}, completion: nil)
}
}
func isScrollViewAtBottom() -> Bool {
return textView.contentOffset.y + textView.frame.height == textView.contentSize.height
}
// MARK: - Analytics
fileprivate func bumpStats() {
if didBumpStats {
return
}
guard let readerPost = post, isViewLoaded && view.window != nil else {
return
}
didBumpStats = true
let isOfflineView = ReachabilityUtils.isInternetReachable() ? "no" : "yes"
let detailType = readerPost.topic?.type == ReaderSiteTopic.TopicType ? DetailAnalyticsConstants.TypePreviewSite : DetailAnalyticsConstants.TypeNormal
var properties = ReaderHelpers.statsPropertiesForPost(readerPost, andValue: nil, forKey: nil)
properties[DetailAnalyticsConstants.TypeKey] = detailType
properties[DetailAnalyticsConstants.OfflineKey] = isOfflineView
WPAppAnalytics.track(.readerArticleOpened, withProperties: properties)
// We can remove the nil check and use `if let` when `ReaderPost` adopts nullibility.
let railcar = readerPost.railcarDictionary()
if railcar != nil {
WPAppAnalytics.trackTrainTracksInteraction(.readerArticleOpened, withProperties: railcar)
}
}
fileprivate func bumpPageViewsForPost() {
if didBumpPageViews {
return
}
guard let readerPost = post, isViewLoaded && view.window != nil else {
return
}
didBumpPageViews = true
ReaderHelpers.bumpPageViewForPost(readerPost)
}
// MARK: - Actions
@IBAction func didTapTagButton(_ sender: UIButton) {
if !isLoaded {
return
}
let controller = ReaderStreamViewController.controllerWithTagSlug(post!.primaryTagSlug)
navigationController?.pushViewController(controller, animated: true)
let properties = ReaderHelpers.statsPropertiesForPost(post!, andValue: post!.primaryTagSlug as AnyObject?, forKey: "tag")
WPAppAnalytics.track(.readerTagPreviewed, withProperties: properties)
}
@IBAction func didTapCommentButton(_ sender: UIButton) {
if !isLoaded {
return
}
let controller = ReaderCommentsViewController(post: post)
navigationController?.pushViewController(controller!, animated: true)
}
@IBAction func didTapLikeButton(_ sender: UIButton) {
if !isLoaded {
return
}
guard let post = post else {
return
}
if !post.isLiked {
UINotificationFeedbackGenerator().notificationOccurred(.success)
}
let service = ReaderPostService(managedObjectContext: post.managedObjectContext!)
service.toggleLiked(for: post, success: nil, failure: { (error: Error?) in
if let anError = error {
DDLogError("Error (un)liking post: \(anError.localizedDescription)")
}
})
}
func didTapHeaderAvatar(_ gesture: UITapGestureRecognizer) {
if gesture.state != .ended {
return
}
previewSite()
}
@IBAction func didTapBlogNameButton(_ sender: UIButton) {
previewSite()
}
@IBAction func didTapMenuButton(_ sender: UIButton) {
ReaderPostMenu.showMenuForPost(post!, fromView: menuButton, inViewController: self)
}
func didTapFeaturedImage(_ gesture: UITapGestureRecognizer) {
if gesture.state != .ended {
return
}
let controller = WPImageViewController(image: featuredImageView.image)
controller?.modalTransitionStyle = .crossDissolve
controller?.modalPresentationStyle = .fullScreen
present(controller!, animated: true, completion: nil)
}
func didTapDiscoverAttribution() {
if post?.sourceAttribution == nil {
return
}
if let blogID = post?.sourceAttribution.blogID {
let controller = ReaderStreamViewController.controllerWithSiteID(blogID, isFeed: false)
navigationController?.pushViewController(controller, animated: true)
return
}
var path: String?
if post?.sourceAttribution.attributionType == SourcePostAttributionTypePost {
path = post?.sourceAttribution.permalink
} else {
path = post?.sourceAttribution.blogURL
}
if let linkURL = URL(string: path!) {
presentWebViewControllerWithURL(linkURL)
}
}
func didTapShareButton(_ sender: UIButton) {
sharingController.shareReaderPost(post!, fromView: sender, inViewController: self)
}
func handleBlockSiteNotification(_ notification: Foundation.Notification) {
if let userInfo = notification.userInfo, let aPost = userInfo["post"] as? NSObject {
if aPost == post! {
_ = navigationController?.popViewController(animated: true)
}
}
}
}
// MARK: - ReaderCardDiscoverAttributionView Delegate Methods
extension ReaderDetailViewController : ReaderCardDiscoverAttributionViewDelegate {
public func attributionActionSelectedForVisitingSite(_ view: ReaderCardDiscoverAttributionView) {
didTapDiscoverAttribution()
}
}
// MARK: - UITextView/WPRichContentView Delegate Methods
extension ReaderDetailViewController: WPRichContentViewDelegate {
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
presentWebViewControllerWithURL(URL)
return false
}
@available(iOS 10, *)
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if interaction == .presentActions {
// show
let frame = textView.frameForTextInRange(characterRange)
let shareController = PostSharingController()
shareController.shareURL(url: URL as NSURL, fromRect: frame, inView: textView, inViewController: self)
} else {
presentWebViewControllerWithURL(URL)
}
return false
}
func richContentView(_ richContentView: WPRichContentView, didReceiveImageAction image: WPRichTextImage) {
var controller: WPImageViewController
if WPImageViewController.isUrlSupported(image.linkURL as URL!) {
controller = WPImageViewController(image: image.imageView.image, andURL: image.linkURL as URL!)
} else if let linkURL = image.linkURL {
presentWebViewControllerWithURL(linkURL as URL)
return
} else {
controller = WPImageViewController(image: image.imageView.image)
}
controller.modalTransitionStyle = .crossDissolve
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
}
}
// MARK: - UIScrollView Delegate Methods
extension ReaderDetailViewController : UIScrollViewDelegate {
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if UIDevice.isPad() || footerView.isHidden || !isLoaded {
return
}
// The threshold for hiding the bars is twice the height of the hidden bars.
// This ensures that once the bars are hidden the view can still be scrolled
// and thus can unhide the bars.
var threshold = footerViewHeightConstraintConstant
if let navHeight = navigationController?.navigationBar.frame.height {
threshold += navHeight
}
threshold *= 2.0
let y = targetContentOffset.pointee.y
if y > scrollView.contentOffset.y && y > threshold {
setBarsHidden(true)
} else {
// Velocity will be 0,0 if the user taps to stop an in progress scroll.
// If the bars are already visible its fine but if the bars are hidden
// we don't want to jar the user by having them reappear.
if !velocity.equalTo(CGPoint.zero) {
setBarsHidden(false)
}
}
}
public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
setBarsHidden(false)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if isScrollViewAtBottom() {
setBarsHidden(false)
}
}
}
// Expand this view controller to full screen if possible
extension ReaderDetailViewController: PrefersFullscreenDisplay {}
// Let's the split view know this vc changes the status bar style.
extension ReaderDetailViewController: DefinesVariableStatusBarStyle {}
| 1ebfbde92f644b36cd5ebf83c8d8861b | 35.500443 | 207 | 0.647092 | false | false | false | false |
slavapestov/swift | refs/heads/master | stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
public struct SubscriptRangeTest {
public let expected: [OpaqueValue<Int>]
public let collection: [OpaqueValue<Int>]
public let bounds: Range<Int>
public let count: Int
public let loc: SourceLoc
public var isEmpty: Bool { return count == 0 }
public func boundsIn<C : CollectionType>(c: C) -> Range<C.Index> {
let i = c.startIndex
return Range(
start: i.advancedBy(numericCast(bounds.startIndex)),
end: i.advancedBy(numericCast(bounds.endIndex)))
}
public init(
expected: [Int], collection: [Int], bounds: Range<Int>,
count: Int,
file: String = #file, line: UInt = #line
) {
self.expected = expected.map(OpaqueValue.init)
self.collection = collection.map(OpaqueValue.init)
self.bounds = bounds
self.count = count
self.loc = SourceLoc(file, line, comment: "test data")
}
}
public struct PrefixThroughTest {
public var collection: [Int]
public let position: Int
public let expected: [Int]
public let loc: SourceLoc
init(
collection: [Int], position: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.position = position
self.expected = expected
self.loc = SourceLoc(file, line, comment: "prefix() test data")
}
}
public struct PrefixUpToTest {
public var collection: [Int]
public let end: Int
public let expected: [Int]
public let loc: SourceLoc
public init(
collection: [Int], end: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.end = end
self.expected = expected
self.loc = SourceLoc(file, line, comment: "prefix() test data")
}
}
internal struct RemoveFirstNTest {
let collection: [Int]
let numberToRemove: Int
let expectedCollection: [Int]
let loc: SourceLoc
init(
collection: [Int], numberToRemove: Int, expectedCollection: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.numberToRemove = numberToRemove
self.expectedCollection = expectedCollection
self.loc = SourceLoc(file, line, comment: "removeFirst(n: Int) test data")
}
}
public struct SuffixFromTest {
public var collection: [Int]
public let start: Int
public let expected: [Int]
public let loc: SourceLoc
init(
collection: [Int], start: Int, expected: [Int],
file: String = #file, line: UInt = #line
) {
self.collection = collection
self.start = start
self.expected = expected
self.loc = SourceLoc(file, line, comment: "prefix() test data")
}
}
public let subscriptRangeTests = [
// Slice an empty collection.
SubscriptRangeTest(
expected: [],
collection: [],
bounds: 0..<0,
count: 0),
// Slice to the full extent.
SubscriptRangeTest(
expected: [ 1010 ],
collection: [ 1010 ],
bounds: 0..<1,
count: 1),
SubscriptRangeTest(
expected: [ 1010, 2020, 3030 ],
collection: [ 1010, 2020, 3030 ],
bounds: 0..<3,
count: 3),
// Slice an empty prefix.
SubscriptRangeTest(
expected: [],
collection: [ 1010, 2020, 3030 ],
bounds: 0..<0,
count: 3),
// Slice a prefix.
SubscriptRangeTest(
expected: [ 1010, 2020 ],
collection: [ 1010, 2020, 3030 ],
bounds: 0..<2,
count: 3),
// Slice an empty suffix.
SubscriptRangeTest(
expected: [],
collection: [ 1010, 2020, 3030 ],
bounds: 3..<3,
count: 3),
// Slice a suffix.
SubscriptRangeTest(
expected: [ 2020, 3030 ],
collection: [ 1010, 2020, 3030 ],
bounds: 1..<3,
count: 3),
// Slice an empty range in the middle.
SubscriptRangeTest(
expected: [],
collection: [ 1010, 2020, 3030 ],
bounds: 2..<2,
count: 3),
// Slice the middle part.
SubscriptRangeTest(
expected: [ 2020 ],
collection: [ 1010, 2020, 3030 ],
bounds: 1..<2,
count: 3),
SubscriptRangeTest(
expected: [ 2020, 3030, 4040 ],
collection: [ 1010, 2020, 3030, 4040, 5050, 6060 ],
bounds: 1..<4,
count: 6),
]
public let prefixUpToTests = [
PrefixUpToTest(
collection: [],
end: 0,
expected: []
),
PrefixUpToTest(
collection: [1010, 2020, 3030, 4040, 5050],
end: 3,
expected: [1010, 2020, 3030]
),
PrefixUpToTest(
collection: [1010, 2020, 3030, 4040, 5050],
end: 5,
expected: [1010, 2020, 3030, 4040, 5050]
),
]
public let prefixThroughTests = [
PrefixThroughTest(
collection: [1010, 2020, 3030, 4040, 5050],
position: 0,
expected: [1010]
),
PrefixThroughTest(
collection: [1010, 2020, 3030, 4040, 5050],
position: 2,
expected: [1010, 2020, 3030]
),
PrefixThroughTest(
collection: [1010, 2020, 3030, 4040, 5050],
position: 4,
expected: [1010, 2020, 3030, 4040, 5050]
),
]
public let suffixFromTests = [
SuffixFromTest(
collection: [],
start: 0,
expected: []
),
SuffixFromTest(
collection: [1010, 2020, 3030, 4040, 5050],
start: 0,
expected: [1010, 2020, 3030, 4040, 5050]
),
SuffixFromTest(
collection: [1010, 2020, 3030, 4040, 5050],
start: 3,
expected: [4040, 5050]
),
SuffixFromTest(
collection: [1010, 2020, 3030, 4040, 5050],
start: 5,
expected: []
),
]
let removeFirstTests: [RemoveFirstNTest] = [
RemoveFirstNTest(
collection: [1010],
numberToRemove: 0,
expectedCollection: [1010]
),
RemoveFirstNTest(
collection: [1010],
numberToRemove: 1,
expectedCollection: []
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 0,
expectedCollection: [1010, 2020, 3030, 4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 1,
expectedCollection: [2020, 3030, 4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 2,
expectedCollection: [3030, 4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 3,
expectedCollection: [4040, 5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 4,
expectedCollection: [5050]
),
RemoveFirstNTest(
collection: [1010, 2020, 3030, 4040, 5050],
numberToRemove: 5,
expectedCollection: []
),
]
extension TestSuite {
public func addForwardCollectionTests<
Collection : CollectionType,
CollectionWithEquatableElement : CollectionType
where
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addSequenceTests(
testNamePrefix,
makeSequence: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeSequenceOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
func makeWrappedCollectionWithEquatableElement(
elements: [MinimalEquatableValue]
) -> CollectionWithEquatableElement {
return makeCollectionOfEquatable(elements.map(wrapValueIntoEquatable))
}
testNamePrefix += String(Collection.Type)
//===----------------------------------------------------------------------===//
// generate()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).generate()/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
for _ in 0..<3 {
checkSequence(
test.collection.map(wrapValue),
c,
resiliencyChecks: .none) {
extractValue($0).value == extractValue($1).value
}
}
}
}
//===----------------------------------------------------------------------===//
// Index
//===----------------------------------------------------------------------===//
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).Index/OutOfBounds/Right/NonEmpty") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
let index = c.endIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
}
}
}
self.test("\(testNamePrefix).Index/OutOfBounds/Right/Empty") {
let c = makeWrappedCollection([])
let index = c.endIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(outOfBoundsIndexOffset)))
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Index)
//===----------------------------------------------------------------------===//
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.endIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.endIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Range)
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).subscript(_: Range)/Get/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let result = c[test.boundsIn(c)]
// FIXME: improve checkForwardCollection to check the SubSequence type.
checkForwardCollection(
test.expected.map(wrapValue),
result,
resiliencyChecks: .none) {
extractValue($0).value == extractValue($1).value
}
}
}
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Right/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.endIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Right/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.endIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
}
//===----------------------------------------------------------------------===//
// isEmpty
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).isEmpty/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
expectEqual(test.isEmpty, c.isEmpty)
}
}
//===----------------------------------------------------------------------===//
// count
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).count/semantics") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
expectEqual(test.count, numericCast(c.count) as Int)
}
}
//===----------------------------------------------------------------------===//
// indexOf()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).indexOf()/WhereElementIsEquatable/semantics") {
for test in findTests {
let c = makeWrappedCollectionWithEquatableElement(test.sequence)
var result = c.indexOf(wrapValueIntoEquatable(test.element))
expectType(
Optional<CollectionWithEquatableElement.Index>.self,
&result)
let zeroBasedIndex = result.map {
numericCast(c.startIndex.distanceTo($0)) as Int
}
expectEqual(
test.expected,
zeroBasedIndex,
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).indexOf()/Predicate/semantics") {
for test in findTests {
let c = makeWrappedCollectionWithEquatableElement(test.sequence)
let closureLifetimeTracker = LifetimeTracked(0)
expectEqual(1, LifetimeTracked.instances)
let result = c.indexOf {
(candidate) in
_blackHole(closureLifetimeTracker)
return extractValueFromEquatable(candidate).value == test.element.value
}
let zeroBasedIndex = result.map {
numericCast(c.startIndex.distanceTo($0)) as Int
}
expectEqual(
test.expected,
zeroBasedIndex,
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// first
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).first") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let result = c.first
if test.isEmpty {
expectEmpty(result)
} else {
expectOptionalEqual(
test.collection[0],
result.map(extractValue)
) { $0.value == $1.value }
}
}
}
//===----------------------------------------------------------------------===//
// indices
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).indices") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let indices = c.indices
expectEqual(c.startIndex, indices.startIndex)
expectEqual(c.endIndex, indices.endIndex)
}
}
//===----------------------------------------------------------------------===//
// dropFirst()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).dropFirst/semantics") {
for test in dropFirstTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.dropFirst(test.dropElements)
expectEqualSequence(
test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// dropLast()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).dropLast/semantics") {
for test in dropLastTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.dropLast(test.dropElements)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// prefix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefix/semantics") {
for test in prefixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.prefix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffix/semantics") {
for test in suffixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.suffix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// split()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).split/semantics") {
for test in splitTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.split(test.maxSplit,
allowEmptySlices: test.allowEmptySlices) {
extractValue($0).value == test.separator
}
expectEqualSequence(test.expected, result.map {
$0.map {
extractValue($0).value
}
},
stackTrace: SourceLocStack().with(test.loc)) { $0 == $1 }
}
}
//===----------------------------------------------------------------------===//
// prefixThrough()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefixThrough/semantics") {
for test in prefixThroughTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let index = c.startIndex.advancedBy(numericCast(test.position))
let result = c.prefixThrough(index)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// prefixUpTo()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefixUpTo/semantics") {
for test in prefixUpToTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let index = c.startIndex.advancedBy(numericCast(test.end))
let result = c.prefixUpTo(index)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffixFrom()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffixFrom/semantics") {
for test in suffixFromTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let index = c.startIndex.advancedBy(numericCast(test.start))
let result = c.suffixFrom(index)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// removeFirst()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst()/slice/semantics") {
for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices = Array(slice.startIndex.successor()..<slice.endIndex)
let removedElement = slice.removeFirst()
expectEqual(test.collection.first, extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeFirst()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
_ = slice.removeFirst() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeFirst(n: Int)/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/semantics") {
for test in removeFirstTests {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex.advancedBy(numericCast(test.numberToRemove)) ..<
slice.endIndex
)
slice.removeFirst(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeFirst(1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/removeNegative/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeFirst(-1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/slice/removeTooMany/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeFirst(3) // Should trap.
}
//===----------------------------------------------------------------------===//
// popFirst()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).popFirst()/slice/semantics") {
// This can just reuse the test data for removeFirst()
for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices = Array(slice.startIndex.successor()..<slice.endIndex)
let removedElement = slice.popFirst()!
expectEqual(test.collection.first, extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"popFirst() shouldn't mutate the tail of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"popFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection,
c.map { extractValue($0).value },
"popFirst() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).popFirst()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectEmpty(slice.popFirst())
}
//===----------------------------------------------------------------------===//
} // addForwardCollectionTests
public func addBidirectionalCollectionTests<
Collection : CollectionType,
CollectionWithEquatableElement : CollectionType
where
Collection.Index : BidirectionalIndexType,
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.Index : BidirectionalIndexType,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Index : BidirectionalIndexType,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addForwardCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset,
outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
testNamePrefix += String(Collection.Type)
//===----------------------------------------------------------------------===//
// last
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).last") {
for test in subscriptRangeTests {
let c = makeWrappedCollection(test.collection)
let result = c.last
if test.isEmpty {
expectEmpty(result)
} else {
expectOptionalEqual(
test.collection[test.count - 1],
result.map(extractValue)
) { $0.value == $1.value }
}
}
}
//===----------------------------------------------------------------------===//
// removeLast()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast()/slice/semantics") {
for test in removeLastTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection)
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex ..<
slice.endIndex.advancedBy(numericCast(-test.numberToRemove))
)
let removedElement = slice.removeLast()
expectEqual(
test.collection.last!.value,
extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeLast()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
_ = slice.removeLast() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeLast(n: Int)/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast(n: Int)/slice/semantics") {
for test in removeLastTests {
let c = makeWrappedCollection(test.collection)
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex ..<
slice.endIndex.advancedBy(numericCast(-test.numberToRemove))
)
slice.removeLast(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"removeLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).removeLast(n: Int)/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeLast(1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/slice/removeNegative/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeLast(-1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/slice/removeTooMany/semantics") {
let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
var slice = c[c.startIndex..<c.startIndex]
expectCrashLater()
slice.removeLast(3) // Should trap.
}
//===----------------------------------------------------------------------===//
// popLast()/slice
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).popLast()/slice/semantics") {
// This can just reuse the test data for removeLast()
for test in removeLastTests.filter({ $0.numberToRemove == 1 }) {
let c = makeWrappedCollection(test.collection)
var slice = c[c.startIndex..<c.endIndex]
let survivingIndices =
Array(
slice.startIndex ..<
slice.endIndex.advancedBy(numericCast(-test.numberToRemove))
)
let removedElement = slice.popLast()!
expectEqual(
test.collection.last!.value,
extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
slice.map { extractValue($0).value },
"popLast() shouldn't mutate the head of the slice",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(slice[$0]).value },
"popLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.collection.map { $0.value },
c.map { extractValue($0).value },
"popLast() shouldn't mutate the collection that was sliced",
stackTrace: SourceLocStack().with(test.loc))
}
}
self.test("\(testNamePrefix).popLast()/slice/empty/semantics") {
let c = makeWrappedCollection(Array<OpaqueValue<Int>>())
var slice = c[c.startIndex..<c.startIndex]
expectEmpty(slice.popLast())
}
//===----------------------------------------------------------------------===//
// Index
//===----------------------------------------------------------------------===//
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).Index/OutOfBounds/Left/NonEmpty") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
let index = c.startIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
}
}
}
self.test("\(testNamePrefix).Index/OutOfBounds/Left/Empty") {
let c = makeWrappedCollection([])
let index = c.startIndex
if resiliencyChecks.creatingOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
} else {
expectFailure {
_blackHole(index.advancedBy(numericCast(-outOfBoundsIndexOffset)))
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Index)
//===----------------------------------------------------------------------===//
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.startIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.startIndex
if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index])
}
}
}
}
//===----------------------------------------------------------------------===//
// subscript(_: Range)
//===----------------------------------------------------------------------===//
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .None {
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Left/NonEmpty/Get") {
let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init))
var index = c.startIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Left/Empty/Get") {
let c = makeWrappedCollection([])
var index = c.startIndex
if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior == .Trap {
expectCrashLater()
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
} else {
expectFailure {
index = index.advancedBy(numericCast(-outOfBoundsSubscriptOffset))
_blackHole(c[index..<index])
}
}
}
}
//===----------------------------------------------------------------------===//
// dropLast()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).dropLast/semantics") {
for test in dropLastTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.dropLast(test.dropElements)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffix/semantics") {
for test in suffixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.suffix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
} // addBidirectionalCollectionTests
public func addRandomAccessCollectionTests<
Collection : CollectionType,
CollectionWithEquatableElement : CollectionType
where
Collection.Index : RandomAccessIndexType,
Collection.SubSequence : CollectionType,
Collection.SubSequence.Generator.Element == Collection.Generator.Element,
Collection.SubSequence.Index : RandomAccessIndexType,
Collection.SubSequence.SubSequence == Collection.SubSequence,
CollectionWithEquatableElement.Index : RandomAccessIndexType,
CollectionWithEquatableElement.Generator.Element : Equatable
>(
testNamePrefix: String = "",
makeCollection: ([Collection.Generator.Element]) -> Collection,
wrapValue: (OpaqueValue<Int>) -> Collection.Generator.Element,
extractValue: (Collection.Generator.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: ([CollectionWithEquatableElement.Generator.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: (MinimalEquatableValue) -> CollectionWithEquatableElement.Generator.Element,
extractValueFromEquatable: ((CollectionWithEquatableElement.Generator.Element) -> MinimalEquatableValue),
checksAdded: Box<Set<String>> = Box([]),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1
) {
var testNamePrefix = testNamePrefix
if checksAdded.value.contains(#function) {
return
}
checksAdded.value.insert(#function)
addBidirectionalCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
checksAdded: checksAdded,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset,
outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset)
testNamePrefix += String(Collection.Type)
func makeWrappedCollection(elements: [OpaqueValue<Int>]) -> Collection {
return makeCollection(elements.map(wrapValue))
}
//===----------------------------------------------------------------------===//
// prefix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).prefix/semantics") {
for test in prefixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.prefix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// suffix()
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).suffix/semantics") {
for test in suffixTests {
let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init))
let result = s.suffix(test.maxLength)
expectEqualSequence(test.expected, result.map(extractValue).map { $0.value },
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
} // addRandomAccessCollectionTests
}
| cf29bc972b726cc13d136305ef51292e | 33.219727 | 118 | 0.605713 | false | true | false | false |
fleurdeswift/data-structure | refs/heads/master | ExtraDataStructures/Task+MoveFiles.swift | mit | 1 | //
// Task+MoveTask.swift
// ExtraDataStructures
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Foundation
public extension Task {
public class MoveFiles : Task {
public enum ErrorBehavior {
case Revert, Stop, Ignore
}
public func move(urls urls: [NSURL: NSURL], errorBehavior: ErrorBehavior) {
var moves = [NSURL: NSURL]();
var renames = [NSURL: NSURL]();
let errors = ErrorDictionary();
typealias statStruct = stat;
var destinationStats = [NSURL: DarwinStatStruct]();
var bytes: Int64 = 0;
for (source, destination) in urls {
if !source.fileURL {
errors[source] = NSError(domain: NSPOSIXErrorDomain, code: Int(EBADF), userInfo: [NSURLErrorKey: source]);
continue;
}
if !destination.fileURL {
errors[source] = NSError(domain: NSPOSIXErrorDomain, code: Int(EBADF), userInfo: [NSURLErrorKey: source]);
continue;
}
var destinationStat: DarwinStatStruct;
let destinationParent = destination.URLByDeletingLastPathComponent!;
if let cached = destinationStats[destinationParent] {
destinationStat = cached;
}
else {
destinationStat = DarwinStatStruct();
do {
try DarwinStat(destinationParent, &destinationStat);
try DarwinAccess(destinationParent, W_OK);
}
catch {
errors[destinationParent] = error as NSError;
}
}
do {
var sourceStat = DarwinStatStruct();
try DarwinStat(source, &sourceStat);
try DarwinAccess(source, R_OK);
try DarwinAccess(source.URLByDeletingLastPathComponent!, W_OK);
if sourceStat.st_dev != destinationStat.st_dev {
moves[source] = destination;
bytes += sourceStat.st_size;
}
else {
renames[source] = destination;
bytes += 1;
}
}
catch {
errors[source] = error as NSError;
}
}
if errors.count != 0 {
if errorBehavior != .Ignore {
self.error = errors;
return;
}
}
bytes = min(1, bytes);
var results = [NSURL]();
var moved = [NSURL: NSURL]();
var renamed = [NSURL: NSURL]();
var readed: Int64 = 0;
for (source, destination) in renames {
do {
try DarwinRename(old: source, new: destination);
renamed[source] = destination;
readed += 1;
self.progress = Double(readed) / Double(bytes);
results.append(destination);
}
catch {
errors[destination] = error as NSError;
if errorBehavior != .Ignore {
break;
}
}
}
if errors.count != 0 && errorBehavior == .Revert {
MoveFiles.revertRenames(renamed);
self.error = errors;
return;
}
if moves.count > 0 {
let blockSize = 65536 * 4;
let block = Darwin.malloc(blockSize);
defer { Darwin.free(block); }
for (source, destination) in moves {
do {
try moveFile(source, destination, block, blockSize, &readed, bytes);
moved[source] = destination;
results.append(destination);
}
catch {
Darwin.unlink(destination.fileSystemRepresentation);
errors[destination] = error as NSError;
if errorBehavior != .Ignore {
break;
}
}
self.progress = Double(readed) / Double(bytes);
}
}
if errors.count != 0 {
self.error = errors;
if errorBehavior == .Revert {
MoveFiles.revertRenames(renamed);
MoveFiles.revertMoves(moved);
return;
}
}
MoveFiles.deleteMoves(moved);
self.outputs = ["destinationURLs": results];
}
}
private func moveFile(source: NSURL, _ destination: NSURL, _ block: UnsafeMutablePointer<Void>, _ blockSize: Int, inout _ readed: Int64, _ bytes: Int64) throws {
var blockIndex = 0;
let rfd = try DarwinOpen(source, O_RDONLY);
defer { Darwin.close(rfd); }
let wfd = try DarwinOpen(destination, O_WRONLY | O_CREAT | O_EXCL);
defer { Darwin.close(wfd); }
while true {
let blockReaded = try DarwinRead(rfd, block, blockSize);
if blockReaded == 0 {
break;
}
readed += Int64(blockReaded);
try DarwinWrite(wfd, block, blockReaded);
if blockIndex++ > 16 {
blockIndex = 0;
self.progress = Double(readed) / Double(bytes);
}
}
}
private static func revertMoves(moves: [NSURL: NSURL]) {
for (_, destination) in moves {
Darwin.unlink(destination.fileSystemRepresentation);
}
}
private static func deleteMoves(moves: [NSURL: NSURL]) {
for (source, _) in moves {
Darwin.unlink(source.fileSystemRepresentation);
}
}
private static func revertRenames(renames: [NSURL: NSURL]) {
for (source, destination) in renames {
do {
try DarwinRename(old: destination, new: source);
}
catch {
}
}
}
public class func moveFiles(identifier: String, urls: [NSURL: NSURL], errorBehavior: MoveFiles.ErrorBehavior) -> Task.MoveFiles {
return MoveFiles(createWithIdentifier: identifier, description: "Move Files...", dependsOn: nil, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), barrier: false) { task in
(task as! MoveFiles).move(urls: urls, errorBehavior: errorBehavior);
}
}
}
/*
public class MoveFileTask : NSObject, LongTask {
public var progress: Double?;
public var status: String = "Moving files..."
public func cancel() {
}
public let links: [String: String];
public let moves: [NSURL: NSURL];
public let block: ([NSURL: NSError]?) -> Void
public init(linkMoves: [String: String], manualMoves: [NSURL: NSURL], manualAttributes: [NSURL: [String: AnyObject]], completionBlock: ([NSURL: NSError]?) -> Void) {
self.links = linkMoves;
self.moves = manualMoves;
self.block = completionBlock;
super.init();
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
var totalBytes: UInt64 = 0;
var readed: UInt64 = 0;
for (_, attributes) in manualAttributes {
if let bytes = attributes[NSFileSize] as? NSNumber {
totalBytes += bytes.unsignedLongLongValue;
}
}
var blockIndex = 0;
let blockSize = 65536;
let block = Darwin.malloc(blockSize);
defer { Darwin.free(block); }
for (sourceURL, destinationURL) in manualMoves {
let input = NSInputStream(URL: sourceURL)!;
let output = NSOutputStream(URL: destinationURL, append: false)!;
input.open();
output.open();
defer {
input.close();
output.close();
}
while true {
let blockReaded = input.read(UnsafeMutablePointer<UInt8>(block), maxLength: blockSize);
if blockReaded == 0 {
break;
}
else if blockReaded < 0 {
self.revert(sourceURL, error: input.streamError);
return;
}
readed += UInt64(blockReaded);
if output.write(UnsafeMutablePointer<UInt8>(block), maxLength: blockReaded) < 0 {
self.revert(destinationURL, error: output.streamError);
return;
}
if blockIndex++ > 16 {
blockIndex = 0;
let up = readed;
let upt = totalBytes;
dispatch_async(dispatch_get_main_queue()) {
self.progress = min(0.999, Double(up) / Double(upt));
NSNotificationCenter.defaultCenter().postNotificationName(LongTaskProgressChanged, object: self);
}
}
}
}
self.commit();
}
}
public class func moveFiles(files: [NSURL: NSURL], presentingViewController: NSViewController, completionBlock: ([NSURL: NSError]?) -> Void) throws {
if let task = try self.moveFiles(files, completionBlock: completionBlock) {
LongTaskSheet.show(task, parent: presentingViewController);
}
}
/// This function returns nil if the move operation can be performed using the POSIX command
/// rename.
public class func moveFiles(files: [NSURL: NSURL], completionBlock: ([NSURL: NSError]?) -> Void) throws -> LongTask? {
let manager = NSFileManager.defaultManager();
var manualMoves = [NSURL: NSURL]();
var linkMoves = [String: String]();
var attributes = [NSURL: [String: AnyObject]]();
for (source, destination) in files {
if source.fileURL && destination.fileURL {
if let sourcePath = source.path, destinationPath = destination.path {
let attr = try manager.attributesOfItemAtPath(sourcePath);
if Darwin.link(sourcePath, destinationPath) == 0 {
linkMoves[sourcePath] = destinationPath;
continue;
}
attributes[source] = attr;
}
}
manualMoves[source] = destination;
}
if manualMoves.count == 0 {
for (sourcePath, _) in linkMoves {
Darwin.unlink(sourcePath);
}
completionBlock(nil);
return nil;
}
return MoveFileTask(linkMoves: linkMoves, manualMoves: manualMoves, manualAttributes: attributes, completionBlock: completionBlock);
}
private func commit() {
for (sourcePath, _) in links {
Darwin.unlink(sourcePath);
}
for (sourceURL, _) in moves {
if sourceURL.fileURL {
if let path = sourceURL.path {
Darwin.unlink(path);
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.progress = 1.0;
NSNotificationCenter.defaultCenter().postNotificationName(LongTaskProgressChanged, object: self);
self.block(nil);
}
}
private func revert(url: NSURL, error: NSError?) {
for (_, destinationPath) in links {
Darwin.unlink(destinationPath);
}
for (_, destinationURL) in moves {
if destinationURL.fileURL {
if let path = destinationURL.path {
Darwin.unlink(path);
}
else {
assert(false);
}
}
assert(false);
}
dispatch_async(dispatch_get_main_queue()) {
self.progress = 1.0;
NSNotificationCenter.defaultCenter().postNotificationName(LongTaskProgressChanged, object: self);
if let e = error {
self.block([url: e]);
}
else {
self.block([url: NSError(domain: NSPOSIXErrorDomain, code: Int(EFAULT), userInfo: nil)]);
}
}
}
}*/
| 769ccc18a18757183e2a43594b06381e | 33.584856 | 196 | 0.477427 | false | false | false | false |
macemmi/HBCI4Swift | refs/heads/master | HBCI4Swift/HBCI4Swift/Source/HBCILog.swift | gpl-2.0 | 1 | //
// HBCILog.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 02.01.15.
// Copyright (c) 2015 Frank Emminghaus. All rights reserved.
//
import Foundation
func logError(_ message:String?, file:String = #file, function:String = #function, line:Int = #line) {
if let log = _log {
log.logError(message, file: file, function: function, line: line);
}
}
func logWarning(_ message:String?, file:String = #file, function:String = #function, line:Int = #line) {
if let log = _log {
log.logWarning(message, file: file, function: function, line: line);
}
}
func logInfo(_ message:String?, file:String = #file, function:String = #function, line:Int = #line) {
if let log = _log {
log.logInfo(message, file: file, function: function, line: line);
}
}
func logDebug(_ message:String?, file:String = #file, function:String = #function, line:Int = #line, values:Int...) {
if let msg = message {
let m = String(format: msg, arguments: values);
if let log = _log {
log.logDebug(m, file: file, function: function, line: line);
}
}
}
func logDebug(data: Data?, file:String = #file, function:String = #function, line:Int = #line) {
var result = ""
if let data = data {
data.forEach { byte in
if byte < 32 || byte > 126 {
result = result.appendingFormat("<%.02X>", byte)
} else {
result = result + String(Unicode.Scalar(byte)) //Character(Unicode.Scalar(byte))
}
}
}
if let log = _log {
log.logDebug(result, file: file, function: function, line: line);
}
}
public protocol HBCILog {
func logError(_ message:String?, file:String, function:String, line:Int);
func logWarning(_ message:String?, file:String, function:String, line:Int);
func logInfo(_ message:String?, file:String, function:String, line:Int);
func logDebug(_ message:String?, file:String, function:String, line:Int);
}
var _log:HBCILog?;
open class HBCILogManager {
open class func setLog(_ log:HBCILog) {
_log = log;
}
}
open class HBCIConsoleLog: HBCILog {
public init() {}
open func logError(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print(url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print(url.lastPathComponent+", "+function+" \(line): nil message");
}
}
open func logWarning(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print("Warning"+url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print("Warning: "+url.lastPathComponent+", "+function+" \(line): nil message");
}
}
open func logInfo(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print("Info"+url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print("Info"+url.lastPathComponent+", "+function+" \(line): nil message");
}
}
open func logDebug(_ message: String?, file:String, function:String, line:Int) {
if let msg = message {
let url = URL(fileURLWithPath: file);
print("Debug"+url.lastPathComponent+", "+function+" \(line): "+msg);
} else {
let url = URL(fileURLWithPath: file);
print("Debug"+url.lastPathComponent+", "+function+" \(line): nil message");
}
}
}
| 5dc5264933cf77c6ad3799e7ab5e41bf | 34.190909 | 117 | 0.583828 | false | false | false | false |
djflsdl08/BasicIOS | refs/heads/master | Image/Image/NasaViewController.swift | mit | 1 | //
// NasaViewController.swift
// Image
//
// Created by 김예진 on 2017. 10. 13..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class NasaViewController: UIViewController, UISplitViewControllerDelegate {
private struct Storyboard {
static let ShowImageSegue = "Show Image"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Storyboard.ShowImageSegue {
if let ivc = (segue.destination.contentViewController as? ImageViewController) {
let imageName = (sender as? UIButton)?.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName: imageName)
ivc.title = imageName
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
splitViewController?.delegate = self
}
@IBAction func showImage(_ sender: UIButton) {
if let ivc = splitViewController?.viewControllers.last?.contentViewController as? ImageViewController {
let imageName = sender.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName: imageName)
ivc.title = imageName
} else {
performSegue(withIdentifier: Storyboard.ShowImageSegue, sender: sender)
}
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
if primaryViewController.contentViewController == self {
if let ivc = secondaryViewController.contentViewController as? ImageViewController, ivc.imageURL == nil {
return true
}
}
return false
}
}
extension UIViewController {
var contentViewController : UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController ?? self
} else {
return self
}
}
}
| 2a5dbd07cf330083d7ac538354738b50 | 32.311475 | 191 | 0.650098 | false | false | false | false |
samsymons/Photon | refs/heads/master | Photon/Math/Math.swift | mit | 1 | // TypeNames.swift
// Copyright (c) 2017 Sam Symons
//
// 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
import simd
public typealias Point2D = float2
public typealias Point3D = float3
public typealias Vector3D = float3
public typealias Normal = float3
extension float3 {
public static let zero = float3(0, 0, 0)
public init(point: Point3D) {
self.init(point.x, point.y, point.z)
}
}
extension float2 {
public static let zero = float2(0, 0)
public init(point: Point2D) {
self.init(point.x, point.y)
}
}
// MARK: - Mathematical Utilities
public struct MathUtilities {
public static func randomPointInsideUnitSphere() -> Point3D {
let minimum: Float = -1.0
let maximum: Float = 1.0
var point = Point3D(1, 1, 1)
while length(point) >= 1.0 {
let randomX = (minimum...maximum).random()
let randomY = (minimum...maximum).random()
let randomZ = (minimum...maximum).random()
point = Point3D(randomX, randomY, randomZ)
}
return point
}
}
| c5af157a94d6d7cff50a22c0583f8e93 | 31.0625 | 80 | 0.721248 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceModel/Tests/EurofurenceModelTests/Sync/WhenSyncFinishes_ApplicationShould.swift | mit | 1 | import EurofurenceModel
import XCTest
import XCTEurofurenceModel
class WhenSyncFinishes_ApplicationShould: XCTestCase {
class SingleTransactionOnlyAllowedDataStore: InMemoryDataStore {
private var transactionCount = 0
override func performTransaction(_ block: @escaping (DataStoreTransaction) -> Void) {
super.performTransaction(block)
transactionCount += 1
}
func verify(file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(1, transactionCount, file: file, line: line)
}
}
func testNotPerformMultipleTransactions() {
let assertion = SingleTransactionOnlyAllowedDataStore()
let context = EurofurenceSessionTestBuilder().with(assertion).build()
let syncResponse = ModelCharacteristics.randomWithoutDeletions
context.performSuccessfulSync(response: syncResponse)
assertion.verify()
}
}
| 3b2eda2bc9e387772252f978692496aa | 29.225806 | 93 | 0.702241 | false | true | false | false |
burtherman/StreamBaseKit | refs/heads/master | StreamBaseKit/UnionStream.swift | mit | 2 | //
// UnionStream.swift
// StreamBaseKit
//
// Created by Steve Farrell on 8/31/15.
// Copyright (c) 2015 Movem3nt, Inc. All rights reserved.
//
import Foundation
/**
Compose a stream out of other streams. Some example use cases are:
- Placeholders
- Multiple Firebase queries in one view
It's ok for the keys to overlap, and for different substreams to have different
types. The sort order of the first stream is used by the union stream. (The sort orders
of the other streams is ignored.)
*/
public class UnionStream {
private let sources: [StreamBase] // TODO StreamBaseProtocol
private let delegates: [UnionStreamDelegate]
private var timer: NSTimer?
private var numStreamsFinished: Int? = 0
private var union = KeyedArray<BaseItem>()
private var error: NSError?
private var comparator: StreamBase.Comparator {
get {
return sources[0].comparator
}
}
/**
The delegate to notify as the merged stream is updated.
*/
weak public var delegate: StreamBaseDelegate?
/**
Construct a union stream from other streams. The sort order of the first substream
is used for the union.
:param: sources The substreams.
*/
public init(sources: StreamBase...) {
precondition(sources.count > 0)
self.sources = sources
delegates = sources.map{ UnionStreamDelegate(source: $0) }
for (s, d) in zip(sources, delegates) {
d.union = self
s.delegate = d
}
}
private func update() {
var newUnion = [BaseItem]()
var seen = Set<String>()
for source in sources {
for item in source {
if !seen.contains(item.key!) {
newUnion.append(item)
seen.insert(item.key!)
}
}
}
newUnion.sortInPlace(comparator)
StreamBase.applyBatch(union, batch: newUnion, delegate: delegate)
if numStreamsFinished == sources.count {
numStreamsFinished = nil
delegate?.streamDidFinishInitialLoad(error)
}
}
func needsUpdate() {
timer?.invalidate()
timer = NSTimer.schedule(delay: 0.1) { [weak self] timer in
self?.update()
}
}
func didFinishInitialLoad(error: NSError?) {
if let e = error where self.error == nil {
self.error = e
// Any additional errors are ignored.
}
numStreamsFinished?++
needsUpdate()
}
func changed(t: BaseItem) {
if let row = union.find(t.key!) {
delegate?.streamItemsChanged([NSIndexPath(forRow: row, inSection: 0)])
}
}
}
extension UnionStream : Indexable {
public typealias Index = Int
public var startIndex: Index {
return union.startIndex
}
public var endIndex: Index {
return union.startIndex
}
public subscript(i: Index) -> BaseItem {
return union[i]
}
}
extension UnionStream : CollectionType { }
extension UnionStream : StreamBaseProtocol {
public func find(key: String) -> BaseItem? {
if let row = union.find(key) {
return union[row]
}
return nil
}
public func findIndexPath(key: String) -> NSIndexPath? {
if let row = union.find(key) {
return NSIndexPath(forRow: row, inSection: 0)
}
return nil
}
}
private class UnionStreamDelegate: StreamBaseDelegate {
weak var source: StreamBase?
weak var union: UnionStream?
init(source: StreamBase) {
self.source = source
}
func streamWillChange() {
}
func streamDidChange() {
union?.needsUpdate()
}
func streamItemsAdded(paths: [NSIndexPath]) {
}
func streamItemsDeleted(paths: [NSIndexPath]) {
}
func streamItemsChanged(paths: [NSIndexPath]) {
for path in paths {
if let t = source?[path.row] {
union?.changed(t)
}
}
}
func streamDidFinishInitialLoad(error: NSError?) {
union?.didFinishInitialLoad(error)
}
} | ed82ec9457e9bd5a280941c185621f1e | 24.825301 | 94 | 0.580495 | false | false | false | false |
wokalski/Graph.swift | refs/heads/master | Graph/Graph.swift | mit | 1 | /**
Node is a building block of any `Graph`.
*/
public protocol Node: Hashable {
var children: [Self] { get }
}
/**
Graph defines basic directed graph. Instances of conforming can leverage basic Graph algorithms defined in the extension.
*/
public protocol Graph {
associatedtype T : Node
var nodes: [T] { get }
}
public extension Graph {
/**
Checks whether a graph contains a cycle. A cycle means that there is a parent-child relation where child is also a predecessor of the parent.
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- returns: `true` if doesn't contain a cycle
*/
func isAcyclic() -> Bool {
var isAcyclic = true
depthSearch(edgeFound: { edge in
isAcyclic = (edge.type() != .Back)
return isAcyclic
}, nodeStatusChanged: nil)
return isAcyclic
}
/**
Topological sort ([Wikipedia link](https://en.wikipedia.org/wiki/Topological_sorting)) is an ordering of graph's nodes such that for every directed edge u->v, u comes before v in the ordering.
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- returns: Ordered array of nodes or nil if it cannot be done (i.e. the graph contains cycles)
*/
func topologicalSort() -> [T]? {
var orderedVertices = [T]()
var isAcyclic = true
let nodeProcessed = { (nodeInfo: NodeInfo<T>) -> Bool in
if nodeInfo.status == .Processed {
orderedVertices.append(nodeInfo.node)
}
return true
}
depthSearch(edgeFound: { edge in
isAcyclic = (edge.type() != .Back)
return isAcyclic
}
, nodeStatusChanged: nodeProcessed)
return isAcyclic ? orderedVertices : nil
}
/**
Breadth First Search ([Wikipedia link](https://en.wikipedia.org/wiki/Breadth-first_search))
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- Parameter edgeFound: Called whenever a new connection between nodes is discovered
- Parameter nodeStatusChanged: Called when a node changes its status. It is called twice for every node
- Note: Search will stop if `false` is returned from any closure.
- Warning: It will only call `nodeStatusChanged:` on tree edges because we don't maintain entry and exit times of nodes. More information about entry and exit times [here](https://courses.csail.mit.edu/6.006/fall11/rec/rec14.pdf). It is very easy to implement them, but might have big influence on memory use.
*/
func breadthSearch(edgeFound edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) {
var queue = Queue<T>()
var searchInfo = SearchInfo<T>()
for graphRoot in nodes {
if searchInfo.status(graphRoot) == .New {
queue.enqueue(graphRoot)
if updateNodeStatus(&searchInfo, node: graphRoot, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return }
while queue.isEmpty() == false {
let parent = queue.dequeue()
for child in parent.children {
if searchInfo.status(child) == .New {
queue.enqueue(child)
if updateNodeStatus(&searchInfo, node: child, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return }
if let c = edgeFound?(Edge(from: searchInfo.nodeInfo(parent), to: searchInfo.nodeInfo(child))) where c == false { return } // Since we don't maintain entry and exit times, we can only rely on tree edges type.
}
}
if updateNodeStatus(&searchInfo, node: parent, status: .Processed, nodeStatusChanged: nodeStatusChanged) == false { return }
}
}
}
}
/**
Depth First Search ([Wikipedia link](https://en.wikipedia.org/wiki/Depth-first_search))
- Complexity: O(N + E) where N is the number of all nodes, and E is the number of connections between them
- Parameter edgeFound: Called whenever a new connection between nodes is discovered
- Parameter nodeStatusChanged: Called when a node changes its status. It is called twice for every node
- Note: Search will stop if `false` is returned from any closure.
- Warning: This function makes recursive calls. Keep it in mind when operating on big data sets.
*/
func depthSearch(edgeFound edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) {
var searchInfo = SearchInfo<T>()
for node in nodes {
if searchInfo.status(node) == .New {
if dfsVisit(node, searchInfo: &searchInfo, edgeFound: edgeFound, nodeStatusChanged: nodeStatusChanged) == false {
return
}
}
}
}
private func updateNodeStatus(inout searchInfo: SearchInfo<T>, node: T, status: NodeStatus, nodeStatusChanged: (NodeInfo<T> -> Bool)?) -> Bool {
searchInfo.set(node, status: status)
guard let shouldContinue = nodeStatusChanged?(searchInfo.nodeInfo(node)) else {
return true
}
return shouldContinue
}
private func dfsVisit(node: T, inout searchInfo: SearchInfo<T>, edgeFound: (Edge<T> -> Bool)?, nodeStatusChanged: (NodeInfo<T> -> Bool)?) -> Bool {
if updateNodeStatus(&searchInfo, node: node, status: .Discovered, nodeStatusChanged: nodeStatusChanged) == false { return false }
for child in node.children {
if let c = edgeFound?(Edge(from: searchInfo.nodeInfo(node), to: searchInfo.nodeInfo(child))) where c == false { return false }
if searchInfo.status(child) == .New {
if dfsVisit(child, searchInfo: &searchInfo, edgeFound: edgeFound, nodeStatusChanged: nodeStatusChanged) == false {
return false
}
}
}
if updateNodeStatus(&searchInfo, node: node, status: .Processed, nodeStatusChanged: nodeStatusChanged) == false { return false }
return true
}
}
| 1abfdbaade3986aace1213a340c7cc06 | 45.120567 | 314 | 0.611256 | false | false | false | false |
steve-holmes/music-app-2 | refs/heads/master | MusicApp/Modules/Online/OnlineModule.swift | mit | 1 | //
// OnlineModule.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import Swinject
class OnlineModule: Module {
override func register() {
// MARK: Controller
container.register(UINavigationController.self) { [weak self] resolver in
let navigationController = UIStoryboard.online.instantiateViewController(withIdentifier: String(describing: OnlineViewController.self)) as! UINavigationController
if let onlineController = navigationController.viewControllers.first as? OnlineViewController {
onlineController.store = resolver.resolve(OnlineStore.self)!
onlineController.action = resolver.resolve(OnlineAction.self)!
if let searchModule = self?.parent?.searchModule {
onlineController.searchController = searchModule.container.resolve(UISearchController.self)!
}
self?.setupMenu(onlineController)
onlineController.controllers = [
self!.getController(of: HomeViewController.self, in: self!.parent!.homeModule),
self!.getController(of: PlaylistViewController.self, in: self!.parent!.playlistModule),
self!.getController(of: SongViewController.self, in: self!.parent!.songModule),
self!.getController(of: VideoViewController.self, in: self!.parent!.videoModule),
self!.getController(of: RankViewController.self, in: self!.parent!.rankModule),
self!.getController(of: SingerViewController.self, in: self!.parent!.singerModule),
self!.getController(of: TopicViewController.self, in: self!.parent!.topicModule)
]
}
return navigationController
}
container.register(OnlineStore.self) { resolver in
return MAOnlineStore()
}
container.register(OnlineAction.self) { resolver in
return MAOnlineAction(
store: resolver.resolve(OnlineStore.self)!,
service: resolver.resolve(OnlineService.self)!
)
}
// MARK: Domain Model
container.register(OnlineService.self) { resolver in
return MAOnlineService(
coordinator: resolver.resolve(OnlineCoordinator.self)!
)
}
container.register(OnlineCoordinator.self) { resolver in
return MAOnlineCoordinator()
}.initCompleted { [weak self] resolver, coordinator in
let coordinator = coordinator as! MAOnlineCoordinator
coordinator.sourceController = resolver.resolve(UINavigationController.self)?.viewControllers.first as? OnlineViewController
let searchModule = self?.parent?.searchModule
coordinator.getSearchController = { searchModule?.container.resolve(SearchViewController.self) }
}
}
private func setupMenu(_ controller: OnlineViewController) {
let menuColor = UIColor(withIntWhite: 250)
controller.settings.style.buttonBarBackgroundColor = menuColor
controller.settings.style.selectedBarBackgroundColor = .main
controller.settings.style.selectedBarHeight = 3
controller.settings.style.buttonBarBackgroundColor = menuColor
controller.settings.style.buttonBarItemFont = UIFont(name: "AvenirNext-Medium", size: 15)!
controller.settings.style.buttonBarItemTitleColor = .text
controller.buttonBarItemSpec = .cellClass { _ in 80 }
controller.changeCurrentIndexProgressive = { oldCell, newCell, progressPercentage, changeCurrentIndex, animated in
guard changeCurrentIndex == true else { return }
newCell?.label.textColor = .main
oldCell?.label.textColor = .text
newCell?.imageView?.tintColor = .main
oldCell?.imageView?.tintColor = .text
let startScale: CGFloat = 0.9
let endScale: CGFloat = 1.1
if animated {
UIView.animate(withDuration: 0.1) {
newCell?.layer.transform = CATransform3DMakeScale(endScale, endScale, 1)
oldCell?.layer.transform = CATransform3DMakeScale(startScale, startScale, 1)
}
} else {
newCell?.layer.transform = CATransform3DMakeScale(endScale, endScale, 1)
oldCell?.layer.transform = CATransform3DMakeScale(startScale, startScale, 1)
}
}
controller.edgesForExtendedLayout = []
}
}
| 2253ffab7ae14d36fc3ec47e3a539d5d | 42.327434 | 174 | 0.610703 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Managers/Room/RoomIdComponents.swift | apache-2.0 | 1 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// A structure that parses Matrix Room ID and constructs their constituent parts.
struct RoomIdComponents {
// MARK: - Constants
private enum Constants {
static let matrixRoomIdPrefix = "!"
static let homeServerSeparator: Character = ":"
}
// MARK: - Properties
let localRoomId: String
let homeServer: String
// MARK: - Setup
init?(matrixID: String) {
guard MXTools.isMatrixRoomIdentifier(matrixID),
let (localRoomId, homeServer) = RoomIdComponents.getLocalRoomIDAndHomeServer(from: matrixID) else {
return nil
}
self.localRoomId = localRoomId
self.homeServer = homeServer
}
// MARK: - Private
/// Extract local room id and homeserver from Matrix ID
///
/// - Parameter matrixID: A Matrix ID
/// - Returns: A tuple with local room ID and homeserver.
private static func getLocalRoomIDAndHomeServer(from matrixID: String) -> (String, String)? {
let matrixIDParts = matrixID.split(separator: Constants.homeServerSeparator)
guard matrixIDParts.count == 2 else {
return nil
}
let localRoomID = matrixIDParts[0].replacingOccurrences(of: Constants.matrixRoomIdPrefix, with: "")
let homeServer = String(matrixIDParts[1])
return (localRoomID, homeServer)
}
}
| 7a84de0e7013e2bc2caefb8217a72a0c | 30.359375 | 111 | 0.670154 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Sync/SyncStateMachine.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
import Account
private let log = Logger.syncLogger
private let StorageVersionCurrent = 5
// Names of collections that can be enabled/disabled locally.
public let TogglableEngines: [String] = [
"bookmarks",
"history",
"tabs",
"passwords"
]
// Names of collections for which a synchronizer is implemented locally.
private let LocalEngines: [String] = TogglableEngines + ["clients"]
// Names of collections which will appear in a default meta/global produced locally.
// Map collection name to engine version. See http://docs.services.mozilla.com/sync/objectformats.html.
private let DefaultEngines: [String: Int] = [
"bookmarks": 2,
"clients": ClientsStorageVersion,
"history": HistoryStorageVersion,
"tabs": 1,
// We opt-in to syncing collections we don't know about, since no client offers to sync non-enabled,
// non-declined engines yet. See Bug 969669.
"passwords": 1,
"forms": 1,
"addons": 1,
"prefs": 2,
"addresses": 1,
"creditcards": 1,
]
// Names of collections which will appear as declined in a default
// meta/global produced locally.
private let DefaultDeclined: [String] = [String]()
public func computeNewEngines(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> (engines: [String: EngineMeta], declined: [String]) {
var enabled: Set<String> = Set(engineConfiguration.enabled)
var declined: Set<String> = Set(engineConfiguration.declined)
var engines: [String: EngineMeta] = [:]
if let enginesEnablements = enginesEnablements {
let enabledLocally = Set(enginesEnablements.filter { $0.value }.map { $0.key })
let declinedLocally = Set(enginesEnablements.filter { !$0.value }.map { $0.key })
enabled.subtract(declinedLocally)
declined.subtract(enabledLocally)
enabled.formUnion(enabledLocally)
declined.formUnion(declinedLocally)
}
for engine in enabled {
// We take this device's version, or, if we don't know the correct version, 0. Another client should recognize
// the engine, see an old version, wipe and start again.
// TODO: this client does not yet do this wipe-and-update itself!
let version = DefaultEngines[engine] ?? 0
engines[engine] = EngineMeta(version: version, syncID: Bytes.generateGUID())
}
return (engines: engines, declined: Array(declined))
}
// public for testing.
public func createMetaGlobalWithEngineConfiguration(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> MetaGlobal {
let (engines, declined) = computeNewEngines(engineConfiguration, enginesEnablements: enginesEnablements)
return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: engines, declined: declined)
}
public func createMetaGlobal(enginesEnablements: [String: Bool]?) -> MetaGlobal {
let engineConfiguration = EngineConfiguration(enabled: Array(DefaultEngines.keys), declined: DefaultDeclined)
return createMetaGlobalWithEngineConfiguration(engineConfiguration, enginesEnablements: enginesEnablements)
}
public typealias TokenSource = () -> Deferred<Maybe<TokenServerToken>>
public typealias ReadyDeferred = Deferred<Maybe<Ready>>
// See docs in docs/sync.md.
// You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine
// does. Well, such a client is pinned to a particular server, and this state machine must
// acknowledge that a Sync client occasionally must migrate between two servers, preserving
// some state from the last.
// The resultant 'Ready' will be able to provide a suitably initialized storage client.
open class SyncStateMachine {
// The keys are used as a set, to prevent cycles in the state machine.
var stateLabelsSeen = [SyncStateLabel: Bool]()
var stateLabelSequence = [SyncStateLabel]()
let stateLabelsAllowed: Set<SyncStateLabel>
let scratchpadPrefs: Prefs
/// Use this set of states to constrain the state machine to attempt the barest
/// minimum to get to Ready. This is suitable for extension uses. If it is not possible,
/// then no destructive or expensive actions are taken (e.g. total HTTP requests,
/// duration, records processed, database writes, fsyncs, blanking any local collections)
public static let OptimisticStates = Set(SyncStateLabel.optimisticValues)
/// The default set of states that the state machine is allowed to use.
public static let AllStates = Set(SyncStateLabel.allValues)
public init(prefs: Prefs, allowingStates labels: Set<SyncStateLabel> = SyncStateMachine.AllStates) {
self.scratchpadPrefs = prefs.branch("scratchpad")
self.stateLabelsAllowed = labels
}
open class func clearStateFromPrefs(_ prefs: Prefs) {
log.debug("Clearing all Sync prefs.")
Scratchpad.clearFromPrefs(prefs.branch("scratchpad")) // XXX this is convoluted.
prefs.clearAll()
}
fileprivate func advanceFromState(_ state: SyncState) -> ReadyDeferred {
log.info("advanceFromState: \(state.label)")
// Record visibility before taking any action.
let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: state.label) != nil
stateLabelSequence.append(state.label)
if let ready = state as? Ready {
// Sweet, we made it!
return deferMaybe(ready)
}
// Cycles are not necessarily a problem, but seeing the same (recoverable) error condition is a problem.
if state is RecoverableSyncState && labelAlreadySeen {
return deferMaybe(StateMachineCycleError())
}
guard stateLabelsAllowed.contains(state.label) else {
return deferMaybe(DisallowedStateError(state.label, allowedStates: stateLabelsAllowed))
}
return state.advance() >>== self.advanceFromState
}
open func toReady(_ authState: SyncAuthState) -> ReadyDeferred {
let readyDeferred = ReadyDeferred()
RustFirefoxAccounts.shared.accountManager.uponQueue(.main) { accountManager in
authState.token(Date.now(), canBeExpired: false).uponQueue(.main) { success in
guard let (token, kSync) = success.successValue else {
readyDeferred.fill(Maybe(failure: success.failureValue ?? FxAClientError.local(NSError())))
return
}
log.debug("Got token from auth state.")
if Logger.logPII {
log.debug("Server is \(token.api_endpoint).")
}
let prior = Scratchpad.restoreFromPrefs(self.scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync))
if prior == nil {
log.info("No persisted Sync state. Starting over.")
}
var scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKSync(kSync), persistingTo: self.scratchpadPrefs)
// Take the scratchpad and add the fxaDeviceId from the state, and hashedUID from the token
let b = Scratchpad.Builder(p: scratchpad)
if let deviceID = accountManager.deviceConstellation()?.state()?.localDevice?.id {
b.fxaDeviceId = deviceID
} else {
// Either deviceRegistration hasn't occurred yet (our bug) or
// FxA has given us an UnknownDevice error.
log.warning("Device registration has not taken place before sync.")
}
b.hashedUID = token.hashedFxAUID
if let enginesEnablements = authState.enginesEnablements,
!enginesEnablements.isEmpty {
b.enginesEnablements = enginesEnablements
}
if let clientName = authState.clientName {
b.clientName = clientName
}
// Detect if we've changed anything in our client record from the last time we synced…
let ourClientUnchanged = (b.fxaDeviceId == scratchpad.fxaDeviceId)
// …and if so, trigger a reset of clients.
if !ourClientUnchanged {
b.localCommands.insert(LocalCommand.resetEngine(engine: "clients"))
}
scratchpad = b.build()
log.info("Advancing to InitialWithLiveToken.")
let state = InitialWithLiveToken(scratchpad: scratchpad, token: token)
// Start with fresh visibility data.
self.stateLabelsSeen = [:]
self.stateLabelSequence = []
self.advanceFromState(state).uponQueue(.main) { success in
readyDeferred.fill(success)
}
}
}
return readyDeferred
}
}
public enum SyncStateLabel: String {
case Stub = "STUB" // For 'abstract' base classes.
case InitialWithExpiredToken = "initialWithExpiredToken"
case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo"
case InitialWithLiveToken = "initialWithLiveToken"
case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo"
case ResolveMetaGlobalVersion = "resolveMetaGlobalVersion"
case ResolveMetaGlobalContent = "resolveMetaGlobalContent"
case NeedsFreshMetaGlobal = "needsFreshMetaGlobal"
case NewMetaGlobal = "newMetaGlobal"
case HasMetaGlobal = "hasMetaGlobal"
case NeedsFreshCryptoKeys = "needsFreshCryptoKeys"
case HasFreshCryptoKeys = "hasFreshCryptoKeys"
case Ready = "ready"
case FreshStartRequired = "freshStartRequired" // Go around again... once only, perhaps.
case ServerConfigurationRequired = "serverConfigurationRequired"
case ChangedServer = "changedServer"
case MissingMetaGlobal = "missingMetaGlobal"
case MissingCryptoKeys = "missingCryptoKeys"
case MalformedCryptoKeys = "malformedCryptoKeys"
case SyncIDChanged = "syncIDChanged"
case RemoteUpgradeRequired = "remoteUpgradeRequired"
case ClientUpgradeRequired = "clientUpgradeRequired"
static let allValues: [SyncStateLabel] = [
InitialWithExpiredToken,
InitialWithExpiredTokenAndInfo,
InitialWithLiveToken,
InitialWithLiveTokenAndInfo,
NeedsFreshMetaGlobal,
ResolveMetaGlobalVersion,
ResolveMetaGlobalContent,
NewMetaGlobal,
HasMetaGlobal,
NeedsFreshCryptoKeys,
HasFreshCryptoKeys,
Ready,
FreshStartRequired,
ServerConfigurationRequired,
ChangedServer,
MissingMetaGlobal,
MissingCryptoKeys,
MalformedCryptoKeys,
SyncIDChanged,
RemoteUpgradeRequired,
ClientUpgradeRequired,
]
// This is the list of states needed to get to Ready, or failing.
// This is useful in circumstances where it is important to conserve time and/or battery, and failure
// to timely sync is acceptable.
static let optimisticValues: [SyncStateLabel] = [
InitialWithLiveToken,
InitialWithLiveTokenAndInfo,
HasMetaGlobal,
HasFreshCryptoKeys,
Ready,
]
}
/**
* States in this state machine all implement SyncState.
*
* States are either successful main-flow states, or (recoverable) error states.
* Errors that aren't recoverable are simply errors.
* Main-flow states flow one to one.
*
* (Terminal failure states might be introduced at some point.)
*
* Multiple error states (but typically only one) can arise from each main state transition.
* For example, parsing meta/global can result in a number of different non-routine situations.
*
* For these reasons, and the lack of useful ADTs in Swift, we model the main flow as
* the success branch of a Result, and the recovery flows as a part of the failure branch.
*
* We could just as easily use a ternary Either-style operator, but thanks to Swift's
* optional-cast-let it's no saving to do so.
*
* Because of the lack of type system support, all RecoverableSyncStates must have the same
* signature. That signature implies a possibly multi-state transition; individual states
* will have richer type signatures.
*/
public protocol SyncState {
var label: SyncStateLabel { get }
func advance() -> Deferred<Maybe<SyncState>>
}
/*
* Base classes to avoid repeating initializers all over the place.
*/
open class BaseSyncState: SyncState {
open var label: SyncStateLabel { return SyncStateLabel.Stub }
public let client: Sync15StorageClient!
let token: TokenServerToken // Maybe expired.
var scratchpad: Scratchpad
// TODO: 304 for i/c.
open func getInfoCollections() -> Deferred<Maybe<InfoCollections>> {
return chain(self.client.getInfoCollections(), f: {
return $0.value
})
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) {
self.scratchpad = scratchpad
self.token = token
self.client = client
log.info("Inited \(self.label.rawValue)")
}
open func synchronizer<T: Synchronizer>(_ synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs, why: SyncReason) -> T {
return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs, why: why)
}
// This isn't a convenience initializer 'cos subclasses can't call convenience initializers.
public init(scratchpad: Scratchpad, token: TokenServerToken) {
let workQueue = DispatchQueue.global()
let resultQueue = DispatchQueue.main
let backoff = scratchpad.backoffStorage
let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff)
self.scratchpad = scratchpad
self.token = token
self.client = client
log.info("Inited \(self.label.rawValue)")
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(StubStateError())
}
}
open class BaseSyncStateWithInfo: BaseSyncState {
public let info: InfoCollections
init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.info = info
super.init(client: client, scratchpad: scratchpad, token: token)
}
init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.info = info
super.init(scratchpad: scratchpad, token: token)
}
}
/*
* Error types.
*/
public protocol SyncError: MaybeErrorType, SyncPingFailureFormattable {}
extension SyncError {
public var failureReasonName: SyncPingFailureReasonName {
return .unexpectedError
}
}
open class UnknownError: SyncError {
open var description: String {
return "Unknown error."
}
}
open class StateMachineCycleError: SyncError {
open var description: String {
return "The Sync state machine encountered a cycle. This is a coding error."
}
}
open class CouldNotFetchMetaGlobalError: SyncError {
open var description: String {
return "Could not fetch meta/global."
}
}
open class CouldNotFetchKeysError: SyncError {
open var description: String {
return "Could not fetch crypto/keys."
}
}
open class StubStateError: SyncError {
open var description: String {
return "Unexpectedly reached a stub state. This is a coding error."
}
}
open class ClientUpgradeRequiredError: SyncError {
let targetStorageVersion: Int
public init(target: Int) {
self.targetStorageVersion = target
}
open var description: String {
return "Client upgrade required to work with storage version \(self.targetStorageVersion)."
}
}
open class InvalidKeysError: SyncError {
let keys: Keys
public init(_ keys: Keys) {
self.keys = keys
}
open var description: String {
return "Downloaded crypto/keys, but couldn't parse them."
}
}
open class DisallowedStateError: SyncError {
let state: SyncStateLabel
let allowedStates: Set<SyncStateLabel>
public init(_ state: SyncStateLabel, allowedStates: Set<SyncStateLabel>) {
self.state = state
self.allowedStates = allowedStates
}
open var description: String {
return "Sync state machine reached \(String(describing: state)) state, which is disallowed. Legal states are: \(String(describing: allowedStates))"
}
}
/**
* Error states. These are errors that can be recovered from by taking actions. We use RecoverableSyncState as a
* sentinel: if we see the same recoverable state twice, we bail out and complain that we've seen a cycle. (Seeing
* some states -- principally initial states -- twice is fine.)
*/
public protocol RecoverableSyncState: SyncState {
}
/**
* Recovery: discard our local timestamps and sync states; discard caches.
* Be prepared to handle a conflict between our selected engines and the new
* server's meta/global; if an engine is selected locally but not declined
* remotely, then we'll need to upload a new meta/global and sync that engine.
*/
open class ChangedServerError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.ChangedServer }
let newToken: TokenServerToken
let newScratchpad: Scratchpad
public init(scratchpad: Scratchpad, token: TokenServerToken) {
self.newToken = token
self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs)
}
open func advance() -> Deferred<Maybe<SyncState>> {
// TODO: mutate local storage to allow for a fresh start.
let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken)
return deferMaybe(state)
}
}
/**
* Recovery: same as for changed server, but no need to upload a new meta/global.
*/
open class SyncIDChangedError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged }
fileprivate let previousState: BaseSyncStateWithInfo
fileprivate let newMetaGlobal: Fetched<MetaGlobal>
public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) {
self.previousState = previousState
self.newMetaGlobal = newMetaGlobal
}
open func advance() -> Deferred<Maybe<SyncState>> {
// TODO: mutate local storage to allow for a fresh start.
let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint()
let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info)
return deferMaybe(state)
}
}
/**
* Recovery: configure the server.
*/
open class ServerConfigurationRequiredError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.ServerConfigurationRequired }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
let client = self.previousState.client!
let oldScratchpad = self.previousState.scratchpad
let enginesEnablements = oldScratchpad.enginesEnablements
let s = oldScratchpad.evolve()
.setGlobal(nil)
.addLocalCommandsFromKeys(nil)
.setKeys(nil)
.clearEnginesEnablements()
.build().checkpoint()
// Upload a new meta/global ...
let metaGlobal: MetaGlobal
if let oldEngineConfiguration = s.engineConfiguration {
metaGlobal = createMetaGlobalWithEngineConfiguration(oldEngineConfiguration, enginesEnablements: enginesEnablements)
} else {
metaGlobal = createMetaGlobal(enginesEnablements: enginesEnablements)
}
return client.uploadMetaGlobal(metaGlobal, ifUnmodifiedSince: nil)
// ... and a new crypto/keys.
>>> { return client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: s.syncKeyBundle, ifUnmodifiedSince: nil) }
>>> { return deferMaybe(InitialWithLiveToken(client: client, scratchpad: s, token: self.previousState.token)) }
}
}
/**
* Recovery: wipe the server (perhaps unnecessarily) and proceed to configure the server.
*/
open class FreshStartRequiredError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.FreshStartRequired }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
let client = self.previousState.client!
return client.wipeStorage()
>>> { return deferMaybe(ServerConfigurationRequiredError(previousState: self.previousState)) }
}
}
open class MissingMetaGlobalError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
open class MissingCryptoKeysError: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
open class RemoteUpgradeRequired: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.RemoteUpgradeRequired }
fileprivate let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
open class ClientUpgradeRequired: RecoverableSyncState {
open var label: SyncStateLabel { return SyncStateLabel.ClientUpgradeRequired }
fileprivate let previousState: BaseSyncStateWithInfo
let targetStorageVersion: Int
public init(previousState: BaseSyncStateWithInfo, target: Int) {
self.previousState = previousState
self.targetStorageVersion = target
}
open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(ClientUpgradeRequiredError(target: self.targetStorageVersion))
}
}
/*
* Non-error states.
*/
open class InitialWithLiveToken: BaseSyncState {
open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken }
// This looks totally redundant, but try taking it out, I dare you.
public override init(scratchpad: Scratchpad, token: TokenServerToken) {
super.init(scratchpad: scratchpad, token: token)
}
// This looks totally redundant, but try taking it out, I dare you.
public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) {
super.init(client: client, scratchpad: scratchpad, token: token)
}
func advanceWithInfo(_ info: InfoCollections) -> SyncState {
return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
return chain(getInfoCollections(), f: self.advanceWithInfo)
}
}
/**
* Each time we fetch a new meta/global, we need to reconcile it with our
* current state.
*
* It might be identical to our current meta/global, in which case we can short-circuit.
*
* We might have no previous meta/global at all, in which case this state
* simply configures local storage to be ready to sync according to the
* supplied meta/global. (Not necessarily datatype elections: those will be per-device.)
*
* Or it might be different. In this case the previous m/g and our local user preferences
* are compared to the new, resulting in some actions and a final state.
*
* This states are similar in purpose to GlobalSession.processMetaGlobal in Android Sync.
*/
open class ResolveMetaGlobalVersion: BaseSyncStateWithInfo {
let fetched: Fetched<MetaGlobal>
init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.fetched = fetched
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalVersion }
class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalVersion {
return ResolveMetaGlobalVersion(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// First: check storage version.
let v = fetched.value.storageVersion
if v > StorageVersionCurrent {
// New storage version? Uh-oh. No recovery possible here.
log.info("Client upgrade required for storage version \(v)")
return deferMaybe(ClientUpgradeRequired(previousState: self, target: v))
}
if v < StorageVersionCurrent {
// Old storage version? Uh-oh. Wipe and upload both meta/global and crypto/keys.
log.info("Server storage version \(v) is outdated.")
return deferMaybe(RemoteUpgradeRequired(previousState: self))
}
return deferMaybe(ResolveMetaGlobalContent.fromState(self, fetched: self.fetched))
}
}
open class ResolveMetaGlobalContent: BaseSyncStateWithInfo {
let fetched: Fetched<MetaGlobal>
init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.fetched = fetched
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalContent }
class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalContent {
return ResolveMetaGlobalContent(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Check global syncID and contents.
if let previous = self.scratchpad.global?.value {
// Do checks that only apply when we're coming from a previous meta/global.
if previous.syncID != fetched.value.syncID {
log.info("Remote global sync ID has changed. Dropping keys and resetting all local collections.")
let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
let b = self.scratchpad.evolve()
.setGlobal(fetched) // We always adopt the upstream meta/global record.
let previousEngines = Set(previous.engines.keys)
let remoteEngines = Set(fetched.value.engines.keys)
for engine in previousEngines.subtracting(remoteEngines) {
log.info("Remote meta/global disabled previously enabled engine \(engine).")
b.localCommands.insert(.disableEngine(engine: engine))
}
for engine in remoteEngines.subtracting(previousEngines) {
log.info("Remote meta/global enabled previously disabled engine \(engine).")
b.localCommands.insert(.enableEngine(engine: engine))
}
for engine in remoteEngines.intersection(previousEngines) {
let remoteEngine = fetched.value.engines[engine]!
let previousEngine = previous.engines[engine]!
if previousEngine.syncID != remoteEngine.syncID {
log.info("Remote sync ID for \(engine) has changed. Resetting local.")
b.localCommands.insert(.resetEngine(engine: engine))
}
}
let s = b.build().checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
// No previous meta/global. Adopt the new meta/global.
let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
}
private func processFailure(_ failure: MaybeErrorType?) -> MaybeErrorType {
if let failure = failure as? ServerInBackoffError {
log.warning("Server in backoff. Bailing out. \(failure.description)")
return failure
}
// TODO: backoff etc. for all of these.
if let failure = failure as? ServerError<HTTPURLResponse> {
// Be passive.
log.error("Server error. Bailing out. \(failure.description)")
return failure
}
if let failure = failure as? BadRequestError<HTTPURLResponse> {
// Uh oh.
log.error("Bad request. Bailing out. \(failure.description)")
return failure
}
log.error("Unexpected failure. \(failure?.description ?? "nil")")
return failure ?? UnknownError()
}
open class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo }
// This method basically hops over HasMetaGlobal, because it's not a state
// that we expect consumers to know about.
override open func advance() -> Deferred<Maybe<SyncState>> {
// Either m/g and c/k are in our local cache, and they're up-to-date with i/c,
// or we need to fetch them.
// Cached and not changed in i/c? Use that.
// This check would be inaccurate if any other fields were stored in meta/; this
// has been the case in the past, with the Sync 1.1 migration indicator.
if let global = self.scratchpad.global {
if let metaModified = self.info.modified("meta") {
// We check the last time we fetched the record, and that can be
// later than the collection timestamp. All we care about here is if the
// server might have a newer record.
if global.timestamp >= metaModified {
log.debug("Cached meta/global fetched at \(global.timestamp), newer than server modified \(metaModified). Using cached meta/global.")
// Strictly speaking we can avoid fetching if this condition is not true,
// but if meta/ is modified for a different reason -- store timestamps
// for the last collection fetch. This will do for now.
return deferMaybe(HasMetaGlobal.fromState(self))
}
log.info("Cached meta/global fetched at \(global.timestamp) older than server modified \(metaModified). Fetching fresh meta/global.")
} else {
// No known modified time for meta/. That means the server has no meta/global.
// Drop our cached value and fall through; we'll try to fetch, fail, and
// go through the usual failure flow.
log.warning("Local meta/global fetched at \(global.timestamp) found, but no meta collection on server. Dropping cached meta/global.")
// If we bail because we've been overly optimistic, then we nil out the current (broken)
// meta/global. Next time around, we end up in the "No cached meta/global found" branch.
self.scratchpad = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint()
}
} else {
log.debug("No cached meta/global found. Fetching fresh meta/global.")
}
return deferMaybe(NeedsFreshMetaGlobal.fromState(self))
}
}
/*
* We've reached NeedsFreshMetaGlobal somehow, but we haven't yet done anything about it
* (e.g. fetch a new one with GET /storage/meta/global ).
*
* If we don't want to hit the network (e.g. from an extension), we should stop if we get to this state.
*/
open class NeedsFreshMetaGlobal: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshMetaGlobal }
class func fromState(_ state: BaseSyncStateWithInfo) -> NeedsFreshMetaGlobal {
return NeedsFreshMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Fetch.
return self.client.getMetaGlobal().bind { result in
if let resp = result.successValue {
// We use the server's timestamp, rather than the record's modified field.
// Either can be made to work, but the latter has suffered from bugs: see Bug 1210625.
let fetched = Fetched(value: resp.value, timestamp: resp.metadata.timestampMilliseconds)
return deferMaybe(ResolveMetaGlobalVersion.fromState(self, fetched: fetched))
}
if result.failureValue as? NotFound<HTTPURLResponse> != nil {
// OK, this is easy.
// This state is responsible for creating the new m/g, uploading it, and
// restarting with a clean scratchpad.
return deferMaybe(MissingMetaGlobalError(previousState: self))
}
// Otherwise, we have a failure state. Die on the sword!
return deferMaybe(processFailure(result.failureValue))
}
}
}
open class HasMetaGlobal: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal }
class func fromState(_ state: BaseSyncStateWithInfo) -> HasMetaGlobal {
return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal {
return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Check if we have enabled/disabled some engines.
if let enginesEnablements = self.scratchpad.enginesEnablements,
let oldMetaGlobal = self.scratchpad.global {
let (engines, declined) = computeNewEngines(oldMetaGlobal.value.engineConfiguration(), enginesEnablements: enginesEnablements)
let newMetaGlobal = MetaGlobal(syncID: oldMetaGlobal.value.syncID, storageVersion: oldMetaGlobal.value.storageVersion, engines: engines, declined: declined)
return self.client.uploadMetaGlobal(newMetaGlobal, ifUnmodifiedSince: oldMetaGlobal.timestamp) >>> {
self.scratchpad = self.scratchpad.evolve().clearEnginesEnablements().build().checkpoint()
return deferMaybe(NeedsFreshMetaGlobal.fromState(self))
}
}
// Check if crypto/keys is fresh in the cache already.
if let keys = self.scratchpad.keys, keys.value.valid {
if let cryptoModified = self.info.modified("crypto") {
// Both of these are server timestamps. If the record we stored was
// fetched after the last time the record was modified, as represented
// by the "crypto" entry in info/collections, and we're fetching from the
// same server, then the record must be identical, and we can use it
// directly. If are ever additional records in the crypto collection,
// this will fetch keys too frequently. In that case, we should use
// X-I-U-S and expect some 304 responses.
if keys.timestamp >= cryptoModified {
log.debug("Cached keys fetched at \(keys.timestamp), newer than server modified \(cryptoModified). Using cached keys.")
return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, collectionKeys: keys.value))
}
// The server timestamp is newer, so there might be new keys.
// Re-fetch keys and check to see if the actual contents differ.
// If the keys are the same, we can ignore this change. If they differ,
// we need to re-sync any collection whose keys just changed.
log.info("Cached keys fetched at \(keys.timestamp) older than server modified \(cryptoModified). Fetching fresh keys.")
return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: keys.value))
} else {
// No known modified time for crypto/. That likely means the server has no keys.
// Drop our cached value and fall through; we'll try to fetch, fail, and
// go through the usual failure flow.
log.warning("Local keys fetched at \(keys.timestamp) found, but no crypto collection on server. Dropping cached keys.")
self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint()
}
} else {
log.debug("No cached keys found. Fetching fresh keys.")
}
return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: nil))
}
}
open class NeedsFreshCryptoKeys: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshCryptoKeys }
let staleCollectionKeys: Keys?
class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, staleCollectionKeys: Keys?) -> NeedsFreshCryptoKeys {
return NeedsFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: staleCollectionKeys)
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys?) {
self.staleCollectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
// Fetch crypto/keys.
return self.client.getCryptoKeys(self.scratchpad.syncKeyBundle, ifUnmodifiedSince: nil).bind { result in
if let resp = result.successValue {
let collectionKeys = Keys(payload: resp.value.payload)
if !collectionKeys.valid {
log.error("Unexpectedly invalid crypto/keys during a successful fetch.")
return Deferred(value: Maybe(failure: InvalidKeysError(collectionKeys)))
}
let fetched = Fetched(value: collectionKeys, timestamp: resp.metadata.timestampMilliseconds)
let s = self.scratchpad.evolve()
.addLocalCommandsFromKeys(fetched)
.setKeys(fetched)
.build().checkpoint()
return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: s, collectionKeys: collectionKeys))
}
if result.failureValue as? NotFound<HTTPURLResponse> != nil {
// No crypto/keys? We can handle this. Wipe and upload both meta/global and crypto/keys.
return deferMaybe(MissingCryptoKeysError(previousState: self))
}
// Otherwise, we have a failure state.
return deferMaybe(processFailure(result.failureValue))
}
}
}
open class HasFreshCryptoKeys: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.HasFreshCryptoKeys }
let collectionKeys: Keys
class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, collectionKeys: Keys) -> HasFreshCryptoKeys {
return HasFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: collectionKeys)
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) {
self.collectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
override open func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: self.collectionKeys))
}
}
public protocol EngineStateChanges {
func collectionsThatNeedLocalReset() -> [String]
func enginesEnabled() -> [String]
func enginesDisabled() -> [String]
func clearLocalCommands()
}
open class Ready: BaseSyncStateWithInfo {
open override var label: SyncStateLabel { return SyncStateLabel.Ready }
let collectionKeys: Keys
public var hashedFxADeviceID: String {
return (scratchpad.fxaDeviceId + token.hashedFxAUID).sha256.hexEncodedString
}
public var engineConfiguration: EngineConfiguration? {
return scratchpad.engineConfiguration
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) {
self.collectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
}
extension Ready: EngineStateChanges {
public func collectionsThatNeedLocalReset() -> [String] {
var needReset: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .resetAllEngines(except: except):
needReset.formUnion(Set(LocalEngines).subtracting(except))
case let .resetEngine(engine):
needReset.insert(engine)
case .enableEngine, .disableEngine:
break
}
}
return needReset.sorted()
}
public func enginesEnabled() -> [String] {
var engines: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .enableEngine(engine):
engines.insert(engine)
default:
break
}
}
return engines.sorted()
}
public func enginesDisabled() -> [String] {
var engines: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .disableEngine(engine):
engines.insert(engine)
default:
break
}
}
return engines.sorted()
}
public func clearLocalCommands() {
self.scratchpad = self.scratchpad.evolve().clearLocalCommands().build().checkpoint()
}
}
| b87fa8be9b4a9375c502b340847ded4e | 41.511673 | 168 | 0.679076 | false | false | false | false |
UncleJoke/Spiral | refs/heads/master | Spiral/PlayerContactVisitor.swift | mit | 1 | //
// PlayerContactVisitor.swift
// Spiral
//
// Created by 杨萧玉 on 14-7-14.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import Foundation
import SpriteKit
class PlayerContactVisitor:ContactVisitor{
func visitPlayer(body:SKPhysicsBody){
// let thisNode = self.body.node
// let otherNode = body.node
// println(thisNode.name+"->"+otherNode.name)
}
func visitKiller(body:SKPhysicsBody){
let thisNode = self.body.node as! Player
// let otherNode = body.node
if thisNode.shield {
thisNode.shield = false
Data.sharedData.score++
let achievement = GameKitHelper.sharedGameKitHelper.getAchievementForIdentifier(kClean100KillerAchievementID)
if achievement.percentComplete <= 99.0{
achievement.percentComplete += 1
}
GameKitHelper.sharedGameKitHelper.updateAchievement(achievement, identifier: kClean100KillerAchievementID)
(thisNode.parent as! GameScene).soundManager.playKiller()
}
else {
thisNode.removeAllActions()
Data.sharedData.gameOver = true
}
}
func visitScore(body:SKPhysicsBody){
let thisNode = self.body.node as! Player
// let otherNode = body.node
Data.sharedData.score += 2
let achievement = GameKitHelper.sharedGameKitHelper.getAchievementForIdentifier(kCatch500ScoreAchievementID)
if achievement.percentComplete <= 99.8{
achievement.percentComplete += 0.2
}
GameKitHelper.sharedGameKitHelper.updateAchievement(achievement, identifier: kCatch500ScoreAchievementID)
(thisNode.parent as! GameScene).soundManager.playScore()
}
func visitShield(body:SKPhysicsBody){
let thisNode = self.body.node as! Player
// let otherNode = body.node
thisNode.shield = true
Data.sharedData.score++
let achievement = GameKitHelper.sharedGameKitHelper.getAchievementForIdentifier(kCatch500ShieldAchievementID)
if achievement.percentComplete <= 99.8{
achievement.percentComplete += 0.2
}
GameKitHelper.sharedGameKitHelper.updateAchievement(achievement, identifier: kCatch500ShieldAchievementID)
(thisNode.parent as! GameScene).soundManager.playShield()
}
} | efff682f5018e0d3fba240510b161e7e | 35.307692 | 121 | 0.672319 | false | false | false | false |
phatblat/realm-cocoa | refs/heads/master | Realm/Tests/Swift/SwiftUnicodeTests.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 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 XCTest
import Realm
#if canImport(RealmTestSupport)
import RealmTestSupport
#endif
let utf8TestString = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
class SwiftRLMUnicodeTests: RLMTestCase {
// Swift models
func testUTF8StringContents() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = SwiftRLMStringObject.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = SwiftRLMStringObject.allObjects(in: realm).firstObject() as! SwiftRLMStringObject
XCTAssertEqual(obj1.stringCol, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
let obj2 = SwiftRLMStringObject.objects(in: realm, where: "stringCol == %@", utf8TestString).firstObject() as! SwiftRLMStringObject
XCTAssertTrue(obj1.isEqual(to: obj2), "Querying a realm searching for a string with UTF8 content should work")
}
func testUTF8PropertyWithUTF8StringContents() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = SwiftRLMUTF8Object.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = SwiftRLMUTF8Object.allObjects(in: realm).firstObject() as! SwiftRLMUTF8Object
XCTAssertEqual(obj1.柱колоéнǢкƱаم👍, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Test fails because of rdar://17735684
// let obj2 = SwiftRLMUTF8Object.objectsInRealm(realm, "柱колоéнǢкƱаم👍 == %@", utf8TestString).firstObject() as SwiftRLMUTF8Object
// XCTAssertEqual(obj1, obj2, "Querying a realm searching for a string with UTF8 content should work")
}
// Objective-C models
func testUTF8StringContents_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = StringObject.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = StringObject.allObjects(in: realm).firstObject() as! StringObject
XCTAssertEqual(obj1.stringCol, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Temporarily commented out because variadic import seems broken
let obj2 = StringObject.objects(in: realm, where: "stringCol == %@", utf8TestString).firstObject() as! StringObject
XCTAssertTrue(obj1.isEqual(to: obj2), "Querying a realm searching for a string with UTF8 content should work")
}
func testUTF8PropertyWithUTF8StringContents_objc() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = UTF8Object.create(in: realm, withValue: [utf8TestString])
try! realm.commitWriteTransaction()
let obj1 = UTF8Object.allObjects(in: realm).firstObject() as! UTF8Object
XCTAssertEqual(obj1.柱колоéнǢкƱаم, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Test fails because of rdar://17735684
// let obj2 = UTF8Object.objectsInRealm(realm, "柱колоéнǢкƱаم == %@", utf8TestString).firstObject() as UTF8Object
// XCTAssertEqual(obj1, obj2, "Querying a realm searching for a string with UTF8 content should work")
}
}
| b31557155f8f2c0a5bb4d7c7e1c5b2de | 44.375 | 139 | 0.688956 | false | true | false | false |
toshiapp/toshi-ios-client | refs/heads/master | Toshi/Controllers/Payments/View/PaymentAddressInputView.swift | gpl-3.0 | 1 | import Foundation
import UIKit
import TinyConstraints
protocol PaymentAddressInputDelegate: class {
func didRequestScanner()
func didRequestSendPayment()
func didChangeAddress(_ text: String)
}
final class PaymentAddressInputView: UIView {
weak var delegate: PaymentAddressInputDelegate?
var paymentAddress: String? {
didSet {
addressTextField.text = paymentAddress
}
}
private lazy var topDivider: UIView = {
let view = UIView()
view.backgroundColor = Theme.borderColor
return view
}()
private(set) lazy var addressTextField: UITextField = {
let view = UITextField()
view.font = Theme.preferredRegular()
view.delegate = self
view.placeholder = Localized.payment_input_placeholder
view.returnKeyType = .send
view.adjustsFontForContentSizeCategory = true
return view
}()
private lazy var qrButton: UIButton = {
let image = ImageAsset.qr_icon.withRenderingMode(.alwaysTemplate)
let view = UIButton()
view.contentMode = .center
view.tintColor = Theme.darkTextColor
view.setImage(image, for: .normal)
view.addTarget(self, action: #selector(qrButtonTapped(_:)), for: .touchUpInside)
return view
}()
private lazy var bottomDivider: UIView = {
let view = UIView()
view.backgroundColor = Theme.borderColor
return view
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(topDivider)
addSubview(addressTextField)
addSubview(qrButton)
addSubview(bottomDivider)
topDivider.top(to: self)
topDivider.left(to: self)
topDivider.right(to: self)
topDivider.height(.lineHeight)
addressTextField.left(to: self, offset: 16)
addressTextField.centerY(to: self)
qrButton.topToBottom(of: topDivider)
qrButton.leftToRight(of: addressTextField)
qrButton.bottomToTop(of: bottomDivider)
qrButton.right(to: self)
qrButton.width(50)
qrButton.height(58)
bottomDivider.left(to: self, offset: 16)
bottomDivider.bottom(to: self)
bottomDivider.right(to: self, offset: -16)
bottomDivider.height(.lineHeight)
}
@objc func qrButtonTapped(_ button: UIButton) {
delegate?.didRequestScanner()
}
}
extension PaymentAddressInputView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
delegate?.didRequestSendPayment()
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldText: NSString = String.contentsOrEmpty(for: textField.text) as NSString
let textAfterUpdate = textFieldText.replacingCharacters(in: range, with: string)
delegate?.didChangeAddress(textAfterUpdate)
return true
}
}
| fbb07603520f8885e1ace6fb3ffcbc55 | 27.481818 | 129 | 0.661028 | false | false | false | false |
LYM-mg/MGOFO | refs/heads/master | MGOFO/MGOFO/Class/Home/Controller/ManuallyEnterLicenseVC.swift | mit | 1 | //
// ManuallyEnterLicenseVC.swift
// MGOFO
//
// Created by i-Techsys.com on 2017/5/15.
// Copyright © 2017年 i-Techsys. All rights reserved.
// 手动输入车牌号解锁
import UIKit
/*
import AVKit
import AudioToolbox
import CoreAudioKit
import CoreAudio
*/
class ManuallyEnterLicenseVC: UIViewController {
weak var superVC: EnterLicenseViewController?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
setUpNavgationItem()
setUpMainView()
}
fileprivate func setUpNavgationItem() {
self.title = "车辆解锁"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "扫码用车", style: .done, target: self, action: #selector(backToScan))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navigationButtonReturnClick"), highImage: #imageLiteral(resourceName: "navigationButtonReturnClick"), norColor: UIColor.darkGray, selColor: UIColor.lightGray, title: "返回", target: self, action: #selector(ManuallyEnterLicenseVC.popClick(_:)))
}
@objc fileprivate func popClick(_ sender: UIButton) {
let _ = superVC?.navigationController?.popViewController(animated: true)
}
@objc fileprivate func backToScan() {
let _ = superVC?.navigationController?.popViewController(animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.view.endEditing(true)
}
}
// MARK: - setUpMainView
extension ManuallyEnterLicenseVC {
// MARK: setUpMainView
fileprivate func setUpMainView() {
self.automaticallyAdjustsScrollViewInsets = false
setUpNavgationItem()
/// 顶部
let topView = TopView()
topView.resultLabel.isHidden = true
let bottomView = BottomView()
view.addSubview(topView)
view.addSubview(bottomView)
topView.sureBtnBlock = {
let secondController: UINavigationController? = self.superVC?.childViewControllers[1] as? UINavigationController
let oldController: UIViewController = (self.superVC?.currentViewController)!
self.superVC?.transition(from: oldController, to: secondController!, duration: 1, options: .transitionFlipFromLeft, animations: {() -> Void in
}, completion: {(_ finished: Bool) -> Void in
if finished {
// 隐藏返回(这时候无法pop回去上一个界面,否则就无法正常计费,导致BUG)
(self.superVC?.navigationController as! BaseNavigationController).popBtn.isHidden = true
(self.superVC?.navigationController as! BaseNavigationController).removeGlobalPanGes()
(secondController?.childViewControllers[0] as! GetLicensePlateNumberVC).byeCycleNumber = topView.inputTextField.text!
(secondController?.childViewControllers[0] as! GetLicensePlateNumberVC).startPlay()
self.superVC?.currentViewController = secondController
self.superVC?.view.addSubview((self.superVC?.currentViewController.view)!)
}
else {
self.superVC?.currentViewController = oldController
}
})
}
/// 布局
topView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(navHeight+MGGloabalMargin)
make.left.equalToSuperview().offset(MGGloabalMargin)
make.right.equalToSuperview().offset(-MGGloabalMargin)
// make.height.equalTo(240)
}
bottomView.snp.makeConstraints { (make) in
make.top.equalTo(topView.snp.bottom).offset(MGGloabalMargin)
make.centerX.equalToSuperview()
make.height.equalTo(80)
make.width.equalTo(220)
}
}
}
| 937c7ce90d149e928818b98b5459f437 | 38.89899 | 341 | 0.648101 | false | false | false | false |
Paulo-http/HackaBike | refs/heads/master | HackaBike/HackaBike/Source/Components/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// HackaBike
//
// Created by Paulo Henrique Leite on 16/04/16.
// Copyright © 2016 Paulo Henrique Leite. All rights reserved.
//
import UIKit
import CoreData
@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 "com.paulo.HackaBike" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
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("HackaBike", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns 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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// 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 as NSError
let wrappedError = 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 \(wrappedError), \(wrappedError.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
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| b6c8ad226dea187709962de19e534c67 | 54.045045 | 291 | 0.719967 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/top-k-frequent-elements.swift | mit | 2 | /**
* https://leetcode.com/problems/top-k-frequent-elements/
*
*
*/
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
let map = nums.reduce([Int:Int](), {
var dict = $0
if dict[$1]==nil {
dict[$1] = 1
} else {
dict[$1] = 1 + dict[$1]!
}
return dict
}).reduce([Int:[Int]](), {
dict, item in
var dict_r = dict
if dict_r[item.value]==nil{
dict_r[item.value] = [item.key]
} else {
dict_r[item.value] = dict_r[item.value]! + [item.key]
}
return dict_r
})
var count = k
var maxn = nums.count
var ret = [Int]()
while count>0, maxn>0 {
if let list = map[maxn] {
var i = 0
while i<count, i<list.count {
ret += [list[i]]
i += 1
}
count -= i
}
maxn -= 1
}
return ret
}
}
/**
* https://leetcode.com/problems/top-k-frequent-elements/
*
*
*/
// Date: Fri Jul 17 10:16:22 PDT 2020
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
// 1. count the freq of each num in nums.
var count: [Int: Int] = [:]
for n in nums {
count[n] = 1 + count[n, default: 0]
}
// 2. Turn the dictionary into an Array.
var list: [(Int, Int)] = []
for (key, value) in count {
list.append((key, value))
}
// 3. Sort the array by the freq.
list = list.sorted(by: {
$0.1 > $1.1
})
// 4. Return first k elements with first value in the tuple.
return Array(list[0 ..< k].map { $0.0 })
}
}
/**
* https://leetcode.com/problems/top-k-frequent-elements/
*
*
*/
// Date: Fri Jul 17 10:49:12 PDT 2020
class Solution {
/// Bucket Sort
/// - Complexity:
/// - Time: O(n), n is the number of elements in nums.
/// - Space: O(n), n is the number of elements in nums
///
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var count: [Int: Int] = [:]
for n in nums {
count[n] = 1 + count[n, default: 0]
}
var bucket: [[Int]] = Array(repeating: [], count: nums.count + 1)
for (key, value) in count {
if bucket[value] == nil {
bucket[value] = []
}
bucket[value].append(key)
}
var result: [Int] = []
for index in stride(from: nums.count, through: 0, by: -1) {
if bucket[index] != nil, bucket[index].isEmpty == false {
result += bucket[index]
}
if result.count >= k {
return result
}
}
return result
}
}
| ea3eb18100df1b15e17a7678b44ec9fd | 27.028571 | 73 | 0.432892 | false | false | false | false |
evering7/Speak | refs/heads/master | iSpeaking/SpeakData.swift | mit | 1 | //
// Data.swift
// iSpeaking
//
// Created by JianFei Li on 05/05/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class SpeakData: NSObject {
var sourceFeedList : [SourceFeedMem] = []
var feedSubItemList : [FeedSubItemMem] = []
// var sourceRSSList_totalCount : Int = 0
// var sourceRSSList_downloadedCount : Int = 0
func checkFeedURLAddedBefore_InDisk(feedURL: String) -> Bool {
// check if the URL exist in the db
// if it does, return true
// if it doesn't, return false
// if some error, return true
// 1. get context
guard let app = UIApplication.shared.delegate as? AppDelegate else {
return false
}
let context = app.coreDataStack.persistentContainer.newBackgroundContext()
// 2. declare the request for the data
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
// 3. declare an entity structure
let EntityName = "SourceFeedDisk"
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: context)
fetchRequest.entity = entity
// Todo:done save the url in utf8 encoding, and use utf8 encoding to compare
// jianfei 2017 May 18th
// 4. set the conditional for query
let tempFeedURL : String = feedURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
let predicate = NSPredicate.init(format: "feed_URL = %@ ", tempFeedURL)
fetchRequest.predicate = predicate
// 5. Query operation
do {
let fetchedObjects = try context.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchedObjects.count == 1 {
return true
}else if fetchedObjects.count >= 2 {
printLog(message: "There are more than 2 records for a same feed URL. \(feedURL)")
return true
}else { return false } // no record
}catch {
let nsError = error as NSError
fatalError("Query error \(nsError), \(nsError.userInfo)")
// return true
}
}
func AddlySaveFeed_FromMem_ToDisk(sourceFeed: SourceFeedMem){
// check 1 thing the feed url is unique
let tempFeedURL = sourceFeed.feed_URL
if checkFeedURLAddedBefore_InDisk(feedURL: tempFeedURL){
printLog(message: "Failed to verify the feed URL never added before, in other words, the url exist in the database. \(sourceFeed.feed_URL)")
return
}
// first get db_ID
let db_ID = getMinimumAvailableFeedDBid_InDisk()
if db_ID < 0 {
fatalError("Can't get an effective minimum available db_ID for Feeds")
}
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext = appDelegate.coreDataStack.persistentContainer.newBackgroundContext()
// add two things
// check 1 thing
// the feed url is unique
// get minimum id auto, without need to manually set it
// 2
let entity = NSEntityDescription.entity(forEntityName: "SourceFeedDisk", in: managedContext)
let managedSourceFeed = NSManagedObject(entity: entity!, insertInto: managedContext)
// 3
managedSourceFeed.setValue(sourceFeed.feed_Title, forKey: "feed_Title")
managedSourceFeed.setValue(sourceFeed.feed_Language, forKey: "feed_Language")
// first let feed_URL converted to a utf8 encoding string
let tmpFeedURL : String = sourceFeed.feed_URL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
managedSourceFeed.setValue(tmpFeedURL, forKey: "feed_URL")
managedSourceFeed.setValue(sourceFeed.feed_Author, forKey: "feed_Author")
managedSourceFeed.setValue(sourceFeed.feed_Tags, forKey: "feed_Tags") // important
managedSourceFeed.setValue(sourceFeed.svr_Likes, forKey: "svr_Likes")
managedSourceFeed.setValue(sourceFeed.svr_Dislikes, forKey: "svr_Dislikes")
managedSourceFeed.setValue(sourceFeed.svr_SubscribeCount, forKey: "svr_SubscribeCount")
managedSourceFeed.setValue(db_ID, forKey: "db_ID")
managedSourceFeed.setValue(sourceFeed.db_DownloadedXMLFileName, forKey: "db_DownloadedXMLFileName")
managedSourceFeed.setValue(sourceFeed.feed_UpdateTime, forKey: "feed_UpdateTime")
// managedSourceFeed.setValue(sourceFeed.isLastUpdateSuccess, forKey:"isLastUpdateSuccess")
managedSourceFeed.setValue((sourceFeed.feed_IsDownloadSuccess), forKey: "feed_IsDownloadSuccess")
managedSourceFeed.setValue(sourceFeed.feed_DownloadTime, forKey:"feed_DownloadTime")
// could this line be executed correctly? need checking!
managedSourceFeed.setValue((sourceFeed.feed_IsRSSorAtom), forKey: "feed_IsRSSorAtom")
// total 14, db 2, feed 9, server 3
// 4
do {
try managedContext.save()
}catch let error as NSError {
printLog(message: "Could not save. \(error), \(error.userInfo)")
}
}
func getMinimumAvailableFeedDBid_InDisk() -> Int64 {
// 1. get context
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return -1
}
// 1-2.
let managedContext = appDelegate.coreDataStack.persistentContainer.newBackgroundContext()
// 2. declare the request for data
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
// fetchRequest.fetchLimit = 10
let highestSortDescriptor = NSSortDescriptor(key: "db_ID",ascending: false)
fetchRequest.sortDescriptors = [highestSortDescriptor]
// 3. declare an entity
let EntityName = "SourceFeedDisk"
let entity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: managedContext)
fetchRequest.entity = entity
// 4. setup query condition
let predicate = NSPredicate.init(format: " %K >= %@ ", "db_ID", "0")
fetchRequest.predicate = predicate
// 5. do query operation
do {
let fetchedObjects = try managedContext.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchedObjects.count == 0 {
return 0 // no field exist before
} else {
return (fetchedObjects[0].db_ID + 1)
}
}catch {
let nsError = error as NSError
fatalError("query error: \(nsError), \(nsError.userInfo)")
}
}
func getFeedSubItem_FromDisk_PendingToMemory() -> [FeedSubItemDisk]{
// get the feed sub item to memory
// 1. get a new context
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "can not get an appDelegate object")
return []
}
let context = app.coreDataStack.privateUserContext
// 2. get fetch request
let fetchRequest = NSFetchRequest<FeedSubItemDisk>(entityName: "FeedSubItemDisk")
// 3. do the fetch
var localFeedSubItemList : [FeedSubItemDisk] = []
do {
localFeedSubItemList = try context.fetch(fetchRequest)
return localFeedSubItemList
}catch {
printLog(message: "Could not fetch. \(error.localizedDescription)")
return []
}
}
// todo: delete ? for better running
func getSourceFeed_FromDisk_PendingToMemory() -> [SourceFeedDisk] {
// 1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return []
}
let managedContext = appDelegate.coreDataStack.privateUserContext
// 2
let fetchRequest = NSFetchRequest<SourceFeedDisk>(entityName: "SourceFeedDisk")
var localFeedList: [SourceFeedDisk] = []
// 3
do {
localFeedList = try managedContext.fetch(fetchRequest)
return localFeedList
}catch let error as NSError {
printLog(message: "Could not fetch. \(error), \(error.userInfo)")
return []
}
}
func getSourceRSSCount() -> Int? {
// 1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return nil
}
let managedContext = appDelegate.coreDataStack.privateUserContext
let fetchRequest: NSFetchRequest<SourceFeedDisk> = SourceFeedDisk.fetchRequest()
do {
// go get the results
let searchResults = try managedContext.fetch(fetchRequest)
// Todo, more simplified solution to search for
// I like to check the size of the returned results
printLog(message: "num of results = \(searchResults.count)")
return searchResults.count
// You need to convert to NSManagedObject to use for loops
// for source in searchResults as [NSManagedObject] {
// // get the Key Value pairs
// print("\(String(describing: source.value(forKey: "author")))")
// }
}catch {
print("Error with request : \(error)")
return nil
}
}
func insertSomeDefaultSourceFeed(){
// Add code to save coredata
let sourceFeedObject : SourceFeedMem = SourceFeedMem()
// sourceFeedObject.initialize()
// sourceFeedObject.db_ID = 1
sourceFeedObject.feed_URL = "http://blog.sina.com.cn/rss/1462466974.xml"
// test if could check the exist record
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// 20170520. Test ok of the addly save feed
// self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
//sourceFeedObject.db_ID = 2
sourceFeedObject.feed_URL = "https://lijinghe.com/feed/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 3
sourceFeedObject.feed_URL = "http://www.767stock.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 4
sourceFeedObject.feed_URL = "http://www.huxiu.com/rss/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 5
sourceFeedObject.feed_URL = "http://blog.caixin.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 6
sourceFeedObject.feed_URL = "http://next.36kr.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 7
sourceFeedObject.feed_URL = "http://www.goingconcern.cn/feed.xml"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 8
sourceFeedObject.feed_URL = "http://feeds.appinn.com/appinns/"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 9
sourceFeedObject.feed_URL = "http://sspai.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 10
sourceFeedObject.feed_URL = "http://zhan.renren.com/zhihujx/rss"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
// sourceFeedObject.db_ID = 11
sourceFeedObject.feed_URL = "http://www.ifanr.com/feed"
self.AddlySaveFeed_FromMem_ToDisk(sourceFeed: sourceFeedObject)
//Todo: add more from a text file, so the usability improved
// Finally, should get the content again.
}
func loadFeedList_FromDisk_ToMemory(diskList: [SourceFeedDisk], memList: inout [SourceFeedMem]){
if diskList.count == 0 {
printLog(message: "No need to copy, disklist is 0-length")
return
}
for sourceFeed: SourceFeedDisk in diskList {
let memSourceFeed = sourceFeed.loadSourceFeed_FromDisk_ToMemory()
memList.append(memSourceFeed)
}
}
func loadFeedSubItemList_FromDisk_ToMemory(diskList: [FeedSubItemDisk], memList: inout [FeedSubItemMem]){
// load
// load feed sub item list one by one from disk db to memory
// check count of disk list
if diskList.count == 0 {
printLog(message: "No need to copy, feed sub item disklist is 0-length")
return
}
// iteration through the disk list to get full new list
for feedSubItem: FeedSubItemDisk in diskList {
let memFeedSubItem = feedSubItem.loadFeedSubItemClass_FromDisk_ToMemory()
memList.append(memFeedSubItem)
}
}
func UpdatelySaveFeedMemData_ToDisk(sourceFeedClass: SourceFeedMem) -> Bool
{
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return false // failure
}
// let managedContext =
let managedContext = app.coreDataStack.privateUserContext
// let fetchRequest = NSFetchRequest<SourceFeed>(entityName: "SourceFeed")
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
// fetchRequest.fetchOffset = 0
let EntityName = "SourceFeedDisk"
let entity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: managedContext)
fetchRequest.entity = entity
let predicate = NSPredicate(format: "db_ID = %lld", sourceFeedClass.db_ID)
fetchRequest.predicate = predicate
do {
let fetchResults = try managedContext.fetch(fetchRequest) as! [SourceFeedDisk]
if fetchResults.count == 1 {
// Here, Modify the data
// let sourceFeed: SourceFeed = fetchResults[0]
// todo: add feed_SubItemCount = 10 in the future
fetchResults[0].db_DownloadedXMLFileName = sourceFeedClass.db_DownloadedXMLFileName
// sourceFeed.db_ID
fetchResults[0].feed_Author = sourceFeedClass.feed_Author
fetchResults[0].feed_DownloadTime = sourceFeedClass.feed_DownloadTime as NSDate
fetchResults[0].feed_IsDownloadSuccessBool = sourceFeedClass.feed_IsDownloadSuccess
fetchResults[0].feed_IsRSSorAtomBool = sourceFeedClass.feed_IsRSSorAtom
fetchResults[0].feed_Language = sourceFeedClass.feed_Language
fetchResults[0].feed_Tags = sourceFeedClass.feed_Tags
fetchResults[0].feed_Title = sourceFeedClass.feed_Title
fetchResults[0].feed_UpdateTime = sourceFeedClass.feed_UpdateTime as NSDate
fetchResults[0].feed_URL = sourceFeedClass.feed_URL
fetchResults[0].svr_Likes = sourceFeedClass.svr_Likes
fetchResults[0].svr_Dislikes = sourceFeedClass.svr_Dislikes
fetchResults[0].svr_SubscribeCount = sourceFeedClass.svr_SubscribeCount
app.coreDataStack.saveContext()
printLog(message: "return as success truely")
return true // success
}else {
printLog(message: "return because fields count not equal 1")
return false // failure
}
// }else {
// printLog(message: "unwrap the fetchResults failure")
// return false
// }
}catch {
printLog(message: "\(error.localizedDescription)")
return false
}
// let entity = NSEntityDescription.entity(forEntityName: "SourceFeed", in: managedContext)
//
// let managedSourceFeed = NSManagedObject(entity: entity!, insertInto: managedContext)
}
// todo: From here 2017.5.10. still working on name modification
func UpdateOrAdd_SaveFeedSubItemData_ToDisk(sourceFeedClass: SourceFeedMem) -> Bool {
// Steps: It should be circle
// 1. Do a query, check if exist a title-same article / subitem or not
// 2. if exist, update the feed sub item
// 3. if not exist, add the feed sub item
// 4. if success, return true
// frame 1. a check for rss or atom
// frame 2. loop
// Step 1. Do a query, to check if exist a title-same article.
if sourceFeedClass.feed_IsRSSorAtom == true {
// rss feed
// do a loop
if let items = sourceFeedClass.mem_rssFeed.items{
for item: RSSFeedItem in items {
let db_SubItemID = getCurrentlyExistIDForItem_InMem(subItem: item) // query mem data
if db_SubItemID < 0 {
// indicating no sub item id
Addly_SaveFeedSubItemData_ToDisk(rssFeedItem: item, sourceFeedClass: sourceFeedClass)
} else {
// indicating existing the sub item id
// todo here
Update_SaveFeedSubItemData_ToDisk(rssFeedItem: item, sourceFeedClass: sourceFeedClass)
}
}
}
}else{
// atom
}
return false
}
func getCurrentlyExistIDForItem_InMem(subItem: RSSFeedItem) -> Int64 {
// For use of RSSFeed
// get the existing id from
// search the maximum id
if self.feedSubItemList.count == 0 {
return -1 // no exist the id
}
// search for the exist id
for feedSubItem : FeedSubItemMem in self.feedSubItemList {
// search the Article URL
if let subLink = subItem.link {
if feedSubItem.item_ArticleURL == subLink {
return feedSubItem.db_SubItemID
}
}
}
return -2 // search but no exist
}
func getCurrentlyExistIDForItem_InDisk(subItem: RSSFeedItem ) -> Int64 {
// return -1 means unsuccessful to get an existing FeedItem
// do a query by title and link
// step 1. get the data context
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return -1 // failure
}
let context = app.coreDataStack.privateUserContext
// step 2. declare the data search request
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.fetchLimit = 2
fetchRequest.fetchOffset = 0
// step 3. declare an entity
let EntityName = "FeedSubItemDisk"
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: context)
fetchRequest.entity = entity
// step 4. setup conditional form for search
let predicate = NSPredicate.init(format: "item_ArticleURL = %@ ", subItem.link!)
fetchRequest.predicate = predicate
// step 5. query operation
do {
let fetchedObjects = try context.fetch(fetchRequest) as! [FeedSubItemDisk]
// iterate the query results
if fetchedObjects.count == 1 {
// Only one is the correct state
return fetchedObjects[0].db_SubItemID
}else if fetchedObjects.count >= 2 {
printLog(message: "Unexpected: the query results count exceed 1. \(fetchedObjects.count)")
return fetchedObjects[0].db_SubItemID
}else {
// return -1 indicate no records are found
return -1
}
}catch {
fatalError("Query Error: \(error.localizedDescription)")
// return -2 // means error indeed
}
}
func Update_SaveFeedSubItemData_ToDisk(rssFeedItem: RSSFeedItem, sourceFeedClass: SourceFeedMem) -> Bool{
return true
}
func Addly_SaveFeedSubItemData_ToDisk(rssFeedItem: RSSFeedItem, sourceFeedClass: SourceFeedMem) -> Bool{
// function: add a feeditem to feeditem disk database
// step 1. get the data context
// TODO: simplify these two lines as a func
guard let app = UIApplication.shared.delegate as? AppDelegate else {
printLog(message: "Return failure because cannot get appDelegate")
return false // failure
}
let context = app.coreDataStack.privateUserContext
// step 2. create a FeedSubItem object
let EntityName = "FeedSubItemDisk"
let oneItem = NSEntityDescription.insertNewObject(forEntityName: EntityName, into: context) as! FeedSubItemDisk
// step 3. assign value to the object
// TODO: add a real file name
oneItem.db_DownloadedHtmlFileName = ""
oneItem.db_SubItemID = getAvailableMinimumSubItemID() // TODO: Add this function
return false
}
func getAvailableMinimumSubItemID() -> Int64 {
// Todo
return 1
}
func parseFeedXmlAndUpdateMemData(sourceFeedClass: SourceFeedMem){
// let singleSourceRSS = speakData.sourceRSSList[0]
let fileURL = getRSSxmlFileURLfromLastComponent(lastPathCompo:
sourceFeedClass.db_DownloadedXMLFileName)
let feedParser = FeedParser(URL: fileURL)
let result = feedParser?.parse()
if let newResult = result {
switch newResult {
case Result.rss (let rssFeed):
printLog(message: "url: \(sourceFeedClass.feed_URL)")
printLog(message: "link \(String(describing: rssFeed.link))")
// Start to convert things in rssfeed
sourceFeedClass.feed_Title = rssFeed.title ?? "no title"
sourceFeedClass.feed_Language = rssFeed.language ?? "no specified lang"
// url blank
sourceFeedClass.feed_Author = rssFeed.managingEditor ?? "no editor/author"
sourceFeedClass.feed_Tags = String(describing: rssFeed.categories)
// skip: likes, dislikes, subscribeCount, id, downloadedXMLFileName,
let upDate: Date
if rssFeed.pubDate != nil {
upDate = (rssFeed.pubDate)!
}else{
upDate = getDefaultTime()
}
sourceFeedClass.feed_UpdateTime = upDate
sourceFeedClass.feed_IsRSSorAtom = true
sourceFeedClass.mem_rssFeed = rssFeed
// sourceFeedClass.isLastUpdateSuccess = true
// skip: isDownloadSuccess, lastDownloadTime
// Here: should convert items into RSSArticleItem
if let rssFeedItems = rssFeed.items {
let isSuccess = self.addFeedSubItems_FromNetFeed_ToMemoryList(rssFeedItems: rssFeedItems)
if !isSuccess {
printLog(message: "fail to add RSS Feed Item to MemList")
}
}
case Result.atom (let atomFeed):
printLog(message: "url: \(sourceFeedClass.feed_URL)")
printLog(message: "link: \(String(describing: atomFeed.links))")
sourceFeedClass.feed_Title = atomFeed.title ?? "no title"
sourceFeedClass.feed_Language = "unkown language"
sourceFeedClass.feed_Author = String(describing: atomFeed.authors)
sourceFeedClass.feed_Tags = String(describing: atomFeed.categories)
sourceFeedClass.feed_UpdateTime = (atomFeed.updated) ?? getDefaultTime()
sourceFeedClass.feed_IsRSSorAtom = false
sourceFeedClass.mem_atomFeed = atomFeed
// sourceFeedClass.isLastUpdateSuccess = true
if let atomFeedItems = atomFeed.entries {
let isSuccess = self.addFeedSubItems_FromNetFeed_ToMemoryList(atomFeedItems: atomFeedItems)
if !isSuccess {
printLog(message: "fail to add atom feed to MemList")
}
}
// atomFeed.links?[0].attributes?.title
case Result.failure(let error):
printLog(message: error)
}
}else { // result is nil
printLog(message: "error in parsing the result: the result is nil")
}
}
func addFeedSubItems_FromNetFeed_ToMemoryList(rssFeedItems: [RSSFeedItem]) -> Bool{
// from rssFeedItmes to articleOfRSSList
for singleRSSFeedItem: RSSFeedItem in rssFeedItems {
let feedSubItemClass = singleRSSFeedItem.loadFeedSubItem_FromNetFeed_ToMemory()
self.feedSubItemList.append(feedSubItemClass)
}
return true
}
func addFeedSubItems_FromNetFeed_ToMemoryList(atomFeedItems: [AtomFeedEntry]) -> Bool {
for singleAtomFeedItem: AtomFeedEntry in atomFeedItems{
let feedSubItemClass = singleAtomFeedItem.loadFeedSubItem_FromNetFeed_ToMemory()
self.feedSubItemList.append(feedSubItemClass)
}
return true
}
class func getAvailabeMinimumIDofFeedSubItem_InMem() -> Int64 {
// todo: may be here need to add disk id
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var maxID: Int64 = 0
for singleArticleItem in appDelegate.speakData.feedSubItemList {
if maxID < (singleArticleItem.db_SubItemID) {
maxID = (singleArticleItem.db_SubItemID)
}
}
return (maxID + 1) // minimum available id
}
class func getAvailableMinimumSubItemID() -> Int64 {
// ToDo: Add this function
return 1
}
}
| f5be837f5c5c2d06de39b0b2eb70dae0 | 36.644684 | 152 | 0.582159 | false | false | false | false |
vnu/vTweetz | refs/heads/master | Pods/SwiftDate/SwiftDate/Dictionary+SwiftDate.swift | apache-2.0 | 2 | //
// SwiftDate, an handy tool to manage date and timezones in swift
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Generate a Date from a Dictionary of NSCalendarUnit:Value
public typealias DateComponentDictionary = [ NSCalendarUnit: AnyObject ]
//MARK: - Extension: NSCalendarUnit -
protocol CalendarAsDictionaryKey: Hashable {}
extension NSCalendarUnit: CalendarAsDictionaryKey {
public var hashValue: Int {
get {
return Int(self.rawValue)
}
}
}
extension Dictionary where Value: AnyObject, Key: CalendarAsDictionaryKey {
func components() -> NSDateComponents {
let components = NSDateComponents()
for (key, value) in self {
if let value = value as? Int {
components.setValue(value, forComponent: key as! NSCalendarUnit)
} else if let value = value as? NSCalendar {
components.calendar = value
} else if let value = value as? NSTimeZone {
components.timeZone = value
}
}
return components
}
/**
Convert a dictionary of <NSCalendarUnit,Value> in a DateInRegion. Both timeZone and calendar must be specified into the dictionary. You can also specify a locale; if nil UTCRegion()'s locale will be used instead.
- parameter locale: optional locale (Region().locale if nil)
- returns: DateInRegion if date components are complete, nil if cannot be used to generate a valid date
*/
func dateInRegion() -> DateInRegion? {
return DateInRegion(self.components())
}
func dateRegion() -> Region? {
let components = self.components()
let calendar = components.calendar ?? NSCalendar.currentCalendar()
let timeZone = components.timeZone ?? NSTimeZone.defaultTimeZone()
let locale = calendar.locale ?? NSLocale.currentLocale()
return Region(calendar: calendar, timeZone: timeZone, locale: locale)
}
/**
Convert a dictionary of <NSCalendarUnit,Value> in absolute time NSDate instance. Both timeZone and calendar must be specified into the dictionary. You can also specify a locale; if nil UTCRegion()'s locale will be used instead.
- returns: absolute time NSDate object, nil if dictionary values cannot be used to generate a valid date
*/
func absoluteTime() -> NSDate? {
let date = self.dateInRegion()
return date?.absoluteTime
}
}
| ef6dfc09caf57df15e102ec9c40bf1de | 38.413043 | 232 | 0.691395 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | refs/heads/main | WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/ValidateBST/ValidateBSTFactory.swift | mit | 1 | //
// ValidateBSTFactory.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 02/07/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class ValidateBSTFactory: NSObject {
// MARK: Build
class func buildBinaryTree(relationships: [[Int]]) -> ValidateBSTNode {
var nodes = [Int: ValidateBSTNode]()
for relationship in relationships {
let parentNodeValue = relationship[0]
let childNodeValue = relationship[1]
var parentNode = nodes[parentNodeValue]
var childNode = nodes[childNodeValue]
if parentNode == nil {
parentNode = ValidateBSTNode(value: parentNodeValue)
nodes[parentNodeValue] = parentNode
}
if childNode == nil {
childNode = ValidateBSTNode(value: childNodeValue)
nodes[childNodeValue] = childNode
}
parentNode!.addNodeAsChild(node: childNode!)
}
return rootNode(nodes: nodes)
}
class func rootNode(nodes: [Int: ValidateBSTNode]) -> ValidateBSTNode {
var rootNode: ValidateBSTNode?
for node in nodes.values {
if node.parent == nil {
rootNode = node
break
}
}
return rootNode!
}
}
| e6f6fbfda2bd49bdcb9554000ca0eb3e | 25.851852 | 75 | 0.541379 | false | false | false | false |
strike65/SwiftyStats | refs/heads/master | SwiftyStats/CommonSource/ProbDist/ProbDist-Gamma.swift | gpl-3.0 | 1 | //
// Created by VT on 20.07.18.
// Copyright © 2018 strike65. All rights reserved.
/*
Copyright (2017-2019) strike65
GNU GPL 3+
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, version 3 of the License.
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 Foundation
#if os(macOS) || os(iOS)
import os.log
#endif
extension SSProbDist {
/// Gamma distribution
public enum Gamma {
/// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Gamma distribution.
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0
public static func para<FPT: SSFloatingPoint & Codable>(shape a: FPT, scale b: FPT) throws -> SSProbDistParams<FPT> {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>()
result.mean = a * b
result.variance = a * b * b
result.kurtosis = 3 + 6 / a
result.skewness = 2 / sqrt(a)
return result
}
/// Returns the pdf of the Gamma distribution.
/// - Parameter x: x
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0
public static func pdf<FPT: SSFloatingPoint & Codable>(x: FPT, shape a: FPT, scale b: FPT) throws -> FPT {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
var ex1: FPT
var ex2: FPT
if x <= 0 {
return 0
}
else {
let a1: FPT = -a * SSMath.log1(b)
let a2: FPT = -x / b
let a3: FPT = -1 + a
ex1 = a1 + a2
ex2 = ex1 + a3 * SSMath.log1(x)
let a4: FPT = ex2 - SSMath.lgamma1(a)
let result = SSMath.exp1(a4)
return result
}
}
/// Returns the cdf of the Gamma distribution.
/// - Parameter x: x
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0
public static func cdf<FPT: SSFloatingPoint & Codable>(x: FPT, shape a: FPT, scale b: FPT) throws -> FPT {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if x < 0 {
return 0
}
var cv: Bool = false
let result = SSSpecialFunctions.gammaNormalizedP(x: x / b, a: a, converged: &cv)
if cv {
return result
}
else {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("unable to retrieve a result", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .maxNumberOfIterationReached, file: #file, line: #line, function: #function)
}
}
/// Returns the quantile of the Gamma distribution.
/// - Parameter p: p
/// - Parameter a: Shape parameter
/// - Parameter b: Scale parameter
/// - Throws: SSSwiftyStatsError if a <= 0 || b <= 0 || p < 0 || p > 1
public static func quantile<FPT: SSFloatingPoint & Codable>(p: FPT, shape a: FPT, scale b: FPT) throws -> FPT {
if (a <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if (b <= 0) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("scale parameter a is expected to be > 0", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if p < 0 || p > 1 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("p is expected to be >= 0 and <= 1 ", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if p == 0 {
return 0
}
if p == 1 {
return FPT.infinity
}
var gVal: FPT = 0
var maxG: FPT = 0
var minG: FPT = 0
maxG = a * b + 4000
minG = 0
gVal = a * b
var test: FPT
var i = 1
while((maxG - minG) > Helpers.makeFP(1.0E-14)) {
test = try! cdf(x: gVal, shape: a, scale: b)
if test > p {
maxG = gVal
}
else {
minG = gVal
}
gVal = (maxG + minG) * Helpers.makeFP(0.5 )
i = i + 1
if i >= 7500 {
break
}
}
if((a * b) > 10000) {
let t1: FPT = gVal * Helpers.makeFP(1E07)
let ri: FPT = floor(t1)
let rd: FPT = ri / Helpers.makeFP(1E07)
return rd
}
else {
return gVal
}
}
}
}
| 513cb359ec67151430f5ade5b941d894 | 36.710744 | 135 | 0.458799 | false | false | false | false |
charlesmwang/Yukina | refs/heads/master | Yukina/YKHelper_Internal.swift | mit | 1 | import Foundation
func mergeDictionary<K,V>(dict1: [K:V], dict2: [K:V]) -> [K:V] {
var dict:[K:V] = dict1
for (key, value) in dict2 {
dict.updateValue(value, forKey: key)
}
return dict
}
func extractQueryItems(queryItems:[AnyObject]?) -> [String:String]{
let dictQueryItems:[[String:String]]? = queryItems?.map({ (queryItem) -> [String:String] in
if let queryItem = queryItem as? NSURLQueryItem, let value = queryItem.value {
return [queryItem.name: value]
}
else {
return [:]
}
})
if let dictQueryItems = dictQueryItems {
let dictQueryItem:[String:String] = dictQueryItems.reduce([:], combine: { (queryItem1, queryItem2) -> [String:String] in
return mergeDictionary(queryItem1, queryItem2)
})
return dictQueryItem
}
return [String:String]()
}
| 8089708f94ed163873045848667f67ee | 27.967742 | 128 | 0.596882 | false | false | false | false |
simplyzhao/ForecastIO | refs/heads/master | ForecastIO/AlertObject.swift | mit | 1 | //
// AlertObject.swift
// Weather
//
// Created by Alex Zhao on 11/25/15.
// Copyright © 2015 Alex Zhao. All rights reserved.
//
import Foundation
public struct AlertObject {
public let title: String?
public let expires: NSTimeInterval?
public let description: String?
public let uri: NSURL?
init(data: [String: AnyObject]) {
self.title = data["title"] as? String
self.expires = data["expires"] as? NSTimeInterval
self.description = data["description"] as? String
if let uriString = data["uri"] as? String {
self.uri = NSURL(string: uriString)
} else {
self.uri = nil
}
}
} | c577f8ebcdf733ef786741ae4c663246 | 23.678571 | 57 | 0.598551 | false | false | false | false |
daniel-barros/TV-Calendar | refs/heads/master | TraktKit/Common/TraktWatchedShow.swift | gpl-3.0 | 1 | //
// TraktWatchedShow.swift
// TraktKit
//
// Created by Maximilian Litteral on 4/13/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct TraktWatchedShow: TraktProtocol {
// Extended: Min
public let plays: Int // Total number of plays
public let lastWatchedAt: Date
public let show: TraktShow
public let seasons: [TraktWatchedSeason]
// Initialize
public init?(json: RawJSON?) {
guard
let json = json,
let plays = json["plays"] as? Int,
let lastWatchedAt = Date.dateFromString(json["last_watched_at"]),
let show = TraktShow(json: json["show"] as? RawJSON) else { return nil }
self.plays = plays
self.lastWatchedAt = lastWatchedAt
self.show = show
var tempSeasons: [TraktWatchedSeason] = []
let jsonSeasons = json["seasons"] as? [RawJSON] ?? []
for jsonSeason in jsonSeasons {
guard
let season = TraktWatchedSeason(json: jsonSeason) else { continue }
tempSeasons.append(season)
}
seasons = tempSeasons
}
}
| 20e56fd51839bb0e285968a6c7483acf | 29.666667 | 84 | 0.596154 | false | false | false | false |
omise/omise-ios | refs/heads/master | OmiseSDK/TrueMoneyFormViewController.swift | mit | 1 | import UIKit
@objc(OMSTrueMoneyFormViewController)
class TrueMoneyFormViewController: UIViewController, PaymentSourceChooser, PaymentChooserUI, PaymentFormUIController {
var flowSession: PaymentCreatorFlowSession?
private var client: Client?
private var isInputDataValid: Bool {
return formFields.reduce(into: true) { (valid, field) in
valid = valid && field.isValid
}
}
@IBInspectable var preferredPrimaryColor: UIColor? {
didSet {
applyPrimaryColor()
}
}
@IBInspectable var preferredSecondaryColor: UIColor? {
didSet {
applySecondaryColor()
}
}
var currentEditingTextField: OmiseTextField?
@IBOutlet var contentView: UIScrollView!
@IBOutlet private var phoneNumberTextField: OmiseTextField!
@IBOutlet private var submitButton: MainActionButton!
@IBOutlet private var requestingIndicatorView: UIActivityIndicatorView!
@IBOutlet private var errorLabel: UILabel!
@IBOutlet var formLabels: [UILabel]!
@IBOutlet var formFields: [OmiseTextField]!
@IBOutlet var formFieldsAccessoryView: UIToolbar!
@IBOutlet var gotoPreviousFieldBarButtonItem: UIBarButtonItem!
@IBOutlet var gotoNextFieldBarButtonItem: UIBarButtonItem!
@IBOutlet var doneEditingBarButtonItem: UIBarButtonItem!
// need to refactor loadView, removing super results in crash
// swiftlint:disable prohibited_super_call
override func loadView() {
super.loadView()
view.backgroundColor = .background
formFieldsAccessoryView.barTintColor = .formAccessoryBarTintColor
submitButton.defaultBackgroundColor = .omise
submitButton.disabledBackgroundColor = .line
}
override func viewDidLoad() {
super.viewDidLoad()
applyPrimaryColor()
applySecondaryColor()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
formFields.forEach {
$0.inputAccessoryView = formFieldsAccessoryView
}
formFields.forEach {
$0.adjustsFontForContentSizeCategory = true
}
formLabels.forEach {
$0.adjustsFontForContentSizeCategory = true
}
submitButton.titleLabel?.adjustsFontForContentSizeCategory = true
if #available(iOS 11, *) {
// We'll leave the adjusting scroll view insets job for iOS 11 and later to the layoutMargins + safeAreaInsets here
} else {
automaticallyAdjustsScrollViewInsets = true
}
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillChangeFrame(_:)),
name: NotificationKeyboardWillChangeFrameNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide(_:)),
name: NotificationKeyboardWillHideFrameNotification,
object: nil
)
phoneNumberTextField.validator = try? NSRegularExpression(pattern: "\\d{10,11}\\s?", options: [])
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if #available(iOS 11, *) {
// There's a bug in iOS 10 and earlier which the text field's intrinsicContentSize is returned the value
// that doesn't take the result of textRect(forBounds:) method into an account for the initial value
// So we need to invalidate the intrinsic content size here to ask those text fields to calculate their
// intrinsic content size again
} else {
formFields.forEach {
$0.invalidateIntrinsicContentSize()
}
}
}
@IBAction private func submitForm(_ sender: AnyObject) {
guard let phoneNumber = phoneNumberTextField.text?.trimmingCharacters(in: CharacterSet.whitespaces) else {
return
}
let trueMoneyInformation = PaymentInformation.TrueMoney(phoneNumber: phoneNumber)
requestingIndicatorView.startAnimating()
view.isUserInteractionEnabled = false
view.tintAdjustmentMode = .dimmed
submitButton.isEnabled = false
flowSession?.requestCreateSource(.truemoney(trueMoneyInformation)) { _ in
self.requestingIndicatorView.stopAnimating()
self.view.isUserInteractionEnabled = true
self.view.tintAdjustmentMode = .automatic
self.submitButton.isEnabled = true
}
}
@IBAction private func validateFieldData(_ textField: OmiseTextField) {
submitButton.isEnabled = isInputDataValid
}
@IBAction private func validateTextFieldDataOf(_ sender: OmiseTextField) {
let duration = TimeInterval(NavigationControllerHideShowBarDuration)
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .layoutSubviews]) {
self.validateField(sender)
}
sender.borderColor = currentSecondaryColor
}
@IBAction private func updateInputAccessoryViewFor(_ sender: OmiseTextField) {
let duration = TimeInterval(NavigationControllerHideShowBarDuration)
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .layoutSubviews]) {
self.errorLabel.alpha = 0.0
}
updateInputAccessoryViewWithFirstResponder(sender)
sender.borderColor = view.tintColor
}
@IBAction private func doneEditing(_ button: UIBarButtonItem?) {
doneEditing()
}
private func validateField(_ textField: OmiseTextField) {
do {
try textField.validate()
errorLabel.alpha = 0.0
} catch {
switch error {
case OmiseTextFieldValidationError.emptyText:
errorLabel.text = "-" // We need to set the error label some string in order to have it retains its height
case OmiseTextFieldValidationError.invalidData:
errorLabel.text = NSLocalizedString(
"truemoney-form.phone-number-field.invalid-data.error.text",
tableName: "Error",
bundle: .module,
value: "Phone number is invalid",
comment: "An error text in the TrueMoney form displayed when the phone number is invalid"
)
default:
errorLabel.text = error.localizedDescription
}
errorLabel.alpha = errorLabel.text != "-" ? 1.0 : 0.0
}
}
@objc func keyboardWillChangeFrame(_ notification: NSNotification) {
guard let frameEnd = notification.userInfo?[NotificationKeyboardFrameEndUserInfoKey] as? CGRect,
let frameStart = notification.userInfo?[NotificationKeyboardFrameBeginUserInfoKey] as? CGRect,
frameEnd != frameStart else {
return
}
let intersectedFrame = contentView.convert(frameEnd, from: nil)
contentView.contentInset.bottom = intersectedFrame.height
let bottomScrollIndicatorInset: CGFloat
if #available(iOS 11.0, *) {
bottomScrollIndicatorInset = intersectedFrame.height - contentView.safeAreaInsets.bottom
} else {
bottomScrollIndicatorInset = intersectedFrame.height
}
contentView.scrollIndicatorInsets.bottom = bottomScrollIndicatorInset
}
@objc func keyboardWillHide(_ notification: NSNotification) {
contentView.contentInset.bottom = 0.0
contentView.scrollIndicatorInsets.bottom = 0.0
}
}
| 9fba63485272d4f7fd57b38eb20c292f | 37.199052 | 127 | 0.638586 | false | false | false | false |
Authman2/Pix | refs/heads/master | Eureka-master/Source/Core/Cell.swift | apache-2.0 | 5 | // Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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
/// Base class for the Eureka cells
open class BaseCell : UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Block that returns the height for this cell.
public var height: (()->CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder : AnyObject? = self
while responder != nil {
if responder! is FormViewController {
return responder as? FormViewController
}
responder = responder?.next
}
return nil
}
open func setup(){}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T: Equatable> : BaseCell, TypedCellType {
public typealias Value = T
/// The row associated to this cell
public weak var row : RowOf<T>!
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row){
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { UITableViewAutomaticDimension }
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup(){
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update(){
super.update()
textLabel?.text = row.title
textLabel?.textColor = row.isDisabled ? .gray : .black
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
get { return false }
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
/// The untyped row associated to this cell.
public override var baseRow : BaseRow! { return row }
}
| 29a3528830e32c16409dc14f8df8bf06 | 30.248408 | 126 | 0.665104 | false | false | false | false |
ddgold/Cathedral | refs/heads/master | Cathedral/Controllers/GameViewController.swift | apache-2.0 | 1 | //
// GameViewController.swift
// Cathedral
//
// Created by Doug Goldstein on 1/29/19.
// Copyright © 2019 Doug Goldstein. All rights reserved.
//
import UIKit
import AVFoundation
/// A cathedral game controller.
class GameViewController: UIViewController
{
//MARK: - Properties
/// The game model
var game: Game!
/// The static sub views of the game.
private var boardView: BoardView!
private var topPoolView: PoolView!
private var bottomPoolView: PoolView!
private var messageLabel: UILabel!
private var buildButton: UIButton!
/// The light player.
private var lightPlayer: Player!
/// The dark player.
private var darkPlayer: Player!
/// The active piece.
private var activePiece: PieceView?
/// The actice pool.
private var activePool: PoolView?
/// The point of a pan gesture's start.
private var panStart: CGPoint?
/// The offset of a pan gesture into the active piece.
private var panOffset: CGPoint?
/// The rotation of the active piece before the rotation gesture.
private var rotateStart: CGFloat?
/// The piece that the long press gestures is touching.
private var pressedPiece: PieceView?
/// The point of a long press gesture's start.
private var pressStart: CGPoint?
/// The offset of a long press gesture into the pressed piece.
private var pressOffset: CGPoint?
/// The player assigned to the top pool.
private let topPoolPlayer = Owner.dark
/// The completion handler that return the game to calling controller when this controller disappears.
var completionHandler: ((Game?, Bool) -> Void)?
/// The calculate size of a tile based on controller's safe space.
var tileSize: CGFloat
{
let totalSafeHeight = view.frame.height - 180
let maxHeightSize = (totalSafeHeight - 40) / 18
let totalSafeWidth = view.frame.width
let maxWidthSize = totalSafeWidth / 12
return min(maxHeightSize, maxWidthSize)
}
//MARK: - ViewController Lifecycle
/// Initialze the controller's sub views once the controller has loaded.
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.title = "Cathedral"
// Initialize subviews
boardView = buildBoard()
topPoolView = buildPool(top: true)
bottomPoolView = buildPool(top: false)
messageLabel = buildMessageLabel()
buildButton = buildBuildButton()
// Initialize player
lightPlayer = game.playerType(for: .light).init(game: game, owner: .light)
darkPlayer = game.playerType(for: .dark).init(game: game, owner: .dark)
// Bring board view to front and set background color
self.view.bringSubviewToFront(boardView)
self.view.backgroundColor = .white
// Listen for theme changes
Theme.subscribe(self, selector: #selector(updateTheme(_:)))
updateTheme(nil)
// Start / resume Game
nextTurn()
}
/// This game controller is disappearing, return the game via the completion handler.
///
/// - Parameter animated: Whether or not the disappearing is animated.
override func viewDidDisappear(_ animated: Bool)
{
completionHandler?(game, false)
}
//MARK: - Button and Gesture Recognizer Actions
/// Handle a pan gesture accross the game board view.
///
/// - Parameter sender: The pan gesture recognizer.
@objc func handleBoardPanGesture(_ sender: UIPanGestureRecognizer)
{
if let activePiece = self.activePiece
{
switch sender.state
{
// Began dragging piece
case .began:
if activePiece.contains(point: sender.location(in: activePiece))
{
let touchLocation = sender.location(in: boardView)
panStart = activePiece.frame.origin
panOffset = CGPoint(x: touchLocation.x - panStart!.x, y: touchLocation.y - panStart!.y)
pickupActivePiece()
}
// Dragged piece
case .changed:
if let panOffset = self.panOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - panOffset.x, y: boardTouchLocation.y - panOffset.y)
activePiece.move(to: offsetLocation)
}
// Stopped dragging piece
case .ended:
if let panOffset = self.panOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - panOffset.x, y: boardTouchLocation.y - panOffset.y)
if let activePool = self.activePool
{
if (activePool == topPoolView) && (boardTouchLocation.y < 0) ||
(activePool == bottomPoolView) && (boardTouchLocation.y > boardView.frame.height)
{
activePool.addPiece(activePiece, at: boardTouchLocation)
self.activePiece = nil
self.panStart = nil
self.panOffset = nil
return
}
}
activePiece.move(to: offsetLocation)
putdownActivePiece()
self.panStart = nil
self.panOffset = nil
}
// Cancel dragging piece
case .cancelled:
if let panStart = self.panStart
{
activePiece.move(to: panStart)
putdownActivePiece()
self.panStart = nil
self.panOffset = nil
}
// Other unapplicable states
default:
break
}
}
}
/// Handle a rotation gesture on the game board view.
///
/// - Parameter sender: The rotation gesture recognizer.
@objc func handleBoardRotation(_ sender: UIRotationGestureRecognizer)
{
if let activePiece = self.activePiece
{
switch sender.state
{
// Begin Spinning Piece
case .began:
// Record starting angle
self.rotateStart = activePiece.angle
pickupActivePiece()
// Spin Piece
case .changed:
if let rotateStart = self.rotateStart
{
// Spin active piece
activePiece.rotate(to: rotateStart + sender.rotation)
}
// End Spinning Piece
case .ended:
if let rotateStart = self.rotateStart
{
// Set active piece direction then snap to 90º angle and board grid
activePiece.rotate(to: rotateStart + sender.rotation)
putdownActivePiece()
self.rotateStart = nil
}
// Cancel Spinning Piece
case .cancelled:
if let rotateStart = self.rotateStart
{
// Reset active piece rotation
activePiece.rotate(to: rotateStart)
putdownActivePiece()
self.rotateStart = nil
}
// Do nothing
default:
break
}
}
}
/// Handle a double tap gesture on the game board view.
///
/// - Parameter sender: The double tap gesture recognizer.
@objc func handleBoardDoubleTap(_ sender: UITapGestureRecognizer)
{
if let activePiece = self.activePiece
{
if activePiece.contains(point: sender.location(in: activePiece))
{
let start = activePiece.frame.origin
activePiece.rotate(to: activePiece.angle + (CGFloat.pi / 2))
activePiece.move(to: start)
putdownActivePiece()
}
}
}
/// Handle a long press on one of the pool views.
///
/// - Parameter sender: The long press gesture recognizer.
@objc func handlePoolLongPress(_ sender: UILongPressGestureRecognizer)
{
// There's already an active piece
if self.activePiece != nil
{
return
}
if let activePool = self.activePool
{
switch sender.state
{
// Began dragging piece
case .began:
let poolTouchLocation = sender.location(in: activePool)
if let (index, selectedPiece) = activePool.selectPiece(at: poolTouchLocation)
{
let boardTouchLocation = sender.location(in: boardView)
if (!canBuildPiece(selectedPiece))
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
else
{
pressStart = activePool.convert(selectedPiece.frame, to: boardView).origin
pressOffset = CGPoint(x: boardTouchLocation.x - pressStart!.x, y: boardTouchLocation.y - pressStart!.y)
pressedPiece = selectedPiece
activePool.removePiece(at: index)
boardView.buildPiece(pressedPiece!)
pressedPiece!.frame = CGRect(origin: pressStart!, size: pressedPiece!.frame.size)
}
}
// Dragged piece
case .changed:
if let pressedPiece = self.pressedPiece, let pressOffset = self.pressOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - pressOffset.x, y: boardTouchLocation.y - pressOffset.y)
pressedPiece.move(to: offsetLocation)
}
// Stopped dragging piece
case .ended:
if let pressedPiece = self.pressedPiece, let pressOffset = self.pressOffset
{
let boardTouchLocation = sender.location(in: boardView)
let offsetLocation = CGPoint(x: boardTouchLocation.x - pressOffset.x, y: boardTouchLocation.y - pressOffset.y)
if (activePool == topPoolView) && (boardTouchLocation.y < 0) ||
(activePool == bottomPoolView) && (boardTouchLocation.y > boardView.frame.height)
{
activePool.addPiece(pressedPiece, at: boardTouchLocation)
self.pressStart = nil
self.pressOffset = nil
self.pressedPiece = nil
return
}
boardView.buildPiece(pressedPiece)
activePiece = pressedPiece
activePiece!.move(to: offsetLocation)
putdownActivePiece()
self.pressStart = nil
self.pressOffset = nil
self.pressedPiece = nil
}
// Cancel dragging piece
case .cancelled:
if let pressedPiece = self.pressedPiece
{
activePool.addPiece(pressedPiece)
self.pressStart = nil
self.pressOffset = nil
self.pressedPiece = nil
}
// Do nothing
default:
break
}
}
}
/// Handle the buildButton being pressed.
///
/// - Parameter sender: The button press sender.
@objc func buildButtonPressed(_ sender: UIButton)
{
assert(activePiece != nil, "There isn't an active piece")
// Build Piece in modal
buildPiece(activePiece!)
// Update view
activePiece!.state = .standard
activePiece = nil
nextTurn()
}
/// Rematch button has been pressed.
///
/// - Parameter sender: The button press sender.
@objc func rematchButtonPressed(_ sender: UIButton)
{
completionHandler?(game, true)
}
//MARK: - Functions
/// Builds a new board.
///
/// - Returns: The new board.
private func buildBoard() -> BoardView
{
let newBoard = BoardView(tileSize: tileSize)
view.addSubview(newBoard)
newBoard.translatesAutoresizingMaskIntoConstraints = false
newBoard.heightAnchor.constraint(equalToConstant: tileSize * 12).isActive = true
newBoard.widthAnchor.constraint(equalToConstant: tileSize * 12).isActive = true
newBoard.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
newBoard.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 30).isActive = true
let boardPanRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handleBoardPanGesture))
newBoard.addGestureRecognizer(boardPanRecognizer)
let boardDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleBoardDoubleTap))
boardDoubleTapRecognizer.numberOfTapsRequired = 2
newBoard.addGestureRecognizer(boardDoubleTapRecognizer)
let boardRotationRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(handleBoardRotation))
newBoard.addGestureRecognizer(boardRotationRecognizer)
// Build existing pieces
for piece in game.builtPieces
{
let pieceView = PieceView(piece, tileSize: tileSize)
newBoard.buildPiece(pieceView)
}
// Build claimed tiles
for claimedAddress in game.lightClaimedAddresses
{
let claimedTile = ClaimedTileView(owner: .light, address: claimedAddress, tileSize: tileSize)
newBoard.claimTile(claimedTile)
}
for claimedAddress in game.darkClaimedAddresses
{
let claimedTile = ClaimedTileView(owner: .dark, address: claimedAddress, tileSize: tileSize)
newBoard.claimTile(claimedTile)
}
return newBoard
}
/// Builds a new pool.
///
/// - Parameter top: Whether to build a top pool or a bottom pool.
/// - Returns: The new pool.
private func buildPool(top: Bool) -> PoolView
{
let owner = top ? topPoolPlayer : topPoolPlayer.opponent
let newPool = PoolView(owner: owner, buildings: game.unbuiltBuildings(for: owner), tileSize: tileSize)
view.addSubview(newPool)
newPool.translatesAutoresizingMaskIntoConstraints = false
newPool.heightAnchor.constraint(equalToConstant: (tileSize * 3) + 20).isActive = true
newPool.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
newPool.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
if top
{
newPool.bottomAnchor.constraint(equalTo: boardView.topAnchor, constant: 0).isActive = true
}
else
{
newPool.topAnchor.constraint(equalTo: boardView.bottomAnchor, constant: 0).isActive = true
}
let poolTapRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handlePoolLongPress))
newPool.addGestureRecognizer(poolTapRecognizer)
return newPool
}
/// Builds a new messageLabel.
///
/// - Returns: The new label.
private func buildMessageLabel() -> UILabel
{
let newLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 500, height: 100))
view.addSubview(newLabel)
newLabel.text = "Place Holder"
newLabel.textAlignment = .center
newLabel.translatesAutoresizingMaskIntoConstraints = false
newLabel.heightAnchor.constraint(equalToConstant: 60).isActive = true
newLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
newLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
newLabel.bottomAnchor.constraint(equalTo: topPoolView.topAnchor, constant: 0).isActive = true
return newLabel
}
/// Builds a new buildButton.
///
/// - Returns: The new button.
private func buildBuildButton() -> UIButton
{
let newButton = UIButton(type: .system)
view.addSubview(newButton)
newButton.setTitle("Build Building", for: .normal)
newButton.translatesAutoresizingMaskIntoConstraints = false
newButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
newButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
newButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
newButton.topAnchor.constraint(equalTo: bottomPoolView.bottomAnchor, constant: 0).isActive = true
newButton.addTarget(self, action: #selector(buildButtonPressed), for: .touchUpInside)
return newButton
}
/// Start moving the active piece.
/// - Note: There must be an active piece.
private func pickupActivePiece()
{
guard let activePiece = self.activePiece else
{
fatalError("There is no active piece")
}
buildButton.isEnabled = false
activePiece.state = .standard
}
/// Stop moving the active piece, snapping it to the board, or putting back into the active pool.
/// - Note: There must be an active piece.
private func putdownActivePiece()
{
guard let activePiece = self.activePiece else
{
fatalError("There is no active piece")
}
activePiece.snapToBoard()
// Update state
if canBuildPiece(activePiece)
{
buildButton.isEnabled = true
activePiece.state = .success
}
else
{
buildButton.isEnabled = false
activePiece.state = .failure
}
}
/// Determines if a given piece view can be built.
/// - Note: If the piece's address or direction is not set, checks if the piece can be built anywhere.
///
/// - Parameter piece: The piece view.
/// - Returns: Whether the given piece can be built.
private func canBuildPiece(_ piece: PieceView) -> Bool
{
if (piece.address == nil) || (piece.direction == nil)
{
return game!.canBuildBuilding(piece.building, for: piece.owner)
}
else
{
return game!.canBuildBuilding(piece.building, for: piece.owner, facing: piece.direction!, at: piece.address!)
}
}
/// Build a given piece view at its current position.
/// - Note: Piece must have address and direction set, and be in a valid position.
///
/// - Parameter piece: The piece view.
private func buildPiece(_ piece: PieceView)
{
assert((piece.address != nil) && (piece.direction != nil), "Must set piece's address and direciton before building it")
assert(canBuildPiece(piece), "Piece at an invalid position")
let (claimant, destroyed) = game!.buildBuilding(piece.building, for: piece.owner, facing: piece.direction!, at: piece.address!)
for address in claimant
{
let claimedTile = ClaimedTileView(owner: piece.owner, address: address, tileSize: tileSize)
boardView.claimTile(claimedTile)
}
for piece in destroyed
{
let pieceView = boardView.destroyPiece(piece)
// If Cathedral piece, remove from superviews, else return to pool
switch piece.owner
{
case .church:
pieceView.removeFromSuperview()
default:
poolForOwner(piece.owner).addPiece(pieceView)
}
}
}
/// Get the correct pool for a given player owner.
///
/// - Parameter owner: The player owner, must be light or dark.
/// - Returns: The pool for the given owner.
private func poolForOwner(_ owner: Owner) -> PoolView
{
assert(!owner.isChurch, "The church does not have pool")
if (owner == topPoolPlayer)
{
return topPoolView
}
else
{
return bottomPoolView
}
}
/// Move on to the next turn.
private func nextTurn()
{
// Turn off build button
buildButton.isEnabled = false
// Set message and potential active piece (for Cathedral turn) or pool (for player turn)
if let nextOwner = game!.nextTurn
{
if (nextOwner == .church)
{
let player = lightPlayer
if let computerPlayer = player as? Computer
{
let piece = computerPlayer.nextMove()
let pieceView = PieceView(piece, tileSize: tileSize)
boardView.buildPiece(pieceView)
buildPiece(pieceView)
self.nextTurn()
}
else
{
messageLabel.text = "Build the Cathedral"
activePool = nil
activePiece = PieceView(owner: .church, building: .cathedral, tileSize: tileSize)
activePiece!.move(to: CGPoint(x: tileSize * 4, y: tileSize * 4))
putdownActivePiece()
boardView.buildPiece(activePiece!)
}
}
else
{
let pool = poolForOwner(nextOwner)
let player = (nextOwner == .light) ? lightPlayer! : darkPlayer!
if let computerPlayer = player as? Computer
{
let piece = computerPlayer.nextMove()
pool.removePiece(piece.building)
let pieceView = PieceView(piece, tileSize: tileSize)
boardView.buildPiece(pieceView)
buildPiece(pieceView)
self.nextTurn()
}
else
{
messageLabel.text = "It's \(player.name)'s turn to build."
activePool = poolForOwner(nextOwner)
}
}
}
else
{
let (winner, _) = game!.calculateWinner()!
if let winner = winner
{
messageLabel.text = "Game is over, \(winner) is the winner!"
}
else
{
messageLabel.text = "Game is over, it was a tie."
}
let rematchButton = UIBarButtonItem(title: "Rematch", style: .plain, target: self, action: #selector(rematchButtonPressed))
self.navigationItem.rightBarButtonItem = rematchButton
game = nil
activePool = nil
}
// Update which building in pools can be built
for targetPool in [topPoolView!, bottomPoolView!]
{
if (targetPool == activePool)
{
enablePool(targetPool)
}
else
{
disablePool(targetPool)
}
}
}
/// Enable a given pool, updating highlighting.
///
/// - Parameter poolView: The pool view.
private func enablePool(_ poolView: PoolView)
{
for case let piece as PieceView in poolView.subviews
{
if (canBuildPiece(piece))
{
piece.state = .standard
}
else
{
piece.state = .failure
}
}
}
/// Disable a given pool, darkening all pieces.
///
/// - Parameter poolView: The pool view.
private func disablePool(_ poolView: PoolView)
{
for case let piece as PieceView in poolView.subviews
{
piece.state = .disabled
}
}
/// Updates the view to the current theme.
///
/// - Parameters:
/// - notification: Unused.
@objc private func updateTheme(_: Notification?)
{
let theme = Theme.activeTheme
messageLabel.textColor = theme.textColor
buildButton.tintColor = theme.tintColor
view.backgroundColor = theme.backgroundColor
}
}
| 92afc733e14692d05f2467d63655a649 | 34.327891 | 135 | 0.541362 | false | false | false | false |
esttorhe/RxSwift | refs/heads/feature/swift2.0 | RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift | mit | 3 | //
// ControlTarget.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
#if os(iOS)
import UIKit
typealias Control = UIKit.UIControl
typealias ControlEvents = UIKit.UIControlEvents
#elseif os(OSX)
import Cocoa
typealias Control = Cocoa.NSControl
#endif
// This should be only used from `MainScheduler`
class ControlTarget: RxTarget {
typealias Callback = (Control) -> Void
let selector: Selector = "eventHandler:"
unowned let control: Control
#if os(iOS)
let controlEvents: UIControlEvents
#endif
var callback: Callback?
#if os(iOS)
init(control: Control, controlEvents: UIControlEvents, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.controlEvents = controlEvents
self.callback = callback
super.init()
control.addTarget(self, action: selector, forControlEvents: controlEvents)
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#elseif os(OSX)
init(control: Control, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.callback = callback
super.init()
control.target = self
control.action = selector
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#endif
func eventHandler(sender: Control!) {
if let callback = self.callback {
callback(control)
}
}
override func dispose() {
super.dispose()
#if os(iOS)
self.control.removeTarget(self, action: self.selector, forControlEvents: self.controlEvents)
#elseif os(OSX)
self.control.target = nil
self.control.action = nil
#endif
self.callback = nil
}
} | b63f427505adcf688c3c25834bd3ab6c | 23.511628 | 100 | 0.622686 | false | false | false | false |
amraboelela/swift | refs/heads/master | test/attr/attr_native_dynamic.swift | apache-2.0 | 12 | // RUN: %target-swift-frontend -swift-version 5 -typecheck -dump-ast %s | %FileCheck %s
struct Strukt {
// CHECK: (struct_decl {{.*}} "Strukt"
// CHECK: (var_decl {{.*}} "dynamicStorageOnlyVar" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored readWriteImpl=stored
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=dynamicStorageOnlyVar
dynamic var dynamicStorageOnlyVar : Int = 0
// CHECK: (var_decl {{.*}} "computedVar" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar
dynamic var computedVar : Int {
return 0
}
// CHECK: (var_decl {{.*}} "computedVar2" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar2
dynamic var computedVar2 : Int {
get {
return 0
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterSetter" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarGetterSetter
dynamic var computedVarGetterSetter : Int {
get {
return 0
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterModify" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarGetterModify
dynamic var computedVarGetterModify : Int {
get {
return 0
}
_modify {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadSet" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarReadSet
dynamic var computedVarReadSet : Int {
_read {
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadModify" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarReadModify
dynamic var computedVarReadModify : Int {
_read {
}
_modify {
}
}
// CHECK: (var_decl {{.*}} "storedWithObserver" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored_with_observers readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}}access=private dynamic didSet_for=storedWithObserver
// CHECK: (accessor_decl {{.*}}access=internal dynamic get_for=storedWithObserver
// CHECK: (accessor_decl {{.*}}access=internal set_for=storedWithObserver
// CHECK: (accessor_decl {{.*}}access=internal _modify_for=storedWithObserver
dynamic var storedWithObserver : Int {
didSet {
}
}
// CHECK: (func_decl {{.*}} access=internal dynamic
dynamic func aMethod(arg: Int) -> Int {
return arg
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Int) -> Int {
get {
return 1
}
set {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Float) -> Int {
get {
return 1
}
_modify {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Double) -> Int {
_read {
}
_modify {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Strukt) -> Int {
_read {
}
set {
}
}
}
class Klass {
// CHECK: (class_decl {{.*}} "Klass"
// CHECK: (var_decl {{.*}} "dynamicStorageOnlyVar" type='Int' interface type='Int' access=internal dynamic readImpl=stored writeImpl=stored readWriteImpl=stored
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=dynamicStorageOnlyVar
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=dynamicStorageOnlyVar
dynamic var dynamicStorageOnlyVar : Int = 0
// CHECK: (var_decl {{.*}} "computedVar" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar
dynamic var computedVar : Int {
return 0
}
// CHECK: (var_decl {{.*}} "computedVar2" type='Int' interface type='Int' access=internal dynamic readImpl=getter immutable
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVar2
dynamic var computedVar2 : Int {
get {
return 0
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterSetter" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarGetterSetter
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarGetterSetter
dynamic var computedVarGetterSetter : Int {
get {
return 0
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarGetterModify" type='Int' interface type='Int' access=internal dynamic readImpl=getter writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarGetterModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarGetterModify
dynamic var computedVarGetterModify : Int {
get {
return 0
}
_modify {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadSet" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadSet
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=computedVarReadSet
dynamic var computedVarReadSet : Int {
_read {
}
set {
}
}
// CHECK: (var_decl {{.*}} "computedVarReadModify" type='Int' interface type='Int' access=internal dynamic readImpl=read_coroutine writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal get_for=computedVarReadModify
// CHECK: (accessor_decl {{.*}} access=internal set_for=computedVarReadModify
dynamic var computedVarReadModify : Int {
_read {
}
_modify {
}
}
// CHECK: (func_decl {{.*}} "aMethod(arg:)" {{.*}} access=internal dynamic
dynamic func aMethod(arg: Int) -> Int {
return arg
}
// CHECK-NOT: (func_decl {{.*}} "anotherMethod()" {{.*}} access=internal{{.*}} dynamic
func anotherMethod() -> Int {
return 3
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=mutable_addressor readWriteImpl=mutable_addressor
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Int) -> Int {
unsafeAddress {
fatalError()
}
unsafeMutableAddress {
fatalError()
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=getter writeImpl=mutable_addressor readWriteImpl=mutable_addressor
// CHECK: (accessor_decl {{.*}} access=internal dynamic get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Float) -> Int {
get {
return 1
}
unsafeMutableAddress {
fatalError()
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=read_coroutine writeImpl=mutable_addressor readWriteImpl=mutable_addressor
// CHECK: (accessor_decl {{.*}} access=internal dynamic _read_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeMutableAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Double) -> Int {
_read {
}
unsafeMutableAddress {
fatalError()
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=setter readWriteImpl=materialize_to_temporary
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic set_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal _modify_for=subscript(_:)
dynamic subscript(_ index: Int8) -> Int {
unsafeAddress {
fatalError()
}
set {
}
}
// CHECK: (subscript_decl {{.*}} "subscript(_:)" {{.*}} access=internal dynamic readImpl=addressor writeImpl=modify_coroutine readWriteImpl=modify_coroutine
// CHECK: (accessor_decl {{.*}} access=internal dynamic unsafeAddress_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal dynamic _modify_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal get_for=subscript(_:)
// CHECK: (accessor_decl {{.*}} access=internal set_for=subscript(_:)
dynamic subscript(_ index: Int16) -> Int {
unsafeAddress {
fatalError()
}
_modify {
}
}
}
class SubKlass : Klass {
// CHECK: (class_decl {{.*}} "SubKlass"
// CHECK: (func_decl {{.*}} "aMethod(arg:)" interface type='(SubKlass) -> (Int) -> Int' access=internal {{.*}} dynamic
override dynamic func aMethod(arg: Int) -> Int {
return 23
}
// CHECK: (func_decl {{.*}} "anotherMethod()" interface type='(SubKlass) -> () -> Int' access=internal {{.*}} dynamic
override dynamic func anotherMethod() -> Int {
return 23
}
}
| 932af1cfdeaca008cbdea85f27e25f83 | 44.37037 | 192 | 0.678813 | false | false | false | false |
objecthub/swift-lispkit | refs/heads/master | Sources/LispKit/Base/MethodProfiler.swift | apache-2.0 | 1 | //
// MethodProfiler.swift
// LispKit
//
// Created by Matthias Zenger on 01/01/2022.
// Copyright © 2022 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public final class MethodProfiler {
let className: String
var open: [Double] = []
var stats: [String : (Int, Double)] = [:]
init(_ className: String) {
self.className = className
}
func enter() {
open.append(Timer.absoluteTimeInSec)
}
func exit(_ name: String) {
let time = Timer.absoluteTimeInSec - open.last!
open.removeLast()
if let (count, average) = stats[name] {
stats[name] = (count + 1, (average * Double(count) + time)/Double(count + 1))
} else {
stats[name] = (1, time)
}
}
public func printStats() {
Swift.print("==== \(self.className) ================")
for (name, (count, average)) in self.stats {
Swift.print("\(name),\(count),\(average),\(average * Double(count))")
}
}
}
| aed9ecb7798e9b25775b8c92d3712e7d | 28.057692 | 83 | 0.645268 | false | false | false | false |
ZeldaIV/TDC2015-FP | refs/heads/master | Demo 2/Sequences/Pods/RxSwift/RxSwift/Observables/Implementations/Zip+CollectionType.swift | gpl-3.0 | 28 | //
// Zip+CollectionType.swift
// Rx
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ZipCollectionTypeSink<C: CollectionType, R, O: ObserverType where C.Generator.Element : ObservableType, O.E == R> : Sink<O> {
typealias Parent = ZipCollectionType<C, R>
typealias SourceElement = C.Generator.Element.E
let parent: Parent
let lock = NSRecursiveLock()
// state
var numberOfValues = 0
var values: [Queue<SourceElement>]
var isDone: [Bool]
var numberOfDone = 0
var subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
self.values = [Queue<SourceElement>](count: parent.count, repeatedValue: Queue(capacity: 4))
self.isDone = [Bool](count: parent.count, repeatedValue: false)
self.subscriptions = Array<SingleAssignmentDisposable>()
self.subscriptions.reserveCapacity(parent.count)
for _ in 0 ..< parent.count {
self.subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<SourceElement>, atIndex: Int) {
lock.performLocked {
switch event {
case .Next(let element):
values[atIndex].enqueue(element)
if values[atIndex].count == 1 {
numberOfValues++
}
if numberOfValues < parent.count {
let numberOfOthersThatAreDone = self.numberOfDone - (isDone[atIndex] ? 1 : 0)
if numberOfOthersThatAreDone == self.parent.count - 1 {
self.observer?.on(.Completed)
self.dispose()
}
return
}
do {
var arguments = [SourceElement]()
arguments.reserveCapacity(parent.count)
// recalculate number of values
numberOfValues = 0
for i in 0 ..< values.count {
arguments.append(values[i].dequeue())
if values[i].count > 0 {
numberOfValues++
}
}
let result = try parent.resultSelector(arguments)
self.observer?.on(.Next(result))
}
catch let error {
self.observer?.on(.Error(error))
self.dispose()
}
case .Error(let error):
self.observer?.on(.Error(error))
self.dispose()
case .Completed:
if isDone[atIndex] {
return
}
isDone[atIndex] = true
numberOfDone++
if numberOfDone == self.parent.count {
self.observer?.on(.Completed)
self.dispose()
}
else {
self.subscriptions[atIndex].dispose()
}
}
}
}
func run() -> Disposable {
var j = 0
for i in parent.sources.startIndex ..< parent.sources.endIndex {
let index = j
self.subscriptions[j].disposable = self.parent.sources[i].subscribeSafe(ObserverOf { event in
self.on(event, atIndex: index)
})
j++
}
return CompositeDisposable(disposables: self.subscriptions.map { $0 })
}
}
class ZipCollectionType<C: CollectionType, R where C.Generator.Element : ObservableType> : Producer<R> {
typealias ResultSelector = [C.Generator.Element.E] throws -> R
let sources: C
let resultSelector: ResultSelector
let count: Int
init(sources: C, resultSelector: ResultSelector) {
self.sources = sources
self.resultSelector = resultSelector
self.count = Int(self.sources.count.toIntMax())
}
override func run<O : ObserverType where O.E == R>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | fea3263058e268420312460047837261 | 33.22963 | 134 | 0.511905 | false | false | false | false |
swernimo/iOS | refs/heads/master | VirtualTourist/VirtualTourist/Photo.swift | mit | 1 | //
// Photo.swift
// VirtualTourist
//
// Created by Sean Wernimont on 2/27/16.
// Copyright © 2016 Just One Guy. All rights reserved.
//
import Foundation
import CoreData
@objc(Photo)
class Photo : NSManagedObject {
@NSManaged var imageData: NSData?
@NSManaged var filePath: String?
@NSManaged var pin: Pin
@NSManaged var id: String
init(pin: Pin, image: NSData, path: String, context: NSManagedObjectContext){
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
self.pin = pin
imageData = image
id = NSUUID().UUIDString
filePath = path
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
} | e62d68d3f5bbc86948d2f02d1608b3c8 | 27.606061 | 113 | 0.688229 | false | false | false | false |
grzegorzleszek/algorithms-swift | refs/heads/master | Sources/Graph+TravelingSalesman.swift | mit | 1 | //
// Graph+TravelingSalesman.swift
//
// Copyright © 2018 Grzegorz.Leszek. All rights reserved.
//
// Permission is hereby granted, free of charge, to first 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 WpathANTY OF first KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WpathANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR first 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
struct Path {
var vertices: [Vertex]
var weight: Int
}
extension Graph {
/// Traveling Salesman
/// Initialize: T [ S ,v ] - the shortest path, which:
/// * Starts in vertex 1
/// * Visits each vertex from S – {v}
/// * End in v
/// 1. T [ {v},v ] = w ( 1,v )
/// 2. T[S,v] = min( T [ S – {v}, x ] + w ( x,v )), where x∈S - {v}
/// 3. to find cycle we need to T[V(G)-{1},v] + w(v,1)
func tsp(start: Vertex, goal: Vertex? = nil, graph: Graph) -> Path {
if graph._vertices.count <= 1 {
return Path(vertices: graph._vertices, weight: 0)
}
let singlePaths = graph._edges.map { Path(vertices: [$0.left, $0.right], weight: $0.weight) }
var bestPaths = makeBestPath(from: singlePaths, start: start)
for _ in 0..<graph._vertices.count
{
for i in 0..<bestPaths.count
{
addSinglePath(graph, &bestPaths, i)
}
}
let size = bestPaths.map { $0.vertices.count }.max()
let filteredPaths = bestPaths.filter { $0.vertices.count == size }
guard let anyPath = filteredPaths.first else { return Path(vertices: [], weight: 0) }
var theBestPath: Path = anyPath
for path in filteredPaths
{
if (theBestPath.weight >= path.weight)
{
theBestPath = path
}
}
return theBestPath
}
func addSinglePath(_ graph: Graph, _ bestPaths: inout [Path], _ index: Int) {
guard let lastVertex = bestPaths[index].vertices.last else { return }
var _neighbors = graph.neighborsOf(lastVertex, withGiven: graph._edges)
for vertex in bestPaths[index].vertices {
if contain(vertex, onArray: _neighbors) {
_neighbors = _neighbors.filter { $0.id != vertex.id }
}
}
for vertex in _neighbors {
var path = bestPaths[index]
let pathWeight = graph.findEdge(vertex, (path.vertices.last ?? vertex))?.weight ?? 0
path.vertices.append(vertex)
path.weight = path.weight + pathWeight
bestPaths.append(path)
}
}
func makeBestPath(from singlePaths: [Path], start: Vertex) -> [Path] {
return singlePaths.filter { (path) -> Bool in
return path.vertices.contains { (vertex) -> Bool in
return vertex == start
}
}
}
}
| 7eea7f82ea76eee0db488900c9cf3ccc | 37.322917 | 101 | 0.609948 | false | false | false | false |
studyYF/Weibo-swift- | refs/heads/master | WeiBo/WeiBo/CLasses/Home(首页)/HomeModel/StatusViewModel.swift | apache-2.0 | 1 | //
// StatusViewModel.swift
// Weibo
//
// Created by YF on 16/10/5.
// Copyright © 2016年 YF. All rights reserved.
//
import UIKit
//MARK: - 把所有的要显示的属性都放在这里处理
class StatusViewModel: NSObject {
//MARK: - 定义属性
var status : StatusModel?
///来源text
var sourceText : String?
///创建时间text
var createAtText : String?
///用户类型图片
var verified_image : UIImage?
///会员等级图片
var mbrank_image : UIImage?
///用户头像地址
var profileURL : NSURL?
///微博配图的url数组
var pictureURLs : [NSURL] = [NSURL]()
//MARK: - 自定义构造函数
init(status : StatusModel) {
super.init()
self.status = status
handleViewModel(status)
}
}
//MARK: - 处理模型数据
extension StatusViewModel {
private func handleViewModel(status : StatusModel) {
//1.处理微博创建时间
if let create_at = status.created_at {
createAtText = NSDate.createDateString(create_at)
}
//2.处理微博来源
//where 表示两个条件都需要满足
if let source = status.source where source != "" {
let startIndex = (source as NSString).rangeOfString(">").location + 1
let length = (source as NSString).rangeOfString("</").location - startIndex
sourceText = (source as NSString).substringWithRange(NSRange(location: startIndex, length: length))
}
//3.处理认证图标
let verified_type = status.user?.verified_type ?? -1
switch verified_type {
case 0 :
verified_image = UIImage(named: "avatar_vip")
case 2,3,5 :
verified_image = UIImage(named: "avatar_enterprise_vip")
case 220 :
verified_image = UIImage(named: "avatar_grassroot")
default :
verified_image = nil
}
//4.处理用户等级图标
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
mbrank_image = UIImage(named: "common_icon_membership_level\(mbrank)")
}
//5.处理用户头像url
let profile_image_url = status.user?.profile_image_url ?? ""
profileURL = NSURL(string: profile_image_url)
//6.处理微博配图url
let picURls = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let pic_urls = picURls {
for picDict in pic_urls {
guard let urlString = picDict["thumbnail_pic"] else {
continue
}
pictureURLs.append((NSURL(string: urlString))!)
}
}
}
}
| f84458a841ae96a40dfd0e565b898a09 | 29.083333 | 111 | 0.566284 | false | false | false | false |
KristopherGBaker/RubiParser | refs/heads/master | RubiParserTests/RubiParserTestCase.swift | mit | 1 | //
// RubiParserTestCase.swift
// RubiParser
//
// Created by Kris Baker on 12/18/16.
// Copyright © 2016 Empyreal Night, LLC. All rights reserved.
//
@testable import RubiParser
import XCTest
/// Tests for RubiParser.
class RubiParserTestCase: XCTestCase {
/// The parser.
internal var parser: RubiParser!
/// The document.
internal var doc: RubiDocument!
/// Initialize parser.
override func setUp() {
super.setUp()
parser = RubiScannerParser()
}
/// Tests parse for the EasyNews1 example.
func testParse() {
guard let html = loadExample(name: "EasyNews1") else {
XCTFail("unable to load EasyNews1 example")
return
}
doc = parser.parse(html)
assertEasyNews1()
}
// Tests parse for the EasyNews2 example.
func testParseWithImage() {
guard let html = loadExample(name: "EasyNews2") else {
XCTFail("unable to load EasyNews2 example")
return
}
doc = parser.parse(html)
assertEasyNews2()
print(doc.kanjiString)
print(doc.kanaString)
doc.items.forEach { printNode(node: $0) }
func printNode(node: RubiNode) {
if case RubiNode.ruby(let kanji, let reading) = node {
print("Kanji: \(kanji) \(reading)")
}
else if case RubiNode.word(let text) = node {
print(text)
}
else if case RubiNode.text(let text) = node {
print(text)
}
else if case RubiNode.image(let url) = node {
print(url)
}
else if case RubiNode.paragraph(let children) = node {
children.forEach { printNode(node: $0) }
}
}
}
/// Asserts the parsed EasyNews1 document is correct.
func assertEasyNews1() {
XCTAssertEqual(doc.items.count, 6)
if case RubiNode.paragraph(children: let children) = doc.items[0] {
XCTAssert(children.count == 33)
if case RubiNode.text(text: let text) = children[0] {
XCTAssert(text == "アメリカ")
} else {
XCTFail("unexpected items")
}
} else {
XCTFail("unexpected items")
}
if case RubiNode.paragraph(children: let children) = doc.items[3] {
XCTAssert(children.count == 25)
if case RubiNode.ruby(kanji: let kanji, reading: let reading) = children[0] {
XCTAssert(kanji == "東京都")
XCTAssert(reading == "とうきょうと")
} else {
XCTFail("unexpected items")
}
} else {
XCTFail("unexpected items")
}
}
func assertEasyNews2() {
XCTAssert(doc.items.count == 4)
if case RubiNode.image(url: let url) = doc.items[0] {
XCTAssert(url == URL(string: "http://www3.nhk.or.jp/news/easy/manu_still/baby.jpg"))
}
}
}
| cfe6a772ca66c72f0d4f57323fc85ad2 | 26.709091 | 96 | 0.538058 | false | true | false | false |
kaizeiyimi/Phantom | refs/heads/master | Phantom/codes/Tracker.swift | mit | 1 | //
// Tracker.swift
// Phantom
//
// Created by kaizei on 16/1/26.
// Copyright © 2016年 kaizei. All rights reserved.
//
import Foundation
// MARK: - Task Tracking
final public class TrackingToken: Hashable {
public var hashValue: Int {
return "\(unsafeAddressOf(self))".hashValue
}
}
public func ==(lhs: TrackingToken, rhs: TrackingToken) -> Bool {
return lhs === rhs
}
// MARK: - TaskTracker.
final public class TaskTracker {
struct TrackingItem {
let queue: dispatch_queue_t?
let progress: (ProgressInfo -> Void)?
let decoderCompletion: (decoder: (NSURL, NSData) -> DecodeResult<Any>, completion: Result<Any> -> Void)?
}
public private(set) var task: Task!
public private(set) var progressInfo: ProgressInfo?
public private(set) var result: Result<NSData>?
private var lock = OS_SPINLOCK_INIT
private var trackings: [TrackingToken: TrackingItem] = [:]
private let trackerQueue: dispatch_queue_t
init(trackerQueue: dispatch_queue_t? = nil) {
self.trackerQueue = trackerQueue ?? dispatch_queue_create("Phantom.TaskTracker.queue", DISPATCH_QUEUE_CONCURRENT)
}
public static func track(url: NSURL, trackerQueue: dispatch_queue_t? = nil, downloader: Downloader = sharedDownloader, cache: DownloaderCache? = nil) -> TaskTracker {
let tracker = TaskTracker()
tracker.task = downloader.download(url, cache: cache, queue: tracker.trackerQueue,
progress: tracker.notifyProgress, decoder: tracker.decoder, completion: tracker.notifyCompletion)
return tracker
}
// MARK: tracking
/// `queue` default to trackerQueue.
public func addTracking(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)) -> TrackingToken {
return addTracking(TrackingItem(queue: queue, progress: progress, decoderCompletion: nil))
}
public func addTracking<T>(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)?, decoder: (NSURL, NSData) -> DecodeResult<T> , completion: Result<T> -> Void) -> TrackingToken {
return addTracking(TrackingItem(queue: queue, progress: progress, decoderCompletion: (wrapDecoder(decoder), wrapCompletion(completion))))
}
public func removeTracking(token: TrackingToken?) {
if let token = token {
OSSpinLockLock(&lock)
trackings.removeValueForKey(token)
OSSpinLockUnlock(&lock)
}
}
// MARK: progress, decoder and completion wrappers.
func notifyProgress(progressInfo: ProgressInfo) {
OSSpinLockLock(&lock)
self.progressInfo = progressInfo
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyProgrss($0, progressInfo: progressInfo) }
}
private func decoder(url: NSURL, data: NSData) -> DecodeResult<NSData> {
return .Success(data: data)
}
func notifyCompletion(result: Result<NSData>) {
OSSpinLockLock(&lock)
self.result = result
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyCompletion($0, result: result) }
}
// MARK: private methods
private func addTracking(item: TrackingItem) -> TrackingToken {
OSSpinLockLock(&lock)
let token = TrackingToken()
trackings[token] = item
let progressInfo = self.progressInfo
let result = self.result
OSSpinLockUnlock(&lock)
if let progressInfo = progressInfo {
notifyProgrss(item, progressInfo: progressInfo)
}
if let result = result {
notifyCompletion(item, result: result)
}
return token
}
private func notifyProgrss(item: TrackingItem, progressInfo: ProgressInfo) {
guard let progress = item.progress else { return }
dispatch_async(item.queue ?? trackerQueue){ progress(progressInfo) }
}
private func notifyCompletion(item: TrackingItem, result: Result<NSData>) {
guard let decoderCompletion = item.decoderCompletion else { return }
switch result {
case .Success(_, _):
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {[trackerQueue] in
let decoded = decode(result, decoder: decoderCompletion.decoder)
dispatch_async(item.queue ?? trackerQueue) {
decoderCompletion.completion(decoded)
}
}
case .Failed(_, _):
dispatch_async(item.queue ?? trackerQueue) {
decoderCompletion.completion(decode(result, decoder: decoderCompletion.decoder))
}
}
}
}
// MARK: - ResultTracker. only track progress and result
struct ResultTrackingItem<T> {
let queue: dispatch_queue_t?
let progress: (ProgressInfo -> Void)?
let completion: (Result<T> -> Void)?
}
final public class ResultTracker<T> {
public private(set) var task: Task!
public private(set) var progressInfo: ProgressInfo?
public private(set) var result: Result<T>?
private var lock = OS_SPINLOCK_INIT
private var trackings: [TrackingToken: ResultTrackingItem<T>] = [:]
private let trackerQueue: dispatch_queue_t
init(trackerQueue: dispatch_queue_t? = nil) {
self.trackerQueue = trackerQueue ?? dispatch_queue_create("Phantom.ResultTracker.queue", DISPATCH_QUEUE_CONCURRENT)
}
public static func track(url: NSURL, trackerQueue: dispatch_queue_t? = nil, downloader: Downloader = sharedDownloader, cache: DownloaderCache? = nil, decoder: (NSURL, NSData) -> DecodeResult<T>) -> ResultTracker<T> {
let tracker = ResultTracker<T>(trackerQueue: trackerQueue)
tracker.task = downloader.download(url, cache: cache, queue: tracker.trackerQueue,
progress: tracker.notifyProgress, decoder: decoder, completion: tracker.notifyCompletion)
return tracker
}
// MARK: tracking
/// `queue` default to trackerQueue.
public func addTracking(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)) -> TrackingToken {
return addTracking(ResultTrackingItem<T>(queue: queue, progress: progress, completion: nil))
}
public func addTracking(queue: dispatch_queue_t? = nil, progress: (ProgressInfo -> Void)?, completion: Result<T> -> Void) -> TrackingToken {
return addTracking(ResultTrackingItem(queue: queue, progress: progress, completion: completion))
}
public func removeTracking(token: TrackingToken?) {
if let token = token {
OSSpinLockLock(&lock)
trackings.removeValueForKey(token)
OSSpinLockUnlock(&lock)
}
}
// MARK: progress, decoder and completion wrappers.
func notifyProgress(progressInfo: ProgressInfo) {
OSSpinLockLock(&lock)
self.progressInfo = progressInfo
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyProgrss($0, progressInfo: progressInfo) }
}
func notifyCompletion(result: Result<T>) {
OSSpinLockLock(&lock)
self.result = result
let items = trackings.values
OSSpinLockUnlock(&lock)
items.forEach{ notifyCompletion($0, result: result) }
}
// MARK: private methods
private func addTracking(item: ResultTrackingItem<T>) -> TrackingToken {
OSSpinLockLock(&lock)
let token = TrackingToken()
trackings[token] = item
let progressInfo = self.progressInfo
let result = self.result
OSSpinLockUnlock(&lock)
if let progressInfo = progressInfo {
notifyProgrss(item, progressInfo: progressInfo)
}
if let result = result {
notifyCompletion(item, result: result)
}
return token
}
private func notifyProgrss(item: ResultTrackingItem<T>, progressInfo: ProgressInfo) {
guard let progress = item.progress else { return }
dispatch_async(item.queue ?? trackerQueue){ progress(progressInfo) }
}
private func notifyCompletion(item: ResultTrackingItem<T>, result: Result<T>) {
guard let completion = item.completion else { return }
dispatch_async(item.queue ?? trackerQueue) { completion(result) }
}
}
| 308f52ad7e9f82d43c7b57a1a4787194 | 36.19469 | 220 | 0.648941 | false | false | false | false |
oskarpearson/rileylink_ios | refs/heads/master | NightscoutUploadKit/DeviceStatus/PumpStatus.swift | mit | 1 | //
// PumpStatus.swift
// RileyLink
//
// Created by Pete Schwamb on 7/26/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct PumpStatus {
let clock: Date
let pumpID: String
let iob: IOBStatus?
let battery: BatteryStatus?
let suspended: Bool?
let bolusing: Bool?
let reservoir: Double?
public init(clock: Date, pumpID: String, iob: IOBStatus? = nil, battery: BatteryStatus? = nil, suspended: Bool? = nil, bolusing: Bool? = nil, reservoir: Double? = nil) {
self.clock = clock
self.pumpID = pumpID
self.iob = iob
self.battery = battery
self.suspended = suspended
self.bolusing = bolusing
self.reservoir = reservoir
}
public var dictionaryRepresentation: [String: Any] {
var rval = [String: Any]()
rval["clock"] = TimeFormat.timestampStrFromDate(clock)
rval["pumpID"] = pumpID
if let battery = battery {
rval["battery"] = battery.dictionaryRepresentation
}
if let reservoir = reservoir {
rval["reservoir"] = reservoir
}
if let iob = iob {
rval["iob"] = iob.dictionaryRepresentation
}
return rval
}
}
| 9b1e10bb5733d0cceae0c1ee6ec70f41 | 25.16 | 173 | 0.583333 | false | false | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/UI/ExperimentItemsViewController.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
protocol ExperimentItemsViewControllerDelegate: class {
func experimentItemsViewControllerDidSelectItem(_ displayItem: DisplayItem)
func experimentItemsViewControllerCommentPressedForItem(_ displayItem: DisplayItem)
func experimentItemsViewControllerMenuPressedForItem(_ displayItem: DisplayItem,
button: MenuButton)
}
// swiftlint:disable type_body_length
/// A view controller that displays experiment items in a list.
class ExperimentItemsViewController: VisibilityTrackingViewController,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
ExperimentItemsDataSourceDelegate,
ExperimentCardCellDelegate {
// MARK: - Properties
let archivedFlagCellIdentifier = "ArchivedFlagCell"
let textNoteCardCellIdentifier = "TextNoteCardCell"
let pictureCardCellIdentifier = "PictureCardCell"
let snapshotCardCellIdentifier = "SnapshotCardCell"
let trialCardCellIdentifier = "TrialCardCell"
let triggerCardCellIdentifier = "TriggerCardCell"
let defaultCellIdentifier = "DefaultCell"
private(set) var collectionView: UICollectionView
private let experimentDataSource: ExperimentItemsDataSource!
weak var delegate: ExperimentItemsViewControllerDelegate?
/// The scroll delegate will recieve a subset of scroll delegate calls (didScroll,
/// didEndDecelerating, didEndDragging, willEndDragging).
weak var scrollDelegate: UIScrollViewDelegate?
/// The experiment's interaction options.
var experimentInteractionOptions: ExperimentInteractionOptions
/// Whether to show the archived flag.
var shouldShowArchivedFlag: Bool {
set {
experimentDataSource.shouldShowArchivedFlag = newValue
}
get {
return experimentDataSource.shouldShowArchivedFlag
}
}
var experimentDisplay: ExperimentDisplay = .normal {
didSet {
collectionView.backgroundColor = experimentDisplay.backgroundColor
}
}
/// The scroll position to use when adding items. This is changed when adding content to a trial
/// while recording but should be replaced by logic that can scroll to a view within a trial cell.
var collectionViewChangeScrollPosition = UICollectionView.ScrollPosition.top
/// Returns the insets for experiment cells.
var cellInsets: UIEdgeInsets {
if FeatureFlags.isActionAreaEnabled { return MaterialCardCell.cardInsets }
if experimentDisplay == .pdfExport {
return MaterialCardCell.cardInsets
}
var insets: UIEdgeInsets {
switch displayType {
case .compact, .compactWide:
return MaterialCardCell.cardInsets
case .regular:
return UIEdgeInsets(top: MaterialCardCell.cardInsets.top,
left: 150,
bottom: MaterialCardCell.cardInsets.bottom,
right: 150)
case .regularWide:
// The right side needs to compensate for the drawer sidebar when the experiment is not
// archived.
return UIEdgeInsets(top: MaterialCardCell.cardInsets.top,
left: 90,
bottom: MaterialCardCell.cardInsets.bottom,
right: 90)
}
}
return UIEdgeInsets(top: insets.top,
left: insets.left + view.safeAreaInsetsOrZero.left,
bottom: insets.bottom,
right: insets.right + view.safeAreaInsetsOrZero.right)
}
/// Returns true if there are no trials or notes in the experiment, otherwise false.
var isEmpty: Bool {
return experimentDataSource.experimentItems.count +
experimentDataSource.recordingTrialItemCount == 0
}
private let metadataManager: MetadataManager
private let trialCardNoteViewPool = TrialCardNoteViewPool()
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - experimentInteractionOptions: The experiment's interaction options.
/// - metadataManager: The metadata manager.
/// - shouldShowArchivedFlag: Whether to show the archived flag.
init(experimentInteractionOptions: ExperimentInteractionOptions,
metadataManager: MetadataManager,
shouldShowArchivedFlag: Bool) {
self.experimentInteractionOptions = experimentInteractionOptions
experimentDataSource = ExperimentItemsDataSource(shouldShowArchivedFlag: shouldShowArchivedFlag)
self.metadataManager = metadataManager
let flowLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
super.init(nibName: nil, bundle: nil)
experimentDataSource.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
if FeatureFlags.isActionAreaEnabled == true {
view.preservesSuperviewLayoutMargins = true
}
// Always register collection view cells early to avoid a reload occurring first.
collectionView.register(ArchivedFlagCell.self,
forCellWithReuseIdentifier: archivedFlagCellIdentifier)
collectionView.register(TextNoteCardCell.self,
forCellWithReuseIdentifier: textNoteCardCellIdentifier)
collectionView.register(PictureCardCell.self,
forCellWithReuseIdentifier: pictureCardCellIdentifier)
collectionView.register(SnapshotCardCell.self,
forCellWithReuseIdentifier: snapshotCardCellIdentifier)
collectionView.register(TrialCardCell.self, forCellWithReuseIdentifier: trialCardCellIdentifier)
collectionView.register(TriggerCardCell.self,
forCellWithReuseIdentifier: triggerCardCellIdentifier)
collectionView.register(UICollectionViewCell.self,
forCellWithReuseIdentifier: defaultCellIdentifier)
// Collection view.
collectionView.alwaysBounceVertical = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = experimentDisplay.backgroundColor
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
if FeatureFlags.isActionAreaEnabled == true {
collectionView.snp.makeConstraints { (make) in
make.top.bottom.equalToSuperview()
make.leading.equalTo(view.snp.leadingMargin)
make.trailing.equalTo(view.snp.trailingMargin)
}
} else {
collectionView.pinToEdgesOfView(view)
}
}
override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
})
}
/// Replaces the experiment items with new items.
///
/// - Parameter items: An array of display items.
func setExperimentItems(_ items: [DisplayItem]) {
experimentDataSource.experimentItems = items
collectionView.reloadData()
}
/// Sets the bottom and right collection view insets. Top insets are not set because they are
/// updated automatically by the MDC app bar.
///
/// - Parameters:
/// - bottom: The bottom inset.
/// - right: The right inset.
func setCollectionViewInsets(bottom: CGFloat, right: CGFloat) {
collectionView.contentInset.bottom = bottom
collectionView.contentInset.right = right
collectionView.scrollIndicatorInsets = collectionView.contentInset
if isViewVisible {
// Invalidating the collection view layout while the view is off screen causes the size for
// item at method to be called too early when navigating back to this view. Being called too
// early can result in a negative width to be calculated, which crashes the app.
collectionView.collectionViewLayout.invalidateLayout()
}
}
/// If a trial with a matching ID exists it will be updated with the given trial, otherwise the
/// trial will be added in the proper sort order.
///
/// - Parameters:
/// - displayTrial: A display trial.
/// - didFinishRecording: Whether or not this is a display trial that finished recording, and
/// should be moved from the recording trial section, to a recorded trial.
func addOrUpdateTrial(_ displayTrial: DisplayTrial, didFinishRecording: Bool) {
if didFinishRecording {
experimentDataSource.removeRecordingTrial()
}
experimentDataSource.addOrUpdateTrial(displayTrial)
}
/// Adds an experiment item to the end of the existing items.
///
/// - Parameters:
/// - displayItem: A display item.
/// - isSorted: Whether the item should be inserted in the correct sort order or added
/// to the end.
func addItem(_ displayItem: DisplayItem, sorted isSorted: Bool = false) {
experimentDataSource.addItem(displayItem, sorted: isSorted)
}
/// Adds a recording trial to the data source.
///
/// - Parameter recordingTrial: A recording trial.
func addOrUpdateRecordingTrial(_ recordingTrial: DisplayTrial) {
experimentDataSource.addOrUpdateRecordingTrial(recordingTrial)
}
/// Updates a matching trial with a new trial.
///
/// - Parameter displayTrial: A display trial.
func updateTrial(_ displayTrial: DisplayTrial) {
experimentDataSource.updateTrial(displayTrial)
}
/// Removes the trial with a given ID.
///
/// - Parameter trialID: A trial ID.
/// - Returns: The index of the removed trial if the removal succeeded.
@discardableResult func removeTrial(withID trialID: String) -> Int? {
return experimentDataSource.removeTrial(withID: trialID)
}
/// Removes the recording trial.
func removeRecordingTrial() {
return experimentDataSource.removeRecordingTrial()
}
/// Updates a matching note with a new note.
///
/// - Parameter displayNote: A display note.
func updateNote(_ displayNote: DisplayNote) {
experimentDataSource.updateNote(displayNote)
}
/// Removes the note with a given ID.
///
/// - Parameter noteID: A note ID.
func removeNote(withNoteID noteID: String) {
experimentDataSource.removeNote(withNoteID: noteID)
}
// MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return experimentDataSource.numberOfSections
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return experimentDataSource.numberOfItemsInSection(section)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat
if FeatureFlags.isActionAreaEnabled {
let collectionViewWidth = collectionView.bounds.width
let insets = [collectionView.adjustedContentInset, cellInsets]
.reduce(0) { return $0 + $1.left + $1.right }
width = collectionViewWidth - insets
} else {
width = collectionView.bounds.size.width - collectionView.contentInset.right -
cellInsets.left - cellInsets.right
}
var calculatedCellHeight: CGFloat
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .archivedFlag:
calculatedCellHeight = ArchivedFlagCell.height
case .experimentData, .recordingTrial:
// The experiment's data.
let showHeader = experimentDataSource.isExperimentDataSection(indexPath.section)
let isRecordingTrial = experimentDataSource.isRecordingTrialSection(indexPath.section)
guard let experimentItem =
experimentDataSource.item(inSection: section,
atIndex: indexPath.item) else { return .zero }
switch experimentItem.itemType {
case .textNote(let displayTextNote):
calculatedCellHeight = TextNoteCardCell.height(inWidth: width,
textNote: displayTextNote,
showingHeader: showHeader,
showingInlineTimestamp: isRecordingTrial)
case .snapshotNote(let displaySnapshotNote):
calculatedCellHeight = SnapshotCardCell.height(inWidth: width,
snapshotNote: displaySnapshotNote,
showingHeader: showHeader)
case .trial(let displayTrial):
calculatedCellHeight = TrialCardCell.height(inWidth: width,
trial: displayTrial,
experimentDisplay: experimentDisplay)
case .pictureNote(let displayPictureNote):
let pictureStyle: PictureStyle = isRecordingTrial ? .small : .large
calculatedCellHeight = PictureCardCell.height(inWidth: width,
pictureNote: displayPictureNote,
pictureStyle: pictureStyle,
showingHeader: showHeader)
case .triggerNote(let displayTriggerNote):
calculatedCellHeight = TriggerCardCell.height(inWidth: width,
triggerNote: displayTriggerNote,
showingHeader: showHeader,
showingInlineTimestamp: isRecordingTrial)
}
calculatedCellHeight = ceil(calculatedCellHeight)
}
return CGSize(width: width, height: calculatedCellHeight)
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .archivedFlag:
return collectionView.dequeueReusableCell(withReuseIdentifier: archivedFlagCellIdentifier,
for: indexPath)
case .experimentData, .recordingTrial:
let showHeader = experimentDataSource.isExperimentDataSection(indexPath.section)
let isRecordingTrial = experimentDataSource.isRecordingTrialSection(indexPath.section)
let displayItem = experimentDataSource.item(inSection: section, atIndex: indexPath.item)
let showCaptionButton = experimentDisplay.showCaptionButton(for: experimentInteractionOptions)
let cell: UICollectionViewCell
switch displayItem?.itemType {
case .textNote(let textNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: textNoteCardCellIdentifier,
for: indexPath)
if let cell = cell as? TextNoteCardCell {
cell.setTextNote(textNote,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .snapshotNote(let snapshotNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: snapshotCardCellIdentifier,
for: indexPath)
if let cell = cell as? SnapshotCardCell {
cell.setSnapshotNote(snapshotNote,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
showCaptionButton: showCaptionButton,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .trial(let trial)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: trialCardCellIdentifier,
for: indexPath)
if let cell = cell as? TrialCardCell {
// The trial card note view pool must be set before configuring the cell.
cell.setTrialCardNoteViewPool(trialCardNoteViewPool)
if trial.status == .recording {
cell.configureRecordingCellWithTrial(trial, metadataManager: metadataManager)
} else {
cell.configureCellWithTrial(trial,
metadataManager: metadataManager,
experimentDisplay: experimentDisplay)
}
cell.delegate = self
}
case .pictureNote(let displayPictureNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureCardCellIdentifier,
for: indexPath)
if let cell = cell as? PictureCardCell {
let pictureStyle: PictureStyle = isRecordingTrial ? .small : .large
cell.setPictureNote(displayPictureNote,
withPictureStyle: pictureStyle,
metadataManager: metadataManager,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
showCaptionButton: showCaptionButton,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .triggerNote(let displayTriggerNote)?:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: triggerCardCellIdentifier,
for: indexPath)
if let cell = cell as? TriggerCardCell {
cell.setTriggerNote(displayTriggerNote,
showHeader: showHeader,
showInlineTimestamp: isRecordingTrial,
showCaptionButton: showCaptionButton,
experimentDisplay: experimentDisplay)
cell.delegate = self
}
case .none:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: defaultCellIdentifier,
for: indexPath)
}
// Set the cell borders
if isRecordingTrial, let cell = cell as? MaterialCardCell {
let isFirstCellInRecordingSection = indexPath.item == 0
let isLastCellInRecordingSection =
indexPath.item == experimentDataSource.recordingTrialItemCount - 1
if isFirstCellInRecordingSection && isLastCellInRecordingSection {
cell.border = MaterialCardCell.Border(options: .all)
} else if isFirstCellInRecordingSection {
cell.border = MaterialCardCell.Border(options: .top)
} else if isLastCellInRecordingSection {
cell.border = MaterialCardCell.Border(options: .bottom)
} else {
cell.border = MaterialCardCell.Border(options: .none)
}
}
return cell
}
}
func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
if experimentDataSource.section(atIndex: indexPath.section) == .experimentData ||
experimentDataSource.isRecordingTrialSection(indexPath.section) {
// Loading picture note images on demand instead of all at once prevents crashes and reduces
// the memory footprint.
if let pictureNoteCell = cell as? PictureCardCell {
pictureNoteCell.displayImage()
} else if let trialNoteCell = cell as? TrialCardCell {
trialNoteCell.displayImages()
}
}
}
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
if experimentDataSource.section(atIndex: indexPath.section) == .experimentData {
if let pictureNoteCell = cell as? PictureCardCell {
pictureNoteCell.removeImage()
} else if let trialNoteCell = cell as? TrialCardCell {
trialNoteCell.removeImages()
}
}
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
// Determine the last section with items.
var lastSectionWithItems: Int?
for i in 0..<experimentDataSource.numberOfSections {
if experimentDataSource.numberOfItemsInSection(i) > 0 {
lastSectionWithItems = i
}
}
if experimentDataSource.numberOfItemsInSection(section) == 0 {
// If the section is empty, no insets.
return .zero
} else if section == lastSectionWithItems {
// If this is the last section with items, include the bottom inset.
return cellInsets
} else {
// If this is not the last section with items section, but this section has items,
// use standard insets without bottom. This avoids an issue where two stacked
// sections can have double padding.
var modifiedInsets = cellInsets
modifiedInsets.bottom = 0
return modifiedInsets
}
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if experimentDataSource.isRecordingTrialSection(section) {
return 0
}
return MaterialCardCell.cardInsets.bottom
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .experimentData, .recordingTrial:
guard let displayItem =
experimentDataSource.item(inSection: section, atIndex: indexPath.item) else { return }
delegate?.experimentItemsViewControllerDidSelectItem(displayItem)
default:
return
}
}
// MARK: - ExperimentCardCellDelegate
func experimentCardCellCommentButtonPressed(_ cell: MaterialCardCell) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .experimentData:
guard let displayItem = experimentDataSource.item(inSection: section,
atIndex: indexPath.item) else { return }
delegate?.experimentItemsViewControllerCommentPressedForItem(displayItem)
case .recordingTrial:
return
default:
return
}
}
func experimentCardCellMenuButtonPressed(_ cell: MaterialCardCell, button: MenuButton) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
let section = experimentDataSource.section(atIndex: indexPath.section)
switch section {
case .experimentData, .recordingTrial:
guard let displayItem = experimentDataSource.item(inSection: section,
atIndex: indexPath.item) else { return }
delegate?.experimentItemsViewControllerMenuPressedForItem(displayItem, button: button)
default:
return
}
}
// Unsupported.
func experimentCardCellTimestampButtonPressed(_ cell: MaterialCardCell) {}
// MARK: - ExperimentItemsDataSourceDelegate
func experimentDataSource(_ experimentDataSource: ExperimentItemsDataSource,
didChange changes: [CollectionViewChange],
scrollToIndexPath indexPath: IndexPath?) {
guard isViewVisible else {
collectionView.reloadData()
return
}
// Perform changes.
collectionView.performChanges(changes)
// Scroll to index path if necessary.
guard let indexPath = indexPath else { return }
collectionView.scrollToItem(at: indexPath,
at: collectionViewChangeScrollPosition,
animated: true)
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollDelegate?.scrollViewDidScroll!(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollDelegate?.scrollViewDidEndDecelerating!(scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
scrollDelegate?.scrollViewDidEndDragging!(scrollView, willDecelerate: decelerate)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollDelegate?.scrollViewWillEndDragging!(scrollView,
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
// swiftlint:enable type_body_length
| 0623a146bf758360ad4376a2e90bf1a6 | 41.339286 | 100 | 0.664967 | false | false | false | false |
cornerstonecollege/402 | refs/heads/master | Younseo/CustomViews/CustomViews/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// CustomViews
//
// Created by hoconey on 2016/10/13.
// Copyright © 2016年 younseo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 0, y: 50, width: 100, height: 100)
let circle = FirstCustomView(frame: frame)
//circle.backgroundColor = UIColor.red
self.view.addSubview(circle)
let frame2 = CGRect(x: 200, y: 50, width: 100, height: 100)
let circle2 = FirstCustomView(frame: frame2)
//circle.backgroundColor = UIColor.red
self.view.addSubview(circle2)
let frame3 = CGRect(x: 100, y: 250, width: 100, height: 200)
let circle3 = FirstCustomView(frame: frame3)
//circle.backgroundColor = UIColor.red
self.view.addSubview(circle3)
let circleFrame = CGRect(x: 100, y: 100, width: 100, height: 100)
let circle4 = CircleView(frame: circleFrame)
//circle4.backgroundColor = UIColor.yellow
self.view.addSubview(circle4)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| c5a4d95a6228fbdb0bb19a8a691b8ae2 | 26.6 | 73 | 0.620773 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/core/LifetimeManager.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
x: T, @noescape _ f: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try f()
}
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
x: T, @noescape _ f: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try f(x)
}
extension String {
/// Invoke `f` on the contents of this string, represented as
/// a nul-terminated array of char, ensuring that the array's
/// lifetime extends through the execution of `f`.
public func withCString<Result>(
@noescape f: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.nulTerminatedUTF8.withUnsafeBufferPointer {
try f(UnsafePointer($0.baseAddress))
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(x: T) {
Builtin.fixLifetime(x)
}
/// Invokes `body` with an `UnsafeMutablePointer` to `arg` and returns the
/// result. Useful for calling Objective-C APIs that take "in/out"
/// parameters (and default-constructible "out" parameters) by pointer.
public func withUnsafeMutablePointer<T, Result>(
arg: inout T,
@noescape _ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Like `withUnsafeMutablePointer`, but passes pointers to `arg0` and `arg1`.
public func withUnsafeMutablePointers<A0, A1, Result>(
arg0: inout A0,
_ arg1: inout A1,
@noescape _ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
return try body(
UnsafeMutablePointer<A0>(Builtin.addressof(&arg0)),
UnsafeMutablePointer<A1>(Builtin.addressof(&arg1)))
}
/// Like `withUnsafeMutablePointer`, but passes pointers to `arg0`, `arg1`,
/// and `arg2`.
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
@noescape _ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
return try body(
UnsafeMutablePointer<A0>(Builtin.addressof(&arg0)),
UnsafeMutablePointer<A1>(Builtin.addressof(&arg1)),
UnsafeMutablePointer<A2>(Builtin.addressof(&arg2)))
}
/// Invokes `body` with an `UnsafePointer` to `arg` and returns the
/// result. Useful for calling Objective-C APIs that take "in/out"
/// parameters (and default-constructible "out" parameters) by pointer.
public func withUnsafePointer<T, Result>(
arg: inout T,
@noescape _ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
/// Like `withUnsafePointer`, but passes pointers to `arg0` and `arg1`.
public func withUnsafePointers<A0, A1, Result>(
arg0: inout A0,
_ arg1: inout A1,
@noescape _ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
return try body(
UnsafePointer<A0>(Builtin.addressof(&arg0)),
UnsafePointer<A1>(Builtin.addressof(&arg1)))
}
/// Like `withUnsafePointer`, but passes pointers to `arg0`, `arg1`,
/// and `arg2`.
public func withUnsafePointers<A0, A1, A2, Result>(
arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
@noescape _ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
return try body(
UnsafePointer<A0>(Builtin.addressof(&arg0)),
UnsafePointer<A1>(Builtin.addressof(&arg1)),
UnsafePointer<A2>(Builtin.addressof(&arg2)))
}
| 4ba161b5828d3c327b6b544d121eae2b | 32.450382 | 80 | 0.675491 | false | false | false | false |
guardianproject/poe | refs/heads/master | POE/Classes/Roboto.swift | bsd-3-clause | 1 | //
// Roboto.swift
// POE
//
// Created by Benjamin Erhart on 24.03.17.
// Copyright © 2017 Guardian Project. All rights reserved.
//
import UIKit
enum Roboto {
static let defaultSize: CGFloat = 17
static let regular = "Roboto-Regular"
static let italic = "Roboto-Italic"
static let bold = "Roboto-Bold"
static let boldItalic = "Roboto-BoldItalic"
static let black = "Roboto-Black"
static let blackItalic = "Roboto-BlackItalic"
static let medium = "Roboto-Medium"
static let mediumItalic = "Roboto-MediumItalic"
static let light = "Roboto-Light"
static let lightItalic = "Roboto-LightItalic"
static let thin = "Roboto-Thin"
static let thinItalic = "Roboto-ThinItalic"
static let condensed = "RobotoCondensed-Regular"
static let condensedItalic = "RobotoCondensed-Italic"
static let condensedBold = "RobotoCondensed-Bold"
static let condensedBoldItalic = "RobotoCondensed-BoldItalic"
static let condensedLight = "RobotoCondensed-Light"
static let condensedLightItalic = "RobotoCondensed-LightItalic"
}
/**
Evaluate a given font and replace it with the most adequate font of the Roboto family.
- Parameter oldFont
The original font.
Inspired by [Using custom font for entire iOS app swift](http://stackoverflow.com/questions/28180449/using-custom-font-for-entire-ios-app-swift).
*/
private func replaceFont(_ oldFont: UIFont?) -> UIFont? {
let oldName = oldFont?.fontName.lowercased() ?? ""
var name :String
if oldName.contains("condensed") {
if oldName.contains("bold") || oldName.contains("black") {
name = oldName.contains("italic") ? Roboto.condensedBoldItalic : Roboto.condensedBold
}
else if oldName.contains("light") || oldName.contains("ultralight") || oldName.contains("thin") {
name = oldName.contains("italic") ? Roboto.condensedLightItalic : Roboto.condensedLight
}
else if oldName.contains("italic") {
name = Roboto.condensedItalic
}
else {
name = Roboto.condensed
}
}
else if oldName.contains("bold") {
name = oldName.contains("italic") ? Roboto.boldItalic : Roboto.bold
}
else if oldName.contains("black") {
name = oldName.contains("italic") ? Roboto.blackItalic : Roboto.black
}
else if oldName.contains("medium") {
name = oldName.contains("italic") ? Roboto.mediumItalic : Roboto.medium
}
else if oldName.contains("light") {
name = oldName.contains("italic") ? Roboto.lightItalic : Roboto.light
}
else if oldName.contains("ultralight") || oldName.contains("thin") {
name = oldName.contains("italic") ? Roboto.thinItalic : Roboto.thin
}
else if oldName.contains("italic") {
name = Roboto.italic
}
else {
name = Roboto.regular
}
if let font = UIFont(name: name, size: oldFont?.pointSize ?? Roboto.defaultSize) {
return font
}
return oldFont
}
extension UILabel {
@objc var substituteFont: Bool {
get {
return false
}
set {
self.font = replaceFont(self.font)
}
}
}
extension UITextView {
@objc var substituteFont : Bool {
get {
return false
}
set {
self.font = replaceFont(self.font)
}
}
}
extension UITextField {
@objc var substituteFont : Bool {
get {
return false
}
set {
self.font = replaceFont(self.font)
}
}
}
/**
Taken from
[Can I embed a custom font in a bundle and access it from an ios framework?](http://stackoverflow.com/questions/14735522/can-i-embed-a-custom-font-in-a-bundle-and-access-it-from-an-ios-framework)
*/
private func registerFont(from url: URL) throws {
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
throw NSError(domain: "Could not create font data provider for \(url).", code: -1, userInfo: nil)
}
let font = CGFont(fontDataProvider)
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
throw error!.takeUnretainedValue()
}
}
/**
Inspired by
[Can I embed a custom font in a bundle and access it from an ios framework?](http://stackoverflow.com/questions/14735522/can-i-embed-a-custom-font-in-a-bundle-and-access-it-from-an-ios-framework)
*/
private func fontURLs() -> [URL] {
var urls = [URL]()
// Fortunately, file and font names are identical with the Roboto font family.
let fileNames = [
Roboto.black, Roboto.blackItalic,
Roboto.bold, Roboto.boldItalic,
Roboto.italic,
Roboto.light, Roboto.lightItalic,
Roboto.medium, Roboto.mediumItalic,
Roboto.regular,
Roboto.thin, Roboto.thinItalic,
Roboto.condensedBold, Roboto.condensedBoldItalic,
Roboto.condensedItalic,
Roboto.condensedLight, Roboto.condensedLightItalic,
Roboto.condensed]
fileNames.forEach({
if let url = XibViewController.getBundle().url(forResource: $0, withExtension: "ttf") {
urls.append(url)
}
})
return urls
}
/**
#robotoIt() needs to be called only once.
This flag tracks that.
*/
private var robotoed = false
/**
Loads and injects the Roboto font family dynamically into the app.
Replaces the normal font of UILabels, UITextViews and UITextFields with proper styles of the
Roboto font family.
If the fonts are not properly replaced, ensure that the font files are added to the "POE" target
properly!
*/
func robotoIt() {
if (!robotoed) {
do {
try fontURLs().forEach({ try registerFont(from: $0) })
} catch {
print(error)
}
UILabel.appearance().substituteFont = true
UITextView.appearance().substituteFont = true
UITextField.appearance().substituteFont = true
robotoed = true
// // Debug: Print list of font families and their fonts.
// for family: String in UIFont.familyNames {
// print("\(family)")
// for names: String in UIFont.fontNames(forFamilyName: family) {
// print("== \(names)")
// }
// }
}
}
| d27b514d7167020d762c4181ecf3c921 | 29.681159 | 199 | 0.635648 | false | false | false | false |
raymondshadow/SwiftDemo | refs/heads/master | SwiftApp/DesignMode/DesignMode/ProtoType(原型)/Resume.swift | apache-2.0 | 1 | //
// Resume.swift
// DesignMode
//
// Created by wuyp on 2017/9/12.
// Copyright © 2017年 Raymond. All rights reserved.
//
import Foundation
class WorkExperience: NSObject, NSCopying {
var company: String = ""
var timespan: String = ""
init(company: String, timespan: String) {
self.company = company
self.timespan = timespan
}
func copy(with zone: NSZone? = nil) -> Any {
let new = WorkExperience(company: company, timespan: timespan)
return new
}
}
class Resume: NSObject, NSCopying {
var name: String
var workExperience: WorkExperience
init(name: String, experience: WorkExperience) {
self.name = name
self.workExperience = experience.copy() as! WorkExperience
}
func copy(with zone: NSZone? = nil) -> Any {
let new = Resume(name: name, experience: workExperience)
return new
}
}
| 3a73b87ac3cae87ef0bb8960aa055e43 | 22.641026 | 70 | 0.621475 | false | false | false | false |
mvader/advent-of-code | refs/heads/master | 2021/03/01.swift | mit | 1 | import Foundation
let lines = try String(contentsOfFile: "./input.txt", encoding: .utf8).split(separator: "\n")
let diagnostic = lines.map { line in Int(line, radix: 2)! }
let rowSize = lines.first!.count
let gammaRate = (0 ..< rowSize).map { i in
let mask = 1 << (rowSize - i - 1)
let ones = diagnostic.reduce(0) { acc, n in acc + ((n & mask) > 0 ? 1 : 0) }
return (ones > diagnostic.count / 2) ? mask : 0
}.reduce(0, +)
let epsilonRate = ((1 << rowSize) - 1) ^ gammaRate
print(gammaRate * epsilonRate)
| 502bc348da8f972b368c805c1372dcf3 | 35.428571 | 93 | 0.639216 | false | false | false | false |
Bluthwort/Bluthwort | refs/heads/master | Sources/Classes/Style/UITableViewCellStyle.swift | mit | 1 | //
// UITableViewCellStyle.swift
//
// Copyright (c) 2018 Bluthwort
//
// 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.
//
extension Bluthwort where Base: UITableViewCell {
@discardableResult
public func backgroundView(_ view: UIView?) -> Bluthwort {
// The view used as the background of the cell.
base.backgroundView = view
return self
}
@discardableResult
public func selectedBackgroundView(_ view: UIView?) -> Bluthwort {
// The view used as the background of the cell when it is selected.
base.selectedBackgroundView = view
return self
}
@discardableResult
public func multipleSelectionBackgroundView(_ view: UIView?) -> Bluthwort {
// The background view to use for a selected cell when the table view allows multiple row
// selections.
base.multipleSelectionBackgroundView = view
return self
}
@discardableResult
public func accessoryType(_ type: UITableViewCellAccessoryType) -> Bluthwort {
// The type of standard accessory view the cell should use (normal state).
base.accessoryType = type
return self
}
@discardableResult
public func accessoryView(_ view: UIView?) -> Bluthwort {
// A view that is used, typically as a control, on the right side of the cell (normal state).
base.accessoryView = view
return self
}
@discardableResult
public func editingAccessoryType(_ type: UITableViewCellAccessoryType) -> Bluthwort {
// The type of standard accessory view the cell should use in the table view’s editing state.
base.editingAccessoryType = type
return self
}
@discardableResult
public func editingAccessoryView(_ view: UIView?) -> Bluthwort {
// A view that is used typically as a control on the right side of the cell when it is in
// editing mode.
base.editingAccessoryView = view
return self
}
@discardableResult
public func isSelected(_ flag: Bool, animated: Bool? = nil) -> Bluthwort {
if let animated = animated {
// Sets the selected state of the cell, optionally animating the transition between
// states.
base.setSelected(flag, animated: animated)
} else {
// A Boolean value that indicates whether the cell is selected.
base.isSelected = flag
}
return self
}
@discardableResult
public func selectionStyle(_ style: UITableViewCellSelectionStyle) -> Bluthwort {
// The style of selection for a cell.
base.selectionStyle = style
return self
}
@discardableResult
public func isHighlighted(_ flag: Bool, animated: Bool? = nil) -> Bluthwort {
if let animated = animated {
// Sets the highlighted state of the cell, optionally animating the transition between
// states.
base.setHighlighted(flag, animated: animated)
} else {
// A Boolean value that indicates whether the cell is highlighted.
base.isHighlighted = flag
}
return self
}
@discardableResult
public func isEditing(_ flag: Bool, animated: Bool? = nil) -> Bluthwort {
if let animated = animated {
// Toggles the receiver into and out of editing mode.
base.setEditing(flag, animated: animated)
} else {
// A Boolean value that indicates whether the cell is in an editable state.
base.isEditing = flag
}
return self
}
@discardableResult
public func showsReorderControl(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the cell shows the reordering control.
base.showsReorderControl = flag
return self
}
@available(iOS 11.0, *)
@discardableResult
public func userInteractionEnabledWhileDragging(_ flag: Bool) -> Bluthwort {
// A Boolean value indicating whether users can interact with a cell while it is being dragged.
base.userInteractionEnabledWhileDragging = flag
return self
}
@discardableResult
public func indentationLevel(_ level: Int) -> Bluthwort {
// The indentation level of the cell’s content.
base.indentationLevel = level
return self
}
@discardableResult
public func indentationWidth(_ width: CGFloat) -> Bluthwort {
// The width for each level of indentation of a cell's content.
base.indentationWidth = width
return self
}
@discardableResult
public func shouldIndentWhileEditing(_ flag: Bool) -> Bluthwort {
// A Boolean value that controls whether the cell background is indented when the table view
// is in editing mode.
base.shouldIndentWhileEditing = flag
return self
}
@discardableResult
public func separatorInset(_ inset: UIEdgeInsets) -> Bluthwort {
// The inset values for the cell’s content.
base.separatorInset = inset
return self
}
@discardableResult
public func focusStyle(_ style: UITableViewCellFocusStyle) -> Bluthwort {
// The appearance of the cell when focused.
base.focusStyle = style
return self
}
}
| e6cdab7b09fc3e816734955e117aa8b6 | 35.58046 | 103 | 0.664415 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.