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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Helpers/IconButton+Factory.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireCommonComponents
extension IconButton {
static let width: CGFloat = 64
static let height: CGFloat = 64
static func acceptCall() -> IconButton {
return .init(
icon: .phone,
accessibilityId: "AcceptButton",
backgroundColor: [.normal: SemanticColors.LegacyColors.strongLimeGreen],
iconColor: [.normal: .white],
width: IconButton.width
)
}
static func endCall() -> IconButton {
return .init(
icon: .endCall,
size: .small,
accessibilityId: "LeaveCallButton",
backgroundColor: [.normal: SemanticColors.LegacyColors.vividRed],
iconColor: [.normal: .white],
width: IconButton.width
)
}
static func sendButton() -> IconButton {
let sendButtonIconColor = SemanticColors.Icon.foregroundDefaultWhite
let sendButton = IconButton(
icon: .send,
accessibilityId: "sendButton",
backgroundColor: [.normal: UIColor.accent(),
.highlighted: UIColor.accentDarken,
.disabled: SemanticColors.Button.backgroundSendDisabled],
iconColor: [.normal: sendButtonIconColor,
.highlighted: sendButtonIconColor,
.disabled: sendButtonIconColor]
)
return sendButton
}
fileprivate convenience init(
icon: StyleKitIcon,
size: StyleKitIcon.Size = .tiny,
accessibilityId: String,
backgroundColor: [UIControl.State: UIColor],
iconColor: [UIControl.State: UIColor],
width: CGFloat? = nil
) {
self.init(fontSpec: .smallLightFont)
circular = true
setIcon(icon, size: size, for: .normal)
accessibilityIdentifier = accessibilityId
translatesAutoresizingMaskIntoConstraints = false
for (state, color) in backgroundColor {
setBackgroundImageColor(color, for: state)
}
for (state, color) in iconColor {
setIconColor(color, for: state)
}
borderWidth = 0
if let width = width {
widthAnchor.constraint(equalToConstant: width).isActive = true
heightAnchor.constraint(greaterThanOrEqualToConstant: width).isActive = true
}
}
}
extension UIControl.State: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.rawValue)
}
}
|
826ade976ae1a7029deaa79dfb35e555
| 30.676471 | 88 | 0.626431 | false | false | false | false |
srn214/Floral
|
refs/heads/master
|
Floral/Pods/JXPhotoBrowser/Source/Core/JXPhotoBrowserBaseDelegate.swift
|
mit
|
1
|
//
// JXPhotoBrowserBaseDelegate.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2018/10/14.
//
import Foundation
import UIKit
open class JXPhotoBrowserBaseDelegate: NSObject, JXPhotoBrowserDelegate {
/// 弱引用 PhotoBrowser
open weak var browser: JXPhotoBrowser?
/// 图片内容缩张模式
open var contentMode: UIView.ContentMode = .scaleAspectFill
/// 长按回调。回传参数分别是:浏览器,图片序号,图片对象,手势对象
open var longPressedCallback: ((JXPhotoBrowser, Int, UIImage?, UILongPressGestureRecognizer) -> Void)?
/// 是否Right to left语言
open lazy var isRTLLayout = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft
//
// MARK: - 处理状态栏
//
/// 是否需要遮盖状态栏。默认true
open var isNeedCoverStatusBar = true
/// 保存原windowLevel
open var originWindowLevel: UIWindow.Level?
/// 遮盖状态栏。以改变windowLevel的方式遮盖
/// - parameter cover: true-遮盖;false-不遮盖
open func coverStatusBar(_ cover: Bool) {
guard isNeedCoverStatusBar else {
return
}
guard let window = browser?.view.window ?? UIApplication.shared.keyWindow else {
return
}
if originWindowLevel == nil {
originWindowLevel = window.windowLevel
}
guard let originLevel = originWindowLevel else {
return
}
window.windowLevel = cover ? .statusBar : originLevel
}
//
// MARK: - UICollectionViewDelegate
//
open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? JXPhotoBrowserBaseCell else {
return
}
cell.imageView.contentMode = contentMode
// 绑定 Cell 回调事件
// 单击
cell.clickCallback = { _ in
self.dismiss()
}
// 拖
cell.panChangedCallback = { scale in
// 实测用scale的平方,效果比线性好些
let alpha = scale * scale
self.browser?.transDelegate.maskAlpha = alpha
// 半透明时重现状态栏,否则遮盖状态栏
self.coverStatusBar(scale > 0.95)
}
// 拖完松手
cell.panReleasedCallback = { isDown in
if isDown {
self.dismiss()
} else {
self.browser?.transDelegate.maskAlpha = 1.0
self.coverStatusBar(true)
}
}
// 长按
weak var weakCell = cell
cell.longPressedCallback = { gesture in
if let browser = self.browser {
self.longPressedCallback?(browser, indexPath.item, weakCell?.imageView.image, gesture)
}
}
}
/// 关闭
private func dismiss() {
self.browser?.dismiss(animated: true, completion: nil)
}
/// scrollView滑动
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
var value: CGFloat = 0
if isRTLLayout {
value = (scrollView.contentSize.width - scrollView.contentOffset.x - scrollView.bounds.width / 2) / scrollView.bounds.width
} else {
value = (scrollView.contentOffset.x + scrollView.bounds.width / 2) / scrollView.bounds.width
}
browser?.pageIndex = max(0, Int(value))
}
/// 取当前显示页的内容视图。比如是 ImageView.
open func displayingContentView(_ browser: JXPhotoBrowser, pageIndex: Int) -> UIView? {
let indexPath = IndexPath.init(item: pageIndex, section: 0)
let cell = browser.collectionView.cellForItem(at: indexPath) as? JXPhotoBrowserBaseCell
return cell?.imageView
}
/// 取转场动画视图
open func transitionZoomView(_ browser: JXPhotoBrowser, pageIndex: Int) -> UIView? {
let indexPath = IndexPath.init(item: pageIndex, section: 0)
let cell = browser.collectionView.cellForItem(at: indexPath) as? JXPhotoBrowserBaseCell
return UIImageView(image: cell?.imageView.image)
}
open func photoBrowser(_ browser: JXPhotoBrowser, pageIndexDidChanged pageIndex: Int) {
// Empty.
}
open func photoBrowserViewDidLoad(_ browser: JXPhotoBrowser) {
// Empty.
}
open func photoBrowser(_ browser: JXPhotoBrowser, viewWillAppear animated: Bool) {
// 遮盖状态栏
coverStatusBar(true)
}
open func photoBrowserViewWillLayoutSubviews(_ browser: JXPhotoBrowser) {
// Empty.
}
open func photoBrowserViewDidLayoutSubviews(_ browser: JXPhotoBrowser) {
// Empty.
}
open func photoBrowser(_ browser: JXPhotoBrowser, viewDidAppear animated: Bool) {
// Empty.
}
open func photoBrowser(_ browser: JXPhotoBrowser, viewWillDisappear animated: Bool) {
// 还原状态栏
coverStatusBar(false)
}
open func photoBrowser(_ browser: JXPhotoBrowser, viewDidDisappear animated: Bool) {
// Empty.
}
open func dismissPhotoBrowser(_ browser: JXPhotoBrowser) {
self.dismiss()
}
open func photoBrowserDidReloadData(_ browser: JXPhotoBrowser) {
// Empty.
}
}
|
b1e8e6d3df3a49efb32b98047b033c9e
| 30.012195 | 138 | 0.613645 | false | false | false | false |
hollance/swift-algorithm-club
|
refs/heads/master
|
Multiset/Multiset.playground/Sources/Multiset.swift
|
mit
|
3
|
//
// Multiset.swift
// Multiset
//
// Created by Simon Whitaker on 28/08/2017.
//
import Foundation
public struct Multiset<T: Hashable> {
private var storage: [T: UInt] = [:]
public private(set) var count: UInt = 0
public init() {}
public init<C: Collection>(_ collection: C) where C.Element == T {
for element in collection {
self.add(element)
}
}
public mutating func add (_ elem: T) {
storage[elem, default: 0] += 1
count += 1
}
public mutating func remove (_ elem: T) {
if let currentCount = storage[elem] {
if currentCount > 1 {
storage[elem] = currentCount - 1
} else {
storage.removeValue(forKey: elem)
}
count -= 1
}
}
public func isSubSet (of superset: Multiset<T>) -> Bool {
for (key, count) in storage {
let supersetcount = superset.storage[key] ?? 0
if count > supersetcount {
return false
}
}
return true
}
public func count(for key: T) -> UInt {
return storage[key] ?? 0
}
public var allItems: [T] {
var result = [T]()
for (key, count) in storage {
for _ in 0 ..< count {
result.append(key)
}
}
return result
}
}
// MARK: - Equatable
extension Multiset: Equatable {
public static func == (lhs: Multiset<T>, rhs: Multiset<T>) -> Bool {
if lhs.storage.count != rhs.storage.count {
return false
}
for (lkey, lcount) in lhs.storage {
let rcount = rhs.storage[lkey] ?? 0
if lcount != rcount {
return false
}
}
return true
}
}
// MARK: - ExpressibleByArrayLiteral
extension Multiset: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: T...) {
self.init(elements)
}
}
|
a2b9c6c06d072a174c6ec5f4904a8d84
| 19.761905 | 70 | 0.585436 | false | false | false | false |
nthery/SwiftForth
|
refs/heads/master
|
SwiftForth/main.swift
|
mit
|
1
|
//
// Forth read-eval-print loop
//
import Foundation
import SwiftForthKit
class ErrorPrinter : ForthErrorHandler {
func HandleError(msg: String) {
println("ERROR: \(msg)")
}
}
class StdinLineReader {
var stdin = NSFileHandle.fileHandleWithStandardInput()
func read() -> String {
// TODO: broken: read whole file when input is not console
return NSString(data: stdin.availableData, encoding: NSUTF8StringEncoding)!
}
}
func repl() {
var reader = StdinLineReader()
var evaluator = ForthEvaluator()
evaluator.setErrorHandler(ErrorPrinter())
while true {
println("[ \(evaluator.argStack) ]")
print("==> ")
let input = reader.read()
if input.isEmpty {
break
}
evaluator.eval(input)
print(evaluator.getAndResetOutput())
}
}
repl()
|
930724f89bb345bfa11c6db48dec1b7b
| 20.825 | 83 | 0.620413 | false | false | false | false |
zisko/swift
|
refs/heads/master
|
test/SILGen/closures.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
import Swift
var zero = 0
// <rdar://problem/15921334>
// CHECK-LABEL: sil hidden @$S8closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}}F : $@convention(thin) <A, R> () -> @owned @callee_guaranteed (@in A) -> @out R {
func return_local_generic_function_without_captures<A, R>() -> (A) -> R {
func f(_: A) -> R {
Builtin.int_trap()
}
// CHECK: [[FN:%.*]] = function_ref @$S8closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1
// CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [callee_guaranteed] [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1
// CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_guaranteed (@in A) -> @out R
return f
}
func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R {
func f(_: A) -> R {
_ = a
}
return f
}
// CHECK-LABEL: sil hidden @$S8closures17read_only_captureyS2iF : $@convention(thin) (Int) -> Int {
func read_only_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// SEMANTIC ARC TODO: This is incorrect. We need to do the project_box on the copy.
// CHECK: [[PROJECT:%.*]] = project_box [[XBOX]]
// CHECK: store [[X]] to [trivial] [[PROJECT]]
func cap() -> Int {
return x
}
return cap()
// CHECK: [[XBOX_BORROW:%.*]] = begin_borrow [[XBOX]]
// SEMANTIC ARC TODO: See above. This needs to happen on the copy_valued box.
// CHECK: mark_function_escape [[PROJECT]]
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$S8closures17read_only_capture.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX_BORROW]])
// CHECK: end_borrow [[XBOX_BORROW]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: } // end sil function '$S8closures17read_only_captureyS2iF'
// CHECK: sil private @[[CAP_NAME]]
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: return [[X]]
// } // end sil function '[[CAP_NAME]]'
// SEMANTIC ARC TODO: This is a place where we have again project_box too early.
// CHECK-LABEL: sil hidden @$S8closures16write_to_captureyS2iF : $@convention(thin) (Int) -> Int {
func write_to_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: store [[X]] to [trivial] [[XBOX_PB]]
// CHECK: [[X2BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[X2BOX_PB:%.*]] = project_box [[X2BOX]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*Int
// CHECK: copy_addr [[ACCESS]] to [initialization] [[X2BOX_PB]]
// CHECK: [[X2BOX_BORROW:%.*]] = begin_borrow [[X2BOX]]
// SEMANTIC ARC TODO: This next mark_function_escape should be on a projection from X2BOX_BORROW.
// CHECK: mark_function_escape [[X2BOX_PB]]
var x2 = x
func scribble() {
x2 = zero
}
scribble()
// CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:\$S8closures16write_to_capture.*]] : $@convention(thin) (@guaranteed { var Int }) -> ()
// CHECK: apply [[SCRIB]]([[X2BOX_BORROW]])
// SEMANTIC ARC TODO: This should load from X2BOX_BORROW project. There is an
// issue here where after a copy_value, we need to reassign a projection in
// some way.
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[X2BOX_PB]] : $*Int
// CHECK: [[RET:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: destroy_value [[X2BOX]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
return x2
}
// CHECK: } // end sil function '$S8closures16write_to_captureyS2iF'
// CHECK: sil private @[[SCRIB_NAME]]
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[XADDR]] : $*Int
// CHECK: assign {{%[0-9]+}} to [[ACCESS]]
// CHECK: return
// CHECK: } // end sil function '[[SCRIB_NAME]]'
// CHECK-LABEL: sil hidden @$S8closures21multiple_closure_refs{{[_0-9a-zA-Z]*}}F
func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) {
var x = x
func cap() -> Int {
return x
}
return (cap, cap)
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$S8closures21multiple_closure_refs.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [callee_guaranteed] [[CAP]]
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$S8closures21multiple_closure_refs.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [callee_guaranteed] [[CAP]]
// CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}})
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @$S8closures18capture_local_funcySiycycSiF : $@convention(thin) (Int) -> @owned @callee_guaranteed () -> @owned @callee_guaranteed () -> Int {
func capture_local_func(_ x: Int) -> () -> () -> Int {
// CHECK: bb0([[ARG:%.*]] : @trivial $Int):
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: store [[ARG]] to [trivial] [[XBOX_PB]]
func aleph() -> Int { return x }
func beth() -> () -> Int { return aleph }
// CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:\$S8closures18capture_local_funcySiycycSiF4bethL_SiycyF]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY.
// CHECK: mark_function_escape [[XBOX_PB]]
// CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [callee_guaranteed] [[BETH_REF]]([[XBOX_COPY]])
return beth
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[BETH_CLOSURE]]
}
// CHECK: } // end sil function '$S8closures18capture_local_funcySiycycSiF'
// CHECK: sil private @[[ALEPH_NAME:\$S8closures18capture_local_funcySiycycSiF5alephL_SiyF]] : $@convention(thin) (@guaranteed { var Int }) -> Int {
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: sil private @[[BETH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int {
// CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: This should be on a PB from XBOX_COPY.
// CHECK: mark_function_escape [[XBOX_PB]]
// CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [callee_guaranteed] [[ALEPH_REF]]([[XBOX_COPY]])
// CHECK: return [[ALEPH_CLOSURE]]
// CHECK: } // end sil function '[[BETH_NAME]]'
// CHECK-LABEL: sil hidden @$S8closures22anon_read_only_capture{{[_0-9a-zA-Z]*}}F
func anon_read_only_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
return ({ x })()
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures22anon_read_only_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int
// -- apply expression
// CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]])
// -- cleanup
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: sil private @[[CLOSURE_NAME]]
// CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Int):
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: return [[X]]
// CHECK-LABEL: sil hidden @$S8closures21small_closure_capture{{[_0-9a-zA-Z]*}}F
func small_closure_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
return { x }()
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures21small_closure_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int
// -- apply expression
// CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]])
// -- cleanup
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: sil private @[[CLOSURE_NAME]]
// CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Int):
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]]
// CHECK: return [[X]]
// CHECK-LABEL: sil hidden @$S8closures35small_closure_capture_with_argument{{[_0-9a-zA-Z]*}}F
func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int {
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
return { x + $0 }
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @guaranteed { var Int }) -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [callee_guaranteed] [[ANON]]([[XBOX_COPY]])
// -- return
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[ANON_CLOSURE_APP]]
}
// FIXME(integers): the following checks should be updated for the new way +
// gets invoked. <rdar://problem/29939484>
// XCHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int, @owned { var Int }) -> Int
// XCHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : ${ var Int }):
// XCHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// XCHECK: [[PLUS:%[0-9]+]] = function_ref @$Ss1poiS2i_SitF{{.*}}
// XCHECK: [[LHS:%[0-9]+]] = load [trivial] [[XADDR]]
// XCHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]])
// XCHECK: destroy_value [[XBOX]]
// XCHECK: return [[RET]]
// CHECK-LABEL: sil hidden @$S8closures24small_closure_no_capture{{[_0-9a-zA-Z]*}}F
func small_closure_no_capture() -> (_ y: Int) -> Int {
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$S8closures24small_closure_no_captureS2icyFS2icfU_]] : $@convention(thin) (Int) -> Int
// CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_guaranteed (Int) -> Int
// CHECK: return [[ANON_THICK]]
return { $0 }
}
// CHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int
// CHECK: bb0([[YARG:%[0-9]+]] : @trivial $Int):
// CHECK-LABEL: sil hidden @$S8closures17uncaptured_locals{{[_0-9a-zA-Z]*}}F :
func uncaptured_locals(_ x: Int) -> (Int, Int) {
var x = x
// -- locals without captures are stack-allocated
// CHECK: bb0([[XARG:%[0-9]+]] : @trivial $Int):
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XADDR]]
// CHECK: store [[XARG]] to [trivial] [[PB]]
var y = zero
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
return (x, y)
}
class SomeClass {
var x : Int = zero
init() {
x = { self.x }() // Closing over self.
}
}
// Closures within destructors <rdar://problem/15883734>
class SomeGenericClass<T> {
deinit {
var i: Int = zero
// CHECK: [[C1REF:%[0-9]+]] = function_ref @$S8closures16SomeGenericClassCfdSiyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> Int
// CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int
var x = { i + zero } ()
// CHECK: [[C2REF:%[0-9]+]] = function_ref @$S8closures16SomeGenericClassCfdSiyXEfU0_ : $@convention(thin) () -> Int
// CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int
var y = { zero } ()
// CHECK: [[C3REF:%[0-9]+]] = function_ref @$S8closures16SomeGenericClassCfdyyXEfU1_ : $@convention(thin) <τ_0_0> () -> ()
// CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> ()
var z = { _ = T.self } ()
}
// CHECK-LABEL: sil private @$S8closures16SomeGenericClassCfdSiyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> Int
// CHECK-LABEL: sil private @$S8closures16SomeGenericClassCfdSiyXEfU0_ : $@convention(thin) () -> Int
// CHECK-LABEL: sil private @$S8closures16SomeGenericClassCfdyyXEfU1_ : $@convention(thin) <T> () -> ()
}
// This is basically testing that the constraint system ranking
// function conversions as worse than others, and therefore performs
// the conversion within closures when possible.
class SomeSpecificClass : SomeClass {}
func takesSomeClassGenerator(_ fn : () -> SomeClass) {}
func generateWithConstant(_ x : SomeSpecificClass) {
takesSomeClassGenerator({ x })
}
// CHECK-LABEL: sil private @$S8closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CyXEfU_ : $@convention(thin) (@guaranteed SomeSpecificClass) -> @owned SomeClass {
// CHECK: bb0([[T0:%.*]] : @guaranteed $SomeSpecificClass):
// CHECK: debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1
// CHECK: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK: [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass
// CHECK: return [[T0_COPY_CASTED]]
// CHECK: } // end sil function '$S8closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CyXEfU_'
// Check the annoying case of capturing 'self' in a derived class 'init'
// method. We allocate a mutable box to deal with 'self' potentially being
// rebound by super.init, but 'self' is formally immutable and so is captured
// by value. <rdar://problem/15599464>
class Base {}
class SelfCapturedInInit : Base {
var foo : () -> SelfCapturedInInit
// CHECK-LABEL: sil hidden @$S8closures18SelfCapturedInInitC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit {
// CHECK: bb0([[SELF:%.*]] : @owned $SelfCapturedInInit):
//
// First create our initial value for self.
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SelfCapturedInInit }, let, name "self"
// CHECK: [[UNINIT_SELF:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: store [[SELF]] to [init] [[PB_SELF_BOX]]
//
// Then perform the super init sequence.
// CHECK: [[TAKEN_SELF:%.*]] = load [take] [[PB_SELF_BOX]]
// CHECK: [[UPCAST_TAKEN_SELF:%.*]] = upcast [[TAKEN_SELF]]
// CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_TAKEN_SELF]]) : $@convention(method) (@owned Base) -> @owned Base
// CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $Base to $SelfCapturedInInit
// CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_SELF_BOX]]
//
// Finally put self in the closure.
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_SELF_BOX]]
// CHECK: [[COPIED_SELF:%.*]] = load [copy] [[PB_SELF_BOX]]
// CHECK: [[FOO_VALUE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[COPIED_SELF]]) : $@convention(thin) (@guaranteed SelfCapturedInInit) -> @owned SelfCapturedInInit
// CHECK: [[FOO_LOCATION:%.*]] = ref_element_addr [[BORROWED_SELF]]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[FOO_LOCATION]] : $*@callee_guaranteed () -> @owned SelfCapturedInInit
// CHECK: assign [[FOO_VALUE]] to [[ACCESS]]
override init() {
super.init()
foo = { self }
}
}
func takeClosure(_ fn: () -> Int) -> Int { return fn() }
class TestCaptureList {
var x = zero
func testUnowned() {
let aLet = self
takeClosure { aLet.x }
takeClosure { [unowned aLet] in aLet.x }
takeClosure { [weak aLet] in aLet!.x }
var aVar = self
takeClosure { aVar.x }
takeClosure { [unowned aVar] in aVar.x }
takeClosure { [weak aVar] in aVar!.x }
takeClosure { self.x }
takeClosure { [unowned self] in self.x }
takeClosure { [weak self] in self!.x }
takeClosure { [unowned newVal = TestCaptureList()] in newVal.x }
takeClosure { [weak newVal = TestCaptureList()] in newVal!.x }
}
}
class ClassWithIntProperty { final var x = 42 }
func closeOverLetLValue() {
let a : ClassWithIntProperty
a = ClassWithIntProperty()
takeClosure { a.x }
}
// The let property needs to be captured into a temporary stack slot so that it
// is loadable even though we capture the value.
// CHECK-LABEL: sil private @$S8closures18closeOverLetLValueyyFSiyXEfU_ : $@convention(thin) (@guaranteed ClassWithIntProperty) -> Int {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithIntProperty):
// CHECK: [[TMP_CLASS_ADDR:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1
// CHECK: [[COPY_ARG:%.*]] = copy_value [[ARG]]
// CHECK: store [[COPY_ARG]] to [init] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[BORROWED_LOADED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]]
// CHECK: [[INT_IN_CLASS_ADDR:%.*]] = ref_element_addr [[BORROWED_LOADED_CLASS]] : $ClassWithIntProperty, #ClassWithIntProperty.x
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[INT_IN_CLASS_ADDR]] : $*Int
// CHECK: [[INT_IN_CLASS:%.*]] = load [trivial] [[ACCESS]] : $*Int
// CHECK: end_borrow [[BORROWED_LOADED_CLASS]] from [[LOADED_CLASS]]
// CHECK: destroy_value [[LOADED_CLASS]]
// CHECK: destroy_addr [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: dealloc_stack %1 : $*ClassWithIntProperty
// CHECK: return [[INT_IN_CLASS]]
// CHECK: } // end sil function '$S8closures18closeOverLetLValueyyFSiyXEfU_'
// GUARANTEED-LABEL: sil private @$S8closures18closeOverLetLValueyyFSiyXEfU_ : $@convention(thin) (@guaranteed ClassWithIntProperty) -> Int {
// GUARANTEED: bb0(%0 : @guaranteed $ClassWithIntProperty):
// GUARANTEED: [[TMP:%.*]] = alloc_stack $ClassWithIntProperty
// GUARANTEED: [[COPY:%.*]] = copy_value %0 : $ClassWithIntProperty
// GUARANTEED: store [[COPY]] to [init] [[TMP]] : $*ClassWithIntProperty
// GUARANTEED: [[LOADED_COPY:%.*]] = load [copy] [[TMP]]
// GUARANTEED: [[BORROWED:%.*]] = begin_borrow [[LOADED_COPY]]
// GUARANTEED: end_borrow [[BORROWED]] from [[LOADED_COPY]]
// GUARANTEED: destroy_value [[LOADED_COPY]]
// GUARANTEED: destroy_addr [[TMP]]
// GUARANTEED: } // end sil function '$S8closures18closeOverLetLValueyyFSiyXEfU_'
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
mutating func mutatingMethod() {
// This should not capture the refcount of the self shadow.
takesNoEscapeClosure { x = 42; return x }
}
}
// Check that the address of self is passed in, but not the refcount pointer.
// CHECK-LABEL: sil hidden @$S8closures24StructWithMutatingMethodV08mutatingE0{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*StructWithMutatingMethod):
// CHECK: [[CLOSURE:%[0-9]+]] = function_ref @$S8closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int
// CHECK: partial_apply [callee_guaranteed] [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int
// Check that the closure body only takes the pointer.
// CHECK-LABEL: sil private @$S8closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int {
// CHECK: bb0(%0 : @trivial $*StructWithMutatingMethod):
class SuperBase {
func boom() {}
}
class SuperSub : SuperBase {
override func boom() {}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1ayyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1a[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1ayyF'
func a() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]])
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func a1() {
self.boom()
super.boom()
}
a1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1byyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1b[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1byyF'
func b() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1b.*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[ARG]])
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func b1() {
// CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> ()
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase)
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
func b2() {
self.boom()
super.boom()
}
b2()
}
b1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1cyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1c[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]])
// CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]]
// CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]]
// CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]]
// CHECK: apply [[B]]()
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[PA_COPY]]
// CHECK: end_borrow [[BORROWED_PA]] from [[PA]]
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$S8closures8SuperSubC1cyyF'
func c() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> ()
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let c1 = { () -> Void in
self.boom()
super.boom()
}
c1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1dyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1d[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]])
// CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]]
// CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]]
// CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]]
// CHECK: apply [[B]]()
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[PA_COPY]]
// CHECK: end_borrow [[BORROWED_PA]] from [[PA]]
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$S8closures8SuperSubC1dyyF'
func d() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1d.*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[ARG]])
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let d1 = { () -> Void in
// CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
func d2() {
super.boom()
}
d2()
}
d1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1eyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME1:\$S8closures8SuperSubC1e[_0-9a-zA-Z]*]] : $@convention(thin)
// CHECK: = apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1eyyF'
func e() {
// CHECK: sil private @[[INNER_FUNC_NAME1]] : $@convention(thin)
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME2:\$S8closures8SuperSubC1e.*]] : $@convention(thin)
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]])
// CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]]
// CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]]
// CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]]
// CHECK: apply [[B]]() : $@callee_guaranteed () -> ()
// CHECK: end_borrow [[B]]
// CHECK: destroy_value [[PA_COPY]]
// CHECK: end_borrow [[BORROWED_PA]] from [[PA]]
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '[[INNER_FUNC_NAME1]]'
func e1() {
// CHECK: sil private @[[INNER_FUNC_NAME2]] : $@convention(thin)
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPERCAST:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPERCAST:%.*]] = begin_borrow [[ARG_COPY_SUPERCAST]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPERCAST]])
// CHECK: destroy_value [[ARG_COPY_SUPERCAST]]
// CHECK: return
// CHECK: } // end sil function '[[INNER_FUNC_NAME2]]'
let e2 = {
super.boom()
}
e2()
}
e1()
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1fyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1fyyFyycfU_]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]])
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$S8closures8SuperSubC1fyyF'
func f() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1fyyFyycfU_yyKXKfu_]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]])
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA]]
// CHECK: [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[CVT]])
// CHECK: [[REABSTRACT_CVT:%.*]] = convert_escape_to_noescape [[REABSTRACT_PA]]
// CHECK: [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @$Ss2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
// CHECK: try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
// CHECK: [[NORMAL_BB]]{{.*}}
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let f1 = {
// CHECK: sil private [transparent] @[[INNER_FUNC_2]]
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
nil ?? super.boom()
}
}
// CHECK-LABEL: sil hidden @$S8closures8SuperSubC1gyyF : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$S8closures8SuperSubC1g[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: = apply [[INNER]]([[SELF]])
// CHECK: } // end sil function '$S8closures8SuperSubC1gyyF'
func g() {
// CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$S8closures8SuperSubC1g.*]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]])
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA]] : $@callee_guaranteed () -> @error Error to $@noescape @callee_guaranteed () -> @error Error
// CHECK: [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CVT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> @error Error) -> (@out (), @error Error)
// CHECK: [[REABSTRACT_CVT:%.*]] = convert_escape_to_noescape [[REABSTRACT_PA]]
// CHECK: [[TRY_APPLY_FUNC:%.*]] = function_ref @$Ss2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
// CHECK: try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
// CHECK: [[NORMAL_BB]]{{.*}}
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func g1() {
// CHECK: sil private [transparent] @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
nil ?? super.boom()
}
g1()
}
}
// CHECK-LABEL: sil hidden @$S8closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> ()
// -- We enter with an assumed strong +1.
// CHECK: bb0([[SELF:%.*]] : @guaranteed $UnownedSelfNestedCapture):
// CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box ${ var @sil_unowned UnownedSelfNestedCapture }
// CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]]
// -- strong +2
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_COPY]] :
// -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here.
// -- strong +2, unowned +1
// CHECK: [[UNOWNED_SELF_COPY:%.*]] = copy_value [[UNOWNED_SELF]]
// CHECK: store [[UNOWNED_SELF_COPY]] to [init] [[PB]]
// SEMANTIC ARC TODO: This destroy_value should probably be /after/ the load from PB on the next line.
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[UNOWNED_SELF:%.*]] = load_borrow [[PB]]
// -- strong +2, unowned +1
// CHECK: [[SELF:%.*]] = copy_unowned_value [[UNOWNED_SELF]]
// CHECK: end_borrow [[UNOWNED_SELF]] from [[PB]]
// CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]]
// -- strong +2, unowned +2
// CHECK: [[UNOWNED_SELF2_COPY:%.*]] = copy_value [[UNOWNED_SELF2]]
// -- strong +1, unowned +2
// CHECK: destroy_value [[SELF]]
// -- closure takes unowned ownership
// CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[UNOWNED_SELF2_COPY]])
// CHECK: [[OUTER_CONVERT:%.*]] = convert_escape_to_noescape [[OUTER_CLOSURE]]
// -- call consumes closure
// -- strong +1, unowned +1
// CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CONVERT]]
// CHECK: [[B:%.*]] = begin_borrow [[INNER_CLOSURE]]
// CHECK: [[CONSUMED_RESULT:%.*]] = apply [[B]]()
// CHECK: destroy_value [[CONSUMED_RESULT]]
// CHECK: destroy_value [[INNER_CLOSURE]]
// -- destroy_values unowned self in box
// -- strong +1, unowned +0
// CHECK: destroy_value [[OUTER_SELF_CAPTURE]]
// -- strong +0, unowned +0
// CHECK: } // end sil function '$S8closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F'
// -- outer closure
// -- strong +0, unowned +1
// CHECK: sil private @[[OUTER_CLOSURE_FUN:\$S8closures24UnownedSelfNestedCaptureC06nestedE0yyFACycyXEfU_]] : $@convention(thin) (@guaranteed @sil_unowned UnownedSelfNestedCapture) -> @owned @callee_guaranteed () -> @owned UnownedSelfNestedCapture {
// CHECK: bb0([[CAPTURED_SELF:%.*]] : @guaranteed $@sil_unowned UnownedSelfNestedCapture):
// -- strong +0, unowned +2
// CHECK: [[CAPTURED_SELF_COPY:%.*]] = copy_value [[CAPTURED_SELF]] :
// -- closure takes ownership of unowned ref
// CHECK: [[INNER_CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CAPTURED_SELF_COPY]])
// -- strong +0, unowned +1 (claimed by closure)
// CHECK: return [[INNER_CLOSURE]]
// CHECK: } // end sil function '[[OUTER_CLOSURE_FUN]]'
// -- inner closure
// -- strong +0, unowned +1
// CHECK: sil private @[[INNER_CLOSURE_FUN:\$S8closures24UnownedSelfNestedCaptureC06nestedE0yyFACycyXEfU_ACycfU_]] : $@convention(thin) (@guaranteed @sil_unowned UnownedSelfNestedCapture) -> @owned UnownedSelfNestedCapture {
// CHECK: bb0([[CAPTURED_SELF:%.*]] : @guaranteed $@sil_unowned UnownedSelfNestedCapture):
// -- strong +1, unowned +1
// CHECK: [[SELF:%.*]] = copy_unowned_value [[CAPTURED_SELF:%.*]] :
// -- strong +1, unowned +0 (claimed by return)
// CHECK: return [[SELF]]
// CHECK: } // end sil function '[[INNER_CLOSURE_FUN]]'
class UnownedSelfNestedCapture {
func nestedCapture() {
{[unowned self] in { self } }()()
}
}
// Check that capturing 'self' via a 'super' call also captures the generic
// signature if the base class is concrete and the derived class is generic
class ConcreteBase {
func swim() {}
}
// CHECK-LABEL: sil private @$S8closures14GenericDerivedC4swimyyFyyXEfU_ : $@convention(thin) <Ocean> (@guaranteed GenericDerived<Ocean>) -> ()
// CHECK: bb0([[ARG:%.*]] : @guaranteed $GenericDerived<Ocean>):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $GenericDerived<Ocean> to $ConcreteBase
// CHECK: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[METHOD:%.*]] = function_ref @$S8closures12ConcreteBaseC4swimyyF
// CHECK: apply [[METHOD]]([[BORROWED_ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> ()
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: } // end sil function '$S8closures14GenericDerivedC4swimyyFyyXEfU_'
class GenericDerived<Ocean> : ConcreteBase {
override func swim() {
withFlotationAid {
super.swim()
}
}
func withFlotationAid(_ fn: () -> ()) {}
}
// Don't crash on this
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258() {
r25993258_helper { _ in () }
}
// rdar://29810997
//
// Using a let from a closure in an init was causing the type-checker
// to produce invalid AST: 'self.fn' was an l-value, but 'self' was already
// loaded to make an r-value. This was ultimately because CSApply was
// building the member reference correctly in the context of the closure,
// where 'fn' is not settable, but CSGen / CSSimplify was processing it
// in the general DC of the constraint system, i.e. the init, where
// 'fn' *is* settable.
func r29810997_helper(_ fn: (Int) -> Int) -> Int { return fn(0) }
struct r29810997 {
private let fn: (Int) -> Int
private var x: Int
init(function: @escaping (Int) -> Int) {
fn = function
x = r29810997_helper { fn($0) }
}
}
// DI will turn this into a direct capture of the specific stored property.
// CHECK-LABEL: sil hidden @$S8closures16r29810997_helperyS3iXEF : $@convention(thin) (@noescape @callee_guaranteed (Int) -> Int) -> Int
|
7057685256d96bc2e8d94fa003265191
| 50.437421 | 285 | 0.60002 | false | false | false | false |
TedMore/FoodTracker
|
refs/heads/master
|
FoodTracker/RatingControl.swift
|
apache-2.0
|
1
|
//
// RatingControl.swift
// FoodTracker
//
// Created by TedChen on 10/18/15.
// Copyright © 2015 LEON. All rights reserved.
//
import UIKit
class RatingControl: UIView {
// MARK: Properties
var rating = 0 {
didSet {
setNeedsLayout()
}
}
var ratingButtons = [UIButton]()
var spacing = 5
var stars = 5
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let filledStarImage = UIImage(named: "filledStar")
let emptyStarImage = UIImage(named: "emptyStar")
for _ in 0..<stars {
let button = UIButton()
button.setImage(emptyStarImage, forState: .Normal)
button.setImage(filledStarImage, forState: .Selected)
button.setImage(filledStarImage, forState: [.Highlighted, .Selected])
button.adjustsImageWhenHighlighted = false
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
ratingButtons += [button]
addSubview(button)
}
}
override func layoutSubviews() {
// Set the button's width and height to a square the size of the frame's height.
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
// Offset each button's origin by the length of the button plus spacing.
for (index, button) in ratingButtons.enumerate() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionStates()
}
override func intrinsicContentSize() -> CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + spacing) * stars
return CGSize(width: width, height: buttonSize)
}
// MARK: Button Action
func ratingButtonTapped(button: UIButton) {
rating = ratingButtons.indexOf(button)! + 1
updateButtonSelectionStates()
}
func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerate() {
// If the index of a button is less than the rating, that button should be selected.
button.selected = index < rating
}
}
}
|
bdac2ad63aa71683a4a7b2fa4bfb4eb0
| 30.584416 | 121 | 0.601151 | false | false | false | false |
ejeinc/MetalScope
|
refs/heads/master
|
Sources/RenderLoop.swift
|
mit
|
1
|
//
// PlayerRenderLoop.swift
// MetalScope
//
// Created by Jun Tanaka on 2017/02/03.
// Copyright © 2017 eje Inc. All rights reserved.
//
import QuartzCore
public final class RenderLoop {
public let queue: DispatchQueue
public var isPaused: Bool {
return displayLink.isPaused
}
private let action: (TimeInterval) -> Void
private lazy var displayLink: CADisplayLink = {
let link = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
link.add(to: .main, forMode: .commonModes)
link.isPaused = true
return link
}()
public init(queue: DispatchQueue = DispatchQueue(label: "com.eje-c.MetalScope.RenderLoop.queue"), action: @escaping (_ targetTime: TimeInterval) -> Void) {
self.queue = queue
self.action = action
}
public func pause() {
displayLink.isPaused = true
}
public func resume() {
displayLink.isPaused = false
}
@objc private func handleDisplayLink(_ sender: CADisplayLink) {
let time: TimeInterval
if #available(iOS 10, *) {
time = sender.targetTimestamp
} else {
time = sender.timestamp + sender.duration
}
queue.async { [weak self] in
self?.action(time)
}
}
}
|
f9c0733fd66b5598b3101e675fa69112
| 24.745098 | 159 | 0.615385 | false | false | false | false |
tomasharkema/HoelangTotTrein.iOS
|
refs/heads/develop
|
HoelangTotTrein/Array+HLTT.swift
|
apache-2.0
|
1
|
//
// Array+HLTT.swift
// HoelangTotTrein
//
// Created by Tomas Harkema on 18-02-15.
// Copyright (c) 2015 Tomas Harkema. All rights reserved.
//
import Foundation
extension Array {
func slice(n:Int) -> [T] {
if n == -1 {
return self
}
var objects: [T] = []
var index = 0
for obj in self {
if index == n {
return objects
} else {
objects.append(obj)
index++
}
}
return objects
}
func contains<T : Equatable>(obj: T) -> Bool {
return self.filter({$0 as? T == obj}).count > 0
}
}
|
9ad3a2db918405e6192bac5b8647ca6c
| 14.842105 | 58 | 0.514143 | false | false | false | false |
ochan1/OC-PublicCode
|
refs/heads/master
|
Tip Calc to Currency Converter/TipPro/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TipPro
//
// Created by Dion Larson on 9/23/16.
// Copyright © 2016 Make School. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipSelector: UISegmentedControl!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var baseAmountField: UITextField!
@IBAction func calculateTip(_ sender: AnyObject) {
let conversionRates = [1.328, 1.32, 3.673]
if va baseAmount = Double(baseAmountField.text!) {
resultLabel.text = String(format: "%.2f", baseAmount = conversionRates[tipSelector.selectedSegmentIndex])
}
} else {
resultLabel.text = "0.00"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// "IBActions" are functions
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
|
7238a0547cde7ec0cf79620326f80593
| 24.465116 | 117 | 0.689498 | false | false | false | false |
noppoMan/swifty-libuv
|
refs/heads/master
|
Sources/IdleWrap.swift
|
mit
|
1
|
//
// IdleWrap.swift
// SwiftyLibuv
//
// Created by Yuki Takei on 6/12/16.
//
//
import CLibUv
private func idle_cb(handle: UnsafeMutablePointer<uv_idle_t>?) {
guard let handle = handle else {
return
}
let ctx = handle.pointee.data.assumingMemoryBound(to: IdleContext.self)
if ctx.pointee.queues.count <= 0 {
return
}
let lastIndex = ctx.pointee.queues.count - 1
let queue = ctx.pointee.queues.remove(at: lastIndex)
queue()
}
private struct IdleContext {
var queues: [() -> ()] = []
}
public class IdleWrap {
private var handle: UnsafeMutablePointer<uv_idle_t>
private var ctx: UnsafeMutablePointer<IdleContext>
public private(set) var isStarted = false
public init(loop: Loop = Loop.defaultLoop){
handle = UnsafeMutablePointer<uv_idle_t>.allocate(capacity: MemoryLayout<uv_idle_t>.size)
ctx = UnsafeMutablePointer<IdleContext>.allocate(capacity: 1)
ctx.initialize(to: IdleContext())
handle.pointee.data = UnsafeMutableRawPointer(ctx)
uv_idle_init(loop.loopPtr, handle)
}
public func append(_ queue: @escaping () -> ()){
ctx.pointee.queues.append(queue)
}
public func start(){
uv_idle_start(handle, idle_cb)
isStarted = true
}
public func stop(){
uv_idle_stop(handle)
dealloc(handle.pointee.data, capacity: 1)
dealloc(handle)
}
}
|
85b3d526e94735dec687f65c55b38665
| 22.234375 | 97 | 0.616678 | false | false | false | false |
nicolas-miari/EditableButton
|
refs/heads/master
|
EditableButton Demo App/EditableButton Demo App/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// EditableButton Demo App
//
// Created by Nicolás Fernando Miari on 2017/01/31.
// Copyright © 2017 Nicolas Miari. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
/// Edited with keyboard
@IBOutlet weak var textButton: EditableButton!
/// Edited with date picker
@IBOutlet weak var dateButton: EditableButton!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureTextButton()
configureDateButton()
}
private func configureTextButton() {
textButton.setTitle("Sample Text", for: .normal)
let textToolbar = UIToolbar(frame: CGRect.zero)
textToolbar.barStyle = .default
let textDoneButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(ViewController.textDone(_:)))
let textSpacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
textToolbar.items = [textSpacer, textDoneButton]
textToolbar.sizeToFit()
textButton.inputAccessoryView = textToolbar
}
private func configureDateButton() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateButton.setTitle(dateFormatter.string(from: Date()), for: .normal)
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
dateButton.inputView = datePicker
datePicker.addTarget(self, action: #selector(ViewController.dateChanged(_:)), for: .valueChanged)
let dateToolbar = UIToolbar(frame: CGRect.zero)
dateToolbar.barStyle = .default
let dateDoneButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(ViewController.dateDone(_:)))
let dateSpacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
dateToolbar.items = [dateSpacer, dateDoneButton]
dateToolbar.sizeToFit()
dateButton.inputAccessoryView = dateToolbar
}
// MARK: - Control Actions
@IBAction func dateChanged(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateButton.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}
@IBAction func dateDone(_ sender: UIBarButtonItem) {
dateButton.resignFirstResponder()
}
@IBAction func textDone(_ sender: UIBarButtonItem) {
textButton.resignFirstResponder()
}
}
|
a224affc71176a260bb1cd3f63ae78d6
| 29.47191 | 105 | 0.667773 | false | false | false | false |
JaSpa/swift
|
refs/heads/master
|
test/SILGen/address_only_types.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
enum Bool { case true_, false_ }
protocol Unloadable {
func foo() -> Int
var address_only_prop : Unloadable { get }
var loadable_prop : Int { get }
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B9_argument{{[_0-9a-zA-Z]*}}F
func address_only_argument(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]]
// CHECK-NEXT: destroy_addr [[XARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B17_ignored_argument{{[_0-9a-zA-Z]*}}F
func address_only_ignored_argument(_: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: destroy_addr [[XARG]]
// CHECK-NOT: dealloc_stack {{.*}} [[XARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_return{{[_0-9a-zA-Z]*}}F
func address_only_return(_ x: Unloadable, y: Int) -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64):
// CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable, let, name "x"
// CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y"
// CHECK-NEXT: copy_addr [[XARG]] to [initialization] [[RET]]
// CHECK-NEXT: destroy_addr [[XARG]]
// CHECK-NEXT: [[VOID:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[VOID]]
return x
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B15_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_missing_return() -> Unloadable {
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B27_conditional_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_conditional_missing_return(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]]
switch Bool.true_ {
case .true_:
// CHECK: [[TRUE]]:
// CHECK: copy_addr %1 to [initialization] %0 : $*Unloadable
// CHECK: destroy_addr %1
// CHECK: return
return x
case .false_:
()
}
// CHECK: [[FALSE]]:
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B29_conditional_missing_return_2
func address_only_conditional_missing_return_2(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE1]]:
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE2]]:
// CHECK: unreachable
// CHECK: bb{{.*}}:
// CHECK: return
}
var crap : Unloadable = some_address_only_function_1()
func some_address_only_function_1() -> Unloadable { return crap }
func some_address_only_function_2(_ x: Unloadable) -> () {}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_call_1
func address_only_call_1() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
return some_address_only_function_1()
// FIXME emit into
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: apply [[FUNC]]([[RET]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B21_call_1_ignore_returnyyF
func address_only_call_1_ignore_return() {
// CHECK: bb0:
some_address_only_function_1()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_call_2{{[_0-9a-zA-Z]*}}F
func address_only_call_2(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]] : $*Unloadable
some_address_only_function_2(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: [[X_CALL_ARG:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[XARG]] to [initialization] [[X_CALL_ARG]]
// CHECK: apply [[FUNC]]([[X_CALL_ARG]])
// CHECK: dealloc_stack [[X_CALL_ARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B12_call_1_in_2{{[_0-9a-zA-Z]*}}F
func address_only_call_1_in_2() {
// CHECK: bb0:
some_address_only_function_2(some_address_only_function_1())
// CHECK: [[FUNC2:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: [[FUNC1:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC1]]([[TEMP]])
// CHECK: apply [[FUNC2]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B12_materialize{{[_0-9a-zA-Z]*}}F
func address_only_materialize() -> Int {
// CHECK: bb0:
return some_address_only_function_1().foo()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr [[TEMP]] : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]]
// CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1
// CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]])
// CHECK: destroy_addr [[TEMP_PROJ]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B21_assignment_from_temp{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp(_ dest: inout Unloadable) {
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable):
dest = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [take] [[TEMP]] to %0 :
// CHECK-NOT: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B19_assignment_from_lv{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv(_ dest: inout Unloadable, v: Unloadable) {
var v = v
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable, [[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: [[VBOX:%.*]] = alloc_box ${ var Unloadable }
// CHECK: [[PBOX:%[0-9]+]] = project_box [[VBOX]]
// CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*Unloadable
dest = v
// FIXME: emit into?
// CHECK: copy_addr [[PBOX]] to %0 :
// CHECK: destroy_value [[VBOX]]
}
var global_prop : Unloadable {
get {
return crap
}
set {}
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B33_assignment_from_temp_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp_to_property() {
// CHECK: bb0:
global_prop = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T018address_only_types11global_propAA10Unloadable_pfs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B31_assignment_from_lv_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv_to_property(_ v: Unloadable) {
// CHECK: bb0([[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[VARG]] : $*Unloadable
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T018address_only_types11global_propAA10Unloadable_pfs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
global_prop = v
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B4_varAA10Unloadable_pyF
func address_only_var() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
var x = some_address_only_function_1()
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Unloadable }
// CHECK: [[XPB:%.*]] = project_box [[XBOX]]
// CHECK: apply {{%.*}}([[XPB]])
return x
// CHECK: copy_addr [[XPB]] to [initialization] [[RET]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return
}
func unloadable_to_unloadable(_ x: Unloadable) -> Unloadable { return x }
var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable
// CHECK-LABEL: sil hidden @_T018address_only_types05call_a1_B22_nontuple_arg_function{{[_0-9a-zA-Z]*}}F
func call_address_only_nontuple_arg_function(_ x: Unloadable) {
some_address_only_nontuple_arg_function(x)
}
|
04bf271b757c1f14b9e3725a20013e36
| 39 | 127 | 0.626087 | false | false | false | false |
pusher-community/pusher-websocket-swift
|
refs/heads/master
|
Sources/Models/ChannelsProtocolCloseCode.swift
|
mit
|
2
|
import Foundation
// MARK: - Channels Protocol close codes
/// Describes closure codes as specified by the Pusher Channels Protocol.
///
/// These closure codes fall in the 4000 - 4999 range, i.e. the `privateCode` case of `NWProtocolWebSocket.CloseCode`.
///
/// Reference: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol#error-codes
enum ChannelsProtocolCloseCode: UInt16 {
// MARK: - Channels Protocol reconnection strategies
/// Describes the reconnection strategy for a given `PusherChannelsProtocolCloseCode`.
///
/// Reference: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol#connection-closure
enum ReconnectionStrategy: UInt16 {
/// Indicates an error resulting in the connection being closed by Pusher Channels,
/// and that attempting to reconnect using the same parameters will not succeed.
case doNotReconnectUnchanged
/// Indicates an error resulting in the connection being closed by Pusher Channels,
/// and that the client may reconnect after 1s or more.
case reconnectAfterBackingOff
/// Indicates an error resulting in the connection being closed by Pusher Channels,
/// and that the client may reconnect immediately.
case reconnectImmediately
/// Indicates that the reconnection strategy is unknown due to the closure code being
/// outside of the expected range as specified by the Pusher Channels Protocol.
case unknown
// MARK: - Initialization
init(rawValue: UInt16) {
switch rawValue {
case 4000...4099:
self = .doNotReconnectUnchanged
case 4100...4199:
self = .reconnectAfterBackingOff
case 4200...4299:
self = .reconnectImmediately
default:
self = .unknown
}
}
}
// 4000 - 4099
case applicationOnlyAcceptsSSLConnections = 4000
case applicationDoesNotExist = 4001
case applicationDisabled = 4003
case applicationIsOverConnectionQuota = 4004
case pathNotFound = 4005
case invalidVersionStringFormat = 4006
case unsupportedProtocolVersion = 4007
case noProtocolVersionSupplied = 4008
case connectionIsUnauthorized = 4009
// 4100 - 4199
case overCapacity = 4100
// 4200 - 4299
case genericReconnectImmediately = 4200
/// Ping was sent to the client, but no reply was received
case pongReplyNotReceived = 4201
/// Client has been inactive for a long time (currently 24 hours)
/// and client does not support ping.
case closedAfterInactivity = 4202
// MARK: - Public properties
var reconnectionStrategy: ReconnectionStrategy {
return ReconnectionStrategy(rawValue: self.rawValue)
}
}
|
f7d6cf314ed2ef36ac87ab411415f9f8
| 35.891566 | 120 | 0.642391 | false | false | false | false |
apple/swift-system
|
refs/heads/main
|
Sources/System/Internals/Mocking.swift
|
apache-2.0
|
1
|
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// Syscall mocking support.
//
// NOTE: This is currently the bare minimum needed for System's testing purposes, though we do
// eventually want to expose some solution to users.
//
// Mocking is contextual, accessible through MockingDriver.withMockingEnabled. Mocking
// state, including whether it is enabled, is stored in thread-local storage. Mocking is only
// enabled in testing builds of System currently, to minimize runtime overhead of release builds.
//
#if ENABLE_MOCKING
internal struct Trace {
internal struct Entry: Hashable {
private var name: String
private var arguments: [AnyHashable]
internal init(name: String, _ arguments: [AnyHashable]) {
self.name = name
self.arguments = arguments
}
}
private var entries: [Entry] = []
private var firstEntry: Int = 0
internal var isEmpty: Bool { firstEntry >= entries.count }
internal mutating func dequeue() -> Entry? {
guard !self.isEmpty else { return nil }
defer { firstEntry += 1 }
return entries[firstEntry]
}
fileprivate mutating func add(_ e: Entry) {
entries.append(e)
}
}
internal enum ForceErrno: Equatable {
case none
case always(errno: CInt)
case counted(errno: CInt, count: Int)
}
// Provide access to the driver, context, and trace stack of mocking
internal class MockingDriver {
// Record syscalls and their arguments
internal var trace = Trace()
// Mock errors inside syscalls
internal var forceErrno = ForceErrno.none
// Whether we should pretend to be Windows for syntactic operations
// inside FilePath
fileprivate var forceWindowsSyntaxForPaths = false
}
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
internal var currentMockingDriver: MockingDriver? {
#if !ENABLE_MOCKING
fatalError("Contextual mocking in non-mocking build")
#endif
guard let rawPtr = getTLS(driverKey) else { return nil }
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
}
extension MockingDriver {
/// Enables mocking for the duration of `f` with a clean trace queue
/// Restores prior mocking status and trace queue after execution
internal static func withMockingEnabled(
_ f: (MockingDriver) throws -> ()
) rethrows {
let priorMocking = currentMockingDriver
let driver = MockingDriver()
defer {
if let object = priorMocking {
setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
} else {
setTLS(driverKey, nil)
}
_fixLifetime(driver)
}
setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
return try f(driver)
}
}
// Check TLS for mocking
@inline(never)
private var contextualMockingEnabled: Bool {
return currentMockingDriver != nil
}
extension MockingDriver {
internal static var enabled: Bool { mockingEnabled }
internal static var forceWindowsPaths: Bool {
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
}
}
#endif // ENABLE_MOCKING
@inline(__always)
internal var mockingEnabled: Bool {
// Fast constant-foldable check for release builds
#if ENABLE_MOCKING
return contextualMockingEnabled
#else
return false
#endif
}
@inline(__always)
internal var forceWindowsPaths: Bool {
#if !ENABLE_MOCKING
return false
#else
return MockingDriver.forceWindowsPaths
#endif
}
#if ENABLE_MOCKING
// Strip the mock_system prefix and the arg list suffix
private func originalSyscallName(_ function: String) -> String {
// `function` must be of format `system_<name>(<parameters>)`
precondition(function.starts(with: "system_"))
return String(function.dropFirst("system_".count).prefix { $0 != "(" })
}
private func mockImpl(
name: String,
path: UnsafePointer<CInterop.PlatformChar>?,
_ args: [AnyHashable]
) -> CInt {
precondition(mockingEnabled)
let origName = originalSyscallName(name)
guard let driver = currentMockingDriver else {
fatalError("Mocking requested from non-mocking context")
}
var mockArgs: Array<AnyHashable> = []
if let p = path {
mockArgs.append(String(_errorCorrectingPlatformString: p))
}
mockArgs.append(contentsOf: args)
driver.trace.add(Trace.Entry(name: origName, mockArgs))
switch driver.forceErrno {
case .none: break
case .always(let e):
system_errno = e
return -1
case .counted(let e, let count):
assert(count >= 1)
system_errno = e
driver.forceErrno = count > 1 ? .counted(errno: e, count: count-1) : .none
return -1
}
return 0
}
internal func _mock(
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
) -> CInt {
return mockImpl(name: name, path: path, args)
}
internal func _mockInt(
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
) -> Int {
Int(mockImpl(name: name, path: path, args))
}
internal func _mockOffT(
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
) -> _COffT {
_COffT(mockImpl(name: name, path: path, args))
}
#endif // ENABLE_MOCKING
// Force paths to be treated as Windows syntactically if `enabled` is
// true.
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
#if ENABLE_MOCKING
guard enabled else {
body()
return
}
MockingDriver.withMockingEnabled { driver in
driver.forceWindowsSyntaxForPaths = true
body()
}
#else
body()
#endif
}
|
2ff841bebfafc9e77d715e0a37706a40
| 25.84434 | 101 | 0.709893 | false | false | false | false |
alobanov/Dribbble
|
refs/heads/master
|
Dribbble/shared/managers/Popup.swift
|
mit
|
1
|
//
// Popup.swift
// Dribbble
//
// Created by Lobanov Aleksey on 09.09.16.
// Copyright © 2016 Lobanov Aleksey. All rights reserved.
//
import Foundation
import SwiftMessages
import PopupDialog
class Popup {
static let shared = Popup() // Singletone
private init() {}
static func show(_ title: String, body: String) {
let popup = MessageView.viewFromNib(layout: .CardView)
popup.configureTheme(.error)
popup.backgroundView.backgroundColor = UIColor.white
popup.titleLabel?.textColor = UIColor.black
popup.bodyLabel?.textColor = UIColor.darkGray
popup.titleLabel?.font = UIFont.systemFont(ofSize: 14)
popup.bodyLabel?.font = UIFont.systemFont(ofSize: 13)
popup.configureContent(title: title, body: body, iconImage: nil,
iconText:nil, buttonImage: nil, buttonTitle: nil, buttonTapHandler: { _ in SwiftMessages.hide() })
popup.button?.isHidden = true
var warningConfig = SwiftMessages.Config()
warningConfig.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
warningConfig.dimMode = .gray(interactive: true)
SwiftMessages.show(config: warningConfig, view: popup)
}
func noInternet() {
let popup = MessageView.viewFromNib(layout: .CardView)
popup.configureTheme(.error)
popup.configureContent(title: "No internet", body: "Check your internet connection")
popup.button?.isHidden = true
var warningConfig = SwiftMessages.Config()
warningConfig.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
warningConfig.dimMode = .gray(interactive: false)
warningConfig.duration = .forever
SwiftMessages.show(config: warningConfig, view: popup)
}
func hide() {
SwiftMessages.hide()
}
static func showNavError(_ err: NSError) {
let popup = MessageView.viewFromNib(layout: .TabView)
popup.configureTheme(.error)
popup.titleLabel?.font = UIFont.systemFont(ofSize: 14)
popup.bodyLabel?.font = UIFont.systemFont(ofSize: 13)
popup.configureContent(title: "", body: err.localizedDescription)
popup.button?.isHidden = true
var warningConfig = SwiftMessages.Config()
warningConfig.presentationContext = .automatic
warningConfig.duration = .seconds(seconds: 3)
warningConfig.dimMode = .none
SwiftMessages.show(config: warningConfig, view: popup)
}
func showCriticalError(_ err: NSError, closeHandler:(() -> Void)?) {
let popup = MessageView.viewFromNib(layout: .CardView)
popup.configureTheme(.error)
popup.titleLabel?.font = UIFont.systemFont(ofSize: 14)
popup.bodyLabel?.font = UIFont.systemFont(ofSize: 13)
popup.configureContent(title: "Error (code: \(err.code))",
body: err.localizedDescription,
iconImage: nil,
iconText: "😧",
buttonImage: nil,
buttonTitle: "",
buttonTapHandler: { _ in
if let b = closeHandler {
b()
}
SwiftMessages.hide()
})
popup.button?.tintColor = UIColor.white
popup.button?.backgroundColor = UIColor.clear
popup.button?.isHidden = false
var warningConfig = SwiftMessages.Config()
warningConfig.presentationContext = .window(windowLevel: UIWindowLevelStatusBar)
warningConfig.duration = .forever
warningConfig.dimMode = .gray(interactive: false)
SwiftMessages.show(config: warningConfig, view: popup)
}
func showAlertError(_ error: NSError) {
let ok = CancelButton(title: "Ok") {}
self.showAlert("Error (code: \(error.code))", subtitle: error.localizedDescription, buttons: [ok])
}
func showAlert(_ title: String, subtitle: String, buttons: [PopupDialogButton]) {
// Prepare the popup assets
let title = title
let message = subtitle
// Create the dialog
let popup = PopupDialog(title: title, message: message, buttonAlignment: .horizontal)
// Add buttons to dialog
// Alternatively, you can use popup.addButton(buttonOne)
// to add a single button
popup.addButtons(buttons)
// Present dialog
self.presentController().present(popup, animated: true, completion: nil)
}
private func presentController() -> UIViewController {
let keyWindow: UIWindow = UIApplication.shared.delegate!.window!!
return keyWindow.rootViewController!;
}
}
|
460d0be6149142a224286b744680294d
| 33.606061 | 125 | 0.658494 | false | true | false | false |
joerocca/GitHawk
|
refs/heads/master
|
Classes/Issues/Files/IssueFileCell.swift
|
mit
|
1
|
//
// IssueFileCell.swift
// Freetime
//
// Created by Ryan Nystrom on 8/12/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
final class IssueFileCell: SelectableCell {
private let changeLabel = UILabel()
private let pathLabel = UILabel()
private let disclosure = UIImageView(image: UIImage(named: "chevron-right")?.withRenderingMode(.alwaysTemplate))
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
disclosure.tintColor = Styles.Colors.Gray.light.color
disclosure.contentMode = .scaleAspectFit
contentView.addSubview(disclosure)
disclosure.snp.makeConstraints { make in
make.right.equalTo(-Styles.Sizes.gutter)
make.centerY.equalTo(contentView)
make.size.equalTo(Styles.Sizes.icon)
}
contentView.addSubview(changeLabel)
changeLabel.snp.makeConstraints { make in
make.left.equalTo(Styles.Sizes.gutter)
make.bottom.equalTo(contentView.snp.centerY)
make.right.lessThanOrEqualTo(disclosure.snp.left).offset(-Styles.Sizes.rowSpacing)
}
pathLabel.font = Styles.Fonts.body
pathLabel.textColor = Styles.Colors.Gray.dark.color
pathLabel.lineBreakMode = .byTruncatingHead
contentView.addSubview(pathLabel)
pathLabel.snp.makeConstraints { make in
make.left.equalTo(Styles.Sizes.gutter)
make.top.equalTo(changeLabel.snp.bottom)
make.right.lessThanOrEqualTo(disclosure.snp.left).offset(-Styles.Sizes.rowSpacing)
}
addBorder(.bottom, left: Styles.Sizes.gutter)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public API
func configure(path: String, additions: Int, deletions: Int) {
let changeString = NSMutableAttributedString()
var attributes: [NSAttributedStringKey: Any] = [
.font: Styles.Fonts.secondaryBold
]
if additions > 0 {
attributes[.foregroundColor] = Styles.Colors.Green.medium.color
changeString.append(NSAttributedString(string: "+\(additions) ", attributes: attributes))
}
if deletions > 0 {
attributes[.foregroundColor] = Styles.Colors.Red.medium.color
changeString.append(NSAttributedString(string: "-\(deletions)", attributes: attributes))
}
changeLabel.attributedText = changeString
pathLabel.text = path
}
}
|
3d7cde63af8544cbc3bbc1f27c3858b3
| 31.848101 | 116 | 0.659345 | false | false | false | false |
ekohe/ios-charts
|
refs/heads/master
|
Source/ChartsRealm/Data/RealmBubbleDataSet.swift
|
apache-2.0
|
2
|
//
// RealmBubbleDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if NEEDS_CHARTS
import Charts
#endif
import Realm
import RealmSwift
import Realm.Dynamic
open class RealmBubbleDataSet: RealmBarLineScatterCandleBubbleDataSet, IBubbleChartDataSet
{
open override func initialize()
{
}
public required init()
{
super.init()
}
public init(results: RLMResults<RLMObject>?, xValueField: String, yValueField: String, sizeField: String, label: String?)
{
_sizeField = sizeField
super.init(results: results, xValueField: xValueField, yValueField: yValueField, label: label)
}
public convenience init(results: Results<Object>?, xValueField: String, yValueField: String, sizeField: String, label: String?)
{
var converted: RLMResults<RLMObject>?
if results != nil
{
converted = ObjectiveCSupport.convert(object: results!)
}
self.init(results: converted, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, xValueField: String, yValueField: String, sizeField: String)
{
self.init(results: results, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField, label: "DataSet")
}
public convenience init(results: Results<Object>?, xValueField: String, yValueField: String, sizeField: String)
{
var converted: RLMResults<RLMObject>?
if results != nil
{
converted = ObjectiveCSupport.convert(object: results!)
}
self.init(results: converted, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField)
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String, yValueField: String, sizeField: String, label: String?)
{
_sizeField = sizeField
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label)
}
public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String, yValueField: String, sizeField: String, label: String?)
{
var converted: RLMRealm?
if realm != nil
{
converted = ObjectiveCSupport.convert(object: realm!)
}
self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField, label: label)
}
// MARK: - Data functions and accessors
internal var _sizeField: String?
internal var _maxSize = CGFloat(0.0)
open var maxSize: CGFloat { return _maxSize }
open var normalizeSizeEnabled: Bool = true
open var isNormalizeSizeEnabled: Bool { return normalizeSizeEnabled }
internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry
{
let entry = BubbleChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, y: object[_yValueField!] as! Double, size: object[_sizeField!] as! CGFloat)
return entry
}
open override func calcMinMax()
{
if _cache.count == 0
{
return
}
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
for e in _cache as! [BubbleChartDataEntry]
{
calcMinMax(entry: e)
let size = e.size
if size > _maxSize
{
_maxSize = size
}
}
}
// MARK: - Styling functions and accessors
/// Sets/gets the width of the circle that surrounds the bubble when highlighted
open var highlightCircleWidth: CGFloat = 2.5
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmBubbleDataSet
copy._xMin = _xMin
copy._xMax = _xMax
copy._maxSize = _maxSize
copy.highlightCircleWidth = highlightCircleWidth
return copy
}
}
|
27729de5ac47c71d50ca222737266a54
| 30.868966 | 179 | 0.637092 | false | false | false | false |
Desgard/Calendouer-iOS
|
refs/heads/master
|
Calendouer/Calendouer/App/Model/LifeScoreObject.swift
|
mit
|
1
|
//
// LifeScoreObject.swift
// Calendouer
//
// Created by 段昊宇 on 2017/4/24.
// Copyright © 2017年 Desgard_Duan. All rights reserved.
//
import UIKit
class LifeScoreObject: NSObject, NSCoding {
var city = ""
// 空气指数
var air_brf = ""
var air_txt = ""
// 舒适度指数
var comf_brf = ""
var comf_txt = ""
// 穿衣指数
var drsg_brf = ""
var drsg_txt = ""
// 感冒指数
var flu_brf = ""
var flu_txt = ""
// 运动指数
var sport_brf = ""
var sport_txt = ""
// 旅游指数
var trav_brf = ""
var trav_txt = ""
// 紫外线指数
var uv_brf = ""
var uv_txt = ""
// 洗车指数
var cw_brf = ""
var cw_txt = "'"
// 唯一标示,用于数据库
var id = ""
public func toData() -> LifeScoreData {
let lifeScore = LifeScoreData()
lifeScore.city = city
lifeScore.air_brf = air_brf
lifeScore.air_txt = air_txt
lifeScore.comf_brf = comf_brf
lifeScore.comf_txt = comf_txt
lifeScore.cw_brf = cw_brf
lifeScore.cw_txt = cw_txt
lifeScore.drsg_brf = drsg_brf
lifeScore.drsg_txt = drsg_txt
lifeScore.flu_brf = flu_brf
lifeScore.flu_txt = flu_txt
lifeScore.sport_brf = sport_brf
lifeScore.sport_txt = sport_txt
lifeScore.trav_brf = trav_brf
lifeScore.trav_txt = trav_txt
lifeScore.uv_brf = uv_brf
lifeScore.uv_txt = uv_txt
lifeScore.id = id
return lifeScore
}
required override init() {
}
// MARK: - NSCoding -
private struct LifeScoreObjectCodingKey {
static let kCodingCity = "city"
static let kCodingAir_brf = "air_brf"
static let kCodingAir_txt = "air_txt"
static let kCodingComf_brf = "comf_brf"
static let kCodingComf_txt = "comf_txt"
static let kCodingDrsg_brf = "drsg_brf"
static let kCodingDrsg_txt = "drsg_txt"
static let kCodingFlu_brf = "flu_brf"
static let kCodingFlu_txt = "flu_txt"
static let kCodingSport_brf = "sport_brf"
static let kCodingSport_txt = "sport_txt"
static let kCodingTrav_brf = "trav_brf"
static let kCodingTrav_txt = "trav_txt"
static let kCodingUv_brf = "uv_brf"
static let kCodingUv_txt = "uv_txt"
static let kCodingCw_brf = "cw_brf"
static let kCodingCw_txt = "cw_txt"
static let kCodingID = "id"
}
required init?(coder aDecoder: NSCoder) {
self.city = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingCity) as! String
self.air_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingAir_brf) as! String
self.air_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingAir_txt) as! String
self.comf_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingComf_brf) as! String
self.comf_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingComf_txt) as! String
self.drsg_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingDrsg_brf) as! String
self.drsg_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingDrsg_txt) as! String
self.flu_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingFlu_brf) as! String
self.flu_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingFlu_txt) as! String
self.sport_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingSport_brf) as! String
self.sport_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingSport_txt) as! String
self.trav_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingTrav_brf) as! String
self.trav_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingTrav_txt) as! String
self.uv_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingUv_brf) as! String
self.uv_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingUv_txt) as! String
self.cw_brf = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingCw_brf) as! String
self.cw_txt = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingCw_txt) as! String
self.id = aDecoder.decodeObject(forKey: LifeScoreObjectCodingKey.kCodingID) as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.city, forKey: LifeScoreObjectCodingKey.kCodingCity)
aCoder.encode(self.air_brf, forKey: LifeScoreObjectCodingKey.kCodingAir_brf)
aCoder.encode(self.air_txt, forKey: LifeScoreObjectCodingKey.kCodingAir_txt)
aCoder.encode(self.comf_brf, forKey: LifeScoreObjectCodingKey.kCodingComf_brf)
aCoder.encode(self.comf_txt, forKey: LifeScoreObjectCodingKey.kCodingComf_txt)
aCoder.encode(self.drsg_brf, forKey: LifeScoreObjectCodingKey.kCodingDrsg_brf)
aCoder.encode(self.drsg_txt, forKey: LifeScoreObjectCodingKey.kCodingDrsg_txt)
aCoder.encode(self.flu_brf, forKey: LifeScoreObjectCodingKey.kCodingFlu_brf)
aCoder.encode(self.flu_txt, forKey: LifeScoreObjectCodingKey.kCodingFlu_txt)
aCoder.encode(self.sport_brf, forKey: LifeScoreObjectCodingKey.kCodingSport_brf)
aCoder.encode(self.sport_txt, forKey: LifeScoreObjectCodingKey.kCodingSport_txt)
aCoder.encode(self.trav_brf, forKey: LifeScoreObjectCodingKey.kCodingTrav_brf)
aCoder.encode(self.trav_txt, forKey: LifeScoreObjectCodingKey.kCodingTrav_txt)
aCoder.encode(self.uv_brf, forKey: LifeScoreObjectCodingKey.kCodingUv_brf)
aCoder.encode(self.uv_txt, forKey: LifeScoreObjectCodingKey.kCodingUv_txt)
aCoder.encode(self.cw_brf, forKey: LifeScoreObjectCodingKey.kCodingCw_brf)
aCoder.encode(self.cw_txt, forKey: LifeScoreObjectCodingKey.kCodingCw_txt)
aCoder.encode(self.id , forKey: LifeScoreObjectCodingKey.kCodingID)
}
public func randomLifeScore() -> (String, String, String, String) {
var res_type: [String] = []
var res_qlt: [String] = []
var res_txt: [String] = []
var res_img: [String] = []
if air_brf == "较差" || air_brf == "很差" {
res_qlt.append(air_brf)
res_type.append("空气质量")
res_txt.append(air_txt)
res_img.append("as_air")
}
if comf_brf == "不舒适" || comf_brf == "不宜" {
res_type.append("舒适度")
res_qlt.append(comf_brf)
res_txt.append(comf_txt)
res_img.append("as_comf")
}
if drsg_brf == "不宜" || drsg_brf == "不舒适" {
res_type.append("穿衣指数")
res_qlt.append(drsg_brf)
res_txt.append(drsg_txt)
res_img.append("as_drsg")
}
if flu_brf == "易发" {
res_type.append("感冒指数")
res_qlt.append(flu_brf)
res_txt.append(flu_txt)
res_img.append("as_flu")
}
if sport_brf == "不宜" {
res_type.append("运动指数")
res_qlt.append(sport_brf)
res_txt.append(sport_txt)
res_img.append("as_sport")
}
if trav_brf == "不宜" {
res_type.append("旅游指数")
res_qlt.append(trav_brf)
res_txt.append(trav_txt)
res_img.append("as_trav")
}
if uv_brf == "强" || uv_brf == "最强" {
res_type.append("紫外线指数")
res_qlt.append(uv_brf)
res_txt.append(uv_txt)
res_img.append("as_uv")
}
if cw_brf == "不宜" {
res_type.append("洗车指数")
res_qlt.append(cw_brf)
res_txt.append(cw_txt)
res_img.append("as_cw")
}
if res_type.count > 0 {
let index = Int(arc4random()) % res_type.count
return (res_type[index], res_qlt[index], res_txt[index], res_img[index])
}
return ("", "", "", "")
}
}
|
61d1d0ecec8d338909b68fa64027fa00
| 42.868421 | 113 | 0.594241 | false | false | false | false |
ChaosCoder/Fluency
|
refs/heads/master
|
Fluency/FailableTask.swift
|
mit
|
1
|
import Foundation
class FailableTask: Task
{
var successTask : Task?
var failureTask : Task?
override func execute()
{
success(nil)
}
override init()
{
super.init()
}
required init(task: Task) {
let failableTask = task as! FailableTask
successTask = failableTask.successTask
failureTask = failableTask.failureTask
super.init(task: task)
}
final internal func success(result : Any?)
{
let context = Context(process: self.context.process, task: self.originalTask, result: result)
finish(result)
if let nextTask = successTask
{
nextTask.start(context)
}
}
final internal func failure(error : NSError)
{
let context = Context(process: self.context.process, task: self.originalTask, result: error)
finish(error)
if let nextTask = failureTask
{
nextTask.start(context)
}
else
{
context.process.unhandledFailure(self, error: error, context: context)
}
}
override func plantUML(visited: [Task]) -> String
{
var uml = "\"\(plantUMLDescription)\" as \(addressString)\n"
if visited.contains(self) || plantUMLVisited > 0
{
return uml
}
plantUMLVisited++
if successTask != nil || failureTask != nil
{
uml += "if \"\" then\n"
if let successTask = successTask
{
uml += "--> " + successTask.plantUML(visited + [self])
}
else
{
uml += "-->[success] (*)\n"
}
uml += "else\n"
if let failureTask = failureTask
{
uml += "-->[failure] " + failureTask.plantUML(visited + [self])
}
else
{
uml += "-->[failure] (*)\n"
}
uml += "endif\n"
}
return uml
}
}
|
8cc81aa551fa5a33f54ce14d986fd789
| 17.202247 | 95 | 0.625077 | false | false | false | false |
danielsaidi/KeyboardKit
|
refs/heads/master
|
Demo/Demo/Demo/DemoAppearance.swift
|
mit
|
1
|
//
// DemoAppearance.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
import UIKit
final class DemoAppearance {
private init() {}
static func apply() {
let navbar = UINavigationBar.appearance()
let navbarAppearance = UINavigationBarAppearance()
navbarAppearance.configureWithOpaqueBackground()
//navbarAppearance.backgroundColor = .accent
navbarAppearance.titleTextAttributes = titleAttributes
navbarAppearance.largeTitleTextAttributes = largeTitleAttributes
//navbar.tintColor = UIColor.darkGray
navbar.standardAppearance = navbarAppearance
navbar.scrollEdgeAppearance = navbarAppearance
}
}
private extension DemoAppearance {
static func font(sized size: CGFloat) -> UIFont {
FontFamily.SourceSansPro.bold.font(size: size) ?? .systemFont(ofSize: size)
}
static var titleAttributes: [NSAttributedString.Key: Any] {
[.font: font(sized: 20), .foregroundColor: UIColor.label, .shadow: shadow]
}
static var largeTitleAttributes: [NSAttributedString.Key: Any] {
[.font: font(sized: 30), .foregroundColor: UIColor.label, .shadow: shadow]
}
static var shadow: NSShadow {
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowColor = UIColor.clear
return shadow
}
}
|
b37adf6a96d268e5b6529916ec0a9269
| 28.877551 | 83 | 0.681694 | false | false | false | false |
937447974/YJCocoa
|
refs/heads/master
|
YJCocoa/Classes/AppFrameworks/UIKit/TableView/YJUITableViewCell.swift
|
mit
|
1
|
//
// YJUITableViewCell.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2019/5/22.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import UIKit
@objc extension UITableViewCell {
/// 获取 YJUITableCellObject
open class func cellObject() -> YJUITableCellObject {
return YJUITableCellObject(cellClass: self)
}
/// 获取 YJUITableCellObject 并自动填充模型
open class func cellObject(with cellModel: Any?, didSelectClosure: YJUITableCellSelectClosure? = nil) -> YJUITableCellObject {
let co = self.cellObject()
co.cellModel = cellModel
co.didSelectClosure = didSelectClosure
return co
}
/// 获取 cell 的显示高
open class func tableViewManager(_ tableViewManager: YJUITableViewManager, heightWith cellObject: YJUITableCellObject) -> CGFloat {
return tableViewManager.tableView.rowHeight
}
/// 刷新 UITableViewCell
open func tableViewManager(_ tableViewManager: YJUITableViewManager, reloadWith cellObject: YJUITableCellObject) {}
}
open class YJUITableViewCell: UITableViewCell {
public private(set) var cellObject: YJUITableCellObject!
public private(set) var tableViewManager: YJUITableViewManager!
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func tableViewManager(_ tableViewManager: YJUITableViewManager, reloadWith cellObject: YJUITableCellObject) {
super.tableViewManager(tableViewManager, reloadWith: cellObject)
self.tableViewManager = tableViewManager
self.cellObject = cellObject
}
}
|
745c900db2d788bb824a57c50cfa2709
| 31.084746 | 135 | 0.706815 | false | false | false | false |
megavolt605/CNLUIKitTools
|
refs/heads/master
|
CNLUIKitTools/CNLTabBarController.swift
|
mit
|
1
|
//
// CNLTabBarController.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 19/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
open class CNLTabBarController: UITabBarController, UITabBarControllerDelegate {
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
open func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard let tabViewControllers = tabBarController.viewControllers,
let fromView = tabBarController.selectedViewController?.view,
let fromViewController = tabBarController.selectedViewController,
let fromIndex = tabViewControllers.index(of: fromViewController),
let toView = viewController.view,
let toIndex = tabViewControllers.index(of: viewController),
fromView != toView
else { return false }
UIView.transition(
from: fromView,
to: toView,
duration: 0.3,
options: (toIndex > fromIndex) ? .transitionFlipFromLeft : .transitionFlipFromRight,
completion: { finished in
if finished {
tabBarController.selectedIndex = toIndex
}
}
)
return true
}
}
|
b657ec0d0d3a8149939a8ced5c366b23
| 32.093023 | 127 | 0.624736 | false | false | false | false |
mitochrome/complex-gestures-demo
|
refs/heads/master
|
apps/GestureInput/Carthage/Checkouts/RxDataSources/RxSwift/RxCocoa/macOS/NSTextField+Rx.swift
|
mit
|
4
|
//
// NSTextField+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 5/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(macOS)
import Cocoa
#if !RX_NO_MODULE
import RxSwift
#endif
/// Delegate proxy for `NSTextField`.
///
/// For more information take a look at `DelegateProxyType`.
open class RxTextFieldDelegateProxy
: DelegateProxy<NSTextField, NSTextFieldDelegate>
, DelegateProxyType
, NSTextFieldDelegate {
/// Typed parent object.
public weak private(set) var textField: NSTextField?
/// Initializes `RxTextFieldDelegateProxy`
///
/// - parameter parentObject: Parent object for delegate proxy.
init(parentObject: NSTextField) {
self.textField = parentObject
super.init(parentObject: parentObject, delegateProxy: RxTextFieldDelegateProxy.self)
}
public static func registerKnownImplementations() {
self.register { RxTextFieldDelegateProxy(parentObject: $0) }
}
fileprivate let textSubject = PublishSubject<String?>()
// MARK: Delegate methods
open override func controlTextDidChange(_ notification: Notification) {
let textField: NSTextField = castOrFatalError(notification.object)
let nextValue = textField.stringValue
self.textSubject.on(.next(nextValue))
_forwardToDelegate?.controlTextDidChange?(notification)
}
// MARK: Delegate proxy methods
/// For more information take a look at `DelegateProxyType`.
open class func currentDelegate(for object: ParentObject) -> NSTextFieldDelegate? {
return object.delegate
}
/// For more information take a look at `DelegateProxyType`.
open class func setCurrentDelegate(_ delegate: NSTextFieldDelegate?, to object: ParentObject) {
object.delegate = delegate
}
}
extension Reactive where Base: NSTextField {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<NSTextField, NSTextFieldDelegate> {
return RxTextFieldDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for `text` property.
public var text: ControlProperty<String?> {
let delegate = RxTextFieldDelegateProxy.proxy(for: base)
let source = Observable.deferred { [weak textField = self.base] in
delegate.textSubject.startWith(textField?.stringValue)
}.takeUntil(deallocated)
let observer = Binder(base) { (control, value: String?) in
control.stringValue = value ?? ""
}
return ControlProperty(values: source, valueSink: observer.asObserver())
}
}
#endif
|
10f454465ae51388d151a7831406b33c
| 29.3 | 99 | 0.690502 | false | false | false | false |
nodekit-io/nodekit-windows
|
refs/heads/master
|
src/nodekit/NKElectro/common/NKEMenu/NKEMenu-ios.swift
|
apache-2.0
|
1
|
/*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
* Portions Copyright (c) 2013 GitHub, Inc. under MIT License
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import UIKit
// NKElectro MENU Placeholder code only: on roadmap but lower priority as not supported on mobile
extension NKE_Menu: NKScriptExport {
static func attachTo(context: NKScriptContext) {
let principal = NKE_Menu()
context.NKloadPlugin(principal, namespace: "io.nodekit.electro._menu", options: [String:AnyObject]())
}
func rewriteGeneratedStub(stub: String, forKey: String) -> String {
switch (forKey) {
case ".global":
let url = NSBundle(forClass: NKE_Menu.self).pathForResource("menu", ofType: "js", inDirectory: "lib-electro")
let appjs = try? NSString(contentsOfFile: url!, encoding: NSUTF8StringEncoding) as String
let url2 = NSBundle(forClass: NKE_Menu.self).pathForResource("menu-item", ofType: "js", inDirectory: "lib-electro")
let appjs2 = try? NSString(contentsOfFile: url2!, encoding: NSUTF8StringEncoding) as String
return "function loadplugin1(){\n" + appjs! + "\n}\n" + "\n" + "function loadplugin2(){\n" + appjs2! + "\n}\n" + stub + "\n" + "loadplugin1(); loadplugin2();" + "\n"
default:
return stub
}
}
}
class NKE_Menu: NSObject, NKEMenuProtocol {
func setApplicationMenu(menu: [String: AnyObject]) -> Void { NKE_Menu.NotImplemented(); }
func sendActionToFirstResponder(action: String) -> Void { NKE_Menu.NotImplemented(); } //OS X
private static func NotImplemented(functionName: String = __FUNCTION__) -> Void {
log("!menu.\(functionName) is not implemented")
}
}
|
ae1f1128facd6e3689405a2e7775b09e
| 39.553571 | 177 | 0.683399 | false | false | false | false |
luispadron/GradePoint
|
refs/heads/master
|
GradePoint/Controllers/Onboarding/Onboard4ViewController.swift
|
apache-2.0
|
1
|
//
// Onboard3ViewController.swift
// GradePoint
//
// Created by Luis Padron on 2/20/17.
// Copyright © 2017 Luis Padron. All rights reserved.
//
import UIKit
import UICircularProgressRing
class Onboard4ViewController: UIViewController {
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var progressRing: UICircularProgressRing!
@IBOutlet weak var button: UIButton!
private var hasAnimated = false
override func viewDidLoad() {
super.viewDidLoad()
// Set initial alpha for the views
self.headerLabel.alpha = 0.0
self.progressRing.alpha = 0.0
self.button.alpha = 0.0
// Set the style for the UIButton
self.button.contentEdgeInsets = UIEdgeInsets.init(top: 12, left: 18, bottom: 12, right: 18)
self.button.layer.backgroundColor = self.view.backgroundColor?.lighter(by: 20)?.cgColor
self.button.layer.cornerRadius = 6.0
// Customization for progress ring
self.progressRing.animationTimingFunction = .easeInEaseOut
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !hasAnimated { self.animateViews() }
self.hasAnimated = true
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Customize font size/ring properties
if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass {
switch traitCollection.horizontalSizeClass {
case .compact:
progressRing.font = UIFont.systemFont(ofSize: 60)
progressRing.outerRingWidth = 14
progressRing.innerRingWidth = 10
default:
progressRing.font = UIFont.systemFont(ofSize: 90)
progressRing.outerRingWidth = 20
progressRing.innerRingWidth = 16
}
}
}
// MARK: Animations
func animateViews() {
UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, options: [], animations: {
// Set the opacity for the views
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1/2, animations: {
self.headerLabel.alpha = 1.0
})
UIView.addKeyframe(withRelativeStartTime: 1/2, relativeDuration: 1/2, animations: {
self.progressRing.alpha = 1.0
})
}) { _ in
// Animate the progress ring
self.progressRing.startProgress(to: 100, duration: 2.0, completion: { [weak self] in
// When done animate the button alpha
UIView.animate(withDuration: 0.5, animations: {
self?.button.alpha = 1.0
})
})
}
}
// MARK: Actions
@IBAction func onButtonTap(_ sender: UIButton) {
// Set the has onboarded user to true
let defaults = UserDefaults.standard
defaults.set(true, forKey: kUserDefaultOnboardingComplete)
// Notify delegate were done onboarding
let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.finishedPresentingOnboarding()
}
}
|
34b7a705d97beb5c578d6833b883c14a
| 33.649485 | 99 | 0.614103 | false | false | false | false |
Sourcegasm/Math-Parser-Swift
|
refs/heads/master
|
Math Parser/MathParserFormatter.swift
|
mit
|
1
|
//
// MathParserFormatter.swift
// Math Parser
//
// Created by Vid Drobnic on 8/9/15.
// Copyright (c) 2015 Vid Drobnic. All rights reserved.
//
import Foundation
let mathParserDecimalSeparator = NSLocale.currentLocale().objectForKey(NSLocaleDecimalSeparator) as! String
var mathParserNumberSeparator: String {
get {
if mathParserDecimalSeparator == "." {
return ","
} else {
return "."
}
}
}
func mathParserFormatNumber(number: String) -> String {
var mutatableNumber = number.stringByReplacingOccurrencesOfString(".", withString: mathParserDecimalSeparator, options: NSStringCompareOptions.LiteralSearch, range: nil)
var decimalSeparatorFound = false
if mutatableNumber.rangeOfString(mathParserDecimalSeparator, options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil) == nil {
decimalSeparatorFound = true
}
var count = 0
for var index = mutatableNumber.endIndex.predecessor(); index > mutatableNumber.startIndex; index = index.predecessor() {
if mutatableNumber[index] == Character(mathParserDecimalSeparator) {
decimalSeparatorFound = true
continue
} else if !decimalSeparatorFound {
continue
}
if count == 2 {
mutatableNumber.splice(mathParserNumberSeparator, atIndex: index)
count = 0
continue
}
++count
}
return mutatableNumber
}
func mathParserFormatExpression(expression: String) -> String {
var mutableExpression = expression.stringByReplacingOccurrencesOfString(",", withString: "; ", options: NSStringCompareOptions.LiteralSearch, range: nil)
var result = ""
var currentNumber = ""
for character in mutableExpression {
if character.isNumber {
currentNumber.append(character)
} else if !currentNumber.isEmpty {
result += mathParserFormatNumber(currentNumber)
currentNumber = ""
result.append(character)
} else {
result.append(character)
}
}
if !currentNumber.isEmpty {
result += mathParserFormatNumber(currentNumber)
}
return result
}
|
d06e9fa4988114d8285b05787d752f6c
| 29.36 | 173 | 0.646309 | false | false | false | false |
realtime-framework/realtime-news-swift
|
refs/heads/master
|
Realtime/Realtime/PapersViewController.swift
|
mit
|
1
|
//
// PapersViewController.swift
// RealtimeNews
//
// Created by Joao Caixinha on 25/02/15.
// Copyright (c) 2015 Realtime. All rights reserved.
//
import UIKit
class PapersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SMProtocol {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
var isFiltred:Bool = false
var filter:String = ""
var notificationItem:AnyObject?
var entrys:NSMutableArray?
@IBOutlet weak var tablePapers: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tablePapers.dataSource = self
self.tablePapers.delegate = self
}
override func viewWillAppear(animated: Bool) {
self.tabBarItem.badgeValue = nil
}
override func viewWillDisappear(animated:Bool)
{
if self.entrys != nil && self.entrys!.count > 0
{
for item in self.entrys!{
let obj:DataObject = item as! DataObject
obj.isNew = false
obj.isUpdated = false
}
self.tablePapers.reloadData()
}
}
func didReceivedData(data:NSMutableArray)
{
self.entrys = data
self.entrys = NSMutableArray(array: Utils.performSearch(self.entrys!, name: "White Papers", key: "type"))
if (self.isFiltred == true) {
self.entrys = NSMutableArray(array: Utils.performSearch(self.entrys!, name: filter, key: "tag"))
}
self.entrys = Utils.orderTopics(self.entrys!)
self.tablePapers?.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.entrys == nil
{
return 0
}
return self.entrys!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let indent:NSString = "cell"
var cell:DataTableViewCell? = tableView.dequeueReusableCellWithIdentifier(indent as String) as? DataTableViewCell
if (cell == nil) {
cell = DataTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: indent as String)
}
cell?.imageLogo.image = nil
let item:DataObject = self.entrys!.objectAtIndex(indexPath.row) as! DataObject
cell!.setCellForData(item, forRow: indexPath.row)
return cell!;
}
var reload_distance:CGFloat?
func scrollViewDidScroll(scrollView: UIScrollView) {
let height:CGFloat = scrollView.frame.size.height;
let contentYoffset:CGFloat = scrollView.contentOffset.y;
let distanceFromBottom:CGFloat = scrollView.contentSize.height - contentYoffset;
if(distanceFromBottom < height && self.entrys != nil)
{
scrollLimit = self.entrys!.count + limit
NSNotificationCenter.defaultCenter().postNotificationName("getData", object: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (self.notificationItem != nil) {
let content:ContentViewController = segue.destinationViewController as! ContentViewController
content.model = self.notificationItem as? DataObject
self.notificationItem = nil;
}else{
let selectedIndex = self.tablePapers.indexPathForCell(sender as! UITableViewCell)
let content:ContentViewController = segue.destinationViewController as! ContentViewController
content.model = self.entrys!.objectAtIndex(selectedIndex!.row as Int) as? DataObject
}
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
if (identifier == "contentView") {
let selectedIndex = self.tablePapers.indexPathForCell(sender as! UITableViewCell)
let obj:DataObject = self.entrys!.objectAtIndex(selectedIndex!.row as Int) as! DataObject
if ((obj.isOffline == true) && (obj.onDisk == false)) {
let alert:UIAlertView = UIAlertView(title: "Information", message: "You are currently offline and this content is not saved locally. Please try again later.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return false;
}
}
return true;
}
}
|
e3399d89f91c992b884e98be7653a930
| 35.129032 | 214 | 0.634821 | false | false | false | false |
deyton/swift
|
refs/heads/master
|
benchmark/single-source/ByteSwap.swift
|
apache-2.0
|
8
|
//===--- ByteSwap.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift byte swap.
// rdar://problem/22151907
import Foundation
import TestsUtils
// a naive O(n) implementation of byteswap.
@inline(never)
func byteswap_n(_ a: UInt64) -> UInt64 {
#if swift(>=4)
return ((a & 0x00000000000000FF) &<< 56) |
((a & 0x000000000000FF00) &<< 40) |
((a & 0x0000000000FF0000) &<< 24) |
((a & 0x00000000FF000000) &<< 8) |
((a & 0x000000FF00000000) &>> 8) |
((a & 0x0000FF0000000000) &>> 24) |
((a & 0x00FF000000000000) &>> 40) |
((a & 0xFF00000000000000) &>> 56)
#else
return ((a & 0x00000000000000FF) << 56) |
((a & 0x000000000000FF00) << 40) |
((a & 0x0000000000FF0000) << 24) |
((a & 0x00000000FF000000) << 8) |
((a & 0x000000FF00000000) >> 8) |
((a & 0x0000FF0000000000) >> 24) |
((a & 0x00FF000000000000) >> 40) |
((a & 0xFF00000000000000) >> 56)
#endif
}
// a O(logn) implementation of byteswap.
@inline(never)
func byteswap_logn(_ a: UInt64) -> UInt64 {
var a = a
a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32
a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16
a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8
return a
}
@inline(never)
public func run_ByteSwap(_ N: Int) {
var s: UInt64 = 0
for _ in 1...10000*N {
// Check some results.
let x : UInt64 = UInt64(getInt(0))
s = s &+ byteswap_logn(byteswap_n(x &+ 2457))
&+ byteswap_logn(byteswap_n(x &+ 9129))
&+ byteswap_logn(byteswap_n(x &+ 3333))
}
CheckResults(s == (2457 &+ 9129 &+ 3333) &* 10000 &* N)
}
|
d4a9ff694d04872d2689985767b3df34
| 33.1875 | 80 | 0.556673 | false | false | false | false |
PJayRushton/TeacherTools
|
refs/heads/master
|
TeacherTools/TestHelper.swift
|
mit
|
1
|
//
// TestHelper.swift
// TeacherTools
//
// Created by Parker Rushton on 10/30/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import Foundation
let fakeUser = User(id: "-Kud72jKowj03jA3", cloudKitId: "_And;lkfjieb894j9gry", creationDate: Date(), firstName: "Lord Farquad")
let group1Id = "09oi;q4oraeh"
let group2Id = "jsqar8efd8"
let student1Id = "EIHf83nf"
let student2Id = "apsoin3k"
let student3Id = "ih3qgreav"
let student4Id = "9ui3qgirje"
var fakeStudent1 = Student(id: "EIHf83nf", name: "MacKenzie")
var fakeStudent2 = Student(id: "apsoin3k", name: "Amanda")
var fakeStudent3 = Student(id: "ih3qgreav", name: "Holly")
var fakeStudent4 = Student(id: "9ui3qgirje", name: "David")
var fakeStudent5 = Student(id: "9ui3qg8h67", name: "Korina")
var fakeStudent6 = Student(id: "3q454heddr", name: "Josh")
var fakeStudent7 = Student(id: "bg4asdfrw2", name: "Helaman")
var fakeStudent8 = Student(id: "p98iuqhrg4", name: "DonCarlos")
var fakeStudent9 = Student(id: "p89ppu43gs", name: "Michael")
var fakeStudent10 = Student(id: "09hugrhjof", name: "Janina")
var fakeStudent11 = Student(id: "iowtrjtree", name: "Albert")
var fakeStudent12 = Student(id: "poijq342as", name: "Elijah")
var fakeStudent13 = Student(id: "0oijgqrawe", name: "Chloe")
var allStudents: [Student] {
return [fakeStudent1, fakeStudent2, fakeStudent3, fakeStudent4, fakeStudent5, fakeStudent6, fakeStudent7, fakeStudent8, fakeStudent9, fakeStudent10, fakeStudent11, fakeStudent12, fakeStudent13]
}
var evenStudents: [Student] {
return allStudents.filter { allStudents.index(of: $0)! % 2 == 0 }
}
struct LoadFakeUser: Command {
func execute(state: AppState, core: Core<AppState>) {
core.fire(event: Selected<User>(fakeUser))
}
}
struct LoadFakeGroups: Command {
let group1 = Group(id: group1Id, name: "SCIENCE!", studentIds: evenStudents.map { $0.id })
let group2 = Group(id: group2Id, name: "Labs", studentIds: allStudents.map { $0.id }, teamSize: 3)
func execute(state: AppState, core: Core<AppState>) {
core.fire(event: Updated<[Group]>([group1, group2]))
}
}
struct LoadFakeStudents: Command {
func execute(state: AppState, core: Core<AppState>) {
core.fire(event: Updated<[Student]>(allStudents))
}
}
|
dcab1f720a61f0a3cf9ff5931d02e8fc
| 32.529412 | 197 | 0.703509 | false | false | false | false |
iqingchen/DouYuZhiBo
|
refs/heads/master
|
DY/DY/Classes/Main/View/PageContentView.swift
|
mit
|
1
|
//
// PageContentView.swift
// DY
//
// Created by zhang on 16/11/30.
// Copyright © 2016年 zhang. All rights reserved.
//
import UIKit
//MARK: - 定义代理方法
protocol PageContentViewDelegate: class {
func pageContentViewWithScroll(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}
//MARK: - 定义常量
private let collectionIdentifier : String = "childsVcCell"
//MARK: - 定义PageContentView类
class PageContentView: UIView {
//MARK: - 定义属性
fileprivate var childVcs : [UIViewController]
fileprivate var startScrollViewX : CGFloat = 0
fileprivate weak var parentViewControll : UIViewController?
fileprivate var isForbidScroll : Bool = false
weak var delegate: PageContentViewDelegate?
//MARK: - 懒加载控件
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 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.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
return collectionView
}()
//MARK: - 自定义构造函数
init(frame: CGRect, childVcs: [UIViewController], parentsViewControll: UIViewController?) {
self.childVcs = childVcs
parentViewControll = parentsViewControll
super.init(frame: frame)
//设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI界面
extension PageContentView {
fileprivate func setupUI() {
//1.添加子控制自控制器到父控制器中
for child in childVcs {
parentViewControll?.addChildViewController(child)
}
//2.添加UICollectionView,用于在cell中存放控制器view
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK: - 设置collectionView的代理
extension PageContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath)
//清除之前添加的view
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
//设置cell属性
let childVc = childVcs[indexPath.row]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: - 实现scrollview的代理方法
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScroll = false
startScrollViewX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isForbidScroll == true {return}
//1.定义需要获取的函数
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
//2.判断是左滑还是右滑
let scrollOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if scrollOffsetX > startScrollViewX {
//左滑
progress = scrollOffsetX / scrollViewW - floor(scrollOffsetX / scrollViewW)
sourceIndex = Int(scrollOffsetX / scrollViewW)
targetIndex = sourceIndex + 1
//预防越界
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//全部滑过去progress为1
if scrollOffsetX - startScrollViewX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else {
//右滑
progress = 1 - (scrollOffsetX / scrollViewW - floor(scrollOffsetX / scrollViewW))
targetIndex = Int(scrollOffsetX / scrollViewW)
sourceIndex = targetIndex + 1
//预防越界
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
//3.将progress/sourceIndex/targetIndex传递出去
delegate?.pageContentViewWithScroll(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK: - 对外暴露的方法
extension PageContentView {
func setCurrentIndex(currentIndex: Int) {
isForbidScroll = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
|
ceb5377168f0a00fb51eac6e3dfd6c58
| 33.38255 | 134 | 0.657037 | false | false | false | false |
travtex/SpotMark
|
refs/heads/master
|
SpotMark/LocationDetailsViewController.swift
|
mit
|
1
|
//
// LocationDetailsViewController.swift
// SpotMark
//
// Created by Travis Flatt on 7/8/15.
// Copyright (c) 2015 Travis Flatt. All rights reserved.
//
import UIKit
import CoreLocation
private let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .ShortStyle
return formatter
}()
class LocationDetailsViewController: UITableViewController, UITextViewDelegate {
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBAction func done() {
println("Description '\(descriptionText)'")
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func cancel() {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func categoryPickerDidPickCategory(segue: UIStoryboardSegue) {
let controller = segue.sourceViewController as! CategoryPickerViewController
categoryName = controller.selectedCategoryName
categoryLabel.text = categoryName
}
var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
var placemark: CLPlacemark?
var descriptionText = ""
var categoryName = "No Category"
override func viewDidLoad() {
super.viewDidLoad()
descriptionTextView.text = descriptionText
categoryLabel.text = categoryName
latitudeLabel.text = String(format: "%.8f", coordinate.latitude)
longitudeLabel.text = String(format: "%.8f", coordinate.longitude)
if let placemark = placemark {
addressLabel.text = stringFromPlacemark(placemark)
} else {
addressLabel.text = "No Address Found"
}
dateLabel.text = formatDate(NSDate())
}
func formatDate(date: NSDate) -> String {
return dateFormatter.stringFromDate(date)
}
func stringFromPlacemark(placemark: CLPlacemark) -> String {
return "\(placemark.subThoroughfare) \(placemark.thoroughfare), " +
"\(placemark.locality), " +
"\(placemark.administrativeArea) \(placemark.postalCode), " +
"\(placemark.country)"
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return 88
} else if indexPath.section == 2 && indexPath.row == 2 {
addressLabel.frame.size = CGSize(width: view.bounds.size.width - 115, height: 10000)
addressLabel.sizeToFit()
addressLabel.frame.origin.x = view.bounds.size.width - addressLabel.frame.size.width - 15
return addressLabel.frame.size.height + 20
} else {
return 44
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PickCategory" {
let controller = segue.destinationViewController as! CategoryPickerViewController
controller.selectedCategoryName = categoryName
}
}
}
extension LocationDetailsViewController: UITextViewDelegate {
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
descriptionText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
return true
}
func textViewDidEndEditing(textView: UITextView) {
descriptionText = textView.text
}
}
|
fa7c6c132307df01d09526e8f3636ec3
| 33.651376 | 119 | 0.668962 | false | false | false | false |
Eonil/EditorLegacy
|
refs/heads/trial1
|
Modules/EditorUIComponents/EditorUIComponents/DarkVibrantCompatibility/AttributedStringTableCellView.swift
|
mit
|
1
|
//
// AttributedStringTableCellView.swift
// EditorDebuggingFeature
//
// Created by Hoon H. on 2015/02/03.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import AppKit
/// This class creates text-field and image-view itself.
/// You should not add or set them.
///
/// This view is tuned to look properly in dark-vibrancy mode in Yosemite.
/// This kind of manual patch applied because Yosemite does not provide
/// proper coloring, and may look somewhat weired in later OS X versions.
/// Patch at the time if you have some such troubles.
public final class AttributedStringTableCellView: NSTableCellView {
public convenience init() {
self.init(frame: CGRect.zeroRect)
}
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
_configureSubviews()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
_configureSubviews()
}
@availability(*,unavailable)
public final override var textField:NSTextField? {
get {
return super.textField
}
set(v) {
if v == nil {
super.textField = v // This can be called by dealloc.
} else {
fatalError("You cannot change text-field object.")
}
}
}
public var attributedString:NSAttributedString? {
get {
return self.objectValue as! NSAttributedString?
}
set(v) {
self.objectValue = v
}
}
@objc
public override var objectValue:AnyObject? {
get {
return super.objectValue
}
set(v) {
precondition(v == nil || v! is NSAttributedString)
super.objectValue = v
if let n = v as? NSAttributedString {
_originText = n
// _highlightText = Text(n).setTextColor(NSColor.selectedTextColor()).attributedString
_highlightText = Text(n).setTextColor(NSColor.labelColor()).attributedString
} else {
_originText = NSAttributedString()
_highlightText = NSAttributedString()
}
}
}
@objc
public override var backgroundStyle:NSBackgroundStyle {
didSet {
switch backgroundStyle {
case .Dark:
super.textField!.attributedStringValue = _highlightText
case .Light:
super.textField!.attributedStringValue = _originText
default:
fatalError("Unsupported constant `\(backgroundStyle.rawValue)`.")
}
}
}
////
private var _originText = NSAttributedString()
private var _highlightText = NSAttributedString()
private func _configureSubviews() {
let tv = NSTextField()
let mv = NSImageView()
addSubview(tv)
addSubview(mv)
super.textField = tv
super.imageView = mv
////
tv.editable = false
tv.bordered = false
tv.bezeled = false
tv.drawsBackground = false
tv.backgroundColor = NSColor.clearColor()
tv.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints([
NSLayoutConstraint(item: tv, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tv, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tv, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tv, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0),
])
}
}
extension AttributedStringTableCellView {
}
|
0c8c23ab2eb281eb5ee065fe529f1d0f
| 22.535948 | 185 | 0.710914 | false | false | false | false |
mspvirajpatel/SwiftyBase
|
refs/heads/master
|
Example/SwiftyBase/Controller/ImageViewer/DisplayAllImageView.swift
|
mit
|
1
|
//
// DisplayAllImageView.swift
// SwiftyBase
//
// Created by MacMini-2 on 18/09/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import SwiftyBase
class DisplayAllImageView: BaseView,UICollectionViewDelegate,UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
// MARK: - Attribute -
var photoCollectionView:UICollectionView!
var flowLayout:UICollectionViewFlowLayout!
var photoListArray:NSMutableArray!
var photoListCount:NSInteger!
var previousPhotoListCount:NSInteger!
var nextPhotoListCount:NSInteger!
var collectionCellSize:CGSize! = AppInterfaceUtility.getAppropriateSizeFromSize(UIScreen.main.bounds.size, withDivision: 3.0, andInterSpacing: 5.0)
// MARK: - Lifecycle -
override init(frame: CGRect)
{
super.init(frame:frame)
self.loadViewControls()
self.setViewlayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
deinit{
}
// MARK: - Layout -
override func loadViewControls()
{
super.loadViewControls()
photoListArray = [
"http://www.intrawallpaper.com/static/images/HD-Wallpapers1_Q75eDHE_lG95giJ.jpeg",
"http://www.intrawallpaper.com/static/images/hd-wallpapers-8_FY4tW4s.jpg",
"http://www.intrawallpaper.com/static/images/tiger-wallpapers-hd-Bengal-Tiger-hd-wallpaper.jpg",
"http://www.intrawallpaper.com/static/images/3D-Beach-Wallpaper-HD-Download_QssSQPf.jpg",
"http://www.intrawallpaper.com/static/images/pixars_up_hd_wide-wide.jpg",
"http://www.intrawallpaper.com/static/images/tree_snake_hd-wide.jpg",
"http://www.intrawallpaper.com/static/images/3D-Wallpaper-HD-35_hx877p1.jpg",
"http://www.intrawallpaper.com/static/images/tropical-beach-background-8.jpg",
"http://www.intrawallpaper.com/static/images/1912472_ePOwBxX.jpg",
"http://www.intrawallpaper.com/static/images/Colors_digital_hd_wallpaper_F37Cy15.jpg",
"http://www.intrawallpaper.com/static/images/funky-wallpaper-hd_4beLiY2.jpg",
"http://www.intrawallpaper.com/static/images/dna_nano_tech-wide_dyyhibN.jpg",
"http://www.intrawallpaper.com/static/images/dream_village_hd-HD.jpg",
"http://www.intrawallpaper.com/static/images/hd-wallpaper-25_hOaS0Jp.jpg","http://www.intrawallpaper.com/static/images/Golden-Gate-Bridge-HD-Wallpapers-WideScreen2.jpg"
,"http://www.intrawallpaper.com/static/images/hd-wallpaper-40_HM6Q9LK.jpg"
]
photoListCount = photoListArray.count
/* photoCollectionView Allocation */
flowLayout = UICollectionViewFlowLayout.init()
flowLayout.scrollDirection = .vertical
photoCollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: flowLayout)
photoCollectionView.translatesAutoresizingMaskIntoConstraints = false
photoCollectionView.allowsMultipleSelection = false
photoCollectionView.backgroundColor = UIColor.clear
photoCollectionView.delegate = self
photoCollectionView.dataSource = self
photoCollectionView .register(PhotoCollectionCell.self, forCellWithReuseIdentifier: CellIdentifire.defaultCell)
self.addSubview(photoCollectionView)
}
override func setViewlayout()
{
super.setViewlayout()
baseLayout.expandView(photoCollectionView, insideView: self)
self.layoutSubviews()
self.layoutIfNeeded()
}
// MARK: - Public Interface -
// MARK: - User Interaction -
// MARK: - Internal Helpers -
// MARK: - UICollectionView DataSource Methods -
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if photoListCount == 0 {
self.displayErrorMessageLabel("No Record Found")
}
else
{
self.displayErrorMessageLabel(nil)
}
return photoListCount ?? 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell : PhotoCollectionCell!
cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifire.defaultCell, for: indexPath) as? PhotoCollectionCell
if cell == nil
{
cell = PhotoCollectionCell(frame: CGRect.zero)
}
if(indexPath.row < photoListArray.count){
var imageString:NSString? = photoListArray[indexPath.row] as? NSString
cell.displayImage(image: imageString!)
imageString = nil;
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
func setPhoto() -> [PhotoModel] {
var photos: [PhotoModel] = []
for photoURLString in photoListArray {
let photoModel = PhotoModel(imageUrlString: photoURLString as? String, sourceImageView: nil)
photos.append(photoModel)
}
return photos
}
let photoBrowser = PhotoBrowser(photoModels: setPhoto())
photoBrowser.delegate = self
photoBrowser.show(inVc: self.getViewControllerFromSubView()!, beginPage: indexPath.row)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionCellSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
}
// MARK: - Server Request -
// public func getAllImagesRequest()
// {
//
// operationQueue.addOperation { [weak self] in
// if self == nil{
// return
// }
//
// BaseAPICall.shared.postReques(URL: APIConstant.userPhotoList, Parameter: NSDictionary(), Type: APITask.GetAllImages) { [weak self] (result) in
// if self == nil{
// return
// }
//
// switch result{
// case .Success(let object,let error):
//
// self!.hideProgressHUD()
//
// var imageArray: NSMutableArray! = object as! NSMutableArray
// self!.previousPhotoListCount = self!.photoListArray.count
// self!.nextPhotoListCount = imageArray.count
// self!.photoListArray = imageArray
// self!.photoListCount = self!.photoListArray.count
//
// AppUtility.executeTaskInMainQueueWithCompletion { [weak self] in
// if self == nil{
// return
// }
// self!.photoCollectionView.reloadData()
// }
//
// defer{
// imageArray = nil
// }
//
// break
// case .Error(let error):
//
// self!.hideProgressHUD()
// AppUtility.executeTaskInMainQueueWithCompletion {
// AppUtility.showWhisperAlert(message: error!.serverMessage, duration: 1.0)
// }
//
// break
// case .Internet(let isOn):
// self!.handleNetworkCheck(isAvailable: isOn)
// break
// }
// }
// }
// }
//
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
extension DisplayAllImageView: PhotoBrowserDelegate {
func photoBrowserWillEndDisplay(_ endPage: Int) {
let currentIndexPath = IndexPath(row: endPage, section: 0)
let cell = photoCollectionView.cellForItem(at: currentIndexPath) as? PhotoCollectionCell
cell?.alpha = 0.0
}
func photoBrowserDidEndDisplay(_ endPage: Int) {
let currentIndexPath = IndexPath(row: endPage, section: 0)
let cell = photoCollectionView.cellForItem(at: currentIndexPath) as? PhotoCollectionCell
cell?.alpha = 1.0
}
func photoBrowserDidDisplayPage(_ currentPage: Int, totalPages: Int) {
let visibleIndexPaths = photoCollectionView.indexPathsForVisibleItems
let currentIndexPath = IndexPath(row: currentPage, section: 0)
if !visibleIndexPaths.contains(currentIndexPath) {
photoCollectionView.scrollToItem(at: currentIndexPath, at: .top, animated: false)
photoCollectionView.layoutIfNeeded()
}
}
func sourceImageViewForCurrentIndex(_ index: Int) -> UIImageView? {
let currentIndexPath = IndexPath(row: index, section: 0)
let cell = photoCollectionView.cellForItem(at: currentIndexPath) as? PhotoCollectionCell
let sourceView = cell?.feedImageView
return sourceView
}
}
|
df21c3a715ae5951a87393f95b376a24
| 34.893471 | 180 | 0.603925 | false | false | false | false |
xmkevinchen/CKMessagesKit
|
refs/heads/master
|
CKMessagesKit/Sources/View/Components/CKMessagesToolbar.swift
|
mit
|
1
|
//
// CKMessagesToolbar.swift
// CKMessagesKit
//
// Created by Kevin Chen on 8/30/16.
// Copyright © 2016 Kevin Chen. All rights reserved.
//
import UIKit
public class CKMessagesToolbar: UIToolbar {
public var preferredDefaultHeight: CGFloat = 44.0 {
willSet {
assert(newValue > 0)
}
}
public var maximumHeight = CGFloat.greatestFiniteMagnitude
public private(set) var contentView: CKMessagesToolbarContentView!
public var textView: CKMessagesComposerTextView {
return contentView.textView
}
override public func awakeFromNib() {
super.awakeFromNib()
self.contentView = CKMessagesToolbarContentView.viewFromNib()
addSubview(contentView)
pinSubview(contentView)
setNeedsUpdateConstraints()
translatesAutoresizingMaskIntoConstraints = false
}
}
// MARK:- BarItems
public extension CKMessagesToolbar {
public var leftBarItem: CKMessagesToolbarItem? {
get {
return contentView.leftBarItem
}
set {
contentView.leftBarItem = newValue
}
}
public var leftBarItems: [CKMessagesToolbarItem]? {
get {
return contentView.leftBarItems
}
set {
contentView.leftBarItems = newValue
}
}
public var rightBarItem: CKMessagesToolbarItem? {
get {
return contentView.rightBarItem
}
set {
contentView.rightBarItem = newValue
}
}
public var rightBarItems: [CKMessagesToolbarItem]? {
get {
return contentView.rightBarItems
}
set {
contentView.rightBarItems = newValue
}
}
}
|
6a7d1af1afdb093383dde33a9d20bd72
| 21.22619 | 77 | 0.577397 | false | false | false | false |
teamVCH/sway
|
refs/heads/master
|
sway/TrackDetailViewController.swift
|
mit
|
1
|
//
// TrackDetailViewController.swift
// sway
//
// Created by Hina Sakazaki on 10/15/15.
// Copyright © 2015 VCH. All rights reserved.
//
import UIKit
import CoreData
let collaborateSegue = "collaborateSegue"
// Retreive the managedObjectContext from AppDelegate
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let favoriteImage = UIImage(named: "favorite")
let favoriteOutlineImage = UIImage(named: "favorite_outline")
class TrackDetailViewController: UIViewController, AVAudioPlayerExtDelegate {
@IBOutlet weak var waveformView: WaveformView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var originatorImage: UIImageView!
@IBOutlet weak var originatorName: UILabel!
@IBOutlet weak var lengthLabel: UILabel!
@IBOutlet weak var publishedOnLabel: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var originatorImageView: UIImageView!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var tagsLabel: UILabel!
@IBOutlet weak var collaboratorCount: UILabel!
@IBOutlet weak var likeCount: UILabel!
@IBOutlet weak var replayCount: UILabel!
@IBOutlet weak var collabButton: UIButton!
@IBOutlet weak var collaboratorsView: UIView!
var tune: Tune!
var audioPlayer: AVAudioPlayerExt?
override func viewDidLoad() {
super.viewDidLoad()
originatorImage.layer.cornerRadius = 20
originatorImage.clipsToBounds = true
collabButton.layer.cornerRadius = 4
collabButton.clipsToBounds = true
}
override func viewWillAppear(animated: Bool) {
if let tune = tune {
titleLabel.text = tune.title!
var originator = tune.getOriginators().0
if !originator.isDataAvailable() {
originator = try! originator.fetchIfNeeded()
}
if let url = originator.objectForKey(kProfileImageUrl) as? String {
originatorImage.setImageURLWithFade(NSURL(string: url)!, alpha: CGFloat(1.0), completion: nil)
} else {
originatorImage.image = defaultUserImage
}
if let _ = tune.audioUrl {
if let cachedAudioUrl = tune.cachedAudioUrl {
setAudio(cachedAudioUrl)
} else {
SwiftLoader.show("Loading audio...", animated: true)
tune.downloadAndCacheAudio({ (cachedUrl: NSURL?, error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(),{
SwiftLoader.hide()
if let cachedUrl = cachedUrl {
self.setAudio(cachedUrl)
}
})
})
}
}
if let name = originator.objectForKey("username") as? String {
self.originatorName.text = "By " + name
}
if let date = tune.createDate {
publishedOnLabel.text = "Published " + formatTimeElapsed(date)
}
if let length = tune.length {
lengthLabel.text = Recording.formatTime(Double(length), includeMs: false)
} else {
lengthLabel.text = "0:00"
}
renderCounts()
renderCollaborators()
tagsLabel.text = getTagsAsString(tune.tagNames)
if tune.isLiked() {
likeButton.setImage(favoriteImage, forState: .Normal)
} else {
likeButton.setImage(favoriteOutlineImage, forState: .Normal)
}
}
}
private func setAudio(cachedUrl: NSURL) {
do {
try self.audioPlayer = AVAudioPlayerExt(contentsOfURL: cachedUrl)
self.audioPlayer!.delegate = self
self.audioPlayer!.prepareToPlay()
print("Cached audio downloaded")
} catch let error as NSError {
print("Error loading audio player: \(error)")
}
self.waveformView.audioUrl = cachedUrl
self.waveformView.normalColor = UIColor.whiteColor()
self.waveformView.progressColor = UIColor.lightGrayColor()
}
private func renderCollaborators() {
if let collaborators = tune.getCollaborators() {
let imageviews = collaboratorsView.subviews as! [UIImageView]
for (index, elem) in collaborators.reverse().enumerate() {
if (index < 4) {
imageviews[index].hidden = false
if let url = elem.objectForKey(kProfileImageUrl) as? String {
imageviews[index].setImageURLWithFade(NSURL(string: url)!, alpha: CGFloat(1.0), completion: nil)
} else {
imageviews[index].image = defaultUserImage
}
imageviews[index].layer.cornerRadius = 12
imageviews[index].clipsToBounds = true
}
}
}
}
private func renderCounts() {
if let replays = tune.replayCount {
replayCount.text = (replays == 1) ? "\(replays) replay" : "\(replays) replays"
}
let likerCount = tune.likers != nil ? tune.likers!.count : 0
likeCount.text = (likerCount == 1) ? "\(likerCount) like" : "\(likerCount) likes"
collaboratorCount.text = (tune.collaboratorCount == 1) ?
"\(tune.collaboratorCount!) collaborator" : "\(tune.collaboratorCount!) collaborators"
}
private func getTagsAsString(tags: [String]?) -> String {
var tagString = ""
if let tags = tags {
for tag in tags {
tagString += "#\(tag) "
}
}
if tune != nil {
if let collaborator = tune.getOriginators().1 {
if let username = collaborator.objectForKey("username") as? String {
if tagString.characters.count > 0 {
tagString += "\n\n" //TODO: this is a hack
}
tagString += "\(username) contributed new audio"
}
}
}
return tagString
}
private func formatTimeElapsed(sinceDate: NSDate) -> String {
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Short
formatter.collapsesLargestUnit = false
formatter.maximumUnitCount = 1
let interval = NSDate().timeIntervalSinceDate(sinceDate)
if interval < 30.0 {
return "Just Now"
} else {
return formatter.stringFromTimeInterval(interval)! + " ago"
}
}
override func viewWillDisappear(animated: Bool) {
if let audioPlayer = audioPlayer {
if audioPlayer.playing {
audioPlayer.stop()
}
}
}
@IBAction func onTapPlayPause(sender: UIButton) {
if let audioPlayer = audioPlayer {
if audioPlayer.playing {
audioPlayer.stop()
sender.selected = false
} else {
audioPlayer.play()
sender.selected = true
if let replayCount = tune.replayCount {
let newCount = replayCount + 1
tune.replayCount = newCount
self.replayCount.text = (newCount == 1) ? "\(newCount) replay" : "\(newCount) replays"
}
}
}
}
@IBAction func onTapLike(sender: UIButton) {
let previouslyLiked = tune.isLiked()
var count = tune.likers != nil ? tune.likers!.count : 0
// Like or unlike
tune.like(!previouslyLiked)
// Update UI immediately
previouslyLiked ? sender.setImage(favoriteOutlineImage, forState: .Normal) : sender.setImage(favoriteImage, forState: .Normal)
count = previouslyLiked ? count - 1 : count + 1
likeCount.text = (count == 1) ? "\(count) like" : "\(count) likes"
// TODO: Need delegate to update like count for main view
}
func audioPlayerUpdateTime(player: AVAudioPlayer) {
waveformView.updateTime(audioPlayer!.currentTime)
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
playButton.selected = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let segueId = segue.identifier {
if segueId == collaborateSegue {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onPublishedTune:", name: publishedTune, object: nil)
var recordViewController: RecordViewController!
if let _ = segue.destinationViewController as? UINavigationController {
let destinationNavigationController = segue.destinationViewController as! UINavigationController
recordViewController = destinationNavigationController.topViewController as! RecordViewController
} else {
recordViewController = segue.destinationViewController as! RecordViewController
}
let recording = NSEntityDescription.insertNewObjectForEntityForName(recordingEntityName, inManagedObjectContext: managedObjectContext) as! Recording
//recording.originalTuneId = tune.id!
recording.originalTune = tune
let backingAudioUrl = recording.getAudioUrl(.Backing, create: true)
try! NSFileManager.defaultManager().copyItemAtURL(tune.cachedAudioUrl!, toURL: backingAudioUrl!)
if let title = tune.title {
recording.title = title
}
if let tags = tune.tagNames {
var rTags = Set<RecordingTag>()
for tag in tags {
let rTag = NSEntityDescription.insertNewObjectForEntityForName(recordingTagEntityName, inManagedObjectContext: managedObjectContext) as! RecordingTag
rTag.tag = tag
rTag.recording = recording
rTags.insert(rTag)
}
recording.tags = rTags
}
recordViewController.recording = recording
}
}
}
func onPublishedTune(notification: NSNotification) {
// Get the Tune passed in fron the NSNotification
if let userInfo = notification.userInfo as? [String: Tune] {
self.tune = userInfo["Tune"]
self.view.setNeedsLayout()
}
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
f5423e616d3214f8ecb17156bf0db51c
| 37.372937 | 173 | 0.569794 | false | false | false | false |
glbuyer/GbKit
|
refs/heads/master
|
GbKit/Utilities/GbNetworkBaseUtility.swift
|
mit
|
1
|
//
// GbNetworkBaseUtility.swift
// glbuyer-buyer-ios
//
// Created by Jausing Wang on 2017/4/27.
// Copyright © 2017年 glbuyer. All rights reserved.
//
import Foundation
import Alamofire
public typealias GbNetworkRequestSuccessCallback = (_ code:Int?,_ message:String?, _ data: [String:Any]?) -> Void
public typealias GbNetworkRequestFailureCallback = (_ code:Int?,_ message:String?, _ data: [String:Any]?) -> Void
public typealias VoidCallback = () -> Void
public class GbNetworkBaseUtility {
static let NETWORK_FAILURE_CODE = 500
static fileprivate var headers : HTTPHeaders {
get {
if getAccessToken() != nil {
return [
"Authorization":"Bearer \(getAccessToken()!)",
"Content-Type": "application/json"
]
}
return ["Content-Type": "application/json"]
}
}
static let afManager = GbNetworkBaseUtility.defaultAlamofireSessionManager()
fileprivate class func alamofireSessionManager(withTimeout isLongTimeOut:Bool, hasAuthorizationHeader: Bool) -> SessionManager{
let configuration = URLSessionConfiguration.default
if !isLongTimeOut {
configuration.timeoutIntervalForRequest = 5 // seconds
configuration.timeoutIntervalForResource = 5
}
let manager = Alamofire.SessionManager(configuration: configuration)
return manager
}
private class func defaultAlamofireSessionManager() -> SessionManager{
return alamofireSessionManager(withTimeout: true, hasAuthorizationHeader: true)
}
public class func handleResponseResult(withResult result: [String:Any], success: GbNetworkRequestSuccessCallback, failure: GbNetworkRequestFailureCallback) {
if result["code"] as! Int == 0 {
success(result["code"] as? Int,result["message"] as? String,result["data"] as? Dictionary)
}
else{
failure(result["code"] as? Int,result["message"] as? String,result["data"] as? Dictionary)
}
}
public class func networkGetRequest(withURL url: String, parameters: [String:Any]?, success: @escaping GbNetworkRequestSuccessCallback, failure: @escaping GbNetworkRequestFailureCallback) {
let paraSend = (parameters?.count == 0 ? nil : parameters)
afManager.request(url, method: .get, parameters: paraSend, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON{ response in
switch response.result {
case .success(let value):
handleResponseResult(withResult: value as! Dictionary, success: success, failure: failure)
case .failure(let error):
failure(NETWORK_FAILURE_CODE, error.localizedDescription, [:])
}
}
}
public class func networkPostRequest(withURL url: String, parameters: [String:Any]?, success: @escaping GbNetworkRequestSuccessCallback, failure: @escaping GbNetworkRequestFailureCallback) {
let paraSend = (parameters?.count == 0 ? nil : parameters)
afManager.request(url, method: .post, parameters: paraSend, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON{ response in
switch response.result {
case .success(let value):
handleResponseResult(withResult: value as! Dictionary, success: success, failure: failure)
case .failure(let error):
failure(NETWORK_FAILURE_CODE, error.localizedDescription, [:])
}
}
}
public class func networkDeleteRequest(withURL url: String, parameters: [String:Any]?, success: @escaping GbNetworkRequestSuccessCallback, failure: @escaping GbNetworkRequestFailureCallback) {
let paraSend = (parameters?.count == 0 ? nil : parameters)
afManager.request(url, method: .delete, parameters: paraSend, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON{ response in
switch response.result {
case .success(let value):
handleResponseResult(withResult: value as! Dictionary, success: success, failure: failure)
case .failure(let error):
failure(NETWORK_FAILURE_CODE, error.localizedDescription, [:])
}
}
}
class func getAccessToken() -> String? {
return UserDefaults.standard.string(forKey: "accessToken")
}
}
|
96bbc00ef9df4fb26aa6c58d3427e631
| 36.712 | 196 | 0.62622 | false | false | false | false |
madoffox/Stretching
|
refs/heads/master
|
Stretching/Stretching/ABSTraining.swift
|
mit
|
1
|
//
// WendesdayTraining.swift
// Stretching
//
// Created by Admin on 18.12.16.
// Copyright © 2016 Admin. All rights reserved.
//
import Foundation
import UIKit
func ifItIsWednesday(){
trainingDay.name = "'Велосипед'"
trainingDay.picture = UIImage(named: "велосипед", in: nil, compatibleWith: nil)!
dayTraining.append(trainingDay)
trainingDay.name = "Касания стоп"
trainingDay.picture = UIImage(named: "касания стоп", in: nil, compatibleWith: nil)!
dayTraining.append(trainingDay)
trainingDay.name = "Скручивания"
trainingDay.picture = UIImage(named: "скручивания", in: nil, compatibleWith: nil)!
dayTraining.append(trainingDay)
trainingDay.name = "Боковые скручивания"
trainingDay.picture = UIImage(named: "боковые скручивания", in: nil, compatibleWith: nil)!
dayTraining.append(trainingDay)
trainingDay.name = "Планка"
trainingDay.picture = UIImage(named: "планка", in: nil, compatibleWith: nil)!
dayTraining.append(trainingDay)
}
|
52b8ba5ff070e6c71d5b4c7931158a4f
| 27.777778 | 94 | 0.694981 | false | false | false | false |
a7ex/SwiftDTO
|
refs/heads/master
|
SwiftDTO/Exporter/BaseExporter.swift
|
apache-2.0
|
1
|
//
// BaseExporter.swift
// SwiftDTO
//
// Created by Alex da Franca on 08.06.17.
// Copyright © 2017 Farbflash. All rights reserved.
//
import Foundation
protocol DTOFileGenerator {
func generateFiles(inFolder folderPath: String?, withParseSupport parseSupport: Bool)
}
class BaseExporter {
let parser: XMLModelParser
let indent = " "
init(parser: XMLModelParser) {
self.parser = parser
}
func generateClassFinally(_ properties: [XMLElement]?, withName className: String, parentProtocol: ProtocolDeclaration?, storedProperties: [RESTProperty]?, parseSupport: Bool) -> String? {
return "Override 'generateProtocolFileForProtocol()' in your concrete subclass of BaseExporter!"
}
func generateEnumFileForEntityFinally(_ restprops: [RESTProperty], withName className: String, enumParentName: String) -> String? {
return "Override 'generateProtocolFileForProtocol()' in your concrete subclass of BaseExporter!"
}
func generateProtocolFileForProtocol(_ protocolName: String) -> String? {
return "Override 'generateProtocolFileForProtocol()' in your concrete subclass of BaseExporter!"
}
func generateParseExtensionFinally(_ properties: [XMLElement]?, withName className: String, parentProtocol: ProtocolDeclaration?, storedProperties: [RESTProperty]?) -> String? {
return "Override 'generateParseExtension()' in your concrete subclass of BaseExporter!"
}
func fileExtensionForCurrentOutputType() -> String {
// Override in concrete subclass. This is the default: -> swift
return "swift"
}
final func generateEnums(inDirectory outputDir: String) {
for enumInfo in parser.enums {
if let content = generateEnumFileForEntityFinally(enumInfo.restprops,
withName: enumInfo.name,
enumParentName: enumInfo.typeName) {
writeContent(content, toFileAtPath: pathForClassName(enumInfo.name, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
}
}
final func generateProtocolFiles(inDirectory outputDir: String) {
for complexType in parser.complexTypesInfos where parser.protocolNames.contains(complexType.name) {
// write protocol files to disk:
if let content = generateProtocolFileForProtocol(complexType.name) {
writeContent(content, toFileAtPath: pathForClassName(complexType.name, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
}
}
final func generateClassFiles(inDirectory outputDir: String, withParseSupport parseSupport: Bool) {
for complexType in parser.complexTypesInfos where !parser.protocolNames.contains(complexType.name) {
// write DTO structs to disk:
let protoDeclaration = parser.protocols?.first(where: { $0.name == complexType.parentName })
if let content = generateClassFinally(nil,
withName: complexType.name,
parentProtocol: protoDeclaration,
storedProperties: complexType.restprops,
parseSupport: parseSupport) {
writeContent(content, toFileAtPath: pathForClassName(complexType.name, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
if parseSupport {
if let content = generateParseExtensionFinally(nil,
withName: complexType.name,
parentProtocol: protoDeclaration,
storedProperties: complexType.restprops) {
writeContent(content, toFileAtPath: pathForParseExtension(complexType.name, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
}
}
}
final func generateClassFilesFromCoreData(inDirectory outputDir: String, withParseSupport parseSupport: Bool) {
let entities = parser.coreDataEntities
for thisEntity in entities {
guard let className = thisEntity.attributeStringValue(for: "name"),
let unwrappedEntity = thisEntity as? XMLElement else { continue }
if let content = generateEnumFileFor(entity: unwrappedEntity, withName: className) {
writeContent(content, toFileAtPath: pathForClassName(className, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
}
for thisEntity in entities {
guard let className = thisEntity.attributeStringValue(for: "name"),
let unwrappedEntity = thisEntity as? XMLElement else { continue }
if let content = generateProtocolFileForEntity(unwrappedEntity, withName: className) {
writeContent(content, toFileAtPath: pathForClassName(className, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
}
for thisEntity in entities {
guard let className = thisEntity.attributeStringValue(for: "name"),
let unwrappedEntity = thisEntity as? XMLElement else { continue }
if let content = generateClassFileForEntity(unwrappedEntity, withName: className, parseSupport: parseSupport) {
writeContent(content, toFileAtPath: pathForClassName(className, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType()))
}
if parseSupport {
guard let className = thisEntity.attributeStringValue(for: "name"),
let unwrappedEntity = thisEntity as? XMLElement else { continue }
if let content = generateParseExtensionForEntity(unwrappedEntity,
withName: className) {
let outputpath = pathForParseExtension(className, inFolder: outputDir, fileExtension: fileExtensionForCurrentOutputType())
writeContent(content, toFileAtPath: outputpath)
}
}
}
}
// MARK: - Helper Methods
private final func generateProtocolFileForEntity(_ entity: XMLElement, withName className: String) -> String? {
guard (entity.children as? [XMLElement]) != nil else { return nil }
if parser.protocolNames.contains(className) {
return generateProtocolFileForProtocol(className)
}
return nil
}
private final func generateEnumFileFor(entity: XMLElement, withName className: String) -> String? {
guard (entity.children as? [XMLElement]) != nil else { return nil }
if parser.enumNames.contains(className) {
return generateEnumFileForEntity(entity, withName: className)
}
return nil
}
private final func generateEnumFileForEntity(_ entity: XMLElement, withName className: String) -> String? {
guard let properties = entity.children as? [XMLElement] else { return nil }
let restprops = properties.flatMap { RESTProperty(xmlElement: $0,
enumParentName: "String",
withEnumNames: parser.enumNames,
withProtocolNames: parser.protocolNames,
withProtocols: parser.protocols,
withPrimitiveProxyNames: parser.primitiveProxyNames,
embedParseSDKSupport: false) }
return generateEnumFileForEntityFinally(restprops, withName: className, enumParentName: "String")
}
private final func generateClassFileForEntity(_ entity: XMLElement, withName className: String, parseSupport: Bool) -> String? {
guard let properties = entity.children as? [XMLElement] else { return nil }
guard !parser.enumNames.contains(className),
!parser.protocolNames.contains(className),
!entity.isPrimitiveProxy else { return nil }
let parentProtocol: ProtocolDeclaration?
if let protocolName = entity.attribute(forName: "parentEntity")?.stringValue {
parentProtocol = (parser.protocols?.filter { $0.name == protocolName })?.first
}
else {
parentProtocol = nil
}
return generateClassFinally(properties, withName: className, parentProtocol: parentProtocol, storedProperties: nil, parseSupport: parseSupport)
}
private final func generateParseExtensionForEntity(_ entity: XMLElement, withName className: String) -> String? {
guard let properties = entity.children as? [XMLElement] else { return nil }
guard !parser.enumNames.contains(className),
!parser.protocolNames.contains(className),
!entity.isPrimitiveProxy else { return nil }
let parentProtocol: ProtocolDeclaration?
if let protocolName = entity.attribute(forName: "parentEntity")?.stringValue {
parentProtocol = (parser.protocols?.filter { $0.name == protocolName })?.first
}
else {
parentProtocol = nil
}
return generateParseExtensionFinally(properties, withName: className, parentProtocol: parentProtocol, storedProperties: nil)
}
final func createAndExportParentRelationships(inDirectory folderPath: String) {
struct ParentRel {
let name: String
let children: Set<String>
}
if parser.parentRelations.count > 0 {
let keyset = Set<String>(parser.parentRelations.map { $0.parentClass })
var parentRels = [ParentRel]()
for key in keyset {
let subcls = parser.parentRelations.filter { $0.parentClass == key && !(keyset.contains($0.subclass)) }
parentRels.append(ParentRel(name: key, children: Set(subcls.map { $0.subclass })))
}
var parRelString = "{\n"
for (idx, thisPR) in parentRels.enumerated() {
if idx != 0 { parRelString += ",\n" }
parRelString += " \"\(thisPR.name)\": [\n"
let sortedChildren = thisPR.children.sorted(by: { (left, right) -> Bool in
let leftCType = parser.complexTypesInfos.first(where: { $0.name == left })
let rightCType = parser.complexTypesInfos.first(where: { $0.name == right })
return (leftCType?.restprops.count ?? 0) < (rightCType?.restprops.count ?? 0)
})
for (ind, str) in sortedChildren.enumerated() {
if ind != 0 { parRelString += ",\n" }
parRelString += " \"\(str)\""
}
parRelString += "\n ]"
}
parRelString += "\n}"
let fileurl = URL(fileURLWithPath: folderPath)
let newUrl = fileurl.appendingPathComponent("DTOParentInfo.json")
writeContent(parRelString, toFileAtPath: newUrl.path)
}
}
final func copyStaticSwiftFiles(named filenames: [String], inDirectory folderPath: String) {
for filename in filenames {
if let swfilePath = Bundle.main.path(forResource: filename, ofType: fileExtensionForCurrentOutputType()),
let classContents = try? String(contentsOfFile: swfilePath, encoding: String.Encoding.utf8) {
writeContent(classContents, toFileAtPath: pathForClassName(filename, inFolder: folderPath, fileExtension: fileExtensionForCurrentOutputType()))
}
}
}
}
|
18310252dd09d96057a59bbae933839c
| 49.466387 | 192 | 0.618933 | false | false | false | false |
dduan/swift
|
refs/heads/master
|
test/SILGen/property_behavior.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -emit-silgen -enable-experimental-property-behaviors %s | FileCheck %s
protocol behavior {
associatedtype Value
}
extension behavior {
var value: Value {
get { }
set { }
}
}
// TODO: global accessor doesn't get walked because it's in DerivedFileUnit
var global: Int __behavior behavior
struct S1<T> {
var instance: T __behavior behavior
// CHECK-LABEL: sil hidden @_TFV17property_behavior2S1g8instancex
// CHECK: [[BEHAVIOR_IMP:%.*]] = function_ref @_TFE17property_behaviorPS_8behaviorg5valuewx5Value
// CHECK: apply [[BEHAVIOR_IMP]]<S1<T>, T>
// CHECK-LABEL: sil hidden @_TFV17property_behavior2S1s8instancex
// CHECK: [[BEHAVIOR_IMP:%.*]] = function_ref @_TFE17property_behaviorPS_8behaviors5valuewx5Value
// CHECK: apply [[BEHAVIOR_IMP]]<S1<T>, T>
static var typeLevel: T __behavior behavior
// CHECK-LABEL: sil hidden @_TZFV17property_behavior2S1g9typeLevelx
// CHECK: [[BEHAVIOR_IMP:%.*]] = function_ref @_TFE17property_behaviorPS_8behaviorg5valuewx5Value
// CHECK: apply [[BEHAVIOR_IMP]]<S1<T>.Type, T>
// CHECK-LABEL: sil hidden @_TZFV17property_behavior2S1s9typeLevelx
// CHECK: [[BEHAVIOR_IMP:%.*]] = function_ref @_TFE17property_behaviorPS_8behaviors5valuewx5Value
// CHECK: apply [[BEHAVIOR_IMP]]<S1<T>.Type, T>
}
class C1<T> {
var instance: T __behavior behavior
static var typeLevel: T __behavior behavior
}
var zero: Int { get { } }
func exerciseBehavior<T>(inout _ sx: S1<T>, inout _ sy: S1<Int>,
_ cx: C1<T>, _ cy: C1<Int>,
_ z: T) {
/* FIXME
var local: T __behavior behavior
_ = local
local = z
var localInt: Int __behavior behavior
_ = localInt
localInt = zero
*/
_ = global
global = zero
_ = sx.instance
sx.instance = z
_ = S1<T>.typeLevel
S1<T>.typeLevel = z
_ = sy.instance
sy.instance = zero
_ = S1<Int>.typeLevel
S1<Int>.typeLevel = zero
_ = cx.instance
cx.instance = z
_ = C1<T>.typeLevel
C1<T>.typeLevel = z
_ = cy.instance
cy.instance = zero
_ = C1<Int>.typeLevel
C1<Int>.typeLevel = zero
}
protocol withStorage {
associatedtype Value
var storage: Value? { get set }
}
extension withStorage {
var value: Value {
get { }
set { }
}
static func initStorage() -> Value? { }
}
// TODO: storage behaviors in non-instance context
struct S2<T> {
var instance: T __behavior withStorage
}
class C2<T> {
var instance: T __behavior withStorage
}
func exerciseStorage<T>(inout _ sx: S2<T>, inout _ sy: S2<Int>,
_ cx: C2<T>, _ cy: C2<Int>,
_ z: T) {
_ = sx.instance
sx.instance = z
_ = sy.instance
sy.instance = zero
_ = cx.instance
cx.instance = z
_ = cy.instance
cy.instance = zero
}
protocol withInit {
associatedtype Value
var storage: Value? { get set }
func parameter() -> Value
}
extension withInit {
var value: Value {
get { }
set { }
}
static func initStorage() -> Value? { }
}
// TODO: parameterized behaviors in non-instance context
func any<T>() -> T { }
struct S3<T> {
var instance: T __behavior withInit { any() }
}
class C3<T> {
var instance: T __behavior withInit { any() }
}
func exerciseStorage<T>(inout _ sx: S3<T>, inout _ sy: S3<Int>,
_ cx: C3<T>, _ cy: C3<Int>,
_ z: T) {
_ = sx.instance
sx.instance = z
_ = sy.instance
sy.instance = zero
_ = cx.instance
cx.instance = z
_ = cy.instance
cy.instance = zero
}
// FIXME: printing sil_witness_tables for behaviors should indicate what
// var decl the behavior is attached to
// CHECK-LABEL: sil_witness_table private (): behavior module property_behavior
// CHECK: associated_type Value: Int
// CHECK-LABEL: sil_witness_table private <T> S1<T>: behavior module property_behavior
// CHECK: associated_type Value: T
// CHECK-LABEL: sil_witness_table private <T> S1<T>.Type: behavior module property_behavior
// CHECK: associated_type Value: T
// CHECK-LABEL: sil_witness_table private <T> C1<T>: behavior module property_behavior
// CHECK: associated_type Value: T
// CHECK-LABEL: sil_witness_table private <T> C1<T>.Type: behavior module property_behavior
// CHECK: associated_type Value: T
// CHECK-LABEL: sil_witness_table private <T> S2<T>: withStorage module property_behavior {
// CHECK: associated_type Value: T
// CHECK: method #withStorage.storage!getter.1
// CHECK: method #withStorage.storage!setter.1
// CHECK: method #withStorage.storage!materializeForSet.1
// CHECK-LABEL: sil_witness_table private <T> C2<T>: withStorage module property_behavior {
// CHECK: associated_type Value: T
// CHECK: method #withStorage.storage!getter.1
// CHECK: method #withStorage.storage!setter.1
// CHECK: method #withStorage.storage!materializeForSet.1
|
503abc836f75b60967cd3dded57bd764
| 25.721925 | 107 | 0.63358 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureCardPayment/Sources/FeatureCardPaymentData/Client/CardClient.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Errors
import FeatureCardPaymentDomain
import Foundation
import NetworkKit
final class CardClient: CardClientAPI {
// MARK: - Types
private enum Parameter {
static let currency = "currency"
}
private enum Path {
static let card = ["payments", "cards"]
static let cardSuccessRate = ["payments", "cards", "success-rate"]
static func activateCard(with id: String) -> [String] { Path.card + [id, "activate"] }
}
// MARK: - Properties
private let requestBuilder: RequestBuilder
private let networkAdapter: NetworkAdapterAPI
// MARK: - Setup
init(
networkAdapter: NetworkAdapterAPI = resolve(tag: DIKitContext.retail),
requestBuilder: RequestBuilder = resolve(tag: DIKitContext.retail)
) {
self.networkAdapter = networkAdapter
self.requestBuilder = requestBuilder
}
// MARK: - CardListClientAPI
/// Streams a list of available cards
/// - Returns: A Single with `CardPayload` array
func getCardList(enableProviders: Bool) -> AnyPublisher<[CardPayload], NabuNetworkError> {
let path = Path.card
let parameters = [
URLQueryItem(name: "cardProvider", value: "true")
]
let request = requestBuilder.get(
path: path,
parameters: enableProviders ? parameters : nil,
authenticated: true
)!
return networkAdapter.perform(request: request)
}
// MARK: - CardDetailClientAPI
func getCard(by id: String) -> AnyPublisher<CardPayload, NabuNetworkError> {
let path = Path.card + [id]
let request = requestBuilder.get(
path: path,
authenticated: true
)!
return networkAdapter.perform(request: request)
}
// MARK: - CardDeletionClientAPI
func deleteCard(by id: String) -> AnyPublisher<Void, NabuNetworkError> {
let path = Path.card + [id]
let request = requestBuilder.delete(
path: path,
authenticated: true
)!
return networkAdapter.perform(request: request)
}
// MARK: - CardChargeClientAPI
func chargeCard(by id: String) -> AnyPublisher<Void, NabuNetworkError> {
let path = Path.card + [id, "charge"]
let request = requestBuilder.post(
path: path,
authenticated: true
)!
return networkAdapter.perform(request: request)
}
// MARK: - CardAdditionClientAPI
func add(
for currency: String,
email: String,
billingAddress: CardPayload.BillingAddress,
paymentMethodTokens: [String: String]
) -> AnyPublisher<CardPayload, NabuNetworkError> {
struct RequestPayload: Encodable {
let currency: String
let email: String
let address: CardPayload.BillingAddress
let paymentMethodTokens: [String: String]
}
let payload = RequestPayload(
currency: currency,
email: email,
address: billingAddress,
paymentMethodTokens: paymentMethodTokens
)
let path = Path.card
let request = requestBuilder.post(
path: path,
body: try? payload.encode(),
authenticated: true
)!
return networkAdapter.perform(request: request)
}
// MARK: - CardActivationClientAPI
/// Attempt to register the card method with the partner.
/// Successful response should have card object and status should move to ACTIVE.
/// - Parameters:
/// - id: ID of the card
/// - url: Everypay only - URL to return to after card verified
/// - cvv: Card verification value
/// - Returns: The card details
func activateCard(
by id: String,
url: String,
cvv: String
) -> AnyPublisher<ActivateCardResponse.Partner, NabuNetworkError> {
struct Attributes: Encodable {
struct EveryPay: Encodable {
let customerUrl: String
}
let everypay: EveryPay?
let redirectURL: String
let cvv: String
let useOnlyAlreadyValidatedCardRef = false
init(redirectURL: String, cvv: String) {
everypay = .init(customerUrl: redirectURL)
self.cvv = cvv
self.redirectURL = redirectURL
}
}
let path = Path.activateCard(with: id)
let payload = Attributes(redirectURL: url, cvv: cvv)
let request = requestBuilder.post(
path: path,
body: try? payload.encode(),
authenticated: true
)!
return networkAdapter.perform(request: request)
.map { (response: ActivateCardResponse) in
response.partner
}
.eraseToAnyPublisher()
}
// MARK: - CardSuccessRateClientAPI
func getCardSuccessRate(
binNumber: String
) -> AnyPublisher<CardSuccessRate.Response, NabuNetworkError> {
let path = Path.cardSuccessRate
let parameters = [
URLQueryItem(name: "bin", value: binNumber)
]
let request = requestBuilder.get(
path: path,
parameters: parameters,
authenticated: true
)!
return networkAdapter.perform(request: request)
.map { (response: CardSuccessRate) in
CardSuccessRate.Response(response, bin: binNumber)
}
.eraseToAnyPublisher()
}
}
|
077c44760d15d27949240a166265b65a
| 29.235294 | 94 | 0.598161 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/HistoricalBalanceCell/HistoricalBalanceCellPresenter.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import MoneyKit
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxRelay
import RxSwift
import ToolKit
final class HistoricalBalanceCellPresenter {
private typealias AccessibilityId = Accessibility.Identifier.Dashboard.AssetCell
private let badgeImageViewModel: BadgeImageViewModel
var thumbnail: Driver<BadgeImageViewModel> {
.just(badgeImageViewModel)
}
var name: Driver<LabelContent> {
.just(
.init(
text: interactor.cryptoCurrency.name,
font: .main(.semibold, 20),
color: .dashboardAssetTitle,
accessibility: .id("\(AccessibilityId.titleLabelFormat)\(interactor.cryptoCurrency.name)")
)
)
}
var assetNetworkContent: Driver<LabelContent?> {
let network = cryptoCurrency.assetModel.kind.erc20ParentChain?.name
guard let network = network else {
return .just(nil)
}
return .just(
.init(
text: network,
font: .main(.semibold, 12),
color: .descriptionText,
accessibility: .id("\(AccessibilityId.titleLabelFormat)\(network)")
)
)
}
var displayCode: Driver<LabelContent> {
.just(
.init(
text: interactor.cryptoCurrency.displayCode,
font: .main(.medium, 14),
color: .descriptionText,
accessibility: .id("\(AccessibilityId.titleLabelFormat)\(interactor.cryptoCurrency.displayCode)")
)
)
}
let pricePresenter: AssetPriceViewPresenter
let sparklinePresenter: AssetSparklinePresenter
let balancePresenter: AssetBalanceViewPresenter
var cryptoCurrency: CryptoCurrency {
interactor.cryptoCurrency
}
private let interactor: HistoricalBalanceCellInteractor
init(
interactor: HistoricalBalanceCellInteractor,
appMode: AppMode
) {
self.interactor = interactor
sparklinePresenter = AssetSparklinePresenter(
with: interactor.sparklineInteractor
)
pricePresenter = AssetPriceViewPresenter(
interactor: interactor.priceInteractor,
descriptors: .assetPrice(accessibilityIdSuffix: interactor.cryptoCurrency.displayCode)
)
balancePresenter = AssetBalanceViewPresenter(
alignment: appMode == .defi ? .trailing : .leading,
interactor: interactor.balanceInteractor,
descriptors: .default(
cryptoAccessiblitySuffix: AccessibilityId.cryptoBalanceLabelFormat,
fiatAccessiblitySuffix: AccessibilityId.fiatBalanceLabelFormat
)
)
let theme = BadgeImageViewModel.Theme(
backgroundColor: .background,
cornerRadius: .round,
imageViewContent: ImageViewContent(
imageResource: interactor.cryptoCurrency.logoResource,
accessibility: .id("\(AccessibilityId.assetImageView)\(interactor.cryptoCurrency.displayCode)"),
renderingMode: .normal
),
marginOffset: 0
)
badgeImageViewModel = BadgeImageViewModel(theme: theme)
}
}
|
b71a137d5cd25dc6274381f82917cd56
| 32.247525 | 113 | 0.634902 | false | false | false | false |
xtcan/playerStudy_swift
|
refs/heads/master
|
TCVideo_Study/TCVideo_Study/Classes/Live/View/ChatView/ChatToolsView.swift
|
apache-2.0
|
1
|
//
// ChatToolsView.swift
// TCVideo_Study
//
// Created by tcan on 2017/7/18.
// Copyright © 2017年 tcan. All rights reserved.
//
import UIKit
protocol ChatToolsViewDelegate : class {
func chatToolsView(toolView : ChatToolsView, message : String)
}
class ChatToolsView: UIView ,NibLoadable{
/// 代理属性
weak var delegate : ChatToolsViewDelegate?
fileprivate lazy var emotionBtn : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
fileprivate lazy var emotionView : EmotionView = EmotionView(frame : CGRect(x: 0, y: 0, width: kScreenW, height: 250))
/// 文字输入框
@IBOutlet weak var inputTextField: UITextField!
/// 发送按钮
@IBOutlet weak var sendMsgBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
/// 输入文字
@IBAction func textFieldDidEdit(_ sender: UITextField) {
sendMsgBtn.isEnabled = sender.text!.characters.count != 0
}
/// 发送按钮点击
@IBAction func sendBtnClick(_ sender: UIButton) {
//获取输入到内容
let message = inputTextField.text!
//清空内容
inputTextField.text = ""
sender.isEnabled = false
//把输入的内容传递给代理
delegate?.chatToolsView(toolView: self, message: message)
}
}
extension ChatToolsView {
fileprivate func setupUI(){
//注:textfield显示不了表情attachment,用textview才可以
//测试: 让textFiled显示`富文本`
// let attrString = NSAttributedString(string: "I am fine", attributes: [NSForegroundColorAttributeName : UIColor.green])
// let attachment = NSTextAttachment()
// attachment.image = UIImage(named: "[大哭]")
// let attrStr = NSAttributedString(attachment: attachment)
// inputTextField.attributedText = attrStr
// 1.初始化inputView中rightView
emotionBtn.setImage(UIImage(named: "chat_btn_emoji"), for: .normal)
emotionBtn.setImage(UIImage(named: "chat_btn_keyboard"), for: .selected)
emotionBtn.addTarget(self, action: #selector(emotionBtnClick(_:)), for: UIControlEvents.touchUpInside)
inputTextField.rightView = emotionBtn
inputTextField.rightViewMode = .always
inputTextField.allowsEditingTextAttributes = true
// 2.设置emotionView的闭包(weak当对象销毁值, 会自动将指针指向nil)
// weak var weakSelf = self
emotionView.emotionClickCallback = {[weak self] emotion in
// 1.判断是否是删除按钮
if emotion.emotionName == "delete-n" {
self?.inputTextField.deleteBackward()
return
}
// 2.获取光标位置
guard let range = self?.inputTextField.selectedTextRange else { return }
self?.inputTextField.replace(range, withText: emotion.emotionName)
}
}
}
extension ChatToolsView {
@objc fileprivate func emotionBtnClick(_ btn : UIButton){
btn.isSelected = !btn.isSelected
//切换键盘
//记录当前光标的位置
let range = inputTextField.selectedTextRange
inputTextField.resignFirstResponder()
inputTextField.inputView = inputTextField.inputView == nil ? emotionView : nil
inputTextField.becomeFirstResponder()
//恢复光标的位置
inputTextField.selectedTextRange = range
}
}
|
e618766b17f3f0e67950e43cf253ba18
| 30.72381 | 129 | 0.631342 | false | false | false | false |
apple/swift-experimental-string-processing
|
refs/heads/main
|
Tests/Prototypes/PTCaRet/PTCaRet.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/*
NOTE: This is still work-in-progress, but is meant to highlight
a very different kind of matching application.
PTCaRet is PTLTL + CaRet (call and return). It extends PTLTL with
the notion of an "abstract trace" using the basic computing
abstraction: function calls.
Traces can "call" a function, and the abstact trace will just
see a call followed by a return: the call abstracts any
intermediary events while that subroutine executes.
The subroutine itself sees the full trace in its abstract trace,
including its own triggered events, but it doesn't see events
from calls it makes to its subroutines.
Full trace call appears as:
call begin ...body... end return
where `call/return` appear in caller's abstract trace. In the
callee's abstract trace, `call/begin/end/return`, as well as any
direct events triggered (i.e. not from inside a subroutine call)
appear.
A function call is like a fence. While a fence is a single
object, it makes sense to talk about both the fence itself
as well as from which side you're looking at it.
By anchoring against `begin`, you are specifying formulae over
your dynamic call stack, as you can see those `begin` but not any
that were abstracted over by completed function calls. I.e.
abstract operations paired with this `call/begin/end/return`
convention allows one to define an emergent "call stack" trace
and specify properties of that.
Properties could include "g cannot be called indirectly by f".
"If f was called, an unfinished call to g must be on the call
stack", etc.
Abstract since against begin enforces a function precondition
that has also held as an invariant up to the present moment
(or containing formula). `let f = .abstractSince(x, .begin)`
means `x` held as a precondition at the start of the currently
executing function, and has held up until... whatever you're
going to use `f` with.
Normal PTLTL formulae require 1 global bit per temporal operator.
PTCaRet requires that monitors have a local bit-stack. Formulae
require 1 stack bit per abstract temporal operator.
NOTE: Really really want small-bitvector data structure. Call
stack can be a single small-bitvector via a AoS->SoA conversion.
Inspiration: "Synthesizing Monitors for Safety Properties - This Time With Calls and Returns" by Rosu et al.
*/
public enum PTCaRet<Event: Hashable> {}
extension PTCaRet {
enum Formula {
// Atoms
case bool(Bool)
case event(Event)
// Custom Predicates
case customEvent((Event) -> Bool)
case custom(() -> Bool) // TODO: Matching state to closure
// Boolean logic
indirect case not(Formula)
indirect case and(Formula, Formula)
indirect case or(Formula, Formula)
static func xor(_ a: Formula, _ b: Formula) -> Formula {
.and(.or(a, b), .not(.and(a, b)))
}
static func implies(_ a: Formula, _ b: Formula) -> Formula {
.or(b, .not(a))
}
static func equals(_ a: Formula, _ b: Formula) -> Formula {
.and(.implies(a, b), .implies(b, a))
}
// MARK: - temporal operators
/// `a` held true in prior trace
///
/// Initially false (if trace is empty)
indirect case previously(Formula)
/// `a` has held since `b`
///
/// Either `b` holds currently, or `a` holds and
/// `.previously(.since(a, b))` holds.
///
/// Initially false (if trace is empty)
///
/// TODO: Isn't this a strong since instead of weak since?
/// Don't we need an `.or(.empty, .since...)` to permit
/// always `a`?
indirect case since(Formula, Formula)
/*
As a logic, PTLTL is usually specified with just since
and previously, as all others can be derived from those.
I'm making always/never/sometime fundamental. This
dramatically improves the implementation and fixes
corner-case bugs one tends to find in papers.
*/
/// `a` has always held
///
/// .since(a, .bool(false))
///
/// (but I think the since we have is actually strong)
indirect case always(Formula)
/// `a` never happened
///
/// .always(.not(a))
///
indirect case never(Formula)
/// `a` happened sometime in the past
///
/// .not(.never(a))
///
indirect case sometime(Formula)
// Abstract atoms
case call // Appears in caller and callee trace
case begin // Appears in callee trace
// ... body of function ...
case end // Appears in callee trace
case ret // Appears in caller and callee trace
// Abstract custom predicates
case callSpecific(String)
// TODO: more
// MARK: - Abstract temporal operators
/// `a` held true in prior abstract trace
///
/// Initially false (if abstract trace is empty)
indirect case abstractPreviously(Formula)
/// `a` has held since `b` in the abstract trace
///
/// Either `b` holds currently, or `a` holds and
/// `.previously(.abstractSince(a, b))` holds.
///
/// Initially false (if trace is empty)
///
/// TODO: Isn't this a strong since instead of weak since?
/// Don't we need an `.or(.empty, .since...)` to permit
/// always `a`?
indirect case abstractSince(Formula, Formula)
/*
Again, gonna make others fundamental
*/
/// `a` has always held in the abstract trace
///
/// .abstractSince(a, since: .bool(false))
///
/// (but I think the since we have is actually strong)
indirect case abstractAlways(Formula)
/// `a` never happened in the abstract trace
///
/// .abstractAlways(.not(a))
///
indirect case abstractNever(Formula)
/// `a` happened sometime in the past in the abstract trace
///
/// .not(.abstractNever(a))
///
indirect case abstractSometime(Formula)
/*
*/
// MARK: - Stack operators
/*
Again making these otherwise-derived cases fundamental
*/
/// `a` has held true at the start of every (non-terminated) function
/// on the call stack since `b` most recently held true at the start of a (non-terminated)
/// function on the call stack.
///
/// .abstractCheck(
/// a, filteredBy: .begin,
/// since: b, filteredBy: .begin)
///
/// I.e. ignore completed function calls
///
indirect case stackSinceOnBegins(Formula, Formula)
/// `a` has held true at every call of a function (including terminated ones)
/// since `b` held true at the call of a (non-terminated)
/// function on the call stack.
///
/// I.e. ignore completed function calls
///
/// .abstractCheck(
/// a, filteredBy: .call,
/// since: .previously(b), filteredBy: .begin)
///
indirect case stackSinceOnCalls(Formula, Formula)
// TODO: Is the above actually a good idea? Should we just
// have `a` also filtered on begins and do a previously?
// That would mean we have derived a "stack trace" using
// begin and we're running formula over the stack trace.
// TODO: Or, do we want to split things out? How should we do this?
/// `a` has always held at the start of every (non-terminated) function on the call
/// stack
///
indirect case stackAlwaysOnBegins(Formula)
/// `a` has always held at every call of a function in the abstract trace
///
indirect case stackAlwaysOnCalls(Formula)
}
}
extension PTCaRet.Formula {
init(_ a: Formula, since b: Formula) {
self = .since(a, b)
}
}
/// A trace is a (finite) sequence of states.
///
/// A non-empty trace can be decomposed into the current
/// state and the trace prior to transitioning into that state.
struct Trace<State> {
var isEmpty: Bool {
fatalError()
}
var current: State {
fatalError()
}
var prior: Trace<State> {
fatalError()
}
}
// Just my attempts at making sane programming tools around this
// logic
extension PTCaRet.Formula {
typealias Formula = Self
/// `a` has never held since `b` most recently held.
///
/// `b`, or `¬a`and `.previously(.neverSince(a, b))`
///
static func never(
_ a: Formula, since b: Formula
) -> Formula {
.since(.not(a), b)
}
/// `a` has held sometime since `b` most recently held.
///
/// `b`, or `¬a`and `.previously(.neverSince(a, b))`
///
static func abstractNever(
_ a: Formula, since b: Formula
) -> Formula {
.abstractSince(.not(a), b)
}
/// `a` has held sometime since `b` most recently held.
///
/// `¬b`, and `a` or `.previously(.sometimeSince(a, b))`
///
static func sometime(
_ a: Formula, since b: Formula
) -> Formula {
.not(.since(.not(a), b))
}
/// `a` has held sometime since `b` most recently held.
///
/// `¬b`, and `a` or
/// `.previously(.abstractSometimeSince(a, b))`
///
static func abstractSometime(
_ a: Formula, since b: Formula
) -> Formula {
.not(.abstractSince(.not(a), b))
}
// MARK: - compound temporal operators
/// If `a` occurred since `start`, `b` must have held sometime after
///
/// (¬a S start ∨ ¬(¬b S a))
///
/// a S_never start ∨ b S_sometime a
///
static func requirement(
_ a: Formula,
requiresEventually b: Formula,
since start: Formula
) -> Formula {
.or(.never(a, since: start), .sometime(b, since: a))
}
/// If `a` abstract-occurred since `start`, `b` must have held sometime after
///
/// (¬a S̅ start ∨ ¬(¬b S̅ a))
///
static func abstractRequirement(
_ a: Formula,
requiresEventually b: Formula,
since start: Formula
) -> Formula {
.or(.abstractNever(a, since: start), .abstractSometime(b, since: a))
}
/// If `a` occurred since `start`, `b` must have held sometime after. This
/// is checked when `trigger` happens.
///
/// trigger → .requirement(
/// a, requiresEventually: b, since: start)
///
static func requirement(
_ a: Formula,
requiresEventually b: Formula,
since start: Formula,
triggeredBy trigger: Formula
) -> Formula {
.implies(
trigger,
.requirement(a, requiresEventually: b, since: start))
}
/// If `a` abstract-occurred since `start`, `b` must have held sometime after. This
/// is checked when `trigger` happens.
///
/// trigger → (¬a S̅ start ∨ ¬(¬b S̅ a))
///
static func abstractRequirement(
_ a: Formula,
requiresEventually b: Formula,
since start: Formula,
triggeredBy trigger: Formula
) -> Formula {
.implies(
trigger,
.abstractRequirement(a, requiresEventually: b, since: start))
}
/// `a` simultaneously held when `b` most recently held.
///
/// (b → a) ∧ (¬b → ◦(b → a) S b
///
static func simultaneously(
_ a: Formula,
during b: Formula
) -> Formula {
// Note: More efficient to implement directly
.and(
.implies(b, a),
.implies(.not(b), .since(.previously(.implies(b, a)), b)))
}
/// `a` simultaneously held when `b` most recently held.
///
/// (b → a) ∧ (¬b → ◦(b → a) S̅ b
///
static func abstractSimultaneously(
_ a: Formula,
during b: Formula
) -> Formula {
// Note that we don't do abstract previously, it's not necessary
.and(
.implies(b, a),
.implies(.not(b), .abstractSince(.previously(.implies(b, a)), b)))
}
/// `a` held at the start of the current function
static func atFunctionBegin(_ a: Formula) -> Formula {
.abstractSimultaneously(a, during: .begin)
}
/// `a` held during the call of the current function (immediately before start, from caller's context)
static func atFunctionCall(_ a: Formula) -> Formula {
.atFunctionBegin(.previously(a))
}
/// `a` has held true at every occurrence of `filterA` since the
/// most recent occurrence of both `b` and `filterB`.
///
/// (filterA → a) S (filterB ∧ b)
///
static func check(
_ a: Formula, filteredBy filterA: Formula,
since b: Formula, filteredBy filterB: Formula
) -> Formula {
.since(.implies(filterA, a), .and(filterB, b))
}
/// `a` has held true at every occurrence of `filterA` since the
/// most recent occurrence of both `b` and `filterB`.
///
/// (filterA → a) S̅ (filterB ∧ b)
///
static func abstractCheck(
_ a: Formula, filteredBy filterA: Formula,
since b: Formula, filteredBy filterB: Formula
) -> Formula {
.abstractSince(.implies(filterA, a), .and(filterB, b))
}
}
///
/// Derivations:
///
/// ¬(¬'enter_phase_1' S 'begin')
/// 'enter_phase_1' S_sometime 'begin'
///
/// ¬'acquire' S 'enter_phase_1' ∨ ¬(¬'release' S 'acquire')
/// ¬'acquire' S 'enter_phase_1' ∨ 'release' S_sometime 'acquire'
/// 'acquire' S_never 'enter_phase_1' ∨ 'release' S_sometime 'acquire'
///
/// (¬acquire S begin ∨ ¬(¬release S acquire))
/// acquire S_never begin ∨ release S_sometime acquire
///
/// @ψ = (begin → ψ) ∧ (¬begin → ◦(begin → ψ) S̅ begin).
|
1efe8310d4c93dd5565ccccc3cba428b
| 27.263713 | 109 | 0.620587 | false | false | false | false |
wireapp/wire-ios-data-model
|
refs/heads/develop
|
Source/ConversationList/ConversationDirectory.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2019 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 Foundation
public enum ConversationListType {
case archived, unarchived, pending, contacts, groups, favorites, folder(_ folder: LabelType)
}
public struct ConversationDirectoryChangeInfo {
public var reloaded: Bool
public var updatedLists: [ConversationListType]
public var updatedFolders: Bool
public init(reloaded: Bool, updatedLists: [ConversationListType], updatedFolders: Bool) {
self.reloaded = reloaded
self.updatedLists = updatedLists
self.updatedFolders = updatedFolders
}
}
public protocol ConversationDirectoryObserver: AnyObject {
func conversationDirectoryDidChange(_ changeInfo: ConversationDirectoryChangeInfo)
}
public protocol ConversationDirectoryType {
/// All folder created by the user
var allFolders: [LabelType] { get }
/// Create a new folder with a given name
func createFolder(_ name: String) -> LabelType?
/// Retrieve a conversation list by a given type
func conversations(by: ConversationListType) -> [ZMConversation]
/// Observe changes to the conversation lists & folders
///
/// NOTE that returned token must be retained for as long you want the observer to be active
func addObserver(_ observer: ConversationDirectoryObserver) -> Any
}
extension ZMConversationListDirectory: ConversationDirectoryType {
public func conversations(by type: ConversationListType) -> [ZMConversation] {
switch type {
case .archived:
return archivedConversations as! [ZMConversation]
case .unarchived:
return unarchivedConversations as! [ZMConversation]
case .pending:
return pendingConnectionConversations as! [ZMConversation]
case .contacts:
return oneToOneConversations as! [ZMConversation]
case .groups:
return groupConversations as! [ZMConversation]
case .favorites:
return favoriteConversations as! [ZMConversation]
case .folder(let label):
guard let objectID = (label as? Label)?.objectID else { return [] } // TODO jacob make optional?
return listsByFolder[objectID] as? [ZMConversation] ?? []
}
}
public func addObserver(_ observer: ConversationDirectoryObserver) -> Any {
let observerProxy = ConversationListObserverProxy(observer: observer, directory: self)
let listToken = ConversationListChangeInfo.addListObserver(observerProxy, for: nil, managedObjectContext: managedObjectContext)
let reloadToken = ConversationListChangeInfo.addReloadObserver(observerProxy, managedObjectContext: managedObjectContext)
let folderToken = ConversationListChangeInfo.addFolderObserver(observerProxy, managedObjectContext: managedObjectContext)
return [folderToken, listToken, reloadToken, observerProxy]
}
@objc
public func createFolder(_ name: String) -> LabelType? {
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: UUID(), create: true, in: managedObjectContext, created: &created)
label?.name = name
label?.kind = .folder
return label
}
}
private class ConversationListObserverProxy: NSObject, ZMConversationListObserver, ZMConversationListReloadObserver, ZMConversationListFolderObserver {
weak var observer: ConversationDirectoryObserver?
var directory: ZMConversationListDirectory
init(observer: ConversationDirectoryObserver, directory: ZMConversationListDirectory) {
self.observer = observer
self.directory = directory
}
func conversationListsDidReload() {
observer?.conversationDirectoryDidChange(ConversationDirectoryChangeInfo(reloaded: true, updatedLists: [], updatedFolders: false))
}
func conversationListsDidChangeFolders() {
observer?.conversationDirectoryDidChange(ConversationDirectoryChangeInfo(reloaded: false, updatedLists: [], updatedFolders: true))
}
func conversationListDidChange(_ changeInfo: ConversationListChangeInfo) {
let updatedLists: [ConversationListType]
if changeInfo.conversationList === directory.oneToOneConversations {
updatedLists = [.contacts]
} else if changeInfo.conversationList === directory.groupConversations {
updatedLists = [.groups]
} else if changeInfo.conversationList === directory.archivedConversations {
updatedLists = [.archived]
} else if changeInfo.conversationList === directory.pendingConnectionConversations {
updatedLists = [.pending]
} else if changeInfo.conversationList === directory.unarchivedConversations {
updatedLists = [.unarchived]
} else if changeInfo.conversationList === directory.favoriteConversations {
updatedLists = [.favorites]
} else if let label = changeInfo.conversationList.label, label.kind == .folder {
updatedLists = [.folder(label)]
} else {
updatedLists = []
}
observer?.conversationDirectoryDidChange(ConversationDirectoryChangeInfo(reloaded: false, updatedLists: updatedLists, updatedFolders: false))
}
}
|
173067630ff173a8d65e4a460a4628db
| 39.034014 | 151 | 0.717247 | false | false | false | false |
fnazarios/weather-app
|
refs/heads/dev
|
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Subjects/PublishSubject.swift
|
apache-2.0
|
4
|
//
// PublishSubject.swift
// Rx
//
// Created by Krunoslav Zaher on 2/11/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an object that is both an observable sequence as well as an observer.
Each notification is broadcasted to all subscribed observers.
*/
public class PublishSubject<Element>
: Observable<Element>
, SubjectType
, Cancelable
, ObserverType
, LockOwnerType
, SynchronizedOnType
, SynchronizedSubscribeType
, SynchronizedUnsubscribeType
, SynchronizedDisposeType {
public typealias SubjectObserverType = PublishSubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
let _lock = NSRecursiveLock()
// state
private var _disposed = false
private var _observers = Bag<AnyObserver<Element>>()
private var _stoppedEvent = nil as Event<Element>?
/**
Indicates whether the subject has been disposed.
*/
public var disposed: Bool {
get {
return _disposed
}
}
/**
Creates a subject.
*/
public override init() {
super.init()
}
/**
Notifies all subscribed observers about next event.
- parameter event: Event to send to the observers.
*/
public func on(event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next(_):
if _disposed || _stoppedEvent != nil {
return
}
_observers.on(event)
case .Completed, .Error:
if _stoppedEvent == nil {
_stoppedEvent = event
_observers.on(event)
_observers.removeAll()
}
}
}
/**
Subscribes an observer to the subject.
- parameter observer: Observer to subscribe to the subject.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
return synchronizedSubscribe(observer)
}
func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return NopDisposable.instance
}
if _disposed {
observer.on(.Error(RxError.DisposedError))
return NopDisposable.instance
}
let key = _observers.insert(observer.asObserver())
return SubscriptionDisposable(owner: self, key: key)
}
func _synchronized_unsubscribe(disposeKey: DisposeKey) {
_ = _observers.removeKey(disposeKey)
}
/**
Returns observer interface for subject.
*/
public func asObserver() -> PublishSubject<Element> {
return self
}
/**
Unsubscribe all observers and release resources.
*/
public func dispose() {
synchronizedDispose()
}
func _synchronized_dispose() {
_disposed = true
_observers.removeAll()
_stoppedEvent = nil
}
}
|
23749f66f2aadc2e39e77ada4a3360e6
| 24.382813 | 102 | 0.599754 | false | false | false | false |
iotn2n/CocoaMqttC
|
refs/heads/master
|
CocoaMqttC/ViewController.swift
|
mit
|
1
|
//
// EventBus.swift
// CocoaMqttC
//
// Created by iotn2n on 16/4/23.
// Copyright © 2016年 iot. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var animal: String?
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var animalsImageView: UIImageView! {
didSet {
animalsImageView.clipsToBounds = true
animalsImageView.layer.borderWidth = 1.0
animalsImageView.layer.cornerRadius = animalsImageView.frame.width / 2.0
}
}
@IBAction func connectToServer() {
let chatViewController = storyboard?.instantiateViewControllerWithIdentifier("ChatViewController") as? ChatViewController
navigationController!.pushViewController(chatViewController!, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.interactivePopGestureRecognizer?.enabled = false
tabBarController?.delegate = self
animal = tabBarController?.selectedViewController?.tabBarItem.title
}
override func viewWillAppear(animated: Bool) {
navigationController?.navigationBar.hidden = false
}
}
extension ViewController: UITabBarControllerDelegate {
// Prevent automatic popToRootViewController on double-tap of UITabBarController
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
return viewController != tabBarController.selectedViewController
}
}
|
781b1e844483871830e1a8893c9b4431
| 31.458333 | 134 | 0.717405 | false | false | false | false |
imxieyi/iosu
|
refs/heads/master
|
iosu/Scenes/GamePlayScene.swift
|
mit
|
1
|
//
// GameScene.swift
// iosu
//
// Created by xieyi on 2017/3/28.
// Copyright © 2017年 xieyi. All rights reserved.
//
import SpriteKit
import SpriteKitEasingSwift
import GameplayKit
class GamePlayScene: SKScene {
var bmactions:[SKAction] = []
var actiontimepoints:[Int] = []
static var testBMIndex = 6 //The index of beatmap to test in the beatmaps
var maxlayer:CGFloat=100000
var minlayer:CGFloat=0
var hitaudioHeader:String = "normal-"
static var realwidth:Double=512
static var realheight:Double=384
static var scrwidth:Double=750
static var scrheight:Double=750
static var scrscale:Double=1
static var leftedge:Double=0
static var bottomedge:Double=0
static var bgdim:Double=0.2
static var effvolume:Float = 1.0
static var current:SKScene?
fileprivate var actions:ActionSet?
fileprivate var bgvactions:[SKAction]=[]
fileprivate var bgvtimes:[Int]=[]
open static var sliderball:SliderBall?
var bm:Beatmap?
override func sceneDidLoad() {
GamePlayScene.current = self
GamePlayScene.sliderball=SliderBall(scene: self)
GamePlayScene.scrscale=Double(size.height)/480.0
GamePlayScene.realwidth=512.0*GamePlayScene.scrscale
GamePlayScene.realheight=384.0*GamePlayScene.scrscale
GamePlayScene.scrwidth=Double(size.width)
GamePlayScene.scrheight=Double(size.height)
GamePlayScene.bottomedge=(Double(size.height)-GamePlayScene.realheight)/2
GamePlayScene.leftedge=(Double(size.width)-GamePlayScene.realwidth)/2
let beatmaps=BeatmapScanner()
debugPrint("test beatmap:\(beatmaps.beatmaps[GamePlayScene.testBMIndex])")
debugPrint("Enter GamePlayScene, screen size: \(size.width)*\(size.height)")
debugPrint("scrscale:\(GamePlayScene.scrscale)")
debugPrint("realwidth:\(GamePlayScene.realwidth)")
debugPrint("realheight:\(GamePlayScene.realheight)")
debugPrint("bottomedge:\(GamePlayScene.bottomedge)")
debugPrint("leftedge:\(GamePlayScene.leftedge)")
do{
bm=try Beatmap(file: (beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [beatmaps.beatmaps[GamePlayScene.testBMIndex]])[0])
if (bm?.bgvideos.count)! > 0 && GameViewController.showvideo {
debugPrint("got \(String(describing: bm?.bgvideos.count)) videos")
for i in 0...(bm?.bgvideos.count)!-1 {
let file=(beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [(bm?.bgvideos[i].file)!])[0]
//var file=URL(fileURLWithPath: beatmaps.beatmapdirs[GamePlayScene.testBMIndex], isDirectory: true)
//let file=beatmaps.bmdirurls[GamePlayScene.testBMIndex].appendingPathComponent(bm?.bgvideos[i])
if FileManager.default.fileExists(atPath: file) {
bgvactions.append(BGVPlayer.setcontent(file))
bgvtimes.append((bm?.bgvideos[i].time)!)
} else {
debugPrint("video not found: \(file)")
}
}
} else if bm?.bgimg != "" && !(StoryBoardScene.hasSB) {
debugPrint("got bgimg:\(String(describing: bm?.bgimg))")
let bgimg=UIImage(contentsOfFile: (beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [(bm?.bgimg)!])[0])
if bgimg==nil {
debugPrint("Background image not found")
} else {
let bgnode=SKSpriteNode(texture: SKTexture(image: bgimg!))
let bgscale:CGFloat = max(size.width/(bgimg?.size.width)!,size.height/(bgimg?.size.height)!)
bgnode.setScale(bgscale)
bgnode.zPosition=0
bgnode.position=CGPoint(x: size.width/2, y: size.height/2)
addChild(bgnode)
}
}
let dimnode=SKShapeNode(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height))
dimnode.fillColor = .black
dimnode.alpha=CGFloat(GamePlayScene.bgdim)
dimnode.zPosition=1
addChild(dimnode)
switch (bm?.sampleSet)! {
case .auto:
//Likely to be an error
hitaudioHeader="normal-"
break
case .normal:
hitaudioHeader="normal-"
break
case .soft:
hitaudioHeader="soft-"
break
case .drum:
hitaudioHeader="drum-"
break
}
debugPrint("bgimg:\(String(describing: bm?.bgimg))")
debugPrint("audio:\(String(describing: bm?.audiofile))")
debugPrint("colors: \(String(describing: bm?.colors.count))")
debugPrint("timingpoints: \(String(describing: bm?.timingpoints.count))")
debugPrint("hitobjects: \(String(describing: bm?.hitobjects.count))")
debugPrint("hitsoundset: \(hitaudioHeader)")
bm?.audiofile=(beatmaps.beatmapdirs[GamePlayScene.testBMIndex] as NSString).strings(byAppendingPaths: [(bm?.audiofile)!])[0] as String
if !FileManager.default.fileExists(atPath: (bm?.audiofile)!){
throw BeatmapError.audioFileNotExist
}
actions = ActionSet(beatmap: bm!, scene: self)
actions?.prepare()
BGMusicPlayer.instance.gameScene = self
BGMusicPlayer.instance.gameEarliest = Int((actions?.nexttime())!) - Int((bm?.difficulty?.ARTime)!)
BGMusicPlayer.instance.setfile((bm?.audiofile)!)
if bgvtimes.count>0 {
BGMusicPlayer.instance.videoEarliest = bgvtimes.first!
}
} catch BeatmapError.fileNotFound {
debugPrint("ERROR:beatmap file not found")
} catch BeatmapError.illegalFormat {
debugPrint("ERROR:Illegal beatmap format")
} catch BeatmapError.noAudioFile {
debugPrint("ERROR:Audio file not found")
} catch BeatmapError.audioFileNotExist {
debugPrint("ERROR:Audio file does not exist")
} catch BeatmapError.noColor {
debugPrint("ERROR:Color not found")
} catch BeatmapError.noHitObject{
debugPrint("ERROR:No hitobject found")
} catch let error {
debugPrint("ERROR:unknown error(\(error.localizedDescription))")
}
}
static func conv(x:Double) -> Double {
return leftedge+x*scrscale
}
static func conv(y:Double) -> Double {
return scrheight-bottomedge-y*scrscale
}
static func conv(w:Double) -> Double {
return w*scrscale
}
static func conv(h:Double) -> Double {
return h*scrscale
}
func showresult(x:CGFloat,y:CGFloat,result:HitResult,audio:String) {
var img:SKTexture
switch result {
case .s300:
img = SkinBuffer.get("hit300")!
break
case .s100:
img = SkinBuffer.get("hit100")!
break
case .s50:
img = SkinBuffer.get("hit50")!
break
case .fail:
img = SkinBuffer.get("hit0")!
break
}
let node = SKSpriteNode(texture: img)
let scale = CGFloat((bm?.difficulty?.AbsoluteCS)! / 128)
node.setScale(scale)
node.colorBlendFactor = 0
node.alpha = 0
node.position = CGPoint(x: x, y: y)
node.zPosition = 100001
self.addChild(node)
if result != .fail {
self.run(.playSoundFileNamed(audio, atVolume: GamePlayScene.effvolume, waitForCompletion: true))
} else {
self.run(.playSoundFileNamed("combobreak.mp3", atVolume: GamePlayScene.effvolume, waitForCompletion: true))
}
node.run(.group([.sequence([.fadeIn(withDuration: 0.2),.fadeOut(withDuration: 0.6)]),.sequence([.scale(by: 1.5, duration: 0.1),.scale(to: scale, duration: 0.1)])]))
}
func hitsound2str(hitsound:HitSound) -> String {
switch hitsound {
case .normal:
return "hitnormal.wav"
case .clap:
return "hitclap.wav"
case .finish:
return "hitfinish.wav"
case .whistle:
return "hitwhistle.wav"
}
}
func distance(x1:CGFloat,y1:CGFloat,x2:CGFloat,y2:CGFloat) -> CGFloat {
return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
}
//Slider Status
private var onslider = false
private var hastouch = false
private var lastpoint:CGPoint = .zero
fileprivate func updateslider(_ time:Double) {
let act = actions?.currentact()
if act?.getobj().type != .slider {
return
}
let sact = act as! SliderAction
let sliderpoint = sact.getposition(time)
if hastouch {
if distance(x1: lastpoint.x, y1: lastpoint.y, x2: sliderpoint.x, y2: sliderpoint.y) <= CGFloat((bm?.difficulty?.AbsoluteCS)!) {
onslider = true
GamePlayScene.sliderball?.showfollowcircle()
} else {
GamePlayScene.sliderball?.hidefollowcircle()
onslider = false
}
} else {
onslider = false
}
switch sact.update(time, following: onslider) {
case .failOnce:
//self.run(.playSoundFileNamed("combobreak.mp3", waitForCompletion: false))
break
case .failAll:
showresult(x: sliderpoint.x, y: sliderpoint.y, result: .fail, audio: "")
actions?.pointer += 1
hastouch = false
break
case .edgePass:
self.run(.playSoundFileNamed(hitaudioHeader + hitsound2str(hitsound: sact.getobj().hitSound), atVolume: GamePlayScene.effvolume, waitForCompletion: true))
break
case .end:
if sact.failcount > 0 {
showresult(x: sact.endx, y: sact.endy, result: .s100, audio: hitaudioHeader + hitsound2str(hitsound: sact.getobj().hitSound))
} else {
showresult(x: sact.endx, y: sact.endy, result: .s300, audio: hitaudioHeader + hitsound2str(hitsound: sact.getobj().hitSound))
}
GamePlayScene.sliderball?.hideall()
actions?.pointer += 1
hastouch = false
break
case .tickPass:
self.run(.playSoundFileNamed(hitaudioHeader + "slidertick.wav", atVolume: GamePlayScene.effvolume, waitForCompletion: true))
break
case .failTick:
self.run(.playSoundFileNamed("combobreak.mp3", atVolume: GamePlayScene.effvolume, waitForCompletion: true))
break
default:
break
}
}
func touchDown(atPoint pos : CGPoint) {
hastouch = true
let act = actions?.currentact()
if act != nil {
let time = BGMusicPlayer.instance.getTime()*1000
switch (act?.getobj().type)! {
case .circle:
if (act?.gettime())! - time < (bm?.difficulty?.ARTime)! {
let circle = act?.getobj() as! HitCircle
if distance(x1: pos.x, y1: pos.y, x2: CGFloat(circle.x), y2: CGFloat(circle.y)) <= CGFloat((bm?.difficulty?.AbsoluteCS)!) {
//debugPrint("time:\(time) required:\(act?.gettime())")
let result = (act as! CircleAction).judge(time)
showresult(x: CGFloat(circle.x), y: CGFloat(circle.y), result: result, audio: hitaudioHeader + hitsound2str(hitsound: circle.hitSound))
}
}
hastouch = false
break
case .slider:
lastpoint = pos
updateslider(time)
break
default:
break
}
}
}
func touchMoved(toPoint pos : CGPoint) {
let act = actions?.currentact()
if act == nil {
return
}
if (act?.getobj().type)! == .slider {
lastpoint = pos
updateslider(BGMusicPlayer.instance.getTime()*1000)
}
}
func touchUp(atPoint pos : CGPoint) {
hastouch = false
GamePlayScene.sliderball?.hidefollowcircle()
let act = actions?.currentact()
if act == nil {
return
}
updateslider(BGMusicPlayer.instance.getTime()*1000)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
var bgvindex = 0
var firstrun=true
func destroyNode(_ node: SKNode) {
for child in node.children {
destroyNode(child)
}
node.removeAllActions()
node.removeAllChildren()
node.removeFromParent()
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
if(firstrun){
firstrun=false
GamePlayScene.sliderball?.initialize(CGFloat((bm?.difficulty?.AbsoluteCS)!))
}
if BGMusicPlayer.instance.state == .stopped {
destroyNode(self)
bm?.hitobjects.removeAll()
bm = nil
actions?.destroy()
actions = nil
SkinBuffer.clean()
}
var mtime=BGMusicPlayer.instance.getTime()*1000
if self.bgvindex < self.bgvactions.count {
if self.bgvtimes[self.bgvindex] - Int(mtime) < 1000 {
var offset=self.bgvtimes[self.bgvindex] - Int(mtime)
if offset<0 {
offset=0
}
debugPrint("push bgvideo \(self.bgvindex) with offset \(offset)")
self.run(SKAction.group([self.bgvactions[self.bgvindex],SKAction.sequence([SKAction.wait(forDuration: Double(offset)/1000),BGVPlayer.play()])]))
self.bgvindex+=1
}
}
if BGMusicPlayer.instance.state == .stopped {
return
}
mtime=BGMusicPlayer.instance.getTime()*1000
let act = self.actions?.currentact()
if act != nil {
if act?.getobj().type == .slider {
self.updateslider(mtime)
}
}
if let bm = self.bm, let actions = self.actions {
var offset = actions.nexttime() - mtime - (bm.difficulty?.ARTime)!
while actions.hasnext() && offset <= 1000 {
if BGMusicPlayer.instance.state == .stopped {
return
}
//debugPrint("mtime \(mtime) objtime \((actions?.nexttime())!) ar \((bm?.difficulty?.ARTime)!) offset \(offset)")
actions.shownext(offset)
offset = actions.nexttime() - mtime - (bm.difficulty?.ARTime)!
}
}
}
}
|
6965db9bea4d7a10c1fbff9edadda622
| 39.319588 | 172 | 0.574214 | false | false | false | false |
dbaldwin/DronePan
|
refs/heads/master
|
DronePan/ViewControllers/SegmentTableViewCell.swift
|
gpl-3.0
|
1
|
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
protocol SegmentTableViewCellDelegate {
func displayMessage(title: String, message: String)
func newValueForKey(key: SettingsViewKey, value: String)
}
class SegmentTableViewCell: UITableViewCell {
var delegate : SegmentTableViewCellDelegate?
var title : String?
var values : [String]?
var helpText : String?
var key : SettingsViewKey?
var currentValue : String?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var segmentControl: UISegmentedControl!
func prepareForDisplay(initialSelection: String) {
if let title = self.title {
self.titleLabel.text = title
}
if let values = self.values {
self.segmentControl.removeAllSegments()
for (index, value) in values.enumerate() {
self.segmentControl.insertSegmentWithTitle(value, atIndex: index, animated: false)
if value == initialSelection {
self.segmentControl.selectedSegmentIndex = index
}
}
}
}
@IBAction func helpButtonClicked(sender: UIButton) {
if let helpText = self.helpText, titleText = self.titleLabel.text {
self.delegate?.displayMessage(titleText, message: helpText)
}
}
@IBAction func segmentValueChanged(sender: UISegmentedControl) {
if let key = self.key, value = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex) {
self.delegate?.newValueForKey(key, value: value)
}
}
}
|
d59496a7e8a4f2d64b8a214c0616be60
| 33.546875 | 99 | 0.672999 | false | false | false | false |
reidmweber/SwiftCSV
|
refs/heads/master
|
SwiftCSVTests/TSVTests.swift
|
mit
|
1
|
//
// TSVTests.swift
// SwiftCSV
//
// Created by naoty on 2014/06/15.
// Copyright (c) 2014年 Naoto Kaneko. All rights reserved.
//
import XCTest
import SwiftCSV
class TSVTests: XCTestCase {
var tsv: CSV!
var error: NSErrorPointer = nil
override func setUp() {
let url = NSBundle(forClass: TSVTests.self).URLForResource("users", withExtension: "tsv")
let tab = NSCharacterSet(charactersInString: "\t")
do {
tsv = try CSV(contentsOfURL: url!, delimiter: tab, encoding: NSUTF8StringEncoding)
} catch let error1 as NSError {
error.memory = error1
tsv = nil
}
}
func testHeaders() {
XCTAssertEqual(tsv.headers, ["id", "name", "age"], "")
}
func testRows() {
let expects = [
["id": "1", "name": "Alice", "age": "18"],
["id": "2", "name": "Bob", "age": "19"],
["id": "3", "name": "Charlie", "age": ""],
]
XCTAssertEqual(tsv.rows, expects, "")
}
func testColumns() {
XCTAssertEqual(["id": ["1", "2", "3"], "name": ["Alice", "Bob", "Charlie"], "age": ["18", "19", ""]], tsv.columns, "")
}
}
|
af3b21df698278bf6aea5c89138fdbcc
| 26.930233 | 126 | 0.521232 | false | true | false | false |
JaSpa/swift
|
refs/heads/master
|
test/stdlib/TestDate.swift
|
apache-2.0
|
8
|
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import CoreFoundation
#if FOUNDATION_XCTEST
import XCTest
class TestDateSuper : XCTestCase { }
#else
import StdlibUnittest
class TestDateSuper { }
#endif
class TestDate : TestDateSuper {
func testDateComparison() {
let d1 = Date()
let d2 = d1 + 1
expectTrue(d2 > d1)
expectTrue(d1 < d2)
let d3 = Date(timeIntervalSince1970: 12345)
let d4 = Date(timeIntervalSince1970: 12345)
expectTrue(d3 == d4)
expectTrue(d3 <= d4)
expectTrue(d4 >= d3)
}
func testDateMutation() {
let d0 = Date()
var d1 = Date()
d1 = d1 + 1
let d2 = Date(timeIntervalSinceNow: 10)
expectTrue(d2 > d1)
expectTrue(d1 != d0)
let d3 = d1
d1 += 10
expectTrue(d1 > d3)
}
func testDateHash() {
let d0 = NSDate()
let d1 = Date(timeIntervalSinceReferenceDate: d0.timeIntervalSinceReferenceDate)
expectEqual(d0.hashValue, d1.hashValue)
}
func testCast() {
let d0 = NSDate()
let d1 = d0 as Date
expectEqual(d0.timeIntervalSinceReferenceDate, d1.timeIntervalSinceReferenceDate)
}
func testDistantPast() {
let distantPast = Date.distantPast
let currentDate = Date()
expectTrue(distantPast < currentDate)
expectTrue(currentDate > distantPast)
expectTrue(distantPast.timeIntervalSince(currentDate) < 3600.0*24*365*100) /* ~1 century in seconds */
}
func testDistantFuture() {
let distantFuture = Date.distantFuture
let currentDate = Date()
expectTrue(currentDate < distantFuture)
expectTrue(distantFuture > currentDate)
expectTrue(distantFuture.timeIntervalSince(currentDate) > 3600.0*24*365*100) /* ~1 century in seconds */
}
func dateWithString(_ str: String) -> Date {
let formatter = DateFormatter()
// Note: Calendar(identifier:) is OSX 10.9+ and iOS 8.0+ whereas the CF version has always been available
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
return formatter.date(from: str)! as Date
}
func testEquality() {
let date = dateWithString("2010-05-17 14:49:47 -0700")
let sameDate = dateWithString("2010-05-17 14:49:47 -0700")
expectEqual(date, sameDate)
expectEqual(sameDate, date)
let differentDate = dateWithString("2010-05-17 14:49:46 -0700")
expectNotEqual(date, differentDate)
expectNotEqual(differentDate, date)
let sameDateByTimeZone = dateWithString("2010-05-17 13:49:47 -0800")
expectEqual(date, sameDateByTimeZone)
expectEqual(sameDateByTimeZone, date)
let differentDateByTimeZone = dateWithString("2010-05-17 14:49:47 -0800")
expectNotEqual(date, differentDateByTimeZone)
expectNotEqual(differentDateByTimeZone, date)
}
func testTimeIntervalSinceDate() {
let referenceDate = dateWithString("1900-01-01 00:00:00 +0000")
let sameDate = dateWithString("1900-01-01 00:00:00 +0000")
let laterDate = dateWithString("2010-05-17 14:49:47 -0700")
let earlierDate = dateWithString("1810-05-17 14:49:47 -0700")
let laterSeconds = laterDate.timeIntervalSince(referenceDate)
expectEqual(laterSeconds, 3483121787.0)
let earlierSeconds = earlierDate.timeIntervalSince(referenceDate)
expectEqual(earlierSeconds, -2828311813.0)
let sameSeconds = sameDate.timeIntervalSince(referenceDate)
expectEqual(sameSeconds, 0.0)
}
func testDateComponents() {
// Make sure the optional init stuff works
let dc = DateComponents()
expectNil(dc.year)
let dc2 = DateComponents(year: 1999)
expectNil(dc2.day)
expectEqual(1999, dc2.year)
}
func test_AnyHashableContainingDate() {
let values: [Date] = [
dateWithString("2016-05-17 14:49:47 -0700"),
dateWithString("2010-05-17 14:49:47 -0700"),
dateWithString("2010-05-17 14:49:47 -0700"),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(Date.self, type(of: anyHashables[0].base))
expectEqual(Date.self, type(of: anyHashables[1].base))
expectEqual(Date.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSDate() {
let values: [NSDate] = [
NSDate(timeIntervalSince1970: 1000000000),
NSDate(timeIntervalSince1970: 1000000001),
NSDate(timeIntervalSince1970: 1000000001),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(Date.self, type(of: anyHashables[0].base))
expectEqual(Date.self, type(of: anyHashables[1].base))
expectEqual(Date.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableContainingDateComponents() {
let values: [DateComponents] = [
DateComponents(year: 2016),
DateComponents(year: 1995),
DateComponents(year: 1995),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(DateComponents.self, type(of: anyHashables[0].base))
expectEqual(DateComponents.self, type(of: anyHashables[1].base))
expectEqual(DateComponents.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSDateComponents() {
func makeNSDateComponents(year: Int) -> NSDateComponents {
let result = NSDateComponents()
result.year = year
return result
}
let values: [NSDateComponents] = [
makeNSDateComponents(year: 2016),
makeNSDateComponents(year: 1995),
makeNSDateComponents(year: 1995),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(DateComponents.self, type(of: anyHashables[0].base))
expectEqual(DateComponents.self, type(of: anyHashables[1].base))
expectEqual(DateComponents.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
}
#if !FOUNDATION_XCTEST
var DateTests = TestSuite("TestDate")
DateTests.test("testDateComparison") { TestDate().testDateComparison() }
DateTests.test("testDateMutation") { TestDate().testDateMutation() }
DateTests.test("testDateHash") { TestDate().testDateHash() }
DateTests.test("testCast") { TestDate().testCast() }
DateTests.test("testDistantPast") { TestDate().testDistantPast() }
DateTests.test("testDistantFuture") { TestDate().testDistantFuture() }
DateTests.test("testEquality") { TestDate().testEquality() }
DateTests.test("testTimeIntervalSinceDate") { TestDate().testTimeIntervalSinceDate() }
DateTests.test("testDateComponents") { TestDate().testDateComponents() }
DateTests.test("test_AnyHashableContainingDate") { TestDate().test_AnyHashableContainingDate() }
DateTests.test("test_AnyHashableCreatedFromNSDate") { TestDate().test_AnyHashableCreatedFromNSDate() }
DateTests.test("test_AnyHashableContainingDateComponents") { TestDate().test_AnyHashableContainingDateComponents() }
DateTests.test("test_AnyHashableCreatedFromNSDateComponents") { TestDate().test_AnyHashableCreatedFromNSDateComponents() }
runAllTests()
#endif
|
cdc0101669aee2e7c51940c0c47f570b
| 37.281106 | 122 | 0.657157 | false | true | false | false |
mrdepth/EVEOnlineAPI
|
refs/heads/master
|
EVEAPI/EVEAPI/ZKillboard.swift
|
mit
|
1
|
//
// ZKillboard.swift
// EVEAPI
//
// Created by Artem Shimanski on 26.06.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
import Alamofire
import Futures
enum ZKillboardError: Error {
case invalidRequest(URLRequest)
case internalError
case network(error: Error)
case objectSerialization(reason: String)
case serialization(error: Error)
case notFound
case invalidFormat(Any.Type, Any)
}
extension DateFormatter {
static var zKillboardDateFormatter: DateFormatter {
return .esiDateTimeFormatter
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
// dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// return dateFormatter
}
}
public class ZKillboard {
let baseURL = "https://zkillboard.com/api/"
var sessionManager = Session()
public init() {
}
open func request(_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> DataRequest {
let convertible = RequestConvertible(url: url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
cachePolicy: cachePolicy)
return sessionManager.request(convertible)
}
public func kills(filter: [Filter], page: Int?, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Killmail]>> {
let promise = Promise<ESI.Result<[Killmail]>>()
guard filter.count > 1 else {
try! promise.fail(ZKillboardError.notFound)
return promise.future
}
var args = filter.map {$0.value}
if let page = page {
args.append("page/\(page)")
}
let url = baseURL
let progress = Progress(totalUnitCount: 100)
request(url + args.joined(separator: "/") + "/", method: .get, cachePolicy: cachePolicy).downloadProgress { p in
progress.completedUnitCount = Int64(p.fractionCompleted * 100)
}.validate().responseZKillboard { (response: DataResponse<[Killmail]>) in
promise.set(response: response, cached: 600.0)
}
return promise.future
}
}
extension DataRequest {
@discardableResult
public func responseZKillboard<T: Decodable>(queue: DispatchQueue = .main,
completionHandler: @escaping (DataResponse<T>) -> Void) -> Self
{
let decoder = JSONDecoder()
// decoder.dateDecodingStrategy = .formatted(ZKillboard.dateFormatter)
return responseDecodable(queue: queue, decoder: decoder, completionHandler: completionHandler)
}
}
extension ZKillboard {
public enum Sorting {
case ascending
case descending
}
// fileprivate static let dateFormatter: DateFormatter = {
// return DateFormatter.esiDateTimeFormatter
// }()
public enum Filter {
case characterID([Int64])
case corporationID([Int64])
case allianceID([Int64])
case factionID([Int64])
case shipTypeID([Int])
case groupID([Int])
case solarSystemID([Int])
case regionID([Int])
case warID([Int])
case iskValue(Int64)
// case startTime(Date)
// case endTime(Date)
case noItems
case noAttackers
case zkbOnly
case kills
case losses
case wSpace
case solo
case finalBlowOnly
public var value: String {
switch self {
case let .characterID(id):
return "characterID/\(id.map{String($0)}.joined(separator: ","))"
case let .corporationID(id):
return "corporationID/\(id.map{String($0)}.joined(separator: ","))"
case let .allianceID(id):
return "allianceID/\(id.map{String($0)}.joined(separator: ","))"
case let .factionID(id):
return "factionID/\(id.map{String($0)}.joined(separator: ","))"
case let .shipTypeID(id):
return "shipTypeID/\(id.map{String($0)}.joined(separator: ","))"
case let .groupID(id):
return "groupID/\(id.map{String($0)}.joined(separator: ","))"
case let .solarSystemID(id):
return "solarSystemID/\(id.map{String($0)}.joined(separator: ","))"
case let .regionID(id):
return "regionID/\(id.map{String($0)}.joined(separator: ","))"
case let .warID(id):
return "warID/\(id.map{String($0)}.joined(separator: ","))"
case let .iskValue(id):
return "iskValue/\(id)"
// case let .startTime(date):
// return "startTime/\(dateFormatter.string(from: date))"
// case let .endTime(date):
// return "endTime/\(dateFormatter.string(from: date))"
case .noItems:
return "no-items"
case .noAttackers:
return "no-attackers"
case .zkbOnly:
return "zkbOnly"
case .kills:
return "kills"
case .losses:
return "losses"
case .wSpace:
return "w-space"
case .solo:
return "solo"
case .finalBlowOnly:
return "finalblow-only"
}
}
}
public struct Killmail: Codable, Hashable {
public var killmailID: Int64
public var fittedValue: Double?
public var hash: String
public var locationID: Int?
public var points: Int
public var totalValue: Double?
public var npc: Bool
public var solo: Bool
public var awox: Bool
enum CodingKeys: String, CodingKey {
case killmailID = "killmail_id"
case zkb
}
enum ZKBCodingKeys: String, CodingKey {
case fittedValue
case hash
case locationID
case points
case totalValue
case npc
case solo
case awox
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
killmailID = try container.decode(Int64.self, forKey: .killmailID)
let zkb = try container.nestedContainer(keyedBy: ZKBCodingKeys.self, forKey: .zkb)
fittedValue = try zkb.decodeIfPresent(Double.self, forKey: .fittedValue)
hash = try zkb.decode(String.self, forKey: .hash)
locationID = try zkb.decodeIfPresent(Int.self, forKey: .locationID)
points = try zkb.decode(Int.self, forKey: .points)
totalValue = try zkb.decodeIfPresent(Double.self, forKey: .totalValue)
npc = try zkb.decode(Bool.self, forKey: .npc)
solo = try zkb.decode(Bool.self, forKey: .solo)
awox = try zkb.decode(Bool.self, forKey: .awox)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(killmailID, forKey: .killmailID)
var zkb = container.nestedContainer(keyedBy: ZKBCodingKeys.self, forKey: .zkb)
try zkb.encodeIfPresent(fittedValue, forKey: .fittedValue)
try zkb.encode(hash, forKey: .hash)
try zkb.encodeIfPresent(locationID, forKey: .locationID)
try zkb.encode(points, forKey: .points)
try zkb.encodeIfPresent(totalValue, forKey: .totalValue)
try zkb.encode(npc, forKey: .npc)
try zkb.encode(solo, forKey: .solo)
try zkb.encode(awox, forKey: .awox)
}
}
}
|
45b1554bbb200f16d93a5d9d24ed0cac
| 27.912134 | 147 | 0.683068 | false | false | false | false |
1Fr3dG/TextFormater
|
refs/heads/master
|
Sources/TFBGColor.swift
|
mit
|
1
|
//
// TFBGColor.swift
// TextFormater
//
// Created by 高宇 on 2019/3/21.
//
import Foundation
import MarkdownKit
open class TFBGColor: MarkdownCommonElement {
fileprivate static let regex = "(.?|^)(<bgcolor\\s\\w+>)(.+?)(</bgcolor>)"
open var font: MarkdownFont?
open var color: MarkdownColor?
open var bgcolor: MarkdownColor
open var regex: String {
return TFBGColor.regex
}
public init(defaultColor: MarkdownColor? = nil) {
self.bgcolor = defaultColor ?? MarkdownColor.white
}
open func addAttributes(_ attributedString: NSMutableAttributedString, range: NSRange) {
attributedString.addAttribute(.backgroundColor, value: self.bgcolor, range: range)
}
public func match(_ match: NSTextCheckingResult, attributedString: NSMutableAttributedString) {
let colorAttributedString = attributedString.attributedSubstring(from: match.range(at: 2))
let colorString = colorAttributedString.string.dropFirst().dropLast().lowercased()
var colorName = "white"
if colorString.contains(" ") {
colorName = colorString.components(separatedBy: " ")[1]
}
switch colorName {
case "black":
self.bgcolor = MarkdownColor.black
case "blue":
self.bgcolor = MarkdownColor.blue
case "brown":
self.bgcolor = MarkdownColor.brown
case "cyan":
self.bgcolor = MarkdownColor.cyan
case "gray":
self.bgcolor = MarkdownColor.gray
case "green":
self.bgcolor = MarkdownColor.green
case "magenta":
self.bgcolor = MarkdownColor.magenta
case "orange":
self.bgcolor = MarkdownColor.orange
case "purple":
self.bgcolor = MarkdownColor.purple
case "red":
self.bgcolor = MarkdownColor.red
case "white":
self.bgcolor = MarkdownColor.white
case "yellow":
self.color = MarkdownColor.yellow
default:
self.bgcolor = MarkdownColor.black
}
// deleting trailing markdown
attributedString.deleteCharacters(in: match.range(at: 4))
// formatting string (may alter the length)
addAttributes(attributedString, range: match.range(at: 3))
// deleting leading markdown
attributedString.deleteCharacters(in: match.range(at: 2))
}
}
|
62f102b595c7273fc3d164981676534e
| 30.948718 | 99 | 0.611958 | false | false | false | false |
jinSasaki/Vulcan
|
refs/heads/master
|
Sources/Vulcan/Vulcan.swift
|
mit
|
1
|
//
// Vulcan.swift
// Vulcan
//
// Created by Jin Sasaki on 2017/04/23.
// Copyright © 2017年 Sasakky. All rights reserved.
//
import UIKit
final public class Vulcan {
public static var defaultImageDownloader: ImageDownloader = ImageDownloader.default
public private(set) var priority: Int = Int.min
public var imageDownloader: ImageDownloader {
get {
return _imageDownloader ?? Vulcan.defaultImageDownloader
}
set {
_imageDownloader = newValue
}
}
public static var cacheMemoryCapacity: Int? {
get {
return defaultImageDownloader.cache?.memoryCapacity
}
set {
guard let newValue = newValue else { return }
defaultImageDownloader.cache?.memoryCapacity = newValue
}
}
public static var diskCapacity: Int? {
get {
return defaultImageDownloader.cache?.diskCapacity
}
set {
guard let newValue = newValue else { return }
defaultImageDownloader.cache?.diskCapacity = newValue
}
}
public static var diskPath: String? {
get {
return defaultImageDownloader.cache?.diskPath
}
set {
guard let newValue = newValue else { return }
defaultImageDownloader.cache?.diskPath = newValue
}
}
internal weak var imageView: UIImageView?
private var _imageDownloader: ImageDownloader?
private var downloadTaskId: String?
private var dummyView: UIImageView?
public static func setDefault(imageDownloader: ImageDownloader) {
self.defaultImageDownloader = imageDownloader
}
public func setImage(url: URL, placeholderImage: UIImage? = nil, composer: ImageComposable? = nil, options: ImageDecodeOptions? = nil, completion: ImageDownloadHandler? = nil) {
let downloader = imageDownloader
cancelLoading()
imageView?.image = placeholderImage
let id = downloader.download(url: url, composer: composer, options: options) { (url, result) in
switch result {
case .success(let image):
DispatchQueue.main.async {
self.showImage(image: image)
}
default:
break
}
completion?(url, result)
}
self.downloadTaskId = id
}
public enum PriorityURL {
case url(URL, priority: Int)
case request(URLRequest, priority: Int)
public var priority: Int {
switch self {
case .url(_, let priority):
return priority
case .request(_, let priority):
return priority
}
}
public var url: URL {
switch self {
case .url(let url, _):
return url
case .request(let request, _):
return request.url!
}
}
}
/// Download images with priority
public func setImage(urls: [PriorityURL], placeholderImage: UIImage? = nil, composer: ImageComposable? = nil, options: ImageDecodeOptions? = nil) {
let downloader = imageDownloader
cancelLoading()
imageView?.image = placeholderImage
let ids = urls.sorted(by: { $0.priority < $1.priority })
.map({ (priorityURL) -> String in
return downloader.download(url: priorityURL.url, composer: composer, options: options) { (url, result) in
switch result {
case .success(let image):
DispatchQueue.main.async {
if self.priority <= priorityURL.priority {
self.priority = priorityURL.priority
self.showImage(image: image)
}
}
default:
break
}
}
})
self.downloadTaskId = ids.joined(separator: ",")
}
public func cancelLoading() {
let downloader = imageDownloader
guard let splited = downloadTaskId?.components(separatedBy: ",") else {
return
}
splited.forEach({ downloader.cancel(id: $0) })
self.priority = Int.min
}
private func showImage(image newImage: UIImage) {
guard let baseImageView = self.imageView else { return }
let imageView = dummyView ?? UIImageView()
imageView.frame = baseImageView.bounds
imageView.alpha = 1
imageView.image = baseImageView.image
imageView.contentMode = baseImageView.contentMode
baseImageView.addSubview(imageView)
baseImageView.image = newImage
dummyView = imageView
UIView.animate(withDuration: 0.3, animations: {
self.dummyView?.alpha = 0
}) { (finished) in
self.dummyView?.removeFromSuperview()
self.dummyView = nil
}
}
}
|
1a53c2de932e846e689c853eba720c68
| 32.184211 | 181 | 0.565821 | false | false | false | false |
AlanJN/ios-charts
|
refs/heads/master
|
Charts/Classes/Renderers/RadarChartRenderer.swift
|
apache-2.0
|
12
|
//
// RadarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class RadarChartRenderer: LineScatterCandleRadarChartRenderer
{
internal weak var _chart: RadarChartView!
public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
_chart = chart
}
public override func drawData(context context: CGContext?)
{
if (_chart !== nil)
{
let radarData = _chart.data
if (radarData != nil)
{
for set in radarData!.dataSets as! [RadarChartDataSet]
{
if set.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set)
}
}
}
}
}
internal func drawDataSet(context context: CGContext?, dataSet: RadarChartDataSet)
{
CGContextSaveGState(context)
let sliceangle = _chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = _chart.factor
let center = _chart.centerOffsets
var entries = dataSet.yVals
let path = CGPathCreateMutable()
var hasMovedToPoint = false
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
let p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value - _chart.chartYMin) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle)
if (p.x.isNaN)
{
continue
}
if (!hasMovedToPoint)
{
CGPathMoveToPoint(path, nil, p.x, p.y)
hasMovedToPoint = true
}
else
{
CGPathAddLineToPoint(path, nil, p.x, p.y)
}
}
CGPathCloseSubpath(path)
// draw filled
if (dataSet.isDrawFilledEnabled)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextSetAlpha(context, dataSet.fillAlpha)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextFillPath(context)
}
// draw the line (only if filled is disabled or alpha is below 255)
if (!dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0)
{
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextSetLineWidth(context, dataSet.lineWidth)
CGContextSetAlpha(context, 1.0)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextStrokePath(context)
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext?)
{
if (_chart.data === nil)
{
return
}
let data = _chart.data!
let defaultValueFormatter = _chart.valueFormatter
let sliceangle = _chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = _chart.factor
let center = _chart.centerOffsets
let yoffset = CGFloat(5.0)
for (var i = 0, count = data.dataSetCount; i < count; i++)
{
let dataSet = data.getDataSetByIndex(i) as! RadarChartDataSet
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
var entries = dataSet.yVals
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
let p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle)
let valueFont = dataSet.valueFont
let valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
public override func drawExtras(context context: CGContext?)
{
drawWeb(context: context)
}
private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawWeb(context context: CGContext?)
{
let sliceangle = _chart.sliceAngle
CGContextSaveGState(context)
// calculate the factor that is needed for transforming the value to
// pixels
let factor = _chart.factor
let rotationangle = _chart.rotationAngle
let center = _chart.centerOffsets
// draw the web lines that come from the center
CGContextSetLineWidth(context, _chart.webLineWidth)
CGContextSetStrokeColorWithColor(context, _chart.webColor.CGColor)
CGContextSetAlpha(context, _chart.webAlpha)
let modulus = _chart.skipWebLineCount
for var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i += modulus
{
let p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle)
_webLineSegmentsBuffer[0].x = center.x
_webLineSegmentsBuffer[0].y = center.y
_webLineSegmentsBuffer[1].x = p.x
_webLineSegmentsBuffer[1].y = p.y
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2)
}
// draw the inner-web
CGContextSetLineWidth(context, _chart.innerWebLineWidth)
CGContextSetStrokeColorWithColor(context, _chart.innerWebColor.CGColor)
CGContextSetAlpha(context, _chart.webAlpha)
let labelCount = _chart.yAxis.entryCount
for (var j = 0; j < labelCount; j++)
{
for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++)
{
let r = CGFloat(_chart.yAxis.entries[j] - _chart.chartYMin) * factor
let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle)
let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle)
_webLineSegmentsBuffer[0].x = p1.x
_webLineSegmentsBuffer[0].y = p1.y
_webLineSegmentsBuffer[1].x = p2.x
_webLineSegmentsBuffer[1].y = p2.y
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _highlightPointBuffer = CGPoint()
public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight])
{
if (_chart.data === nil)
{
return
}
let data = _chart.data as! RadarChartData
CGContextSaveGState(context)
CGContextSetLineWidth(context, data.highlightLineWidth)
if (data.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let sliceangle = _chart.sliceAngle
let factor = _chart.factor
let center = _chart.centerOffsets
for (var i = 0; i < indices.count; i++)
{
let set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! RadarChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
// get the index to highlight
let xIndex = indices[i].xIndex
let e = set.entryForXIndex(xIndex)
if (e === nil || e!.xIndex != xIndex)
{
continue
}
let j = set.entryIndex(entry: e!, isEqual: true)
let y = (e!.value - _chart.chartYMin)
if (y.isNaN)
{
continue
}
_highlightPointBuffer = ChartUtils.getPosition(center: center, dist: CGFloat(y) * factor,
angle: sliceangle * CGFloat(j) + _chart.rotationAngle)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
}
CGContextRestoreGState(context)
}
}
|
4e22bb981303a7b8e4e8935cbdabe93f
| 32.522184 | 273 | 0.54974 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletCreation/WalletCreationService.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import ToolKit
import WalletPayloadKit
public struct WalletCreatedContext: Equatable {
public let guid: String
public let sharedKey: String
public let password: String
}
public typealias CreateWalletMethod = (
_ email: String,
_ password: String,
_ accountName: String,
_ recaptchaToken: String?
) -> AnyPublisher<WalletCreatedContext, WalletCreationServiceError>
public typealias ImportWalletMethod = (
_ email: String,
_ password: String,
_ accountName: String,
_ mnemonic: String
) -> AnyPublisher<Either<WalletCreatedContext, EmptyValue>, WalletCreationServiceError>
public typealias SetResidentialInfoMethod = (
_ country: String,
_ state: String?
) -> AnyPublisher<Void, Never>
public typealias UpdateCurrencyForNewWallets = (
_ country: String,
_ guid: String,
_ sharedKey: String
) -> AnyPublisher<Void, Never>
public struct WalletCreationService {
/// Creates a new wallet using the given details
public var createWallet: CreateWalletMethod
/// Imports and creates a new wallet using the given details
public var importWallet: ImportWalletMethod
/// Sets the residential info as part of account creation
public var setResidentialInfo: SetResidentialInfoMethod
/// Sets the default currency for a new wallet account
public var updateCurrencyForNewWallets: UpdateCurrencyForNewWallets
}
extension WalletCreationService {
// swiftlint:disable line_length
public static func live(
walletManager: WalletManagerAPI,
walletCreator: WalletCreatorAPI,
nabuRepository: NabuRepositoryAPI,
updateCurrencyService: @escaping UpdateCurrencyForNewWallets,
nativeWalletCreationEnabled: @escaping () -> AnyPublisher<Bool, Never>
) -> Self {
let walletManager = walletManager
let walletCreator = walletCreator
let nativeWalletCreationEnabled = nativeWalletCreationEnabled
return Self(
createWallet: { email, password, accountName, token -> AnyPublisher<WalletCreatedContext, WalletCreationServiceError> in
nativeWalletCreationEnabled()
.flatMap { isEnabled -> AnyPublisher<WalletCreatedContext, WalletCreationServiceError> in
guard isEnabled else {
return legacyCreation(
walletManager: walletManager,
email: email,
password: password
)
.eraseToAnyPublisher()
}
let siteKey = AuthenticationKeys.googleRecaptchaSiteKey
return walletCreator.createWallet(
email: email,
password: password,
accountName: accountName,
recaptchaToken: token,
siteKey: siteKey,
language: "en"
)
.mapError(WalletCreationServiceError.creationFailure)
.map(WalletCreatedContext.from(model:))
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
},
importWallet: { email, password, accountName, mnemonic -> AnyPublisher<Either<WalletCreatedContext, EmptyValue>, WalletCreationServiceError> in
nativeWalletCreationEnabled()
.flatMap { isEnabled -> AnyPublisher<Either<WalletCreatedContext, EmptyValue>, WalletCreationServiceError> in
guard isEnabled else {
return legacyImportWallet(
email: email,
password: password,
mnemonic: mnemonic,
walletManager: walletManager
)
.map { _ -> Either<WalletCreatedContext, EmptyValue> in
// this makes me sad, for legacy JS code we ignore this as the loading of the wallet
// happens internally just after `didRecoverWallet` delegate method is called
.right(.noValue)
}
.mapError { _ in WalletCreationServiceError.creationFailure(.genericFailure) }
.eraseToAnyPublisher()
}
return walletCreator.importWallet(
mnemonic: mnemonic,
email: email,
password: password,
accountName: accountName,
language: "en"
)
.mapError(WalletCreationServiceError.creationFailure)
.map { model -> Either<WalletCreatedContext, EmptyValue> in
.left(WalletCreatedContext.from(model: model))
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
},
setResidentialInfo: { country, state -> AnyPublisher<Void, Never> in
// we fire the request but we ignore the error,
// even if this fails the user will still have to submit their details
// as part of the KYC flow
nabuRepository.setInitialResidentialInfo(
country: country,
state: state
)
.ignoreFailure()
},
updateCurrencyForNewWallets: { country, guid, sharedKey -> AnyPublisher<Void, Never> in
// we ignore the failure since this is kind of a side effect for new wallets :(
updateCurrencyService(country, guid, sharedKey)
.ignoreFailure(setFailureType: Never.self)
.eraseToAnyPublisher()
}
)
}
public static var noop: Self {
Self(
createWallet: { _, _, _, _ -> AnyPublisher<WalletCreatedContext, WalletCreationServiceError> in
.empty()
},
importWallet: { _, _, _, _ -> AnyPublisher<Either<WalletCreatedContext, EmptyValue>, WalletCreationServiceError> in
.empty()
},
setResidentialInfo: { _, _ -> AnyPublisher<Void, Never> in
.empty()
},
updateCurrencyForNewWallets: { _, _, _ -> AnyPublisher<Void, Never> in
.empty()
}
)
}
}
// MARK: - Legacy Import
private func legacyImportWallet(
email: String,
password: String,
mnemonic: String,
walletManager: WalletManagerAPI
) -> AnyPublisher<EmptyValue, WalletError> {
walletManager.loadWalletJS()
walletManager.recover(
email: email,
password: password,
seedPhrase: mnemonic
)
return listenForRecoveryEvents(walletManager: walletManager)
}
private func listenForRecoveryEvents(
walletManager: WalletManagerAPI
) -> AnyPublisher<EmptyValue, WalletError> {
let recovered = walletManager.walletRecovered
.mapError { _ in WalletError.recovery(.failedToRecoverWallet) }
.map { _ in EmptyValue.noValue }
.eraseToAnyPublisher()
// always fail upon receiving an event from `walletRecoveryFailed`
let recoveryFailed = walletManager.walletRecoveryFailed
.mapError { _ in WalletError.recovery(.failedToRecoverWallet) }
.flatMap { _ -> AnyPublisher<EmptyValue, WalletError> in
.failure(.recovery(.failedToRecoverWallet))
}
.eraseToAnyPublisher()
return Publishers.Merge(recovered, recoveryFailed)
.mapError { _ in WalletError.recovery(.failedToRecoverWallet) }
.map { _ in .noValue }
.eraseToAnyPublisher()
}
// MARK: - Legacy Creation
func legacyCreation(
walletManager: WalletManagerAPI,
email: String,
password: String
) -> AnyPublisher<WalletCreatedContext, WalletCreationServiceError> {
walletManager.loadWalletJS()
walletManager.newWallet(password: password, email: email)
return walletManager.didCreateNewAccount
.flatMap { result -> AnyPublisher<WalletCreatedContext, WalletCreationServiceError> in
switch result {
case .success(let value):
return .just(
WalletCreatedContext.from(model: value)
)
.eraseToAnyPublisher()
case .failure(let error):
return .failure(WalletCreationServiceError.creationFailure(.legacyError(error)))
}
}
.eraseToAnyPublisher()
}
extension WalletCreatedContext {
static func from(model: WalletCreation) -> Self {
WalletCreatedContext(
guid: model.guid,
sharedKey: model.sharedKey,
password: model.password
)
}
}
|
0554fd38d76c9d38af64256431a3c217
| 38.930736 | 155 | 0.57784 | false | false | false | false |
colbylwilliams/bugtrap
|
refs/heads/master
|
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/Pivotal/Domain/PivotalPerson.swift
|
mit
|
1
|
//
// PivotalPerson.swift
// bugTrap
//
// Created by Colby L Williams on 11/10/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class PivotalPerson : JsonSerializable {
var id = 0
var name = ""
var initials = ""
var username = ""
var email = ""
var kind = ""
init() {
}
init (id: Int, name: String, initials: String, username: String, email: String, kind: String) {
self.id = id
self.name = name
self.initials = initials
self.username = username
self.email = email
self.kind = kind
}
class func deserialize (json: JSON) -> PivotalPerson? {
let id = json["id"].intValue
let name = json["name"].stringValue
let initials = json["initials"].stringValue
let username = json["username"].stringValue
let email = json["email"].stringValue
let kind = json["kind"].stringValue
return PivotalPerson (id: id, name: name, initials: initials, username: username, email: email, kind: kind)
}
class func deserializeAll(json: JSON) -> [PivotalPerson] {
var items = [PivotalPerson]()
if let jsonArray = json.array {
for item: JSON in jsonArray {
if let pivotalPerson = deserialize(item) {
items.append(pivotalPerson)
}
}
}
return items
}
func serialize () -> NSMutableDictionary {
return NSMutableDictionary()
}
}
|
d1972498eadd3b9ece305f131015c589
| 17.273973 | 109 | 0.657164 | false | false | false | false |
bizz84/ReviewTime
|
refs/heads/master
|
ReviewTime/WS/URLManagerWS.swift
|
mit
|
3
|
//
// URLManagerWS.swift
// ReviewTime
//
// Created by Nathan Hegedus on 28/08/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
enum UrlRequestType: String {
case iOS = "bwmso8jg"
case Mac = "czcf5ge6"
case ShortData = "6pwwyjdy"
}
class URLManagerWS: NSObject {
static var url = "https://www.kimonolabs.com/api/"
static var apiKey = "?apikey=MGKzHaqx4RETL4rx4pvIxO7JLvBrBMo3"
static var macUrlSufix = "czcf5ge6?apikey=MGKzHaqx4RETL4rx4pvIxO7JLvBrBMo3"
static var shorDataSufix = "6pwwyjdy?apikey=MGKzHaqx4RETL4rx4pvIxO7JLvBrBMo3"
static var iosCode = "bwmso8jg?apikey=MGKzHaqx4RETL4rx4pvIxO7JLvBrBMo3"
// MARK: - Public Static Methods
class func createURL(requestType: UrlRequestType) -> String {
return self.url + requestType.rawValue + apiKey
}
}
|
2f6e2dd76f7db2622db633f1f796034e
| 25.454545 | 81 | 0.695304 | false | false | false | false |
OscarSwanros/swift
|
refs/heads/master
|
test/decl/func/static_func.swift
|
apache-2.0
|
2
|
// RUN: %target-typecheck-verify-swift
static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{1-8=}}
class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{1-7=}}
override static func gf3() {} // expected-error {{static methods may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
override class func gf4() {} // expected-error {{class methods may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
static override func gf5() {} // expected-error {{static methods may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
class override func gf6() {} // expected-error {{class methods may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
static gf7() {} // expected-error {{expected declaration}} expected-error {{closure expression is unused}} expected-error{{begin with a closure}} expected-note{{did you mean to use a 'do' statement?}} {{14-14=do }}
class gf8() {} // expected-error {{expected '{' in class}} expected-error {{closure expression is unused}} expected-error{{begin with a closure}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }}
func inGlobalFunc() {
static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{3-10=}}
class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{3-9=}}
}
struct InMemberFunc {
func member() {
static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{5-12=}}
class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{5-11=}}
}
}
struct DuplicateStatic {
static static func f1() {} // expected-error{{'static' specified twice}}{{10-17=}}
static class func f2() {} // expected-error{{'class' specified twice}}{{10-16=}}
class static func f3() {} // expected-error{{'static' specified twice}}{{9-16=}} expected-error{{class methods are only allowed within classes; use 'static' to declare a static method}}{{3-8=static}}
class class func f4() {} // expected-error{{'class' specified twice}}{{9-15=}} expected-error{{class methods are only allowed within classes; use 'static' to declare a static method}}{{3-8=static}}
override static static func f5() {} // expected-error{{'static' specified twice}}{{19-26=}} expected-error{{'override' can only be specified on class members}} {{3-12=}}
static override static func f6() {} // expected-error{{'static' specified twice}}{{19-26=}} expected-error{{'override' can only be specified on class members}} {{10-19=}}
static static override func f7() {} // expected-error{{'static' specified twice}}{{10-17=}} expected-error{{'override' can only be specified on class members}} {{17-26=}}
static final func f8() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
struct S { // expected-note {{extended type declared here}}
static func f1() {}
class func f2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
}
extension S {
static func ef1() {}
class func ef2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
}
enum E { // expected-note {{extended type declared here}}
static func f1() {}
class func f2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
static final func f3() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
extension E {
static func f4() {}
class func f5() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
}
class C {
static func f1() {} // expected-note 3{{overridden declaration is here}}
class func f2() {}
class func f3() {}
class func f4() {} // expected-note {{overridden declaration is here}}
class func f5() {} // expected-note {{overridden declaration is here}}
static final func f6() {} // expected-error {{static declarations are already final}} {{10-16=}}
final class func f7() {} // expected-note 3{{overridden declaration is here}}
}
extension C {
static func ef1() {}
class func ef2() {} // expected-note {{overridden declaration is here}}
class func ef3() {} // expected-note {{overridden declaration is here}}
class func ef4() {} // expected-note {{overridden declaration is here}}
class func ef5() {} // expected-note {{overridden declaration is here}}
}
class C_Derived : C {
override static func f1() {} // expected-error {{cannot override static method}}
override class func f2() {}
class override func f3() {}
override class func ef2() {} // expected-error {{overriding declarations from extensions is not supported}}
class override func ef3() {} // expected-error {{overriding declarations from extensions is not supported}}
override static func f7() {} // expected-error {{static method overrides a 'final' class method}}
}
class C_Derived2 : C {
override final class func f1() {} // expected-error {{cannot override static method}}
override final class func f7() {} // expected-error {{class method overrides a 'final' class method}}
}
class C_Derived3 : C {
override class func f1() {} // expected-error {{cannot override static method}}
override class func f7() {} // expected-error {{class method overrides a 'final' class method}}
}
extension C_Derived {
override class func f4() {} // expected-error {{overriding declarations in extensions is not supported}}
class override func f5() {} // expected-error {{overriding declarations in extensions is not supported}}
override class func ef4() {} // expected-error {{overriding declarations in extensions is not supported}}
class override func ef5() {} // expected-error {{overriding declarations in extensions is not supported}}
}
protocol P {
static func f1()
static func f2()
static func f3() {} // expected-error {{protocol methods must not have bodies}}
static final func f4() // expected-error {{only classes and class members may be marked with 'final'}}
}
|
b469c89f9161cb49c14202b819e8b121
| 55.780702 | 214 | 0.687162 | false | false | false | false |
puyanLiu/LPYFramework
|
refs/heads/master
|
第三方框架改造/SwiftRulerView-master/YKScrollRulerSwift/String+Extension.swift
|
apache-2.0
|
2
|
//
// String+Extension.swift
// QQMProjectSwift
//
// Created by liupuyan on 2017/5/12.
// Copyright © 2017年 liupuyan. All rights reserved.
//
import Foundation
extension String {
// String使用下标读取字符串
subscript(r: Range<Int>) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
return self[startIndex..<endIndex]
}
}
func removeCharWithString(chars: NSArray) -> String {
let str = self
chars.enumerateObjects({ (obj, idx, stop) in
})
return str
}
}
// MARK: - 添加Range->NSRange,NSRange->Range
extension String {
/// Range->NSRange
///
/// - Parameter range: <#range description#>
/// - Returns: <#return value description#>
func nsRnage(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange.init(location: utf16.distance(from: utf16.startIndex, to: from), length: utf16.distance(from: from, to: to))
}
/// NSRange->Range
///
/// - Parameter nsRange: <#nsRange description#>
/// - Returns: <#return value description#>
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from..<to
}
}
|
d2d16c5897d625c49152c0f221ea4b36
| 30.017241 | 131 | 0.60756 | false | false | false | false |
m-alani/contests
|
refs/heads/master
|
hackerrank/AppleAndOrange.swift
|
mit
|
1
|
//
// AppleAndOrange.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/apple-and-orange
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Read S & T
var inputLine = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})
let houseStart = inputLine[0]
let houseEnd = inputLine[1]
// Read A & B
inputLine = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})
let appleTree = inputLine[0]
let orangeTree = inputLine[1]
// Read M & N and ignore the values (not needed in our implementation)
_ = readLine()
// Read apples & oranges arrays
let apples = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})
let oranges = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})
// Process the cases and print the output
print(apples.filter({$0 + appleTree <= houseEnd && $0 + appleTree >= houseStart}).count)
print(oranges.filter({$0 + orangeTree <= houseEnd && $0 + orangeTree >= houseStart}).count)
|
ecebfdb946cac7941c482c538183e97c
| 35.806452 | 118 | 0.691499 | false | false | false | false |
kaltura/developer-platform
|
refs/heads/master
|
test/golden/top_level_array/swift.swift
|
agpl-3.0
|
1
|
var entryId = ""
var conversionProfileId = 0
var dynamicConversionAttributes = []
dynamicConversionAttributes[0] = ConversionAttribute()
dynamicConversionAttributes[0].flavorParamsId = 3
let requestBuilder = MediaService.convert(entryId: entryId, conversionProfileId: conversionProfileId, dynamicConversionAttributes: dynamicConversionAttributes)
requestBuilder.set(completion: {(result: Int?, error: ApiException?) in
print(result!)
done()
})
executor.send(request: requestBuilder.build(client))
|
e919d89734adf464f7975cebe8f85e66
| 40.666667 | 159 | 0.819639 | false | false | false | false |
jungtong/MaruKit
|
refs/heads/master
|
Pod/Classes/MaruKit.swift
|
mit
|
1
|
//
// MaruKit.swift
// LernaFramework
//
// Created by jungtong on 2015. 9. 21..
//
//
import Foundation
import LernaFramework
public class MaruKit {
// 최신만화 불러오기
class public func parseMaruNewPage(page: Int) throws -> [String : AnyObject] {
var resultDict = [String : AnyObject]()
var newArray = [[String : String]]()
guard var dataString = LernaNetwork.getStringOfURL("\(maruURLNew)\(page)", timeLimit: 99) else {
throw MaruError.InvalidURL
}
// 필요한 부분만 짤라낸다.
do {
try dataString.cropString(fromString: "만화 업데이트 알림", toString: "처음페이지")
} catch let error {
throw error
}
// 쓸데없는 문자열 정리하고
dataString.cleanUp()
// 각각의 게시글 단위로 분석!
let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<td class=\"subj", second: " <span>|</span>", firstInclude: false, secondInclude: false)
for range in arrayOfRange {
let subString = dataString.substringWithRange(range)
guard let maruNewtitle = subString.subStringBetweenStringsReverse(first: "\">", second: "<span class=\"comment\">") else {
throw MaruError.parseMaruNewError
}
guard var newMaruEpPath = subString.subStringBetweenStrings(first: "href=\"", second: "\">", firstInclude: false, secondInclude: false) else {
throw MaruError.parseMaruNewError
}
if (newMaruEpPath.rangeOfString("uid=") != nil) {
newMaruEpPath = newMaruEpPath.subStringReverseFindToEnd("uid=")!
}
else if (newMaruEpPath.rangeOfString("mangaup/") != nil) {
newMaruEpPath = newMaruEpPath.subStringReverseFindToEnd("mangaup/")!
}
if newMaruEpPath == "" {
throw MaruError.parseMaruNewError
}
// maruNewQImage 는 필수요소가 아님.
var maruNewQImage = subString.subStringBetweenStrings(first: "url(", second: ")\">", firstInclude: false, secondInclude: false)
if maruNewQImage == nil {
maruNewQImage = ""
}
// maruNewTime 는 필수요소가 아님.
var maruNewTime = subString.subStringReverseFindToEnd("<small>")
if maruNewTime == nil {
maruNewTime = ""
}
let newMaru: [String : String] = [
KEY_NEW_TITLE : maruNewtitle,
KEY_NEW_ID : newMaruEpPath,
KEY_NEW_DATETIME : maruNewTime!,
KEY_NEW_QIMAGE : maruNewQImage!
]
newArray.append(newMaru)
}
resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME)
resultDict.updateValue(newArray, forKey: KEY_MARU_DATAARRAY)
return resultDict
}
// 최신만화 분석
class public func parseMaruNewId(newId: String) throws -> [String : AnyObject] {
var resultDict = [String : AnyObject]()
var maruEpArray = [[String : String]]()
guard var dataString = LernaNetwork.getStringOfURL("\(maruURL)/b/mangaup/\(newId)") else {
throw MaruError.InvalidURL
}
// 타이틀 찾기
var maruNewTitle = dataString.subStringBetweenStrings(first: "<title>MARUMARU - 마루마루 - ", second: "</title>", firstInclude: false, secondInclude: false)
if maruNewTitle == nil {
maruNewTitle = ""
}
// 필요한 부분만 짤라낸다.
do {
try dataString.cropString(fromString: "<div class=\"ctt_box\">", toString: "<div class=\"middle_box\">", isFirstFromString: true)
} catch let error {
throw error
}
// 쓸데없는 문자열 정리하고
dataString.cleanUp()
// 썸네일 찾기
var thumbPath = dataString.subStringBetweenStrings(first: "<img src=\"http://", second: "\"", firstInclude: false, secondInclude: false)
if thumbPath == nil {
thumbPath = dataString.subStringBetweenStrings(first: "src=\"http://", second: "\"", firstInclude: false, secondInclude: false)
}
if thumbPath == nil {
thumbPath = dataString.subStringBetweenSecondToFirst(first: "href=\"http://", second: "\" imageanchor=")
}
if thumbPath == nil || !(thumbPath?.rangeOfString(".png") == nil || thumbPath?.rangeOfString(".jpg") == nil) { // || thumbPath?.rangeOfString(".png") == nil
thumbPath = ""
}
else {
thumbPath = "http://\(thumbPath!)"
}
var maruID: String?
// 각각의 게시글 단위로 분석!
let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<a target=\"_blank\"", second: "</a>", firstInclude: false, secondInclude: false)
for range in arrayOfRange {
var subString = dataString.substringWithRange(range)
// 쓸모없는 태그들 지우고
subString.removeSubStringBetweenStrings(first: "<", second: ">")
let maruEpTitle = subString.subStringReverseFindToEnd(">")
if maruEpTitle == nil {
throw MaruError.ErrorTodo
}
if maruEpTitle == "" {
continue
}
let maruEpPath = subString.subStringBetweenStrings(first: "href=\"", second: "\"", firstInclude: false, secondInclude: false)
if maruEpPath == nil {
throw MaruError.ErrorTodo
}
// maruEpPath 의마지막요소꺼내기 (ID)
let maruEpId = maruEpPath!.subStringReverseFindToEnd("/")!
if maruEpTitle!.containsString("전편") {
maruID = maruEpPath?.subStringReverseFindToEnd("uid=")
if maruID == nil {
maruID = maruEpPath?.subStringReverseFindToEnd("manga/")
}
continue
}
let ep: [String : String] = [
KEY_EP_TITLE : maruEpTitle!,
KEY_EP_ID : maruEpId,
]
maruEpArray.append(ep)
}
if maruID == nil {
maruID = ""
}
resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME)
resultDict.updateValue(newId, forKey: KEY_NEW_ID)
resultDict.updateValue(maruNewTitle!, forKey: KEY_NEW_TITLE)
resultDict.updateValue(thumbPath!, forKey: KEY_MARU_QIMAGE)
resultDict.updateValue(maruEpArray, forKey: KEY_MARU_DATAARRAY)
resultDict.updateValue(maruID!, forKey: KEY_MARU_ID)
return resultDict
}
// 전체만화 불러오기
class public func parseMaruAll(sort: Int) throws -> [String : AnyObject] {
var resultDict = [String : AnyObject]()
var maruArray = [[String : String]]()
var page: Int = 1
while(true) {
let parseResult: [String : AnyObject]
do {
parseResult = try parseMaruAllPage(sort, page: page)
}
catch let error {
throw error
}
let maruDataArray: [[String : String]] = parseResult[KEY_MARU_DATAARRAY]! as! [[String : String]]
if maruDataArray.count > 0 {
maruArray.appendContentsOf(maruDataArray)
page++
}
else {
break
}
}
resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME)
resultDict.updateValue(maruArray, forKey: KEY_MARU_DATAARRAY)
return resultDict
}
// 전체만화 페이지 별 불러오기
public class func parseMaruAllPage(sort: Int, page: Int) throws -> [String : AnyObject] {
// DDLogInfo(" 전체목록 \(page) 페이지 로딩 -> ")
var resultDict = [String : AnyObject]()
var maruArray = [[String : String]]()
let urlString: String
if (MaruEnum(rawValue: sort) == MaruEnum.AllSortNew) {
urlString = "\(maruURLAllgid)\(page)"
}
else {
urlString = "\(maruURLAllsubject)\(page)"
}
//---------------------------------------------
guard var dataString = LernaNetwork.getStringOfURL(urlString, timeLimit: 99) else {
throw MaruError.AllMaru_getContents(String(page))
}
// 필요한 부분만 짤라낸다.
do {
try dataString.cropString(fromString: "최신순으로 정렬", toString: "글쓰기")
} catch let error {
throw error
}
// 쓸데없는 문자열 정리하고
dataString.cleanUp()
// 각각의 게시글 단위로 분석!
let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<p class=\"crop\">", second: "comment", firstInclude: false, secondInclude: false)
for range in arrayOfRange {
let subString = dataString.substringWithRange(range)
let maruTitle: String?
if subString.containsString("cat") {
maruTitle = subString.subStringBetweenStringsReverse(first: "</span>", second: "</a><span")
}
else {
maruTitle = subString.subStringBetweenStringsReverse(first: "]", second: "</a><span")
}
// maruTitle 찾지 못함
if maruTitle == nil {
throw MaruError.AllMaru_parse_maruTitle(String(page))
}
var maruID = subString.subStringBetweenStrings(first: "uid=", second: "\"", firstInclude: false, secondInclude: false)
if maruID == nil {
maruID = subString.subStringBetweenStrings(first: "/b/manga/", second: "\">", firstInclude: false, secondInclude: false)
}
if maruID == nil {
throw MaruError.AllMaru_parse_maruID(String(page))
}
// maruQImage 는 필수요소가 아님.
var maruQImage = subString.subStringBetweenStrings(first: "img src=\"", second: "\" ", firstInclude: false, secondInclude: false)
if maruQImage == nil {
maruQImage = ""
}
// maruCategory 는 필수요소가 아님.
var maruCategory = subString.subStringBetweenStrings(first: "class=\"cat\">[", second: "]", firstInclude: false, secondInclude: false)
if maruCategory == nil {
maruCategory = subString.subStringBetweenStrings(first: "[", second: "]", firstInclude: false, secondInclude: false)
if maruCategory == nil {
maruCategory = ""
}
}
let maru: [String : String] = [
KEY_MARU_TITLE : maruTitle!,
KEY_MARU_CATEGORY : maruCategory!,
KEY_MARU_ID : maruID!,
KEY_MARU_QIMAGE : maruQImage!
]
maruArray.append(maru)
}
// DDLogInfo(" \(maruArray.count) 개.")
resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME)
resultDict.updateValue(maruArray, forKey: KEY_MARU_DATAARRAY)
return resultDict
}
// MaruId 로딩
class public func parseMaruId(maruId: String) throws -> [String : AnyObject] {
var resultDict = [String : AnyObject]()
var maruEpArray = [[String : String]]()
guard var dataString = LernaNetwork.getStringOfURL("\(maruURLID)\(maruId)") else {
throw MaruError.ErrorTodo
}
// 타이틀 찾기
var maruTitle = dataString.subStringBetweenStrings(first: "<title>MARUMARU - 마루마루 - ", second: "</title>", firstInclude: false, secondInclude: false)
if maruTitle == nil {
maruTitle = ""
}
// 필요한 부분만 짤라낸다.
do {
try dataString.cropString(fromString: "스크랩", toString: "이 글을 추천합니다!")
} catch let error {
throw error
}
// 썸네일 주소 찾기
var thumbPath = dataString.subStringBetweenStrings(first: "<img src=\"http://", second: "\"", firstInclude: false, secondInclude: false)
if thumbPath == nil {
thumbPath = dataString.subStringBetweenStrings(first: "src=\"http://", second: "\"", firstInclude: false, secondInclude: false)
}
if thumbPath == nil {
thumbPath = dataString.subStringBetweenSecondToFirst(first: "href=\"http://", second: "\" imageanchor=")
}
if thumbPath == nil || !(thumbPath?.rangeOfString(".png") == nil || thumbPath?.rangeOfString(".jpg") == nil) { // || thumbPath?.rangeOfString(".png") == nil
thumbPath = ""
}
else {
thumbPath = "http://\(thumbPath!)"
}
// 쓸데없는 문자열 정리하고
dataString.cleanUp()
// 각각의 게시글 단위로 분석!
let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "<a target=\"_blank\"", second: "/a>", firstInclude: false, secondInclude: false, first2: "<a class=\"con_link\"")
for range in arrayOfRange {
var subString = dataString.substringWithRange(range)
// 쓸모없는 태그들 지우고
subString.removeSubStringBetweenStrings(first: "<", second: ">")
// ep title 찾기
guard var maruEpTitle: String = subString.subStringBetweenStrings(first: ">", second: "<", firstInclude: false, secondInclude: false) else {
throw MaruError.ErrorTodo
}
maruEpTitle = maruEpTitle.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if maruEpTitle == "" {
continue
}
// ep path 찾기
guard let maruEpPath = subString.subStringBetweenStrings(first: "href=\"", second: "\"", firstInclude: false, secondInclude: false) else {
throw MaruError.ErrorTodo
}
// maruEpPath 의마지막요소꺼내기 (ID)
let maruEpId = maruEpPath.subStringReverseFindToEnd("/")!
if Int(maruEpId) == nil {
continue
}
// 중복된 maruEpPath가 있을 경우 title 이어주기
if maruEpArray.last?[KEY_EP_ID] == maruEpId {
maruEpTitle = "\((maruEpArray.last?[KEY_EP_TITLE]!)!)\(maruEpTitle)"
maruEpArray.removeLast()
}
if maruEpTitle == "" {
continue
}
let ep: [String : String] = [
KEY_EP_TITLE : maruEpTitle,
KEY_EP_ID : maruEpId,
]
maruEpArray.append(ep)
}
resultDict.updateValue(LernaUtil.getCurrentDataTime(), forKey: KEY_MARU_DATETIME)
resultDict.updateValue(maruId, forKey: KEY_MARU_ID)
resultDict.updateValue(maruTitle!, forKey: KEY_MARU_TITLE)
resultDict.updateValue(thumbPath!, forKey: KEY_MARU_QIMAGE)
resultDict.updateValue(maruEpArray, forKey: KEY_MARU_DATAARRAY)
return resultDict
}
// MARK: - Completion Handler
// MaruEpId 로딩
class public func parseMaruEpId(maruEpId: String, completionHandler: (result: [String : AnyObject]) -> Void) throws {
guard var dataString = LernaNetwork.getStringOfURL("\(maruURLEp)\(maruEpId)") else {
throw MaruError.ErrorTodo
}
var resultDict = [String : AnyObject]()
var resultArray = [String]()
if (dataString.rangeOfString("password") != nil) {
resultDict.updateValue("Password", forKey: KEY_RESULT)
completionHandler(result: resultDict)
return
}
if (dataString.rangeOfString("You are being redirected...") != nil) {
resultDict.updateValue("Redirected", forKey: KEY_RESULT)
completionHandler(result: resultDict)
return
}
// 필요한 부분만 짤라낸다.
do {
if dataString.rangeOfString("Skip to content") != nil {
try dataString.cropString(fromString: "Skip to content", toString: "돌아가기")
}
else {
try dataString.cropString(fromString: "midtext", toString: "돌아가기")
}
} catch {
resultDict.updateValue("ParseError1", forKey: KEY_RESULT)
completionHandler(result: resultDict)
return
}
// 쓸데없는 문자열 정리하고
dataString.cleanUp()
let arrayOfRange = dataString.rangeOfAllBetweenSubstrings(first: "data-lazy-src=\"", second: "\"", firstInclude: false, secondInclude: false)
if arrayOfRange.isEmpty {
resultDict.updateValue("ParseError2", forKey: KEY_RESULT)
completionHandler(result: resultDict)
return
}
for range in arrayOfRange! {
var subString = dataString.substringWithRange(range)
// ?이후 지우기
if let range = subString.rangeOfString("?") {
subString = subString.substringToIndex(range.startIndex)
}
// 중복되지 않게 저장.
if !resultArray.contains(subString) {
resultArray.append(subString)
}
}
resultDict.updateValue(resultArray, forKey: KEY_MARU_DATAARRAY)
resultDict.updateValue(maruEpId, forKey: KEY_EP_ID)
resultDict.updateValue(RESULT_SUCCESS, forKey: KEY_RESULT)
completionHandler(result: resultDict)
}
// MaruId 로딩
class public func parseMaruId(maruId: String, completionHandler:(result: [String : AnyObject]?) -> Void) throws {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
do {
completionHandler(result: try self.parseMaruId(maruId))
}
catch {
completionHandler(result: nil)
}
})
}
// 전체만화 불러오기
class public func parseMaruAll(sort: Int, completionHandler:(result: [String : AnyObject]?) -> Void) throws {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
do {
completionHandler(result: try self.parseMaruAll(sort))
}
catch {
completionHandler(result: nil)
}
})
}
// 전체만화 페이지 별 불러오기
public class func parseMaruAllPage(sort: Int, page: Int, completionHandler:(result: [String : AnyObject]?) -> Void) throws {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
do {
completionHandler(result: try self.parseMaruAllPage(sort, page: page))
}
catch {
completionHandler(result: nil)
}
})
}
// 최신만화 페이지 불러오기
class public func parseMaruNewPage(page: Int, completionHandler:(result: [String : AnyObject]?) -> Void) throws {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
do {
completionHandler(result: try self.parseMaruNewPage(page))
}
catch {
completionHandler(result: nil)
}
})
}
// 최신만화 분석
class public func parseMaruNewId(newId: String, completionHandler:(result: [String : AnyObject]?) -> Void) throws {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
do {
completionHandler(result: try self.parseMaruNewId(newId))
}
catch {
completionHandler(result: nil)
}
})
}
}
|
d40b95ab8bccc5c8c3499d9fcac1f671
| 36.86148 | 187 | 0.545158 | false | false | false | false |
timfuqua/AEXMLDemo
|
refs/heads/master
|
AEXML.swift
|
mit
|
1
|
//
// AEXML.swift
//
// Copyright (c) 2014 Marko Tadic - http://markotadic.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
class AEXMLElement {
// MARK: Properties
let name: String
var value: String
private(set) var attributes: [NSObject : AnyObject]
private(set) var parent: AEXMLElement?
private(set) var children: [AEXMLElement] = [AEXMLElement]()
private let indentChar = "\t"
// MARK: Lifecycle
init(
_ name: String,
value: String = String(),
attributes: [NSObject : AnyObject] = [NSObject : AnyObject]()
) {
self.name = name
self.value = value
self.attributes = attributes
}
// MARK: XML Read
// returns the first element with given name
subscript(
key: String
) -> AEXMLElement {
if name == "error" {
return self
}
else {
let filtered = children.filter { $0.name == key }
return filtered.count > 0 ? filtered.first! : AEXMLElement("error", value: "element <\(key)> not found")
}
}
var last: AEXMLElement {
let filtered = parent?.children.filter { $0.name == self.name }
return filtered?.count > 0 ? filtered!.last! : self
}
var all: [AEXMLElement] {
let filtered = parent?.children.filter { $0.name == self.name }
return filtered?.count > 0 ? filtered! : [self]
}
// MARK: XML Write
func addChild(
child: AEXMLElement
) -> AEXMLElement {
child.parent = self
children.append(child)
return child
}
func addChild(
name: String,
value: String = String(),
attributes: [NSObject : AnyObject] = [NSObject : AnyObject]()
) -> AEXMLElement {
let child = AEXMLElement(name, value: value, attributes: attributes)
return addChild(child)
}
func addAttribute(
name: NSObject,
value: AnyObject
) {
attributes[name] = value
}
private var parentsCount: Int {
var count = 0
var element = self
while let parent = element.parent? {
count++
element = parent
}
return count
}
private func indentation(
count: Int
) -> String {
var indent = String()
if count > 0 {
for i in 0..<count {
indent += indentChar
}
}
return indent
}
var xmlString: String {
var xml = String()
// open element
xml += indentation(parentsCount - 1)
xml += "<\(name)"
if attributes.count > 0 {
// insert attributes
for att in attributes {
xml += " \(att.0.description)=\"\(att.1.description)\""
}
}
if value == "" && children.count == 0 {
// close element
xml += " />"
}
else {
if children.count > 0 {
// add children
xml += ">\n"
for child in children {
xml += "\(child.xmlString)\n"
}
// add indentation
xml += indentation(parentsCount - 1)
xml += "</\(name)>"
}
else {
// insert value and close element
xml += ">\(value)</\(name)>"
}
}
return xml
}
var xmlStringCompact: String {
let chars = NSCharacterSet(charactersInString: "\n" + indentChar)
return join("", xmlString.componentsSeparatedByCharactersInSet(chars))
}
}
// MARK: -
class AEXMLDocument: AEXMLElement {
// MARK: Properties
let version: Double
let encoding: String
var rootElement: AEXMLElement {
return children.count == 1 ? children.first! : AEXMLElement("error", value: "document does not have root element")
}
// MARK: Lifecycle
init(
version: Double = 1.0,
encoding: String = "utf-8"
) {
self.version = version
self.encoding = encoding
super.init("AEXMLDocumentRoot")
parent = nil
}
convenience init?(
version: Double = 1.0,
encoding: String = "utf-8",
xmlData: NSData,
inout error: NSError?
) {
self.init(version: version, encoding: encoding)
if let parseError = readXMLData(xmlData) {
error = parseError
return nil
}
}
// MARK: Read XML
func readXMLData(
data: NSData
) -> NSError? {
children.removeAll(keepCapacity: false)
let xmlParser = AEXMLParser(xmlDocument: self, xmlData: data)
return xmlParser.tryParsing() ?? nil
}
// MARK: Override
override var xmlString: String {
var xml = "<?xml version=\"\(version)\" encoding=\"\(encoding)\"?>\n"
for child in children {
xml += child.xmlString
}
return xml
}
}
// MARK: -
class AEXMLParser: NSObject, NSXMLParserDelegate {
// MARK: Properties
let xmlDocument: AEXMLDocument
let xmlData: NSData
var currentParent: AEXMLElement?
var currentElement: AEXMLElement?
var currentValue = String()
var parseError: NSError?
// MARK: Lifecycle
init(
xmlDocument: AEXMLDocument,
xmlData: NSData
) {
self.xmlDocument = xmlDocument
self.xmlData = xmlData
currentParent = xmlDocument
super.init()
}
// returns NSError from NSXMLParser delegate callback "parseErrorOccurred"
// returns nil if NSXMLParser successfully parsed XML data
func tryParsing(
) -> NSError? {
var success = false
let parser = NSXMLParser(data: xmlData)
parser.delegate = self
success = parser.parse()
return success ? nil : parseError
}
// MARK: NSXMLParserDelegate
func parser(
parser: NSXMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [NSObject : AnyObject]
) {
currentValue = String()
currentElement = currentParent?.addChild(elementName, attributes: attributeDict)
currentParent = currentElement
}
func parser(
parser: NSXMLParser,
foundCharacters string: String
) {
currentValue += string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
currentElement?.value = currentValue
}
// because of the existing bug in NSXMLParser "didEndElement" delegate callback
// here are used unwrapped optionals for namespaceURI and qualifiedName and that's the only reason why AEXMLParser is not private class
func parser(
parser: NSXMLParser,
didEndElement elementName: String,
namespaceURI: String!,
qualifiedName qName: String!
) {
currentParent = currentParent?.parent
}
func parser(
parser: NSXMLParser,
parseErrorOccurred parseError: NSError
) {
self.parseError = parseError
}
}
|
547e5c51d8b625243a257dea9507f872
| 24.417827 | 139 | 0.531178 | false | false | false | false |
crash-wu/SGRoutePlan
|
refs/heads/master
|
SGRoutePlan/Classes/SGRouteStruct.swift
|
mit
|
1
|
//
// SGRouteStruct.swift
// Pods
//
// Created by 吴小星 on 16/8/18.
//
//
import Foundation
public struct SGRouteStruct {
/*** POI大头针图层 ***/
public static let POI_POPO_LAYER_NAME = "poi_popo_layer_name"
/*** POI大头针选择图层 ***/
public static let POI_POPO_SELECT_LAYER_NAME = "poi_popo_select_layer_name"
/*** 兴趣点点击弹出Callout名称 ****/
public static let POI_CALLOUT_LAYER_NAME = "poi_callout_layer_name"
/*** 驾车路线图层 ****/
public static let CAR_LINE_LAYER_NAME = "car_line_layer_name"
/******** 驾车路线起点图层 *********/
public static let CAR_LINE_ORIGIN_LAYER_NAME = "car_Line_origin_layer_name"
/******** 驾车路线终点图层 *********/
public static let CAR_LINE_DESTION_LAYER_NAME = "car_line_destion_layer_name"
/******** CallOut 类型 *********/
public static let CALLOUT_TYPE = "type"
/******** POI 名称 *********/
public static let POI_NAME = "poi_name"
/******** POI 地址 *********/
public static let POI_ADDRESS = "poi_address"
/******** POI 联系电话 *********/
public static let POI_PHONE = "poi_phone"
/******** POI 坐标 *********/
public static let POI_LONLAT = "poi_lonlat"
}
|
4c7a9db90ee0b2e6e5f0e888b794e82e
| 23.32 | 81 | 0.537449 | false | false | false | false |
cuappdev/tcat-ios
|
refs/heads/master
|
TCAT/Controllers/CustomNavigationController.swift
|
mit
|
1
|
//
// RouteDetailViewController.swift
// TCAT
//
// Created by Matthew Barker on 2/11/17.
// Copyright © 2017 cuappdev. All rights reserved.
//
import NotificationBannerSwift
import UIKit
class CustomNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
/// Attributed string details for the back button text of a navigation controller
static let buttonTitleTextAttributes: [NSAttributedString.Key: Any] = [
.font: UIFont.getFont(.regular, size: 14)
]
private let additionalWidth: CGFloat = 30
private let additionalHeight: CGFloat = 100
/// Attributed string details for the title text of a navigation controller
private let titleTextAttributes: [NSAttributedString.Key: Any] = [
.font: UIFont.getFont(.regular, size: 18),
.foregroundColor: Colors.black
]
private let banner = StatusBarNotificationBanner(title: Constants.Banner.noInternetConnection, style: .danger)
private var screenshotObserver: NSObjectProtocol?
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
view.backgroundColor = Colors.white
customizeAppearance()
ReachabilityManager.shared.addListener(self) { [weak self] connection in
guard let self = self else { return }
switch connection {
case .wifi, .cellular:
self.banner.dismiss()
case .none:
self.banner.show(queuePosition: .front, on: self)
self.banner.autoDismiss = false
self.banner.isUserInteractionEnabled = false
}
self.setNeedsStatusBarAppearanceUpdate()
}
}
open override var childForStatusBarStyle: UIViewController? {
return visibleViewController
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return banner.isDisplaying ? .lightContent : .default
}
override func viewDidLoad() {
super.viewDidLoad()
if responds(to: #selector(getter: interactivePopGestureRecognizer)) {
interactivePopGestureRecognizer?.delegate = self
delegate = self
}
// Add screenshot listener, log view controller name
let notifName = UIApplication.userDidTakeScreenshotNotification
screenshotObserver = NotificationCenter.default.addObserver(forName: notifName, object: nil, queue: .main) { _ in
guard let currentViewController = self.visibleViewController else { return }
let payload = ScreenshotTakenPayload(location: "\(type(of: currentViewController))")
Analytics.shared.log(payload)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let screenshotObserver = screenshotObserver {
NotificationCenter.default.removeObserver(screenshotObserver)
}
}
private func customizeAppearance() {
navigationBar.backgroundColor = Colors.white
navigationBar.barTintColor = Colors.white
navigationBar.tintColor = Colors.primaryText
navigationBar.titleTextAttributes = titleTextAttributes
navigationItem.backBarButtonItem?.setTitleTextAttributes(
CustomNavigationController.buttonTitleTextAttributes, for: .normal
)
}
/// Return an instance of custom back button
private func customBackButton() -> UIBarButtonItem {
let backButton = UIButton()
backButton.setImage(#imageLiteral(resourceName: "back"), for: .normal)
backButton.tintColor = Colors.primaryText
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.getFont(.regular, size: 14.0),
.foregroundColor: Colors.primaryText,
.baselineOffset: 0.3
]
let attributedString = NSMutableAttributedString(string: " " + Constants.Buttons.back, attributes: attributes)
backButton.setAttributedTitle(attributedString, for: .normal)
backButton.sizeToFit()
// Expand frame to create bigger touch area
backButton.frame = CGRect(x: backButton.frame.minX, y: backButton.frame.minY, width: backButton.frame.width + additionalWidth, height: backButton.frame.height + additionalHeight)
backButton.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: additionalWidth)
backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
return UIBarButtonItem(customView: backButton)
}
/// Move back one view controller in navigationController stack
@objc private func backAction() {
_ = popViewController(animated: true)
}
// MARK: - UINavigationController Functions
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if responds(to: #selector(getter: interactivePopGestureRecognizer)) {
interactivePopGestureRecognizer?.isEnabled = false
}
super.pushViewController(viewController, animated: animated)
if viewControllers.count > 1 {
navigationBar.titleTextAttributes = titleTextAttributes
// Add back button for non-modal non-peeked screens
if !viewController.isModal {
viewController.navigationItem.hidesBackButton = true
viewController.navigationItem.setLeftBarButton(customBackButton(), animated: true)
}
}
}
override func popViewController(animated: Bool) -> UIViewController? {
let viewController = super.popViewController(animated: animated)
if let homeMapVC = viewControllers.last as? HomeMapViewController {
homeMapVC.navigationItem.leftBarButtonItem = nil
}
return viewController
}
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
super.present(viewControllerToPresent, animated: flag, completion: completion)
banner.dismiss()
}
// MARK: - UINavigationControllerDelegate Functions
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
setNavigationBarHidden(viewController is ParentHomeMapViewController, animated: animated)
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
interactivePopGestureRecognizer?.isEnabled = (responds(to: #selector(getter: interactivePopGestureRecognizer)) && viewControllers.count > 1)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
}
class OnboardingNavigationController: UINavigationController {
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
navigationBar.isTranslucent = true
}
open override var childForStatusBarStyle: UIViewController? {
return visibleViewController
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Do NOT remove this initializer; OnboardingNavigationController will crash without it.
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
}
|
fd7e3401fe1a1473b1f01128ecbbea74
| 38.576531 | 186 | 0.698466 | false | false | false | false |
alblue/swift
|
refs/heads/master
|
test/SILOptimizer/pgo_si_inlinelarge.swift
|
apache-2.0
|
14
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_si_inlinelarge -o %t/main
// This unusual use of 'sh' allows the path of the profraw file to be
// substituted by %target-run.
// RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_si_inlinelarge -o - | %FileCheck %s --check-prefix=SIL
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_si_inlinelarge -o - | %FileCheck %s --check-prefix=SIL-OPT
// REQUIRES: profile_runtime
// REQUIRES: executable_test
// REQUIRES: OS=macosx
public func bar(_ x: Int64) -> Int64 {
if (x == 0) {
return 42
}
if (x == 1) {
return 6
}
if (x == 2) {
return 9
}
if (x == 3) {
return 93
}
if (x == 4) {
return 94
}
if (x == 5) {
return 95
}
if (x == 6) {
return 96
}
if (x == 7) {
return 97
}
if (x == 8) {
return 98
}
if (x == 9) {
return 99
}
if (x == 10) {
return 910
}
if (x == 11) {
return 911
}
if (x == 11) {
return 911
}
if (x == 11) {
return 911
}
if (x == 12) {
return 912
}
if (x == 13) {
return 913
}
if (x == 14) {
return 914
}
if (x == 15) {
return 916
}
if (x == 17) {
return 917
}
if (x == 18) {
return 918
}
if (x == 19) {
return 919
}
if (x % 2 == 0) {
return 4242
}
var ret : Int64 = 0
for currNum in stride(from: 5, to: x, by: 5) {
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
print("in bar stride")
ret += currNum
print(ret)
}
return ret
}
// SIL-LABEL: sil @$s18pgo_si_inlinelarge3fooyys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
// SIL-OPT-LABEL: sil @$s18pgo_si_inlinelarge3fooyys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
public func foo(_ x: Int64) {
// SIL: switch_enum {{.*}} : $Optional<Int64>, case #Optional.some!enumelt.1: {{.*}} !case_count(100), case #Optional.none!enumelt: {{.*}} !case_count(1)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(50)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(1)
// SIL-OPT: integer_literal $Builtin.Int64, 93
// SIL-OPT: integer_literal $Builtin.Int64, 42
// SIL-OPT: function_ref @$s18pgo_si_inlinelarge3barys5Int64VADF : $@convention(thin) (Int64) -> Int64
var sum : Int64 = 0
for index in 1...x {
if (index % 2 == 0) {
sum += bar(index)
}
if (index == 50) {
sum += bar(index)
}
sum += 1
}
print(sum)
}
// SIL-LABEL: } // end sil function '$s18pgo_si_inlinelarge3fooyys5Int64VF'
// SIL-OPT-LABEL: } // end sil function '$s18pgo_si_inlinelarge3fooyys5Int64VF'
foo(100)
|
ebbf96da90567247784400a26535ff03
| 23.266667 | 172 | 0.570513 | false | false | false | false |
dmrschmidt/DSWaveformImage
|
refs/heads/main
|
Sources/DSWaveformImage/WaveformAnalyzer.swift
|
mit
|
1
|
//
// see
// * http://www.davidstarke.com/2015/04/waveforms.html
// * http://stackoverflow.com/questions/28626914
// for very good explanations of the asset reading and processing path
//
// FFT done using: https://github.com/jscalo/tempi-fft
//
import Foundation
import Accelerate
import AVFoundation
struct WaveformAnalysis {
let amplitudes: [Float]
let fft: [TempiFFT]?
}
/// Calculates the waveform of the initialized asset URL.
public class WaveformAnalyzer {
public enum AnalyzeError: Error { case generic }
/// Everything below this noise floor cutoff will be clipped and interpreted as silence. Default is `-50.0`.
public var noiseFloorDecibelCutoff: Float = -50.0
private let assetReader: AVAssetReader
private let audioAssetTrack: AVAssetTrack
public init?(audioAssetURL: URL) {
let audioAsset = AVURLAsset(url: audioAssetURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])
do {
let assetReader = try AVAssetReader(asset: audioAsset)
guard let assetTrack = audioAsset.tracks(withMediaType: .audio).first else {
print("ERROR loading asset track")
return nil
}
self.assetReader = assetReader
self.audioAssetTrack = assetTrack
} catch {
print("ERROR loading asset \(error)")
return nil
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
/// Calculates the amplitude envelope of the initialized audio asset URL, downsampled to the required `count` amount of samples.
/// Calls the completionHandler on a background thread.
/// - Parameter count: amount of samples to be calculated. Downsamples.
/// - Parameter qos: QoS of the DispatchQueue the calculations are performed (and returned) on.
///
/// Returns sampled result or nil in edge-error cases.
public func samples(count: Int, qos: DispatchQoS.QoSClass = .userInitiated) async throws -> [Float] {
try await withCheckedThrowingContinuation { continuation in
waveformSamples(count: count, qos: qos, fftBands: nil) { analysis in
if let amplitudes = analysis?.amplitudes {
continuation.resume(with: .success(amplitudes))
} else {
continuation.resume(with: .failure(AnalyzeError.generic))
}
}
}
}
#endif
/// Calculates the amplitude envelope of the initialized audio asset URL, downsampled to the required `count` amount of samples.
/// Calls the completionHandler on a background thread.
/// - Parameter count: amount of samples to be calculated. Downsamples.
/// - Parameter qos: QoS of the DispatchQueue the calculations are performed (and returned) on.
/// - Parameter completionHandler: called from a background thread. Returns the sampled result or nil in edge-error cases.
public func samples(count: Int, qos: DispatchQoS.QoSClass = .userInitiated, completionHandler: @escaping (_ amplitudes: [Float]?) -> ()) {
waveformSamples(count: count, qos: qos, fftBands: nil) { analysis in
completionHandler(analysis?.amplitudes)
}
}
}
// MARK: - Private
fileprivate extension WaveformAnalyzer {
func waveformSamples(
count requiredNumberOfSamples: Int,
qos: DispatchQoS.QoSClass,
fftBands: Int?,
completionHandler: @escaping (_ analysis: WaveformAnalysis?) -> ()) {
guard requiredNumberOfSamples > 0 else {
completionHandler(nil)
return
}
let trackOutput = AVAssetReaderTrackOutput(track: audioAssetTrack, outputSettings: outputSettings())
assetReader.add(trackOutput)
assetReader.asset.loadValuesAsynchronously(forKeys: ["duration"]) {
var error: NSError?
let status = self.assetReader.asset.statusOfValue(forKey: "duration", error: &error)
switch status {
case .loaded:
let totalSamples = self.totalSamplesOfTrack()
DispatchQueue.global(qos: qos).async {
let analysis = self.extract(totalSamples: totalSamples, downsampledTo: requiredNumberOfSamples, fftBands: fftBands)
switch self.assetReader.status {
case .completed:
completionHandler(analysis)
default:
print("ERROR: reading waveform audio data has failed \(self.assetReader.status)")
completionHandler(nil)
}
}
case .failed, .cancelled, .loading, .unknown:
print("failed to load due to: \(error?.localizedDescription ?? "unknown error")")
completionHandler(nil)
@unknown default:
print("failed to load due to: \(error?.localizedDescription ?? "unknown error")")
completionHandler(nil)
}
}
}
func extract(totalSamples: Int,
downsampledTo targetSampleCount: Int,
fftBands: Int?) -> WaveformAnalysis {
var outputSamples = [Float]()
var outputFFT = fftBands == nil ? nil : [TempiFFT]()
var sampleBuffer = Data()
var sampleBufferFFT = Data()
// read upfront to avoid frequent re-calculation (and memory bloat from C-bridging)
let samplesPerPixel = max(1, totalSamples / targetSampleCount)
let samplesPerFFT = 4096 // ~100ms at 44.1kHz, rounded to closest pow(2) for FFT
self.assetReader.startReading()
while self.assetReader.status == .reading {
let trackOutput = assetReader.outputs.first!
guard let nextSampleBuffer = trackOutput.copyNextSampleBuffer(),
let blockBuffer = CMSampleBufferGetDataBuffer(nextSampleBuffer) else {
break
}
var readBufferLength = 0
var readBufferPointer: UnsafeMutablePointer<Int8>? = nil
CMBlockBufferGetDataPointer(blockBuffer, atOffset: 0, lengthAtOffsetOut: &readBufferLength, totalLengthOut: nil, dataPointerOut: &readBufferPointer)
sampleBuffer.append(UnsafeBufferPointer(start: readBufferPointer, count: readBufferLength))
if fftBands != nil {
// don't append data to this buffer unless we're going to use it.
sampleBufferFFT.append(UnsafeBufferPointer(start: readBufferPointer, count: readBufferLength))
}
CMSampleBufferInvalidate(nextSampleBuffer)
let processedSamples = process(sampleBuffer, from: assetReader, downsampleTo: samplesPerPixel)
outputSamples += processedSamples
if processedSamples.count > 0 {
// vDSP_desamp uses strides of samplesPerPixel; remove only the processed ones
sampleBuffer.removeFirst(processedSamples.count * samplesPerPixel * MemoryLayout<Int16>.size)
// this takes care of a memory leak where Memory continues to increase even though it should clear after calling .removeFirst(…) above.
sampleBuffer = Data(sampleBuffer)
}
if let fftBands = fftBands, sampleBufferFFT.count / MemoryLayout<Int16>.size >= samplesPerFFT {
let processedFFTs = process(sampleBufferFFT, samplesPerFFT: samplesPerFFT, fftBands: fftBands)
sampleBufferFFT.removeFirst(processedFFTs.count * samplesPerFFT * MemoryLayout<Int16>.size)
outputFFT? += processedFFTs
}
}
// if we don't have enough pixels yet,
// process leftover samples with padding (to reach multiple of samplesPerPixel for vDSP_desamp)
if outputSamples.count < targetSampleCount {
let missingSampleCount = (targetSampleCount - outputSamples.count) * samplesPerPixel
let backfillPaddingSampleCount = missingSampleCount - (sampleBuffer.count / MemoryLayout<Int16>.size)
let backfillPaddingSampleCount16 = backfillPaddingSampleCount * MemoryLayout<Int16>.size
let backfillPaddingSamples = [UInt8](repeating: 0, count: backfillPaddingSampleCount16)
sampleBuffer.append(backfillPaddingSamples, count: backfillPaddingSampleCount16)
let processedSamples = process(sampleBuffer, from: assetReader, downsampleTo: samplesPerPixel)
outputSamples += processedSamples
}
let targetSamples = Array(outputSamples[0..<targetSampleCount])
return WaveformAnalysis(amplitudes: normalize(targetSamples), fft: outputFFT)
}
private func process(_ sampleBuffer: Data,
from assetReader: AVAssetReader,
downsampleTo samplesPerPixel: Int) -> [Float] {
var downSampledData = [Float]()
let sampleLength = sampleBuffer.count / MemoryLayout<Int16>.size
// guard for crash in very long audio files
guard sampleLength / samplesPerPixel > 0 else { return downSampledData }
sampleBuffer.withUnsafeBytes { (samplesRawPointer: UnsafeRawBufferPointer) in
let unsafeSamplesBufferPointer = samplesRawPointer.bindMemory(to: Int16.self)
let unsafeSamplesPointer = unsafeSamplesBufferPointer.baseAddress!
var loudestClipValue: Float = 0.0
var quietestClipValue = noiseFloorDecibelCutoff
var zeroDbEquivalent: Float = Float(Int16.max) // maximum amplitude storable in Int16 = 0 Db (loudest)
let samplesToProcess = vDSP_Length(sampleLength)
var processingBuffer = [Float](repeating: 0.0, count: Int(samplesToProcess))
vDSP_vflt16(unsafeSamplesPointer, 1, &processingBuffer, 1, samplesToProcess) // convert 16bit int to float (
vDSP_vabs(processingBuffer, 1, &processingBuffer, 1, samplesToProcess) // absolute amplitude value
vDSP_vdbcon(processingBuffer, 1, &zeroDbEquivalent, &processingBuffer, 1, samplesToProcess, 1) // convert to DB
vDSP_vclip(processingBuffer, 1, &quietestClipValue, &loudestClipValue, &processingBuffer, 1, samplesToProcess)
let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel)
let downSampledLength = sampleLength / samplesPerPixel
downSampledData = [Float](repeating: 0.0, count: downSampledLength)
vDSP_desamp(processingBuffer,
vDSP_Stride(samplesPerPixel),
filter,
&downSampledData,
vDSP_Length(downSampledLength),
vDSP_Length(samplesPerPixel))
}
return downSampledData
}
private func process(_ sampleBuffer: Data,
samplesPerFFT: Int,
fftBands: Int) -> [TempiFFT] {
var ffts = [TempiFFT]()
let sampleLength = sampleBuffer.count / MemoryLayout<Int16>.size
sampleBuffer.withUnsafeBytes { (samplesRawPointer: UnsafeRawBufferPointer) in
let unsafeSamplesBufferPointer = samplesRawPointer.bindMemory(to: Int16.self)
let unsafeSamplesPointer = unsafeSamplesBufferPointer.baseAddress!
let samplesToProcess = vDSP_Length(sampleLength)
var processingBuffer = [Float](repeating: 0.0, count: Int(samplesToProcess))
vDSP_vflt16(unsafeSamplesPointer, 1, &processingBuffer, 1, samplesToProcess) // convert 16bit int to float
repeat {
let fftBuffer = processingBuffer[0..<samplesPerFFT]
let fft = TempiFFT(withSize: samplesPerFFT, sampleRate: 44100.0)
fft.windowType = TempiFFTWindowType.hanning
fft.fftForward(Array(fftBuffer))
fft.calculateLinearBands(minFrequency: 0, maxFrequency: fft.nyquistFrequency, numberOfBands: fftBands)
ffts.append(fft)
processingBuffer.removeFirst(samplesPerFFT)
} while processingBuffer.count >= samplesPerFFT
}
return ffts
}
func normalize(_ samples: [Float]) -> [Float] {
return samples.map { $0 / noiseFloorDecibelCutoff }
}
// swiftlint:disable force_cast
private func totalSamplesOfTrack() -> Int {
var totalSamples = 0
autoreleasepool {
let descriptions = audioAssetTrack.formatDescriptions as! [CMFormatDescription]
descriptions.forEach { formatDescription in
guard let basicDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription) else { return }
let channelCount = Int(basicDescription.pointee.mChannelsPerFrame)
let sampleRate = basicDescription.pointee.mSampleRate
let duration = Double(assetReader.asset.duration.value)
let timescale = Double(assetReader.asset.duration.timescale)
let totalDuration = duration / timescale
totalSamples = Int(sampleRate * totalDuration) * channelCount
}
}
return totalSamples
}
// swiftlint:enable force_cast
}
// MARK: - Configuration
private extension WaveformAnalyzer {
func outputSettings() -> [String: Any] {
return [
AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsNonInterleaved: false
]
}
}
|
bee493aaa08c5ca76079f80c1195eaa4
| 45.714777 | 160 | 0.647271 | false | false | false | false |
tingkerians/master
|
refs/heads/Doharmony
|
doharmony/FriendsViewController.swift
|
unlicense
|
1
|
//
// ViewController.swift
// PageMenuDemoStoryboard
//
// Created by Niklas Fahl on 12/19/14.
// Copyright (c) 2014 CAPS. All rights reserved.
//
import UIKit
class FriendsViewController: UIViewControllerProtectedPage,UITabBarControllerDelegate,CAPSPageMenuDelegate {
var pageMenu : CAPSPageMenu?
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.hidden = true
self.tabBarController?.delegate = self
// Initialize view controllers to display and place in array
var controllerArray : [UIViewController] = []
let controller1 : PostsTableViewController = PostsTableViewController(nibName: "PostsTableViewController", bundle: nil)
controller1.title = locale.Post
controller1.searchBar = searchBar
controllerArray.append(controller1)
let controller2 : MyFriendsTableViewController = MyFriendsTableViewController(nibName: "MyFriendsTableViewController", bundle: nil)
controller2.title = locale.Friend
controller2.searchBar = searchBar
controllerArray.append(controller2)
let controller3 : FollowingsTableViewController = FollowingsTableViewController(nibName: "FollowingsTableViewController", bundle: nil)
controller3.title = locale.Following
controller3.searchBar = searchBar
controllerArray.append(controller3)
let controller4 : AllMembersTableViewController = AllMembersTableViewController(nibName: "AllMembersTableViewController", bundle: nil)
controller4.title = locale.All
controller4.searchBar = searchBar
controllerArray.append(controller4)
// Initialize scroll menu
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: env.CAPSPageMenuOptions)
pageMenu?.delegate = self
self.addChildViewController(pageMenu!)
self.view.addSubview(pageMenu!.view)
self.view.bringSubviewToFront(searchBar)
}
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
let selectedIndex = tabBarController.viewControllers?.indexOf(viewController)
tabBarTransition.selectedIndex = selectedIndex
tabBarTransition.prevSelectedIndex = tabBarController.selectedIndex
return true
}
func didMoveToPage(controller: UIViewController, index: Int) {
if(controller.title == locale.Post){
searchBar.hidden = true
searchBar.endEditing(true)
}else{
searchBar.hidden = false
}
}
}
|
a2032fb30f68443e9fa16961bc425eac
| 40.477612 | 183 | 0.709968 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothGATT/ATTHandleValueIndication.swift
|
mit
|
1
|
//
// ATTHandleValueIndication.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Handle Value Indication
///
/// A server can send an indication of an attribute’s value.
@frozen
public struct ATTHandleValueIndication: ATTProtocolDataUnit, Equatable {
public static var attributeOpcode: ATTOpcode { return .handleValueIndication }
/// The handle of the attribute.
public var handle: UInt16
/// The handle of the attribute.
public var value: Data
public init(handle: UInt16, value: Data) {
self.handle = handle
self.value = value
}
}
public extension ATTHandleValueIndication {
init?(data: Data) {
guard data.count >= 3,
type(of: self).validateOpcode(data)
else { return nil }
self.handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2])))
self.value = data.suffixCheckingBounds(from: 3)
}
var data: Data {
return Data(self)
}
}
public extension ATTHandleValueIndication {
init(attribute: GATTDatabase.Attribute, maximumTransmissionUnit: ATTMaximumTransmissionUnit) {
// If the attribue value is longer than (ATT_MTU-3) octets,
// then only the first (ATT_MTU-3) octets of this attribute value
// can be sent in a indication.
let dataSize = Int(maximumTransmissionUnit.rawValue) - 3
let value: Data
if attribute.value.count > dataSize {
value = Data(attribute.value.prefix(dataSize))
} else {
value = attribute.value
}
self.init(handle: attribute.handle, value: value)
}
}
// MARK: - DataConvertible
extension ATTHandleValueIndication: DataConvertible {
var dataLength: Int {
return 3 + value.count
}
static func += <T: DataContainer> (data: inout T, value: ATTHandleValueIndication) {
data += attributeOpcode.rawValue
data += value.handle.littleEndian
data += value.value
}
}
|
f1ddc7ba363ebb684d8e49137e7383c7
| 24.05618 | 98 | 0.604036 | false | false | false | false |
PayPal-Opportunity-Hack-Chennai-2015/No-Food-Waste
|
refs/heads/master
|
ios/NoFoodWaster/NoFoodWaster/Theme.swift
|
apache-2.0
|
3
|
//
// Theme.swift
// NoFoodWaster
//
// Created by Ravi Shankar on 28/11/15.
// Copyright © 2015 Ravi Shankar. All rights reserved.
//
import UIKit
func applyTheme() {
let sharedApplication = UIApplication.sharedApplication()
sharedApplication.delegate?.window??.tintColor = mainColor
sharedApplication.statusBarStyle = UIStatusBarStyle.LightContent
styleForTabBar()
styleForNavigationBar()
styleForTableView()
}
func styleForTabBar() {
UITabBar.appearance().barTintColor = barTintColor
UITabBar.appearance().tintColor = UIColor.whiteColor()
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.whiteColor()], forState:.Selected)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.blackColor()], forState:.Normal)
}
func styleForNavigationBar() {
UINavigationBar.appearance().barTintColor = barTintColor
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: standardTextFont, NSForegroundColorAttributeName: UIColor.whiteColor()]
}
func styleForTableView() {
UITableView.appearance().backgroundColor = backgroundColor
UITableView.appearance().separatorStyle = .SingleLine
}
func formatDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
let dateStr = dateFormatter.stringFromDate(date)
return dateStr
}
var mainColor: UIColor {
return UIColor(red: 215.0/255.0, green: 100.0/255.0, blue: 76.0/255.0, alpha: 1.0)
}
var barTintColor: UIColor {
return UIColor(red: 215.0/255.0, green: 100.0/255.0, blue: 76.0/255.0, alpha: 1.0)
}
var barTextColor: UIColor {
return UIColor(red: 254.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
}
var backgroundColor: UIColor {
return UIColor(red: 251.0/255.0, green: 243.0/255.0, blue: 241.0/255.0, alpha: 1.0)
}
var secondaryColor: UIColor {
return UIColor(red: 251.0/255.0, green: 243.0/255.0, blue: 241.0/255.0, alpha: 1.0)
}
var textColor: UIColor {
return UIColor(red: 63.0/255.0, green: 62.0/255.0, blue: 61.0/255.0, alpha: 1.0)
}
var headingTextColor: UIColor {
return UIColor(red: 44.0/255.0, green: 45.0/255.0, blue: 40.0/255.0, alpha: 1.0)
}
var subtitleTextColor: UIColor {
return UIColor(red: 156.0/255.0, green: 155.0/255.0, blue: 150.0/255.0, alpha: 1.0)
}
var standardTextFont: UIFont {
return UIFont(name: "HelveticaNeue-Medium", size: 15)!
}
var subtitleFont: UIFont {
return UIFont(name: "HelveticaNeue-Light", size: 15)!
}
var headlineFot: UIFont {
return UIFont(name: "HelveticaNeue-Bold", size: 15)!
}
|
d02cc973ed98dae810eb55726d7bae99
| 28.666667 | 149 | 0.720551 | false | false | false | false |
lukemetz/Paranormal
|
refs/heads/master
|
Paranormal/Paranormal/GPUImageFilters/ChamferFilter.swift
|
mit
|
2
|
import Foundation
import GPUImage
class ChamferFilter : GPUImageFilter {
var depth : Float = 2.0
var radius : Float = 20.0
var shape : Float = 0.0
override init() {
super.init(fragmentShaderFromFile: "Chamfer")
}
convenience init(radius: Float, depth: Float, shape: Float) {
self.init()
self.depth = depth
self.radius = radius
self.shape = shape
}
override init!(fragmentShaderFromString fragmentShaderString: String!) {
super.init(fragmentShaderFromString: fragmentShaderString)
}
override init!(vertexShaderFromString vertexShaderString: String!,
fragmentShaderFromString fragmentShaderString: String!) {
super.init(vertexShaderFromString: vertexShaderString,
fragmentShaderFromString: fragmentShaderString)
}
override func setupFilterForSize(filterFrameSize: CGSize) {
super.setupFilterForSize(filterFrameSize)
runSynchronouslyOnVideoProcessingQueue {
GPUImageContext.setActiveShaderProgram(self.valueForKey("filterProgram") as GLProgram!)
self.setFloat(GLfloat(1.0/filterFrameSize.height), forUniformName: "texelHeight")
self.setFloat(GLfloat(1.0/filterFrameSize.width), forUniformName: "texelWidth")
self.setFloat(GLfloat(self.depth), forUniformName: "depth")
self.setFloat(GLfloat(self.radius), forUniformName: "radius")
self.setFloat(GLfloat(self.shape), forUniformName: "shape")
}
}
}
|
c6bcd63ccd45feee3218a8867c0a7971
| 35.380952 | 99 | 0.687827 | false | false | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0
|
refs/heads/master
|
Playground Collection/Part 5 - Pirate Fleet 2/Structs with Protocols/Structs with Protocols.playground/Pages/Equatable Example.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
/*:
## Equatable Example
*/
//: ### PlayingCard Protocol
/*:
This protocol describes what are the necessary traits for something to be considered a `PlayingCard`. For example, to be considered a `PlayingCard` you must have the following properties:
- a `Bool` variable called `isFaceDown`
- a computed `String` variable property called `shortName`.
*/
protocol PlayingCard {
var isFaceDown: Bool { get set }
var shortName: String { get }
}
//: ### A Joker is-a PlayingCard and it is Equatable
struct Joker: PlayingCard, Equatable {
enum Color {
case red
case black
}
let color: Color
// for a Joker to be considered a PlayingCard it must provide these properties!
var isFaceDown: Bool
var shortName: String {
if isFaceDown {
return "???"
}
switch color {
case .red:
return "R 🃏"
case .black:
return "B 🃏"
}
}
}
//: For a Joker to be Equatable, we must define equality between Jokers.
func ==(lhs: Joker, rhs: Joker) -> Bool {
return true
}
var redJoker = Joker(color: .red, isFaceDown: false)
var blackJoker = Joker(color: .black, isFaceDown: false)
blackJoker == redJoker
blackJoker != redJoker
//: [Next](@next)
|
a070b3ba8af505f70f54b63001f577ce
| 23.259259 | 187 | 0.625191 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
test/attr/attr_noescape.swift
|
apache-2.0
|
10
|
// RUN: %target-parse-verify-swift
@noescape var fn : () -> Int = { 4 } // expected-error {{@noescape may only be used on 'parameter' declarations}} {{1-11=}}
func doesEscape(fn : () -> Int) {}
func takesGenericClosure<T>(a : Int, @noescape _ fn : () -> T) {}
func takesNoEscapeClosure(@noescape fn : () -> Int) {
takesNoEscapeClosure { 4 } // ok
fn() // ok
var x = fn // expected-error {{@noescape parameter 'fn' may only be called}}
// This is ok, because the closure itself is noescape.
takesNoEscapeClosure { fn() }
// This is not ok, because it escapes the 'fn' closure.
doesEscape { fn() } // expected-error {{closure use of @noescape parameter 'fn' may allow it to escape}}
// This is not ok, because it escapes the 'fn' closure.
func nested_function() {
fn() // expected-error {{declaration closing over @noescape parameter 'fn' may allow it to escape}}
}
takesNoEscapeClosure(fn) // ok
doesEscape(fn) // expected-error {{invalid conversion from non-escaping function of type '@noescape () -> Int' to potentially escaping function type '() -> Int'}}
takesGenericClosure(4, fn) // ok
takesGenericClosure(4) { fn() } // ok.
}
class SomeClass {
final var x = 42
func test() {
// This should require "self."
doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
// Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't
// require "self." qualification of member references.
takesNoEscapeClosure { x }
}
func foo() -> Int {
foo()
func plain() { foo() }
let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
func outer() {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() }
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 }
}
let outer2: () -> Void = {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
}
doesEscape {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
return 0
}
takesNoEscapeClosure {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
return 0
}
struct Outer {
func bar() -> Int {
bar()
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
func structOuter() {
struct Inner {
func bar() -> Int {
bar() // no-warning
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
}
return 0
}
}
// Implicit conversions (in this case to @convention(block)) are ok.
@_silgen_name("whatever")
func takeNoEscapeAsObjCBlock(@noescape _: @convention(block) () -> Void)
func takeNoEscapeTest2(@noescape fn : () -> ()) {
takeNoEscapeAsObjCBlock(fn)
}
// Autoclosure implies noescape, but produce nice diagnostics so people know
// why noescape problems happen.
func testAutoclosure(@autoclosure a : () -> Int) { // expected-note{{parameter 'a' is implicitly @noescape because it was declared @autoclosure}}
doesEscape { a() } // expected-error {{closure use of @noescape parameter 'a' may allow it to escape}}
}
// <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both
func redundant(@noescape // expected-error {{@noescape is implied by @autoclosure and should not be redundantly specified}} {{16-25=}}
@autoclosure fn : () -> Int) {
}
protocol P1 {
typealias Element
}
protocol P2 : P1 {
typealias Element
}
func overloadedEach<O: P1, T>(source: O, _ transform: O.Element -> (), _: T) {}
func overloadedEach<P: P2, T>(source: P, _ transform: P.Element -> (), _: T) {}
struct S : P2 {
typealias Element = Int
func each(@noescape transform: Int -> ()) {
overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, @noescape Int -> (), Int)'}}
transform, 1)
// expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, O.Element -> (), T), (P, P.Element -> (), T)}}
}
}
// rdar://19763676 - False positive in @noescape analysis triggered by parameter label
func r19763676Callee(@noescape f: (param: Int) -> Int) {}
func r19763676Caller(@noescape g: (Int) -> Int) {
r19763676Callee({ _ in g(1) })
}
// <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments
func calleeWithDefaultParameters(@noescape f: () -> (), x : Int = 1) {} // expected-warning {{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}}
func callerOfDefaultParams(@noescape g: () -> ()) {
calleeWithDefaultParameters(g)
}
// <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape
class NoEscapeImmediatelyApplied {
func f() {
// Shouldn't require "self.", the closure is obviously @noescape.
_ = { return ivar }()
}
final var ivar = 42
}
// Reduced example from XCTest overlay, involves a TupleShuffleExpr
public func XCTAssertTrue(@autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
}
public func XCTAssert( @autoclosure expression: () -> BooleanType, _ message: String = "", file: String = __FILE__, line: UInt = __LINE__) -> Void {
XCTAssertTrue(expression, message, file: file, line: line);
}
|
938de4499e05326e2783856d1771c0bf
| 50.478448 | 199 | 0.647325 | false | false | false | false |
danielsaidi/KeyboardKit
|
refs/heads/master
|
Sources/KeyboardKit/Gestures/KeyboardGestures.swift
|
mit
|
1
|
//
// KeyboardGestures.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-01-10.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This view wraps a view then applies keyboard gestures to it.
It can be applied with the `keyboardGestures` view modifier.
*/
struct KeyboardGestures<Content: View>: View {
init(
view: Content,
action: KeyboardAction?,
isPressed: Binding<Bool>,
tapAction: KeyboardGestureAction?,
doubleTapAction: KeyboardGestureAction?,
longPressAction: KeyboardGestureAction?,
pressAction: KeyboardGestureAction?,
releaseAction: KeyboardGestureAction?,
repeatAction: KeyboardGestureAction?,
dragAction: KeyboardDragGestureAction?) {
self.view = view
self.action = action
self.isPressed = isPressed
self.tapAction = tapAction
self.doubleTapAction = doubleTapAction
self.longPressAction = longPressAction
self.pressAction = pressAction
self.releaseAction = releaseAction
self.repeatAction = repeatAction
self.dragAction = dragAction
}
private let view: Content
private let action: KeyboardAction?
private let isPressed: Binding<Bool>
private let tapAction: KeyboardGestureAction?
private let doubleTapAction: KeyboardGestureAction?
private let longPressAction: KeyboardGestureAction?
private let pressAction: KeyboardGestureAction?
private let releaseAction: KeyboardGestureAction?
private let repeatAction: KeyboardGestureAction?
private let dragAction: KeyboardDragGestureAction?
@EnvironmentObject private var inputCalloutContext: InputCalloutContext
@EnvironmentObject private var secondaryInputCalloutContext: SecondaryInputCalloutContext
private let repeatTimer = RepeatGestureTimer()
@State private var isDragGestureTriggered = false
@State private var isInputCalloutEnabled = true
@State private var isRepeatGestureActive = false {
didSet { isRepeatGestureActive ? startRepeatTimer() : stopRepeatTimer() }
}
var body: some View {
view.overlay(GeometryReader { geo in
Color.clearInteractable
.gesture(tapGesture)
.simultaneousGesture(doubleTapGesture)
.simultaneousGesture(dragGesture(for: geo))
.simultaneousGesture(longPressGesture)
.simultaneousGesture(longPressDragGesture(for: geo))
})
}
}
// MARK: - Gestures
private extension KeyboardGestures {
/**
This is a plain double-tap gesure.
*/
var doubleTapGesture: some Gesture {
TapGesture(count: 2).onEnded {
doubleTapAction?()
triggerPressedHighlight()
}
}
/**
This is a drag gesture that starts immediately.
*/
func dragGesture(for geo: GeometryProxy) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { _ in
if isDragGestureTriggered { return }
isDragGestureTriggered = true
pressAction?()
isPressed.wrappedValue = true
guard isInputCalloutEnabled else { return }
inputCalloutContext.updateInput(for: action, geo: geo) }
.onEnded { _ in
releaseAction?()
isDragGestureTriggered = false
isPressed.wrappedValue = false
inputCalloutContext.reset()
stopRepeatTimer() }
}
/**
This is a plain long press gesure.
*/
var longPressGesture: some Gesture {
LongPressGesture().onEnded { _ in
longPressAction?()
startRepeatTimer()
}
}
/**
This is a drag gesture that starts after a long press.
*/
func longPressDragGesture(for geo: GeometryProxy) -> some Gesture {
LongPressGesture()
.onEnded { _ in beginSecondaryInputGesture(for: geo) }
.sequenced(before: DragGesture(minimumDistance: 0))
.onChanged {
switch $0 {
case .first: break
case .second(_, let drag): handleSecondaryInputDragGesture(drag)
}
}
.onEnded { _ in endSecondaryInputGesture() }
}
/**
This is a plain tap gesure.
*/
var tapGesture: some Gesture {
TapGesture().onEnded {
tapAction?()
triggerPressedHighlight()
inputCalloutContext.reset()
}
}
}
// MARK: - Functions
private extension KeyboardGestures {
var shouldTapAfterSecondaryInputGesture: Bool {
dragAction == nil && longPressAction == nil && repeatAction == nil && !secondaryInputCalloutContext.isActive
}
func beginSecondaryInputGesture(for geo: GeometryProxy) {
isInputCalloutEnabled = false
secondaryInputCalloutContext.updateInputs(for: action, geo: geo)
guard secondaryInputCalloutContext.isActive else { return }
inputCalloutContext.reset()
}
func endSecondaryInputGesture() {
isInputCalloutEnabled = true
if shouldTapAfterSecondaryInputGesture { tapAction?() }
secondaryInputCalloutContext.endDragGesture()
guard secondaryInputCalloutContext.isActive else { return }
}
func handleSecondaryInputDragGesture(_ drag: DragGesture.Value?) {
secondaryInputCalloutContext.updateSelection(with: drag)
guard let drag = drag else { return }
dragAction?(drag.startLocation, drag.location)
}
func startRepeatTimer() {
guard let action = repeatAction else { return }
repeatTimer.start(action: action)
}
func stopRepeatTimer() {
repeatTimer.stop()
}
func triggerPressedHighlight() {
if isInputCalloutEnabled { return }
isPressed.wrappedValue = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
isPressed.wrappedValue = false
}
}
}
|
bb3364b3983643b532dcd6f41ffdcbce
| 30.947917 | 116 | 0.634985 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/Components/LinkView/LinkView.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxRelay
import RxSwift
/// A view model for `LinkView` that can display a link embedded in text,
/// levaraging `InteractableTextView` to do so.
public final class LinkView: UIView {
// MARK: - Properties
public var viewModel: LinkViewModel! {
didSet {
disposeBag = DisposeBag()
guard let viewModel = viewModel else {
return
}
textView.viewModel = viewModel.textViewModel
viewModel.textDidChange
.observe(on: MainScheduler.instance)
.bindAndCatch(weak: textView) { _ in
self.textDidChange()
}
.disposed(by: disposeBag)
}
}
private let textView = InteractableTextView()
private var disposeBag = DisposeBag()
// MARK: - Setup
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
addSubview(textView)
textView.fillSuperview()
}
private func textDidChange() {
textView.setupHeight()
}
}
|
976ec7f558e58334328a109c1bb90fe9
| 23.245283 | 73 | 0.583658 | false | false | false | false |
ephread/Instructions
|
refs/heads/main
|
Examples/Example/Sources/Core/View Controllers/Delegate Examples/KeyboardViewController.swift
|
mit
|
1
|
// Copyright (c) 2017-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
import Instructions
/// This class serves as a base for all the other examples
internal class KeyboardViewController: UIViewController {
// MARK: - IBOutlet
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var textField: UITextField!
// MARK: - Public properties
var coachMarksController = CoachMarksController()
let avatarText = "That's your profile picture. You look gorgeous!"
let inputText = "Please enter your name here"
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
coachMarksController.overlay.isUserInteractionEnabled = false
coachMarksController.dataSource = self
coachMarksController.delegate = self
textField.delegate = self
textField.returnKeyType = UIReturnKeyType.done
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow),
name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide),
name: UIResponder.keyboardDidHideNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startInstructions()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.coachMarksController.stop(immediately: true)
}
func startInstructions() {
self.coachMarksController.start(in: .window(over: self))
}
@objc func keyboardWillShow() {
}
@objc func keyboardWillHide() {
}
@objc func keyboardDidShow() {
coachMarksController.flow.resume()
}
@objc func keyboardDidHide() {
}
}
// MARK: - Protocol Conformance | CoachMarksControllerDataSource
extension KeyboardViewController: CoachMarksControllerDataSource {
func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int {
return 2
}
func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkAt index: Int) -> CoachMark {
switch index {
case 0:
return coachMarksController.helper.makeCoachMark(for: self.avatar)
case 1:
return coachMarksController.helper.makeCoachMark(for: self.textField)
default:
return coachMarksController.helper.makeCoachMark()
}
}
func coachMarksController(
_ coachMarksController: CoachMarksController,
coachMarkViewsAt index: Int,
madeFrom coachMark: CoachMark
) -> (bodyView: (UIView & CoachMarkBodyView), arrowView: (UIView & CoachMarkArrowView)?) {
var coachViews: (bodyView: CoachMarkBodyDefaultView, arrowView: CoachMarkArrowDefaultView?)
switch index {
case 1:
coachViews = coachMarksController.helper
.makeDefaultCoachViews(withArrow: true,
withNextText: false,
arrowOrientation: .bottom)
coachViews.bodyView.hintLabel.text = self.inputText
coachViews.bodyView.isUserInteractionEnabled = false
default:
let orientation = coachMark.arrowOrientation
coachViews = coachMarksController.helper
.makeDefaultCoachViews(withArrow: true,
withNextText: false,
arrowOrientation: orientation)
coachViews.bodyView.hintLabel.text = self.avatarText
}
return (bodyView: coachViews.bodyView, arrowView: coachViews.arrowView)
}
}
// MARK: - Protocol Conformance | CoachMarksControllerDelegate
extension KeyboardViewController: CoachMarksControllerDelegate {
func coachMarksController(_ coachMarksController: CoachMarksController,
willShow coachMark: inout CoachMark,
beforeChanging change: ConfigurationChange,
at index: Int) {
if index == 1 {
coachMark.arrowOrientation = .bottom
if change == .nothing {
textField.becomeFirstResponder()
coachMarksController.flow.pause()
}
}
}
func coachMarksController(_ coachMarksController: CoachMarksController,
didEndShowingBySkipping skipped: Bool) {
textField.resignFirstResponder()
}
}
// MARK: - Protocol Conformance | UITextFieldDelegate
extension KeyboardViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
coachMarksController.flow.showNext()
return true
}
}
|
7a6afe851080de666ab6cd1eb88c09b9
| 36.172185 | 114 | 0.625512 | false | false | false | false |
nderkach/FlightKit
|
refs/heads/master
|
Pod/Classes/FlightKit.swift
|
mit
|
1
|
import KeychainAccess
import Alamofire
import SwiftyJSON
//import RZVibrantButton
import SCLAlertView
struct FlightColors {
static var tomatoRed = UIColor(red: 172/255.0, green: 57/255.0, blue: 49/255.0, alpha: 1.0) // #AC3931
static var darkBlue = UIColor(red: 36/255.0, green: 30/255.0, blue: 78/255.0, alpha: 1.0) // #241E4E
static var coolYellow = UIColor(red: 214/255.0, green: 216/255.0, blue: 79/255.0, alpha: 1.0) // #D6D84F
static var lightBlue = UIColor(red: 111/255.0, green: 138/255.0, blue: 183/255.0, alpha: 1.0) // #6F8AB7
static var presqueWhite = UIColor(red: 251/255.0, green: 251/255.0, blue: 255/255.0, alpha: 1.0) // #FBFBFF
}
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
UIView.transitionWithView(self, duration: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
self.image = UIImage(data: data!)
}, completion: nil)
}
}
}
}
public class FlightKit {
class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiateWithOwner(nil, options: nil)[0] as? UIView
}
class func bundle() -> NSBundle? {
let bundle = NSBundle(forClass: self)
let path = bundle.pathForResource("FlightKit", ofType: "bundle") as String!
let fBundle = NSBundle(path: path)
return fBundle;
}
public class func storyboard() -> UIStoryboard? {
return UIStoryboard(name: "FlightKit", bundle: bundle())
}
public class func initView(from: String, to: String, label: String?, sview:UIView) {
let view:FlightView = loadFromNibNamed("FromView", bundle:bundle()) as! FlightView;
view.backgroundImage.image = UIImage(named: "weird_plane", inBundle: bundle(), compatibleWithTraitCollection: nil)
view.setImageForAirport(to);
view.requestMinPrice(from, destination: to, fromDate: NSDate(), toDate: NSDate().dateByAddingTimeInterval(30*86400))
if let l = label {
view.destinationLabel.text = l
} else {
view.destinationLabel.text = "Fly to \(to)"
}
view.frame = CGRectMake(0.0, 0.0, sview.bounds.width, sview.bounds.height)
sview.addSubview(view);
}
}
public class FlightView: UIView {
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var destinationLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var effectsView: UIVisualEffectView!
@IBOutlet weak var button: UIButton!
var oauthToken: String!
let keychain = Keychain(service: "io.booq").synchronizable(true)
@IBAction func buttonPushed(sender: UIButton) {
let alertView = SCLAlertView()
let txt = alertView.addTextField("Enter your email")
alertView.addButton("Let me know") {
print("let me know: \(txt.text!)")
SCLAlertView().showSuccess(
"Cool, we'll let you know",
subTitle: "We'll monitor price changes for this flight and let you know when is the best time to buy your ticket.",
closeButtonTitle: "Got it",
duration: 5.0)
}
alertView.addButton("Book now") {
print("book now")
}
alertView.showCloseButton = false
alertView.showTitle(
"Almost there...", // Title of view
subTitle: "Book now or wait till the price changes?",
duration: 0.0,
completeText: "",
style: .Wait,
colorStyle: 0xAC3931,
colorTextButton: 0xFFFFFF
)
}
func requestSabreToken(completion: () -> Void) -> Void {
let headers = [
"Authorization": "Basic VmpFNk1uWjFOMmsyY1dsbGFXcGlNbW8yY1RwRVJWWkRSVTVVUlZJNlJWaFU6VXpWa05HaE5lVlk9",
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = ["grant_type": "client_credentials"]
Alamofire.request(.POST, "https://api.test.sabre.com/v2/auth/token", headers: headers, parameters:parameters)
.responseJSON { (_, _, data) in
if (data.isFailure) {
if let error = data.value {
print(JSON(error)["error_description"])
}
completion()
} else {
let json = JSON(data.value!)
self.oauthToken = json["access_token"].string
completion()
print(self.oauthToken)
let expTime = json["expires_in"].double
let expDate: NSDate = NSDate().dateByAddingTimeInterval(expTime!)
print(expDate)
let data = NSKeyedArchiver.archivedDataWithRootObject(["value": self.oauthToken, "expirationDate": expDate])
self.keychain[data: "token"] = data
}
}
}
func obtainSabreToken(completion: () -> Void) -> Void {
let token = keychain[data: "token"] as NSData?
if token == nil {
requestSabreToken() {
completion()
}
} else {
let dtoken = NSKeyedUnarchiver.unarchiveObjectWithData(token!) as! Dictionary<String, AnyObject>
let date = dtoken["expirationDate"] as! NSDate
if NSDate().compare(date) == .OrderedDescending {
requestSabreToken() {
completion()
}
} else {
oauthToken = dtoken["value"] as! String
completion()
}
}
}
public func requestMinPrice(origin: String, destination: String, fromDate: NSDate, toDate: NSDate) {
obtainSabreToken {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let fromDateString = formatter.stringFromDate(fromDate)
let toDateString = formatter.stringFromDate(toDate)
let url = "https://api.test.sabre.com/v1.8.1/shop/calendar/flights"
var json: JSON?
if let path = FlightKit.bundle()!.pathForResource("post_calendar", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
json!["OTA_AirLowFareSearchRQ"]["OriginDestinationInformation"][0]["DepartureDates"]["dayOrDaysRange"][0]["DaysRange"]["FromDate"].stringValue = fromDateString
json!["OTA_AirLowFareSearchRQ"]["OriginDestinationInformation"][0]["DepartureDates"]["dayOrDaysRange"][0]["DaysRange"]["ToDate"].stringValue = toDateString
json!["OTA_AirLowFareSearchRQ"]["OriginDestinationInformation"][0]["OriginLocation"]["LocationCode"].stringValue = origin
json!["OTA_AirLowFareSearchRQ"]["OriginDestinationInformation"][0]["DestinationLocation"]["LocationCode"].stringValue = destination
json!["OTA_AirLowFareSearchRQ"]["OriginDestinationInformation"][1]["OriginLocation"]["LocationCode"].stringValue = destination
json!["OTA_AirLowFareSearchRQ"]["OriginDestinationInformation"][1]["DestinationLocation"]["LocationCode"].stringValue = origin
}
}
let headers = [
"Authorization": "Bearer " + self.oauthToken,
"Content-Type": "application/json"
]
let parameters = json!.object as! [String: AnyObject]
print("jsonData:\(json!)")
Alamofire.request(.POST, url, headers: headers, parameters:parameters, encoding: .JSON)
.responseJSON { (_, _, json) in
let price = JSON(json.value!)["OTA_AirLowFareSearchRS"]["PricedItineraries"]["PricedItinerary"][0]["AirItineraryPricingInfo"][0]["ItinTotalFare"]["TotalFare"]["Amount"].int
print(price)
if let p = price {
self.priceLabel.text = "Starting at $\(p)"
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.priceLabel.alpha = 1.0
}, completion: nil)
}
}
}
}
func commonInit() {
obtainSabreToken(){}
}
public override func awakeFromNib() {
self.priceLabel.alpha = 0.0
// var invertButton:RZVibrantButton = RZVibrantButton(frame:CGRectZero, style:RZVibrantButtonStyle.Invert)
// invertButton.vibrancyEffect = UIVibrancyEffect(forBlurEffect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
// invertButton.text = "Invert"
// self.effectsView.addSubview(invertButton)
commonInit()
}
public func setImageForAirport(airport: String) {
backgroundImage.imageFromUrl("https://media.expedia.com/mobiata/mobile/apps/ExpediaBooking/FlightDestinations/images/\(airport).jpg")
}
}
|
4d2d5e1256d3919aff665af098dcda28
| 42.611607 | 192 | 0.579853 | false | false | false | false |
naokits/NKMessngr
|
refs/heads/dev
|
NKMessngr/MasterViewController.swift
|
mit
|
1
|
//
// MasterViewController.swift
// NKMessngr
//
// Created by naokits on 7/12/15.
// Copyright (c) 2015 Naoki Tsutsui. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class MasterViewController: UITableViewController {
var objects = [AnyObject]()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let token = FBSDKAccessToken.currentAccessToken() {
println("トークン: \(token)")
} else {
println("トークンが取得できませんでした。")
self.performSegueWithIdentifier("toLogin", sender: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as! NSDate
(segue.destinationViewController as! DetailViewController).detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
|
e402dde65aa4f43426ba743502869e48
| 32.306122 | 157 | 0.673713 | false | false | false | false |
loiwu/SCoreData
|
refs/heads/master
|
Loi_Bow Ties/Loi_Bow Ties/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Loi_Bow Ties
//
// Created by loi on 1/16/15.
// Copyright (c) 2015 GWrabbit. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var timesWornLabel: UILabel!
@IBOutlet weak var lastWornLabel: UILabel!
@IBOutlet weak var favoriteLabel: UILabel!
var managedContext: NSManagedObjectContext!
var currentBowtie: Bowtie!
override func viewDidLoad() {
super.viewDidLoad()
insertSampleData()
let request = NSFetchRequest(entityName:"Bowtie")
let firstTitle = segmentedControl.titleForSegmentAtIndex(0)
request.predicate =
NSPredicate(format:"searchKey == %@", firstTitle!)
var error: NSError? = nil
var results =
managedContext.executeFetchRequest(request,
error: &error) as [Bowtie]?
if let bowties = results {
currentBowtie = bowties[0]
populate(currentBowtie)
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
@IBAction func segmentedControl(control: UISegmentedControl) {
let selectedValue =
control.titleForSegmentAtIndex(control.selectedSegmentIndex)
let fetchRequest = NSFetchRequest(entityName:"Bowtie")
fetchRequest.predicate =
NSPredicate(format:"searchKey == %@", selectedValue!)
var error: NSError?
let results =
managedContext.executeFetchRequest(fetchRequest,
error: &error) as [Bowtie]?
if let bowties = results {
currentBowtie = bowties.last!
populate(currentBowtie)
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
@IBAction func wear(sender: AnyObject) {
let times = currentBowtie.timesWorn.integerValue
currentBowtie.timesWorn = NSNumber(integer: (times + 1))
currentBowtie.lastWorn = NSDate()
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error!.userInfo)")
}
populate(currentBowtie)
}
@IBAction func rate(sender: AnyObject) {
let alert = UIAlertController(title: "New Rating",
message: "Rate this bow tie",
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default,
handler: { (action: UIAlertAction!) in
})
let saveAction = UIAlertAction(title: "Save",
style: .Default,
handler: { (action: UIAlertAction!) in
let textField = alert.textFields![0] as UITextField
self.updateRating(textField.text)
})
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField!) in
}
alert.addAction(cancelAction)
alert.addAction(saveAction)
self.presentViewController(alert,
animated: true,
completion: nil)
}
func populate(bowtie: Bowtie) {
imageView.image = UIImage(data:bowtie.photoData)
nameLabel.text = bowtie.name
ratingLabel.text = "Rating: \(bowtie.rating.doubleValue)/5"
timesWornLabel.text =
"# times worn: \(bowtie.timesWorn.integerValue)"
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
lastWornLabel.text = "Last worn: " +
dateFormatter.stringFromDate(bowtie.lastWorn)
favoriteLabel.hidden = !bowtie.isFavorite.boolValue
view.tintColor = bowtie.tintColor as UIColor
}
func updateRating(numString: String) {
currentBowtie!.rating = (numString as NSString).doubleValue
var error: NSError?
if !self.managedContext.save(&error) {
if error!.code == NSValidationNumberTooLargeError ||
error!.code == NSValidationNumberTooSmallError {
rate(currentBowtie)
}
} else {
populate(currentBowtie)
}
}
func insertSampleData() {
let fetchRequest = NSFetchRequest(entityName:"Bowtie")
fetchRequest.predicate = NSPredicate(
format: "searchKey != nil")
let count = managedContext.countForFetchRequest(fetchRequest,
error: nil);
if count > 0 { return }
let path = NSBundle.mainBundle().pathForResource("SampleData",
ofType: "plist")
let dataArray = NSArray(contentsOfFile: path!)!
for dict : AnyObject in dataArray {
let entity = NSEntityDescription.entityForName("Bowtie",
inManagedObjectContext: managedContext)
let bowtie = Bowtie(entity: entity!,
insertIntoManagedObjectContext: managedContext)
let btDict = dict as NSDictionary
bowtie.name = btDict["name"] as NSString
bowtie.searchKey = btDict["searchKey"] as NSString
bowtie.rating = btDict["rating"] as NSNumber
let tintColorDict = btDict["tintColor"] as NSDictionary
bowtie.tintColor = colorFromDict(tintColorDict)
let imageName = btDict["imageName"] as NSString
let image = UIImage(named:imageName)
let photoData = UIImagePNGRepresentation(image)
bowtie.photoData = photoData
bowtie.lastWorn = btDict["lastWorn"] as NSDate
bowtie.timesWorn = btDict["timesWorn"] as NSNumber
bowtie.isFavorite = btDict["isFavorite"] as NSNumber
}
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error!.userInfo)")
}
}
func colorFromDict(dict: NSDictionary) -> UIColor {
let red = dict["red"] as NSNumber
let green = dict["green"] as NSNumber
let blue = dict["blue"] as NSNumber
let color = UIColor(red: CGFloat(red)/255.0,
green: CGFloat(green)/255.0,
blue: CGFloat(blue)/255.0,
alpha: 1)
return color;
}
}
|
019433c072f5a9243a2e65b237595509
| 30.490909 | 70 | 0.567119 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/DriverSupport/Frontend.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 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 SwiftDriver
import protocol TSCBasic.FileSystem
public struct DriverSupport {
public static func checkSupportedFrontendFlags(flags: Set<String>, fileSystem: FileSystem) -> Bool {
do {
let executor = try SPMSwiftDriverExecutor(resolver: ArgsResolver(fileSystem: fileSystem), fileSystem: fileSystem, env: [:])
let driver = try Driver(args: ["swiftc"], executor: executor)
return driver.supportedFrontendFlags.intersection(flags) == flags
} catch {
return false
}
}
}
|
cbd6854fa6ec226d722b52d0c130386c
| 38.296296 | 135 | 0.592837 | false | false | false | false |
coodly/TalkToCloud
|
refs/heads/main
|
Sources/TalkToCloud/CURLRequest.swift
|
apache-2.0
|
1
|
/*
* Copyright 2020 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
internal class CURLRequest {
private lazy var identifier = UUID().uuidString
private lazy var directory = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
private lazy var sent = self.directory.appendingPathComponent("\(self.identifier)-sent")
private lazy var received = self.directory.appendingPathComponent("\(self.identifier)-received")
private lazy var headers = self.directory.appendingPathComponent("\(self.identifier)-headers")
private let request: URLRequest
private let autoClean: Bool
public init(request: URLRequest, autoClean: Bool = true) {
self.request = request
self.autoClean = autoClean
}
deinit {
guard autoClean else {
return
}
FileManager.default.remove([sent, received, headers])
}
internal func execute(completion: (Data?, URLResponse?, Error?) -> ()) {
var arguments = [String]()
arguments.append("--location")
arguments.append("--dump-header")
arguments.append(headers.path)
request.allHTTPHeaderFields?.forEach() {
key, value in
if key.lowercased() == "user-agent" {
arguments.append("-A")
arguments.append("\"\(value)\"")
} else {
arguments.append("-H")
arguments.append("\(key): \(value)")
}
}
if let body = request.httpBody {
try! body.write(to: sent)
arguments.append("--data-binary")
arguments.append("@\(sent.path)")
}
arguments.append("--output")
arguments.append(received.path)
arguments.append(request.url!.absoluteString)
Logging.verbose("curl \(arguments.joined(separator: " "))")
let result = Shell.shared.curl.launch(arguments)
assert(result.status == 0)
let data = try? Data(contentsOf: received)
let response = self.response()
completion(data, response, nil)
}
private func response() -> URLResponse? {
guard let data = try? Data(contentsOf: headers), let string = String(data: data, encoding: .utf8) else {
return nil
}
let lines = string.components(separatedBy: "\n")
guard let statusLine = lines.first, let status = statusLine.httpStatusCode else {
return nil
}
let headerFields = headers(from: Array(lines.dropFirst()))
return HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: headerFields)
}
private func headers(from lines: [String]) -> [String: String] {
var result = [String: String]()
for line in lines {
guard let index = line.firstIndex(of: ":") else {
continue
}
let name = String(line.prefix(upTo: index))
let value = line.suffix(from: index).trimmingCharacters(in: .whitespacesAndNewlines)
result[name] = value
}
return result
}
}
extension String {
fileprivate var httpStatusCode: Int? {
components(separatedBy: " ").compactMap({ Int($0) }).first
}
}
|
b97a3aea27a92aefc43566151e76e3ae
| 33.973451 | 115 | 0.614119 | false | false | false | false |
LbfAiYxx/douyuTV
|
refs/heads/master
|
DouYu/DouYu/Classes/Main/controller/AnimationViewController.swift
|
mit
|
1
|
//
// AnimationViewController.swift
// DouYu
//
// Created by 刘冰峰 on 2017/1/16.
// Copyright © 2017年 LBF. All rights reserved.
//
import UIKit
class AnimationViewController: UIViewController {
var contentView: UIView?
lazy var animationView: UIImageView = { [unowned self] in
let animationView = UIImageView(image: UIImage.init(named: "img_loading_1"))
animationView.center = self.view.center
animationView.animationImages = [UIImage.init(named: "img_loading_1")!,UIImage.init(named: "img_loading_2")!]
animationView.animationDuration = 0.5
animationView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin]
return animationView
}()
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
}
}
extension AnimationViewController{
func setUpView() {
contentView?.isHidden = true
view.addSubview(animationView)
animationView.startAnimating()
}
func finishLoadData(){
animationView.stopAnimating()
animationView.isHidden = true
contentView?.isHidden = false
}
}
|
1b24fcd4be36aab5df65293b667f6241
| 22.745098 | 117 | 0.628406 | false | false | false | false |
jfosterdavis/Charles
|
refs/heads/develop
|
Charles/Perks.swift
|
apache-2.0
|
1
|
//
// Perks.swift
// Charles
//
// Created by Jacob Foster Davis on 5/29/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
/******************************************************/
/*******************///MARK: Defines and holds all perks in the game
/******************************************************/
struct Perks {
/******************************************************/
/*******************///MARK: Patterns and trends
//Roberte can unlock almost every perk, except for the highest level perks, of those s/he imitates. This makes Roberte very handy.
//John is the only one who can unlock Emeritus. He can also unlock highest level of insight. This makes John possibly the only one who can allow player to win the game.
//Laura and John only can unlock Synesthesia
//Charles and Fred are same price and level, need both (unless Roberte) to unlock all Stacks perks
//Stanly and Jr. are required to get most out of Insight (unless Roberte)
//Matthew and Charles are only that can get In the Ballpark
//
//Synesthesia designed to be low cost and last long enough to not annoy the user. This is really for users that hate the annoying voices! Higher levels give much longer duration.
//Insight allows player to see the stickView which shows colors in a physical form. Colorblind users may like this. Designed to be not to expensive and easy to obtain. higher levels get up to 1 week
//Study increases XP gained from each successful match. Expensive and slow to obtain. They stack additively, so a user that has all unlocked could get +6 (=7) xp each time they succeed. Highest level very expensive and hard to obtain. Highest level only unlockable at high character level because it requires John
//Stacks gives multiplicative bonuses to score, which stack. Player could get up to 12X score each time. Short duration. Lowe levels easy to obtain, higher levels not as easy.
//Closeenough reduces the precision requirements to progress in a level. Higher levels require so much precision they will be near impossible without this perk. lower levels easy to obtain and have a mild duration. Higher levels very expensive and short duration.
/******************************************************/
static let ValidPerks:[Perk] = [
Stacks,
Synesthesia,
Study,
Insight,
Closeenough,
Adaptation,
Synesthesia2,
Adaptation2,
Insight2,
Closeenough2,
Stacks2,
Study2,
Stacks3,
Closeenough3,
Adaptation3,
Stacks4,
Insight3,
Study3,
Synesthesia3,
Adaptation4,
Stacks5,
Study4,
Closeenough4
]
static let UnlockablePerks:[Perk] = [
Stacks,
Synesthesia,
Study,
Insight,
Closeenough,
Adaptation,
Synesthesia2,
Adaptation2,
Insight2,
Closeenough2,
Stacks2,
Study2,
Stacks3,
Closeenough3,
Adaptation3,
Stacks4,
Insight3,
Study3,
Synesthesia3,
Adaptation4,
Stacks5,
Study4,
Closeenough4
]
/******************************************************/
/*******************///MARK: Synesthesia
/******************************************************/
static let Synesthesia = Perk( name: "Synėsthėsia",
gameDescription: "Whėn othėrs hėar words, you hėar music.",
type: .musicalVoices, //types are strings that the game will look for when determining how to behave
price: 750,
meta1: Bundle.main.path(forResource: "1c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
meta2: Bundle.main.path(forResource: "2c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
meta3: Bundle.main.path(forResource: "2c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
minutesUnlocked: 30, //30
icon: #imageLiteral(resourceName: "musicNote"),
displayColor: UIColor(red: 255/255.0, green: 182/255.0, blue: 249/255.0, alpha: 0.75),
levelEligibleAt: 6, //6
requiredPartyMembers: [Characters.Laura, Characters.R0berte]
)
static let Synesthesia2 = Perk( name: "Synėsthetic",
gameDescription: "You try your hardėst not to listėn, and you hėar only music.",
type: .musicalVoices, //types are strings that the game will look for when determining how to behave
price: 2500,
meta1: Bundle.main.path(forResource: "1c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
meta2: Bundle.main.path(forResource: "2c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
meta3: Bundle.main.path(forResource: "Finala", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
minutesUnlocked: 7200, //5 days, 7200
icon: #imageLiteral(resourceName: "musicNote"),
displayColor: UIColor(red: 255/255.0, green: 182/255.0, blue: 249/255.0, alpha: 0.75),
levelEligibleAt: 18,
requiredPartyMembers: [Characters.Laura, Characters.R0berte]
)
static let Synesthesia3 = Perk( name: "Synėsthetė",
gameDescription: "It sėėms likė you havė always only hėard music.",
type: .musicalVoices, //types are strings that the game will look for when determining how to behave
price: 25000,
meta1: Bundle.main.path(forResource: "1c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
meta2: Bundle.main.path(forResource: "2c", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
meta3: Bundle.main.path(forResource: "Finala", ofType: "m4a", inDirectory: "Audio/PerkSynesthesia"),
minutesUnlocked: 57600, //40 days, 57600
icon: #imageLiteral(resourceName: "musicNote"),
displayColor: UIColor(red: 255/255.0, green: 182/255.0, blue: 249/255.0, alpha: 0.75),
levelEligibleAt: 75, //75
requiredPartyMembers: [Characters.Laura, Characters.R0berte]
)
/******************************************************/
/*******************///MARK: Adaptation
/******************************************************/
//Adaptation stacks, except forks which takes the lowest fork for all active values
static let Adaptation = Perk( name: "Adjust",
gameDescription: "Allows your companions to modėstly adapt to the challėnge at hand.",
type: .adaptClothing, //types are strings that the game will look for when determining how to behave
price: 1000, //1000
meta1: 0.20, //portion of slots to adjust
meta2: 3, //number of forks for a good move
meta3: 0.40, //likelihood a good move option will prevail over a random
minutesUnlocked: 45, //45
icon: #imageLiteral(resourceName: "hex-key"),
displayColor: UIColor(red: 255/255.0, green: 126/255.0, blue: 55/255.0, alpha: 1), //orange
levelEligibleAt: 10, //10
requiredPartyMembers: []
)
static let Adaptation2 = Perk( name: "Compėnsatė",
gameDescription: "Another, morė potėnt, sourcė of adaptation.",
type: .adaptClothing, //types are strings that the game will look for when determining how to behave
price: 15000, //15000
meta1: 0.25, //portion of slots to adjust
meta2: 2, //number of forks for a good move
meta3: 0.50, //likelihood a good move option will prevail over a random
minutesUnlocked: 1445, //1 day and 5 minutes, 1445
icon: #imageLiteral(resourceName: "hex-key"),
displayColor: UIColor(red: 255/255.0, green: 126/255.0, blue: 55/255.0, alpha: 1), //orange
levelEligibleAt: 20, //20
requiredPartyMembers: []
)
//Adaptation 3 also considers the color of the player's initial progress color
static let Adaptation3 = Perk( name: "Adapt",
gameDescription: "Anothėr powėrful sourcė of adaptation.",
type: .adaptClothing, //types are strings that the game will look for when determining how to behave
price: 90000,//90000
meta1: 0.30, //portion of slots to adjust
meta2: 2, //number of forks for a good move
meta3: 0.75, //likelihood a good move option will prevail over a random
minutesUnlocked: 2880, //2 days, 2880
icon: #imageLiteral(resourceName: "hex-key"),
displayColor: UIColor(red: 255/255.0, green: 126/255.0, blue: 55/255.0, alpha: 1), //orange
levelEligibleAt: 56, //56
requiredPartyMembers: []
)
//Adaptation 4 also considers the color of the player's initial progress color - or rather, it resets the player's color to black.
static let Adaptation4 = Perk( name: "Evolvė",
gameDescription: "The most powėrful in the systėm of adaptation tools.",
type: .adaptClothing, //types are strings that the game will look for when determining how to behave
price: 300000, //300000
meta1: 0.35, //portion of slots to adjust
meta2: 1, //number of forks for a good move
meta3: 0.90, //likelihood a good move option will prevail over a random
minutesUnlocked: 20160, //14 days, 20160
icon: #imageLiteral(resourceName: "hex-key"),
displayColor: UIColor(red: 255/255.0, green: 126/255.0, blue: 55/255.0, alpha: 1), //orange
levelEligibleAt: 82, //82
requiredPartyMembers: []
)
/******************************************************/
/*******************///MARK: Insight
/******************************************************/
static let Insight = Perk( name: "Insight",
gameDescription: "You sėė things othėrs might not.",
type: .visualizeColorValues, //types are strings that the game will look for when determining how to behave
price: 5000, //5000
meta1: 1,
meta2: nil,
meta3: nil,
minutesUnlocked: 60, //60
icon: #imageLiteral(resourceName: "lightbulb"),
displayColor: UIColor(red: 0/255.0, green: 134/255.0, blue: 237/255.0, alpha: 1),
levelEligibleAt: 8, //8
requiredPartyMembers: []
)
static let Insight2 = Perk( name: "Pėrcėption",
gameDescription: "You sėė morė things othėrs might not, with the hėlp of a friėnd.",
type: .visualizeColorValues, //types are strings that the game will look for when determining how to behave
price: 25000, //25000
meta1: 2,
meta2: nil,
meta3: nil,
minutesUnlocked: 240, //4 hours
icon: #imageLiteral(resourceName: "lightbulb"),
displayColor: UIColor(red: 0/255.0, green: 134/255.0, blue: 237/255.0, alpha: 1),
levelEligibleAt: Characters.StanleyJr.levelEligibleAt,
requiredPartyMembers: [Characters.StanleyJr, Characters.R0berte]
)
static let Insight3 = Perk( name: "Epiphany",
gameDescription: "You sėė many things othėrs might not, with the hėlp of a friėnd.",
type: .visualizeColorValues, //types are strings that the game will look for when determining how to behave
price: 250000, //250,000
meta1: 3,
meta2: nil,
meta3: nil,
minutesUnlocked: 20160, //2 weeks 20160
icon: #imageLiteral(resourceName: "lightbulb"),
displayColor: UIColor(red: 0/255.0, green: 134/255.0, blue: 237/255.0, alpha: 1),
levelEligibleAt: 63,
requiredPartyMembers: [Characters.Stanley, Characters.John, Characters.R0berte]
)
/******************************************************/
/*******************///MARK: Study
/******************************************************/
static let Study = Perk( name: "Quick Study",
gameDescription: "You lėarn morė at ėach ėncountėr.",
type: .increasedXP, //types are strings that the game will look for when determining how to behave
price: 50000, //50000
meta1: 1,
meta2: nil,
meta3: nil,
minutesUnlocked: 30,
icon: #imageLiteral(resourceName: "pencil"),
displayColor: UIColor(red: 114/255.0, green: 42/255.0, blue: 183/255.0, alpha: 1),
levelEligibleAt: 7,
requiredPartyMembers: []
)
static let Study2 = Perk( name: "Study Buddy",
gameDescription: "Anothėr sourcė of advancėd lėarning, with the hėlp of a friėnd.",
type: .increasedXP, //types are strings that the game will look for when determining how to behave
price: 85000,
meta1: 1,
meta2: nil,
meta3: nil,
minutesUnlocked: 45,
icon: #imageLiteral(resourceName: "pencil"),
displayColor: UIColor(red: 114/255.0, green: 42/255.0, blue: 183/255.0, alpha: 1),
levelEligibleAt: 34, //34
requiredPartyMembers: [Characters.Fred, Characters.Dawson, Characters.R0berte]
)
static let Study3 = Perk( name: "Numbėr Crunch",
gameDescription: "Anothėr sourcė of lėarning, availablė with the hėlp of a mėchanical friėnd.",
type: .increasedXP, //types are strings that the game will look for when determining how to behave
price: 101010,
meta1: 1,
meta2: nil,
meta3: nil,
minutesUnlocked: 35,
icon: #imageLiteral(resourceName: "pencil"),
displayColor: UIColor(red: 114/255.0, green: 42/255.0, blue: 183/255.0, alpha: 1),
levelEligibleAt: Characters.R0berte.levelEligibleAt,
requiredPartyMembers: [Characters.R0berte]
)
static let Study4 = Perk( name: "Emėritus",
gameDescription: "The most potėnt of lėarning tools, availablė with the help of a lost friėnd (or a real tool).",
type: .increasedXP, //types are strings that the game will look for when determining how to behave
price: 2007000,
meta1: 3,
meta2: nil,
meta3: nil,
minutesUnlocked: 90,
icon: #imageLiteral(resourceName: "pencil"),
displayColor: UIColor(red: 114/255.0, green: 42/255.0, blue: 183/255.0, alpha: 1),
levelEligibleAt: Characters.John.levelEligibleAt! + 0,
requiredPartyMembers: [Characters.John, Characters.R0berte]
)
/******************************************************/
/*******************///MARK: Stacks
/******************************************************/
static let Stacks = Perk( name: "Innovatė",
gameDescription: "You find a way to walk away with morė from ėach ėncountėr.",
type: .increasedScore, //types are strings that the game will look for when determining how to behave
price: 10000, //10000
meta1: 2,
meta2: nil,
meta3: nil,
minutesUnlocked: 45, //45
icon: #imageLiteral(resourceName: "hex-DollarSign"),
displayColor: UIColor(red: 249/255.0, green: 219/255.0, blue: 0/255.0, alpha: 1),
levelEligibleAt: 5, //5
requiredPartyMembers: []
)
static let Stacks2 = Perk( name: "Crėatė",
gameDescription: "With hėlp, you crėatė an additional way to ėarn more.",
type: .increasedScore, //types are strings that the game will look for when determining how to behave
price: 30000,
meta1: 2,
meta2: nil,
meta3: nil,
minutesUnlocked: 55, //55
icon: #imageLiteral(resourceName: "hex-DollarSign"),
displayColor: UIColor(red: 249/255.0, green: 219/255.0, blue: 0/255.0, alpha: 1),
levelEligibleAt: 33, //33
requiredPartyMembers: [Characters.Charles, Characters.Laura, Characters.R0berte]
)
static let Stacks3 = Perk( name: "Producė",
gameDescription: "You producė an additional tool - ėarning much more with the hėlp of a friėnd.",
type: .increasedScore, //types are strings that the game will look for when determining how to behave
price: 85000,
meta1: 3,
meta2: nil,
meta3: nil,
minutesUnlocked: 600, //10 hours
icon: #imageLiteral(resourceName: "hex-DollarSign"),
displayColor: UIColor(red: 249/255.0, green: 219/255.0, blue: 0/255.0, alpha: 1),
levelEligibleAt: 48, //48
requiredPartyMembers: [Characters.Fred, Characters.Bessie, Characters.R0berte]
)
static let Stacks5 = Perk( name: "Cash Cow",
gameDescription: "Cash from the cow.",
type: .increasedScore, //types are strings that the game will look for when determining how to behave
price: 250000,
meta1: 4,
meta2: nil,
meta3: nil,
minutesUnlocked: 480, //8 hours
icon: #imageLiteral(resourceName: "hex-DollarSign"),
displayColor: UIColor(red: 249/255.0, green: 219/255.0, blue: 0/255.0, alpha: 1),
levelEligibleAt: 100, //100
requiredPartyMembers: [Characters.Bessie]
)
static let Stacks4 = Perk( name: "Invėnt",
gameDescription: "Your crėations culminatė and producė much, much morė.",
type: .increasedScore, //types are strings that the game will look for when determining how to behave
price: 220000,
meta1: 4,
meta2: nil,
meta3: nil,
minutesUnlocked: 7200, //5 Days, 7200
icon: #imageLiteral(resourceName: "hex-DollarSign"),
displayColor: UIColor(red: 249/255.0, green: 219/255.0, blue: 0/255.0, alpha: 1),
levelEligibleAt: 61,
requiredPartyMembers: []
)
/******************************************************/
/*******************///MARK: Closeenough
/******************************************************/
static let Closeenough = Perk( name: "Closė Enough",
gameDescription: "Your good mannėrs ėnablė you to squėak by whėrė othėrs would fail.",
type: .precisionAdjustment, //types are strings that the game will look for when determining how to behave
price: 10000,
meta1: -0.02,
meta2: nil,
meta3: nil,
minutesUnlocked: 4320, //3 days, 4320
icon: #imageLiteral(resourceName: "bullseye"),
displayColor: UIColor(red: 25/255.0, green: 25/255.0, blue: 25/255.0, alpha: 1),
levelEligibleAt: 9,
requiredPartyMembers: []
)
static let Closeenough2 = Perk( name: "Just About",
gameDescription: "Your rėputation allows you to gėt by whėrė othėrs would fail.",
type: .precisionAdjustment, //types are strings that the game will look for when determining how to behave
price: 50000,
meta1: -0.035,
meta2: nil,
meta3: nil,
minutesUnlocked: 300, //5 hours 300
icon: #imageLiteral(resourceName: "bullseye"),
displayColor: UIColor(red: 25/255.0, green: 25/255.0, blue: 25/255.0, alpha: 1),
levelEligibleAt: 30,
requiredPartyMembers: [Characters.Matthew, Characters.Stanley, Characters.Charles, Characters.Sparkle, Characters.R0berte]
)
static let Closeenough3 = Perk( name: "Ballpark",
gameDescription: "Pėople likė you. Whėn you arė almost thėrė, you arė.",
type: .precisionAdjustment, //types are strings that the game will look for when determining how to behave
price: 200000,
meta1: -0.05,
meta2: nil,
meta3: nil,
minutesUnlocked: 20,
icon: #imageLiteral(resourceName: "bullseye"),
displayColor: UIColor(red: 25/255.0, green: 25/255.0, blue: 25/255.0, alpha: 1),
levelEligibleAt: Characters.Matthew.levelEligibleAt, //Matthew
requiredPartyMembers: [Characters.Matthew, Characters.Sparkle, Characters.R0berte]
)
static let Closeenough4 = Perk( name: "Out of My Way",
gameDescription: "Some challenges can only be overcome with the right person.",
type: .precisionAdjustment, //types are strings that the game will look for when determining how to behave
price: 400000,
meta1: -0.10,
meta2: nil,
meta3: nil,
minutesUnlocked: 10,
icon: #imageLiteral(resourceName: "bullseye"),
displayColor: UIColor(red: 25/255.0, green: 25/255.0, blue: 25/255.0, alpha: 1),
levelEligibleAt: 130, //130 is love of life
requiredPartyMembers: [Characters.John]
)
/******************************************************/
/*******************///MARK: Investment
/******************************************************/
//early levels give valuable bonuses to characters base
//second highest level of this perk will bankrupt the player by making all characters bleed his score
//when perk expires a fullscreen modal shows a crash - player loses money
static let Investment = Perk( name: "Stock",
gameDescription: "You makė somė clėar and ėasy rėturns by making this invėstmėnt.",
type: .investment, //types are strings that the game will look for when determining how to behave
price: 0,
meta1: 300, //increase to base score for all characters
meta2: nil, //increase to closeenough
meta3: nil,
minutesUnlocked: 30, //short time requies player to keep asking for it
icon: #imageLiteral(resourceName: "hex-rubyBlur10"),
displayColor: UIColor(red: 0/255.0, green: 128/255.0, blue: 64/255.0, alpha: 1), //green. A snake or money?
levelEligibleAt: Characters.Francisco.levelEligibleAt,
requiredPartyMembers: [Characters.Francisco]
)
static let Investment2 = Perk( name: "Invėstmėnt",
gameDescription: "You makė somė vėry clėar and ėasy returns by making this invėstment.",
type: .investment, //types are strings that the game will look for when determining how to behave
price: 0,
meta1: 600, //increase to base score for all characters
meta2: nil, //increase to closeenough
meta3: nil,
minutesUnlocked: 45,
icon: #imageLiteral(resourceName: "hex-rubyBlur6"),
displayColor: UIColor(red: 0/255.0, green: 128/255.0, blue: 64/255.0, alpha: 1), //green. A snake or money?
levelEligibleAt: 1, //15
requiredPartyMembers: [Characters.Francisco]
)
static let Investment3 = Perk( name: "Portfolio",
gameDescription: "You makė somė clėar and ėasy returns in a lot of ways by making this investment.",
type: .investment, //types are strings that the game will look for when determining how to behave
price: 0,
meta1: 900, //increase to base score for all characters
meta2: -0.01, //increase to closeenough
meta3: nil,
minutesUnlocked: 15, //2 Days, 2880
icon: #imageLiteral(resourceName: "hex-rubyBlur4"),
displayColor: UIColor(red: 0/255.0, green: 128/255.0, blue: 64/255.0, alpha: 1), //green. A snake or money?
levelEligibleAt: 1, //18
requiredPartyMembers: [Characters.Francisco]
)
static let Investment4 = Perk( name: "Rėinvėstmėnt",
gameDescription: "You will dėfinatėly makė somė ėasy rėturns in a lot of ways by making this invėstment.",
type: .investment, //types are strings that the game will look for when determining how to behave
price: 0,
meta1: 1500, //increase to base score for all characters
meta2: -0.01, //increase to closeenough
meta3: nil,
minutesUnlocked: 15, //3 days 4320
icon: #imageLiteral(resourceName: "hex-rubyBlur2"),
displayColor: UIColor(red: 0/255.0, green: 128/255.0, blue: 64/255.0, alpha: 1), //green. A snake or money?
levelEligibleAt: 1, //22
requiredPartyMembers: [Characters.Francisco]
)
static let Investment5 = Perk( name: "Big Payoff",
gameDescription: "You have madė many surė-firė invėstmėnts bėforė this and havė no rėason to think this will bė any different.",
type: .investment, //types are strings that the game will look for when determining how to behave
price: 0,
meta1: 2400, //increase to base score for all characters
meta2: -0.02, //increase to closeenough
meta3: true, //when this perk expires, player will lose 80% of all money, all perks will expire (be locked), level will be reset to "looter" (level 22)
minutesUnlocked: 30, //7 Days, 10080. make player forget about it
icon: #imageLiteral(resourceName: "hex-ruby"),
displayColor: UIColor(red: 0/255.0, green: 128/255.0, blue: 64/255.0, alpha: 1), //green. A snake or money?
levelEligibleAt: 1, //24
requiredPartyMembers: [Characters.Francisco]
)
//TODO: figure this one out
static let FranciscoRedemption = Perk( name: "Rėdėmption",
gameDescription: "You havė madė many surė-firė invėstmėnts bėforė this and have no rėason to think this will bė any different.",
type: .investment, //types are strings that the game will look for when determining how to behave
price: 2500,
meta1: 700, //increase to base score for all characters
meta2: -0.02, //increase to closeenough
meta3: true, //when this perk expires, player will lose 50% of all money plus 5% for all other active (or being unlocked) investment perks, all perks will expire (be locked), level will be reset to "looter" (level 22)
minutesUnlocked: 10080, //7 Days, 10080. make player forget about it
icon: #imageLiteral(resourceName: "hex-ruby"),
displayColor: UIColor(red: 0/255.0, green: 128/255.0, blue: 64/255.0, alpha: 1), //green. A snake or money?
levelEligibleAt: Characters.John.levelEligibleAt,
requiredPartyMembers: [Characters.Francisco]
)
}
|
818bc765fece28a19030ba47adb5b7fe
| 57.113594 | 321 | 0.508412 | false | false | false | false |
moowahaha/Chuck
|
refs/heads/master
|
Chuck/Ball.swift
|
mit
|
1
|
//
// Ball.swift
// Chuck
//
// Created by Stephen Hardisty on 14/10/15.
// Copyright © 2015 Mr. Stephen. All rights reserved.
//
import UIKit
import SpriteKit
let Radius = CGFloat(70)
let InitialSpeedMultiplier = CGFloat(0.3)
class Ball: SKShapeNode {
private var speedMultiplier: CGFloat?
var isStopped: Bool = true
class func generate(location: CGPoint) -> Ball {
let ball = Ball(circleOfRadius: Radius)
ball.fillColor = SKColor.whiteColor()
ball.position = location
ball.speedMultiplier = InitialSpeedMultiplier
ball.physicsBody = SKPhysicsBody(circleOfRadius: Radius)
if let physics = ball.physicsBody {
physics.affectedByGravity = false
physics.friction = 0.005
physics.restitution = 0.99
physics.mass = 0.6
physics.allowsRotation = false
physics.linearDamping = 0.1
physics.angularDamping = 0.0
physics.dynamic = true
}
return ball
}
func die() {
self.physicsBody!.restitution = 0.5
self.physicsBody!.linearDamping = 0.5
self.physicsBody!.friction = 0.5
UIView.animateWithDuration(
0.4,
delay: 0.2,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
self.alpha = 0.4
},
completion: nil
)
}
func stop(location: CGPoint) {
self.physicsBody!.affectedByGravity = false
self.physicsBody!.velocity = CGVectorMake(0.0, 0.0)
self.moveTo(location)
self.isStopped = true
}
func moveTo(location: CGPoint) {
self.position = location
}
func roll(velocity: CGPoint) {
self.physicsBody!.affectedByGravity = true
self.isStopped = false
self.speedMultiplier = self.speedMultiplier! + (CGFloat(arc4random())/CGFloat(UInt32.max) / 50)
self.physicsBody!.applyImpulse(
CGVectorMake(
velocity.x * self.speedMultiplier!,
velocity.y * self.speedMultiplier! * -1.0
)
)
}
}
|
277ab069dc6be7502897b6d4475828a5
| 27.285714 | 103 | 0.58494 | false | false | false | false |
hollance/swift-algorithm-club
|
refs/heads/master
|
Z-Algorithm/ZetaAlgorithm.swift
|
mit
|
3
|
/* Z-Algorithm based algorithm for pattern/string matching
The code is based on the book:
"Algorithms on String, Trees and Sequences: Computer Science and Computational Biology"
by Dan Gusfield
Cambridge University Press, 1997
*/
import Foundation
extension String {
func indexesOf(pattern: String) -> [Int]? {
let patternLength = pattern.count
let zeta = ZetaAlgorithm(ptrn: pattern + "💲" + self)
guard zeta != nil else {
return nil
}
var indexes: [Int] = [Int]()
/* Scan the zeta array to find matched patterns */
for i in 0 ..< zeta!.count {
if zeta![i] == patternLength {
indexes.append(i - patternLength - 1)
}
}
guard !indexes.isEmpty else {
return nil
}
return indexes
}
}
|
235852a7ccd1aa59a6915cfde392c708
| 20.555556 | 88 | 0.637887 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Post/Scheduling/CalendarCollectionView.swift
|
gpl-2.0
|
1
|
import Foundation
import JTAppleCalendar
enum CalendarCollectionViewStyle {
case month
case year
}
class CalendarCollectionView: WPJTACMonthView {
let calDataSource: CalendarDataSource
let style: CalendarCollectionViewStyle
init(calendar: Calendar,
style: CalendarCollectionViewStyle = .month,
startDate: Date? = nil,
endDate: Date? = nil) {
calDataSource = CalendarDataSource(
calendar: calendar,
style: style,
startDate: startDate,
endDate: endDate
)
self.style = style
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
calDataSource = CalendarDataSource(calendar: Calendar.current, style: .month)
style = .month
super.init(coder: aDecoder)
setup()
}
private func setup() {
register(DateCell.self, forCellWithReuseIdentifier: DateCell.Constants.reuseIdentifier)
register(CalendarYearHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: CalendarYearHeaderView.reuseIdentifier)
backgroundColor = .clear
switch style {
case .month:
scrollDirection = .horizontal
scrollingMode = .stopAtEachCalendarFrame
case .year:
scrollDirection = .vertical
allowsMultipleSelection = true
allowsRangedSelection = true
rangeSelectionMode = .continuous
minimumLineSpacing = 0
minimumInteritemSpacing = 0
cellSize = 50
}
showsHorizontalScrollIndicator = false
isDirectionalLockEnabled = true
calendarDataSource = calDataSource
calendarDelegate = calDataSource
}
}
class CalendarDataSource: JTACMonthViewDataSource {
var willScroll: ((DateSegmentInfo) -> Void)?
var didScroll: ((DateSegmentInfo) -> Void)?
var didSelect: ((Date?, Date?) -> Void)?
// First selected date
var firstDate: Date?
// End selected date
var endDate: Date?
private let calendar: Calendar
private let style: CalendarCollectionViewStyle
init(calendar: Calendar,
style: CalendarCollectionViewStyle,
startDate: Date? = nil,
endDate: Date? = nil) {
self.calendar = calendar
self.style = style
self.firstDate = startDate
self.endDate = endDate
}
func configureCalendar(_ calendar: JTACMonthView) -> ConfigurationParameters {
/// When style is year, display the last 20 years til this month
if style == .year {
var dateComponent = DateComponents()
dateComponent.year = -20
let startDate = Calendar.current.date(byAdding: dateComponent, to: Date())
let endDate = Date().endOfMonth
if let startDate = startDate, let endDate = endDate {
return ConfigurationParameters(startDate: startDate, endDate: endDate, calendar: self.calendar)
}
}
let startDate = Date.farPastDate
let endDate = Date.farFutureDate
return ConfigurationParameters(startDate: startDate, endDate: endDate, calendar: self.calendar)
}
}
extension CalendarDataSource: JTACMonthViewDelegate {
func calendar(_ calendar: JTACMonthView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTACDayCell {
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: DateCell.Constants.reuseIdentifier, for: indexPath)
if let dateCell = cell as? DateCell {
configure(cell: dateCell, with: cellState)
}
return cell
}
func calendar(_ calendar: JTACMonthView, willDisplay cell: JTACDayCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
configure(cell: cell, with: cellState)
}
func calendar(_ calendar: JTACMonthView, willScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
willScroll?(visibleDates)
}
func calendar(_ calendar: JTACMonthView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
didScroll?(visibleDates)
}
func calendar(_ calendar: JTACMonthView, didSelectDate date: Date, cell: JTACDayCell?, cellState: CellState, indexPath: IndexPath) {
if style == .year {
// If the date is in the future, bail out
if date > Date() {
return
}
if let firstDate = firstDate {
if let endDate = endDate {
// When tapping a selected firstDate or endDate reset the rest
if date == firstDate || date == endDate {
self.firstDate = date
self.endDate = nil
// Increase the range at the left side
} else if date < firstDate {
self.firstDate = date
// Increase the range at the right side
} else {
self.endDate = date
}
// When tapping a single selected date, deselect everything
} else if date == firstDate {
self.firstDate = nil
self.endDate = nil
// When selecting a second date
} else {
self.firstDate = min(firstDate, date)
endDate = max(firstDate, date)
}
// When selecting the first date
} else {
firstDate = date
}
// Monthly calendar only selects a single date
} else {
firstDate = date
}
didSelect?(firstDate, endDate)
UIView.performWithoutAnimation {
calendar.reloadItems(at: calendar.indexPathsForVisibleItems)
}
configure(cell: cell, with: cellState)
}
func calendar(_ calendar: JTACMonthView, didDeselectDate date: Date, cell: JTACDayCell?, cellState: CellState, indexPath: IndexPath) {
configure(cell: cell, with: cellState)
}
func calendarSizeForMonths(_ calendar: JTACMonthView?) -> MonthSize? {
return style == .year ? MonthSize(defaultSize: 50) : nil
}
func calendar(_ calendar: JTACMonthView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTACMonthReusableView {
let date = range.start
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
let header = calendar.dequeueReusableJTAppleSupplementaryView(withReuseIdentifier: CalendarYearHeaderView.reuseIdentifier, for: indexPath)
(header as! CalendarYearHeaderView).titleLabel.text = formatter.string(from: date)
return header
}
private func configure(cell: JTACDayCell?, with state: CellState) {
let cell = cell as? DateCell
cell?.configure(with: state, startDate: firstDate, endDate: endDate, hideInOutDates: style == .year)
}
}
class DateCell: JTACDayCell {
struct Constants {
static let labelSize: CGFloat = 28
static let reuseIdentifier = "dateCell"
static var selectedColor: UIColor {
UIColor(light: .primary(.shade5), dark: .primary(.shade90))
}
}
let dateLabel = UILabel()
let leftPlaceholder = UIView()
let rightPlaceholder = UIView()
let dateFormatter = DateFormatter()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
dateLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.textAlignment = .center
dateLabel.font = UIFont.preferredFont(forTextStyle: .callout)
// Show circle behind text for selected day
dateLabel.clipsToBounds = true
dateLabel.layer.cornerRadius = Constants.labelSize/2
addSubview(dateLabel)
NSLayoutConstraint.activate([
dateLabel.widthAnchor.constraint(equalToConstant: Constants.labelSize),
dateLabel.heightAnchor.constraint(equalTo: dateLabel.widthAnchor),
dateLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
dateLabel.centerXAnchor.constraint(equalTo: centerXAnchor)
])
leftPlaceholder.translatesAutoresizingMaskIntoConstraints = false
rightPlaceholder.translatesAutoresizingMaskIntoConstraints = false
addSubview(leftPlaceholder)
addSubview(rightPlaceholder)
NSLayoutConstraint.activate([
leftPlaceholder.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.6),
leftPlaceholder.heightAnchor.constraint(equalTo: dateLabel.heightAnchor),
leftPlaceholder.trailingAnchor.constraint(equalTo: centerXAnchor),
leftPlaceholder.centerYAnchor.constraint(equalTo: centerYAnchor)
])
NSLayoutConstraint.activate([
rightPlaceholder.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.5),
rightPlaceholder.heightAnchor.constraint(equalTo: dateLabel.heightAnchor),
rightPlaceholder.leadingAnchor.constraint(equalTo: centerXAnchor, constant: 0),
rightPlaceholder.centerYAnchor.constraint(equalTo: centerYAnchor)
])
bringSubviewToFront(dateLabel)
}
}
extension DateCell {
/// Configure the DateCell
///
/// - Parameters:
/// - state: the representation of the cell state
/// - startDate: the first Date selected
/// - endDate: the last Date selected
/// - hideInOutDates: a Bool to hide/display dates outside of the current month (filling the entire row)
/// - Returns: UIColor. Red in cases of error
func configure(with state: CellState,
startDate: Date? = nil,
endDate: Date? = nil,
hideInOutDates: Bool = false) {
dateLabel.text = state.text
dateFormatter.setLocalizedDateFormatFromTemplate("MMM d, yyyy")
dateLabel.accessibilityLabel = dateFormatter.string(from: state.date)
dateLabel.accessibilityTraits = .button
var textColor: UIColor
if hideInOutDates && state.dateBelongsTo != .thisMonth {
isHidden = true
} else {
isHidden = false
}
// Reset state
leftPlaceholder.backgroundColor = .clear
rightPlaceholder.backgroundColor = .clear
dateLabel.backgroundColor = .clear
textColor = .text
switch position(for: state.date, startDate: startDate, endDate: endDate) {
case .middle:
textColor = .text
leftPlaceholder.backgroundColor = Constants.selectedColor
rightPlaceholder.backgroundColor = Constants.selectedColor
dateLabel.backgroundColor = .clear
case .left:
textColor = .white
dateLabel.backgroundColor = .primary
rightPlaceholder.backgroundColor = Constants.selectedColor
case .right:
textColor = .white
dateLabel.backgroundColor = .primary
leftPlaceholder.backgroundColor = Constants.selectedColor
case .full:
textColor = .textInverted
leftPlaceholder.backgroundColor = .clear
rightPlaceholder.backgroundColor = .clear
dateLabel.backgroundColor = .primary
case .none:
leftPlaceholder.backgroundColor = .clear
rightPlaceholder.backgroundColor = .clear
dateLabel.backgroundColor = .clear
if state.date > Date() {
textColor = .textSubtle
} else if state.dateBelongsTo == .thisMonth {
textColor = .text
} else {
textColor = .textSubtle
}
}
dateLabel.textColor = textColor
}
func position(for date: Date, startDate: Date?, endDate: Date?) -> SelectionRangePosition {
if let startDate = startDate, let endDate = endDate {
if date == startDate {
return .left
} else if date == endDate {
return .right
} else if date > startDate && date < endDate {
return .middle
}
} else if let startDate = startDate {
if date == startDate {
return .full
}
}
return .none
}
}
// MARK: - Year Header View
class CalendarYearHeaderView: JTACMonthReusableView {
static let reuseIdentifier = "CalendarYearHeaderView"
let titleLabel: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = Constants.stackViewSpacing
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
pinSubviewToSafeArea(stackView)
stackView.addArrangedSubview(titleLabel)
titleLabel.font = .preferredFont(forTextStyle: .headline)
titleLabel.textAlignment = .center
titleLabel.textColor = Constants.titleColor
let weekdaysView = WeekdaysHeaderView(calendar: Calendar.current)
stackView.addArrangedSubview(weekdaysView)
stackView.setCustomSpacing(Constants.spacingAfterWeekdays, after: weekdaysView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private enum Constants {
static let stackViewSpacing: CGFloat = 16
static let spacingAfterWeekdays: CGFloat = 8
static let titleColor = UIColor(light: .gray(.shade70), dark: .textSubtle)
}
}
extension Date {
var startOfMonth: Date? {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))
}
var endOfMonth: Date? {
guard let startOfMonth = startOfMonth else {
return nil
}
return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: startOfMonth)
}
}
class WPJTACMonthView: JTACMonthView {
// Avoids content to scroll above/below the maximum/minimum size
override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
let maxY = contentSize.height - frame.size.height
if contentOffset.y > maxY {
super.setContentOffset(CGPoint(x: contentOffset.x, y: maxY), animated: animated)
} else if contentOffset.y < 0 {
super.setContentOffset(CGPoint(x: contentOffset.x, y: 0), animated: animated)
} else {
super.setContentOffset(contentOffset, animated: animated)
}
}
}
|
2a97f87d61e3c40b52c792d5545afaee
| 34.06089 | 152 | 0.62915 | false | false | false | false |
ifabijanovic/swtor-holonet
|
refs/heads/master
|
ios/HoloNet/Module/App/UI/Base/BaseViewController.swift
|
gpl-3.0
|
1
|
//
// BaseViewController.swift
// SWTOR HoloNet
//
// Created by Ivan Fabijanovic on 15/07/15.
// Copyright (c) 2015 Ivan Fabijanović. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class BaseViewController: UIViewController, Themeable {
let toolbox: Toolbox
private(set) var theme: Theme?
private(set) var disposeBag: DisposeBag
init(toolbox: Toolbox, nibName: String?, bundle: Bundle?) {
self.toolbox = toolbox
self.disposeBag = DisposeBag()
super.init(nibName: nibName, bundle: bundle)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) { fatalError() }
// MARK: -
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.toolbox
.theme
.drive(onNext: self.apply(theme:))
.disposed(by: self.disposeBag)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.disposeBag = DisposeBag()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme?.statusBarStyle ?? .default
}
func apply(theme: Theme) {
guard self.theme != theme else { return }
self.theme = theme
self.setNeedsStatusBarAppearanceUpdate()
}
}
|
a99439533352b883b128079592854bf6
| 24.611111 | 63 | 0.626898 | false | false | false | false |
SusanDoggie/DoggieUI
|
refs/heads/main
|
Sources/DoggieUI/Views/SDNumberField.swift
|
mit
|
1
|
//
// SDNumberField.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS)
import UIKit
extension Decimal {
fileprivate func rounded(scale: Int = 0, roundingMode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
var x = self
var result = Decimal()
NSDecimalRound(&result, &x, scale, roundingMode)
return result
}
}
@IBDesignable open class SDNumberField: UIControl {
private let button = UIButton(type: .custom)
private weak var keyboard: SDNumberFieldKeyboard?
fileprivate var _text: String = "0" {
didSet {
button.setTitle(_text, for: .normal)
}
}
@IBInspectable open var value: CGFloat {
get {
return Decimal(string: _text).map { CGFloat(NSDecimalNumber(decimal: $0).doubleValue) } ?? 0
}
set {
_text = "\(Decimal(Double(newValue)).rounded(scale: decimalRoundingPlaces))"
}
}
@IBInspectable open var decimalRoundingPlaces: Int = 9
@IBInspectable open var isSigned: Bool = true
@IBInspectable open var isDecimal: Bool = true
@IBInspectable open var labelColor: UIColor? = DEFAULT_LABEL_COLOR {
didSet {
button.setTitleColor(labelColor, for: .normal)
}
}
@IBInspectable open var keyboardSize: CGSize = CGSize(width: 214, height: 346)
@IBInspectable open var keyboardBackgroundColor: UIColor? = DEFAULT_BACKGROUND_COLOR
@IBInspectable open var keyButtonBackgroundColor: UIColor? = DEFAULT_BACKGROUND_COLOR
@IBInspectable open var keyLabelColor: UIColor? = DEFAULT_LABEL_COLOR
@IBInspectable open var keyButtonSpacing: CGFloat = 8
@IBInspectable open var keyButtonCornerRadius: CGFloat = 0
@IBInspectable open var keyButtonBorderWidth: CGFloat = 0
@IBInspectable open var keyButtonBorderColor: UIColor?
#if os(iOS)
@IBInspectable open var enablePointerInteraction: Bool = false
var _pointerStyleProvider: Any?
@available(iOS 13.4, macCatalyst 13.4, *)
open var pointerStyleProvider: UIButton.PointerStyleProvider? {
get {
return _pointerStyleProvider as? UIButton.PointerStyleProvider
}
set {
_pointerStyleProvider = newValue
}
}
#endif
open var lineBreakMode: NSLineBreakMode {
get {
return button.titleLabel?.lineBreakMode ?? .byTruncatingTail
}
set {
button.titleLabel?.lineBreakMode = newValue
}
}
@IBInspectable open var adjustsFontSizeToFitWidth: Bool {
get {
return button.titleLabel?.adjustsFontSizeToFitWidth ?? false
}
set {
button.titleLabel?.adjustsFontSizeToFitWidth = newValue
}
}
@IBInspectable open var minimumScaleFactor: CGFloat {
get {
return button.titleLabel?.minimumScaleFactor ?? 0
}
set {
button.titleLabel?.minimumScaleFactor = newValue
}
}
@IBInspectable open var allowsDefaultTighteningForTruncation: Bool {
get {
return button.titleLabel?.allowsDefaultTighteningForTruncation ?? false
}
set {
button.titleLabel?.allowsDefaultTighteningForTruncation = newValue
}
}
open override var isEnabled: Bool {
get {
return button.isEnabled
}
set {
button.isEnabled = newValue
}
}
open override var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment {
get {
return button.contentHorizontalAlignment
}
set {
button.contentHorizontalAlignment = newValue
}
}
open override var contentVerticalAlignment: UIControl.ContentVerticalAlignment {
get {
return button.contentVerticalAlignment
}
set {
button.contentVerticalAlignment = newValue
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self._init()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self._init()
}
private func _init() {
self.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[button]|", options: [], metrics: nil, views: ["button": button]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[button]|", options: [], metrics: nil, views: ["button": button]))
button.setTitle(_text, for: .normal)
button.setTitleColor(labelColor, for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
@objc func buttonAction(_ sender: Any) {
let keyboard = SDNumberFieldKeyboard()
keyboard.delegate = self
keyboard.preferredContentSize = keyboardSize
keyboard.modalPresentationStyle = .popover
keyboard.popoverPresentationController?.sourceView = self
keyboard.popoverPresentationController?.sourceRect = self.bounds
keyboard.popoverPresentationController?.delegate = keyboard
keyboard.popoverPresentationController?.permittedArrowDirections = [.up, .down]
self.keyboard = keyboard
if var viewController = self.window?.rootViewController {
while true {
if let presentedViewController = viewController.presentedViewController {
viewController = presentedViewController
} else if let navigationController = viewController as? UINavigationController, let visibleViewController = navigationController.visibleViewController {
viewController = visibleViewController
} else if let tabBarController = viewController as? UITabBarController, let selectedViewController = tabBarController.selectedViewController {
viewController = selectedViewController
} else {
viewController.present(keyboard, animated: true, completion: nil)
self.sendActions(for: .editingDidBegin)
return
}
}
}
}
open func endEditing() {
self.keyboard?._endEditing()
self.keyboard?.dismiss(animated: true, completion: nil)
}
}
private class SDNumberFieldKeyboard: UIViewController, UIPopoverPresentationControllerDelegate {
weak var delegate: SDNumberField?
let label = UILabel()
var old_value: String?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = delegate?.keyboardBackgroundColor
label.text = delegate?._text
label.textAlignment = .right
label.adjustsFontSizeToFitWidth = true
let label_container = UIView()
label.textColor = delegate?.keyLabelColor
label_container.backgroundColor = delegate?.keyButtonBackgroundColor
label_container.cornerRadius = delegate?.keyButtonCornerRadius ?? 0
label_container.borderWidth = delegate?.keyButtonBorderWidth ?? 0
label_container.borderColor = delegate?.keyButtonBorderColor
label_container.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label]|", options: [], metrics: nil, views: ["label": label]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-|", options: [], metrics: nil, views: ["label": label]))
var buttons: [UIButton] = []
func _set_button(_ button: UIButton) {
button.backgroundColor = delegate?.keyButtonBackgroundColor
button.setTitleColor(delegate?.keyLabelColor, for: .normal)
button.cornerRadius = delegate?.keyButtonCornerRadius ?? 0
button.borderWidth = delegate?.keyButtonBorderWidth ?? 0
button.borderColor = delegate?.keyButtonBorderColor
if #available(iOS 13.4, macCatalyst 13.4, *) {
button.isPointerInteractionEnabled = delegate?.enablePointerInteraction ?? false
button.pointerStyleProvider = delegate?.pointerStyleProvider
}
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
for i in 0..<10 {
let button = UIButton(type: .custom)
button.tag = i
button.setTitle("\(i)", for: .normal)
_set_button(button)
buttons.append(button)
}
do {
let button = UIButton(type: .custom)
button.tag = 10
button.setTitle("⌫", for: .normal)
_set_button(button)
buttons.append(button)
}
var dot_button: UIButton?
if delegate?.isDecimal == true {
let button = UIButton(type: .custom)
button.tag = 11
button.setTitle(".", for: .normal)
_set_button(button)
buttons.append(button)
dot_button = button
}
var sign_button: UIButton?
if delegate?.isSigned == true {
let button = UIButton(type: .custom)
button.tag = 12
button.setTitle("⁺∕₋", for: .normal)
_set_button(button)
buttons.append(button)
sign_button = button
}
let h_stack_0 = UIStackView(arrangedSubviews: sign_button.map { [$0, label_container] } ?? [label_container])
let h_stack_1 = UIStackView(arrangedSubviews: [buttons[7], buttons[8], buttons[9]])
let h_stack_2 = UIStackView(arrangedSubviews: [buttons[4], buttons[5], buttons[6]])
let h_stack_3 = UIStackView(arrangedSubviews: [buttons[1], buttons[2], buttons[3]])
let h_stack_4 = UIStackView(arrangedSubviews: dot_button.map { [$0, buttons[0], buttons[10]] } ?? [buttons[0], buttons[10]])
h_stack_0.spacing = delegate?.keyButtonSpacing ?? 0
h_stack_1.spacing = delegate?.keyButtonSpacing ?? 0
h_stack_2.spacing = delegate?.keyButtonSpacing ?? 0
h_stack_3.spacing = delegate?.keyButtonSpacing ?? 0
h_stack_4.spacing = delegate?.keyButtonSpacing ?? 0
let stack = UIStackView(arrangedSubviews: [h_stack_0, h_stack_1, h_stack_2, h_stack_3, h_stack_4])
stack.spacing = delegate?.keyButtonSpacing ?? 0
stack.axis = .vertical
stack.distribution = .fillEqually
self.view.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stack.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: delegate?.keyButtonSpacing ?? 0),
stack.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: delegate?.keyButtonSpacing ?? 0),
self.view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: stack.trailingAnchor, constant: delegate?.keyButtonSpacing ?? 0),
self.view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: stack.bottomAnchor, constant: delegate?.keyButtonSpacing ?? 0),
])
NSLayoutConstraint.activate(buttons.dropFirst(2).map { NSLayoutConstraint(item: $0, attribute: .width, relatedBy: .equal, toItem: buttons[1], attribute: .width, multiplier: 1, constant: 0) })
}
override var canBecomeFirstResponder: Bool {
return true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.resignFirstResponder()
}
func _endEditing() {
guard let delegate = self.delegate else { return }
if delegate._text.isEmpty {
delegate._text = old_value ?? "0"
delegate.sendActions(for: .editingChanged)
} else if let decimal = Decimal(string: delegate._text), delegate._text != "\(decimal)" {
delegate._text = "\(decimal)"
delegate.sendActions(for: .editingChanged)
}
delegate.sendActions(for: .editingDidEnd)
}
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
for press in presses {
guard let key = press.key else { continue }
let inputs = key.charactersIgnoringModifiers
switch inputs {
case "\u{8}": self.inputCommandAction(inputs)
case "0"..."9": self.inputCommandAction(inputs)
case ".":
if delegate?.isDecimal == true {
self.inputCommandAction(inputs)
}
case "-":
if delegate?.isSigned == true {
self.inputCommandAction(inputs)
}
case "\r":
self._endEditing()
self.dismiss(animated: true, completion: nil)
default: break
}
}
}
@objc func buttonAction(_ sender: UIButton) {
switch sender.tag {
case 10: self.inputCommandAction("\u{8}")
case 11: self.inputCommandAction(".")
case 12: self.inputCommandAction("-")
default: self.inputCommandAction("\(sender.tag)")
}
}
func inputCommandAction(_ key: String) {
guard let delegate = self.delegate else { return }
if old_value == nil {
old_value = delegate._text
if key != "-" {
delegate._text = ""
}
}
switch key {
case "\u{8}":
if !delegate._text.isEmpty {
delegate._text.removeLast()
}
case ".":
if delegate._text.isEmpty {
delegate._text = "0."
} else if !delegate._text.contains(".") {
delegate._text += "."
}
case "-":
if delegate._text.first == "-" {
delegate._text.removeFirst()
} else {
delegate._text = "-" + delegate._text
}
case "0"..."9": delegate._text += key
default: break
}
label.text = delegate._text
delegate.sendActions(for: .editingChanged)
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
self._endEditing()
}
}
#endif
|
2caa73f74b6e2df8b8bf27398104791e
| 34.559322 | 199 | 0.596938 | false | false | false | false |
waywalker/HouseWarmer
|
refs/heads/master
|
HouseWarmer/NeviWebAPI.swift
|
unlicense
|
1
|
import Foundation
import Result
import Siesta
import SwiftyJSON
class NeviWebAPI {
static let shared = NeviWebAPI()
fileprivate let service = Service(baseURL: NeviWebConfig.apiURL)
fileprivate var sessionIDHeader: String? { didSet { resetConfiguration() } }
fileprivate init() {
#if DEBUG
LogCategory.enabled = [.network]
#endif
service.configure("**") {
$0.headers["Session-Id"] = self.sessionIDHeader
}
service.configure {
$0.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
}
service.configureTransformer("/gateway") {
try ($0.content as JSON)
.arrayValue
.map(Gateway.init)
}
service.configureTransformer("/device") {
try ($0.content as JSON)
.arrayValue
.map(Thermostat.init)
}
service.configureTransformer("/device/*/data") {
try DeviceData(json: $0.content)
}
}
}
// MARK: - Configuration
extension NeviWebAPI {
fileprivate func resetConfiguration() {
service.invalidateConfiguration()
service.wipeResources()
}
}
// MARK: - Resources
extension NeviWebAPI {
var gateway: Resource {
return service.resource("/gateway")
}
var device: Resource {
return service.resource("/device")
}
}
// MARK: - API calls
extension NeviWebAPI {
func login(email: String, password: String, completion: @escaping (_ result: Result<Void, AnyError>) -> Void) {
let json = [
"email": email,
"password": password
]
service.resource("/login").request(.post, json: json)
.onSuccess { (entity) in
guard
let sessionID = entity.jsonDict["session"] as? String
else {
let error = AnyError(DecodingError.missingData("session"))
completion(.failure(error))
return
}
do {
try NeviWebConfig.keychain.set(sessionID, key: email)
self.service.resource("/login").wipe()
completion(.success())
} catch {
let error = AnyError(error)
completion(.failure(error))
}
}
.onFailure { (error) in
let error = AnyError(error)
completion(.failure(error))
}
}
func authenticate(sessionID: String) {
sessionIDHeader = sessionID
}
}
|
53d9504c1a77b37df69251a11823e2aa
| 21.573427 | 115 | 0.439281 | false | true | false | false |
Sherlouk/IGListKit
|
refs/heads/master
|
Carthage/Checkouts/IGListKit/Examples/Examples-tvOS/IGListKitExamples/Views/EmbeddedCollectionViewCell.swift
|
bsd-3-clause
|
4
|
/**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import IGListKit
final class EmbeddedCollectionViewCell: UICollectionViewCell {
lazy var collectionView: IGListCollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let view = IGListCollectionView(frame: .zero, collectionViewLayout: layout)
view.backgroundColor = .clear
view.alwaysBounceVertical = false
view.alwaysBounceHorizontal = true
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = contentView.frame
}
override var canBecomeFocused: Bool {
get {
return false
}
}
}
|
4d5af1404c1c1bb407f4003be837ccbb
| 33.047619 | 83 | 0.715385 | false | false | false | false |
ChristianKienle/highway
|
refs/heads/master
|
Sources/HighwayCore/Highways/Invocation/Invocation.swift
|
mit
|
1
|
import Foundation
import Arguments
public final class Invocation {
// MARK: - Init
public init(highway: String = "", arguments: Arguments = .empty, verbose: Bool = false) {
self.highway = highway
self.arguments = arguments
self.verbose = verbose
}
// MARK: - Properties
public let highway: String
public let arguments: Arguments
public let verbose: Bool
public var representsEmptyInvocation: Bool { return highway == "" }
}
extension Invocation: Equatable {
public static func ==(l: Invocation, r: Invocation) -> Bool {
return l.highway == r.highway && l.arguments == r.arguments && l.verbose == r.verbose
}
}
|
0af78c57991264ff26b023779adf1cff
| 28.956522 | 93 | 0.648766 | false | false | false | false |
johannescarlen/resizeablemapview
|
refs/heads/master
|
ResizeableMapView/ViewController.swift
|
mit
|
1
|
/*
The MIT License (MIT)
Copyright (c) 2015 Johannes Carlén
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var dragView: UIView!
@IBOutlet weak var containerHeightConstraint: NSLayoutConstraint!
private var locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 100
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapView.delegate = self
locationManager.delegate = self
// let initialLocation = CLLocation(latitude: 57.705702, longitude: 11.966612)
// centerMapOnLocation(initialLocation)
let pan = UIPanGestureRecognizer(target: self, action: "pan:")
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
dragView.addGestureRecognizer(pan)
}
override func viewDidAppear(animated: Bool) {
checkLocationAuthorizationStatus()
}
func pan(rec:UIPanGestureRecognizer) {
if rec.state == .Changed {
let currentPoint = rec.locationInView(self.dragView)
let minHeight = 40 + self.dragView.frame.height
let maxHeight = self.view.frame.height
let currentHeight = self.containerHeightConstraint.constant
var newHeight = currentHeight + currentPoint.y
if newHeight < minHeight {
newHeight = minHeight
} else if newHeight > maxHeight {
newHeight = maxHeight
}
self.containerHeightConstraint.constant = newHeight
}
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
} else {
println("Requesting authorization...")
locationManager.requestWhenInUseAuthorization()
}
}
}
extension ViewController : MKMapViewDelegate {
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
println("didUpdateUserLocation")
println(userLocation)
let allAnnotations: [MKAnnotation] = [userLocation]
mapView.showAnnotations(allAnnotations, animated: true)
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
println("viewForAnnotation")
println(annotation)
return nil
}
}
extension ViewController : CLLocationManagerDelegate {
}
|
5a2c2ce9cccc7ce366b67e7dc2eec931
| 34.205128 | 105 | 0.684632 | false | false | false | false |
mirego/PinLayout
|
refs/heads/master
|
Tests/iOS/Types+UIKit.swift
|
mit
|
1
|
// Copyright (c) 2018 Luc Dion
// 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
typealias PView = UIView
typealias PScrollView = UIScrollView
typealias PEdgeInsets = UIEdgeInsets
typealias PViewController = UIViewController
typealias PColor = UIColor
typealias PLabel = UILabel
|
da3cc8fc67a4e328f0ea845b78308c76
| 48.333333 | 81 | 0.77027 | false | false | false | false |
turingcorp/gattaca
|
refs/heads/master
|
UnitTests/Firebase/Database/Model/TFDatabaseCountriesItem.swift
|
mit
|
1
|
import XCTest
@testable import gattaca
class TFDatabaseCountriesItem:XCTestCase
{
private let kCountry:String = "banana republic"
private let kUserA:String = "lorem"
private let kUserB:String = "ipsum"
private let kLatitude:Double = 1
private let kLongitude:Double = 2
private let kSyncstamp:TimeInterval = 3
private let kTotalUsers:Int = 2
//MARK: private
private func factoryJson() -> Any
{
let userJson:[String:Any] = [
FDatabaseCountriesItemUser.kKeyLatitude:kLatitude,
FDatabaseCountriesItemUser.kKeyLongitude:kLongitude,
FDatabaseCountriesItemUser.kKeySyncstamp:kSyncstamp]
let json:[String:Any] = [
kUserA:userJson,
kUserB:userJson]
return json
}
//MARK: internal
func testInit()
{
let countries:FDatabaseCountries = FDatabaseCountries()
let country:FDatabaseCountriesItem = FDatabaseCountriesItem(
countries:countries,
identifier:kCountry)
XCTAssertNotNil(
country.identifier,
"identifier should not be nil")
XCTAssertNotNil(
country.parent,
"parent should not be nil")
XCTAssertLessThan(
country.users.count,
1,
"there should not be users")
}
func testInitJson()
{
let json:Any = factoryJson()
let country:FDatabaseCountriesItem? = FDatabaseCountriesItem(
json:json)
XCTAssertNotNil(
country,
"failed creating country from json")
XCTAssertNil(
country?.identifier,
"country should have no identifier")
XCTAssertNil(
country?.parent,
"country should have no parent")
guard
let model:FDatabaseCountriesItem = country
else
{
return
}
let countUsers:Int = model.users.count
XCTAssertEqual(
countUsers,
kTotalUsers,
"failed parsing users")
if countUsers == kTotalUsers
{
let userA:FDatabaseCountriesItemUser = model.users[0]
XCTAssertNotNil(
userA.identifier,
"failed assigning identifier")
let userB:FDatabaseCountriesItemUser = model.users[1]
XCTAssertNotNil(
userB.identifier,
"failed assigning identifier")
}
}
}
|
acb845576e9b2aa7593475b71219db94
| 25.524752 | 69 | 0.547966 | false | false | false | false |
JeffESchmitz/RideNiceRide
|
refs/heads/master
|
RideNiceRideTests/HubwayAPITests.swift
|
mit
|
1
|
//
// HubwayAPITests.swift
// RideNiceRide
//
// Created by Jeff Schmitz on 12/31/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import XCTest
@testable import RideNiceRide
class HubwayAPITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testSharedInstance() {
// let instance = HubwayAPI.sharedInstance()
// XCTAssertNotNil(instance, "HubwayAPI should have returned an instance")
// }
//
// func testSharedInstance_One_And_Only() {
// let instanceOne = HubwayAPI.sharedInstance()
// instanceOne.testVariable = "foo"
// let instanceTwo = HubwayAPI.sharedInstance()
//
// XCTAssertEqual(instanceOne.testVariable, instanceTwo.testVariable)
//
// instanceTwo.testVariable = "bar"
// XCTAssertEqual(instanceOne.testVariable, instanceTwo.testVariable)
// }
}
|
565fc9b9b63bbdcb8fb145cdf78d2730
| 26.975 | 107 | 0.697945 | false | true | false | false |
kickerchen/PayByCrush
|
refs/heads/master
|
PayByCrush/PBCSwap.swift
|
mit
|
1
|
//
// PBCSwap.swift
// PayByCrush
//
// Created by CHENCHIAN on 7/29/15.
// Copyright (c) 2015 KICKERCHEN. All rights reserved.
//
import UIKit
class PBCSwap: NSObject {
var paymentA: PBCPayment!
var paymentB: PBCPayment!
override var description: String {
get {
return NSString(format: "%@ swap %@ with %@", super.description, self.paymentA, self.paymentB) as! String
}
}
override var hash: Int {
get {
return self.paymentA.hash ^ self.paymentB.hash
}
}
override func isEqual(object: AnyObject?) -> Bool {
if object?.isKindOfClass(PBCSwap) == false {
return false
}
let other = object as! PBCSwap
return (other.paymentA == self.paymentA && other.paymentB == self.paymentB) || (other.paymentA == self.paymentB && other.paymentB == self.paymentA)
}
}
|
08c8d736b965efc8e7218ea819d8d052
| 24.027027 | 155 | 0.580994 | false | false | false | false |
powerytg/Accented
|
refs/heads/master
|
Accented/UI/User/ViewModels/UserStreamViewModel.swift
|
mit
|
1
|
//
// UserStreamViewModel.swift
// Accented
//
// User stream photos
//
// Created by Tiangong You on 5/31/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import RMessage
class UserStreamViewModel : SingleHeaderStreamViewModel{
var user : UserModel
override var headerHeight: CGFloat {
return UserStreamLayoutSpec.streamHeaderHeight
}
required init(user : UserModel, stream : StreamModel, collectionView : UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) {
self.user = user
super.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: flowLayoutDelegate)
}
required init(stream: StreamModel, collectionView: UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) {
fatalError("init(stream:collectionView:flowLayoutDelegate:) has not been implemented")
}
override func loadPageAt(_ page : Int) {
let params = ["tags" : "1"]
let userStreamModel = stream as! UserStreamModel
APIService.sharedInstance.getUserPhotos(userId: userStreamModel.userId, page: page, parameters: params, success: nil) { [weak self] (errorMessage) in
self?.collectionFailedRefreshing(errorMessage)
RMessage.showNotification(withTitle: errorMessage, subtitle: nil, type: .error, customTypeName: nil, callback: nil)
}
}
override func streamHeader(_ indexPath : IndexPath) -> UICollectionViewCell {
let streamHeaderCell = collectionView.dequeueReusableCell(withReuseIdentifier: streamHeaderReuseIdentifier, for: indexPath) as! DefaultSingleStreamHeaderCell
let userName = TextUtils.preferredAuthorName(user).uppercased()
streamHeaderCell.titleLabel.text = "\(userName)'S \nPUBLIC PHOTOS"
if let photoCount = user.photoCount {
if photoCount == 0 {
streamHeaderCell.subtitleLabel.text = "NO ITEMS"
} else if photoCount == 1 {
streamHeaderCell.subtitleLabel.text = "1 ITEM"
} else {
streamHeaderCell.subtitleLabel.text = "\(photoCount) ITEMS"
}
} else {
streamHeaderCell.subtitleLabel.isHidden = true
}
streamHeaderCell.orderButton.isHidden = true
streamHeaderCell.orderLabel.isHidden = true
return streamHeaderCell
}
}
|
c6283441acb3a8c2bae4ceb66823ab1d
| 38.258065 | 165 | 0.684881 | false | false | false | false |
hjw6160602/JourneyNotes
|
refs/heads/master
|
JourneyNotes/Classes/Main/JourneyDetail/Navigation/JourneySummaryNavigationTableView.swift
|
mit
|
1
|
//
// JourneySummaryNavigationTableView.swift
// JourneyNotes
//
// Created by 贺嘉炜 on 2017/8/22.
// Copyright © 2017年 贺嘉炜. All rights reserved.
//
import UIKit
fileprivate let kCellReuseID: String = "JourneySummaryNavigationCell"
class JourneySummaryNavigationTableView: UITableView {
var lineRouteDetailArr = [ProdLineRouteDetail]()
var cellHeights: [Int: CGFloat] = [:]
convenience init(frame: CGRect, lineRouteDetailArr: [ProdLineRouteDetail]) {
self.init(frame: frame, style: .grouped)
self.lineRouteDetailArr = lineRouteDetailArr
dataSource = self
delegate = self
separatorStyle = .none
backgroundColor = UIColor.clear
bounces = false
showsVerticalScrollIndicator = false
}
}
extension JourneySummaryNavigationTableView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lineRouteDetailArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: kCellReuseID) as? JourneySummaryNavigationCell
if cell == nil {
cell = Bundle.main.loadNibNamed(kCellReuseID, owner: nil, options: nil)?.first as? JourneySummaryNavigationCell
}
cell?.setup(row: indexPath.row, eachDayEntity: self.lineRouteDetailArr[indexPath.row])
cell?.isLastRow = (indexPath.row == (self.lineRouteDetailArr.count - 1));
if self.cellHeights[indexPath.row] == nil {
self.cellHeights[indexPath.row] = cell?.cellHeight;
}
return cell!
}
}
extension JourneySummaryNavigationTableView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = cellHeights[indexPath.row] {
return height
} else {
return 65
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("滚动到第几天呀?")
}
}
|
02eb39a7756de3829f37cdc0522627f2
| 32.967742 | 123 | 0.684236 | false | false | false | false |
OlegNovosad/Sample
|
refs/heads/master
|
iOS/Severenity/Services/PlacesService.swift
|
apache-2.0
|
2
|
//
// LocationsServerManager.swift
// severenityProject
//
// Created by Yura Yasinskyy on 13.09.16.
// Copyright © 2016 severenity. All rights reserved.
//
import UIKit
import Alamofire
import RealmSwift
import FBSDKLoginKit
class PlacesService: NSObject {
private var realm: Realm?
// MARK: Init
override init() {
super.init()
do {
realm = try Realm()
} catch {
Log.error(message: "Realm error: \(error.localizedDescription)", sender: self)
}
}
// MARK: Methods
/**- This method returns Array with data in callback.
It checks whether data is already in Realm. If yes than it goes to getDataFromRealm method
if no than it calls requestDataFromServer to get data from server.*/
func provideData(_ completion: @escaping (_ result: NSArray) -> Void) {
if checkIfRealmIsEmpty() {
Log.info(message: "Realm is empty, asking server for data", sender: self)
requestDataFromServer {
self.getDataFromRealm { data in
completion(data)
}
}
} else {
Log.info(message: "Realm is not empty, loading data", sender: self)
getDataFromRealm { data in
completion(data)
}
}
}
private func checkIfRealmIsEmpty() -> Bool {
let realmReadQuery = realm?.objects(RealmPlace.self)
return realmReadQuery?.isEmpty ?? false
}
/**- requestDataFromServer gets called when Realm is empty. It than perform request to server,
gets JSON response, parse it and set to Realm. When completed, returns to provideData method.*/
private func requestDataFromServer(_ completion: @escaping () -> Void) {
guard let serverURL = URL.init(string: kPlacesServerURL) else {
Log.error(message: "Cannot create server url", sender: self)
return
}
let serverRequest = URLRequest.init(url: serverURL)
Alamofire.request(serverRequest).responseJSON { response in
guard let places = response.result.value as? [[String: Any]] else {
Log.error(message: "Response does not contain places.", sender: self)
return
}
for place in places {
guard let owners = place["owners"] as? [String] else {
Log.error(message: "Can't find owners in place item.", sender: self)
return
}
for owner in owners where owner == FBSDKAccessToken.current().userID {
// Adding data to Realm DB
let placeInRealm = RealmPlace(place: place)
for object in owners {
let placeOwner = RealmPlaceOwner()
placeOwner.owner = object
placeInRealm.owners.append(placeOwner)
}
placeInRealm.addToDB()
}
}
completion()
}
}
/**- This method makes query to Realm data model and gets all needed data
that is than returned in Array. */
private func getDataFromRealm(_ completion: (_ data: NSArray) -> Void) {
let realmReadQuery = realm?.objects(RealmPlace.self)
var dataFromRealm: [AnyObject] = []
var ownersArray: [AnyObject] = []
var isRightOwnerFound = false
guard let query = realmReadQuery else {
Log.error(message: "Error creating Realm read query", sender: self)
return
}
for place in query {
let tempArray = Array(place.owners)
for owner in tempArray {
ownersArray.append(owner.owner as AnyObject)
isRightOwnerFound = owner.owner == FBSDKAccessToken.current().userID
}
if isRightOwnerFound {
let dictionaryWithPlace: [String: AnyObject] = [
"placeId" : place.placeId as AnyObject,
"name" : place.name as AnyObject,
"type" : place.type as AnyObject,
"createdDate" : place.createdDate as AnyObject,
"owners" : ownersArray as AnyObject,
"lat" : place.lat as AnyObject,
"lng" : place.lng as AnyObject
]
dataFromRealm.append(dictionaryWithPlace as AnyObject)
}
ownersArray.removeAll()
}
completion(dataFromRealm as NSArray)
}
// Try to drop data by type 'Location' etc., not all data
private func dropDataInRealm() {
do {
try realm?.write {
realm?.deleteAll()
}
} catch {
Log.error(message: "Realm error: \(error.localizedDescription)", sender: self)
}
}
}
|
a048ac2b00de9d2d687068024c8cea1e
| 34.314685 | 100 | 0.544158 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Legacy/Neocom/Neocom II Tests/Loadouts_Tests.swift
|
lgpl-2.1
|
2
|
//
// Loadouts_Tests.swift
// Neocom II Tests
//
// Created by Artem Shimanski on 27/01/2019.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import XCTest
@testable import Neocom
import Dgmpp
class Loadouts_Tests: TestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testLoadoutDescriptionEncoding() {
let a = testingLoadout
let data = try! NSKeyedArchiver.archivedData(withRootObject: a, requiringSecureCoding: true)
let b = try! NSKeyedUnarchiver.unarchivedObject(ofClass: LoadoutDescription.self, from: data)
XCTAssertEqual(a, b)
}
func testFleedDescriptionEncoding() {
let a = FleetDescription()
a.pilots = [1:"a", 2: "b"]
a.links = [1:2, 2:2]
let data = try! NSKeyedArchiver.archivedData(withRootObject: a, requiringSecureCoding: true)
let b = try! NSKeyedUnarchiver.unarchivedObject(ofClass: FleetDescription.self, from: data)
XCTAssertEqual(a, b)
}
func testImplantSetDescriptionEncoding() {
let a = ImplantSetDescription()
a.implantIDs = [1, 2, 3]
a.boosterIDs = [4, 5, 6]
let data = try! NSKeyedArchiver.archivedData(withRootObject: a, requiringSecureCoding: true)
let b = try! NSKeyedUnarchiver.unarchivedObject(ofClass: ImplantSetDescription.self, from: data)
XCTAssertEqual(a, b)
}
func testMigration() {
let a = NCFittingLoadout()
a.modules = [DGMModule.Slot.hi: [NCFittingLoadoutModule(typeID: 1, count: 1, identifier: 1, state: DGMModule.State.online, charge: nil, socket: 0),
NCFittingLoadoutModule(typeID: 2, count: 2, identifier: 2, state: DGMModule.State.online, charge: NCFittingLoadoutItem(typeID: 3, count: 1), socket: 0)
]]
a.drones = [NCFittingLoadoutDrone(typeID: 1, count: 1, identifier: nil, isActive: true, squadronTag: 0)]
a.implants = [NCFittingLoadoutItem(typeID: 100, count: 1)]
a.boosters = [NCFittingLoadoutItem(typeID: 101, count: 1)]
a.cargo = [NCFittingLoadoutItem(typeID: 102, count: 100)]
let data = try! NSKeyedArchiver.archivedData(withRootObject: a, requiringSecureCoding: false)
NSKeyedUnarchiver.setClass(LoadoutDescription.self, forClassName: "Neocom_II_Tests.NCFittingLoadout")
NSKeyedUnarchiver.setClass(LoadoutDescription.Item.self, forClassName: "Neocom_II_Tests.NCFittingLoadoutItem")
NSKeyedUnarchiver.setClass(LoadoutDescription.Item.Module.self, forClassName: "Neocom_II_Tests.NCFittingLoadoutModule")
NSKeyedUnarchiver.setClass(LoadoutDescription.Item.Drone.self, forClassName: "Neocom_II_Tests.NCFittingLoadoutDrone")
let b = try! NSKeyedUnarchiver.unarchivedObject(ofClass: LoadoutDescription.self, from: data)
XCTAssertEqual(b, testingLoadout)
}
var testingLoadout: LoadoutDescription {
let loadout = LoadoutDescription()
loadout.modules = [DGMModule.Slot.hi: [LoadoutDescription.Item.Module(typeID: 1, count: 1, identifier: 1, state: DGMModule.State.online, charge: nil, socket: 0),
LoadoutDescription.Item.Module(typeID: 2, count: 2, identifier: 2, state: DGMModule.State.online, charge: LoadoutDescription.Item(typeID: 3, count: 1), socket: 0)]]
loadout.drones = [LoadoutDescription.Item.Drone(typeID: 1, count: 1, identifier: nil, isActive: true, isKamikaze: false, squadronTag: 0)]
loadout.implants = [LoadoutDescription.Item(typeID: 100, count: 1)]
loadout.boosters = [LoadoutDescription.Item(typeID: 101, count: 1)]
loadout.cargo = [LoadoutDescription.Item(typeID: 102, count: 100)]
return loadout
}
}
class NCFittingLoadoutItem: NSObject, NSSecureCoding {
let typeID: Int
var count: Int
let identifier: Int?
public static var supportsSecureCoding: Bool {
return true
}
init(type: DGMType, count: Int = 1) {
self.typeID = type.typeID
self.count = count
self.identifier = type.identifier
super.init()
}
init(typeID: Int, count: Int, identifier: Int? = nil) {
self.typeID = typeID
self.count = count
self.identifier = identifier
super.init()
}
required init?(coder aDecoder: NSCoder) {
typeID = aDecoder.decodeInteger(forKey: "typeID")
count = aDecoder.containsValue(forKey: "count") ? aDecoder.decodeInteger(forKey: "count") : 1
if let s = (aDecoder.decodeObject(forKey: "identifier") as? String) {
identifier = Int(s) ?? s.hashValue
}
else if let n = (aDecoder.decodeObject(forKey: "identifier") as? NSNumber) {
identifier = n.intValue
}
else {
identifier = nil
}
super.init()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(typeID, forKey: "typeID")
if count != 1 {
aCoder.encode(count, forKey: "count")
}
aCoder.encode(identifier, forKey: "identifier")
}
public static func ==(lhs: NCFittingLoadoutItem, rhs: NCFittingLoadoutItem) -> Bool {
return lhs.hash == rhs.hash
}
override var hash: Int {
return [typeID, count].hashValue
}
}
class NCFittingLoadoutModule: NCFittingLoadoutItem {
let state: DGMModule.State
let charge: NCFittingLoadoutItem?
let socket: Int
init(module: DGMModule) {
state = module.preferredState
if let charge = module.charge {
self.charge = NCFittingLoadoutItem(type: charge, count: max(module.charges, 1))
}
else {
self.charge = nil
}
socket = module.socket
super.init(type: module)
}
init(typeID: Int, count: Int, identifier: Int?, state: DGMModule.State = .active, charge: NCFittingLoadoutItem? = nil, socket: Int = -1) {
self.state = state
self.charge = charge
self.socket = socket
super.init(typeID: typeID, count: count, identifier: identifier)
}
required init?(coder aDecoder: NSCoder) {
state = DGMModule.State(rawValue: aDecoder.decodeInteger(forKey: "state")) ?? .unknown
charge = aDecoder.decodeObject(forKey: "charge") as? NCFittingLoadoutItem
socket = aDecoder.containsValue(forKey: "socket") ? aDecoder.decodeInteger(forKey: "socket") : -1
super.init(coder: aDecoder)
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(state.rawValue, forKey: "state")
aCoder.encode(charge, forKey: "charge")
aCoder.encode(socket, forKey: "socket")
}
override var hash: Int {
return [typeID, count, state.rawValue, charge?.typeID ?? 0].hashValue
}
}
class NCFittingLoadoutDrone: NCFittingLoadoutItem {
let isActive: Bool
let isKamikaze: Bool
let squadronTag: Int
init(typeID: Int, count: Int, identifier: Int?, isActive: Bool = true, squadronTag: Int = -1) {
self.isActive = isActive
self.squadronTag = squadronTag
self.isKamikaze = false
super.init(typeID: typeID, count: count, identifier: identifier)
}
init(drone: DGMDrone) {
self.isActive = drone.isActive
self.isKamikaze = drone.isKamikaze
self.squadronTag = drone.squadronTag
super.init(type: drone)
}
required init?(coder aDecoder: NSCoder) {
isActive = aDecoder.containsValue(forKey: "isActive") ? aDecoder.decodeBool(forKey: "isActive") : true
isKamikaze = aDecoder.containsValue(forKey: "isKamikaze") ? aDecoder.decodeBool(forKey: "isKamikaze") : false
squadronTag = aDecoder.containsValue(forKey: "squadronTag") ? aDecoder.decodeInteger(forKey: "squadronTag") : -1
super.init(coder: aDecoder)
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
if !isActive {
aCoder.encode(isActive, forKey: "isActive")
}
if !isKamikaze {
aCoder.encode(isKamikaze, forKey: "isKamikaze")
}
aCoder.encode(squadronTag, forKey: "squadronTag")
}
override var hash: Int {
return [typeID, count, isActive ? 1 : 0].hashValue
}
}
public class NCFittingLoadout: NSObject, NSSecureCoding {
var modules: [DGMModule.Slot: [NCFittingLoadoutModule]]?
var drones: [NCFittingLoadoutDrone]?
var cargo: [NCFittingLoadoutItem]?
var implants: [NCFittingLoadoutItem]?
var boosters: [NCFittingLoadoutItem]?
override init() {
super.init()
}
public static var supportsSecureCoding: Bool {
return true
}
public required init?(coder aDecoder: NSCoder) {
modules = [DGMModule.Slot: [NCFittingLoadoutModule]]()
for (key, value) in aDecoder.decodeObject(forKey: "modules") as? [Int: [NCFittingLoadoutModule]] ?? [:] {
guard let key = DGMModule.Slot(rawValue: key) else {continue}
modules?[key] = value
}
drones = aDecoder.decodeObject(forKey: "drones") as? [NCFittingLoadoutDrone]
cargo = aDecoder.decodeObject(forKey: "cargo") as? [NCFittingLoadoutItem]
implants = aDecoder.decodeObject(forKey: "implants") as? [NCFittingLoadoutItem]
boosters = aDecoder.decodeObject(forKey: "boosters") as? [NCFittingLoadoutItem]
super.init()
}
public func encode(with aCoder: NSCoder) {
var dic = [Int: [NCFittingLoadoutModule]]()
for (key, value) in modules ?? [:] {
dic[key.rawValue] = value
}
aCoder.encode(dic, forKey:"modules")
if drones?.count ?? 0 > 0 {
aCoder.encode(drones, forKey: "drones")
}
if cargo?.count ?? 0 > 0 {
aCoder.encode(cargo, forKey: "cargo")
}
if implants?.count ?? 0 > 0 {
aCoder.encode(implants, forKey: "implants")
}
if boosters?.count ?? 0 > 0 {
aCoder.encode(boosters, forKey: "boosters")
}
}
}
|
99103330509da4fda201f15e58572444
| 32.043478 | 175 | 0.718531 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.